blob: 709ed002643a60dacb4bb73bb9242adeca860cea [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
68 name = "\01?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 +0000115/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
116/// other platforms, unless the user asked for SjLj exceptions.
117static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
118 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
119}
120
121static const EHPersonality &getCPersonality(const llvm::Triple &T,
122 const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000123 if (L.SjLjExceptions)
124 return EHPersonality::GNU_C_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000125 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000126 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000127 return EHPersonality::GNU_C;
128}
129
Reid Klecknere070b992014-11-14 02:01:10 +0000130static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
131 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000132 switch (L.ObjCRuntime.getKind()) {
133 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000134 return getCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000135 case ObjCRuntime::MacOSX:
136 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000137 case ObjCRuntime::WatchOS:
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;
142 // 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;
147 else if (useLibGCCSEHPersonality(T))
148 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;
Reid Klecknere070b992014-11-14 02:01:10 +0000158 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000159 return EHPersonality::GNU_CPlusPlus_SEH;
Reid Klecknere070b992014-11-14 02:01:10 +0000160 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000161}
162
163/// Determines the personality function to use when both C++
164/// and Objective-C exceptions are being caught.
Reid Klecknere070b992014-11-14 02:01:10 +0000165static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
166 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000167 switch (L.ObjCRuntime.getKind()) {
John McCallbd309292010-07-06 01:34:17 +0000168 // The ObjC personality defers to the C++ personality for non-ObjC
169 // handlers. Unlike the C++ case, we use the same personality
170 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000171 case ObjCRuntime::MacOSX:
172 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000173 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +0000174 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000175
John McCall5fb5df92012-06-20 06:18:46 +0000176 // In the fragile ABI, just use C++ exception handling and hope
177 // they're not doing crazy exception mixing.
178 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000179 return getCXXPersonality(T, L);
David Chisnallf9c42252010-05-17 13:49:20 +0000180
David Chisnallb601c962012-07-03 20:49:52 +0000181 // The GCC runtime's personality function inherently doesn't support
John McCall36ea3722010-07-17 00:43:08 +0000182 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000183 case ObjCRuntime::GCC:
Benjamin Kramer9851cb72017-04-01 17:59:01 +0000184 case ObjCRuntime::ObjFW:
185 return getObjCPersonality(T, L);
David Chisnallb601c962012-07-03 20:49:52 +0000186 case ObjCRuntime::GNUstep:
John McCall5fb5df92012-06-20 06:18:46 +0000187 return EHPersonality::GNU_ObjCXX;
188 }
189 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000190}
191
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000192static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000193 if (T.getArch() == llvm::Triple::x86)
194 return EHPersonality::MSVC_except_handler;
195 return EHPersonality::MSVC_C_specific_handler;
196}
197
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000198const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
199 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000200 const llvm::Triple &T = CGM.getTarget().getTriple();
201 const LangOptions &L = CGM.getLangOpts();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000202
Reid Kleckner01485652015-09-17 17:04:13 +0000203 // Functions using SEH get an SEH personality.
204 if (FD && FD->usesSEHTry())
205 return getSEHPersonalityMSVC(T);
206
Reid Kleckner1d59f992015-01-22 01:36:17 +0000207 // Try to pick a personality function that is compatible with MSVC if we're
208 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
209 // the GCC-style personality function.
210 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000211 if (L.SjLjExceptions)
212 return EHPersonality::GNU_CPlusPlus_SJLJ;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000213 else
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000214 return EHPersonality::MSVC_CxxFrameHandler3;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000215 }
216
John McCall36ea3722010-07-17 00:43:08 +0000217 if (L.CPlusPlus && L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000218 return getObjCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000219 else if (L.CPlusPlus)
Reid Klecknere070b992014-11-14 02:01:10 +0000220 return getCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000221 else if (L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000222 return getObjCPersonality(T, L);
John McCallbd309292010-07-06 01:34:17 +0000223 else
Reid Klecknere070b992014-11-14 02:01:10 +0000224 return getCPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000225}
John McCallbd309292010-07-06 01:34:17 +0000226
David Majnemerc28d46e2015-07-22 23:46:21 +0000227const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
228 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
229}
230
John McCall0bdb1fd2010-09-16 06:16:50 +0000231static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000232 const EHPersonality &Personality) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +0000233 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
234 Personality.PersonalityFn,
Reid Klecknerde864822017-03-21 16:57:30 +0000235 llvm::AttributeList(), /*Local=*/true);
John McCall0bdb1fd2010-09-16 06:16:50 +0000236}
237
238static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
239 const EHPersonality &Personality) {
240 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000241 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000242}
243
Vedant Kumardb609472015-09-11 15:40:05 +0000244/// Check whether a landingpad instruction only uses C++ features.
245static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
246 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
247 // Look for something that would've been returned by the ObjC
248 // runtime's GetEHType() method.
249 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
250 if (LPI->isCatch(I)) {
251 // Check if the catch value has the ObjC prefix.
252 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
253 // ObjC EH selector entries are always global variables with
254 // names starting like this.
255 if (GV->getName().startswith("OBJC_EHTYPE"))
256 return false;
257 } else {
258 // Check if any of the filter values have the ObjC prefix.
259 llvm::Constant *CVal = cast<llvm::Constant>(Val);
260 for (llvm::User::op_iterator
261 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
262 if (llvm::GlobalVariable *GV =
263 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
264 // ObjC EH selector entries are always global variables with
265 // names starting like this.
266 if (GV->getName().startswith("OBJC_EHTYPE"))
267 return false;
268 }
269 }
270 }
271 return true;
272}
273
John McCall0bdb1fd2010-09-16 06:16:50 +0000274/// Check whether a personality function could reasonably be swapped
275/// for a C++ personality function.
276static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000277 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000278 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000279 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000280 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
281 if (!PersonalityHasOnlyCXXUses(CE))
282 return false;
283 continue;
284 }
285
Vedant Kumardb609472015-09-11 15:40:05 +0000286 // Otherwise it must be a function.
287 llvm::Function *F = dyn_cast<llvm::Function>(U);
288 if (!F) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000289
Vedant Kumardb609472015-09-11 15:40:05 +0000290 for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
291 if (BB->isLandingPad())
292 if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
293 return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000294 }
295 }
296
297 return true;
298}
299
300/// Try to use the C++ personality function in ObjC++. Not doing this
301/// can cause some incompatibilities with gcc, which is more
302/// aggressive about only using the ObjC++ personality in a function
303/// when it really needs it.
304void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000305 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000306 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000307 return;
308
John McCall3c223932012-11-14 17:48:31 +0000309 // Both the problem this endeavors to fix and the way the logic
310 // above works is specific to the NeXT runtime.
311 if (!LangOpts.ObjCRuntime.isNeXTFamily())
312 return;
313
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000314 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Reid Klecknere070b992014-11-14 02:01:10 +0000315 const EHPersonality &CXX =
316 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000317 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000318 return;
319
Benjamin Kramer793bd552012-02-08 12:41:24 +0000320 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
321 "Different EHPersonalities using the same personality function.");
322
323 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000324
325 // Nothing to do if it's unused.
326 if (!Fn || Fn->use_empty()) return;
327
328 // Can't do the optimization if it has non-C++ uses.
329 if (!PersonalityHasOnlyCXXUses(Fn)) return;
330
331 // Create the C++ personality function and kill off the old
332 // function.
333 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
334
335 // This can happen if the user is screwing with us.
336 if (Fn->getType() != CXXFn->getType()) return;
337
338 Fn->replaceAllUsesWith(CXXFn);
339 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000340}
341
342/// Returns the value to inject into a selector to indicate the
343/// presence of a catch-all.
344static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
345 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000346 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000347}
348
John McCallbb026012010-07-13 21:17:51 +0000349namespace {
350 /// A cleanup to free the exception object if its initialization
351 /// throws.
David Blaikie7e70d682015-08-18 22:40:54 +0000352 struct FreeException final : EHScopeStack::Cleanup {
John McCall5fcf8da2011-07-12 00:15:30 +0000353 llvm::Value *exn;
354 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000355 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000356 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000357 }
358 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000359} // end anonymous namespace
John McCallbb026012010-07-13 21:17:51 +0000360
John McCall2e6567a2010-04-22 01:10:34 +0000361// Emits an exception expression into the given location. This
362// differs from EmitAnyExprToMem only in that, if a final copy-ctor
363// call is required, an exception within that copy ctor causes
364// std::terminate to be invoked.
John McCall7f416cc2015-09-08 08:05:57 +0000365void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
John McCallbd309292010-07-06 01:34:17 +0000366 // Make sure the exception object is cleaned up if there's an
367 // exception during initialization.
John McCall7f416cc2015-09-08 08:05:57 +0000368 pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
David Majnemer7c237072015-03-05 00:46:22 +0000369 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000370
371 // __cxa_allocate_exception returns a void*; we need to cast this
372 // to the appropriate type for the object.
David Majnemer7c237072015-03-05 00:46:22 +0000373 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
John McCall7f416cc2015-09-08 08:05:57 +0000374 Address typedAddr = Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000375
376 // FIXME: this isn't quite right! If there's a final unelided call
377 // to a copy constructor, then according to [except.terminate]p1 we
378 // must call std::terminate() if that constructor throws, because
379 // technically that copy occurs after the exception expression is
380 // evaluated but before the exception is caught. But the best way
381 // to handle that is to teach EmitAggExpr to do the final copy
382 // differently if it can't be elided.
David Majnemer7c237072015-03-05 00:46:22 +0000383 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
384 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000385
John McCalle4df6c82011-01-28 08:37:24 +0000386 // Deactivate the cleanup block.
John McCall7f416cc2015-09-08 08:05:57 +0000387 DeactivateCleanupBlock(cleanup,
388 cast<llvm::Instruction>(typedAddr.getPointer()));
Mike Stump54066142009-12-01 03:41:18 +0000389}
390
John McCall7f416cc2015-09-08 08:05:57 +0000391Address CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000392 if (!ExceptionSlot)
393 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000394 return Address(ExceptionSlot, getPointerAlign());
Mike Stump54066142009-12-01 03:41:18 +0000395}
396
John McCall7f416cc2015-09-08 08:05:57 +0000397Address CodeGenFunction::getEHSelectorSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000398 if (!EHSelectorSlot)
399 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000400 return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
John McCall9b382dd2011-05-28 21:13:02 +0000401}
402
Bill Wendling79a70e42011-09-15 18:57:19 +0000403llvm::Value *CodeGenFunction::getExceptionFromSlot() {
404 return Builder.CreateLoad(getExceptionSlot(), "exn");
405}
406
407llvm::Value *CodeGenFunction::getSelectorFromSlot() {
408 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
409}
410
Richard Smithea852322013-05-07 21:53:22 +0000411void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
412 bool KeepInsertionPoint) {
David Majnemer7c237072015-03-05 00:46:22 +0000413 if (const Expr *SubExpr = E->getSubExpr()) {
414 QualType ThrowType = SubExpr->getType();
415 if (ThrowType->isObjCObjectPointerType()) {
416 const Stmt *ThrowStmt = E->getSubExpr();
417 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
418 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
419 } else {
420 CGM.getCXXABI().emitThrow(*this, E);
John McCall2e6567a2010-04-22 01:10:34 +0000421 }
David Majnemer7c237072015-03-05 00:46:22 +0000422 } else {
423 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000424 }
Mike Stump75546b82009-12-10 00:06:18 +0000425
John McCall20f6ab82011-01-12 03:41:02 +0000426 // throw is an expression, and the expression emitters expect us
427 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000428 if (KeepInsertionPoint)
429 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000430}
Mike Stump58ef18b2009-11-20 23:44:51 +0000431
Mike Stump1d849212009-12-07 23:38:24 +0000432void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000433 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000434 return;
435
Mike Stump1d849212009-12-07 23:38:24 +0000436 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000437 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000438 // Check if CapturedDecl is nothrow and create terminate scope for it.
439 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
440 if (CD->isNothrow())
441 EHStack.pushTerminate();
442 }
Mike Stump1d849212009-12-07 23:38:24 +0000443 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000444 }
Mike Stump1d849212009-12-07 23:38:24 +0000445 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000446 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000447 return;
448
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000449 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
450 if (isNoexceptExceptionSpec(EST)) {
451 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
452 // noexcept functions are simple terminate scopes.
453 EHStack.pushTerminate();
454 }
455 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000456 // TODO: Revisit exception specifications for the MS ABI. There is a way to
457 // encode these in an object file but MSVC doesn't do anything with it.
458 if (getTarget().getCXXABI().isMicrosoft())
459 return;
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000460 unsigned NumExceptions = Proto->getNumExceptions();
461 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000462
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000463 for (unsigned I = 0; I != NumExceptions; ++I) {
464 QualType Ty = Proto->getExceptionType(I);
465 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
466 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
467 /*ForEH=*/true);
468 Filter->setFilter(I, EHType);
469 }
Mike Stump1d849212009-12-07 23:38:24 +0000470 }
Mike Stump1d849212009-12-07 23:38:24 +0000471}
472
John McCall8e4c74b2011-08-11 02:22:43 +0000473/// Emit the dispatch block for a filter scope if necessary.
474static void emitFilterDispatchBlock(CodeGenFunction &CGF,
475 EHFilterScope &filterScope) {
476 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
477 if (!dispatchBlock) return;
478 if (dispatchBlock->use_empty()) {
479 delete dispatchBlock;
480 return;
481 }
482
John McCall8e4c74b2011-08-11 02:22:43 +0000483 CGF.EmitBlockAfterUses(dispatchBlock);
484
485 // If this isn't a catch-all filter, we need to check whether we got
486 // here because the filter triggered.
487 if (filterScope.getNumFilters()) {
488 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000489 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000490 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
491
492 llvm::Value *zero = CGF.Builder.getInt32(0);
493 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000494 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
495 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
496 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000497
498 CGF.EmitBlock(unexpectedBB);
499 }
500
501 // Call __cxa_call_unexpected. This doesn't need to be an invoke
502 // because __cxa_call_unexpected magically filters exceptions
503 // according to the last landing pad the exception was thrown
504 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000505 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000506 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000507 ->setDoesNotReturn();
508 CGF.Builder.CreateUnreachable();
509}
510
Mike Stump1d849212009-12-07 23:38:24 +0000511void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000512 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000513 return;
514
Mike Stump1d849212009-12-07 23:38:24 +0000515 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000516 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000517 // Check if CapturedDecl is nothrow and pop terminate scope for it.
518 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
519 if (CD->isNothrow())
520 EHStack.popTerminate();
521 }
Mike Stump1d849212009-12-07 23:38:24 +0000522 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000523 }
Mike Stump1d849212009-12-07 23:38:24 +0000524 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000525 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000526 return;
527
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000528 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
529 if (isNoexceptExceptionSpec(EST)) {
530 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
531 EHStack.popTerminate();
532 }
533 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000534 // TODO: Revisit exception specifications for the MS ABI. There is a way to
535 // encode these in an object file but MSVC doesn't do anything with it.
536 if (getTarget().getCXXABI().isMicrosoft())
537 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000538 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
539 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000540 EHStack.popFilter();
541 }
Mike Stump1d849212009-12-07 23:38:24 +0000542}
543
Mike Stump58ef18b2009-11-20 23:44:51 +0000544void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000545 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000546 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000547 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000548}
549
John McCallb609d3f2010-07-07 06:56:46 +0000550void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000551 unsigned NumHandlers = S.getNumHandlers();
552 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000553
John McCallbd309292010-07-06 01:34:17 +0000554 for (unsigned I = 0; I != NumHandlers; ++I) {
555 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000556
John McCallbd309292010-07-06 01:34:17 +0000557 llvm::BasicBlock *Handler = createBasicBlock("catch");
558 if (C->getExceptionDecl()) {
559 // FIXME: Dropping the reference type on the type into makes it
560 // impossible to correctly implement catch-by-reference
561 // semantics for pointers. Unfortunately, this is what all
562 // existing compilers do, and it's not clear that the standard
563 // personality routine is capable of doing this right. See C++ DR 388:
564 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000565 Qualifiers CaughtTypeQuals;
566 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
567 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000568
Reid Kleckner10aa7702015-09-16 20:15:55 +0000569 CatchTypeInfo TypeInfo{nullptr, 0};
John McCall2ca705e2010-07-24 00:37:23 +0000570 if (CaughtType->isObjCObjectPointerType())
Reid Kleckner10aa7702015-09-16 20:15:55 +0000571 TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000572 else
Reid Kleckner10aa7702015-09-16 20:15:55 +0000573 TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
574 CaughtType, C->getCaughtType());
John McCallbd309292010-07-06 01:34:17 +0000575 CatchScope->setHandler(I, TypeInfo, Handler);
576 } else {
577 // No exception decl indicates '...', a catch-all.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000578 CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
John McCallbd309292010-07-06 01:34:17 +0000579 }
580 }
John McCallbd309292010-07-06 01:34:17 +0000581}
582
John McCall8e4c74b2011-08-11 02:22:43 +0000583llvm::BasicBlock *
584CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
Reid Kleckner129552b2015-10-08 01:13:52 +0000585 if (EHPersonality::get(*this).usesFuncletPads())
David Majnemerdbf10452015-07-31 17:58:45 +0000586 return getMSVCDispatchBlock(si);
587
John McCall8e4c74b2011-08-11 02:22:43 +0000588 // The dispatch block for the end of the scope chain is a block that
589 // just resumes unwinding.
590 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000591 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000592
593 // Otherwise, we should look at the actual scope.
594 EHScope &scope = *EHStack.find(si);
595
596 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
597 if (!dispatchBlock) {
598 switch (scope.getKind()) {
599 case EHScope::Catch: {
600 // Apply a special case to a single catch-all.
601 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
602 if (catchScope.getNumHandlers() == 1 &&
603 catchScope.getHandler(0).isCatchAll()) {
604 dispatchBlock = catchScope.getHandler(0).Block;
605
606 // Otherwise, make a dispatch block.
607 } else {
608 dispatchBlock = createBasicBlock("catch.dispatch");
609 }
610 break;
611 }
612
613 case EHScope::Cleanup:
614 dispatchBlock = createBasicBlock("ehcleanup");
615 break;
616
617 case EHScope::Filter:
618 dispatchBlock = createBasicBlock("filter.dispatch");
619 break;
620
621 case EHScope::Terminate:
622 dispatchBlock = getTerminateHandler();
623 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000624
Reid Kleckner2586aac2015-09-10 22:11:13 +0000625 case EHScope::PadEnd:
626 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCall8e4c74b2011-08-11 02:22:43 +0000627 }
628 scope.setCachedEHDispatchBlock(dispatchBlock);
629 }
630 return dispatchBlock;
631}
632
David Majnemerdbf10452015-07-31 17:58:45 +0000633llvm::BasicBlock *
634CodeGenFunction::getMSVCDispatchBlock(EHScopeStack::stable_iterator SI) {
635 // Returning nullptr indicates that the previous dispatch block should unwind
636 // to caller.
637 if (SI == EHStack.stable_end())
638 return nullptr;
639
640 // Otherwise, we should look at the actual scope.
641 EHScope &EHS = *EHStack.find(SI);
642
643 llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
644 if (DispatchBlock)
645 return DispatchBlock;
646
647 if (EHS.getKind() == EHScope::Terminate)
648 DispatchBlock = getTerminateHandler();
649 else
650 DispatchBlock = createBasicBlock();
John McCall7f416cc2015-09-08 08:05:57 +0000651 CGBuilderTy Builder(*this, DispatchBlock);
David Majnemerdbf10452015-07-31 17:58:45 +0000652
653 switch (EHS.getKind()) {
654 case EHScope::Catch:
655 DispatchBlock->setName("catch.dispatch");
656 break;
657
658 case EHScope::Cleanup:
659 DispatchBlock->setName("ehcleanup");
660 break;
661
662 case EHScope::Filter:
663 llvm_unreachable("exception specifications not handled yet!");
664
665 case EHScope::Terminate:
666 DispatchBlock->setName("terminate");
667 break;
668
Reid Kleckner2586aac2015-09-10 22:11:13 +0000669 case EHScope::PadEnd:
670 llvm_unreachable("PadEnd dispatch block missing!");
David Majnemerdbf10452015-07-31 17:58:45 +0000671 }
672 EHS.setCachedEHDispatchBlock(DispatchBlock);
673 return DispatchBlock;
674}
675
John McCallbd309292010-07-06 01:34:17 +0000676/// Check whether this is a non-EH scope, i.e. a scope which doesn't
677/// affect exception handling. Currently, the only non-EH scopes are
678/// normal-only cleanup scopes.
679static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000680 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000681 case EHScope::Cleanup:
682 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000683 case EHScope::Filter:
684 case EHScope::Catch:
685 case EHScope::Terminate:
Reid Kleckner2586aac2015-09-10 22:11:13 +0000686 case EHScope::PadEnd:
John McCall2b7fc382010-07-13 20:32:21 +0000687 return false;
688 }
689
David Blaikiee4d798f2012-01-20 21:50:17 +0000690 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000691}
692
693llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
694 assert(EHStack.requiresLandingPad());
695 assert(!EHStack.empty());
696
Reid Kleckner8f1b1f52016-03-01 19:51:48 +0000697 // If exceptions are disabled and SEH is not in use, then there is no invoke
698 // destination. SEH "works" even if exceptions are off. In practice, this
699 // means that C++ destructors and other EH cleanups don't run, which is
700 // consistent with MSVC's behavior.
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000701 const LangOptions &LO = CGM.getLangOpts();
702 if (!LO.Exceptions) {
703 if (!LO.Borland && !LO.MicrosoftExt)
704 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000705 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000706 return nullptr;
707 }
John McCall2b7fc382010-07-13 20:32:21 +0000708
Justin Lebar3e6449b2016-10-04 23:41:49 +0000709 // CUDA device code doesn't have exceptions.
710 if (LO.CUDA && LO.CUDAIsDevice)
711 return nullptr;
712
John McCallbd309292010-07-06 01:34:17 +0000713 // Check the innermost scope for a cached landing pad. If this is
714 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
715 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
716 if (LP) return LP;
717
David Majnemerdbf10452015-07-31 17:58:45 +0000718 const EHPersonality &Personality = EHPersonality::get(*this);
719
720 if (!CurFn->hasPersonalityFn())
721 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
722
Reid Kleckner129552b2015-10-08 01:13:52 +0000723 if (Personality.usesFuncletPads()) {
724 // We don't need separate landing pads in the funclet model.
David Majnemerdbf10452015-07-31 17:58:45 +0000725 LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
726 } else {
727 // Build the landing pad for this scope.
728 LP = EmitLandingPad();
729 }
730
John McCallbd309292010-07-06 01:34:17 +0000731 assert(LP);
732
733 // Cache the landing pad on the innermost scope. If this is a
734 // non-EH scope, cache the landing pad on the enclosing scope, too.
735 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
736 ir->setCachedLandingPad(LP);
737 if (!isNonEHScope(*ir)) break;
738 }
739
740 return LP;
741}
742
743llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
744 assert(EHStack.requiresLandingPad());
745
John McCall8e4c74b2011-08-11 02:22:43 +0000746 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
747 switch (innermostEHScope.getKind()) {
748 case EHScope::Terminate:
749 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000750
Reid Kleckner2586aac2015-09-10 22:11:13 +0000751 case EHScope::PadEnd:
752 llvm_unreachable("PadEnd unnecessary for Itanium!");
David Majnemerdbf10452015-07-31 17:58:45 +0000753
John McCall8e4c74b2011-08-11 02:22:43 +0000754 case EHScope::Catch:
755 case EHScope::Cleanup:
756 case EHScope::Filter:
757 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
758 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000759 }
760
761 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000762 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantl95b24e92015-02-03 20:00:54 +0000763 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000764
765 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000766 llvm::BasicBlock *lpad = createBasicBlock("lpad");
767 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000768
Serge Guelton1d993272017-05-09 19:31:30 +0000769 llvm::LandingPadInst *LPadInst =
770 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +0000771
772 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
773 Builder.CreateStore(LPadExn, getExceptionSlot());
774 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
775 Builder.CreateStore(LPadSel, getEHSelectorSlot());
776
John McCallbd309292010-07-06 01:34:17 +0000777 // Save the exception pointer. It's safe to use a single exception
778 // pointer per function because EH cleanups can never have nested
779 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000780 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000781
782 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000783 bool hasCatchAll = false;
784 bool hasCleanup = false;
785 bool hasFilter = false;
786 SmallVector<llvm::Value*, 4> filterTypes;
787 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Nico Webere68b9f32015-02-25 16:25:00 +0000788 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
789 ++I) {
John McCallbd309292010-07-06 01:34:17 +0000790
791 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000792 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000793 // If we have a cleanup, remember that.
794 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000795 continue;
796
John McCallbd309292010-07-06 01:34:17 +0000797 case EHScope::Filter: {
798 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000799 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000800
Bill Wendlingf0724e82011-09-19 20:31:14 +0000801 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000802 EHFilterScope &filter = cast<EHFilterScope>(*I);
803 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000804
Bill Wendling8c4b7162011-09-22 20:32:54 +0000805 // Add all the filter values.
806 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
807 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000808 goto done;
809 }
810
811 case EHScope::Terminate:
812 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000813 assert(!hasCatchAll);
814 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000815 goto done;
816
817 case EHScope::Catch:
818 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000819
Reid Kleckner2586aac2015-09-10 22:11:13 +0000820 case EHScope::PadEnd:
821 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCallbd309292010-07-06 01:34:17 +0000822 }
823
John McCall8e4c74b2011-08-11 02:22:43 +0000824 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
825 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
826 EHCatchScope::Handler handler = catchScope.getHandler(hi);
Reid Kleckner10aa7702015-09-16 20:15:55 +0000827 assert(handler.Type.Flags == 0 &&
828 "landingpads do not support catch handler flags");
John McCallbd309292010-07-06 01:34:17 +0000829
John McCall8e4c74b2011-08-11 02:22:43 +0000830 // If this is a catch-all, register that and abort.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000831 if (!handler.Type.RTTI) {
John McCall8e4c74b2011-08-11 02:22:43 +0000832 assert(!hasCatchAll);
833 hasCatchAll = true;
834 goto done;
John McCallbd309292010-07-06 01:34:17 +0000835 }
836
837 // Check whether we already have a handler for this type.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000838 if (catchTypes.insert(handler.Type.RTTI).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000839 // If not, add it directly to the landingpad.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000840 LPadInst->addClause(handler.Type.RTTI);
John McCallbd309292010-07-06 01:34:17 +0000841 }
John McCallbd309292010-07-06 01:34:17 +0000842 }
843
844 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000845 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000846 assert(!(hasCatchAll && hasFilter));
847 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000848 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000849
850 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000851 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000852 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000853 // Create a filter expression: a constant array indicating which filter
854 // types there are. The personality routine only lands here if the filter
855 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000856 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000857 llvm::ArrayType *AType =
858 llvm::ArrayType::get(!filterTypes.empty() ?
859 filterTypes[0]->getType() : Int8PtrTy,
860 filterTypes.size());
861
862 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
863 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
864 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
865 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000866
867 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000868 if (hasCleanup)
869 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000870
871 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000872 } else if (hasCleanup) {
873 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000874 }
875
Bill Wendlingf0724e82011-09-19 20:31:14 +0000876 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
877 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000878
879 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000880 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000881
882 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000883 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000884
John McCall8e4c74b2011-08-11 02:22:43 +0000885 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000886}
887
David Majnemer4e52d6f2015-12-12 05:39:21 +0000888static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
David Majnemerdbf10452015-07-31 17:58:45 +0000889 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
890 assert(DispatchBlock);
891
892 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
893 CGF.EmitBlockAfterUses(DispatchBlock);
894
David Majnemer4e52d6f2015-12-12 05:39:21 +0000895 llvm::Value *ParentPad = CGF.CurrentFuncletPad;
896 if (!ParentPad)
897 ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
898 llvm::BasicBlock *UnwindBB =
899 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
900
901 unsigned NumHandlers = CatchScope.getNumHandlers();
902 llvm::CatchSwitchInst *CatchSwitch =
903 CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
David Majnemerdbf10452015-07-31 17:58:45 +0000904
905 // Test against each of the exception types we claim to catch.
David Majnemer4e52d6f2015-12-12 05:39:21 +0000906 for (unsigned I = 0; I < NumHandlers; ++I) {
David Majnemerdbf10452015-07-31 17:58:45 +0000907 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
908
Reid Kleckner10aa7702015-09-16 20:15:55 +0000909 CatchTypeInfo TypeInfo = Handler.Type;
910 if (!TypeInfo.RTTI)
911 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
David Majnemerdbf10452015-07-31 17:58:45 +0000912
David Majnemer4e52d6f2015-12-12 05:39:21 +0000913 CGF.Builder.SetInsertPoint(Handler.Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000914
915 if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000916 CGF.Builder.CreateCatchPad(
917 CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
918 llvm::Constant::getNullValue(CGF.VoidPtrTy)});
David Majnemerdbf10452015-07-31 17:58:45 +0000919 } else {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000920 CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
David Majnemerdbf10452015-07-31 17:58:45 +0000921 }
922
David Majnemer4e52d6f2015-12-12 05:39:21 +0000923 CatchSwitch->addHandler(Handler.Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000924 }
925 CGF.Builder.restoreIP(SavedIP);
David Majnemerdbf10452015-07-31 17:58:45 +0000926}
927
John McCall8e4c74b2011-08-11 02:22:43 +0000928/// Emit the structure of the dispatch block for the given catch scope.
929/// It is an invariant that the dispatch block already exists.
David Majnemer4e52d6f2015-12-12 05:39:21 +0000930static void emitCatchDispatchBlock(CodeGenFunction &CGF,
931 EHCatchScope &catchScope) {
Reid Kleckner129552b2015-10-08 01:13:52 +0000932 if (EHPersonality::get(CGF).usesFuncletPads())
933 return emitCatchPadBlock(CGF, catchScope);
David Majnemerdbf10452015-07-31 17:58:45 +0000934
John McCall8e4c74b2011-08-11 02:22:43 +0000935 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
936 assert(dispatchBlock);
937
938 // If there's only a single catch-all, getEHDispatchBlock returned
939 // that catch-all as the dispatch block.
940 if (catchScope.getNumHandlers() == 1 &&
941 catchScope.getHandler(0).isCatchAll()) {
942 assert(dispatchBlock == catchScope.getHandler(0).Block);
David Majnemer4e52d6f2015-12-12 05:39:21 +0000943 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000944 }
945
946 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
947 CGF.EmitBlockAfterUses(dispatchBlock);
948
949 // Select the right handler.
950 llvm::Value *llvm_eh_typeid_for =
951 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
952
953 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000954 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000955
956 // Test against each of the exception types we claim to catch.
957 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
958 assert(i < e && "ran off end of handlers!");
959 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
960
Reid Kleckner10aa7702015-09-16 20:15:55 +0000961 llvm::Value *typeValue = handler.Type.RTTI;
962 assert(handler.Type.Flags == 0 &&
963 "landingpads do not support catch handler flags");
John McCall8e4c74b2011-08-11 02:22:43 +0000964 assert(typeValue && "fell into catch-all case!");
965 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
966
967 // Figure out the next block.
968 bool nextIsEnd;
969 llvm::BasicBlock *nextBlock;
970
971 // If this is the last handler, we're at the end, and the next
972 // block is the block for the enclosing EH scope.
973 if (i + 1 == e) {
974 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
975 nextIsEnd = true;
976
977 // If the next handler is a catch-all, we're at the end, and the
978 // next block is that handler.
979 } else if (catchScope.getHandler(i+1).isCatchAll()) {
980 nextBlock = catchScope.getHandler(i+1).Block;
981 nextIsEnd = true;
982
983 // Otherwise, we're not at the end and we need a new block.
984 } else {
985 nextBlock = CGF.createBasicBlock("catch.fallthrough");
986 nextIsEnd = false;
987 }
988
989 // Figure out the catch type's index in the LSDA's type table.
990 llvm::CallInst *typeIndex =
991 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
992 typeIndex->setDoesNotThrow();
993
994 llvm::Value *matchesTypeIndex =
995 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
996 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
997
998 // If the next handler is a catch-all, we're completely done.
999 if (nextIsEnd) {
1000 CGF.Builder.restoreIP(savedIP);
David Majnemer4e52d6f2015-12-12 05:39:21 +00001001 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001002 }
Ahmed Charles289896d2012-02-19 11:57:29 +00001003 // Otherwise we need to emit and continue at that block.
1004 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +00001005 }
John McCall8e4c74b2011-08-11 02:22:43 +00001006}
1007
1008void CodeGenFunction::popCatchScope() {
1009 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1010 if (catchScope.hasEHBranches())
1011 emitCatchDispatchBlock(*this, catchScope);
1012 EHStack.popCatch();
1013}
1014
John McCallb609d3f2010-07-07 06:56:46 +00001015void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001016 unsigned NumHandlers = S.getNumHandlers();
1017 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1018 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001019
John McCall8e4c74b2011-08-11 02:22:43 +00001020 // If the catch was not required, bail out now.
1021 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001022 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001023 EHStack.popCatch();
1024 return;
1025 }
1026
1027 // Emit the structure of the EH dispatch for this catch.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001028 emitCatchDispatchBlock(*this, CatchScope);
John McCall8e4c74b2011-08-11 02:22:43 +00001029
John McCallbd309292010-07-06 01:34:17 +00001030 // Copy the handler blocks off before we pop the EH stack. Emitting
1031 // the handlers might scribble on this memory.
Benjamin Kramerda32cf82015-08-04 15:38:49 +00001032 SmallVector<EHCatchScope::Handler, 8> Handlers(
1033 CatchScope.begin(), CatchScope.begin() + NumHandlers);
John McCall8e4c74b2011-08-11 02:22:43 +00001034
John McCallbd309292010-07-06 01:34:17 +00001035 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001036
John McCallbd309292010-07-06 01:34:17 +00001037 // The fall-through block.
1038 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001039
John McCallbd309292010-07-06 01:34:17 +00001040 // We just emitted the body of the try; jump to the continue block.
1041 if (HaveInsertPoint())
1042 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001043
John McCalld8d00be2012-06-15 05:27:05 +00001044 // Determine if we need an implicit rethrow for all these catch handlers;
1045 // see the comment below.
1046 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001047 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001048 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1049 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001050
John McCall8e4c74b2011-08-11 02:22:43 +00001051 // Perversely, we emit the handlers backwards precisely because we
1052 // want them to appear in source order. In all of these cases, the
1053 // catch block will have exactly one predecessor, which will be a
1054 // particular block in the catch dispatch. However, in the case of
1055 // a catch-all, one of the dispatch blocks will branch to two
1056 // different handlers, and EmitBlockAfterUses will cause the second
1057 // handler to be moved before the first.
1058 for (unsigned I = NumHandlers; I != 0; --I) {
1059 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1060 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001061
John McCallbd309292010-07-06 01:34:17 +00001062 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001063 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001064
John McCallbd309292010-07-06 01:34:17 +00001065 // Enter a cleanup scope, including the catch variable and the
1066 // end-catch.
1067 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001068
John McCallbd309292010-07-06 01:34:17 +00001069 // Initialize the catch variable and set up the cleanups.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001070 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1071 CurrentFuncletPad);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001072 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallbd309292010-07-06 01:34:17 +00001073
Justin Bognerea278c32014-01-07 00:20:28 +00001074 // Emit the PGO counter increment.
Justin Bogner66242d62015-04-23 23:06:47 +00001075 incrementProfileCounter(C);
Justin Bogneref512b92014-01-06 22:27:43 +00001076
John McCallbd309292010-07-06 01:34:17 +00001077 // Perform the body of the catch.
1078 EmitStmt(C->getHandlerBlock());
1079
John McCalld8d00be2012-06-15 05:27:05 +00001080 // [except.handle]p11:
1081 // The currently handled exception is rethrown if control
1082 // reaches the end of a handler of the function-try-block of a
1083 // constructor or destructor.
1084
1085 // It is important that we only do this on fallthrough and not on
1086 // return. Note that it's illegal to put a return in a
1087 // constructor function-try-block's catch handler (p14), so this
1088 // really only applies to destructors.
1089 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +00001090 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +00001091 Builder.CreateUnreachable();
1092 Builder.ClearInsertionPoint();
1093 }
1094
John McCallbd309292010-07-06 01:34:17 +00001095 // Fall out through the catch cleanups.
1096 CatchScope.ForceCleanup();
1097
1098 // Branch out of the try.
1099 if (HaveInsertPoint())
1100 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001101 }
1102
John McCallbd309292010-07-06 01:34:17 +00001103 EmitBlock(ContBB);
Justin Bogner66242d62015-04-23 23:06:47 +00001104 incrementProfileCounter(&S);
Mike Stump58ef18b2009-11-20 23:44:51 +00001105}
Mike Stumpaff69af2009-12-09 03:35:49 +00001106
John McCall1e670402010-07-21 00:52:03 +00001107namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001108 struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001109 llvm::Value *ForEHVar;
1110 llvm::Value *EndCatchFn;
1111 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1112 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1113
Craig Topper4f12f102014-03-12 06:41:41 +00001114 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001115 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1116 llvm::BasicBlock *CleanupContBB =
1117 CGF.createBasicBlock("finally.cleanup.cont");
1118
1119 llvm::Value *ShouldEndCatch =
John McCall7f416cc2015-09-08 08:05:57 +00001120 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
John McCall1e670402010-07-21 00:52:03 +00001121 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1122 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001123 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001124 CGF.EmitBlock(CleanupContBB);
1125 }
1126 };
John McCall906da4b2010-07-21 05:47:49 +00001127
David Blaikie7e70d682015-08-18 22:40:54 +00001128 struct PerformFinally final : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001129 const Stmt *Body;
1130 llvm::Value *ForEHVar;
1131 llvm::Value *EndCatchFn;
1132 llvm::Value *RethrowFn;
1133 llvm::Value *SavedExnVar;
1134
1135 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1136 llvm::Value *EndCatchFn,
1137 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1138 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1139 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1140
Craig Topper4f12f102014-03-12 06:41:41 +00001141 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001142 // Enter a cleanup to call the end-catch function if one was provided.
1143 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001144 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1145 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001146
John McCallcebe0ca2010-08-11 00:16:14 +00001147 // Save the current cleanup destination in case there are
1148 // cleanups in the finally block.
1149 llvm::Value *SavedCleanupDest =
1150 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1151 "cleanup.dest.saved");
1152
John McCall906da4b2010-07-21 05:47:49 +00001153 // Emit the finally block.
1154 CGF.EmitStmt(Body);
1155
1156 // If the end of the finally is reachable, check whether this was
1157 // for EH. If so, rethrow.
1158 if (CGF.HaveInsertPoint()) {
1159 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1160 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1161
1162 llvm::Value *ShouldRethrow =
John McCall7f416cc2015-09-08 08:05:57 +00001163 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
John McCall906da4b2010-07-21 05:47:49 +00001164 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1165
1166 CGF.EmitBlock(RethrowBB);
1167 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001168 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
John McCall7f416cc2015-09-08 08:05:57 +00001169 CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
John McCall906da4b2010-07-21 05:47:49 +00001170 } else {
John McCall882987f2013-02-28 19:01:20 +00001171 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001172 }
1173 CGF.Builder.CreateUnreachable();
1174
1175 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001176
1177 // Restore the cleanup destination.
1178 CGF.Builder.CreateStore(SavedCleanupDest,
1179 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001180 }
1181
1182 // Leave the end-catch cleanup. As an optimization, pretend that
1183 // the fallthrough path was inaccessible; we've dynamically proven
1184 // that we're not in the EH case along that path.
1185 if (EndCatchFn) {
1186 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1187 CGF.PopCleanupBlock();
1188 CGF.Builder.restoreIP(SavedIP);
1189 }
1190
1191 // Now make sure we actually have an insertion point or the
1192 // cleanup gods will hate us.
1193 CGF.EnsureInsertPoint();
1194 }
1195 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001196} // end anonymous namespace
John McCall1e670402010-07-21 00:52:03 +00001197
John McCallbd309292010-07-06 01:34:17 +00001198/// Enters a finally block for an implementation using zero-cost
1199/// exceptions. This is mostly general, but hard-codes some
1200/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001201void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1202 const Stmt *body,
1203 llvm::Constant *beginCatchFn,
1204 llvm::Constant *endCatchFn,
1205 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001206 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001207 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001208 assert(rethrowFn && "rethrow function is required");
1209
1210 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001211
John McCallbd309292010-07-06 01:34:17 +00001212 // The rethrow function has one of the following two types:
1213 // void (*)()
1214 // void (*)(void*)
1215 // In the latter case we need to pass it the exception object.
1216 // But we can't use the exception slot because the @finally might
1217 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001218 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001219 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001220 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001221 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001222 if (rethrowFnTy->getNumParams())
1223 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001224
John McCallbd309292010-07-06 01:34:17 +00001225 // A finally block is a statement which must be executed on any edge
1226 // out of a given scope. Unlike a cleanup, the finally block may
1227 // contain arbitrary control flow leading out of itself. In
1228 // addition, finally blocks should always be executed, even if there
1229 // are no catch handlers higher on the stack. Therefore, we
1230 // surround the protected scope with a combination of a normal
1231 // cleanup (to catch attempts to break out of the block via normal
1232 // control flow) and an EH catch-all (semantically "outside" any try
1233 // statement to which the finally block might have been attached).
1234 // The finally block itself is generated in the context of a cleanup
1235 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001236
John McCallbd309292010-07-06 01:34:17 +00001237 // Jump destination for performing the finally block on an exception
1238 // edge. We'll never actually reach this block, so unreachable is
1239 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001240 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001241
John McCallbd309292010-07-06 01:34:17 +00001242 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001243 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
John McCall7f416cc2015-09-08 08:05:57 +00001244 CGF.Builder.CreateFlagStore(false, ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001245
John McCallbd309292010-07-06 01:34:17 +00001246 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001247 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1248 ForEHVar, endCatchFn,
1249 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001250
1251 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001252 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1253 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1254 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001255}
1256
John McCall6b0feb72011-06-22 02:32:12 +00001257void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001258 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001259 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1260 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001261
1262 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001263
John McCall6b0feb72011-06-22 02:32:12 +00001264 // If there are any references to the catch-all block, emit it.
1265 if (catchBB->use_empty()) {
1266 delete catchBB;
1267 } else {
1268 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1269 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001270
Craig Topper8a13c412014-05-21 05:09:00 +00001271 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001272
John McCall6b0feb72011-06-22 02:32:12 +00001273 // If there's a begin-catch function, call it.
1274 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001275 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001276 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001277 }
1278
1279 // If we need to remember the exception pointer to rethrow later, do so.
1280 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001281 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall7f416cc2015-09-08 08:05:57 +00001282 CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
John McCall6b0feb72011-06-22 02:32:12 +00001283 }
1284
1285 // Tell the cleanups in the finally block that we're do this for EH.
John McCall7f416cc2015-09-08 08:05:57 +00001286 CGF.Builder.CreateFlagStore(true, ForEHVar);
John McCall6b0feb72011-06-22 02:32:12 +00001287
1288 // Thread a jump through the finally cleanup.
1289 CGF.EmitBranchThroughCleanup(RethrowDest);
1290
1291 CGF.Builder.restoreIP(savedIP);
1292 }
1293
1294 // Finally, leave the @finally cleanup.
1295 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001296}
1297
1298llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1299 if (TerminateLandingPad)
1300 return TerminateLandingPad;
1301
1302 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1303
1304 // This will get inserted at the end of the function.
1305 TerminateLandingPad = createBasicBlock("terminate.lpad");
1306 Builder.SetInsertPoint(TerminateLandingPad);
1307
1308 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001309 const EHPersonality &Personality = EHPersonality::get(*this);
David Majnemerfcbdb6e2015-06-17 20:53:19 +00001310
1311 if (!CurFn->hasPersonalityFn())
1312 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1313
Serge Guelton1d993272017-05-09 19:31:30 +00001314 llvm::LandingPadInst *LPadInst =
1315 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001316 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001317
Hans Wennborgdcfba332015-10-06 23:40:43 +00001318 llvm::Value *Exn = nullptr;
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001319 if (getLangOpts().CPlusPlus)
1320 Exn = Builder.CreateExtractValue(LPadInst, 0);
1321 llvm::CallInst *terminateCall =
1322 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCalle142ad52013-02-12 03:51:46 +00001323 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001324 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001325
John McCallbd309292010-07-06 01:34:17 +00001326 // Restore the saved insertion state.
1327 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001328
John McCallbd309292010-07-06 01:34:17 +00001329 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001330}
Mike Stump2b488872009-12-09 22:59:31 +00001331
1332llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001333 if (TerminateHandler)
1334 return TerminateHandler;
1335
John McCallbd309292010-07-06 01:34:17 +00001336 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001337
John McCallbd309292010-07-06 01:34:17 +00001338 // Set up the terminate handler. This block is inserted at the very
1339 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001340 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001341 Builder.SetInsertPoint(TerminateHandler);
David Majnemerfeeefb22015-12-14 18:34:18 +00001342 llvm::Value *Exn = nullptr;
David Majnemer971d31b2016-02-24 17:02:45 +00001343 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1344 CurrentFuncletPad);
Reid Kleckner129552b2015-10-08 01:13:52 +00001345 if (EHPersonality::get(*this).usesFuncletPads()) {
David Majnemer4e52d6f2015-12-12 05:39:21 +00001346 llvm::Value *ParentPad = CurrentFuncletPad;
1347 if (!ParentPad)
1348 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
David Majnemer971d31b2016-02-24 17:02:45 +00001349 CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
David Majnemerdbf10452015-07-31 17:58:45 +00001350 } else {
David Majnemerdbf10452015-07-31 17:58:45 +00001351 if (getLangOpts().CPlusPlus)
1352 Exn = getExceptionFromSlot();
David Majnemerdbf10452015-07-31 17:58:45 +00001353 }
David Majnemerfeeefb22015-12-14 18:34:18 +00001354 llvm::CallInst *terminateCall =
1355 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1356 terminateCall->setDoesNotReturn();
1357 Builder.CreateUnreachable();
Mike Stump2b488872009-12-09 22:59:31 +00001358
John McCall21886962010-04-21 10:05:39 +00001359 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001360 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001361
Mike Stump2b488872009-12-09 22:59:31 +00001362 return TerminateHandler;
1363}
John McCallbd309292010-07-06 01:34:17 +00001364
David Chisnall9a837be2012-11-07 16:50:40 +00001365llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001366 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001367
1368 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1369
1370 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001371 EHResumeBlock = createBasicBlock("eh.resume");
1372 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001373
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001374 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001375
1376 // This can always be a call because we necessarily didn't find
1377 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001378 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001379 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001380 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Nico Weberff62a6a2015-02-26 22:34:33 +00001381 getExceptionFromSlot())->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001382 Builder.CreateUnreachable();
1383 Builder.restoreIP(SavedIP);
1384 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001385 }
1386
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001387 // Recreate the landingpad's return value for the 'resume' instruction.
1388 llvm::Value *Exn = getExceptionFromSlot();
1389 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001390
Serge Guelton1d993272017-05-09 19:31:30 +00001391 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001392 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1393 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1394 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1395
1396 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001397 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001398 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001399}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001400
1401void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001402 EnterSEHTryStmt(S);
Reid Klecknera5930002015-02-11 21:40:48 +00001403 {
Nico Weber5779f842015-02-12 23:16:11 +00001404 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
Nico Weber5779f842015-02-12 23:16:11 +00001405
Reid Kleckner11c033e2015-02-12 23:40:45 +00001406 SEHTryEpilogueStack.push_back(&TryExit);
Reid Klecknera5930002015-02-11 21:40:48 +00001407 EmitStmt(S.getTryBlock());
Reid Kleckner11c033e2015-02-12 23:40:45 +00001408 SEHTryEpilogueStack.pop_back();
Nico Weber5779f842015-02-12 23:16:11 +00001409
1410 if (!TryExit.getBlock()->use_empty())
1411 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1412 else
1413 delete TryExit.getBlock();
Reid Klecknera5930002015-02-11 21:40:48 +00001414 }
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001415 ExitSEHTryStmt(S);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001416}
1417
1418namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001419struct PerformSEHFinally final : EHScopeStack::Cleanup {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001420 llvm::Function *OutlinedFinally;
Reid Kleckner55391522015-10-08 21:14:56 +00001421 PerformSEHFinally(llvm::Function *OutlinedFinally)
1422 : OutlinedFinally(OutlinedFinally) {}
Reid Kleckneraca01db2015-02-04 22:37:07 +00001423
Reid Kleckner1d59f992015-01-22 01:36:17 +00001424 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001425 ASTContext &Context = CGF.getContext();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001426 CodeGenModule &CGM = CGF.CGM;
Reid Kleckner65870442015-06-09 17:47:50 +00001427
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001428 CallArgList Args;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001429
1430 // Compute the two argument values.
1431 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
Reid Kleckner15d152d2015-07-07 23:23:31 +00001432 llvm::Value *LocalAddrFn = CGM.getIntrinsic(llvm::Intrinsic::localaddress);
David Blaikie4ba525b2015-07-14 17:27:39 +00001433 llvm::Value *FP = CGF.Builder.CreateCall(LocalAddrFn);
Reid Klecknereb11c412015-07-01 21:00:00 +00001434 llvm::Value *IsForEH =
1435 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1436 Args.add(RValue::get(IsForEH), ArgTys[0]);
1437 Args.add(RValue::get(FP), ArgTys[1]);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001438
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001439 // Arrange a two-arg function info and type.
Reid Klecknereb11c412015-07-01 21:00:00 +00001440 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001441 CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001442
John McCallb92ab1a2016-10-26 23:46:34 +00001443 auto Callee = CGCallee::forDirect(OutlinedFinally);
1444 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001445 }
1446};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001447} // end anonymous namespace
Reid Kleckner1d59f992015-01-22 01:36:17 +00001448
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001449namespace {
1450/// Find all local variable captures in the statement.
1451struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1452 CodeGenFunction &ParentCGF;
1453 const VarDecl *ParentThis;
John McCall0a490152015-09-08 21:15:22 +00001454 llvm::SmallSetVector<const VarDecl *, 4> Captures;
John McCall7f416cc2015-09-08 08:05:57 +00001455 Address SEHCodeSlot = Address::invalid();
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001456 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1457 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1458
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001459 // Return true if we need to do any capturing work.
1460 bool foundCaptures() {
John McCall7f416cc2015-09-08 08:05:57 +00001461 return !Captures.empty() || SEHCodeSlot.isValid();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001462 }
1463
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001464 void Visit(const Stmt *S) {
1465 // See if this is a capture, then recurse.
1466 ConstStmtVisitor<CaptureFinder>::Visit(S);
1467 for (const Stmt *Child : S->children())
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001468 if (Child)
1469 Visit(Child);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001470 }
1471
1472 void VisitDeclRefExpr(const DeclRefExpr *E) {
1473 // If this is already a capture, just make sure we capture 'this'.
1474 if (E->refersToEnclosingVariableOrCapture()) {
John McCall0a490152015-09-08 21:15:22 +00001475 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001476 return;
1477 }
1478
1479 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1480 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
John McCall0a490152015-09-08 21:15:22 +00001481 Captures.insert(D);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001482 }
1483
1484 void VisitCXXThisExpr(const CXXThisExpr *E) {
John McCall0a490152015-09-08 21:15:22 +00001485 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001486 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001487
1488 void VisitCallExpr(const CallExpr *E) {
1489 // We only need to add parent frame allocations for these builtins in x86.
1490 if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1491 return;
1492
1493 unsigned ID = E->getBuiltinCallee();
1494 switch (ID) {
1495 case Builtin::BI__exception_code:
1496 case Builtin::BI_exception_code:
1497 // This is the simple case where we are the outermost finally. All we
1498 // have to do here is make sure we escape this and recover it in the
1499 // outlined handler.
John McCall7f416cc2015-09-08 08:05:57 +00001500 if (!SEHCodeSlot.isValid())
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001501 SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1502 break;
1503 }
1504 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001505};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001506} // end anonymous namespace
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001507
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001508Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
1509 Address ParentVar,
1510 llvm::Value *ParentFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001511 llvm::CallInst *RecoverCall = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00001512 CGBuilderTy Builder(*this, AllocaInsertPt);
1513 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001514 // Mark the variable escaped if nobody else referenced it and compute the
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001515 // localescape index.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001516 auto InsertPair = ParentCGF.EscapedLocals.insert(
1517 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1518 int FrameEscapeIdx = InsertPair.first->second;
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001519 // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001520 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001521 &CGM.getModule(), llvm::Intrinsic::localrecover);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001522 llvm::Constant *ParentI8Fn =
1523 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1524 RecoverCall = Builder.CreateCall(
1525 FrameRecoverFn, {ParentI8Fn, ParentFP,
1526 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1527
1528 } else {
1529 // If the parent didn't have an alloca, we're doing some nested outlining.
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001530 // Just clone the existing localrecover call, but tweak the FP argument to
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001531 // use our FP value. All other arguments are constants.
1532 auto *ParentRecover =
John McCall7f416cc2015-09-08 08:05:57 +00001533 cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001534 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1535 "expected alloca or localrecover in parent LocalDeclMap");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001536 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1537 RecoverCall->setArgOperand(1, ParentFP);
1538 RecoverCall->insertBefore(AllocaInsertPt);
1539 }
1540
1541 // Bitcast the variable, rename it, and insert it in the local decl map.
1542 llvm::Value *ChildVar =
John McCall7f416cc2015-09-08 08:05:57 +00001543 Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1544 ChildVar->setName(ParentVar.getName());
1545 return Address(ChildVar, ParentVar.getAlignment());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001546}
1547
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001548void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
Reid Kleckner0b9bbbf2015-06-09 17:49:42 +00001549 const Stmt *OutlinedStmt,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001550 bool IsFilter) {
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001551 // Find all captures in the Stmt.
1552 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1553 Finder.Visit(OutlinedStmt);
1554
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001555 // We can exit early on x86_64 when there are no captures. We just have to
1556 // save the exception code in filters so that __exception_code() works.
1557 if (!Finder.foundCaptures() &&
1558 CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1559 if (IsFilter)
1560 EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001561 return;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001562 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001563
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001564 llvm::Value *EntryFP = nullptr;
1565 CGBuilderTy Builder(CGM, AllocaInsertPt);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001566 if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1567 // 32-bit SEH filters need to be careful about FP recovery. The end of the
1568 // EH registration is passed in as the EBP physical register. We can
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001569 // recover that with llvm.frameaddress(1).
1570 EntryFP = Builder.CreateCall(
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001571 CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001572 } else {
1573 // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1574 // second parameter.
1575 auto AI = CurFn->arg_begin();
1576 ++AI;
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001577 EntryFP = &*AI;
1578 }
1579
1580 llvm::Value *ParentFP = EntryFP;
1581 if (IsFilter) {
1582 // Given whatever FP the runtime provided us in EntryFP, recover the true
1583 // frame pointer of the parent function. We only need to do this in filters,
1584 // since finally funclets recover the parent FP for us.
1585 llvm::Function *RecoverFPIntrin =
1586 CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
1587 llvm::Constant *ParentI8Fn =
1588 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1589 ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001590 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001591
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001592 // Create llvm.localrecover calls for all captures.
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001593 for (const VarDecl *VD : Finder.Captures) {
1594 if (isa<ImplicitParamDecl>(VD)) {
1595 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1596 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1597 continue;
1598 }
1599 if (VD->getType()->isVariablyModifiedType()) {
1600 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1601 continue;
1602 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001603 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1604 "captured non-local variable");
1605
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001606 // If this decl hasn't been declared yet, it will be declared in the
1607 // OutlinedStmt.
1608 auto I = ParentCGF.LocalDeclMap.find(VD);
1609 if (I == ParentCGF.LocalDeclMap.end())
1610 continue;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001611
John McCall7f416cc2015-09-08 08:05:57 +00001612 Address ParentVar = I->second;
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001613 setAddrOfLocalVar(
1614 VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
Nico Webere4f974c2015-07-02 06:10:53 +00001615 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001616
John McCall7f416cc2015-09-08 08:05:57 +00001617 if (Finder.SEHCodeSlot.isValid()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001618 SEHCodeSlotStack.push_back(
1619 recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1620 }
1621
1622 if (IsFilter)
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001623 EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001624}
1625
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001626/// Arrange a function prototype that can be called by Windows exception
1627/// handling personalities. On Win64, the prototype looks like:
1628/// RetTy func(void *EHPtrs, void *ParentFP);
1629void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001630 bool IsFilter,
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001631 const Stmt *OutlinedStmt) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001632 SourceLocation StartLoc = OutlinedStmt->getLocStart();
1633
1634 // Get the mangled function name.
1635 SmallString<128> Name;
1636 {
1637 llvm::raw_svector_ostream OS(Name);
David Majnemer25eb1652016-03-01 19:42:53 +00001638 const FunctionDecl *ParentSEHFn = ParentCGF.CurSEHParent;
1639 assert(ParentSEHFn && "No CurSEHParent!");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001640 MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1641 if (IsFilter)
David Majnemer25eb1652016-03-01 19:42:53 +00001642 Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001643 else
David Majnemer25eb1652016-03-01 19:42:53 +00001644 Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001645 }
1646
1647 FunctionArgList Args;
1648 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1649 // All SEH finally functions take two parameters. Win64 filters take two
1650 // parameters. Win32 filters take no parameters.
1651 if (IsFilter) {
1652 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001653 getContext(), /*DC=*/nullptr, StartLoc,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001654 &getContext().Idents.get("exception_pointers"),
Alexey Bataev56223232017-06-09 13:40:18 +00001655 getContext().VoidPtrTy, ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001656 } else {
1657 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001658 getContext(), /*DC=*/nullptr, StartLoc,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001659 &getContext().Idents.get("abnormal_termination"),
Alexey Bataev56223232017-06-09 13:40:18 +00001660 getContext().UnsignedCharTy, ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001661 }
1662 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001663 getContext(), /*DC=*/nullptr, StartLoc,
1664 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
1665 ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001666 }
1667
1668 QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1669
John McCallc56a8b32016-03-11 04:30:31 +00001670 const CGFunctionInfo &FnInfo =
1671 CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001672
Reid Kleckner1d59f992015-01-22 01:36:17 +00001673 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001674 llvm::Function *Fn = llvm::Function::Create(
1675 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001676
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001677 IsOutlinedSEHHelper = true;
Nico Weberf2a39a72015-04-13 20:03:03 +00001678
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001679 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1680 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
David Majnemer25eb1652016-03-01 19:42:53 +00001681 CurSEHParent = ParentCGF.CurSEHParent;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001682
1683 CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001684 EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001685}
1686
1687/// Create a stub filter function that will ultimately hold the code of the
1688/// filter expression. The EH preparation passes in LLVM will outline the code
1689/// from the main function body into this stub.
1690llvm::Function *
1691CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1692 const SEHExceptStmt &Except) {
1693 const Expr *FilterExpr = Except.getFilterExpr();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001694 startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001695
1696 // Emit the original filter expression, convert to i32, and return.
1697 llvm::Value *R = EmitScalarExpr(FilterExpr);
David Majnemer2ccba832015-04-17 06:57:25 +00001698 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
Reid Kleckner1d59f992015-01-22 01:36:17 +00001699 FilterExpr->getType()->isSignedIntegerType());
1700 Builder.CreateStore(R, ReturnValue);
1701
1702 FinishFunction(FilterExpr->getLocEnd());
1703
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001704 return CurFn;
1705}
1706
1707llvm::Function *
1708CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1709 const SEHFinallyStmt &Finally) {
1710 const Stmt *FinallyBlock = Finally.getBlock();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001711 startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001712
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001713 // Emit the original filter expression, convert to i32, and return.
1714 EmitStmt(FinallyBlock);
1715
1716 FinishFunction(FinallyBlock->getLocEnd());
1717
1718 return CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001719}
1720
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001721void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1722 llvm::Value *ParentFP,
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001723 llvm::Value *EntryFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001724 // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1725 // __exception_info intrinsic.
1726 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1727 // On Win64, the info is passed as the first parameter to the filter.
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001728 SEHInfo = &*CurFn->arg_begin();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001729 SEHCodeSlotStack.push_back(
1730 CreateMemTemp(getContext().IntTy, "__exception_code"));
1731 } else {
1732 // On Win32, the EBP on entry to the filter points to the end of an
1733 // exception registration object. It contains 6 32-bit fields, and the info
1734 // pointer is stored in the second field. So, GEP 20 bytes backwards and
1735 // load the pointer.
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001736 SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001737 SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001738 SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001739 SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1740 ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1741 }
1742
Reid Kleckner1d59f992015-01-22 01:36:17 +00001743 // Save the exception code in the exception slot to unify exception access in
1744 // the filter function and the landing pad.
1745 // struct EXCEPTION_POINTERS {
1746 // EXCEPTION_RECORD *ExceptionRecord;
1747 // CONTEXT *ContextRecord;
1748 // };
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001749 // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001750 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
Serge Guelton1d993272017-05-09 19:31:30 +00001751 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001752 llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
David Blaikie1ed728c2015-04-05 22:45:47 +00001753 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001754 Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
1755 llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001756 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1757 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001758}
1759
1760llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1761 // Sema should diagnose calling this builtin outside of a filter context, but
1762 // don't crash if we screw up.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001763 if (!SEHInfo)
Reid Kleckner1d59f992015-01-22 01:36:17 +00001764 return llvm::UndefValue::get(Int8PtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001765 assert(SEHInfo->getType() == Int8PtrTy);
1766 return SEHInfo;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001767}
1768
1769llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001770 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
John McCall7f416cc2015-09-08 08:05:57 +00001771 return Builder.CreateLoad(SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001772}
1773
Reid Kleckneraca01db2015-02-04 22:37:07 +00001774llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001775 // Abnormal termination is just the first parameter to the outlined finally
1776 // helper.
1777 auto AI = CurFn->arg_begin();
1778 return Builder.CreateZExt(&*AI, Int32Ty);
Reid Kleckneraca01db2015-02-04 22:37:07 +00001779}
1780
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001781void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1782 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1783 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001784 // Outline the finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001785 llvm::Function *FinallyFunc =
1786 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001787
1788 // Push a cleanup for __finally blocks.
Reid Kleckner55391522015-10-08 21:14:56 +00001789 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001790 return;
1791 }
1792
1793 // Otherwise, we must have an __except block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001794 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001795 assert(Except);
1796 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001797 SEHCodeSlotStack.push_back(
1798 CreateMemTemp(getContext().IntTy, "__exception_code"));
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001799
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001800 // If the filter is known to evaluate to 1, then we can use the clause
1801 // "catch i8* null". We can't do this on x86 because the filter has to save
1802 // the exception code.
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001803 llvm::Constant *C =
John McCallde0fe072017-08-15 21:42:52 +00001804 ConstantEmitter(*this).tryEmitAbstract(Except->getFilterExpr(),
1805 getContext().IntTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001806 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
1807 C->isOneValue()) {
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001808 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1809 return;
1810 }
1811
1812 // In general, we have to emit an outlined filter function. Use the function
1813 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00001814 llvm::Function *FilterFunc =
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001815 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001816 llvm::Constant *OpaqueFunc =
1817 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
Reid Kleckner8be18472015-09-16 21:06:09 +00001818 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
Reid Kleckner1d59f992015-01-22 01:36:17 +00001819}
1820
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001821void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001822 // Just pop the cleanup if it's a __finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001823 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001824 PopCleanupBlock();
1825 return;
1826 }
1827
1828 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001829 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001830 assert(Except && "__try must have __finally xor __except");
1831 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1832
1833 // Don't emit the __except block if the __try block lacked invokes.
1834 // TODO: Model unwind edges from instructions, either with iload / istore or
1835 // a try body function.
1836 if (!CatchScope.hasEHBranches()) {
1837 CatchScope.clearHandlerBlocks();
1838 EHStack.popCatch();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001839 SEHCodeSlotStack.pop_back();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001840 return;
1841 }
1842
1843 // The fall-through block.
1844 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1845
1846 // We just emitted the body of the __try; jump to the continue block.
1847 if (HaveInsertPoint())
1848 Builder.CreateBr(ContBB);
1849
1850 // Check if our filter function returned true.
1851 emitCatchDispatchBlock(*this, CatchScope);
1852
1853 // Grab the block before we pop the handler.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001854 llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001855 EHStack.popCatch();
1856
David Majnemer4e52d6f2015-12-12 05:39:21 +00001857 EmitBlockAfterUses(CatchPadBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001858
Reid Kleckner129552b2015-10-08 01:13:52 +00001859 // __except blocks don't get outlined into funclets, so immediately do a
1860 // catchret.
Reid Kleckner129552b2015-10-08 01:13:52 +00001861 llvm::CatchPadInst *CPI =
1862 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
David Majnemer4e52d6f2015-12-12 05:39:21 +00001863 llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
Reid Kleckner129552b2015-10-08 01:13:52 +00001864 Builder.CreateCatchRet(CPI, ExceptBB);
1865 EmitBlock(ExceptBB);
1866
1867 // On Win64, the exception code is returned in EAX. Copy it into the slot.
1868 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1869 llvm::Function *SEHCodeIntrin =
1870 CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
1871 llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
1872 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001873 }
1874
Reid Kleckner1d59f992015-01-22 01:36:17 +00001875 // Emit the __except body.
1876 EmitStmt(Except->getBlock());
1877
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001878 // End the lifetime of the exception code.
1879 SEHCodeSlotStack.pop_back();
1880
Reid Kleckner3a417c32015-01-30 22:16:45 +00001881 if (HaveInsertPoint())
1882 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001883
1884 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00001885}
Nico Weber9b982072014-07-07 00:12:30 +00001886
1887void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00001888 // If this code is reachable then emit a stop point (if generating
1889 // debug info). We have to do this ourselves because we are on the
1890 // "simple" statement path.
1891 if (HaveInsertPoint())
1892 EmitStopPoint(&S);
1893
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001894 // This must be a __leave from a __finally block, which we warn on and is UB.
1895 // Just emit unreachable.
1896 if (!isSEHTryScope()) {
1897 Builder.CreateUnreachable();
1898 Builder.ClearInsertionPoint();
1899 return;
1900 }
1901
Nico Weber5779f842015-02-12 23:16:11 +00001902 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00001903}