blob: ca1535182ec1bde639fb4de2b606876284b50881 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- C++ -*-===//
Anders Carlsson4b08db72009-10-30 01:42:31 +00002//
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"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000022#include "clang/AST/StmtVisitor.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000023#include "clang/Basic/TargetBuiltins.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000024#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/Intrinsics.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000026#include "llvm/IR/IntrinsicInst.h"
Reid Klecknerebaf28d2015-04-14 20:59:00 +000027#include "llvm/Support/SaveAndRestore.h"
John McCallbd309292010-07-06 01:34:17 +000028
Anders Carlsson4b08db72009-10-30 01:42:31 +000029using namespace clang;
30using namespace CodeGen;
31
John McCall2c33ba82013-02-12 03:51:38 +000032static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000033 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000034
Chris Lattner2192fe52011-07-18 04:24:23 +000035 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000036 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000037
John McCall2c33ba82013-02-12 03:51:38 +000038 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000039}
40
John McCall2c33ba82013-02-12 03:51:38 +000041static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000042 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000043
Chris Lattner2192fe52011-07-18 04:24:23 +000044 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000045 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000046
John McCall2c33ba82013-02-12 03:51:38 +000047 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000048}
49
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000050llvm::Constant *CodeGenModule::getTerminateFn() {
Mike Stump33270212009-12-02 07:41:41 +000051 // void __terminate();
52
Chris Lattner2192fe52011-07-18 04:24:23 +000053 llvm::FunctionType *FTy =
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000054 llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000055
Chris Lattner0e62c1c2011-07-23 10:55:15 +000056 StringRef name;
John McCall9de19782011-07-06 01:22:26 +000057
58 // In C++, use std::terminate().
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000059 if (getLangOpts().CPlusPlus &&
60 getTarget().getCXXABI().isItaniumFamily()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +000061 name = "_ZSt9terminatev";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000062 } else if (getLangOpts().CPlusPlus &&
63 getTarget().getCXXABI().isMicrosoft()) {
David Majnemerb710a932015-05-11 03:57:49 +000064 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemerfb6ffca2015-05-10 21:38:26 +000065 name = "__std_terminate";
66 else
67 name = "\01?terminate@@YAXXZ";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000068 } else if (getLangOpts().ObjC1 &&
69 getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +000070 name = "objc_terminate";
71 else
72 name = "abort";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000073 return CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +000074}
75
John McCall2c33ba82013-02-12 03:51:38 +000076static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000077 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +000078 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000079 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +000080
John McCall2c33ba82013-02-12 03:51:38 +000081 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +000082}
83
Craig Topper8a13c412014-05-21 05:09:00 +000084const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +000085const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +000086EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
87const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000088EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
89const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +000090EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
91const EHPersonality
92EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
93const EHPersonality
94EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +000095const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000096EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
97const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +000098EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
99const EHPersonality
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000100EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
101const EHPersonality
102EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
103const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000104EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000105const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000106EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Reid Kleckner1d59f992015-01-22 01:36:17 +0000107const EHPersonality
108EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
109const EHPersonality
110EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000111const EHPersonality
112EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000113
Reid Klecknere070b992014-11-14 02:01:10 +0000114/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
115/// other platforms, unless the user asked for SjLj exceptions.
116static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
117 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
118}
119
120static const EHPersonality &getCPersonality(const llvm::Triple &T,
121 const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000122 if (L.SjLjExceptions)
123 return EHPersonality::GNU_C_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000124 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000125 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000126 return EHPersonality::GNU_C;
127}
128
Reid Klecknere070b992014-11-14 02:01:10 +0000129static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
130 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000131 switch (L.ObjCRuntime.getKind()) {
132 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000133 return getCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000134 case ObjCRuntime::MacOSX:
135 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000136 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +0000137 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000138 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000139 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
140 return EHPersonality::GNUstep_ObjC;
141 // fallthrough
David Chisnallb601c962012-07-03 20:49:52 +0000142 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000143 case ObjCRuntime::ObjFW:
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000144 if (L.SjLjExceptions)
145 return EHPersonality::GNU_ObjC_SJLJ;
146 else if (useLibGCCSEHPersonality(T))
147 return EHPersonality::GNU_ObjC_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000148 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000149 }
John McCall5fb5df92012-06-20 06:18:46 +0000150 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000151}
152
Reid Klecknere070b992014-11-14 02:01:10 +0000153static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
154 const LangOptions &L) {
John McCall36ea3722010-07-17 00:43:08 +0000155 if (L.SjLjExceptions)
156 return EHPersonality::GNU_CPlusPlus_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000157 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000158 return EHPersonality::GNU_CPlusPlus_SEH;
Reid Klecknere070b992014-11-14 02:01:10 +0000159 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000160}
161
162/// Determines the personality function to use when both C++
163/// and Objective-C exceptions are being caught.
Reid Klecknere070b992014-11-14 02:01:10 +0000164static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
165 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000166 switch (L.ObjCRuntime.getKind()) {
John McCallbd309292010-07-06 01:34:17 +0000167 // The ObjC personality defers to the C++ personality for non-ObjC
168 // handlers. Unlike the C++ case, we use the same personality
169 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000170 case ObjCRuntime::MacOSX:
171 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000172 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +0000173 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000174
John McCall5fb5df92012-06-20 06:18:46 +0000175 // In the fragile ABI, just use C++ exception handling and hope
176 // they're not doing crazy exception mixing.
177 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000178 return getCXXPersonality(T, L);
David Chisnallf9c42252010-05-17 13:49:20 +0000179
David Chisnallb601c962012-07-03 20:49:52 +0000180 // The GCC runtime's personality function inherently doesn't support
John McCall36ea3722010-07-17 00:43:08 +0000181 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000182 case ObjCRuntime::GCC:
Benjamin Kramer9851cb72017-04-01 17:59:01 +0000183 case ObjCRuntime::ObjFW:
184 return getObjCPersonality(T, L);
David Chisnallb601c962012-07-03 20:49:52 +0000185 case ObjCRuntime::GNUstep:
John McCall5fb5df92012-06-20 06:18:46 +0000186 return EHPersonality::GNU_ObjCXX;
187 }
188 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000189}
190
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000191static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000192 if (T.getArch() == llvm::Triple::x86)
193 return EHPersonality::MSVC_except_handler;
194 return EHPersonality::MSVC_C_specific_handler;
195}
196
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000197const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
198 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000199 const llvm::Triple &T = CGM.getTarget().getTriple();
200 const LangOptions &L = CGM.getLangOpts();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000201
Reid Kleckner01485652015-09-17 17:04:13 +0000202 // Functions using SEH get an SEH personality.
203 if (FD && FD->usesSEHTry())
204 return getSEHPersonalityMSVC(T);
205
Reid Kleckner1d59f992015-01-22 01:36:17 +0000206 // Try to pick a personality function that is compatible with MSVC if we're
207 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
208 // the GCC-style personality function.
209 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000210 if (L.SjLjExceptions)
211 return EHPersonality::GNU_CPlusPlus_SJLJ;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000212 else
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000213 return EHPersonality::MSVC_CxxFrameHandler3;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000214 }
215
John McCall36ea3722010-07-17 00:43:08 +0000216 if (L.CPlusPlus && L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000217 return getObjCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000218 else if (L.CPlusPlus)
Reid Klecknere070b992014-11-14 02:01:10 +0000219 return getCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000220 else if (L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000221 return getObjCPersonality(T, L);
John McCallbd309292010-07-06 01:34:17 +0000222 else
Reid Klecknere070b992014-11-14 02:01:10 +0000223 return getCPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000224}
John McCallbd309292010-07-06 01:34:17 +0000225
David Majnemerc28d46e2015-07-22 23:46:21 +0000226const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
227 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
228}
229
John McCall0bdb1fd2010-09-16 06:16:50 +0000230static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000231 const EHPersonality &Personality) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +0000232 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
233 Personality.PersonalityFn,
Reid Klecknerde864822017-03-21 16:57:30 +0000234 llvm::AttributeList(), /*Local=*/true);
John McCall0bdb1fd2010-09-16 06:16:50 +0000235}
236
237static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
238 const EHPersonality &Personality) {
239 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000240 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000241}
242
Vedant Kumardb609472015-09-11 15:40:05 +0000243/// Check whether a landingpad instruction only uses C++ features.
244static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
245 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
246 // Look for something that would've been returned by the ObjC
247 // runtime's GetEHType() method.
248 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
249 if (LPI->isCatch(I)) {
250 // Check if the catch value has the ObjC prefix.
251 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
252 // ObjC EH selector entries are always global variables with
253 // names starting like this.
254 if (GV->getName().startswith("OBJC_EHTYPE"))
255 return false;
256 } else {
257 // Check if any of the filter values have the ObjC prefix.
258 llvm::Constant *CVal = cast<llvm::Constant>(Val);
259 for (llvm::User::op_iterator
260 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
261 if (llvm::GlobalVariable *GV =
262 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
263 // ObjC EH selector entries are always global variables with
264 // names starting like this.
265 if (GV->getName().startswith("OBJC_EHTYPE"))
266 return false;
267 }
268 }
269 }
270 return true;
271}
272
John McCall0bdb1fd2010-09-16 06:16:50 +0000273/// Check whether a personality function could reasonably be swapped
274/// for a C++ personality function.
275static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000276 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000277 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000278 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000279 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
280 if (!PersonalityHasOnlyCXXUses(CE))
281 return false;
282 continue;
283 }
284
Vedant Kumardb609472015-09-11 15:40:05 +0000285 // Otherwise it must be a function.
286 llvm::Function *F = dyn_cast<llvm::Function>(U);
287 if (!F) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000288
Vedant Kumardb609472015-09-11 15:40:05 +0000289 for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
290 if (BB->isLandingPad())
291 if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
292 return false;
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.
David Blaikie7e70d682015-08-18 22:40:54 +0000351 struct FreeException final : EHScopeStack::Cleanup {
John McCall5fcf8da2011-07-12 00:15:30 +0000352 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 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000358} // end anonymous namespace
John McCallbb026012010-07-13 21:17:51 +0000359
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.
John McCall7f416cc2015-09-08 08:05:57 +0000364void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address 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.
John McCall7f416cc2015-09-08 08:05:57 +0000367 pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
David Majnemer7c237072015-03-05 00:46:22 +0000368 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();
John McCall7f416cc2015-09-08 08:05:57 +0000373 Address 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.
John McCall7f416cc2015-09-08 08:05:57 +0000386 DeactivateCleanupBlock(cleanup,
387 cast<llvm::Instruction>(typedAddr.getPointer()));
Mike Stump54066142009-12-01 03:41:18 +0000388}
389
John McCall7f416cc2015-09-08 08:05:57 +0000390Address CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000391 if (!ExceptionSlot)
392 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000393 return Address(ExceptionSlot, getPointerAlign());
Mike Stump54066142009-12-01 03:41:18 +0000394}
395
John McCall7f416cc2015-09-08 08:05:57 +0000396Address CodeGenFunction::getEHSelectorSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000397 if (!EHSelectorSlot)
398 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000399 return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
John McCall9b382dd2011-05-28 21:13:02 +0000400}
401
Bill Wendling79a70e42011-09-15 18:57:19 +0000402llvm::Value *CodeGenFunction::getExceptionFromSlot() {
403 return Builder.CreateLoad(getExceptionSlot(), "exn");
404}
405
406llvm::Value *CodeGenFunction::getSelectorFromSlot() {
407 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
408}
409
Richard Smithea852322013-05-07 21:53:22 +0000410void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
411 bool KeepInsertionPoint) {
David Majnemer7c237072015-03-05 00:46:22 +0000412 if (const Expr *SubExpr = E->getSubExpr()) {
413 QualType ThrowType = SubExpr->getType();
414 if (ThrowType->isObjCObjectPointerType()) {
415 const Stmt *ThrowStmt = E->getSubExpr();
416 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
417 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
418 } else {
419 CGM.getCXXABI().emitThrow(*this, E);
John McCall2e6567a2010-04-22 01:10:34 +0000420 }
David Majnemer7c237072015-03-05 00:46:22 +0000421 } else {
422 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000423 }
Mike Stump75546b82009-12-10 00:06:18 +0000424
John McCall20f6ab82011-01-12 03:41:02 +0000425 // throw is an expression, and the expression emitters expect us
426 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000427 if (KeepInsertionPoint)
428 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000429}
Mike Stump58ef18b2009-11-20 23:44:51 +0000430
Mike Stump1d849212009-12-07 23:38:24 +0000431void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000432 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000433 return;
434
Mike Stump1d849212009-12-07 23:38:24 +0000435 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000436 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000437 // Check if CapturedDecl is nothrow and create terminate scope for it.
438 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
439 if (CD->isNothrow())
440 EHStack.pushTerminate();
441 }
Mike Stump1d849212009-12-07 23:38:24 +0000442 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000443 }
Mike Stump1d849212009-12-07 23:38:24 +0000444 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000445 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000446 return;
447
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000448 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
449 if (isNoexceptExceptionSpec(EST)) {
450 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
451 // noexcept functions are simple terminate scopes.
452 EHStack.pushTerminate();
453 }
454 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000455 // TODO: Revisit exception specifications for the MS ABI. There is a way to
456 // encode these in an object file but MSVC doesn't do anything with it.
457 if (getTarget().getCXXABI().isMicrosoft())
458 return;
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000459 unsigned NumExceptions = Proto->getNumExceptions();
460 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000461
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000462 for (unsigned I = 0; I != NumExceptions; ++I) {
463 QualType Ty = Proto->getExceptionType(I);
464 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
465 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
466 /*ForEH=*/true);
467 Filter->setFilter(I, EHType);
468 }
Mike Stump1d849212009-12-07 23:38:24 +0000469 }
Mike Stump1d849212009-12-07 23:38:24 +0000470}
471
John McCall8e4c74b2011-08-11 02:22:43 +0000472/// Emit the dispatch block for a filter scope if necessary.
473static void emitFilterDispatchBlock(CodeGenFunction &CGF,
474 EHFilterScope &filterScope) {
475 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
476 if (!dispatchBlock) return;
477 if (dispatchBlock->use_empty()) {
478 delete dispatchBlock;
479 return;
480 }
481
John McCall8e4c74b2011-08-11 02:22:43 +0000482 CGF.EmitBlockAfterUses(dispatchBlock);
483
484 // If this isn't a catch-all filter, we need to check whether we got
485 // here because the filter triggered.
486 if (filterScope.getNumFilters()) {
487 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000488 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000489 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
490
491 llvm::Value *zero = CGF.Builder.getInt32(0);
492 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000493 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
494 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
495 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000496
497 CGF.EmitBlock(unexpectedBB);
498 }
499
500 // Call __cxa_call_unexpected. This doesn't need to be an invoke
501 // because __cxa_call_unexpected magically filters exceptions
502 // according to the last landing pad the exception was thrown
503 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000504 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000505 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000506 ->setDoesNotReturn();
507 CGF.Builder.CreateUnreachable();
508}
509
Mike Stump1d849212009-12-07 23:38:24 +0000510void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000511 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000512 return;
513
Mike Stump1d849212009-12-07 23:38:24 +0000514 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000515 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000516 // Check if CapturedDecl is nothrow and pop terminate scope for it.
517 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
518 if (CD->isNothrow())
519 EHStack.popTerminate();
520 }
Mike Stump1d849212009-12-07 23:38:24 +0000521 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000522 }
Mike Stump1d849212009-12-07 23:38:24 +0000523 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000524 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000525 return;
526
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000527 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
528 if (isNoexceptExceptionSpec(EST)) {
529 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
530 EHStack.popTerminate();
531 }
532 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000533 // TODO: Revisit exception specifications for the MS ABI. There is a way to
534 // encode these in an object file but MSVC doesn't do anything with it.
535 if (getTarget().getCXXABI().isMicrosoft())
536 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000537 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
538 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000539 EHStack.popFilter();
540 }
Mike Stump1d849212009-12-07 23:38:24 +0000541}
542
Mike Stump58ef18b2009-11-20 23:44:51 +0000543void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000544 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000545 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000546 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000547}
548
John McCallb609d3f2010-07-07 06:56:46 +0000549void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000550 unsigned NumHandlers = S.getNumHandlers();
551 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000552
John McCallbd309292010-07-06 01:34:17 +0000553 for (unsigned I = 0; I != NumHandlers; ++I) {
554 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000555
John McCallbd309292010-07-06 01:34:17 +0000556 llvm::BasicBlock *Handler = createBasicBlock("catch");
557 if (C->getExceptionDecl()) {
558 // FIXME: Dropping the reference type on the type into makes it
559 // impossible to correctly implement catch-by-reference
560 // semantics for pointers. Unfortunately, this is what all
561 // existing compilers do, and it's not clear that the standard
562 // personality routine is capable of doing this right. See C++ DR 388:
563 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000564 Qualifiers CaughtTypeQuals;
565 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
566 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000567
Reid Kleckner10aa7702015-09-16 20:15:55 +0000568 CatchTypeInfo TypeInfo{nullptr, 0};
John McCall2ca705e2010-07-24 00:37:23 +0000569 if (CaughtType->isObjCObjectPointerType())
Reid Kleckner10aa7702015-09-16 20:15:55 +0000570 TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000571 else
Reid Kleckner10aa7702015-09-16 20:15:55 +0000572 TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
573 CaughtType, C->getCaughtType());
John McCallbd309292010-07-06 01:34:17 +0000574 CatchScope->setHandler(I, TypeInfo, Handler);
575 } else {
576 // No exception decl indicates '...', a catch-all.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000577 CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
John McCallbd309292010-07-06 01:34:17 +0000578 }
579 }
John McCallbd309292010-07-06 01:34:17 +0000580}
581
John McCall8e4c74b2011-08-11 02:22:43 +0000582llvm::BasicBlock *
583CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
Reid Kleckner129552b2015-10-08 01:13:52 +0000584 if (EHPersonality::get(*this).usesFuncletPads())
David Majnemerdbf10452015-07-31 17:58:45 +0000585 return getMSVCDispatchBlock(si);
586
John McCall8e4c74b2011-08-11 02:22:43 +0000587 // The dispatch block for the end of the scope chain is a block that
588 // just resumes unwinding.
589 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000590 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000591
592 // Otherwise, we should look at the actual scope.
593 EHScope &scope = *EHStack.find(si);
594
595 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
596 if (!dispatchBlock) {
597 switch (scope.getKind()) {
598 case EHScope::Catch: {
599 // Apply a special case to a single catch-all.
600 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
601 if (catchScope.getNumHandlers() == 1 &&
602 catchScope.getHandler(0).isCatchAll()) {
603 dispatchBlock = catchScope.getHandler(0).Block;
604
605 // Otherwise, make a dispatch block.
606 } else {
607 dispatchBlock = createBasicBlock("catch.dispatch");
608 }
609 break;
610 }
611
612 case EHScope::Cleanup:
613 dispatchBlock = createBasicBlock("ehcleanup");
614 break;
615
616 case EHScope::Filter:
617 dispatchBlock = createBasicBlock("filter.dispatch");
618 break;
619
620 case EHScope::Terminate:
621 dispatchBlock = getTerminateHandler();
622 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000623
Reid Kleckner2586aac2015-09-10 22:11:13 +0000624 case EHScope::PadEnd:
625 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCall8e4c74b2011-08-11 02:22:43 +0000626 }
627 scope.setCachedEHDispatchBlock(dispatchBlock);
628 }
629 return dispatchBlock;
630}
631
David Majnemerdbf10452015-07-31 17:58:45 +0000632llvm::BasicBlock *
633CodeGenFunction::getMSVCDispatchBlock(EHScopeStack::stable_iterator SI) {
634 // Returning nullptr indicates that the previous dispatch block should unwind
635 // to caller.
636 if (SI == EHStack.stable_end())
637 return nullptr;
638
639 // Otherwise, we should look at the actual scope.
640 EHScope &EHS = *EHStack.find(SI);
641
642 llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
643 if (DispatchBlock)
644 return DispatchBlock;
645
646 if (EHS.getKind() == EHScope::Terminate)
647 DispatchBlock = getTerminateHandler();
648 else
649 DispatchBlock = createBasicBlock();
John McCall7f416cc2015-09-08 08:05:57 +0000650 CGBuilderTy Builder(*this, DispatchBlock);
David Majnemerdbf10452015-07-31 17:58:45 +0000651
652 switch (EHS.getKind()) {
653 case EHScope::Catch:
654 DispatchBlock->setName("catch.dispatch");
655 break;
656
657 case EHScope::Cleanup:
658 DispatchBlock->setName("ehcleanup");
659 break;
660
661 case EHScope::Filter:
662 llvm_unreachable("exception specifications not handled yet!");
663
664 case EHScope::Terminate:
665 DispatchBlock->setName("terminate");
666 break;
667
Reid Kleckner2586aac2015-09-10 22:11:13 +0000668 case EHScope::PadEnd:
669 llvm_unreachable("PadEnd dispatch block missing!");
David Majnemerdbf10452015-07-31 17:58:45 +0000670 }
671 EHS.setCachedEHDispatchBlock(DispatchBlock);
672 return DispatchBlock;
673}
674
John McCallbd309292010-07-06 01:34:17 +0000675/// Check whether this is a non-EH scope, i.e. a scope which doesn't
676/// affect exception handling. Currently, the only non-EH scopes are
677/// normal-only cleanup scopes.
678static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000679 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000680 case EHScope::Cleanup:
681 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000682 case EHScope::Filter:
683 case EHScope::Catch:
684 case EHScope::Terminate:
Reid Kleckner2586aac2015-09-10 22:11:13 +0000685 case EHScope::PadEnd:
John McCall2b7fc382010-07-13 20:32:21 +0000686 return false;
687 }
688
David Blaikiee4d798f2012-01-20 21:50:17 +0000689 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000690}
691
692llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
693 assert(EHStack.requiresLandingPad());
694 assert(!EHStack.empty());
695
Reid Kleckner8f1b1f52016-03-01 19:51:48 +0000696 // If exceptions are disabled and SEH is not in use, then there is no invoke
697 // destination. SEH "works" even if exceptions are off. In practice, this
698 // means that C++ destructors and other EH cleanups don't run, which is
699 // consistent with MSVC's behavior.
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000700 const LangOptions &LO = CGM.getLangOpts();
701 if (!LO.Exceptions) {
702 if (!LO.Borland && !LO.MicrosoftExt)
703 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000704 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000705 return nullptr;
706 }
John McCall2b7fc382010-07-13 20:32:21 +0000707
Justin Lebar3e6449b2016-10-04 23:41:49 +0000708 // CUDA device code doesn't have exceptions.
709 if (LO.CUDA && LO.CUDAIsDevice)
710 return nullptr;
711
John McCallbd309292010-07-06 01:34:17 +0000712 // Check the innermost scope for a cached landing pad. If this is
713 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
714 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
715 if (LP) return LP;
716
David Majnemerdbf10452015-07-31 17:58:45 +0000717 const EHPersonality &Personality = EHPersonality::get(*this);
718
719 if (!CurFn->hasPersonalityFn())
720 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
721
Reid Kleckner129552b2015-10-08 01:13:52 +0000722 if (Personality.usesFuncletPads()) {
723 // We don't need separate landing pads in the funclet model.
David Majnemerdbf10452015-07-31 17:58:45 +0000724 LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
725 } else {
726 // Build the landing pad for this scope.
727 LP = EmitLandingPad();
728 }
729
John McCallbd309292010-07-06 01:34:17 +0000730 assert(LP);
731
732 // Cache the landing pad on the innermost scope. If this is a
733 // non-EH scope, cache the landing pad on the enclosing scope, too.
734 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
735 ir->setCachedLandingPad(LP);
736 if (!isNonEHScope(*ir)) break;
737 }
738
739 return LP;
740}
741
742llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
743 assert(EHStack.requiresLandingPad());
744
John McCall8e4c74b2011-08-11 02:22:43 +0000745 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
746 switch (innermostEHScope.getKind()) {
747 case EHScope::Terminate:
748 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000749
Reid Kleckner2586aac2015-09-10 22:11:13 +0000750 case EHScope::PadEnd:
751 llvm_unreachable("PadEnd unnecessary for Itanium!");
David Majnemerdbf10452015-07-31 17:58:45 +0000752
John McCall8e4c74b2011-08-11 02:22:43 +0000753 case EHScope::Catch:
754 case EHScope::Cleanup:
755 case EHScope::Filter:
756 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
757 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000758 }
759
760 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000761 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantl95b24e92015-02-03 20:00:54 +0000762 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000763
764 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000765 llvm::BasicBlock *lpad = createBasicBlock("lpad");
766 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000767
David Majnemerfcbdb6e2015-06-17 20:53:19 +0000768 llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
769 llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +0000770
771 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
772 Builder.CreateStore(LPadExn, getExceptionSlot());
773 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
774 Builder.CreateStore(LPadSel, getEHSelectorSlot());
775
John McCallbd309292010-07-06 01:34:17 +0000776 // Save the exception pointer. It's safe to use a single exception
777 // pointer per function because EH cleanups can never have nested
778 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000779 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000780
781 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000782 bool hasCatchAll = false;
783 bool hasCleanup = false;
784 bool hasFilter = false;
785 SmallVector<llvm::Value*, 4> filterTypes;
786 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Nico Webere68b9f32015-02-25 16:25:00 +0000787 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
788 ++I) {
John McCallbd309292010-07-06 01:34:17 +0000789
790 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000791 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000792 // If we have a cleanup, remember that.
793 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000794 continue;
795
John McCallbd309292010-07-06 01:34:17 +0000796 case EHScope::Filter: {
797 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000798 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000799
Bill Wendlingf0724e82011-09-19 20:31:14 +0000800 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000801 EHFilterScope &filter = cast<EHFilterScope>(*I);
802 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000803
Bill Wendling8c4b7162011-09-22 20:32:54 +0000804 // Add all the filter values.
805 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
806 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000807 goto done;
808 }
809
810 case EHScope::Terminate:
811 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000812 assert(!hasCatchAll);
813 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000814 goto done;
815
816 case EHScope::Catch:
817 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000818
Reid Kleckner2586aac2015-09-10 22:11:13 +0000819 case EHScope::PadEnd:
820 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCallbd309292010-07-06 01:34:17 +0000821 }
822
John McCall8e4c74b2011-08-11 02:22:43 +0000823 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
824 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
825 EHCatchScope::Handler handler = catchScope.getHandler(hi);
Reid Kleckner10aa7702015-09-16 20:15:55 +0000826 assert(handler.Type.Flags == 0 &&
827 "landingpads do not support catch handler flags");
John McCallbd309292010-07-06 01:34:17 +0000828
John McCall8e4c74b2011-08-11 02:22:43 +0000829 // If this is a catch-all, register that and abort.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000830 if (!handler.Type.RTTI) {
John McCall8e4c74b2011-08-11 02:22:43 +0000831 assert(!hasCatchAll);
832 hasCatchAll = true;
833 goto done;
John McCallbd309292010-07-06 01:34:17 +0000834 }
835
836 // Check whether we already have a handler for this type.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000837 if (catchTypes.insert(handler.Type.RTTI).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000838 // If not, add it directly to the landingpad.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000839 LPadInst->addClause(handler.Type.RTTI);
John McCallbd309292010-07-06 01:34:17 +0000840 }
John McCallbd309292010-07-06 01:34:17 +0000841 }
842
843 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000844 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000845 assert(!(hasCatchAll && hasFilter));
846 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000847 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000848
849 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000850 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000851 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000852 // Create a filter expression: a constant array indicating which filter
853 // types there are. The personality routine only lands here if the filter
854 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000855 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000856 llvm::ArrayType *AType =
857 llvm::ArrayType::get(!filterTypes.empty() ?
858 filterTypes[0]->getType() : Int8PtrTy,
859 filterTypes.size());
860
861 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
862 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
863 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
864 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000865
866 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000867 if (hasCleanup)
868 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000869
870 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000871 } else if (hasCleanup) {
872 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000873 }
874
Bill Wendlingf0724e82011-09-19 20:31:14 +0000875 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
876 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000877
878 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000879 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000880
881 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000882 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000883
John McCall8e4c74b2011-08-11 02:22:43 +0000884 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000885}
886
David Majnemer4e52d6f2015-12-12 05:39:21 +0000887static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
David Majnemerdbf10452015-07-31 17:58:45 +0000888 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
889 assert(DispatchBlock);
890
891 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
892 CGF.EmitBlockAfterUses(DispatchBlock);
893
David Majnemer4e52d6f2015-12-12 05:39:21 +0000894 llvm::Value *ParentPad = CGF.CurrentFuncletPad;
895 if (!ParentPad)
896 ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
897 llvm::BasicBlock *UnwindBB =
898 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
899
900 unsigned NumHandlers = CatchScope.getNumHandlers();
901 llvm::CatchSwitchInst *CatchSwitch =
902 CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
David Majnemerdbf10452015-07-31 17:58:45 +0000903
904 // Test against each of the exception types we claim to catch.
David Majnemer4e52d6f2015-12-12 05:39:21 +0000905 for (unsigned I = 0; I < NumHandlers; ++I) {
David Majnemerdbf10452015-07-31 17:58:45 +0000906 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
907
Reid Kleckner10aa7702015-09-16 20:15:55 +0000908 CatchTypeInfo TypeInfo = Handler.Type;
909 if (!TypeInfo.RTTI)
910 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
David Majnemerdbf10452015-07-31 17:58:45 +0000911
David Majnemer4e52d6f2015-12-12 05:39:21 +0000912 CGF.Builder.SetInsertPoint(Handler.Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000913
914 if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000915 CGF.Builder.CreateCatchPad(
916 CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
917 llvm::Constant::getNullValue(CGF.VoidPtrTy)});
David Majnemerdbf10452015-07-31 17:58:45 +0000918 } else {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000919 CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
David Majnemerdbf10452015-07-31 17:58:45 +0000920 }
921
David Majnemer4e52d6f2015-12-12 05:39:21 +0000922 CatchSwitch->addHandler(Handler.Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000923 }
924 CGF.Builder.restoreIP(SavedIP);
David Majnemerdbf10452015-07-31 17:58:45 +0000925}
926
John McCall8e4c74b2011-08-11 02:22:43 +0000927/// Emit the structure of the dispatch block for the given catch scope.
928/// It is an invariant that the dispatch block already exists.
David Majnemer4e52d6f2015-12-12 05:39:21 +0000929static void emitCatchDispatchBlock(CodeGenFunction &CGF,
930 EHCatchScope &catchScope) {
Reid Kleckner129552b2015-10-08 01:13:52 +0000931 if (EHPersonality::get(CGF).usesFuncletPads())
932 return emitCatchPadBlock(CGF, catchScope);
David Majnemerdbf10452015-07-31 17:58:45 +0000933
John McCall8e4c74b2011-08-11 02:22:43 +0000934 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
935 assert(dispatchBlock);
936
937 // If there's only a single catch-all, getEHDispatchBlock returned
938 // that catch-all as the dispatch block.
939 if (catchScope.getNumHandlers() == 1 &&
940 catchScope.getHandler(0).isCatchAll()) {
941 assert(dispatchBlock == catchScope.getHandler(0).Block);
David Majnemer4e52d6f2015-12-12 05:39:21 +0000942 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000943 }
944
945 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
946 CGF.EmitBlockAfterUses(dispatchBlock);
947
948 // Select the right handler.
949 llvm::Value *llvm_eh_typeid_for =
950 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
951
952 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000953 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000954
955 // Test against each of the exception types we claim to catch.
956 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
957 assert(i < e && "ran off end of handlers!");
958 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
959
Reid Kleckner10aa7702015-09-16 20:15:55 +0000960 llvm::Value *typeValue = handler.Type.RTTI;
961 assert(handler.Type.Flags == 0 &&
962 "landingpads do not support catch handler flags");
John McCall8e4c74b2011-08-11 02:22:43 +0000963 assert(typeValue && "fell into catch-all case!");
964 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
965
966 // Figure out the next block.
967 bool nextIsEnd;
968 llvm::BasicBlock *nextBlock;
969
970 // If this is the last handler, we're at the end, and the next
971 // block is the block for the enclosing EH scope.
972 if (i + 1 == e) {
973 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
974 nextIsEnd = true;
975
976 // If the next handler is a catch-all, we're at the end, and the
977 // next block is that handler.
978 } else if (catchScope.getHandler(i+1).isCatchAll()) {
979 nextBlock = catchScope.getHandler(i+1).Block;
980 nextIsEnd = true;
981
982 // Otherwise, we're not at the end and we need a new block.
983 } else {
984 nextBlock = CGF.createBasicBlock("catch.fallthrough");
985 nextIsEnd = false;
986 }
987
988 // Figure out the catch type's index in the LSDA's type table.
989 llvm::CallInst *typeIndex =
990 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
991 typeIndex->setDoesNotThrow();
992
993 llvm::Value *matchesTypeIndex =
994 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
995 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
996
997 // If the next handler is a catch-all, we're completely done.
998 if (nextIsEnd) {
999 CGF.Builder.restoreIP(savedIP);
David Majnemer4e52d6f2015-12-12 05:39:21 +00001000 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001001 }
Ahmed Charles289896d2012-02-19 11:57:29 +00001002 // Otherwise we need to emit and continue at that block.
1003 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +00001004 }
John McCall8e4c74b2011-08-11 02:22:43 +00001005}
1006
1007void CodeGenFunction::popCatchScope() {
1008 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1009 if (catchScope.hasEHBranches())
1010 emitCatchDispatchBlock(*this, catchScope);
1011 EHStack.popCatch();
1012}
1013
John McCallb609d3f2010-07-07 06:56:46 +00001014void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001015 unsigned NumHandlers = S.getNumHandlers();
1016 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1017 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001018
John McCall8e4c74b2011-08-11 02:22:43 +00001019 // If the catch was not required, bail out now.
1020 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001021 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001022 EHStack.popCatch();
1023 return;
1024 }
1025
1026 // Emit the structure of the EH dispatch for this catch.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001027 emitCatchDispatchBlock(*this, CatchScope);
John McCall8e4c74b2011-08-11 02:22:43 +00001028
John McCallbd309292010-07-06 01:34:17 +00001029 // Copy the handler blocks off before we pop the EH stack. Emitting
1030 // the handlers might scribble on this memory.
Benjamin Kramerda32cf82015-08-04 15:38:49 +00001031 SmallVector<EHCatchScope::Handler, 8> Handlers(
1032 CatchScope.begin(), CatchScope.begin() + NumHandlers);
John McCall8e4c74b2011-08-11 02:22:43 +00001033
John McCallbd309292010-07-06 01:34:17 +00001034 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001035
John McCallbd309292010-07-06 01:34:17 +00001036 // The fall-through block.
1037 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001038
John McCallbd309292010-07-06 01:34:17 +00001039 // We just emitted the body of the try; jump to the continue block.
1040 if (HaveInsertPoint())
1041 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001042
John McCalld8d00be2012-06-15 05:27:05 +00001043 // Determine if we need an implicit rethrow for all these catch handlers;
1044 // see the comment below.
1045 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001046 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001047 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1048 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001049
John McCall8e4c74b2011-08-11 02:22:43 +00001050 // Perversely, we emit the handlers backwards precisely because we
1051 // want them to appear in source order. In all of these cases, the
1052 // catch block will have exactly one predecessor, which will be a
1053 // particular block in the catch dispatch. However, in the case of
1054 // a catch-all, one of the dispatch blocks will branch to two
1055 // different handlers, and EmitBlockAfterUses will cause the second
1056 // handler to be moved before the first.
1057 for (unsigned I = NumHandlers; I != 0; --I) {
1058 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1059 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001060
John McCallbd309292010-07-06 01:34:17 +00001061 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001062 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001063
John McCallbd309292010-07-06 01:34:17 +00001064 // Enter a cleanup scope, including the catch variable and the
1065 // end-catch.
1066 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001067
John McCallbd309292010-07-06 01:34:17 +00001068 // Initialize the catch variable and set up the cleanups.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001069 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1070 CurrentFuncletPad);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001071 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallbd309292010-07-06 01:34:17 +00001072
Justin Bognerea278c32014-01-07 00:20:28 +00001073 // Emit the PGO counter increment.
Justin Bogner66242d62015-04-23 23:06:47 +00001074 incrementProfileCounter(C);
Justin Bogneref512b92014-01-06 22:27:43 +00001075
John McCallbd309292010-07-06 01:34:17 +00001076 // Perform the body of the catch.
1077 EmitStmt(C->getHandlerBlock());
1078
John McCalld8d00be2012-06-15 05:27:05 +00001079 // [except.handle]p11:
1080 // The currently handled exception is rethrown if control
1081 // reaches the end of a handler of the function-try-block of a
1082 // constructor or destructor.
1083
1084 // It is important that we only do this on fallthrough and not on
1085 // return. Note that it's illegal to put a return in a
1086 // constructor function-try-block's catch handler (p14), so this
1087 // really only applies to destructors.
1088 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +00001089 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +00001090 Builder.CreateUnreachable();
1091 Builder.ClearInsertionPoint();
1092 }
1093
John McCallbd309292010-07-06 01:34:17 +00001094 // Fall out through the catch cleanups.
1095 CatchScope.ForceCleanup();
1096
1097 // Branch out of the try.
1098 if (HaveInsertPoint())
1099 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001100 }
1101
John McCallbd309292010-07-06 01:34:17 +00001102 EmitBlock(ContBB);
Justin Bogner66242d62015-04-23 23:06:47 +00001103 incrementProfileCounter(&S);
Mike Stump58ef18b2009-11-20 23:44:51 +00001104}
Mike Stumpaff69af2009-12-09 03:35:49 +00001105
John McCall1e670402010-07-21 00:52:03 +00001106namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001107 struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001108 llvm::Value *ForEHVar;
1109 llvm::Value *EndCatchFn;
1110 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1111 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1112
Craig Topper4f12f102014-03-12 06:41:41 +00001113 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001114 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1115 llvm::BasicBlock *CleanupContBB =
1116 CGF.createBasicBlock("finally.cleanup.cont");
1117
1118 llvm::Value *ShouldEndCatch =
John McCall7f416cc2015-09-08 08:05:57 +00001119 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
John McCall1e670402010-07-21 00:52:03 +00001120 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1121 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001122 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001123 CGF.EmitBlock(CleanupContBB);
1124 }
1125 };
John McCall906da4b2010-07-21 05:47:49 +00001126
David Blaikie7e70d682015-08-18 22:40:54 +00001127 struct PerformFinally final : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001128 const Stmt *Body;
1129 llvm::Value *ForEHVar;
1130 llvm::Value *EndCatchFn;
1131 llvm::Value *RethrowFn;
1132 llvm::Value *SavedExnVar;
1133
1134 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1135 llvm::Value *EndCatchFn,
1136 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1137 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1138 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1139
Craig Topper4f12f102014-03-12 06:41:41 +00001140 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001141 // Enter a cleanup to call the end-catch function if one was provided.
1142 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001143 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1144 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001145
John McCallcebe0ca2010-08-11 00:16:14 +00001146 // Save the current cleanup destination in case there are
1147 // cleanups in the finally block.
1148 llvm::Value *SavedCleanupDest =
1149 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1150 "cleanup.dest.saved");
1151
John McCall906da4b2010-07-21 05:47:49 +00001152 // Emit the finally block.
1153 CGF.EmitStmt(Body);
1154
1155 // If the end of the finally is reachable, check whether this was
1156 // for EH. If so, rethrow.
1157 if (CGF.HaveInsertPoint()) {
1158 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1159 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1160
1161 llvm::Value *ShouldRethrow =
John McCall7f416cc2015-09-08 08:05:57 +00001162 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
John McCall906da4b2010-07-21 05:47:49 +00001163 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1164
1165 CGF.EmitBlock(RethrowBB);
1166 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001167 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
John McCall7f416cc2015-09-08 08:05:57 +00001168 CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
John McCall906da4b2010-07-21 05:47:49 +00001169 } else {
John McCall882987f2013-02-28 19:01:20 +00001170 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001171 }
1172 CGF.Builder.CreateUnreachable();
1173
1174 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001175
1176 // Restore the cleanup destination.
1177 CGF.Builder.CreateStore(SavedCleanupDest,
1178 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001179 }
1180
1181 // Leave the end-catch cleanup. As an optimization, pretend that
1182 // the fallthrough path was inaccessible; we've dynamically proven
1183 // that we're not in the EH case along that path.
1184 if (EndCatchFn) {
1185 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1186 CGF.PopCleanupBlock();
1187 CGF.Builder.restoreIP(SavedIP);
1188 }
1189
1190 // Now make sure we actually have an insertion point or the
1191 // cleanup gods will hate us.
1192 CGF.EnsureInsertPoint();
1193 }
1194 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001195} // end anonymous namespace
John McCall1e670402010-07-21 00:52:03 +00001196
John McCallbd309292010-07-06 01:34:17 +00001197/// Enters a finally block for an implementation using zero-cost
1198/// exceptions. This is mostly general, but hard-codes some
1199/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001200void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1201 const Stmt *body,
1202 llvm::Constant *beginCatchFn,
1203 llvm::Constant *endCatchFn,
1204 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001205 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001206 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001207 assert(rethrowFn && "rethrow function is required");
1208
1209 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001210
John McCallbd309292010-07-06 01:34:17 +00001211 // The rethrow function has one of the following two types:
1212 // void (*)()
1213 // void (*)(void*)
1214 // In the latter case we need to pass it the exception object.
1215 // But we can't use the exception slot because the @finally might
1216 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001217 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001218 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001219 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001220 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001221 if (rethrowFnTy->getNumParams())
1222 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001223
John McCallbd309292010-07-06 01:34:17 +00001224 // A finally block is a statement which must be executed on any edge
1225 // out of a given scope. Unlike a cleanup, the finally block may
1226 // contain arbitrary control flow leading out of itself. In
1227 // addition, finally blocks should always be executed, even if there
1228 // are no catch handlers higher on the stack. Therefore, we
1229 // surround the protected scope with a combination of a normal
1230 // cleanup (to catch attempts to break out of the block via normal
1231 // control flow) and an EH catch-all (semantically "outside" any try
1232 // statement to which the finally block might have been attached).
1233 // The finally block itself is generated in the context of a cleanup
1234 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001235
John McCallbd309292010-07-06 01:34:17 +00001236 // Jump destination for performing the finally block on an exception
1237 // edge. We'll never actually reach this block, so unreachable is
1238 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001239 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001240
John McCallbd309292010-07-06 01:34:17 +00001241 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001242 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
John McCall7f416cc2015-09-08 08:05:57 +00001243 CGF.Builder.CreateFlagStore(false, ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001244
John McCallbd309292010-07-06 01:34:17 +00001245 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001246 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1247 ForEHVar, endCatchFn,
1248 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001249
1250 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001251 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1252 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1253 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001254}
1255
John McCall6b0feb72011-06-22 02:32:12 +00001256void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001257 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001258 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1259 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001260
1261 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001262
John McCall6b0feb72011-06-22 02:32:12 +00001263 // If there are any references to the catch-all block, emit it.
1264 if (catchBB->use_empty()) {
1265 delete catchBB;
1266 } else {
1267 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1268 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001269
Craig Topper8a13c412014-05-21 05:09:00 +00001270 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001271
John McCall6b0feb72011-06-22 02:32:12 +00001272 // If there's a begin-catch function, call it.
1273 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001274 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001275 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001276 }
1277
1278 // If we need to remember the exception pointer to rethrow later, do so.
1279 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001280 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall7f416cc2015-09-08 08:05:57 +00001281 CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
John McCall6b0feb72011-06-22 02:32:12 +00001282 }
1283
1284 // Tell the cleanups in the finally block that we're do this for EH.
John McCall7f416cc2015-09-08 08:05:57 +00001285 CGF.Builder.CreateFlagStore(true, ForEHVar);
John McCall6b0feb72011-06-22 02:32:12 +00001286
1287 // Thread a jump through the finally cleanup.
1288 CGF.EmitBranchThroughCleanup(RethrowDest);
1289
1290 CGF.Builder.restoreIP(savedIP);
1291 }
1292
1293 // Finally, leave the @finally cleanup.
1294 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001295}
1296
1297llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1298 if (TerminateLandingPad)
1299 return TerminateLandingPad;
1300
1301 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1302
1303 // This will get inserted at the end of the function.
1304 TerminateLandingPad = createBasicBlock("terminate.lpad");
1305 Builder.SetInsertPoint(TerminateLandingPad);
1306
1307 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001308 const EHPersonality &Personality = EHPersonality::get(*this);
David Majnemerfcbdb6e2015-06-17 20:53:19 +00001309
1310 if (!CurFn->hasPersonalityFn())
1311 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1312
1313 llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
1314 llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001315 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001316
Hans Wennborgdcfba332015-10-06 23:40:43 +00001317 llvm::Value *Exn = nullptr;
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001318 if (getLangOpts().CPlusPlus)
1319 Exn = Builder.CreateExtractValue(LPadInst, 0);
1320 llvm::CallInst *terminateCall =
1321 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCalle142ad52013-02-12 03:51:46 +00001322 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001323 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001324
John McCallbd309292010-07-06 01:34:17 +00001325 // Restore the saved insertion state.
1326 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001327
John McCallbd309292010-07-06 01:34:17 +00001328 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001329}
Mike Stump2b488872009-12-09 22:59:31 +00001330
1331llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001332 if (TerminateHandler)
1333 return TerminateHandler;
1334
John McCallbd309292010-07-06 01:34:17 +00001335 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001336
John McCallbd309292010-07-06 01:34:17 +00001337 // Set up the terminate handler. This block is inserted at the very
1338 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001339 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001340 Builder.SetInsertPoint(TerminateHandler);
David Majnemerfeeefb22015-12-14 18:34:18 +00001341 llvm::Value *Exn = nullptr;
David Majnemer971d31b2016-02-24 17:02:45 +00001342 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1343 CurrentFuncletPad);
Reid Kleckner129552b2015-10-08 01:13:52 +00001344 if (EHPersonality::get(*this).usesFuncletPads()) {
David Majnemer4e52d6f2015-12-12 05:39:21 +00001345 llvm::Value *ParentPad = CurrentFuncletPad;
1346 if (!ParentPad)
1347 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
David Majnemer971d31b2016-02-24 17:02:45 +00001348 CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
David Majnemerdbf10452015-07-31 17:58:45 +00001349 } else {
David Majnemerdbf10452015-07-31 17:58:45 +00001350 if (getLangOpts().CPlusPlus)
1351 Exn = getExceptionFromSlot();
David Majnemerdbf10452015-07-31 17:58:45 +00001352 }
David Majnemerfeeefb22015-12-14 18:34:18 +00001353 llvm::CallInst *terminateCall =
1354 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1355 terminateCall->setDoesNotReturn();
1356 Builder.CreateUnreachable();
Mike Stump2b488872009-12-09 22:59:31 +00001357
John McCall21886962010-04-21 10:05:39 +00001358 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001359 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001360
Mike Stump2b488872009-12-09 22:59:31 +00001361 return TerminateHandler;
1362}
John McCallbd309292010-07-06 01:34:17 +00001363
David Chisnall9a837be2012-11-07 16:50:40 +00001364llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001365 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001366
1367 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1368
1369 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001370 EHResumeBlock = createBasicBlock("eh.resume");
1371 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001372
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001373 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001374
1375 // This can always be a call because we necessarily didn't find
1376 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001377 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001378 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001379 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Nico Weberff62a6a2015-02-26 22:34:33 +00001380 getExceptionFromSlot())->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001381 Builder.CreateUnreachable();
1382 Builder.restoreIP(SavedIP);
1383 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001384 }
1385
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001386 // Recreate the landingpad's return value for the 'resume' instruction.
1387 llvm::Value *Exn = getExceptionFromSlot();
1388 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001389
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001390 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
Reid Kleckneree7cf842014-12-01 22:02:27 +00001391 Sel->getType(), nullptr);
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001392 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1393 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1394 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1395
1396 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001397 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001398 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001399}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001400
1401void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001402 EnterSEHTryStmt(S);
Reid Klecknera5930002015-02-11 21:40:48 +00001403 {
Nico Weber5779f842015-02-12 23:16:11 +00001404 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
Nico Weber5779f842015-02-12 23:16:11 +00001405
Reid Kleckner11c033e2015-02-12 23:40:45 +00001406 SEHTryEpilogueStack.push_back(&TryExit);
Reid Klecknera5930002015-02-11 21:40:48 +00001407 EmitStmt(S.getTryBlock());
Reid Kleckner11c033e2015-02-12 23:40:45 +00001408 SEHTryEpilogueStack.pop_back();
Nico Weber5779f842015-02-12 23:16:11 +00001409
1410 if (!TryExit.getBlock()->use_empty())
1411 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1412 else
1413 delete TryExit.getBlock();
Reid Klecknera5930002015-02-11 21:40:48 +00001414 }
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001415 ExitSEHTryStmt(S);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001416}
1417
1418namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001419struct PerformSEHFinally final : EHScopeStack::Cleanup {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001420 llvm::Function *OutlinedFinally;
Reid Kleckner55391522015-10-08 21:14:56 +00001421 PerformSEHFinally(llvm::Function *OutlinedFinally)
1422 : OutlinedFinally(OutlinedFinally) {}
Reid Kleckneraca01db2015-02-04 22:37:07 +00001423
Reid Kleckner1d59f992015-01-22 01:36:17 +00001424 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001425 ASTContext &Context = CGF.getContext();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001426 CodeGenModule &CGM = CGF.CGM;
Reid Kleckner65870442015-06-09 17:47:50 +00001427
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001428 CallArgList Args;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001429
1430 // Compute the two argument values.
1431 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
Reid Kleckner15d152d2015-07-07 23:23:31 +00001432 llvm::Value *LocalAddrFn = CGM.getIntrinsic(llvm::Intrinsic::localaddress);
David Blaikie4ba525b2015-07-14 17:27:39 +00001433 llvm::Value *FP = CGF.Builder.CreateCall(LocalAddrFn);
Reid Klecknereb11c412015-07-01 21:00:00 +00001434 llvm::Value *IsForEH =
1435 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1436 Args.add(RValue::get(IsForEH), ArgTys[0]);
1437 Args.add(RValue::get(FP), ArgTys[1]);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001438
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001439 // Arrange a two-arg function info and type.
Reid Klecknereb11c412015-07-01 21:00:00 +00001440 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001441 CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001442
John McCallb92ab1a2016-10-26 23:46:34 +00001443 auto Callee = CGCallee::forDirect(OutlinedFinally);
1444 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001445 }
1446};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001447} // end anonymous namespace
Reid Kleckner1d59f992015-01-22 01:36:17 +00001448
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001449namespace {
1450/// Find all local variable captures in the statement.
1451struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1452 CodeGenFunction &ParentCGF;
1453 const VarDecl *ParentThis;
John McCall0a490152015-09-08 21:15:22 +00001454 llvm::SmallSetVector<const VarDecl *, 4> Captures;
John McCall7f416cc2015-09-08 08:05:57 +00001455 Address SEHCodeSlot = Address::invalid();
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001456 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1457 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1458
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001459 // Return true if we need to do any capturing work.
1460 bool foundCaptures() {
John McCall7f416cc2015-09-08 08:05:57 +00001461 return !Captures.empty() || SEHCodeSlot.isValid();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001462 }
1463
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001464 void Visit(const Stmt *S) {
1465 // See if this is a capture, then recurse.
1466 ConstStmtVisitor<CaptureFinder>::Visit(S);
1467 for (const Stmt *Child : S->children())
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001468 if (Child)
1469 Visit(Child);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001470 }
1471
1472 void VisitDeclRefExpr(const DeclRefExpr *E) {
1473 // If this is already a capture, just make sure we capture 'this'.
1474 if (E->refersToEnclosingVariableOrCapture()) {
John McCall0a490152015-09-08 21:15:22 +00001475 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001476 return;
1477 }
1478
1479 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1480 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
John McCall0a490152015-09-08 21:15:22 +00001481 Captures.insert(D);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001482 }
1483
1484 void VisitCXXThisExpr(const CXXThisExpr *E) {
John McCall0a490152015-09-08 21:15:22 +00001485 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001486 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001487
1488 void VisitCallExpr(const CallExpr *E) {
1489 // We only need to add parent frame allocations for these builtins in x86.
1490 if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1491 return;
1492
1493 unsigned ID = E->getBuiltinCallee();
1494 switch (ID) {
1495 case Builtin::BI__exception_code:
1496 case Builtin::BI_exception_code:
1497 // This is the simple case where we are the outermost finally. All we
1498 // have to do here is make sure we escape this and recover it in the
1499 // outlined handler.
John McCall7f416cc2015-09-08 08:05:57 +00001500 if (!SEHCodeSlot.isValid())
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001501 SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1502 break;
1503 }
1504 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001505};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001506} // end anonymous namespace
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001507
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001508Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
1509 Address ParentVar,
1510 llvm::Value *ParentFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001511 llvm::CallInst *RecoverCall = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00001512 CGBuilderTy Builder(*this, AllocaInsertPt);
1513 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001514 // Mark the variable escaped if nobody else referenced it and compute the
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001515 // localescape index.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001516 auto InsertPair = ParentCGF.EscapedLocals.insert(
1517 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1518 int FrameEscapeIdx = InsertPair.first->second;
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001519 // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001520 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001521 &CGM.getModule(), llvm::Intrinsic::localrecover);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001522 llvm::Constant *ParentI8Fn =
1523 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1524 RecoverCall = Builder.CreateCall(
1525 FrameRecoverFn, {ParentI8Fn, ParentFP,
1526 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1527
1528 } else {
1529 // If the parent didn't have an alloca, we're doing some nested outlining.
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001530 // Just clone the existing localrecover call, but tweak the FP argument to
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001531 // use our FP value. All other arguments are constants.
1532 auto *ParentRecover =
John McCall7f416cc2015-09-08 08:05:57 +00001533 cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001534 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1535 "expected alloca or localrecover in parent LocalDeclMap");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001536 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1537 RecoverCall->setArgOperand(1, ParentFP);
1538 RecoverCall->insertBefore(AllocaInsertPt);
1539 }
1540
1541 // Bitcast the variable, rename it, and insert it in the local decl map.
1542 llvm::Value *ChildVar =
John McCall7f416cc2015-09-08 08:05:57 +00001543 Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1544 ChildVar->setName(ParentVar.getName());
1545 return Address(ChildVar, ParentVar.getAlignment());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001546}
1547
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001548void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
Reid Kleckner0b9bbbf2015-06-09 17:49:42 +00001549 const Stmt *OutlinedStmt,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001550 bool IsFilter) {
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001551 // Find all captures in the Stmt.
1552 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1553 Finder.Visit(OutlinedStmt);
1554
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001555 // We can exit early on x86_64 when there are no captures. We just have to
1556 // save the exception code in filters so that __exception_code() works.
1557 if (!Finder.foundCaptures() &&
1558 CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1559 if (IsFilter)
1560 EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001561 return;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001562 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001563
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001564 llvm::Value *EntryFP = nullptr;
1565 CGBuilderTy Builder(CGM, AllocaInsertPt);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001566 if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1567 // 32-bit SEH filters need to be careful about FP recovery. The end of the
1568 // EH registration is passed in as the EBP physical register. We can
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001569 // recover that with llvm.frameaddress(1).
1570 EntryFP = Builder.CreateCall(
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001571 CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001572 } else {
1573 // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1574 // second parameter.
1575 auto AI = CurFn->arg_begin();
1576 ++AI;
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001577 EntryFP = &*AI;
1578 }
1579
1580 llvm::Value *ParentFP = EntryFP;
1581 if (IsFilter) {
1582 // Given whatever FP the runtime provided us in EntryFP, recover the true
1583 // frame pointer of the parent function. We only need to do this in filters,
1584 // since finally funclets recover the parent FP for us.
1585 llvm::Function *RecoverFPIntrin =
1586 CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
1587 llvm::Constant *ParentI8Fn =
1588 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1589 ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001590 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001591
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001592 // Create llvm.localrecover calls for all captures.
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001593 for (const VarDecl *VD : Finder.Captures) {
1594 if (isa<ImplicitParamDecl>(VD)) {
1595 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1596 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1597 continue;
1598 }
1599 if (VD->getType()->isVariablyModifiedType()) {
1600 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1601 continue;
1602 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001603 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1604 "captured non-local variable");
1605
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001606 // If this decl hasn't been declared yet, it will be declared in the
1607 // OutlinedStmt.
1608 auto I = ParentCGF.LocalDeclMap.find(VD);
1609 if (I == ParentCGF.LocalDeclMap.end())
1610 continue;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001611
John McCall7f416cc2015-09-08 08:05:57 +00001612 Address ParentVar = I->second;
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001613 setAddrOfLocalVar(
1614 VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
Nico Webere4f974c2015-07-02 06:10:53 +00001615 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001616
John McCall7f416cc2015-09-08 08:05:57 +00001617 if (Finder.SEHCodeSlot.isValid()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001618 SEHCodeSlotStack.push_back(
1619 recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1620 }
1621
1622 if (IsFilter)
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001623 EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001624}
1625
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001626/// Arrange a function prototype that can be called by Windows exception
1627/// handling personalities. On Win64, the prototype looks like:
1628/// RetTy func(void *EHPtrs, void *ParentFP);
1629void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001630 bool IsFilter,
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001631 const Stmt *OutlinedStmt) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001632 SourceLocation StartLoc = OutlinedStmt->getLocStart();
1633
1634 // Get the mangled function name.
1635 SmallString<128> Name;
1636 {
1637 llvm::raw_svector_ostream OS(Name);
David Majnemer25eb1652016-03-01 19:42:53 +00001638 const FunctionDecl *ParentSEHFn = ParentCGF.CurSEHParent;
1639 assert(ParentSEHFn && "No CurSEHParent!");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001640 MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1641 if (IsFilter)
David Majnemer25eb1652016-03-01 19:42:53 +00001642 Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001643 else
David Majnemer25eb1652016-03-01 19:42:53 +00001644 Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001645 }
1646
1647 FunctionArgList Args;
1648 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1649 // All SEH finally functions take two parameters. Win64 filters take two
1650 // parameters. Win32 filters take no parameters.
1651 if (IsFilter) {
1652 Args.push_back(ImplicitParamDecl::Create(
1653 getContext(), nullptr, StartLoc,
1654 &getContext().Idents.get("exception_pointers"),
1655 getContext().VoidPtrTy));
1656 } else {
1657 Args.push_back(ImplicitParamDecl::Create(
1658 getContext(), nullptr, StartLoc,
1659 &getContext().Idents.get("abnormal_termination"),
1660 getContext().UnsignedCharTy));
1661 }
1662 Args.push_back(ImplicitParamDecl::Create(
1663 getContext(), nullptr, StartLoc,
1664 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1665 }
1666
1667 QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1668
John McCallc56a8b32016-03-11 04:30:31 +00001669 const CGFunctionInfo &FnInfo =
1670 CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001671
Reid Kleckner1d59f992015-01-22 01:36:17 +00001672 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001673 llvm::Function *Fn = llvm::Function::Create(
1674 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001675
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001676 IsOutlinedSEHHelper = true;
Nico Weberf2a39a72015-04-13 20:03:03 +00001677
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001678 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1679 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
David Majnemer25eb1652016-03-01 19:42:53 +00001680 CurSEHParent = ParentCGF.CurSEHParent;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001681
1682 CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001683 EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001684}
1685
1686/// Create a stub filter function that will ultimately hold the code of the
1687/// filter expression. The EH preparation passes in LLVM will outline the code
1688/// from the main function body into this stub.
1689llvm::Function *
1690CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1691 const SEHExceptStmt &Except) {
1692 const Expr *FilterExpr = Except.getFilterExpr();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001693 startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001694
1695 // Emit the original filter expression, convert to i32, and return.
1696 llvm::Value *R = EmitScalarExpr(FilterExpr);
David Majnemer2ccba832015-04-17 06:57:25 +00001697 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
Reid Kleckner1d59f992015-01-22 01:36:17 +00001698 FilterExpr->getType()->isSignedIntegerType());
1699 Builder.CreateStore(R, ReturnValue);
1700
1701 FinishFunction(FilterExpr->getLocEnd());
1702
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001703 return CurFn;
1704}
1705
1706llvm::Function *
1707CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1708 const SEHFinallyStmt &Finally) {
1709 const Stmt *FinallyBlock = Finally.getBlock();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001710 startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001711
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001712 // Emit the original filter expression, convert to i32, and return.
1713 EmitStmt(FinallyBlock);
1714
1715 FinishFunction(FinallyBlock->getLocEnd());
1716
1717 return CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001718}
1719
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001720void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1721 llvm::Value *ParentFP,
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001722 llvm::Value *EntryFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001723 // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1724 // __exception_info intrinsic.
1725 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1726 // On Win64, the info is passed as the first parameter to the filter.
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001727 SEHInfo = &*CurFn->arg_begin();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001728 SEHCodeSlotStack.push_back(
1729 CreateMemTemp(getContext().IntTy, "__exception_code"));
1730 } else {
1731 // On Win32, the EBP on entry to the filter points to the end of an
1732 // exception registration object. It contains 6 32-bit fields, and the info
1733 // pointer is stored in the second field. So, GEP 20 bytes backwards and
1734 // load the pointer.
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001735 SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001736 SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001737 SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001738 SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1739 ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1740 }
1741
Reid Kleckner1d59f992015-01-22 01:36:17 +00001742 // Save the exception code in the exception slot to unify exception access in
1743 // the filter function and the landing pad.
1744 // struct EXCEPTION_POINTERS {
1745 // EXCEPTION_RECORD *ExceptionRecord;
1746 // CONTEXT *ContextRecord;
1747 // };
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001748 // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001749 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1750 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001751 llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
David Blaikie1ed728c2015-04-05 22:45:47 +00001752 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001753 Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
1754 llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001755 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1756 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001757}
1758
1759llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1760 // Sema should diagnose calling this builtin outside of a filter context, but
1761 // don't crash if we screw up.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001762 if (!SEHInfo)
Reid Kleckner1d59f992015-01-22 01:36:17 +00001763 return llvm::UndefValue::get(Int8PtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001764 assert(SEHInfo->getType() == Int8PtrTy);
1765 return SEHInfo;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001766}
1767
1768llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001769 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
John McCall7f416cc2015-09-08 08:05:57 +00001770 return Builder.CreateLoad(SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001771}
1772
Reid Kleckneraca01db2015-02-04 22:37:07 +00001773llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001774 // Abnormal termination is just the first parameter to the outlined finally
1775 // helper.
1776 auto AI = CurFn->arg_begin();
1777 return Builder.CreateZExt(&*AI, Int32Ty);
Reid Kleckneraca01db2015-02-04 22:37:07 +00001778}
1779
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001780void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1781 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1782 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001783 // Outline the finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001784 llvm::Function *FinallyFunc =
1785 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001786
1787 // Push a cleanup for __finally blocks.
Reid Kleckner55391522015-10-08 21:14:56 +00001788 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001789 return;
1790 }
1791
1792 // Otherwise, we must have an __except block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001793 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001794 assert(Except);
1795 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001796 SEHCodeSlotStack.push_back(
1797 CreateMemTemp(getContext().IntTy, "__exception_code"));
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001798
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001799 // If the filter is known to evaluate to 1, then we can use the clause
1800 // "catch i8* null". We can't do this on x86 because the filter has to save
1801 // the exception code.
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001802 llvm::Constant *C =
1803 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001804 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
1805 C->isOneValue()) {
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001806 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1807 return;
1808 }
1809
1810 // In general, we have to emit an outlined filter function. Use the function
1811 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00001812 llvm::Function *FilterFunc =
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001813 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001814 llvm::Constant *OpaqueFunc =
1815 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
Reid Kleckner8be18472015-09-16 21:06:09 +00001816 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
Reid Kleckner1d59f992015-01-22 01:36:17 +00001817}
1818
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001819void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001820 // Just pop the cleanup if it's a __finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001821 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001822 PopCleanupBlock();
1823 return;
1824 }
1825
1826 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001827 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001828 assert(Except && "__try must have __finally xor __except");
1829 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1830
1831 // Don't emit the __except block if the __try block lacked invokes.
1832 // TODO: Model unwind edges from instructions, either with iload / istore or
1833 // a try body function.
1834 if (!CatchScope.hasEHBranches()) {
1835 CatchScope.clearHandlerBlocks();
1836 EHStack.popCatch();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001837 SEHCodeSlotStack.pop_back();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001838 return;
1839 }
1840
1841 // The fall-through block.
1842 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1843
1844 // We just emitted the body of the __try; jump to the continue block.
1845 if (HaveInsertPoint())
1846 Builder.CreateBr(ContBB);
1847
1848 // Check if our filter function returned true.
1849 emitCatchDispatchBlock(*this, CatchScope);
1850
1851 // Grab the block before we pop the handler.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001852 llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001853 EHStack.popCatch();
1854
David Majnemer4e52d6f2015-12-12 05:39:21 +00001855 EmitBlockAfterUses(CatchPadBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001856
Reid Kleckner129552b2015-10-08 01:13:52 +00001857 // __except blocks don't get outlined into funclets, so immediately do a
1858 // catchret.
Reid Kleckner129552b2015-10-08 01:13:52 +00001859 llvm::CatchPadInst *CPI =
1860 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
David Majnemer4e52d6f2015-12-12 05:39:21 +00001861 llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
Reid Kleckner129552b2015-10-08 01:13:52 +00001862 Builder.CreateCatchRet(CPI, ExceptBB);
1863 EmitBlock(ExceptBB);
1864
1865 // On Win64, the exception code is returned in EAX. Copy it into the slot.
1866 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1867 llvm::Function *SEHCodeIntrin =
1868 CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
1869 llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
1870 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001871 }
1872
Reid Kleckner1d59f992015-01-22 01:36:17 +00001873 // Emit the __except body.
1874 EmitStmt(Except->getBlock());
1875
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001876 // End the lifetime of the exception code.
1877 SEHCodeSlotStack.pop_back();
1878
Reid Kleckner3a417c32015-01-30 22:16:45 +00001879 if (HaveInsertPoint())
1880 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001881
1882 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00001883}
Nico Weber9b982072014-07-07 00:12:30 +00001884
1885void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00001886 // If this code is reachable then emit a stop point (if generating
1887 // debug info). We have to do this ourselves because we are on the
1888 // "simple" statement path.
1889 if (HaveInsertPoint())
1890 EmitStopPoint(&S);
1891
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001892 // This must be a __leave from a __finally block, which we warn on and is UB.
1893 // Just emit unreachable.
1894 if (!isSEHTryScope()) {
1895 Builder.CreateUnreachable();
1896 Builder.ClearInsertionPoint();
1897 return;
1898 }
1899
Nico Weber5779f842015-02-12 23:16:11 +00001900 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00001901}