blob: b37ecaa73513dabd89a635b6b9777e6e8283041c [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 McCallde0fe072017-08-15 21:42:52 +000018#include "ConstantEmitter.h"
John McCall5add20c2010-07-20 22:17:55 +000019#include "TargetInfo.h"
Reid Kleckner1d59f992015-01-22 01:36:17 +000020#include "clang/AST/Mangle.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000021#include "clang/AST/StmtCXX.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000022#include "clang/AST/StmtObjC.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000023#include "clang/AST/StmtVisitor.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000024#include "clang/Basic/TargetBuiltins.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000025#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/Intrinsics.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000027#include "llvm/IR/IntrinsicInst.h"
Reid Klecknerebaf28d2015-04-14 20:59:00 +000028#include "llvm/Support/SaveAndRestore.h"
John McCallbd309292010-07-06 01:34:17 +000029
Anders Carlsson4b08db72009-10-30 01:42:31 +000030using namespace clang;
31using namespace CodeGen;
32
John McCall2c33ba82013-02-12 03:51:38 +000033static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000034 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000035
Chris Lattner2192fe52011-07-18 04:24:23 +000036 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000037 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000038
John McCall2c33ba82013-02-12 03:51:38 +000039 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000040}
41
John McCall2c33ba82013-02-12 03:51:38 +000042static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000043 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000044
Chris Lattner2192fe52011-07-18 04:24:23 +000045 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000046 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000047
John McCall2c33ba82013-02-12 03:51:38 +000048 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000049}
50
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000051llvm::Constant *CodeGenModule::getTerminateFn() {
Mike Stump33270212009-12-02 07:41:41 +000052 // void __terminate();
53
Chris Lattner2192fe52011-07-18 04:24:23 +000054 llvm::FunctionType *FTy =
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000055 llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000056
Chris Lattner0e62c1c2011-07-23 10:55:15 +000057 StringRef name;
John McCall9de19782011-07-06 01:22:26 +000058
59 // In C++, use std::terminate().
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000060 if (getLangOpts().CPlusPlus &&
61 getTarget().getCXXABI().isItaniumFamily()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +000062 name = "_ZSt9terminatev";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000063 } else if (getLangOpts().CPlusPlus &&
64 getTarget().getCXXABI().isMicrosoft()) {
David Majnemerb710a932015-05-11 03:57:49 +000065 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemerfb6ffca2015-05-10 21:38:26 +000066 name = "__std_terminate";
67 else
Reid Klecknerfb931542018-03-16 20:36:49 +000068 name = "?terminate@@YAXXZ";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000069 } else if (getLangOpts().ObjC1 &&
70 getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +000071 name = "objc_terminate";
72 else
73 name = "abort";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000074 return CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +000075}
76
John McCall2c33ba82013-02-12 03:51:38 +000077static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000078 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +000079 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000080 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +000081
John McCall2c33ba82013-02-12 03:51:38 +000082 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +000083}
84
Craig Topper8a13c412014-05-21 05:09:00 +000085const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +000086const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +000087EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
88const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000089EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
90const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +000091EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
92const EHPersonality
93EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
94const EHPersonality
95EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +000096const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000097EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
98const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +000099EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
100const EHPersonality
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000101EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
102const EHPersonality
103EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
104const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000105EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000106const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000107EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Reid Kleckner1d59f992015-01-22 01:36:17 +0000108const EHPersonality
109EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
110const EHPersonality
111EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000112const EHPersonality
113EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000114
Reid Klecknere070b992014-11-14 02:01:10 +0000115static const EHPersonality &getCPersonality(const llvm::Triple &T,
116 const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000117 if (L.SjLjExceptions)
118 return EHPersonality::GNU_C_SJLJ;
Saleem Abdulrasool3e701322018-03-09 07:06:42 +0000119 if (L.DWARFExceptions)
120 return EHPersonality::GNU_C;
121 if (T.isWindowsMSVCEnvironment())
122 return EHPersonality::MSVC_CxxFrameHandler3;
Martell Malonec950c652017-11-29 07:25:12 +0000123 if (L.SEHExceptions)
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000124 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000125 return EHPersonality::GNU_C;
126}
127
Reid Klecknere070b992014-11-14 02:01:10 +0000128static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
129 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000130 switch (L.ObjCRuntime.getKind()) {
131 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000132 return getCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000133 case ObjCRuntime::MacOSX:
134 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000135 case ObjCRuntime::WatchOS:
Saleem Abdulrasool3e701322018-03-09 07:06:42 +0000136 if (T.isWindowsMSVCEnvironment())
137 return EHPersonality::MSVC_CxxFrameHandler3;
John McCall5fb5df92012-06-20 06:18:46 +0000138 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000139 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000140 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
141 return EHPersonality::GNUstep_ObjC;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000142 LLVM_FALLTHROUGH;
David Chisnallb601c962012-07-03 20:49:52 +0000143 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000144 case ObjCRuntime::ObjFW:
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000145 if (L.SjLjExceptions)
146 return EHPersonality::GNU_ObjC_SJLJ;
Martell Malonec950c652017-11-29 07:25:12 +0000147 if (L.SEHExceptions)
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000148 return EHPersonality::GNU_ObjC_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000149 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000150 }
John McCall5fb5df92012-06-20 06:18:46 +0000151 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000152}
153
Reid Klecknere070b992014-11-14 02:01:10 +0000154static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
155 const LangOptions &L) {
John McCall36ea3722010-07-17 00:43:08 +0000156 if (L.SjLjExceptions)
157 return EHPersonality::GNU_CPlusPlus_SJLJ;
Saleem Abdulrasool3e701322018-03-09 07:06:42 +0000158 if (L.DWARFExceptions)
159 return EHPersonality::GNU_CPlusPlus;
160 if (T.isWindowsMSVCEnvironment())
161 return EHPersonality::MSVC_CxxFrameHandler3;
Martell Malonec950c652017-11-29 07:25:12 +0000162 if (L.SEHExceptions)
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000163 return EHPersonality::GNU_CPlusPlus_SEH;
Reid Klecknere070b992014-11-14 02:01:10 +0000164 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000165}
166
167/// Determines the personality function to use when both C++
168/// and Objective-C exceptions are being caught.
Reid Klecknere070b992014-11-14 02:01:10 +0000169static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
170 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000171 switch (L.ObjCRuntime.getKind()) {
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000172 // In the fragile ABI, just use C++ exception handling and hope
173 // they're not doing crazy exception mixing.
174 case ObjCRuntime::FragileMacOSX:
175 return getCXXPersonality(T, L);
176
John McCallbd309292010-07-06 01:34:17 +0000177 // The ObjC personality defers to the C++ personality for non-ObjC
178 // handlers. Unlike the C++ case, we use the same personality
179 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000180 case ObjCRuntime::MacOSX:
181 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000182 case ObjCRuntime::WatchOS:
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000183 return getObjCPersonality(T, L);
John McCallbd309292010-07-06 01:34:17 +0000184
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000185 case ObjCRuntime::GNUstep:
186 return EHPersonality::GNU_ObjCXX;
David Chisnallf9c42252010-05-17 13:49:20 +0000187
David Chisnallb601c962012-07-03 20:49:52 +0000188 // The GCC runtime's personality function inherently doesn't support
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000189 // mixed EH. Use the ObjC personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000190 case ObjCRuntime::GCC:
Benjamin Kramer9851cb72017-04-01 17:59:01 +0000191 case ObjCRuntime::ObjFW:
192 return getObjCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000193 }
194 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000195}
196
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000197static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000198 if (T.getArch() == llvm::Triple::x86)
199 return EHPersonality::MSVC_except_handler;
200 return EHPersonality::MSVC_C_specific_handler;
201}
202
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000203const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
204 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000205 const llvm::Triple &T = CGM.getTarget().getTriple();
206 const LangOptions &L = CGM.getLangOpts();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000207
Reid Kleckner01485652015-09-17 17:04:13 +0000208 // Functions using SEH get an SEH personality.
209 if (FD && FD->usesSEHTry())
210 return getSEHPersonalityMSVC(T);
211
Saleem Abdulrasool3e701322018-03-09 07:06:42 +0000212 if (L.ObjC1)
213 return L.CPlusPlus ? getObjCXXPersonality(T, L) : getObjCPersonality(T, L);
214 return L.CPlusPlus ? getCXXPersonality(T, L) : getCPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000215}
John McCallbd309292010-07-06 01:34:17 +0000216
David Majnemerc28d46e2015-07-22 23:46:21 +0000217const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
Reid Kleckner65fa8692017-10-13 16:55:14 +0000218 const auto *FD = CGF.CurCodeDecl;
219 // For outlined finallys and filters, use the SEH personality in case they
220 // contain more SEH. This mostly only affects finallys. Filters could
221 // hypothetically use gnu statement expressions to sneak in nested SEH.
222 FD = FD ? FD : CGF.CurSEHParent;
223 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(FD));
David Majnemerc28d46e2015-07-22 23:46:21 +0000224}
225
John McCall0bdb1fd2010-09-16 06:16:50 +0000226static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000227 const EHPersonality &Personality) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +0000228 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
229 Personality.PersonalityFn,
Reid Klecknerde864822017-03-21 16:57:30 +0000230 llvm::AttributeList(), /*Local=*/true);
John McCall0bdb1fd2010-09-16 06:16:50 +0000231}
232
233static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
234 const EHPersonality &Personality) {
235 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000236 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000237}
238
Vedant Kumardb609472015-09-11 15:40:05 +0000239/// Check whether a landingpad instruction only uses C++ features.
240static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
241 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
242 // Look for something that would've been returned by the ObjC
243 // runtime's GetEHType() method.
244 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
245 if (LPI->isCatch(I)) {
246 // Check if the catch value has the ObjC prefix.
247 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
248 // ObjC EH selector entries are always global variables with
249 // names starting like this.
250 if (GV->getName().startswith("OBJC_EHTYPE"))
251 return false;
252 } else {
253 // Check if any of the filter values have the ObjC prefix.
254 llvm::Constant *CVal = cast<llvm::Constant>(Val);
255 for (llvm::User::op_iterator
256 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
257 if (llvm::GlobalVariable *GV =
258 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
259 // ObjC EH selector entries are always global variables with
260 // names starting like this.
261 if (GV->getName().startswith("OBJC_EHTYPE"))
262 return false;
263 }
264 }
265 }
266 return true;
267}
268
John McCall0bdb1fd2010-09-16 06:16:50 +0000269/// Check whether a personality function could reasonably be swapped
270/// for a C++ personality function.
271static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000272 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000273 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000274 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000275 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
276 if (!PersonalityHasOnlyCXXUses(CE))
277 return false;
278 continue;
279 }
280
Vedant Kumardb609472015-09-11 15:40:05 +0000281 // Otherwise it must be a function.
282 llvm::Function *F = dyn_cast<llvm::Function>(U);
283 if (!F) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000284
Vedant Kumardb609472015-09-11 15:40:05 +0000285 for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
286 if (BB->isLandingPad())
287 if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
288 return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000289 }
290 }
291
292 return true;
293}
294
295/// Try to use the C++ personality function in ObjC++. Not doing this
296/// can cause some incompatibilities with gcc, which is more
297/// aggressive about only using the ObjC++ personality in a function
298/// when it really needs it.
299void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000300 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000301 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000302 return;
303
John McCall3c223932012-11-14 17:48:31 +0000304 // Both the problem this endeavors to fix and the way the logic
305 // above works is specific to the NeXT runtime.
306 if (!LangOpts.ObjCRuntime.isNeXTFamily())
307 return;
308
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000309 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Reid Klecknere070b992014-11-14 02:01:10 +0000310 const EHPersonality &CXX =
311 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000312 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000313 return;
314
Benjamin Kramer793bd552012-02-08 12:41:24 +0000315 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
316 "Different EHPersonalities using the same personality function.");
317
318 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000319
320 // Nothing to do if it's unused.
321 if (!Fn || Fn->use_empty()) return;
322
323 // Can't do the optimization if it has non-C++ uses.
324 if (!PersonalityHasOnlyCXXUses(Fn)) return;
325
326 // Create the C++ personality function and kill off the old
327 // function.
328 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
329
330 // This can happen if the user is screwing with us.
331 if (Fn->getType() != CXXFn->getType()) return;
332
333 Fn->replaceAllUsesWith(CXXFn);
334 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000335}
336
337/// Returns the value to inject into a selector to indicate the
338/// presence of a catch-all.
339static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
340 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000341 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000342}
343
John McCallbb026012010-07-13 21:17:51 +0000344namespace {
345 /// A cleanup to free the exception object if its initialization
346 /// throws.
David Blaikie7e70d682015-08-18 22:40:54 +0000347 struct FreeException final : EHScopeStack::Cleanup {
John McCall5fcf8da2011-07-12 00:15:30 +0000348 llvm::Value *exn;
349 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000350 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000351 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000352 }
353 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000354} // end anonymous namespace
John McCallbb026012010-07-13 21:17:51 +0000355
John McCall2e6567a2010-04-22 01:10:34 +0000356// Emits an exception expression into the given location. This
357// differs from EmitAnyExprToMem only in that, if a final copy-ctor
358// call is required, an exception within that copy ctor causes
359// std::terminate to be invoked.
John McCall7f416cc2015-09-08 08:05:57 +0000360void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
John McCallbd309292010-07-06 01:34:17 +0000361 // Make sure the exception object is cleaned up if there's an
362 // exception during initialization.
John McCall7f416cc2015-09-08 08:05:57 +0000363 pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
David Majnemer7c237072015-03-05 00:46:22 +0000364 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000365
366 // __cxa_allocate_exception returns a void*; we need to cast this
367 // to the appropriate type for the object.
David Majnemer7c237072015-03-05 00:46:22 +0000368 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
John McCall7f416cc2015-09-08 08:05:57 +0000369 Address typedAddr = Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000370
371 // FIXME: this isn't quite right! If there's a final unelided call
372 // to a copy constructor, then according to [except.terminate]p1 we
373 // must call std::terminate() if that constructor throws, because
374 // technically that copy occurs after the exception expression is
375 // evaluated but before the exception is caught. But the best way
376 // to handle that is to teach EmitAggExpr to do the final copy
377 // differently if it can't be elided.
David Majnemer7c237072015-03-05 00:46:22 +0000378 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
379 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000380
John McCalle4df6c82011-01-28 08:37:24 +0000381 // Deactivate the cleanup block.
John McCall7f416cc2015-09-08 08:05:57 +0000382 DeactivateCleanupBlock(cleanup,
383 cast<llvm::Instruction>(typedAddr.getPointer()));
Mike Stump54066142009-12-01 03:41:18 +0000384}
385
John McCall7f416cc2015-09-08 08:05:57 +0000386Address CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000387 if (!ExceptionSlot)
388 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000389 return Address(ExceptionSlot, getPointerAlign());
Mike Stump54066142009-12-01 03:41:18 +0000390}
391
John McCall7f416cc2015-09-08 08:05:57 +0000392Address CodeGenFunction::getEHSelectorSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000393 if (!EHSelectorSlot)
394 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000395 return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
John McCall9b382dd2011-05-28 21:13:02 +0000396}
397
Bill Wendling79a70e42011-09-15 18:57:19 +0000398llvm::Value *CodeGenFunction::getExceptionFromSlot() {
399 return Builder.CreateLoad(getExceptionSlot(), "exn");
400}
401
402llvm::Value *CodeGenFunction::getSelectorFromSlot() {
403 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
404}
405
Richard Smithea852322013-05-07 21:53:22 +0000406void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
407 bool KeepInsertionPoint) {
David Majnemer7c237072015-03-05 00:46:22 +0000408 if (const Expr *SubExpr = E->getSubExpr()) {
409 QualType ThrowType = SubExpr->getType();
410 if (ThrowType->isObjCObjectPointerType()) {
411 const Stmt *ThrowStmt = E->getSubExpr();
412 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
413 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
414 } else {
415 CGM.getCXXABI().emitThrow(*this, E);
John McCall2e6567a2010-04-22 01:10:34 +0000416 }
David Majnemer7c237072015-03-05 00:46:22 +0000417 } else {
418 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000419 }
Mike Stump75546b82009-12-10 00:06:18 +0000420
John McCall20f6ab82011-01-12 03:41:02 +0000421 // throw is an expression, and the expression emitters expect us
422 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000423 if (KeepInsertionPoint)
424 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000425}
Mike Stump58ef18b2009-11-20 23:44:51 +0000426
Mike Stump1d849212009-12-07 23:38:24 +0000427void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000428 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000429 return;
430
Mike Stump1d849212009-12-07 23:38:24 +0000431 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000432 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000433 // Check if CapturedDecl is nothrow and create terminate scope for it.
434 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
435 if (CD->isNothrow())
436 EHStack.pushTerminate();
437 }
Mike Stump1d849212009-12-07 23:38:24 +0000438 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000439 }
Mike Stump1d849212009-12-07 23:38:24 +0000440 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000441 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000442 return;
443
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000444 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
Richard Smitheaf11ad2018-05-03 03:58:32 +0000445 if (isNoexceptExceptionSpec(EST) && Proto->canThrow() == CT_Cannot) {
446 // noexcept functions are simple terminate scopes.
447 EHStack.pushTerminate();
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000448 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000449 // TODO: Revisit exception specifications for the MS ABI. There is a way to
450 // encode these in an object file but MSVC doesn't do anything with it.
451 if (getTarget().getCXXABI().isMicrosoft())
452 return;
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000453 unsigned NumExceptions = Proto->getNumExceptions();
454 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000455
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000456 for (unsigned I = 0; I != NumExceptions; ++I) {
457 QualType Ty = Proto->getExceptionType(I);
458 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
459 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
460 /*ForEH=*/true);
461 Filter->setFilter(I, EHType);
462 }
Mike Stump1d849212009-12-07 23:38:24 +0000463 }
Mike Stump1d849212009-12-07 23:38:24 +0000464}
465
John McCall8e4c74b2011-08-11 02:22:43 +0000466/// Emit the dispatch block for a filter scope if necessary.
467static void emitFilterDispatchBlock(CodeGenFunction &CGF,
468 EHFilterScope &filterScope) {
469 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
470 if (!dispatchBlock) return;
471 if (dispatchBlock->use_empty()) {
472 delete dispatchBlock;
473 return;
474 }
475
John McCall8e4c74b2011-08-11 02:22:43 +0000476 CGF.EmitBlockAfterUses(dispatchBlock);
477
478 // If this isn't a catch-all filter, we need to check whether we got
479 // here because the filter triggered.
480 if (filterScope.getNumFilters()) {
481 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000482 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000483 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
484
485 llvm::Value *zero = CGF.Builder.getInt32(0);
486 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000487 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
488 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
489 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000490
491 CGF.EmitBlock(unexpectedBB);
492 }
493
494 // Call __cxa_call_unexpected. This doesn't need to be an invoke
495 // because __cxa_call_unexpected magically filters exceptions
496 // according to the last landing pad the exception was thrown
497 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000498 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000499 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000500 ->setDoesNotReturn();
501 CGF.Builder.CreateUnreachable();
502}
503
Mike Stump1d849212009-12-07 23:38:24 +0000504void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000505 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000506 return;
507
Mike Stump1d849212009-12-07 23:38:24 +0000508 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000509 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000510 // Check if CapturedDecl is nothrow and pop terminate scope for it.
511 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
512 if (CD->isNothrow())
513 EHStack.popTerminate();
514 }
Mike Stump1d849212009-12-07 23:38:24 +0000515 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000516 }
Mike Stump1d849212009-12-07 23:38:24 +0000517 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000518 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000519 return;
520
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000521 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
Richard Smitheaf11ad2018-05-03 03:58:32 +0000522 if (isNoexceptExceptionSpec(EST) && Proto->canThrow() == CT_Cannot) {
523 EHStack.popTerminate();
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000524 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000525 // TODO: Revisit exception specifications for the MS ABI. There is a way to
526 // encode these in an object file but MSVC doesn't do anything with it.
527 if (getTarget().getCXXABI().isMicrosoft())
528 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000529 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
530 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000531 EHStack.popFilter();
532 }
Mike Stump1d849212009-12-07 23:38:24 +0000533}
534
Mike Stump58ef18b2009-11-20 23:44:51 +0000535void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000536 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000537 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000538 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000539}
540
John McCallb609d3f2010-07-07 06:56:46 +0000541void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000542 unsigned NumHandlers = S.getNumHandlers();
543 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000544
John McCallbd309292010-07-06 01:34:17 +0000545 for (unsigned I = 0; I != NumHandlers; ++I) {
546 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000547
John McCallbd309292010-07-06 01:34:17 +0000548 llvm::BasicBlock *Handler = createBasicBlock("catch");
549 if (C->getExceptionDecl()) {
550 // FIXME: Dropping the reference type on the type into makes it
551 // impossible to correctly implement catch-by-reference
552 // semantics for pointers. Unfortunately, this is what all
553 // existing compilers do, and it's not clear that the standard
554 // personality routine is capable of doing this right. See C++ DR 388:
555 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000556 Qualifiers CaughtTypeQuals;
557 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
558 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000559
Reid Kleckner10aa7702015-09-16 20:15:55 +0000560 CatchTypeInfo TypeInfo{nullptr, 0};
John McCall2ca705e2010-07-24 00:37:23 +0000561 if (CaughtType->isObjCObjectPointerType())
Reid Kleckner10aa7702015-09-16 20:15:55 +0000562 TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000563 else
Reid Kleckner10aa7702015-09-16 20:15:55 +0000564 TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
565 CaughtType, C->getCaughtType());
John McCallbd309292010-07-06 01:34:17 +0000566 CatchScope->setHandler(I, TypeInfo, Handler);
567 } else {
568 // No exception decl indicates '...', a catch-all.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000569 CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
John McCallbd309292010-07-06 01:34:17 +0000570 }
571 }
John McCallbd309292010-07-06 01:34:17 +0000572}
573
John McCall8e4c74b2011-08-11 02:22:43 +0000574llvm::BasicBlock *
575CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
Reid Kleckner129552b2015-10-08 01:13:52 +0000576 if (EHPersonality::get(*this).usesFuncletPads())
David Majnemerdbf10452015-07-31 17:58:45 +0000577 return getMSVCDispatchBlock(si);
578
John McCall8e4c74b2011-08-11 02:22:43 +0000579 // The dispatch block for the end of the scope chain is a block that
580 // just resumes unwinding.
581 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000582 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000583
584 // Otherwise, we should look at the actual scope.
585 EHScope &scope = *EHStack.find(si);
586
587 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
588 if (!dispatchBlock) {
589 switch (scope.getKind()) {
590 case EHScope::Catch: {
591 // Apply a special case to a single catch-all.
592 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
593 if (catchScope.getNumHandlers() == 1 &&
594 catchScope.getHandler(0).isCatchAll()) {
595 dispatchBlock = catchScope.getHandler(0).Block;
596
597 // Otherwise, make a dispatch block.
598 } else {
599 dispatchBlock = createBasicBlock("catch.dispatch");
600 }
601 break;
602 }
603
604 case EHScope::Cleanup:
605 dispatchBlock = createBasicBlock("ehcleanup");
606 break;
607
608 case EHScope::Filter:
609 dispatchBlock = createBasicBlock("filter.dispatch");
610 break;
611
612 case EHScope::Terminate:
613 dispatchBlock = getTerminateHandler();
614 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000615
Reid Kleckner2586aac2015-09-10 22:11:13 +0000616 case EHScope::PadEnd:
617 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCall8e4c74b2011-08-11 02:22:43 +0000618 }
619 scope.setCachedEHDispatchBlock(dispatchBlock);
620 }
621 return dispatchBlock;
622}
623
David Majnemerdbf10452015-07-31 17:58:45 +0000624llvm::BasicBlock *
625CodeGenFunction::getMSVCDispatchBlock(EHScopeStack::stable_iterator SI) {
626 // Returning nullptr indicates that the previous dispatch block should unwind
627 // to caller.
628 if (SI == EHStack.stable_end())
629 return nullptr;
630
631 // Otherwise, we should look at the actual scope.
632 EHScope &EHS = *EHStack.find(SI);
633
634 llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
635 if (DispatchBlock)
636 return DispatchBlock;
637
638 if (EHS.getKind() == EHScope::Terminate)
Reid Kleckner06f19a02018-01-02 21:34:16 +0000639 DispatchBlock = getTerminateFunclet();
David Majnemerdbf10452015-07-31 17:58:45 +0000640 else
641 DispatchBlock = createBasicBlock();
John McCall7f416cc2015-09-08 08:05:57 +0000642 CGBuilderTy Builder(*this, DispatchBlock);
David Majnemerdbf10452015-07-31 17:58:45 +0000643
644 switch (EHS.getKind()) {
645 case EHScope::Catch:
646 DispatchBlock->setName("catch.dispatch");
647 break;
648
649 case EHScope::Cleanup:
650 DispatchBlock->setName("ehcleanup");
651 break;
652
653 case EHScope::Filter:
654 llvm_unreachable("exception specifications not handled yet!");
655
656 case EHScope::Terminate:
657 DispatchBlock->setName("terminate");
658 break;
659
Reid Kleckner2586aac2015-09-10 22:11:13 +0000660 case EHScope::PadEnd:
661 llvm_unreachable("PadEnd dispatch block missing!");
David Majnemerdbf10452015-07-31 17:58:45 +0000662 }
663 EHS.setCachedEHDispatchBlock(DispatchBlock);
664 return DispatchBlock;
665}
666
John McCallbd309292010-07-06 01:34:17 +0000667/// Check whether this is a non-EH scope, i.e. a scope which doesn't
668/// affect exception handling. Currently, the only non-EH scopes are
669/// normal-only cleanup scopes.
670static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000671 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000672 case EHScope::Cleanup:
673 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000674 case EHScope::Filter:
675 case EHScope::Catch:
676 case EHScope::Terminate:
Reid Kleckner2586aac2015-09-10 22:11:13 +0000677 case EHScope::PadEnd:
John McCall2b7fc382010-07-13 20:32:21 +0000678 return false;
679 }
680
David Blaikiee4d798f2012-01-20 21:50:17 +0000681 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000682}
683
684llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
685 assert(EHStack.requiresLandingPad());
686 assert(!EHStack.empty());
687
Reid Kleckner8f1b1f52016-03-01 19:51:48 +0000688 // If exceptions are disabled and SEH is not in use, then there is no invoke
689 // destination. SEH "works" even if exceptions are off. In practice, this
690 // means that C++ destructors and other EH cleanups don't run, which is
691 // consistent with MSVC's behavior.
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000692 const LangOptions &LO = CGM.getLangOpts();
693 if (!LO.Exceptions) {
694 if (!LO.Borland && !LO.MicrosoftExt)
695 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000696 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000697 return nullptr;
698 }
John McCall2b7fc382010-07-13 20:32:21 +0000699
Justin Lebar3e6449b2016-10-04 23:41:49 +0000700 // CUDA device code doesn't have exceptions.
701 if (LO.CUDA && LO.CUDAIsDevice)
702 return nullptr;
703
John McCallbd309292010-07-06 01:34:17 +0000704 // Check the innermost scope for a cached landing pad. If this is
705 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
706 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
707 if (LP) return LP;
708
David Majnemerdbf10452015-07-31 17:58:45 +0000709 const EHPersonality &Personality = EHPersonality::get(*this);
710
711 if (!CurFn->hasPersonalityFn())
712 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
713
Reid Kleckner129552b2015-10-08 01:13:52 +0000714 if (Personality.usesFuncletPads()) {
715 // We don't need separate landing pads in the funclet model.
David Majnemerdbf10452015-07-31 17:58:45 +0000716 LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
717 } else {
718 // Build the landing pad for this scope.
719 LP = EmitLandingPad();
720 }
721
John McCallbd309292010-07-06 01:34:17 +0000722 assert(LP);
723
724 // Cache the landing pad on the innermost scope. If this is a
725 // non-EH scope, cache the landing pad on the enclosing scope, too.
726 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
727 ir->setCachedLandingPad(LP);
728 if (!isNonEHScope(*ir)) break;
729 }
730
731 return LP;
732}
733
734llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
735 assert(EHStack.requiresLandingPad());
736
John McCall8e4c74b2011-08-11 02:22:43 +0000737 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
738 switch (innermostEHScope.getKind()) {
739 case EHScope::Terminate:
740 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000741
Reid Kleckner2586aac2015-09-10 22:11:13 +0000742 case EHScope::PadEnd:
743 llvm_unreachable("PadEnd unnecessary for Itanium!");
David Majnemerdbf10452015-07-31 17:58:45 +0000744
John McCall8e4c74b2011-08-11 02:22:43 +0000745 case EHScope::Catch:
746 case EHScope::Cleanup:
747 case EHScope::Filter:
748 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
749 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000750 }
751
752 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000753 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantl95b24e92015-02-03 20:00:54 +0000754 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000755
756 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000757 llvm::BasicBlock *lpad = createBasicBlock("lpad");
758 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000759
Serge Guelton1d993272017-05-09 19:31:30 +0000760 llvm::LandingPadInst *LPadInst =
761 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +0000762
763 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
764 Builder.CreateStore(LPadExn, getExceptionSlot());
765 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
766 Builder.CreateStore(LPadSel, getEHSelectorSlot());
767
John McCallbd309292010-07-06 01:34:17 +0000768 // Save the exception pointer. It's safe to use a single exception
769 // pointer per function because EH cleanups can never have nested
770 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000771 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000772
773 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000774 bool hasCatchAll = false;
775 bool hasCleanup = false;
776 bool hasFilter = false;
777 SmallVector<llvm::Value*, 4> filterTypes;
778 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Nico Webere68b9f32015-02-25 16:25:00 +0000779 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
780 ++I) {
John McCallbd309292010-07-06 01:34:17 +0000781
782 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000783 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000784 // If we have a cleanup, remember that.
785 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000786 continue;
787
John McCallbd309292010-07-06 01:34:17 +0000788 case EHScope::Filter: {
789 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000790 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000791
Bill Wendlingf0724e82011-09-19 20:31:14 +0000792 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000793 EHFilterScope &filter = cast<EHFilterScope>(*I);
794 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000795
Bill Wendling8c4b7162011-09-22 20:32:54 +0000796 // Add all the filter values.
797 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
798 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000799 goto done;
800 }
801
802 case EHScope::Terminate:
803 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000804 assert(!hasCatchAll);
805 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000806 goto done;
807
808 case EHScope::Catch:
809 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000810
Reid Kleckner2586aac2015-09-10 22:11:13 +0000811 case EHScope::PadEnd:
812 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCallbd309292010-07-06 01:34:17 +0000813 }
814
John McCall8e4c74b2011-08-11 02:22:43 +0000815 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
816 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
817 EHCatchScope::Handler handler = catchScope.getHandler(hi);
Reid Kleckner10aa7702015-09-16 20:15:55 +0000818 assert(handler.Type.Flags == 0 &&
819 "landingpads do not support catch handler flags");
John McCallbd309292010-07-06 01:34:17 +0000820
John McCall8e4c74b2011-08-11 02:22:43 +0000821 // If this is a catch-all, register that and abort.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000822 if (!handler.Type.RTTI) {
John McCall8e4c74b2011-08-11 02:22:43 +0000823 assert(!hasCatchAll);
824 hasCatchAll = true;
825 goto done;
John McCallbd309292010-07-06 01:34:17 +0000826 }
827
828 // Check whether we already have a handler for this type.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000829 if (catchTypes.insert(handler.Type.RTTI).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000830 // If not, add it directly to the landingpad.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000831 LPadInst->addClause(handler.Type.RTTI);
John McCallbd309292010-07-06 01:34:17 +0000832 }
John McCallbd309292010-07-06 01:34:17 +0000833 }
834
835 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000836 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000837 assert(!(hasCatchAll && hasFilter));
838 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000839 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000840
841 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000842 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000843 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000844 // Create a filter expression: a constant array indicating which filter
845 // types there are. The personality routine only lands here if the filter
846 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000847 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000848 llvm::ArrayType *AType =
849 llvm::ArrayType::get(!filterTypes.empty() ?
850 filterTypes[0]->getType() : Int8PtrTy,
851 filterTypes.size());
852
853 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
854 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
855 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
856 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000857
858 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000859 if (hasCleanup)
860 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000861
862 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000863 } else if (hasCleanup) {
864 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000865 }
866
Bill Wendlingf0724e82011-09-19 20:31:14 +0000867 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
868 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000869
870 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000871 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000872
873 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000874 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000875
John McCall8e4c74b2011-08-11 02:22:43 +0000876 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000877}
878
David Majnemer4e52d6f2015-12-12 05:39:21 +0000879static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
David Majnemerdbf10452015-07-31 17:58:45 +0000880 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
881 assert(DispatchBlock);
882
883 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
884 CGF.EmitBlockAfterUses(DispatchBlock);
885
David Majnemer4e52d6f2015-12-12 05:39:21 +0000886 llvm::Value *ParentPad = CGF.CurrentFuncletPad;
887 if (!ParentPad)
888 ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
889 llvm::BasicBlock *UnwindBB =
890 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
891
892 unsigned NumHandlers = CatchScope.getNumHandlers();
893 llvm::CatchSwitchInst *CatchSwitch =
894 CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
David Majnemerdbf10452015-07-31 17:58:45 +0000895
896 // Test against each of the exception types we claim to catch.
David Majnemer4e52d6f2015-12-12 05:39:21 +0000897 for (unsigned I = 0; I < NumHandlers; ++I) {
David Majnemerdbf10452015-07-31 17:58:45 +0000898 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
899
Reid Kleckner10aa7702015-09-16 20:15:55 +0000900 CatchTypeInfo TypeInfo = Handler.Type;
901 if (!TypeInfo.RTTI)
902 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
David Majnemerdbf10452015-07-31 17:58:45 +0000903
David Majnemer4e52d6f2015-12-12 05:39:21 +0000904 CGF.Builder.SetInsertPoint(Handler.Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000905
906 if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000907 CGF.Builder.CreateCatchPad(
908 CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
909 llvm::Constant::getNullValue(CGF.VoidPtrTy)});
David Majnemerdbf10452015-07-31 17:58:45 +0000910 } else {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000911 CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
David Majnemerdbf10452015-07-31 17:58:45 +0000912 }
913
David Majnemer4e52d6f2015-12-12 05:39:21 +0000914 CatchSwitch->addHandler(Handler.Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000915 }
916 CGF.Builder.restoreIP(SavedIP);
David Majnemerdbf10452015-07-31 17:58:45 +0000917}
918
John McCall8e4c74b2011-08-11 02:22:43 +0000919/// Emit the structure of the dispatch block for the given catch scope.
920/// It is an invariant that the dispatch block already exists.
David Majnemer4e52d6f2015-12-12 05:39:21 +0000921static void emitCatchDispatchBlock(CodeGenFunction &CGF,
922 EHCatchScope &catchScope) {
Reid Kleckner129552b2015-10-08 01:13:52 +0000923 if (EHPersonality::get(CGF).usesFuncletPads())
924 return emitCatchPadBlock(CGF, catchScope);
David Majnemerdbf10452015-07-31 17:58:45 +0000925
John McCall8e4c74b2011-08-11 02:22:43 +0000926 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
927 assert(dispatchBlock);
928
929 // If there's only a single catch-all, getEHDispatchBlock returned
930 // that catch-all as the dispatch block.
931 if (catchScope.getNumHandlers() == 1 &&
932 catchScope.getHandler(0).isCatchAll()) {
933 assert(dispatchBlock == catchScope.getHandler(0).Block);
David Majnemer4e52d6f2015-12-12 05:39:21 +0000934 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000935 }
936
937 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
938 CGF.EmitBlockAfterUses(dispatchBlock);
939
940 // Select the right handler.
941 llvm::Value *llvm_eh_typeid_for =
942 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
943
944 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000945 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000946
947 // Test against each of the exception types we claim to catch.
948 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
949 assert(i < e && "ran off end of handlers!");
950 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
951
Reid Kleckner10aa7702015-09-16 20:15:55 +0000952 llvm::Value *typeValue = handler.Type.RTTI;
953 assert(handler.Type.Flags == 0 &&
954 "landingpads do not support catch handler flags");
John McCall8e4c74b2011-08-11 02:22:43 +0000955 assert(typeValue && "fell into catch-all case!");
956 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
957
958 // Figure out the next block.
959 bool nextIsEnd;
960 llvm::BasicBlock *nextBlock;
961
962 // If this is the last handler, we're at the end, and the next
963 // block is the block for the enclosing EH scope.
964 if (i + 1 == e) {
965 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
966 nextIsEnd = true;
967
968 // If the next handler is a catch-all, we're at the end, and the
969 // next block is that handler.
970 } else if (catchScope.getHandler(i+1).isCatchAll()) {
971 nextBlock = catchScope.getHandler(i+1).Block;
972 nextIsEnd = true;
973
974 // Otherwise, we're not at the end and we need a new block.
975 } else {
976 nextBlock = CGF.createBasicBlock("catch.fallthrough");
977 nextIsEnd = false;
978 }
979
980 // Figure out the catch type's index in the LSDA's type table.
981 llvm::CallInst *typeIndex =
982 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
983 typeIndex->setDoesNotThrow();
984
985 llvm::Value *matchesTypeIndex =
986 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
987 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
988
989 // If the next handler is a catch-all, we're completely done.
990 if (nextIsEnd) {
991 CGF.Builder.restoreIP(savedIP);
David Majnemer4e52d6f2015-12-12 05:39:21 +0000992 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000993 }
Ahmed Charles289896d2012-02-19 11:57:29 +0000994 // Otherwise we need to emit and continue at that block.
995 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +0000996 }
John McCall8e4c74b2011-08-11 02:22:43 +0000997}
998
999void CodeGenFunction::popCatchScope() {
1000 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1001 if (catchScope.hasEHBranches())
1002 emitCatchDispatchBlock(*this, catchScope);
1003 EHStack.popCatch();
1004}
1005
John McCallb609d3f2010-07-07 06:56:46 +00001006void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001007 unsigned NumHandlers = S.getNumHandlers();
1008 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1009 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001010
John McCall8e4c74b2011-08-11 02:22:43 +00001011 // If the catch was not required, bail out now.
1012 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001013 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001014 EHStack.popCatch();
1015 return;
1016 }
1017
1018 // Emit the structure of the EH dispatch for this catch.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001019 emitCatchDispatchBlock(*this, CatchScope);
John McCall8e4c74b2011-08-11 02:22:43 +00001020
John McCallbd309292010-07-06 01:34:17 +00001021 // Copy the handler blocks off before we pop the EH stack. Emitting
1022 // the handlers might scribble on this memory.
Benjamin Kramerda32cf82015-08-04 15:38:49 +00001023 SmallVector<EHCatchScope::Handler, 8> Handlers(
1024 CatchScope.begin(), CatchScope.begin() + NumHandlers);
John McCall8e4c74b2011-08-11 02:22:43 +00001025
John McCallbd309292010-07-06 01:34:17 +00001026 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001027
John McCallbd309292010-07-06 01:34:17 +00001028 // The fall-through block.
1029 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001030
John McCallbd309292010-07-06 01:34:17 +00001031 // We just emitted the body of the try; jump to the continue block.
1032 if (HaveInsertPoint())
1033 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001034
John McCalld8d00be2012-06-15 05:27:05 +00001035 // Determine if we need an implicit rethrow for all these catch handlers;
1036 // see the comment below.
1037 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001038 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001039 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1040 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001041
John McCall8e4c74b2011-08-11 02:22:43 +00001042 // Perversely, we emit the handlers backwards precisely because we
1043 // want them to appear in source order. In all of these cases, the
1044 // catch block will have exactly one predecessor, which will be a
1045 // particular block in the catch dispatch. However, in the case of
1046 // a catch-all, one of the dispatch blocks will branch to two
1047 // different handlers, and EmitBlockAfterUses will cause the second
1048 // handler to be moved before the first.
1049 for (unsigned I = NumHandlers; I != 0; --I) {
1050 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1051 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001052
John McCallbd309292010-07-06 01:34:17 +00001053 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001054 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001055
John McCallbd309292010-07-06 01:34:17 +00001056 // Enter a cleanup scope, including the catch variable and the
1057 // end-catch.
1058 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001059
John McCallbd309292010-07-06 01:34:17 +00001060 // Initialize the catch variable and set up the cleanups.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001061 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1062 CurrentFuncletPad);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001063 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallbd309292010-07-06 01:34:17 +00001064
Justin Bognerea278c32014-01-07 00:20:28 +00001065 // Emit the PGO counter increment.
Justin Bogner66242d62015-04-23 23:06:47 +00001066 incrementProfileCounter(C);
Justin Bogneref512b92014-01-06 22:27:43 +00001067
John McCallbd309292010-07-06 01:34:17 +00001068 // Perform the body of the catch.
1069 EmitStmt(C->getHandlerBlock());
1070
John McCalld8d00be2012-06-15 05:27:05 +00001071 // [except.handle]p11:
1072 // The currently handled exception is rethrown if control
1073 // reaches the end of a handler of the function-try-block of a
1074 // constructor or destructor.
1075
1076 // It is important that we only do this on fallthrough and not on
1077 // return. Note that it's illegal to put a return in a
1078 // constructor function-try-block's catch handler (p14), so this
1079 // really only applies to destructors.
1080 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +00001081 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +00001082 Builder.CreateUnreachable();
1083 Builder.ClearInsertionPoint();
1084 }
1085
John McCallbd309292010-07-06 01:34:17 +00001086 // Fall out through the catch cleanups.
1087 CatchScope.ForceCleanup();
1088
1089 // Branch out of the try.
1090 if (HaveInsertPoint())
1091 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001092 }
1093
John McCallbd309292010-07-06 01:34:17 +00001094 EmitBlock(ContBB);
Justin Bogner66242d62015-04-23 23:06:47 +00001095 incrementProfileCounter(&S);
Mike Stump58ef18b2009-11-20 23:44:51 +00001096}
Mike Stumpaff69af2009-12-09 03:35:49 +00001097
John McCall1e670402010-07-21 00:52:03 +00001098namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001099 struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001100 llvm::Value *ForEHVar;
1101 llvm::Value *EndCatchFn;
1102 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1103 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1104
Craig Topper4f12f102014-03-12 06:41:41 +00001105 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001106 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1107 llvm::BasicBlock *CleanupContBB =
1108 CGF.createBasicBlock("finally.cleanup.cont");
1109
1110 llvm::Value *ShouldEndCatch =
John McCall7f416cc2015-09-08 08:05:57 +00001111 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
John McCall1e670402010-07-21 00:52:03 +00001112 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1113 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001114 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001115 CGF.EmitBlock(CleanupContBB);
1116 }
1117 };
John McCall906da4b2010-07-21 05:47:49 +00001118
David Blaikie7e70d682015-08-18 22:40:54 +00001119 struct PerformFinally final : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001120 const Stmt *Body;
1121 llvm::Value *ForEHVar;
1122 llvm::Value *EndCatchFn;
1123 llvm::Value *RethrowFn;
1124 llvm::Value *SavedExnVar;
1125
1126 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1127 llvm::Value *EndCatchFn,
1128 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1129 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1130 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1131
Craig Topper4f12f102014-03-12 06:41:41 +00001132 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001133 // Enter a cleanup to call the end-catch function if one was provided.
1134 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001135 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1136 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001137
John McCallcebe0ca2010-08-11 00:16:14 +00001138 // Save the current cleanup destination in case there are
1139 // cleanups in the finally block.
1140 llvm::Value *SavedCleanupDest =
1141 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1142 "cleanup.dest.saved");
1143
John McCall906da4b2010-07-21 05:47:49 +00001144 // Emit the finally block.
1145 CGF.EmitStmt(Body);
1146
1147 // If the end of the finally is reachable, check whether this was
1148 // for EH. If so, rethrow.
1149 if (CGF.HaveInsertPoint()) {
1150 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1151 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1152
1153 llvm::Value *ShouldRethrow =
John McCall7f416cc2015-09-08 08:05:57 +00001154 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
John McCall906da4b2010-07-21 05:47:49 +00001155 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1156
1157 CGF.EmitBlock(RethrowBB);
1158 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001159 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
John McCall7f416cc2015-09-08 08:05:57 +00001160 CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
John McCall906da4b2010-07-21 05:47:49 +00001161 } else {
John McCall882987f2013-02-28 19:01:20 +00001162 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001163 }
1164 CGF.Builder.CreateUnreachable();
1165
1166 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001167
1168 // Restore the cleanup destination.
1169 CGF.Builder.CreateStore(SavedCleanupDest,
1170 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001171 }
1172
1173 // Leave the end-catch cleanup. As an optimization, pretend that
1174 // the fallthrough path was inaccessible; we've dynamically proven
1175 // that we're not in the EH case along that path.
1176 if (EndCatchFn) {
1177 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1178 CGF.PopCleanupBlock();
1179 CGF.Builder.restoreIP(SavedIP);
1180 }
1181
1182 // Now make sure we actually have an insertion point or the
1183 // cleanup gods will hate us.
1184 CGF.EnsureInsertPoint();
1185 }
1186 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001187} // end anonymous namespace
John McCall1e670402010-07-21 00:52:03 +00001188
John McCallbd309292010-07-06 01:34:17 +00001189/// Enters a finally block for an implementation using zero-cost
1190/// exceptions. This is mostly general, but hard-codes some
1191/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001192void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1193 const Stmt *body,
1194 llvm::Constant *beginCatchFn,
1195 llvm::Constant *endCatchFn,
1196 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001197 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001198 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001199 assert(rethrowFn && "rethrow function is required");
1200
1201 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001202
John McCallbd309292010-07-06 01:34:17 +00001203 // The rethrow function has one of the following two types:
1204 // void (*)()
1205 // void (*)(void*)
1206 // In the latter case we need to pass it the exception object.
1207 // But we can't use the exception slot because the @finally might
1208 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001209 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001210 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001211 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001212 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001213 if (rethrowFnTy->getNumParams())
1214 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001215
John McCallbd309292010-07-06 01:34:17 +00001216 // A finally block is a statement which must be executed on any edge
1217 // out of a given scope. Unlike a cleanup, the finally block may
1218 // contain arbitrary control flow leading out of itself. In
1219 // addition, finally blocks should always be executed, even if there
1220 // are no catch handlers higher on the stack. Therefore, we
1221 // surround the protected scope with a combination of a normal
1222 // cleanup (to catch attempts to break out of the block via normal
1223 // control flow) and an EH catch-all (semantically "outside" any try
1224 // statement to which the finally block might have been attached).
1225 // The finally block itself is generated in the context of a cleanup
1226 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001227
John McCallbd309292010-07-06 01:34:17 +00001228 // Jump destination for performing the finally block on an exception
1229 // edge. We'll never actually reach this block, so unreachable is
1230 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001231 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001232
John McCallbd309292010-07-06 01:34:17 +00001233 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001234 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
John McCall7f416cc2015-09-08 08:05:57 +00001235 CGF.Builder.CreateFlagStore(false, ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001236
John McCallbd309292010-07-06 01:34:17 +00001237 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001238 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1239 ForEHVar, endCatchFn,
1240 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001241
1242 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001243 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1244 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1245 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001246}
1247
John McCall6b0feb72011-06-22 02:32:12 +00001248void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001249 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001250 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1251 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001252
1253 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001254
John McCall6b0feb72011-06-22 02:32:12 +00001255 // If there are any references to the catch-all block, emit it.
1256 if (catchBB->use_empty()) {
1257 delete catchBB;
1258 } else {
1259 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1260 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001261
Craig Topper8a13c412014-05-21 05:09:00 +00001262 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001263
John McCall6b0feb72011-06-22 02:32:12 +00001264 // If there's a begin-catch function, call it.
1265 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001266 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001267 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001268 }
1269
1270 // If we need to remember the exception pointer to rethrow later, do so.
1271 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001272 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall7f416cc2015-09-08 08:05:57 +00001273 CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
John McCall6b0feb72011-06-22 02:32:12 +00001274 }
1275
1276 // Tell the cleanups in the finally block that we're do this for EH.
John McCall7f416cc2015-09-08 08:05:57 +00001277 CGF.Builder.CreateFlagStore(true, ForEHVar);
John McCall6b0feb72011-06-22 02:32:12 +00001278
1279 // Thread a jump through the finally cleanup.
1280 CGF.EmitBranchThroughCleanup(RethrowDest);
1281
1282 CGF.Builder.restoreIP(savedIP);
1283 }
1284
1285 // Finally, leave the @finally cleanup.
1286 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001287}
1288
1289llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1290 if (TerminateLandingPad)
1291 return TerminateLandingPad;
1292
1293 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1294
1295 // This will get inserted at the end of the function.
1296 TerminateLandingPad = createBasicBlock("terminate.lpad");
1297 Builder.SetInsertPoint(TerminateLandingPad);
1298
1299 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001300 const EHPersonality &Personality = EHPersonality::get(*this);
David Majnemerfcbdb6e2015-06-17 20:53:19 +00001301
1302 if (!CurFn->hasPersonalityFn())
1303 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1304
Serge Guelton1d993272017-05-09 19:31:30 +00001305 llvm::LandingPadInst *LPadInst =
1306 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001307 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001308
Hans Wennborgdcfba332015-10-06 23:40:43 +00001309 llvm::Value *Exn = nullptr;
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001310 if (getLangOpts().CPlusPlus)
1311 Exn = Builder.CreateExtractValue(LPadInst, 0);
1312 llvm::CallInst *terminateCall =
1313 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCalle142ad52013-02-12 03:51:46 +00001314 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001315 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001316
John McCallbd309292010-07-06 01:34:17 +00001317 // Restore the saved insertion state.
1318 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001319
John McCallbd309292010-07-06 01:34:17 +00001320 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001321}
Mike Stump2b488872009-12-09 22:59:31 +00001322
1323llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001324 if (TerminateHandler)
1325 return TerminateHandler;
1326
John McCallbd309292010-07-06 01:34:17 +00001327 // Set up the terminate handler. This block is inserted at the very
1328 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001329 TerminateHandler = createBasicBlock("terminate.handler");
Reid Kleckner06f19a02018-01-02 21:34:16 +00001330 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
John McCallbd309292010-07-06 01:34:17 +00001331 Builder.SetInsertPoint(TerminateHandler);
Reid Kleckner06f19a02018-01-02 21:34:16 +00001332
David Majnemerfeeefb22015-12-14 18:34:18 +00001333 llvm::Value *Exn = nullptr;
Reid Kleckner06f19a02018-01-02 21:34:16 +00001334 if (getLangOpts().CPlusPlus)
1335 Exn = getExceptionFromSlot();
David Majnemerfeeefb22015-12-14 18:34:18 +00001336 llvm::CallInst *terminateCall =
1337 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1338 terminateCall->setDoesNotReturn();
1339 Builder.CreateUnreachable();
Mike Stump2b488872009-12-09 22:59:31 +00001340
John McCall21886962010-04-21 10:05:39 +00001341 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001342 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001343
Mike Stump2b488872009-12-09 22:59:31 +00001344 return TerminateHandler;
1345}
John McCallbd309292010-07-06 01:34:17 +00001346
Reid Kleckner06f19a02018-01-02 21:34:16 +00001347llvm::BasicBlock *CodeGenFunction::getTerminateFunclet() {
1348 assert(EHPersonality::get(*this).usesFuncletPads() &&
1349 "use getTerminateLandingPad for non-funclet EH");
1350
1351 llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
1352 if (TerminateFunclet)
1353 return TerminateFunclet;
1354
1355 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1356
1357 // Set up the terminate handler. This block is inserted at the very
1358 // end of the function by FinishFunction.
1359 TerminateFunclet = createBasicBlock("terminate.handler");
1360 Builder.SetInsertPoint(TerminateFunclet);
1361
1362 // Create the cleanuppad using the current parent pad as its token. Use 'none'
1363 // if this is a top-level terminate scope, which is the common case.
1364 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1365 CurrentFuncletPad);
1366 llvm::Value *ParentPad = CurrentFuncletPad;
1367 if (!ParentPad)
1368 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1369 CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1370
1371 // Emit the __std_terminate call.
1372 llvm::CallInst *terminateCall =
1373 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, nullptr);
1374 terminateCall->setDoesNotReturn();
1375 Builder.CreateUnreachable();
1376
1377 // Restore the saved insertion state.
1378 Builder.restoreIP(SavedIP);
1379
1380 return TerminateFunclet;
1381}
1382
David Chisnall9a837be2012-11-07 16:50:40 +00001383llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001384 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001385
1386 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1387
1388 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001389 EHResumeBlock = createBasicBlock("eh.resume");
1390 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001391
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001392 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001393
1394 // This can always be a call because we necessarily didn't find
1395 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001396 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001397 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001398 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Nico Weberff62a6a2015-02-26 22:34:33 +00001399 getExceptionFromSlot())->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001400 Builder.CreateUnreachable();
1401 Builder.restoreIP(SavedIP);
1402 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001403 }
1404
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001405 // Recreate the landingpad's return value for the 'resume' instruction.
1406 llvm::Value *Exn = getExceptionFromSlot();
1407 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001408
Serge Guelton1d993272017-05-09 19:31:30 +00001409 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001410 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1411 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1412 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1413
1414 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001415 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001416 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001417}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001418
1419void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001420 EnterSEHTryStmt(S);
Reid Klecknera5930002015-02-11 21:40:48 +00001421 {
Nico Weber5779f842015-02-12 23:16:11 +00001422 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
Nico Weber5779f842015-02-12 23:16:11 +00001423
Reid Kleckner11c033e2015-02-12 23:40:45 +00001424 SEHTryEpilogueStack.push_back(&TryExit);
Reid Klecknera5930002015-02-11 21:40:48 +00001425 EmitStmt(S.getTryBlock());
Reid Kleckner11c033e2015-02-12 23:40:45 +00001426 SEHTryEpilogueStack.pop_back();
Nico Weber5779f842015-02-12 23:16:11 +00001427
1428 if (!TryExit.getBlock()->use_empty())
1429 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1430 else
1431 delete TryExit.getBlock();
Reid Klecknera5930002015-02-11 21:40:48 +00001432 }
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001433 ExitSEHTryStmt(S);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001434}
1435
1436namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001437struct PerformSEHFinally final : EHScopeStack::Cleanup {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001438 llvm::Function *OutlinedFinally;
Reid Kleckner55391522015-10-08 21:14:56 +00001439 PerformSEHFinally(llvm::Function *OutlinedFinally)
1440 : OutlinedFinally(OutlinedFinally) {}
Reid Kleckneraca01db2015-02-04 22:37:07 +00001441
Reid Kleckner1d59f992015-01-22 01:36:17 +00001442 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001443 ASTContext &Context = CGF.getContext();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001444 CodeGenModule &CGM = CGF.CGM;
Reid Kleckner65870442015-06-09 17:47:50 +00001445
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001446 CallArgList Args;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001447
1448 // Compute the two argument values.
1449 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
Reid Kleckner15d152d2015-07-07 23:23:31 +00001450 llvm::Value *LocalAddrFn = CGM.getIntrinsic(llvm::Intrinsic::localaddress);
David Blaikie4ba525b2015-07-14 17:27:39 +00001451 llvm::Value *FP = CGF.Builder.CreateCall(LocalAddrFn);
Reid Klecknereb11c412015-07-01 21:00:00 +00001452 llvm::Value *IsForEH =
1453 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1454 Args.add(RValue::get(IsForEH), ArgTys[0]);
1455 Args.add(RValue::get(FP), ArgTys[1]);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001456
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001457 // Arrange a two-arg function info and type.
Reid Klecknereb11c412015-07-01 21:00:00 +00001458 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001459 CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001460
John McCallb92ab1a2016-10-26 23:46:34 +00001461 auto Callee = CGCallee::forDirect(OutlinedFinally);
1462 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001463 }
1464};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001465} // end anonymous namespace
Reid Kleckner1d59f992015-01-22 01:36:17 +00001466
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001467namespace {
1468/// Find all local variable captures in the statement.
1469struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1470 CodeGenFunction &ParentCGF;
1471 const VarDecl *ParentThis;
John McCall0a490152015-09-08 21:15:22 +00001472 llvm::SmallSetVector<const VarDecl *, 4> Captures;
John McCall7f416cc2015-09-08 08:05:57 +00001473 Address SEHCodeSlot = Address::invalid();
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001474 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1475 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1476
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001477 // Return true if we need to do any capturing work.
1478 bool foundCaptures() {
John McCall7f416cc2015-09-08 08:05:57 +00001479 return !Captures.empty() || SEHCodeSlot.isValid();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001480 }
1481
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001482 void Visit(const Stmt *S) {
1483 // See if this is a capture, then recurse.
1484 ConstStmtVisitor<CaptureFinder>::Visit(S);
1485 for (const Stmt *Child : S->children())
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001486 if (Child)
1487 Visit(Child);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001488 }
1489
1490 void VisitDeclRefExpr(const DeclRefExpr *E) {
1491 // If this is already a capture, just make sure we capture 'this'.
1492 if (E->refersToEnclosingVariableOrCapture()) {
John McCall0a490152015-09-08 21:15:22 +00001493 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001494 return;
1495 }
1496
1497 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1498 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
John McCall0a490152015-09-08 21:15:22 +00001499 Captures.insert(D);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001500 }
1501
1502 void VisitCXXThisExpr(const CXXThisExpr *E) {
John McCall0a490152015-09-08 21:15:22 +00001503 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001504 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001505
1506 void VisitCallExpr(const CallExpr *E) {
1507 // We only need to add parent frame allocations for these builtins in x86.
1508 if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1509 return;
1510
1511 unsigned ID = E->getBuiltinCallee();
1512 switch (ID) {
1513 case Builtin::BI__exception_code:
1514 case Builtin::BI_exception_code:
1515 // This is the simple case where we are the outermost finally. All we
1516 // have to do here is make sure we escape this and recover it in the
1517 // outlined handler.
John McCall7f416cc2015-09-08 08:05:57 +00001518 if (!SEHCodeSlot.isValid())
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001519 SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1520 break;
1521 }
1522 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001523};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001524} // end anonymous namespace
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001525
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001526Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
1527 Address ParentVar,
1528 llvm::Value *ParentFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001529 llvm::CallInst *RecoverCall = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00001530 CGBuilderTy Builder(*this, AllocaInsertPt);
1531 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001532 // Mark the variable escaped if nobody else referenced it and compute the
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001533 // localescape index.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001534 auto InsertPair = ParentCGF.EscapedLocals.insert(
1535 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1536 int FrameEscapeIdx = InsertPair.first->second;
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001537 // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001538 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001539 &CGM.getModule(), llvm::Intrinsic::localrecover);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001540 llvm::Constant *ParentI8Fn =
1541 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1542 RecoverCall = Builder.CreateCall(
1543 FrameRecoverFn, {ParentI8Fn, ParentFP,
1544 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1545
1546 } else {
1547 // If the parent didn't have an alloca, we're doing some nested outlining.
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001548 // Just clone the existing localrecover call, but tweak the FP argument to
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001549 // use our FP value. All other arguments are constants.
1550 auto *ParentRecover =
John McCall7f416cc2015-09-08 08:05:57 +00001551 cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001552 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1553 "expected alloca or localrecover in parent LocalDeclMap");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001554 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1555 RecoverCall->setArgOperand(1, ParentFP);
1556 RecoverCall->insertBefore(AllocaInsertPt);
1557 }
1558
1559 // Bitcast the variable, rename it, and insert it in the local decl map.
1560 llvm::Value *ChildVar =
John McCall7f416cc2015-09-08 08:05:57 +00001561 Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1562 ChildVar->setName(ParentVar.getName());
1563 return Address(ChildVar, ParentVar.getAlignment());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001564}
1565
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001566void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
Reid Kleckner0b9bbbf2015-06-09 17:49:42 +00001567 const Stmt *OutlinedStmt,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001568 bool IsFilter) {
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001569 // Find all captures in the Stmt.
1570 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1571 Finder.Visit(OutlinedStmt);
1572
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001573 // We can exit early on x86_64 when there are no captures. We just have to
1574 // save the exception code in filters so that __exception_code() works.
1575 if (!Finder.foundCaptures() &&
1576 CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1577 if (IsFilter)
1578 EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001579 return;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001580 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001581
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001582 llvm::Value *EntryFP = nullptr;
1583 CGBuilderTy Builder(CGM, AllocaInsertPt);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001584 if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1585 // 32-bit SEH filters need to be careful about FP recovery. The end of the
1586 // EH registration is passed in as the EBP physical register. We can
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001587 // recover that with llvm.frameaddress(1).
1588 EntryFP = Builder.CreateCall(
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001589 CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001590 } else {
1591 // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1592 // second parameter.
1593 auto AI = CurFn->arg_begin();
1594 ++AI;
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001595 EntryFP = &*AI;
1596 }
1597
1598 llvm::Value *ParentFP = EntryFP;
1599 if (IsFilter) {
1600 // Given whatever FP the runtime provided us in EntryFP, recover the true
1601 // frame pointer of the parent function. We only need to do this in filters,
1602 // since finally funclets recover the parent FP for us.
1603 llvm::Function *RecoverFPIntrin =
1604 CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
1605 llvm::Constant *ParentI8Fn =
1606 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1607 ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001608 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001609
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001610 // Create llvm.localrecover calls for all captures.
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001611 for (const VarDecl *VD : Finder.Captures) {
1612 if (isa<ImplicitParamDecl>(VD)) {
1613 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1614 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1615 continue;
1616 }
1617 if (VD->getType()->isVariablyModifiedType()) {
1618 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1619 continue;
1620 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001621 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1622 "captured non-local variable");
1623
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001624 // If this decl hasn't been declared yet, it will be declared in the
1625 // OutlinedStmt.
1626 auto I = ParentCGF.LocalDeclMap.find(VD);
1627 if (I == ParentCGF.LocalDeclMap.end())
1628 continue;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001629
John McCall7f416cc2015-09-08 08:05:57 +00001630 Address ParentVar = I->second;
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001631 setAddrOfLocalVar(
1632 VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
Nico Webere4f974c2015-07-02 06:10:53 +00001633 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001634
John McCall7f416cc2015-09-08 08:05:57 +00001635 if (Finder.SEHCodeSlot.isValid()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001636 SEHCodeSlotStack.push_back(
1637 recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1638 }
1639
1640 if (IsFilter)
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001641 EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001642}
1643
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001644/// Arrange a function prototype that can be called by Windows exception
1645/// handling personalities. On Win64, the prototype looks like:
1646/// RetTy func(void *EHPtrs, void *ParentFP);
1647void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001648 bool IsFilter,
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001649 const Stmt *OutlinedStmt) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001650 SourceLocation StartLoc = OutlinedStmt->getLocStart();
1651
1652 // Get the mangled function name.
1653 SmallString<128> Name;
1654 {
1655 llvm::raw_svector_ostream OS(Name);
David Majnemer25eb1652016-03-01 19:42:53 +00001656 const FunctionDecl *ParentSEHFn = ParentCGF.CurSEHParent;
1657 assert(ParentSEHFn && "No CurSEHParent!");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001658 MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1659 if (IsFilter)
David Majnemer25eb1652016-03-01 19:42:53 +00001660 Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001661 else
David Majnemer25eb1652016-03-01 19:42:53 +00001662 Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001663 }
1664
1665 FunctionArgList Args;
1666 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1667 // All SEH finally functions take two parameters. Win64 filters take two
1668 // parameters. Win32 filters take no parameters.
1669 if (IsFilter) {
1670 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001671 getContext(), /*DC=*/nullptr, StartLoc,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001672 &getContext().Idents.get("exception_pointers"),
Alexey Bataev56223232017-06-09 13:40:18 +00001673 getContext().VoidPtrTy, ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001674 } else {
1675 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001676 getContext(), /*DC=*/nullptr, StartLoc,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001677 &getContext().Idents.get("abnormal_termination"),
Alexey Bataev56223232017-06-09 13:40:18 +00001678 getContext().UnsignedCharTy, ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001679 }
1680 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001681 getContext(), /*DC=*/nullptr, StartLoc,
1682 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
1683 ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001684 }
1685
1686 QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1687
John McCallc56a8b32016-03-11 04:30:31 +00001688 const CGFunctionInfo &FnInfo =
1689 CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001690
Reid Kleckner1d59f992015-01-22 01:36:17 +00001691 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001692 llvm::Function *Fn = llvm::Function::Create(
1693 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001694
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001695 IsOutlinedSEHHelper = true;
Nico Weberf2a39a72015-04-13 20:03:03 +00001696
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001697 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1698 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
David Majnemer25eb1652016-03-01 19:42:53 +00001699 CurSEHParent = ParentCGF.CurSEHParent;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001700
1701 CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001702 EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001703}
1704
1705/// Create a stub filter function that will ultimately hold the code of the
1706/// filter expression. The EH preparation passes in LLVM will outline the code
1707/// from the main function body into this stub.
1708llvm::Function *
1709CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1710 const SEHExceptStmt &Except) {
1711 const Expr *FilterExpr = Except.getFilterExpr();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001712 startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001713
1714 // Emit the original filter expression, convert to i32, and return.
1715 llvm::Value *R = EmitScalarExpr(FilterExpr);
David Majnemer2ccba832015-04-17 06:57:25 +00001716 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
Reid Kleckner1d59f992015-01-22 01:36:17 +00001717 FilterExpr->getType()->isSignedIntegerType());
1718 Builder.CreateStore(R, ReturnValue);
1719
1720 FinishFunction(FilterExpr->getLocEnd());
1721
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001722 return CurFn;
1723}
1724
1725llvm::Function *
1726CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1727 const SEHFinallyStmt &Finally) {
1728 const Stmt *FinallyBlock = Finally.getBlock();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001729 startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001730
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001731 // Emit the original filter expression, convert to i32, and return.
1732 EmitStmt(FinallyBlock);
1733
1734 FinishFunction(FinallyBlock->getLocEnd());
1735
1736 return CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001737}
1738
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001739void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1740 llvm::Value *ParentFP,
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001741 llvm::Value *EntryFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001742 // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1743 // __exception_info intrinsic.
1744 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1745 // On Win64, the info is passed as the first parameter to the filter.
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001746 SEHInfo = &*CurFn->arg_begin();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001747 SEHCodeSlotStack.push_back(
1748 CreateMemTemp(getContext().IntTy, "__exception_code"));
1749 } else {
1750 // On Win32, the EBP on entry to the filter points to the end of an
1751 // exception registration object. It contains 6 32-bit fields, and the info
1752 // pointer is stored in the second field. So, GEP 20 bytes backwards and
1753 // load the pointer.
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001754 SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001755 SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001756 SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001757 SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1758 ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1759 }
1760
Reid Kleckner1d59f992015-01-22 01:36:17 +00001761 // Save the exception code in the exception slot to unify exception access in
1762 // the filter function and the landing pad.
1763 // struct EXCEPTION_POINTERS {
1764 // EXCEPTION_RECORD *ExceptionRecord;
1765 // CONTEXT *ContextRecord;
1766 // };
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001767 // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001768 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
Serge Guelton1d993272017-05-09 19:31:30 +00001769 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001770 llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
David Blaikie1ed728c2015-04-05 22:45:47 +00001771 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001772 Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
1773 llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001774 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1775 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001776}
1777
1778llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1779 // Sema should diagnose calling this builtin outside of a filter context, but
1780 // don't crash if we screw up.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001781 if (!SEHInfo)
Reid Kleckner1d59f992015-01-22 01:36:17 +00001782 return llvm::UndefValue::get(Int8PtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001783 assert(SEHInfo->getType() == Int8PtrTy);
1784 return SEHInfo;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001785}
1786
1787llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001788 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
John McCall7f416cc2015-09-08 08:05:57 +00001789 return Builder.CreateLoad(SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001790}
1791
Reid Kleckneraca01db2015-02-04 22:37:07 +00001792llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001793 // Abnormal termination is just the first parameter to the outlined finally
1794 // helper.
1795 auto AI = CurFn->arg_begin();
1796 return Builder.CreateZExt(&*AI, Int32Ty);
Reid Kleckneraca01db2015-02-04 22:37:07 +00001797}
1798
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001799void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1800 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1801 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001802 // Outline the finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001803 llvm::Function *FinallyFunc =
1804 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001805
1806 // Push a cleanup for __finally blocks.
Reid Kleckner55391522015-10-08 21:14:56 +00001807 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001808 return;
1809 }
1810
1811 // Otherwise, we must have an __except block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001812 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001813 assert(Except);
1814 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001815 SEHCodeSlotStack.push_back(
1816 CreateMemTemp(getContext().IntTy, "__exception_code"));
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001817
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001818 // If the filter is known to evaluate to 1, then we can use the clause
1819 // "catch i8* null". We can't do this on x86 because the filter has to save
1820 // the exception code.
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001821 llvm::Constant *C =
John McCallde0fe072017-08-15 21:42:52 +00001822 ConstantEmitter(*this).tryEmitAbstract(Except->getFilterExpr(),
1823 getContext().IntTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001824 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
1825 C->isOneValue()) {
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001826 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1827 return;
1828 }
1829
1830 // In general, we have to emit an outlined filter function. Use the function
1831 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00001832 llvm::Function *FilterFunc =
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001833 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001834 llvm::Constant *OpaqueFunc =
1835 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
Reid Kleckner8be18472015-09-16 21:06:09 +00001836 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
Reid Kleckner1d59f992015-01-22 01:36:17 +00001837}
1838
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001839void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001840 // Just pop the cleanup if it's a __finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001841 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001842 PopCleanupBlock();
1843 return;
1844 }
1845
1846 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001847 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001848 assert(Except && "__try must have __finally xor __except");
1849 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1850
1851 // Don't emit the __except block if the __try block lacked invokes.
1852 // TODO: Model unwind edges from instructions, either with iload / istore or
1853 // a try body function.
1854 if (!CatchScope.hasEHBranches()) {
1855 CatchScope.clearHandlerBlocks();
1856 EHStack.popCatch();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001857 SEHCodeSlotStack.pop_back();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001858 return;
1859 }
1860
1861 // The fall-through block.
1862 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1863
1864 // We just emitted the body of the __try; jump to the continue block.
1865 if (HaveInsertPoint())
1866 Builder.CreateBr(ContBB);
1867
1868 // Check if our filter function returned true.
1869 emitCatchDispatchBlock(*this, CatchScope);
1870
1871 // Grab the block before we pop the handler.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001872 llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001873 EHStack.popCatch();
1874
David Majnemer4e52d6f2015-12-12 05:39:21 +00001875 EmitBlockAfterUses(CatchPadBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001876
Reid Kleckner129552b2015-10-08 01:13:52 +00001877 // __except blocks don't get outlined into funclets, so immediately do a
1878 // catchret.
Reid Kleckner129552b2015-10-08 01:13:52 +00001879 llvm::CatchPadInst *CPI =
1880 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
David Majnemer4e52d6f2015-12-12 05:39:21 +00001881 llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
Reid Kleckner129552b2015-10-08 01:13:52 +00001882 Builder.CreateCatchRet(CPI, ExceptBB);
1883 EmitBlock(ExceptBB);
1884
1885 // On Win64, the exception code is returned in EAX. Copy it into the slot.
1886 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1887 llvm::Function *SEHCodeIntrin =
1888 CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
1889 llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
1890 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001891 }
1892
Reid Kleckner1d59f992015-01-22 01:36:17 +00001893 // Emit the __except body.
1894 EmitStmt(Except->getBlock());
1895
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001896 // End the lifetime of the exception code.
1897 SEHCodeSlotStack.pop_back();
1898
Reid Kleckner3a417c32015-01-30 22:16:45 +00001899 if (HaveInsertPoint())
1900 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001901
1902 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00001903}
Nico Weber9b982072014-07-07 00:12:30 +00001904
1905void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00001906 // If this code is reachable then emit a stop point (if generating
1907 // debug info). We have to do this ourselves because we are on the
1908 // "simple" statement path.
1909 if (HaveInsertPoint())
1910 EmitStopPoint(&S);
1911
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001912 // This must be a __leave from a __finally block, which we warn on and is UB.
1913 // Just emit unreachable.
1914 if (!isSEHTryScope()) {
1915 Builder.CreateUnreachable();
1916 Builder.ClearInsertionPoint();
1917 return;
1918 }
1919
Nico Weber5779f842015-02-12 23:16:11 +00001920 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00001921}