blob: 2494f38b3159cc54d8221d8fa9d59c9df6494c35 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson4b08db72009-10-30 01:42:31 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with C++ exception related code generation.
10//
11//===----------------------------------------------------------------------===//
12
David Majnemer442d0a22014-11-25 07:20:20 +000013#include "CGCXXABI.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000014#include "CGCleanup.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000015#include "CGObjCRuntime.h"
Reid Kleckner5d986952019-12-11 07:55:26 -080016#include "CodeGenFunction.h"
John McCallde0fe072017-08-15 21:42:52 +000017#include "ConstantEmitter.h"
John McCall5add20c2010-07-20 22:17:55 +000018#include "TargetInfo.h"
Reid Kleckner1d59f992015-01-22 01:36:17 +000019#include "clang/AST/Mangle.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000020#include "clang/AST/StmtCXX.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000021#include "clang/AST/StmtObjC.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000022#include "clang/AST/StmtVisitor.h"
Heejin Ahnd94bacb2020-05-08 16:19:46 -070023#include "clang/Basic/DiagnosticSema.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000024#include "clang/Basic/TargetBuiltins.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000025#include "llvm/IR/IntrinsicInst.h"
Reid Kleckner5d986952019-12-11 07:55:26 -080026#include "llvm/IR/Intrinsics.h"
27#include "llvm/IR/IntrinsicsWebAssembly.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
James Y Knight9871db02019-02-05 16:42:33 +000033static llvm::FunctionCallee 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 =
Rui Ueyama49a3ad22019-07-16 04:46:31 +000037 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/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
James Y Knight9871db02019-02-05 16:42:33 +000042static llvm::FunctionCallee 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 =
Rui Ueyama49a3ad22019-07-16 04:46:31 +000046 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/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
James Y Knight9871db02019-02-05 16:42:33 +000051llvm::FunctionCallee CodeGenModule::getTerminateFn() {
Mike Stump33270212009-12-02 07:41:41 +000052 // void __terminate();
53
Chris Lattner2192fe52011-07-18 04:24:23 +000054 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +000055 llvm::FunctionType::get(VoidTy, /*isVarArg=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000056
Chris Lattner0e62c1c2011-07-23 10:55:15 +000057 StringRef name;
John McCall9de19782011-07-06 01:22:26 +000058
59 // In C++, use std::terminate().
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000060 if (getLangOpts().CPlusPlus &&
61 getTarget().getCXXABI().isItaniumFamily()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +000062 name = "_ZSt9terminatev";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000063 } else if (getLangOpts().CPlusPlus &&
64 getTarget().getCXXABI().isMicrosoft()) {
David Majnemerb710a932015-05-11 03:57:49 +000065 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemerfb6ffca2015-05-10 21:38:26 +000066 name = "__std_terminate";
67 else
Reid Klecknerfb931542018-03-16 20:36:49 +000068 name = "?terminate@@YAXXZ";
Erik Pilkingtonfa983902018-10-30 20:31:30 +000069 } else if (getLangOpts().ObjC &&
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000070 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
James Y Knight9871db02019-02-05 16:42:33 +000077static llvm::FunctionCallee getCatchallRethrowFn(CodeGenModule &CGM,
78 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +000079 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +000080 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/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 };
Heejin Ahnc6479192018-05-31 22:18:13 +0000114const EHPersonality
115EHPersonality::GNU_Wasm_CPlusPlus = { "__gxx_wasm_personality_v0", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000116
Heejin Ahn00831792018-06-04 18:23:00 +0000117static const EHPersonality &getCPersonality(const TargetInfo &Target,
Reid Klecknere070b992014-11-14 02:01:10 +0000118 const LangOptions &L) {
Heejin Ahn00831792018-06-04 18:23:00 +0000119 const llvm::Triple &T = Target.getTriple();
Shoaib Meenaia5fc6032018-06-08 00:41:01 +0000120 if (T.isWindowsMSVCEnvironment())
121 return EHPersonality::MSVC_CxxFrameHandler3;
John McCall2faab302010-11-07 02:35:25 +0000122 if (L.SjLjExceptions)
123 return EHPersonality::GNU_C_SJLJ;
Saleem Abdulrasool3e701322018-03-09 07:06:42 +0000124 if (L.DWARFExceptions)
125 return EHPersonality::GNU_C;
Martell Malonec950c652017-11-29 07:25:12 +0000126 if (L.SEHExceptions)
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000127 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000128 return EHPersonality::GNU_C;
129}
130
Heejin Ahn00831792018-06-04 18:23:00 +0000131static const EHPersonality &getObjCPersonality(const TargetInfo &Target,
Reid Klecknere070b992014-11-14 02:01:10 +0000132 const LangOptions &L) {
Heejin Ahn00831792018-06-04 18:23:00 +0000133 const llvm::Triple &T = Target.getTriple();
Shoaib Meenaia5fc6032018-06-08 00:41:01 +0000134 if (T.isWindowsMSVCEnvironment())
135 return EHPersonality::MSVC_CxxFrameHandler3;
136
John McCall5fb5df92012-06-20 06:18:46 +0000137 switch (L.ObjCRuntime.getKind()) {
138 case ObjCRuntime::FragileMacOSX:
Heejin Ahn00831792018-06-04 18:23:00 +0000139 return getCPersonality(Target, L);
John McCall5fb5df92012-06-20 06:18:46 +0000140 case ObjCRuntime::MacOSX:
141 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000142 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +0000143 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000144 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000145 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
146 return EHPersonality::GNUstep_ObjC;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000147 LLVM_FALLTHROUGH;
David Chisnallb601c962012-07-03 20:49:52 +0000148 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000149 case ObjCRuntime::ObjFW:
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000150 if (L.SjLjExceptions)
151 return EHPersonality::GNU_ObjC_SJLJ;
Martell Malonec950c652017-11-29 07:25:12 +0000152 if (L.SEHExceptions)
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000153 return EHPersonality::GNU_ObjC_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000154 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000155 }
John McCall5fb5df92012-06-20 06:18:46 +0000156 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000157}
158
Heejin Ahn00831792018-06-04 18:23:00 +0000159static const EHPersonality &getCXXPersonality(const TargetInfo &Target,
160 const LangOptions &L) {
161 const llvm::Triple &T = Target.getTriple();
Shoaib Meenaia5fc6032018-06-08 00:41:01 +0000162 if (T.isWindowsMSVCEnvironment())
163 return EHPersonality::MSVC_CxxFrameHandler3;
John McCall36ea3722010-07-17 00:43:08 +0000164 if (L.SjLjExceptions)
165 return EHPersonality::GNU_CPlusPlus_SJLJ;
Saleem Abdulrasool3e701322018-03-09 07:06:42 +0000166 if (L.DWARFExceptions)
167 return EHPersonality::GNU_CPlusPlus;
Martell Malonec950c652017-11-29 07:25:12 +0000168 if (L.SEHExceptions)
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000169 return EHPersonality::GNU_CPlusPlus_SEH;
Heejin Ahne8b2b882019-09-12 04:01:37 +0000170 if (L.WasmExceptions)
Heejin Ahnc6479192018-05-31 22:18:13 +0000171 return EHPersonality::GNU_Wasm_CPlusPlus;
Reid Klecknere070b992014-11-14 02:01:10 +0000172 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000173}
174
175/// Determines the personality function to use when both C++
176/// and Objective-C exceptions are being caught.
Heejin Ahn00831792018-06-04 18:23:00 +0000177static const EHPersonality &getObjCXXPersonality(const TargetInfo &Target,
178 const LangOptions &L) {
Shoaib Meenaia5fc6032018-06-08 00:41:01 +0000179 if (Target.getTriple().isWindowsMSVCEnvironment())
180 return EHPersonality::MSVC_CxxFrameHandler3;
181
John McCall5fb5df92012-06-20 06:18:46 +0000182 switch (L.ObjCRuntime.getKind()) {
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000183 // In the fragile ABI, just use C++ exception handling and hope
184 // they're not doing crazy exception mixing.
185 case ObjCRuntime::FragileMacOSX:
Heejin Ahn00831792018-06-04 18:23:00 +0000186 return getCXXPersonality(Target, L);
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000187
John McCallbd309292010-07-06 01:34:17 +0000188 // The ObjC personality defers to the C++ personality for non-ObjC
189 // handlers. Unlike the C++ case, we use the same personality
190 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000191 case ObjCRuntime::MacOSX:
192 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000193 case ObjCRuntime::WatchOS:
Heejin Ahn00831792018-06-04 18:23:00 +0000194 return getObjCPersonality(Target, L);
John McCallbd309292010-07-06 01:34:17 +0000195
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000196 case ObjCRuntime::GNUstep:
197 return EHPersonality::GNU_ObjCXX;
David Chisnallf9c42252010-05-17 13:49:20 +0000198
David Chisnallb601c962012-07-03 20:49:52 +0000199 // The GCC runtime's personality function inherently doesn't support
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000200 // mixed EH. Use the ObjC personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000201 case ObjCRuntime::GCC:
Benjamin Kramer9851cb72017-04-01 17:59:01 +0000202 case ObjCRuntime::ObjFW:
Heejin Ahn00831792018-06-04 18:23:00 +0000203 return getObjCPersonality(Target, L);
John McCall5fb5df92012-06-20 06:18:46 +0000204 }
205 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000206}
207
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000208static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000209 if (T.getArch() == llvm::Triple::x86)
210 return EHPersonality::MSVC_except_handler;
211 return EHPersonality::MSVC_C_specific_handler;
212}
213
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000214const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
215 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000216 const llvm::Triple &T = CGM.getTarget().getTriple();
217 const LangOptions &L = CGM.getLangOpts();
Heejin Ahn1eb074d2018-06-01 01:01:37 +0000218 const TargetInfo &Target = CGM.getTarget();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000219
Reid Kleckner01485652015-09-17 17:04:13 +0000220 // Functions using SEH get an SEH personality.
221 if (FD && FD->usesSEHTry())
222 return getSEHPersonalityMSVC(T);
223
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000224 if (L.ObjC)
Heejin Ahn00831792018-06-04 18:23:00 +0000225 return L.CPlusPlus ? getObjCXXPersonality(Target, L)
226 : getObjCPersonality(Target, L);
227 return L.CPlusPlus ? getCXXPersonality(Target, L)
228 : getCPersonality(Target, L);
John McCall36ea3722010-07-17 00:43:08 +0000229}
John McCallbd309292010-07-06 01:34:17 +0000230
David Majnemerc28d46e2015-07-22 23:46:21 +0000231const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
Reid Kleckner65fa8692017-10-13 16:55:14 +0000232 const auto *FD = CGF.CurCodeDecl;
233 // For outlined finallys and filters, use the SEH personality in case they
234 // contain more SEH. This mostly only affects finallys. Filters could
235 // hypothetically use gnu statement expressions to sneak in nested SEH.
236 FD = FD ? FD : CGF.CurSEHParent;
237 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(FD));
David Majnemerc28d46e2015-07-22 23:46:21 +0000238}
239
James Y Knight9871db02019-02-05 16:42:33 +0000240static llvm::FunctionCallee getPersonalityFn(CodeGenModule &CGM,
241 const EHPersonality &Personality) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +0000242 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
243 Personality.PersonalityFn,
Reid Klecknerde864822017-03-21 16:57:30 +0000244 llvm::AttributeList(), /*Local=*/true);
John McCall0bdb1fd2010-09-16 06:16:50 +0000245}
246
247static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
248 const EHPersonality &Personality) {
James Y Knight9871db02019-02-05 16:42:33 +0000249 llvm::FunctionCallee Fn = getPersonalityFn(CGM, Personality);
Dylan McKay02bbe412018-11-09 19:42:05 +0000250 llvm::PointerType* Int8PtrTy = llvm::PointerType::get(
251 llvm::Type::getInt8Ty(CGM.getLLVMContext()),
252 CGM.getDataLayout().getProgramAddressSpace());
253
James Y Knight9871db02019-02-05 16:42:33 +0000254 return llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(Fn.getCallee()),
255 Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000256}
257
Vedant Kumardb609472015-09-11 15:40:05 +0000258/// Check whether a landingpad instruction only uses C++ features.
259static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
260 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
261 // Look for something that would've been returned by the ObjC
262 // runtime's GetEHType() method.
263 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
264 if (LPI->isCatch(I)) {
265 // Check if the catch value has the ObjC prefix.
266 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
267 // ObjC EH selector entries are always global variables with
268 // names starting like this.
269 if (GV->getName().startswith("OBJC_EHTYPE"))
270 return false;
271 } else {
272 // Check if any of the filter values have the ObjC prefix.
273 llvm::Constant *CVal = cast<llvm::Constant>(Val);
274 for (llvm::User::op_iterator
275 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
276 if (llvm::GlobalVariable *GV =
277 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
278 // ObjC EH selector entries are always global variables with
279 // names starting like this.
280 if (GV->getName().startswith("OBJC_EHTYPE"))
281 return false;
282 }
283 }
284 }
285 return true;
286}
287
John McCall0bdb1fd2010-09-16 06:16:50 +0000288/// Check whether a personality function could reasonably be swapped
289/// for a C++ personality function.
290static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000291 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000292 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000293 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000294 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
295 if (!PersonalityHasOnlyCXXUses(CE))
296 return false;
297 continue;
298 }
299
Vedant Kumardb609472015-09-11 15:40:05 +0000300 // Otherwise it must be a function.
301 llvm::Function *F = dyn_cast<llvm::Function>(U);
302 if (!F) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000303
Vedant Kumardb609472015-09-11 15:40:05 +0000304 for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
305 if (BB->isLandingPad())
306 if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
307 return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000308 }
309 }
310
311 return true;
312}
313
314/// Try to use the C++ personality function in ObjC++. Not doing this
315/// can cause some incompatibilities with gcc, which is more
316/// aggressive about only using the ObjC++ personality in a function
317/// when it really needs it.
318void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000319 // If we're not in ObjC++ -fexceptions, there's nothing to do.
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000320 if (!LangOpts.CPlusPlus || !LangOpts.ObjC || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000321 return;
322
John McCall3c223932012-11-14 17:48:31 +0000323 // Both the problem this endeavors to fix and the way the logic
324 // above works is specific to the NeXT runtime.
325 if (!LangOpts.ObjCRuntime.isNeXTFamily())
326 return;
327
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000328 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Heejin Ahn00831792018-06-04 18:23:00 +0000329 const EHPersonality &CXX = getCXXPersonality(getTarget(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000330 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000331 return;
332
Benjamin Kramer793bd552012-02-08 12:41:24 +0000333 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
334 "Different EHPersonalities using the same personality function.");
335
336 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000337
338 // Nothing to do if it's unused.
339 if (!Fn || Fn->use_empty()) return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000340
John McCall0bdb1fd2010-09-16 06:16:50 +0000341 // Can't do the optimization if it has non-C++ uses.
342 if (!PersonalityHasOnlyCXXUses(Fn)) return;
343
344 // Create the C++ personality function and kill off the old
345 // function.
James Y Knight9871db02019-02-05 16:42:33 +0000346 llvm::FunctionCallee CXXFn = getPersonalityFn(*this, CXX);
John McCall0bdb1fd2010-09-16 06:16:50 +0000347
348 // This can happen if the user is screwing with us.
James Y Knight9871db02019-02-05 16:42:33 +0000349 if (Fn->getType() != CXXFn.getCallee()->getType())
350 return;
John McCall0bdb1fd2010-09-16 06:16:50 +0000351
James Y Knight9871db02019-02-05 16:42:33 +0000352 Fn->replaceAllUsesWith(CXXFn.getCallee());
John McCall0bdb1fd2010-09-16 06:16:50 +0000353 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000354}
355
356/// Returns the value to inject into a selector to indicate the
357/// presence of a catch-all.
358static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
359 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000360 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000361}
362
John McCallbb026012010-07-13 21:17:51 +0000363namespace {
364 /// A cleanup to free the exception object if its initialization
365 /// throws.
David Blaikie7e70d682015-08-18 22:40:54 +0000366 struct FreeException final : EHScopeStack::Cleanup {
John McCall5fcf8da2011-07-12 00:15:30 +0000367 llvm::Value *exn;
368 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000369 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000370 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000371 }
372 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000373} // end anonymous namespace
John McCallbb026012010-07-13 21:17:51 +0000374
John McCall2e6567a2010-04-22 01:10:34 +0000375// Emits an exception expression into the given location. This
376// differs from EmitAnyExprToMem only in that, if a final copy-ctor
377// call is required, an exception within that copy ctor causes
378// std::terminate to be invoked.
John McCall7f416cc2015-09-08 08:05:57 +0000379void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
John McCallbd309292010-07-06 01:34:17 +0000380 // Make sure the exception object is cleaned up if there's an
381 // exception during initialization.
John McCall7f416cc2015-09-08 08:05:57 +0000382 pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
David Majnemer7c237072015-03-05 00:46:22 +0000383 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000384
385 // __cxa_allocate_exception returns a void*; we need to cast this
386 // to the appropriate type for the object.
David Majnemer7c237072015-03-05 00:46:22 +0000387 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
John McCall7f416cc2015-09-08 08:05:57 +0000388 Address typedAddr = Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000389
390 // FIXME: this isn't quite right! If there's a final unelided call
391 // to a copy constructor, then according to [except.terminate]p1 we
392 // must call std::terminate() if that constructor throws, because
393 // technically that copy occurs after the exception expression is
394 // evaluated but before the exception is caught. But the best way
395 // to handle that is to teach EmitAggExpr to do the final copy
396 // differently if it can't be elided.
David Majnemer7c237072015-03-05 00:46:22 +0000397 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
398 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000399
John McCalle4df6c82011-01-28 08:37:24 +0000400 // Deactivate the cleanup block.
John McCall7f416cc2015-09-08 08:05:57 +0000401 DeactivateCleanupBlock(cleanup,
402 cast<llvm::Instruction>(typedAddr.getPointer()));
Mike Stump54066142009-12-01 03:41:18 +0000403}
404
John McCall7f416cc2015-09-08 08:05:57 +0000405Address CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000406 if (!ExceptionSlot)
407 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000408 return Address(ExceptionSlot, getPointerAlign());
Mike Stump54066142009-12-01 03:41:18 +0000409}
410
John McCall7f416cc2015-09-08 08:05:57 +0000411Address CodeGenFunction::getEHSelectorSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000412 if (!EHSelectorSlot)
413 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000414 return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
John McCall9b382dd2011-05-28 21:13:02 +0000415}
416
Bill Wendling79a70e42011-09-15 18:57:19 +0000417llvm::Value *CodeGenFunction::getExceptionFromSlot() {
418 return Builder.CreateLoad(getExceptionSlot(), "exn");
419}
420
421llvm::Value *CodeGenFunction::getSelectorFromSlot() {
422 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
423}
424
Richard Smithea852322013-05-07 21:53:22 +0000425void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
426 bool KeepInsertionPoint) {
David Majnemer7c237072015-03-05 00:46:22 +0000427 if (const Expr *SubExpr = E->getSubExpr()) {
428 QualType ThrowType = SubExpr->getType();
429 if (ThrowType->isObjCObjectPointerType()) {
430 const Stmt *ThrowStmt = E->getSubExpr();
431 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
432 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
433 } else {
434 CGM.getCXXABI().emitThrow(*this, E);
John McCall2e6567a2010-04-22 01:10:34 +0000435 }
David Majnemer7c237072015-03-05 00:46:22 +0000436 } else {
437 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000438 }
Mike Stump75546b82009-12-10 00:06:18 +0000439
John McCall20f6ab82011-01-12 03:41:02 +0000440 // throw is an expression, and the expression emitters expect us
441 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000442 if (KeepInsertionPoint)
443 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000444}
Mike Stump58ef18b2009-11-20 23:44:51 +0000445
Mike Stump1d849212009-12-07 23:38:24 +0000446void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000447 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000448 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000449
Mike Stump1d849212009-12-07 23:38:24 +0000450 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000451 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000452 // Check if CapturedDecl is nothrow and create terminate scope for it.
453 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
454 if (CD->isNothrow())
455 EHStack.pushTerminate();
456 }
Mike Stump1d849212009-12-07 23:38:24 +0000457 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000458 }
Mike Stump1d849212009-12-07 23:38:24 +0000459 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000460 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000461 return;
462
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000463 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
Richard Smitheaf11ad2018-05-03 03:58:32 +0000464 if (isNoexceptExceptionSpec(EST) && Proto->canThrow() == CT_Cannot) {
465 // noexcept functions are simple terminate scopes.
466 EHStack.pushTerminate();
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000467 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000468 // TODO: Revisit exception specifications for the MS ABI. There is a way to
469 // encode these in an object file but MSVC doesn't do anything with it.
470 if (getTarget().getCXXABI().isMicrosoft())
471 return;
Heejin Ahnd94bacb2020-05-08 16:19:46 -0700472 // In wasm we currently treat 'throw()' in the same way as 'noexcept'. In
473 // case of throw with types, we ignore it and print a warning for now.
474 // TODO Correctly handle exception specification in wasm
Heejin Ahn48acac32020-05-20 23:02:41 -0700475 if (CGM.getLangOpts().WasmExceptions) {
Heejin Ahnd94bacb2020-05-08 16:19:46 -0700476 if (EST == EST_DynamicNone)
477 EHStack.pushTerminate();
478 else
479 CGM.getDiags().Report(D->getLocation(),
480 diag::warn_wasm_dynamic_exception_spec_ignored)
481 << FD->getExceptionSpecSourceRange();
482 return;
483 }
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000484 unsigned NumExceptions = Proto->getNumExceptions();
485 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000486
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000487 for (unsigned I = 0; I != NumExceptions; ++I) {
488 QualType Ty = Proto->getExceptionType(I);
489 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
490 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
491 /*ForEH=*/true);
492 Filter->setFilter(I, EHType);
493 }
Mike Stump1d849212009-12-07 23:38:24 +0000494 }
Mike Stump1d849212009-12-07 23:38:24 +0000495}
496
John McCall8e4c74b2011-08-11 02:22:43 +0000497/// Emit the dispatch block for a filter scope if necessary.
498static void emitFilterDispatchBlock(CodeGenFunction &CGF,
499 EHFilterScope &filterScope) {
500 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
501 if (!dispatchBlock) return;
502 if (dispatchBlock->use_empty()) {
503 delete dispatchBlock;
504 return;
505 }
506
John McCall8e4c74b2011-08-11 02:22:43 +0000507 CGF.EmitBlockAfterUses(dispatchBlock);
508
509 // If this isn't a catch-all filter, we need to check whether we got
510 // here because the filter triggered.
511 if (filterScope.getNumFilters()) {
512 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000513 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000514 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
515
516 llvm::Value *zero = CGF.Builder.getInt32(0);
517 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000518 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
519 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
520 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000521
522 CGF.EmitBlock(unexpectedBB);
523 }
524
525 // Call __cxa_call_unexpected. This doesn't need to be an invoke
526 // because __cxa_call_unexpected magically filters exceptions
527 // according to the last landing pad the exception was thrown
528 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000529 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000530 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000531 ->setDoesNotReturn();
532 CGF.Builder.CreateUnreachable();
533}
534
Mike Stump1d849212009-12-07 23:38:24 +0000535void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000536 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000537 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000538
Mike Stump1d849212009-12-07 23:38:24 +0000539 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000540 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000541 // Check if CapturedDecl is nothrow and pop terminate scope for it.
542 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
543 if (CD->isNothrow())
544 EHStack.popTerminate();
545 }
Mike Stump1d849212009-12-07 23:38:24 +0000546 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000547 }
Mike Stump1d849212009-12-07 23:38:24 +0000548 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000549 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000550 return;
551
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000552 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
Richard Smitheaf11ad2018-05-03 03:58:32 +0000553 if (isNoexceptExceptionSpec(EST) && Proto->canThrow() == CT_Cannot) {
554 EHStack.popTerminate();
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000555 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000556 // TODO: Revisit exception specifications for the MS ABI. There is a way to
557 // encode these in an object file but MSVC doesn't do anything with it.
558 if (getTarget().getCXXABI().isMicrosoft())
559 return;
Heejin Ahnd94bacb2020-05-08 16:19:46 -0700560 // In wasm we currently treat 'throw()' in the same way as 'noexcept'. In
561 // case of throw with types, we ignore it and print a warning for now.
562 // TODO Correctly handle exception specification in wasm
Heejin Ahn48acac32020-05-20 23:02:41 -0700563 if (CGM.getLangOpts().WasmExceptions) {
Heejin Ahnd94bacb2020-05-08 16:19:46 -0700564 if (EST == EST_DynamicNone)
565 EHStack.popTerminate();
566 return;
567 }
John McCall8e4c74b2011-08-11 02:22:43 +0000568 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
569 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000570 EHStack.popFilter();
571 }
Mike Stump1d849212009-12-07 23:38:24 +0000572}
573
Mike Stump58ef18b2009-11-20 23:44:51 +0000574void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000575 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000576 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000577 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000578}
579
John McCallb609d3f2010-07-07 06:56:46 +0000580void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000581 unsigned NumHandlers = S.getNumHandlers();
582 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000583
John McCallbd309292010-07-06 01:34:17 +0000584 for (unsigned I = 0; I != NumHandlers; ++I) {
585 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000586
John McCallbd309292010-07-06 01:34:17 +0000587 llvm::BasicBlock *Handler = createBasicBlock("catch");
588 if (C->getExceptionDecl()) {
589 // FIXME: Dropping the reference type on the type into makes it
590 // impossible to correctly implement catch-by-reference
591 // semantics for pointers. Unfortunately, this is what all
592 // existing compilers do, and it's not clear that the standard
593 // personality routine is capable of doing this right. See C++ DR 388:
594 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000595 Qualifiers CaughtTypeQuals;
596 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
597 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000598
Reid Kleckner10aa7702015-09-16 20:15:55 +0000599 CatchTypeInfo TypeInfo{nullptr, 0};
John McCall2ca705e2010-07-24 00:37:23 +0000600 if (CaughtType->isObjCObjectPointerType())
Reid Kleckner10aa7702015-09-16 20:15:55 +0000601 TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000602 else
Reid Kleckner10aa7702015-09-16 20:15:55 +0000603 TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
604 CaughtType, C->getCaughtType());
John McCallbd309292010-07-06 01:34:17 +0000605 CatchScope->setHandler(I, TypeInfo, Handler);
606 } else {
607 // No exception decl indicates '...', a catch-all.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000608 CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
John McCallbd309292010-07-06 01:34:17 +0000609 }
610 }
John McCallbd309292010-07-06 01:34:17 +0000611}
612
John McCall8e4c74b2011-08-11 02:22:43 +0000613llvm::BasicBlock *
614CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
Reid Kleckner129552b2015-10-08 01:13:52 +0000615 if (EHPersonality::get(*this).usesFuncletPads())
Heejin Ahnc6479192018-05-31 22:18:13 +0000616 return getFuncletEHDispatchBlock(si);
David Majnemerdbf10452015-07-31 17:58:45 +0000617
John McCall8e4c74b2011-08-11 02:22:43 +0000618 // The dispatch block for the end of the scope chain is a block that
619 // just resumes unwinding.
620 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000621 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000622
623 // Otherwise, we should look at the actual scope.
624 EHScope &scope = *EHStack.find(si);
625
626 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
627 if (!dispatchBlock) {
628 switch (scope.getKind()) {
629 case EHScope::Catch: {
630 // Apply a special case to a single catch-all.
631 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
632 if (catchScope.getNumHandlers() == 1 &&
633 catchScope.getHandler(0).isCatchAll()) {
634 dispatchBlock = catchScope.getHandler(0).Block;
635
636 // Otherwise, make a dispatch block.
637 } else {
638 dispatchBlock = createBasicBlock("catch.dispatch");
639 }
640 break;
641 }
642
643 case EHScope::Cleanup:
644 dispatchBlock = createBasicBlock("ehcleanup");
645 break;
646
647 case EHScope::Filter:
648 dispatchBlock = createBasicBlock("filter.dispatch");
649 break;
650
651 case EHScope::Terminate:
652 dispatchBlock = getTerminateHandler();
653 break;
654 }
655 scope.setCachedEHDispatchBlock(dispatchBlock);
656 }
657 return dispatchBlock;
658}
659
David Majnemerdbf10452015-07-31 17:58:45 +0000660llvm::BasicBlock *
Heejin Ahnc6479192018-05-31 22:18:13 +0000661CodeGenFunction::getFuncletEHDispatchBlock(EHScopeStack::stable_iterator SI) {
David Majnemerdbf10452015-07-31 17:58:45 +0000662 // Returning nullptr indicates that the previous dispatch block should unwind
663 // to caller.
664 if (SI == EHStack.stable_end())
665 return nullptr;
666
667 // Otherwise, we should look at the actual scope.
668 EHScope &EHS = *EHStack.find(SI);
669
670 llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
671 if (DispatchBlock)
672 return DispatchBlock;
673
674 if (EHS.getKind() == EHScope::Terminate)
Reid Kleckner06f19a02018-01-02 21:34:16 +0000675 DispatchBlock = getTerminateFunclet();
David Majnemerdbf10452015-07-31 17:58:45 +0000676 else
677 DispatchBlock = createBasicBlock();
John McCall7f416cc2015-09-08 08:05:57 +0000678 CGBuilderTy Builder(*this, DispatchBlock);
David Majnemerdbf10452015-07-31 17:58:45 +0000679
680 switch (EHS.getKind()) {
681 case EHScope::Catch:
682 DispatchBlock->setName("catch.dispatch");
683 break;
684
685 case EHScope::Cleanup:
686 DispatchBlock->setName("ehcleanup");
687 break;
688
689 case EHScope::Filter:
690 llvm_unreachable("exception specifications not handled yet!");
691
692 case EHScope::Terminate:
693 DispatchBlock->setName("terminate");
694 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000695 }
696 EHS.setCachedEHDispatchBlock(DispatchBlock);
697 return DispatchBlock;
698}
699
John McCallbd309292010-07-06 01:34:17 +0000700/// Check whether this is a non-EH scope, i.e. a scope which doesn't
701/// affect exception handling. Currently, the only non-EH scopes are
702/// normal-only cleanup scopes.
703static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000704 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000705 case EHScope::Cleanup:
706 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000707 case EHScope::Filter:
708 case EHScope::Catch:
709 case EHScope::Terminate:
710 return false;
711 }
712
David Blaikiee4d798f2012-01-20 21:50:17 +0000713 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000714}
715
716llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
717 assert(EHStack.requiresLandingPad());
718 assert(!EHStack.empty());
719
jasonliu55e26782020-02-11 09:52:56 +0000720 // If exceptions are disabled/ignored and SEH is not in use, then there is no
721 // invoke destination. SEH "works" even if exceptions are off. In practice,
722 // this means that C++ destructors and other EH cleanups don't run, which is
Reid Kleckner8f1b1f52016-03-01 19:51:48 +0000723 // consistent with MSVC's behavior.
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000724 const LangOptions &LO = CGM.getLangOpts();
jasonliu55e26782020-02-11 09:52:56 +0000725 if (!LO.Exceptions || LO.IgnoreExceptions) {
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000726 if (!LO.Borland && !LO.MicrosoftExt)
727 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000728 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000729 return nullptr;
730 }
John McCall2b7fc382010-07-13 20:32:21 +0000731
Justin Lebar3e6449b2016-10-04 23:41:49 +0000732 // CUDA device code doesn't have exceptions.
733 if (LO.CUDA && LO.CUDAIsDevice)
734 return nullptr;
735
John McCallbd309292010-07-06 01:34:17 +0000736 // Check the innermost scope for a cached landing pad. If this is
737 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
738 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
739 if (LP) return LP;
740
David Majnemerdbf10452015-07-31 17:58:45 +0000741 const EHPersonality &Personality = EHPersonality::get(*this);
742
743 if (!CurFn->hasPersonalityFn())
744 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
745
Reid Kleckner129552b2015-10-08 01:13:52 +0000746 if (Personality.usesFuncletPads()) {
747 // We don't need separate landing pads in the funclet model.
David Majnemerdbf10452015-07-31 17:58:45 +0000748 LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
749 } else {
750 // Build the landing pad for this scope.
751 LP = EmitLandingPad();
752 }
753
John McCallbd309292010-07-06 01:34:17 +0000754 assert(LP);
755
756 // Cache the landing pad on the innermost scope. If this is a
757 // non-EH scope, cache the landing pad on the enclosing scope, too.
758 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
759 ir->setCachedLandingPad(LP);
760 if (!isNonEHScope(*ir)) break;
761 }
762
763 return LP;
764}
765
766llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
767 assert(EHStack.requiresLandingPad());
jasonliu55e26782020-02-11 09:52:56 +0000768 assert(!CGM.getLangOpts().IgnoreExceptions &&
769 "LandingPad should not be emitted when -fignore-exceptions are in "
770 "effect.");
John McCall8e4c74b2011-08-11 02:22:43 +0000771 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
772 switch (innermostEHScope.getKind()) {
773 case EHScope::Terminate:
774 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000775
John McCall8e4c74b2011-08-11 02:22:43 +0000776 case EHScope::Catch:
777 case EHScope::Cleanup:
778 case EHScope::Filter:
779 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
780 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000781 }
782
783 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000784 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Calixte Denizetfcd661d2018-09-24 18:24:18 +0000785 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000786
787 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000788 llvm::BasicBlock *lpad = createBasicBlock("lpad");
789 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000790
Serge Guelton1d993272017-05-09 19:31:30 +0000791 llvm::LandingPadInst *LPadInst =
792 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +0000793
794 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
795 Builder.CreateStore(LPadExn, getExceptionSlot());
796 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
797 Builder.CreateStore(LPadSel, getEHSelectorSlot());
798
John McCallbd309292010-07-06 01:34:17 +0000799 // Save the exception pointer. It's safe to use a single exception
800 // pointer per function because EH cleanups can never have nested
801 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000802 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000803
804 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000805 bool hasCatchAll = false;
806 bool hasCleanup = false;
807 bool hasFilter = false;
808 SmallVector<llvm::Value*, 4> filterTypes;
809 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Nico Webere68b9f32015-02-25 16:25:00 +0000810 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
811 ++I) {
John McCallbd309292010-07-06 01:34:17 +0000812
813 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000814 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000815 // If we have a cleanup, remember that.
816 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000817 continue;
818
John McCallbd309292010-07-06 01:34:17 +0000819 case EHScope::Filter: {
820 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000821 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000822
Bill Wendlingf0724e82011-09-19 20:31:14 +0000823 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000824 EHFilterScope &filter = cast<EHFilterScope>(*I);
825 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000826
Bill Wendling8c4b7162011-09-22 20:32:54 +0000827 // Add all the filter values.
828 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
829 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000830 goto done;
831 }
832
833 case EHScope::Terminate:
834 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000835 assert(!hasCatchAll);
836 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000837 goto done;
838
839 case EHScope::Catch:
840 break;
841 }
842
John McCall8e4c74b2011-08-11 02:22:43 +0000843 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
844 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
845 EHCatchScope::Handler handler = catchScope.getHandler(hi);
Reid Kleckner10aa7702015-09-16 20:15:55 +0000846 assert(handler.Type.Flags == 0 &&
847 "landingpads do not support catch handler flags");
John McCallbd309292010-07-06 01:34:17 +0000848
John McCall8e4c74b2011-08-11 02:22:43 +0000849 // If this is a catch-all, register that and abort.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000850 if (!handler.Type.RTTI) {
John McCall8e4c74b2011-08-11 02:22:43 +0000851 assert(!hasCatchAll);
852 hasCatchAll = true;
853 goto done;
John McCallbd309292010-07-06 01:34:17 +0000854 }
855
856 // Check whether we already have a handler for this type.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000857 if (catchTypes.insert(handler.Type.RTTI).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000858 // If not, add it directly to the landingpad.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000859 LPadInst->addClause(handler.Type.RTTI);
John McCallbd309292010-07-06 01:34:17 +0000860 }
John McCallbd309292010-07-06 01:34:17 +0000861 }
862
863 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000864 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000865 assert(!(hasCatchAll && hasFilter));
866 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000867 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000868
869 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000870 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000871 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000872 // Create a filter expression: a constant array indicating which filter
873 // types there are. The personality routine only lands here if the filter
874 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000875 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000876 llvm::ArrayType *AType =
877 llvm::ArrayType::get(!filterTypes.empty() ?
878 filterTypes[0]->getType() : Int8PtrTy,
879 filterTypes.size());
880
881 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
882 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
883 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
884 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000885
886 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000887 if (hasCleanup)
888 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000889
890 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000891 } else if (hasCleanup) {
892 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000893 }
894
Bill Wendlingf0724e82011-09-19 20:31:14 +0000895 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
896 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000897
898 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000899 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000900
901 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000902 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000903
John McCall8e4c74b2011-08-11 02:22:43 +0000904 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000905}
906
David Majnemer4e52d6f2015-12-12 05:39:21 +0000907static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
David Majnemerdbf10452015-07-31 17:58:45 +0000908 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
909 assert(DispatchBlock);
910
911 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
912 CGF.EmitBlockAfterUses(DispatchBlock);
913
David Majnemer4e52d6f2015-12-12 05:39:21 +0000914 llvm::Value *ParentPad = CGF.CurrentFuncletPad;
915 if (!ParentPad)
916 ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
917 llvm::BasicBlock *UnwindBB =
918 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
919
920 unsigned NumHandlers = CatchScope.getNumHandlers();
921 llvm::CatchSwitchInst *CatchSwitch =
922 CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
David Majnemerdbf10452015-07-31 17:58:45 +0000923
924 // Test against each of the exception types we claim to catch.
David Majnemer4e52d6f2015-12-12 05:39:21 +0000925 for (unsigned I = 0; I < NumHandlers; ++I) {
David Majnemerdbf10452015-07-31 17:58:45 +0000926 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
927
Reid Kleckner10aa7702015-09-16 20:15:55 +0000928 CatchTypeInfo TypeInfo = Handler.Type;
929 if (!TypeInfo.RTTI)
930 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
David Majnemerdbf10452015-07-31 17:58:45 +0000931
David Majnemer4e52d6f2015-12-12 05:39:21 +0000932 CGF.Builder.SetInsertPoint(Handler.Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000933
934 if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000935 CGF.Builder.CreateCatchPad(
936 CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
937 llvm::Constant::getNullValue(CGF.VoidPtrTy)});
David Majnemerdbf10452015-07-31 17:58:45 +0000938 } else {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000939 CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
David Majnemerdbf10452015-07-31 17:58:45 +0000940 }
941
David Majnemer4e52d6f2015-12-12 05:39:21 +0000942 CatchSwitch->addHandler(Handler.Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000943 }
944 CGF.Builder.restoreIP(SavedIP);
David Majnemerdbf10452015-07-31 17:58:45 +0000945}
946
Heejin Ahnc6479192018-05-31 22:18:13 +0000947// Wasm uses Windows-style EH instructions, but it merges all catch clauses into
948// one big catchpad, within which we use Itanium's landingpad-style selector
949// comparison instructions.
950static void emitWasmCatchPadBlock(CodeGenFunction &CGF,
951 EHCatchScope &CatchScope) {
952 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
953 assert(DispatchBlock);
954
955 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
956 CGF.EmitBlockAfterUses(DispatchBlock);
957
958 llvm::Value *ParentPad = CGF.CurrentFuncletPad;
959 if (!ParentPad)
960 ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
961 llvm::BasicBlock *UnwindBB =
962 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
963
964 unsigned NumHandlers = CatchScope.getNumHandlers();
965 llvm::CatchSwitchInst *CatchSwitch =
966 CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
967
968 // We don't use a landingpad instruction, so generate intrinsic calls to
969 // provide exception and selector values.
970 llvm::BasicBlock *WasmCatchStartBlock = CGF.createBasicBlock("catch.start");
971 CatchSwitch->addHandler(WasmCatchStartBlock);
972 CGF.EmitBlockAfterUses(WasmCatchStartBlock);
973
974 // Create a catchpad instruction.
975 SmallVector<llvm::Value *, 4> CatchTypes;
976 for (unsigned I = 0, E = NumHandlers; I < E; ++I) {
977 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
978 CatchTypeInfo TypeInfo = Handler.Type;
979 if (!TypeInfo.RTTI)
980 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
981 CatchTypes.push_back(TypeInfo.RTTI);
982 }
983 auto *CPI = CGF.Builder.CreateCatchPad(CatchSwitch, CatchTypes);
984
985 // Create calls to wasm.get.exception and wasm.get.ehselector intrinsics.
986 // Before they are lowered appropriately later, they provide values for the
987 // exception and selector.
James Y Knight8799cae2019-02-03 21:53:49 +0000988 llvm::Function *GetExnFn =
Heejin Ahnc6479192018-05-31 22:18:13 +0000989 CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
James Y Knight8799cae2019-02-03 21:53:49 +0000990 llvm::Function *GetSelectorFn =
Heejin Ahnc6479192018-05-31 22:18:13 +0000991 CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_ehselector);
992 llvm::CallInst *Exn = CGF.Builder.CreateCall(GetExnFn, CPI);
993 CGF.Builder.CreateStore(Exn, CGF.getExceptionSlot());
994 llvm::CallInst *Selector = CGF.Builder.CreateCall(GetSelectorFn, CPI);
995
James Y Knight8799cae2019-02-03 21:53:49 +0000996 llvm::Function *TypeIDFn = CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
Heejin Ahnc6479192018-05-31 22:18:13 +0000997
998 // If there's only a single catch-all, branch directly to its handler.
999 if (CatchScope.getNumHandlers() == 1 &&
1000 CatchScope.getHandler(0).isCatchAll()) {
1001 CGF.Builder.CreateBr(CatchScope.getHandler(0).Block);
1002 CGF.Builder.restoreIP(SavedIP);
1003 return;
1004 }
1005
1006 // Test against each of the exception types we claim to catch.
1007 for (unsigned I = 0, E = NumHandlers;; ++I) {
1008 assert(I < E && "ran off end of handlers!");
1009 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
1010 CatchTypeInfo TypeInfo = Handler.Type;
1011 if (!TypeInfo.RTTI)
1012 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
1013
1014 // Figure out the next block.
1015 llvm::BasicBlock *NextBlock;
1016
1017 bool EmitNextBlock = false, NextIsEnd = false;
1018
1019 // If this is the last handler, we're at the end, and the next block is a
1020 // block that contains a call to the rethrow function, so we can unwind to
1021 // the enclosing EH scope. The call itself will be generated later.
1022 if (I + 1 == E) {
1023 NextBlock = CGF.createBasicBlock("rethrow");
1024 EmitNextBlock = true;
1025 NextIsEnd = true;
1026
1027 // If the next handler is a catch-all, we're at the end, and the
1028 // next block is that handler.
1029 } else if (CatchScope.getHandler(I + 1).isCatchAll()) {
1030 NextBlock = CatchScope.getHandler(I + 1).Block;
1031 NextIsEnd = true;
1032
1033 // Otherwise, we're not at the end and we need a new block.
1034 } else {
1035 NextBlock = CGF.createBasicBlock("catch.fallthrough");
1036 EmitNextBlock = true;
1037 }
1038
1039 // Figure out the catch type's index in the LSDA's type table.
1040 llvm::CallInst *TypeIndex = CGF.Builder.CreateCall(TypeIDFn, TypeInfo.RTTI);
1041 TypeIndex->setDoesNotThrow();
1042
1043 llvm::Value *MatchesTypeIndex =
1044 CGF.Builder.CreateICmpEQ(Selector, TypeIndex, "matches");
1045 CGF.Builder.CreateCondBr(MatchesTypeIndex, Handler.Block, NextBlock);
1046
1047 if (EmitNextBlock)
1048 CGF.EmitBlock(NextBlock);
1049 if (NextIsEnd)
1050 break;
1051 }
1052
1053 CGF.Builder.restoreIP(SavedIP);
1054}
1055
John McCall8e4c74b2011-08-11 02:22:43 +00001056/// Emit the structure of the dispatch block for the given catch scope.
1057/// It is an invariant that the dispatch block already exists.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001058static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1059 EHCatchScope &catchScope) {
Heejin Ahnc6479192018-05-31 22:18:13 +00001060 if (EHPersonality::get(CGF).isWasmPersonality())
1061 return emitWasmCatchPadBlock(CGF, catchScope);
Reid Kleckner129552b2015-10-08 01:13:52 +00001062 if (EHPersonality::get(CGF).usesFuncletPads())
1063 return emitCatchPadBlock(CGF, catchScope);
David Majnemerdbf10452015-07-31 17:58:45 +00001064
John McCall8e4c74b2011-08-11 02:22:43 +00001065 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1066 assert(dispatchBlock);
1067
1068 // If there's only a single catch-all, getEHDispatchBlock returned
1069 // that catch-all as the dispatch block.
1070 if (catchScope.getNumHandlers() == 1 &&
1071 catchScope.getHandler(0).isCatchAll()) {
1072 assert(dispatchBlock == catchScope.getHandler(0).Block);
David Majnemer4e52d6f2015-12-12 05:39:21 +00001073 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001074 }
1075
1076 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1077 CGF.EmitBlockAfterUses(dispatchBlock);
1078
1079 // Select the right handler.
James Y Knight8799cae2019-02-03 21:53:49 +00001080 llvm::Function *llvm_eh_typeid_for =
John McCall8e4c74b2011-08-11 02:22:43 +00001081 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1082
1083 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +00001084 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +00001085
1086 // Test against each of the exception types we claim to catch.
1087 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1088 assert(i < e && "ran off end of handlers!");
1089 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1090
Reid Kleckner10aa7702015-09-16 20:15:55 +00001091 llvm::Value *typeValue = handler.Type.RTTI;
1092 assert(handler.Type.Flags == 0 &&
1093 "landingpads do not support catch handler flags");
John McCall8e4c74b2011-08-11 02:22:43 +00001094 assert(typeValue && "fell into catch-all case!");
1095 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1096
1097 // Figure out the next block.
1098 bool nextIsEnd;
1099 llvm::BasicBlock *nextBlock;
1100
1101 // If this is the last handler, we're at the end, and the next
1102 // block is the block for the enclosing EH scope.
1103 if (i + 1 == e) {
1104 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1105 nextIsEnd = true;
1106
1107 // If the next handler is a catch-all, we're at the end, and the
1108 // next block is that handler.
1109 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1110 nextBlock = catchScope.getHandler(i+1).Block;
1111 nextIsEnd = true;
1112
1113 // Otherwise, we're not at the end and we need a new block.
1114 } else {
1115 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1116 nextIsEnd = false;
1117 }
1118
1119 // Figure out the catch type's index in the LSDA's type table.
1120 llvm::CallInst *typeIndex =
1121 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1122 typeIndex->setDoesNotThrow();
1123
1124 llvm::Value *matchesTypeIndex =
1125 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1126 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1127
1128 // If the next handler is a catch-all, we're completely done.
1129 if (nextIsEnd) {
1130 CGF.Builder.restoreIP(savedIP);
David Majnemer4e52d6f2015-12-12 05:39:21 +00001131 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001132 }
Ahmed Charles289896d2012-02-19 11:57:29 +00001133 // Otherwise we need to emit and continue at that block.
1134 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +00001135 }
John McCall8e4c74b2011-08-11 02:22:43 +00001136}
1137
1138void CodeGenFunction::popCatchScope() {
1139 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1140 if (catchScope.hasEHBranches())
1141 emitCatchDispatchBlock(*this, catchScope);
1142 EHStack.popCatch();
1143}
1144
John McCallb609d3f2010-07-07 06:56:46 +00001145void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001146 unsigned NumHandlers = S.getNumHandlers();
1147 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1148 assert(CatchScope.getNumHandlers() == NumHandlers);
Heejin Ahnc6479192018-05-31 22:18:13 +00001149 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
Mike Stump58ef18b2009-11-20 23:44:51 +00001150
John McCall8e4c74b2011-08-11 02:22:43 +00001151 // If the catch was not required, bail out now.
1152 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001153 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001154 EHStack.popCatch();
1155 return;
1156 }
1157
1158 // Emit the structure of the EH dispatch for this catch.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001159 emitCatchDispatchBlock(*this, CatchScope);
John McCall8e4c74b2011-08-11 02:22:43 +00001160
John McCallbd309292010-07-06 01:34:17 +00001161 // Copy the handler blocks off before we pop the EH stack. Emitting
1162 // the handlers might scribble on this memory.
Benjamin Kramerda32cf82015-08-04 15:38:49 +00001163 SmallVector<EHCatchScope::Handler, 8> Handlers(
1164 CatchScope.begin(), CatchScope.begin() + NumHandlers);
John McCall8e4c74b2011-08-11 02:22:43 +00001165
John McCallbd309292010-07-06 01:34:17 +00001166 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001167
John McCallbd309292010-07-06 01:34:17 +00001168 // The fall-through block.
1169 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001170
John McCallbd309292010-07-06 01:34:17 +00001171 // We just emitted the body of the try; jump to the continue block.
1172 if (HaveInsertPoint())
1173 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001174
John McCalld8d00be2012-06-15 05:27:05 +00001175 // Determine if we need an implicit rethrow for all these catch handlers;
1176 // see the comment below.
1177 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001178 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001179 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1180 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001181
Heejin Ahnc6479192018-05-31 22:18:13 +00001182 // Wasm uses Windows-style EH instructions, but merges all catch clauses into
1183 // one big catchpad. So we save the old funclet pad here before we traverse
1184 // each catch handler.
1185 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1186 CurrentFuncletPad);
1187 llvm::BasicBlock *WasmCatchStartBlock = nullptr;
1188 if (EHPersonality::get(*this).isWasmPersonality()) {
1189 auto *CatchSwitch =
1190 cast<llvm::CatchSwitchInst>(DispatchBlock->getFirstNonPHI());
1191 WasmCatchStartBlock = CatchSwitch->hasUnwindDest()
1192 ? CatchSwitch->getSuccessor(1)
1193 : CatchSwitch->getSuccessor(0);
1194 auto *CPI = cast<llvm::CatchPadInst>(WasmCatchStartBlock->getFirstNonPHI());
1195 CurrentFuncletPad = CPI;
1196 }
1197
John McCall8e4c74b2011-08-11 02:22:43 +00001198 // Perversely, we emit the handlers backwards precisely because we
1199 // want them to appear in source order. In all of these cases, the
1200 // catch block will have exactly one predecessor, which will be a
1201 // particular block in the catch dispatch. However, in the case of
1202 // a catch-all, one of the dispatch blocks will branch to two
1203 // different handlers, and EmitBlockAfterUses will cause the second
1204 // handler to be moved before the first.
Heejin Ahnc6479192018-05-31 22:18:13 +00001205 bool HasCatchAll = false;
John McCall8e4c74b2011-08-11 02:22:43 +00001206 for (unsigned I = NumHandlers; I != 0; --I) {
Heejin Ahnc6479192018-05-31 22:18:13 +00001207 HasCatchAll |= Handlers[I - 1].isCatchAll();
John McCall8e4c74b2011-08-11 02:22:43 +00001208 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1209 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001210
John McCallbd309292010-07-06 01:34:17 +00001211 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001212 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001213
John McCallbd309292010-07-06 01:34:17 +00001214 // Enter a cleanup scope, including the catch variable and the
1215 // end-catch.
1216 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001217
John McCallbd309292010-07-06 01:34:17 +00001218 // Initialize the catch variable and set up the cleanups.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001219 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1220 CurrentFuncletPad);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001221 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallbd309292010-07-06 01:34:17 +00001222
Justin Bognerea278c32014-01-07 00:20:28 +00001223 // Emit the PGO counter increment.
Justin Bogner66242d62015-04-23 23:06:47 +00001224 incrementProfileCounter(C);
Justin Bogneref512b92014-01-06 22:27:43 +00001225
John McCallbd309292010-07-06 01:34:17 +00001226 // Perform the body of the catch.
1227 EmitStmt(C->getHandlerBlock());
1228
John McCalld8d00be2012-06-15 05:27:05 +00001229 // [except.handle]p11:
1230 // The currently handled exception is rethrown if control
1231 // reaches the end of a handler of the function-try-block of a
1232 // constructor or destructor.
1233
1234 // It is important that we only do this on fallthrough and not on
1235 // return. Note that it's illegal to put a return in a
1236 // constructor function-try-block's catch handler (p14), so this
1237 // really only applies to destructors.
1238 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +00001239 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +00001240 Builder.CreateUnreachable();
1241 Builder.ClearInsertionPoint();
1242 }
1243
John McCallbd309292010-07-06 01:34:17 +00001244 // Fall out through the catch cleanups.
1245 CatchScope.ForceCleanup();
1246
1247 // Branch out of the try.
1248 if (HaveInsertPoint())
1249 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001250 }
1251
Heejin Ahnc6479192018-05-31 22:18:13 +00001252 // Because in wasm we merge all catch clauses into one big catchpad, in case
1253 // none of the types in catch handlers matches after we test against each of
1254 // them, we should unwind to the next EH enclosing scope. We generate a call
1255 // to rethrow function here to do that.
1256 if (EHPersonality::get(*this).isWasmPersonality() && !HasCatchAll) {
1257 assert(WasmCatchStartBlock);
1258 // Navigate for the "rethrow" block we created in emitWasmCatchPadBlock().
1259 // Wasm uses landingpad-style conditional branches to compare selectors, so
1260 // we follow the false destination for each of the cond branches to reach
1261 // the rethrow block.
1262 llvm::BasicBlock *RethrowBlock = WasmCatchStartBlock;
Chandler Carruthe303c872018-10-15 10:42:50 +00001263 while (llvm::Instruction *TI = RethrowBlock->getTerminator()) {
Heejin Ahnc6479192018-05-31 22:18:13 +00001264 auto *BI = cast<llvm::BranchInst>(TI);
1265 assert(BI->isConditional());
1266 RethrowBlock = BI->getSuccessor(1);
1267 }
1268 assert(RethrowBlock != WasmCatchStartBlock && RethrowBlock->empty());
1269 Builder.SetInsertPoint(RethrowBlock);
Heejin Ahn7e66a502019-03-16 05:39:12 +00001270 llvm::Function *RethrowInCatchFn =
1271 CGM.getIntrinsic(llvm::Intrinsic::wasm_rethrow_in_catch);
1272 EmitNoreturnRuntimeCallOrInvoke(RethrowInCatchFn, {});
Heejin Ahnc6479192018-05-31 22:18:13 +00001273 }
1274
John McCallbd309292010-07-06 01:34:17 +00001275 EmitBlock(ContBB);
Justin Bogner66242d62015-04-23 23:06:47 +00001276 incrementProfileCounter(&S);
Mike Stump58ef18b2009-11-20 23:44:51 +00001277}
Mike Stumpaff69af2009-12-09 03:35:49 +00001278
John McCall1e670402010-07-21 00:52:03 +00001279namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001280 struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001281 llvm::Value *ForEHVar;
James Y Knight9871db02019-02-05 16:42:33 +00001282 llvm::FunctionCallee EndCatchFn;
1283 CallEndCatchForFinally(llvm::Value *ForEHVar,
1284 llvm::FunctionCallee EndCatchFn)
1285 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
John McCall1e670402010-07-21 00:52:03 +00001286
Craig Topper4f12f102014-03-12 06:41:41 +00001287 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001288 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1289 llvm::BasicBlock *CleanupContBB =
1290 CGF.createBasicBlock("finally.cleanup.cont");
1291
1292 llvm::Value *ShouldEndCatch =
John McCall7f416cc2015-09-08 08:05:57 +00001293 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
John McCall1e670402010-07-21 00:52:03 +00001294 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1295 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001296 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001297 CGF.EmitBlock(CleanupContBB);
1298 }
1299 };
John McCall906da4b2010-07-21 05:47:49 +00001300
David Blaikie7e70d682015-08-18 22:40:54 +00001301 struct PerformFinally final : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001302 const Stmt *Body;
1303 llvm::Value *ForEHVar;
James Y Knight9871db02019-02-05 16:42:33 +00001304 llvm::FunctionCallee EndCatchFn;
1305 llvm::FunctionCallee RethrowFn;
John McCall906da4b2010-07-21 05:47:49 +00001306 llvm::Value *SavedExnVar;
1307
1308 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
James Y Knight9871db02019-02-05 16:42:33 +00001309 llvm::FunctionCallee EndCatchFn,
1310 llvm::FunctionCallee RethrowFn, llvm::Value *SavedExnVar)
1311 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1312 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
John McCall906da4b2010-07-21 05:47:49 +00001313
Craig Topper4f12f102014-03-12 06:41:41 +00001314 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001315 // Enter a cleanup to call the end-catch function if one was provided.
1316 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001317 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1318 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001319
John McCallcebe0ca2010-08-11 00:16:14 +00001320 // Save the current cleanup destination in case there are
1321 // cleanups in the finally block.
1322 llvm::Value *SavedCleanupDest =
1323 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1324 "cleanup.dest.saved");
1325
John McCall906da4b2010-07-21 05:47:49 +00001326 // Emit the finally block.
1327 CGF.EmitStmt(Body);
1328
1329 // If the end of the finally is reachable, check whether this was
1330 // for EH. If so, rethrow.
1331 if (CGF.HaveInsertPoint()) {
1332 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1333 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1334
1335 llvm::Value *ShouldRethrow =
John McCall7f416cc2015-09-08 08:05:57 +00001336 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
John McCall906da4b2010-07-21 05:47:49 +00001337 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1338
1339 CGF.EmitBlock(RethrowBB);
1340 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001341 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
John McCall7f416cc2015-09-08 08:05:57 +00001342 CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
John McCall906da4b2010-07-21 05:47:49 +00001343 } else {
John McCall882987f2013-02-28 19:01:20 +00001344 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001345 }
1346 CGF.Builder.CreateUnreachable();
1347
1348 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001349
1350 // Restore the cleanup destination.
1351 CGF.Builder.CreateStore(SavedCleanupDest,
1352 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001353 }
1354
1355 // Leave the end-catch cleanup. As an optimization, pretend that
1356 // the fallthrough path was inaccessible; we've dynamically proven
1357 // that we're not in the EH case along that path.
1358 if (EndCatchFn) {
1359 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1360 CGF.PopCleanupBlock();
1361 CGF.Builder.restoreIP(SavedIP);
1362 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001363
John McCall906da4b2010-07-21 05:47:49 +00001364 // Now make sure we actually have an insertion point or the
1365 // cleanup gods will hate us.
1366 CGF.EnsureInsertPoint();
1367 }
1368 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001369} // end anonymous namespace
John McCall1e670402010-07-21 00:52:03 +00001370
John McCallbd309292010-07-06 01:34:17 +00001371/// Enters a finally block for an implementation using zero-cost
1372/// exceptions. This is mostly general, but hard-codes some
1373/// language/ABI-specific behavior in the catch-all sections.
James Y Knight9871db02019-02-05 16:42:33 +00001374void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF, const Stmt *body,
1375 llvm::FunctionCallee beginCatchFn,
1376 llvm::FunctionCallee endCatchFn,
1377 llvm::FunctionCallee rethrowFn) {
1378 assert((!!beginCatchFn) == (!!endCatchFn) &&
John McCallbd309292010-07-06 01:34:17 +00001379 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001380 assert(rethrowFn && "rethrow function is required");
1381
1382 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001383
John McCallbd309292010-07-06 01:34:17 +00001384 // The rethrow function has one of the following two types:
1385 // void (*)()
1386 // void (*)(void*)
1387 // In the latter case we need to pass it the exception object.
1388 // But we can't use the exception slot because the @finally might
1389 // have a landing pad (which would overwrite the exception slot).
James Y Knight9871db02019-02-05 16:42:33 +00001390 llvm::FunctionType *rethrowFnTy = rethrowFn.getFunctionType();
Craig Topper8a13c412014-05-21 05:09:00 +00001391 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001392 if (rethrowFnTy->getNumParams())
1393 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001394
John McCallbd309292010-07-06 01:34:17 +00001395 // A finally block is a statement which must be executed on any edge
1396 // out of a given scope. Unlike a cleanup, the finally block may
1397 // contain arbitrary control flow leading out of itself. In
1398 // addition, finally blocks should always be executed, even if there
1399 // are no catch handlers higher on the stack. Therefore, we
1400 // surround the protected scope with a combination of a normal
1401 // cleanup (to catch attempts to break out of the block via normal
1402 // control flow) and an EH catch-all (semantically "outside" any try
1403 // statement to which the finally block might have been attached).
1404 // The finally block itself is generated in the context of a cleanup
1405 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001406
John McCallbd309292010-07-06 01:34:17 +00001407 // Jump destination for performing the finally block on an exception
1408 // edge. We'll never actually reach this block, so unreachable is
1409 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001410 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001411
John McCallbd309292010-07-06 01:34:17 +00001412 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001413 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
John McCall7f416cc2015-09-08 08:05:57 +00001414 CGF.Builder.CreateFlagStore(false, ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001415
John McCallbd309292010-07-06 01:34:17 +00001416 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001417 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1418 ForEHVar, endCatchFn,
1419 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001420
1421 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001422 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1423 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1424 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001425}
1426
John McCall6b0feb72011-06-22 02:32:12 +00001427void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001428 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001429 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1430 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001431
1432 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001433
John McCall6b0feb72011-06-22 02:32:12 +00001434 // If there are any references to the catch-all block, emit it.
1435 if (catchBB->use_empty()) {
1436 delete catchBB;
1437 } else {
1438 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1439 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001440
Craig Topper8a13c412014-05-21 05:09:00 +00001441 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001442
John McCall6b0feb72011-06-22 02:32:12 +00001443 // If there's a begin-catch function, call it.
1444 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001445 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001446 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001447 }
1448
1449 // If we need to remember the exception pointer to rethrow later, do so.
1450 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001451 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall7f416cc2015-09-08 08:05:57 +00001452 CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
John McCall6b0feb72011-06-22 02:32:12 +00001453 }
1454
1455 // Tell the cleanups in the finally block that we're do this for EH.
John McCall7f416cc2015-09-08 08:05:57 +00001456 CGF.Builder.CreateFlagStore(true, ForEHVar);
John McCall6b0feb72011-06-22 02:32:12 +00001457
1458 // Thread a jump through the finally cleanup.
1459 CGF.EmitBranchThroughCleanup(RethrowDest);
1460
1461 CGF.Builder.restoreIP(savedIP);
1462 }
1463
1464 // Finally, leave the @finally cleanup.
1465 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001466}
1467
1468llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1469 if (TerminateLandingPad)
1470 return TerminateLandingPad;
1471
1472 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1473
1474 // This will get inserted at the end of the function.
1475 TerminateLandingPad = createBasicBlock("terminate.lpad");
1476 Builder.SetInsertPoint(TerminateLandingPad);
1477
1478 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001479 const EHPersonality &Personality = EHPersonality::get(*this);
David Majnemerfcbdb6e2015-06-17 20:53:19 +00001480
1481 if (!CurFn->hasPersonalityFn())
1482 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1483
Serge Guelton1d993272017-05-09 19:31:30 +00001484 llvm::LandingPadInst *LPadInst =
1485 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001486 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001487
Hans Wennborgdcfba332015-10-06 23:40:43 +00001488 llvm::Value *Exn = nullptr;
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001489 if (getLangOpts().CPlusPlus)
1490 Exn = Builder.CreateExtractValue(LPadInst, 0);
1491 llvm::CallInst *terminateCall =
1492 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCalle142ad52013-02-12 03:51:46 +00001493 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001494 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001495
John McCallbd309292010-07-06 01:34:17 +00001496 // Restore the saved insertion state.
1497 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001498
John McCallbd309292010-07-06 01:34:17 +00001499 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001500}
Mike Stump2b488872009-12-09 22:59:31 +00001501
1502llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001503 if (TerminateHandler)
1504 return TerminateHandler;
1505
John McCallbd309292010-07-06 01:34:17 +00001506 // Set up the terminate handler. This block is inserted at the very
1507 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001508 TerminateHandler = createBasicBlock("terminate.handler");
Reid Kleckner06f19a02018-01-02 21:34:16 +00001509 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
John McCallbd309292010-07-06 01:34:17 +00001510 Builder.SetInsertPoint(TerminateHandler);
Reid Kleckner06f19a02018-01-02 21:34:16 +00001511
David Majnemerfeeefb22015-12-14 18:34:18 +00001512 llvm::Value *Exn = nullptr;
Reid Kleckner06f19a02018-01-02 21:34:16 +00001513 if (getLangOpts().CPlusPlus)
1514 Exn = getExceptionFromSlot();
David Majnemerfeeefb22015-12-14 18:34:18 +00001515 llvm::CallInst *terminateCall =
1516 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1517 terminateCall->setDoesNotReturn();
1518 Builder.CreateUnreachable();
Mike Stump2b488872009-12-09 22:59:31 +00001519
John McCall21886962010-04-21 10:05:39 +00001520 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001521 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001522
Mike Stump2b488872009-12-09 22:59:31 +00001523 return TerminateHandler;
1524}
John McCallbd309292010-07-06 01:34:17 +00001525
Reid Kleckner06f19a02018-01-02 21:34:16 +00001526llvm::BasicBlock *CodeGenFunction::getTerminateFunclet() {
1527 assert(EHPersonality::get(*this).usesFuncletPads() &&
1528 "use getTerminateLandingPad for non-funclet EH");
1529
1530 llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
1531 if (TerminateFunclet)
1532 return TerminateFunclet;
1533
1534 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1535
1536 // Set up the terminate handler. This block is inserted at the very
1537 // end of the function by FinishFunction.
1538 TerminateFunclet = createBasicBlock("terminate.handler");
1539 Builder.SetInsertPoint(TerminateFunclet);
1540
1541 // Create the cleanuppad using the current parent pad as its token. Use 'none'
1542 // if this is a top-level terminate scope, which is the common case.
1543 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1544 CurrentFuncletPad);
1545 llvm::Value *ParentPad = CurrentFuncletPad;
1546 if (!ParentPad)
1547 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1548 CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1549
1550 // Emit the __std_terminate call.
Heejin Ahnc6479192018-05-31 22:18:13 +00001551 llvm::Value *Exn = nullptr;
1552 // In case of wasm personality, we need to pass the exception value to
1553 // __clang_call_terminate function.
1554 if (getLangOpts().CPlusPlus &&
1555 EHPersonality::get(*this).isWasmPersonality()) {
James Y Knight8799cae2019-02-03 21:53:49 +00001556 llvm::Function *GetExnFn =
Heejin Ahnc6479192018-05-31 22:18:13 +00001557 CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
1558 Exn = Builder.CreateCall(GetExnFn, CurrentFuncletPad);
1559 }
Reid Kleckner06f19a02018-01-02 21:34:16 +00001560 llvm::CallInst *terminateCall =
Heejin Ahnc6479192018-05-31 22:18:13 +00001561 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
Reid Kleckner06f19a02018-01-02 21:34:16 +00001562 terminateCall->setDoesNotReturn();
1563 Builder.CreateUnreachable();
1564
1565 // Restore the saved insertion state.
1566 Builder.restoreIP(SavedIP);
1567
1568 return TerminateFunclet;
1569}
1570
David Chisnall9a837be2012-11-07 16:50:40 +00001571llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001572 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001573
1574 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1575
1576 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001577 EHResumeBlock = createBasicBlock("eh.resume");
1578 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001579
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001580 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001581
1582 // This can always be a call because we necessarily didn't find
1583 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001584 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001585 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001586 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Nico Weberff62a6a2015-02-26 22:34:33 +00001587 getExceptionFromSlot())->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001588 Builder.CreateUnreachable();
1589 Builder.restoreIP(SavedIP);
1590 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001591 }
1592
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001593 // Recreate the landingpad's return value for the 'resume' instruction.
1594 llvm::Value *Exn = getExceptionFromSlot();
1595 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001596
Serge Guelton1d993272017-05-09 19:31:30 +00001597 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001598 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1599 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1600 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1601
1602 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001603 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001604 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001605}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001606
1607void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001608 EnterSEHTryStmt(S);
Reid Klecknera5930002015-02-11 21:40:48 +00001609 {
Nico Weber5779f842015-02-12 23:16:11 +00001610 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
Nico Weber5779f842015-02-12 23:16:11 +00001611
Reid Kleckner11c033e2015-02-12 23:40:45 +00001612 SEHTryEpilogueStack.push_back(&TryExit);
Reid Klecknera5930002015-02-11 21:40:48 +00001613 EmitStmt(S.getTryBlock());
Reid Kleckner11c033e2015-02-12 23:40:45 +00001614 SEHTryEpilogueStack.pop_back();
Nico Weber5779f842015-02-12 23:16:11 +00001615
1616 if (!TryExit.getBlock()->use_empty())
1617 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1618 else
1619 delete TryExit.getBlock();
Reid Klecknera5930002015-02-11 21:40:48 +00001620 }
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001621 ExitSEHTryStmt(S);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001622}
1623
1624namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001625struct PerformSEHFinally final : EHScopeStack::Cleanup {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001626 llvm::Function *OutlinedFinally;
Reid Kleckner55391522015-10-08 21:14:56 +00001627 PerformSEHFinally(llvm::Function *OutlinedFinally)
1628 : OutlinedFinally(OutlinedFinally) {}
Reid Kleckneraca01db2015-02-04 22:37:07 +00001629
Reid Kleckner1d59f992015-01-22 01:36:17 +00001630 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001631 ASTContext &Context = CGF.getContext();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001632 CodeGenModule &CGM = CGF.CGM;
Reid Kleckner65870442015-06-09 17:47:50 +00001633
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001634 CallArgList Args;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001635
1636 // Compute the two argument values.
1637 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
Sanjin Sijariccfa2a2a2019-01-16 07:39:44 +00001638 llvm::Value *FP = nullptr;
1639 // If CFG.IsOutlinedSEHHelper is true, then we are within a finally block.
1640 if (CGF.IsOutlinedSEHHelper) {
1641 FP = &CGF.CurFn->arg_begin()[1];
1642 } else {
James Y Knight8799cae2019-02-03 21:53:49 +00001643 llvm::Function *LocalAddrFn =
Sanjin Sijariccfa2a2a2019-01-16 07:39:44 +00001644 CGM.getIntrinsic(llvm::Intrinsic::localaddress);
1645 FP = CGF.Builder.CreateCall(LocalAddrFn);
1646 }
1647
Reid Klecknereb11c412015-07-01 21:00:00 +00001648 llvm::Value *IsForEH =
1649 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
Aaron Smith4eabd002020-04-30 09:38:19 -07001650
1651 // Except _leave and fall-through at the end, all other exits in a _try
1652 // (return/goto/continue/break) are considered as abnormal terminations
1653 // since _leave/fall-through is always Indexed 0,
1654 // just use NormalCleanupDestSlot (>= 1 for goto/return/..),
1655 // as 1st Arg to indicate abnormal termination
1656 if (!F.isForEHCleanup() && F.hasExitSwitch()) {
1657 Address Addr = CGF.getNormalCleanupDestSlot();
1658 llvm::Value *Load = CGF.Builder.CreateLoad(Addr, "cleanup.dest");
1659 llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int32Ty);
1660 IsForEH = CGF.Builder.CreateICmpNE(Load, Zero);
1661 }
1662
Reid Klecknereb11c412015-07-01 21:00:00 +00001663 Args.add(RValue::get(IsForEH), ArgTys[0]);
1664 Args.add(RValue::get(FP), ArgTys[1]);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001665
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001666 // Arrange a two-arg function info and type.
Reid Klecknereb11c412015-07-01 21:00:00 +00001667 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001668 CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001669
John McCallb92ab1a2016-10-26 23:46:34 +00001670 auto Callee = CGCallee::forDirect(OutlinedFinally);
1671 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001672 }
1673};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001674} // end anonymous namespace
Reid Kleckner1d59f992015-01-22 01:36:17 +00001675
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001676namespace {
1677/// Find all local variable captures in the statement.
1678struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1679 CodeGenFunction &ParentCGF;
1680 const VarDecl *ParentThis;
John McCall0a490152015-09-08 21:15:22 +00001681 llvm::SmallSetVector<const VarDecl *, 4> Captures;
John McCall7f416cc2015-09-08 08:05:57 +00001682 Address SEHCodeSlot = Address::invalid();
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001683 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1684 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1685
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001686 // Return true if we need to do any capturing work.
1687 bool foundCaptures() {
John McCall7f416cc2015-09-08 08:05:57 +00001688 return !Captures.empty() || SEHCodeSlot.isValid();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001689 }
1690
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001691 void Visit(const Stmt *S) {
1692 // See if this is a capture, then recurse.
1693 ConstStmtVisitor<CaptureFinder>::Visit(S);
1694 for (const Stmt *Child : S->children())
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001695 if (Child)
1696 Visit(Child);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001697 }
1698
1699 void VisitDeclRefExpr(const DeclRefExpr *E) {
1700 // If this is already a capture, just make sure we capture 'this'.
1701 if (E->refersToEnclosingVariableOrCapture()) {
John McCall0a490152015-09-08 21:15:22 +00001702 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001703 return;
1704 }
1705
1706 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1707 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
John McCall0a490152015-09-08 21:15:22 +00001708 Captures.insert(D);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001709 }
1710
1711 void VisitCXXThisExpr(const CXXThisExpr *E) {
John McCall0a490152015-09-08 21:15:22 +00001712 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001713 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001714
1715 void VisitCallExpr(const CallExpr *E) {
1716 // We only need to add parent frame allocations for these builtins in x86.
1717 if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1718 return;
1719
1720 unsigned ID = E->getBuiltinCallee();
1721 switch (ID) {
1722 case Builtin::BI__exception_code:
1723 case Builtin::BI_exception_code:
1724 // This is the simple case where we are the outermost finally. All we
1725 // have to do here is make sure we escape this and recover it in the
1726 // outlined handler.
John McCall7f416cc2015-09-08 08:05:57 +00001727 if (!SEHCodeSlot.isValid())
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001728 SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1729 break;
1730 }
1731 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001732};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001733} // end anonymous namespace
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001734
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001735Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
1736 Address ParentVar,
1737 llvm::Value *ParentFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001738 llvm::CallInst *RecoverCall = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00001739 CGBuilderTy Builder(*this, AllocaInsertPt);
1740 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001741 // Mark the variable escaped if nobody else referenced it and compute the
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001742 // localescape index.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001743 auto InsertPair = ParentCGF.EscapedLocals.insert(
1744 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1745 int FrameEscapeIdx = InsertPair.first->second;
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001746 // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001747 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001748 &CGM.getModule(), llvm::Intrinsic::localrecover);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001749 llvm::Constant *ParentI8Fn =
1750 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1751 RecoverCall = Builder.CreateCall(
1752 FrameRecoverFn, {ParentI8Fn, ParentFP,
1753 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1754
1755 } else {
1756 // If the parent didn't have an alloca, we're doing some nested outlining.
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001757 // Just clone the existing localrecover call, but tweak the FP argument to
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001758 // use our FP value. All other arguments are constants.
1759 auto *ParentRecover =
John McCall7f416cc2015-09-08 08:05:57 +00001760 cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001761 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1762 "expected alloca or localrecover in parent LocalDeclMap");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001763 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1764 RecoverCall->setArgOperand(1, ParentFP);
1765 RecoverCall->insertBefore(AllocaInsertPt);
1766 }
1767
1768 // Bitcast the variable, rename it, and insert it in the local decl map.
1769 llvm::Value *ChildVar =
John McCall7f416cc2015-09-08 08:05:57 +00001770 Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1771 ChildVar->setName(ParentVar.getName());
1772 return Address(ChildVar, ParentVar.getAlignment());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001773}
1774
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001775void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
Reid Kleckner0b9bbbf2015-06-09 17:49:42 +00001776 const Stmt *OutlinedStmt,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001777 bool IsFilter) {
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001778 // Find all captures in the Stmt.
1779 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1780 Finder.Visit(OutlinedStmt);
1781
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001782 // We can exit early on x86_64 when there are no captures. We just have to
1783 // save the exception code in filters so that __exception_code() works.
1784 if (!Finder.foundCaptures() &&
1785 CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1786 if (IsFilter)
1787 EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001788 return;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001789 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001790
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001791 llvm::Value *EntryFP = nullptr;
1792 CGBuilderTy Builder(CGM, AllocaInsertPt);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001793 if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1794 // 32-bit SEH filters need to be careful about FP recovery. The end of the
1795 // EH registration is passed in as the EBP physical register. We can
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001796 // recover that with llvm.frameaddress(1).
1797 EntryFP = Builder.CreateCall(
Christudasan Devadasan8c5e6fa2019-07-22 12:50:30 +00001798 CGM.getIntrinsic(llvm::Intrinsic::frameaddress, AllocaInt8PtrTy),
1799 {Builder.getInt32(1)});
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001800 } else {
1801 // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1802 // second parameter.
1803 auto AI = CurFn->arg_begin();
1804 ++AI;
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001805 EntryFP = &*AI;
1806 }
1807
1808 llvm::Value *ParentFP = EntryFP;
1809 if (IsFilter) {
1810 // Given whatever FP the runtime provided us in EntryFP, recover the true
1811 // frame pointer of the parent function. We only need to do this in filters,
1812 // since finally funclets recover the parent FP for us.
1813 llvm::Function *RecoverFPIntrin =
Eli Friedmanc4c43b22019-01-16 00:50:44 +00001814 CGM.getIntrinsic(llvm::Intrinsic::eh_recoverfp);
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001815 llvm::Constant *ParentI8Fn =
1816 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1817 ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001818 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001819
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001820 // Create llvm.localrecover calls for all captures.
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001821 for (const VarDecl *VD : Finder.Captures) {
1822 if (isa<ImplicitParamDecl>(VD)) {
1823 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1824 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1825 continue;
1826 }
1827 if (VD->getType()->isVariablyModifiedType()) {
1828 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1829 continue;
1830 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001831 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1832 "captured non-local variable");
1833
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001834 // If this decl hasn't been declared yet, it will be declared in the
1835 // OutlinedStmt.
1836 auto I = ParentCGF.LocalDeclMap.find(VD);
1837 if (I == ParentCGF.LocalDeclMap.end())
1838 continue;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001839
John McCall7f416cc2015-09-08 08:05:57 +00001840 Address ParentVar = I->second;
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001841 setAddrOfLocalVar(
1842 VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
Nico Webere4f974c2015-07-02 06:10:53 +00001843 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001844
John McCall7f416cc2015-09-08 08:05:57 +00001845 if (Finder.SEHCodeSlot.isValid()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001846 SEHCodeSlotStack.push_back(
1847 recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1848 }
1849
1850 if (IsFilter)
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001851 EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001852}
1853
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001854/// Arrange a function prototype that can be called by Windows exception
1855/// handling personalities. On Win64, the prototype looks like:
1856/// RetTy func(void *EHPtrs, void *ParentFP);
1857void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001858 bool IsFilter,
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001859 const Stmt *OutlinedStmt) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001860 SourceLocation StartLoc = OutlinedStmt->getBeginLoc();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001861
1862 // Get the mangled function name.
1863 SmallString<128> Name;
1864 {
1865 llvm::raw_svector_ostream OS(Name);
David Chisnall93ce0182018-08-10 12:53:13 +00001866 const NamedDecl *ParentSEHFn = ParentCGF.CurSEHParent;
David Majnemer25eb1652016-03-01 19:42:53 +00001867 assert(ParentSEHFn && "No CurSEHParent!");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001868 MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1869 if (IsFilter)
David Majnemer25eb1652016-03-01 19:42:53 +00001870 Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001871 else
David Majnemer25eb1652016-03-01 19:42:53 +00001872 Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001873 }
1874
1875 FunctionArgList Args;
1876 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1877 // All SEH finally functions take two parameters. Win64 filters take two
1878 // parameters. Win32 filters take no parameters.
1879 if (IsFilter) {
1880 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001881 getContext(), /*DC=*/nullptr, StartLoc,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001882 &getContext().Idents.get("exception_pointers"),
Alexey Bataev56223232017-06-09 13:40:18 +00001883 getContext().VoidPtrTy, ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001884 } else {
1885 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001886 getContext(), /*DC=*/nullptr, StartLoc,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001887 &getContext().Idents.get("abnormal_termination"),
Alexey Bataev56223232017-06-09 13:40:18 +00001888 getContext().UnsignedCharTy, ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001889 }
1890 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001891 getContext(), /*DC=*/nullptr, StartLoc,
1892 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
1893 ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001894 }
1895
1896 QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1897
John McCallc56a8b32016-03-11 04:30:31 +00001898 const CGFunctionInfo &FnInfo =
1899 CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001900
Reid Kleckner1d59f992015-01-22 01:36:17 +00001901 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001902 llvm::Function *Fn = llvm::Function::Create(
1903 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001904
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001905 IsOutlinedSEHHelper = true;
Nico Weberf2a39a72015-04-13 20:03:03 +00001906
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001907 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001908 OutlinedStmt->getBeginLoc(), OutlinedStmt->getBeginLoc());
David Majnemer25eb1652016-03-01 19:42:53 +00001909 CurSEHParent = ParentCGF.CurSEHParent;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001910
Sanne Woudaecfd6d32019-12-13 14:45:46 +00001911 CGM.SetInternalFunctionAttributes(GlobalDecl(), CurFn, FnInfo);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001912 EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001913}
1914
1915/// Create a stub filter function that will ultimately hold the code of the
1916/// filter expression. The EH preparation passes in LLVM will outline the code
1917/// from the main function body into this stub.
1918llvm::Function *
1919CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1920 const SEHExceptStmt &Except) {
1921 const Expr *FilterExpr = Except.getFilterExpr();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001922 startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001923
1924 // Emit the original filter expression, convert to i32, and return.
1925 llvm::Value *R = EmitScalarExpr(FilterExpr);
David Majnemer2ccba832015-04-17 06:57:25 +00001926 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
Reid Kleckner1d59f992015-01-22 01:36:17 +00001927 FilterExpr->getType()->isSignedIntegerType());
1928 Builder.CreateStore(R, ReturnValue);
1929
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001930 FinishFunction(FilterExpr->getEndLoc());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001931
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001932 return CurFn;
1933}
1934
1935llvm::Function *
1936CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1937 const SEHFinallyStmt &Finally) {
1938 const Stmt *FinallyBlock = Finally.getBlock();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001939 startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001940
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001941 // Emit the original filter expression, convert to i32, and return.
1942 EmitStmt(FinallyBlock);
1943
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001944 FinishFunction(FinallyBlock->getEndLoc());
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001945
1946 return CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001947}
1948
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001949void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1950 llvm::Value *ParentFP,
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001951 llvm::Value *EntryFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001952 // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1953 // __exception_info intrinsic.
1954 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1955 // On Win64, the info is passed as the first parameter to the filter.
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001956 SEHInfo = &*CurFn->arg_begin();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001957 SEHCodeSlotStack.push_back(
1958 CreateMemTemp(getContext().IntTy, "__exception_code"));
1959 } else {
1960 // On Win32, the EBP on entry to the filter points to the end of an
1961 // exception registration object. It contains 6 32-bit fields, and the info
1962 // pointer is stored in the second field. So, GEP 20 bytes backwards and
1963 // load the pointer.
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001964 SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001965 SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001966 SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001967 SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1968 ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1969 }
1970
Reid Kleckner1d59f992015-01-22 01:36:17 +00001971 // Save the exception code in the exception slot to unify exception access in
1972 // the filter function and the landing pad.
1973 // struct EXCEPTION_POINTERS {
1974 // EXCEPTION_RECORD *ExceptionRecord;
1975 // CONTEXT *ContextRecord;
1976 // };
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001977 // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001978 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
Serge Guelton1d993272017-05-09 19:31:30 +00001979 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001980 llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
David Blaikie1ed728c2015-04-05 22:45:47 +00001981 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001982 Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
1983 llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001984 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1985 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001986}
1987
1988llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1989 // Sema should diagnose calling this builtin outside of a filter context, but
1990 // don't crash if we screw up.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001991 if (!SEHInfo)
Reid Kleckner1d59f992015-01-22 01:36:17 +00001992 return llvm::UndefValue::get(Int8PtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001993 assert(SEHInfo->getType() == Int8PtrTy);
1994 return SEHInfo;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001995}
1996
1997llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001998 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
John McCall7f416cc2015-09-08 08:05:57 +00001999 return Builder.CreateLoad(SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00002000}
2001
Reid Kleckneraca01db2015-02-04 22:37:07 +00002002llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002003 // Abnormal termination is just the first parameter to the outlined finally
2004 // helper.
2005 auto AI = CurFn->arg_begin();
2006 return Builder.CreateZExt(&*AI, Int32Ty);
Reid Kleckneraca01db2015-02-04 22:37:07 +00002007}
2008
David Chisnall93ce0182018-08-10 12:53:13 +00002009void CodeGenFunction::pushSEHCleanup(CleanupKind Kind,
2010 llvm::Function *FinallyFunc) {
2011 EHStack.pushCleanup<PerformSEHFinally>(Kind, FinallyFunc);
2012}
2013
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002014void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
2015 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
2016 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002017 // Outline the finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002018 llvm::Function *FinallyFunc =
2019 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002020
2021 // Push a cleanup for __finally blocks.
Reid Kleckner55391522015-10-08 21:14:56 +00002022 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
Reid Kleckner1d59f992015-01-22 01:36:17 +00002023 return;
2024 }
2025
2026 // Otherwise, we must have an __except block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002027 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00002028 assert(Except);
2029 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002030 SEHCodeSlotStack.push_back(
2031 CreateMemTemp(getContext().IntTy, "__exception_code"));
Reid Kleckner2a2e1562015-01-22 02:25:56 +00002032
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002033 // If the filter is known to evaluate to 1, then we can use the clause
2034 // "catch i8* null". We can't do this on x86 because the filter has to save
2035 // the exception code.
Reid Kleckner2a2e1562015-01-22 02:25:56 +00002036 llvm::Constant *C =
John McCallde0fe072017-08-15 21:42:52 +00002037 ConstantEmitter(*this).tryEmitAbstract(Except->getFilterExpr(),
2038 getContext().IntTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002039 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
2040 C->isOneValue()) {
Reid Kleckner2a2e1562015-01-22 02:25:56 +00002041 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
2042 return;
2043 }
2044
2045 // In general, we have to emit an outlined filter function. Use the function
2046 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00002047 llvm::Function *FilterFunc =
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002048 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
Reid Kleckner1d59f992015-01-22 01:36:17 +00002049 llvm::Constant *OpaqueFunc =
2050 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
Reid Kleckner8be18472015-09-16 21:06:09 +00002051 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
Reid Kleckner1d59f992015-01-22 01:36:17 +00002052}
2053
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002054void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00002055 // Just pop the cleanup if it's a __finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002056 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00002057 PopCleanupBlock();
2058 return;
2059 }
2060
2061 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00002062 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00002063 assert(Except && "__try must have __finally xor __except");
2064 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
2065
2066 // Don't emit the __except block if the __try block lacked invokes.
2067 // TODO: Model unwind edges from instructions, either with iload / istore or
2068 // a try body function.
2069 if (!CatchScope.hasEHBranches()) {
2070 CatchScope.clearHandlerBlocks();
2071 EHStack.popCatch();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002072 SEHCodeSlotStack.pop_back();
Reid Kleckner1d59f992015-01-22 01:36:17 +00002073 return;
2074 }
2075
2076 // The fall-through block.
2077 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
2078
2079 // We just emitted the body of the __try; jump to the continue block.
2080 if (HaveInsertPoint())
2081 Builder.CreateBr(ContBB);
2082
2083 // Check if our filter function returned true.
2084 emitCatchDispatchBlock(*this, CatchScope);
2085
2086 // Grab the block before we pop the handler.
David Majnemer4e52d6f2015-12-12 05:39:21 +00002087 llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
Reid Kleckner1d59f992015-01-22 01:36:17 +00002088 EHStack.popCatch();
2089
David Majnemer4e52d6f2015-12-12 05:39:21 +00002090 EmitBlockAfterUses(CatchPadBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00002091
Reid Kleckner129552b2015-10-08 01:13:52 +00002092 // __except blocks don't get outlined into funclets, so immediately do a
2093 // catchret.
Reid Kleckner129552b2015-10-08 01:13:52 +00002094 llvm::CatchPadInst *CPI =
2095 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
David Majnemer4e52d6f2015-12-12 05:39:21 +00002096 llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
Reid Kleckner129552b2015-10-08 01:13:52 +00002097 Builder.CreateCatchRet(CPI, ExceptBB);
2098 EmitBlock(ExceptBB);
2099
2100 // On Win64, the exception code is returned in EAX. Copy it into the slot.
2101 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
2102 llvm::Function *SEHCodeIntrin =
2103 CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
2104 llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
2105 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002106 }
2107
Reid Kleckner1d59f992015-01-22 01:36:17 +00002108 // Emit the __except body.
2109 EmitStmt(Except->getBlock());
2110
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002111 // End the lifetime of the exception code.
2112 SEHCodeSlotStack.pop_back();
2113
Reid Kleckner3a417c32015-01-30 22:16:45 +00002114 if (HaveInsertPoint())
2115 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00002116
2117 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00002118}
Nico Weber9b982072014-07-07 00:12:30 +00002119
2120void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00002121 // If this code is reachable then emit a stop point (if generating
2122 // debug info). We have to do this ourselves because we are on the
2123 // "simple" statement path.
2124 if (HaveInsertPoint())
2125 EmitStopPoint(&S);
2126
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002127 // This must be a __leave from a __finally block, which we warn on and is UB.
2128 // Just emit unreachable.
2129 if (!isSEHTryScope()) {
2130 Builder.CreateUnreachable();
2131 Builder.ClearInsertionPoint();
2132 return;
2133 }
2134
Nico Weber5779f842015-02-12 23:16:11 +00002135 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00002136}