blob: ebeb7270852e432597a70cf62b97d042b4f10960 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- C++ -*-===//
Anders Carlsson4b08db72009-10-30 01:42:31 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ exception related code generation.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
David Majnemer442d0a22014-11-25 07:20:20 +000015#include "CGCXXABI.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000016#include "CGCleanup.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000017#include "CGObjCRuntime.h"
John McCall5add20c2010-07-20 22:17:55 +000018#include "TargetInfo.h"
Reid Kleckner1d59f992015-01-22 01:36:17 +000019#include "clang/AST/Mangle.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000020#include "clang/AST/StmtCXX.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000021#include "clang/AST/StmtObjC.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000022#include "clang/AST/StmtVisitor.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000023#include "clang/Basic/TargetBuiltins.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000024#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/Intrinsics.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000026#include "llvm/IR/IntrinsicInst.h"
Reid Klecknerebaf28d2015-04-14 20:59:00 +000027#include "llvm/Support/SaveAndRestore.h"
John McCallbd309292010-07-06 01:34:17 +000028
Anders Carlsson4b08db72009-10-30 01:42:31 +000029using namespace clang;
30using namespace CodeGen;
31
John McCall2c33ba82013-02-12 03:51:38 +000032static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000033 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000034
Chris Lattner2192fe52011-07-18 04:24:23 +000035 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000036 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000037
John McCall2c33ba82013-02-12 03:51:38 +000038 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000039}
40
John McCall2c33ba82013-02-12 03:51:38 +000041static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000042 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000043
Chris Lattner2192fe52011-07-18 04:24:23 +000044 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000045 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000046
John McCall2c33ba82013-02-12 03:51:38 +000047 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000048}
49
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000050llvm::Constant *CodeGenModule::getTerminateFn() {
Mike Stump33270212009-12-02 07:41:41 +000051 // void __terminate();
52
Chris Lattner2192fe52011-07-18 04:24:23 +000053 llvm::FunctionType *FTy =
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000054 llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000055
Chris Lattner0e62c1c2011-07-23 10:55:15 +000056 StringRef name;
John McCall9de19782011-07-06 01:22:26 +000057
58 // In C++, use std::terminate().
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000059 if (getLangOpts().CPlusPlus &&
60 getTarget().getCXXABI().isItaniumFamily()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +000061 name = "_ZSt9terminatev";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000062 } else if (getLangOpts().CPlusPlus &&
63 getTarget().getCXXABI().isMicrosoft()) {
David Majnemerb710a932015-05-11 03:57:49 +000064 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemerfb6ffca2015-05-10 21:38:26 +000065 name = "__std_terminate";
66 else
67 name = "\01?terminate@@YAXXZ";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000068 } else if (getLangOpts().ObjC1 &&
69 getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +000070 name = "objc_terminate";
71 else
72 name = "abort";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000073 return CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +000074}
75
John McCall2c33ba82013-02-12 03:51:38 +000076static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000077 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +000078 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000079 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +000080
John McCall2c33ba82013-02-12 03:51:38 +000081 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +000082}
83
Craig Topper8a13c412014-05-21 05:09:00 +000084const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +000085const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +000086EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
87const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000088EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
89const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +000090EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
91const EHPersonality
92EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
93const EHPersonality
94EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +000095const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000096EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
97const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +000098EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
99const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000100EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000101const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000102EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Reid Kleckner1d59f992015-01-22 01:36:17 +0000103const EHPersonality
104EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
105const EHPersonality
106EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000107const EHPersonality
108EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000109
Reid Klecknere070b992014-11-14 02:01:10 +0000110/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
111/// other platforms, unless the user asked for SjLj exceptions.
112static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
113 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
114}
115
116static const EHPersonality &getCPersonality(const llvm::Triple &T,
117 const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000118 if (L.SjLjExceptions)
119 return EHPersonality::GNU_C_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000120 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000121 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000122 return EHPersonality::GNU_C;
123}
124
Reid Klecknere070b992014-11-14 02:01:10 +0000125static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
126 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000127 switch (L.ObjCRuntime.getKind()) {
128 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000129 return getCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000130 case ObjCRuntime::MacOSX:
131 case ObjCRuntime::iOS:
132 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000133 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000134 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
135 return EHPersonality::GNUstep_ObjC;
136 // fallthrough
David Chisnallb601c962012-07-03 20:49:52 +0000137 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000138 case ObjCRuntime::ObjFW:
John McCall36ea3722010-07-17 00:43:08 +0000139 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000140 }
John McCall5fb5df92012-06-20 06:18:46 +0000141 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000142}
143
Reid Klecknere070b992014-11-14 02:01:10 +0000144static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
145 const LangOptions &L) {
John McCall36ea3722010-07-17 00:43:08 +0000146 if (L.SjLjExceptions)
147 return EHPersonality::GNU_CPlusPlus_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000148 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000149 return EHPersonality::GNU_CPlusPlus_SEH;
Reid Klecknere070b992014-11-14 02:01:10 +0000150 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000151}
152
153/// Determines the personality function to use when both C++
154/// and Objective-C exceptions are being caught.
Reid Klecknere070b992014-11-14 02:01:10 +0000155static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
156 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000157 switch (L.ObjCRuntime.getKind()) {
John McCallbd309292010-07-06 01:34:17 +0000158 // The ObjC personality defers to the C++ personality for non-ObjC
159 // handlers. Unlike the C++ case, we use the same personality
160 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000161 case ObjCRuntime::MacOSX:
162 case ObjCRuntime::iOS:
163 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000164
John McCall5fb5df92012-06-20 06:18:46 +0000165 // In the fragile ABI, just use C++ exception handling and hope
166 // they're not doing crazy exception mixing.
167 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000168 return getCXXPersonality(T, L);
David Chisnallf9c42252010-05-17 13:49:20 +0000169
David Chisnallb601c962012-07-03 20:49:52 +0000170 // The GCC runtime's personality function inherently doesn't support
John McCall36ea3722010-07-17 00:43:08 +0000171 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000172 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000173 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnallb601c962012-07-03 20:49:52 +0000174 return EHPersonality::GNU_ObjC;
175 case ObjCRuntime::GNUstep:
John McCall5fb5df92012-06-20 06:18:46 +0000176 return EHPersonality::GNU_ObjCXX;
177 }
178 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000179}
180
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000181static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000182 if (T.getArch() == llvm::Triple::x86)
183 return EHPersonality::MSVC_except_handler;
184 return EHPersonality::MSVC_C_specific_handler;
185}
186
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000187const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
188 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000189 const llvm::Triple &T = CGM.getTarget().getTriple();
190 const LangOptions &L = CGM.getLangOpts();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000191
Reid Kleckner01485652015-09-17 17:04:13 +0000192 // Functions using SEH get an SEH personality.
193 if (FD && FD->usesSEHTry())
194 return getSEHPersonalityMSVC(T);
195
Reid Kleckner1d59f992015-01-22 01:36:17 +0000196 // Try to pick a personality function that is compatible with MSVC if we're
197 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
198 // the GCC-style personality function.
199 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000200 if (L.SjLjExceptions)
201 return EHPersonality::GNU_CPlusPlus_SJLJ;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000202 else
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000203 return EHPersonality::MSVC_CxxFrameHandler3;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000204 }
205
John McCall36ea3722010-07-17 00:43:08 +0000206 if (L.CPlusPlus && L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000207 return getObjCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000208 else if (L.CPlusPlus)
Reid Klecknere070b992014-11-14 02:01:10 +0000209 return getCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000210 else if (L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000211 return getObjCPersonality(T, L);
John McCallbd309292010-07-06 01:34:17 +0000212 else
Reid Klecknere070b992014-11-14 02:01:10 +0000213 return getCPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000214}
John McCallbd309292010-07-06 01:34:17 +0000215
David Majnemerc28d46e2015-07-22 23:46:21 +0000216const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
217 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
218}
219
John McCall0bdb1fd2010-09-16 06:16:50 +0000220static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000221 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000222 llvm::Constant *Fn =
Chris Lattnerece04092012-02-07 00:39:47 +0000223 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Kramer793bd552012-02-08 12:41:24 +0000224 Personality.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000225 return Fn;
226}
227
228static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
229 const EHPersonality &Personality) {
230 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000231 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000232}
233
Vedant Kumardb609472015-09-11 15:40:05 +0000234/// Check whether a landingpad instruction only uses C++ features.
235static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
236 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
237 // Look for something that would've been returned by the ObjC
238 // runtime's GetEHType() method.
239 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
240 if (LPI->isCatch(I)) {
241 // Check if the catch value has the ObjC prefix.
242 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
243 // ObjC EH selector entries are always global variables with
244 // names starting like this.
245 if (GV->getName().startswith("OBJC_EHTYPE"))
246 return false;
247 } else {
248 // Check if any of the filter values have the ObjC prefix.
249 llvm::Constant *CVal = cast<llvm::Constant>(Val);
250 for (llvm::User::op_iterator
251 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
252 if (llvm::GlobalVariable *GV =
253 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
254 // ObjC EH selector entries are always global variables with
255 // names starting like this.
256 if (GV->getName().startswith("OBJC_EHTYPE"))
257 return false;
258 }
259 }
260 }
261 return true;
262}
263
John McCall0bdb1fd2010-09-16 06:16:50 +0000264/// Check whether a personality function could reasonably be swapped
265/// for a C++ personality function.
266static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000267 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000268 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000269 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000270 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
271 if (!PersonalityHasOnlyCXXUses(CE))
272 return false;
273 continue;
274 }
275
Vedant Kumardb609472015-09-11 15:40:05 +0000276 // Otherwise it must be a function.
277 llvm::Function *F = dyn_cast<llvm::Function>(U);
278 if (!F) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000279
Vedant Kumardb609472015-09-11 15:40:05 +0000280 for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
281 if (BB->isLandingPad())
282 if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
283 return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000284 }
285 }
286
287 return true;
288}
289
290/// Try to use the C++ personality function in ObjC++. Not doing this
291/// can cause some incompatibilities with gcc, which is more
292/// aggressive about only using the ObjC++ personality in a function
293/// when it really needs it.
294void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000295 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000296 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000297 return;
298
John McCall3c223932012-11-14 17:48:31 +0000299 // Both the problem this endeavors to fix and the way the logic
300 // above works is specific to the NeXT runtime.
301 if (!LangOpts.ObjCRuntime.isNeXTFamily())
302 return;
303
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000304 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Reid Klecknere070b992014-11-14 02:01:10 +0000305 const EHPersonality &CXX =
306 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000307 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000308 return;
309
Benjamin Kramer793bd552012-02-08 12:41:24 +0000310 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
311 "Different EHPersonalities using the same personality function.");
312
313 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000314
315 // Nothing to do if it's unused.
316 if (!Fn || Fn->use_empty()) return;
317
318 // Can't do the optimization if it has non-C++ uses.
319 if (!PersonalityHasOnlyCXXUses(Fn)) return;
320
321 // Create the C++ personality function and kill off the old
322 // function.
323 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
324
325 // This can happen if the user is screwing with us.
326 if (Fn->getType() != CXXFn->getType()) return;
327
328 Fn->replaceAllUsesWith(CXXFn);
329 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000330}
331
332/// Returns the value to inject into a selector to indicate the
333/// presence of a catch-all.
334static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
335 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000336 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000337}
338
John McCallbb026012010-07-13 21:17:51 +0000339namespace {
340 /// A cleanup to free the exception object if its initialization
341 /// throws.
David Blaikie7e70d682015-08-18 22:40:54 +0000342 struct FreeException final : EHScopeStack::Cleanup {
John McCall5fcf8da2011-07-12 00:15:30 +0000343 llvm::Value *exn;
344 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000345 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000346 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000347 }
348 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000349} // end anonymous namespace
John McCallbb026012010-07-13 21:17:51 +0000350
John McCall2e6567a2010-04-22 01:10:34 +0000351// Emits an exception expression into the given location. This
352// differs from EmitAnyExprToMem only in that, if a final copy-ctor
353// call is required, an exception within that copy ctor causes
354// std::terminate to be invoked.
John McCall7f416cc2015-09-08 08:05:57 +0000355void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
John McCallbd309292010-07-06 01:34:17 +0000356 // Make sure the exception object is cleaned up if there's an
357 // exception during initialization.
John McCall7f416cc2015-09-08 08:05:57 +0000358 pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
David Majnemer7c237072015-03-05 00:46:22 +0000359 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000360
361 // __cxa_allocate_exception returns a void*; we need to cast this
362 // to the appropriate type for the object.
David Majnemer7c237072015-03-05 00:46:22 +0000363 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
John McCall7f416cc2015-09-08 08:05:57 +0000364 Address typedAddr = Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000365
366 // FIXME: this isn't quite right! If there's a final unelided call
367 // to a copy constructor, then according to [except.terminate]p1 we
368 // must call std::terminate() if that constructor throws, because
369 // technically that copy occurs after the exception expression is
370 // evaluated but before the exception is caught. But the best way
371 // to handle that is to teach EmitAggExpr to do the final copy
372 // differently if it can't be elided.
David Majnemer7c237072015-03-05 00:46:22 +0000373 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
374 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000375
John McCalle4df6c82011-01-28 08:37:24 +0000376 // Deactivate the cleanup block.
John McCall7f416cc2015-09-08 08:05:57 +0000377 DeactivateCleanupBlock(cleanup,
378 cast<llvm::Instruction>(typedAddr.getPointer()));
Mike Stump54066142009-12-01 03:41:18 +0000379}
380
John McCall7f416cc2015-09-08 08:05:57 +0000381Address CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000382 if (!ExceptionSlot)
383 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000384 return Address(ExceptionSlot, getPointerAlign());
Mike Stump54066142009-12-01 03:41:18 +0000385}
386
John McCall7f416cc2015-09-08 08:05:57 +0000387Address CodeGenFunction::getEHSelectorSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000388 if (!EHSelectorSlot)
389 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000390 return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
John McCall9b382dd2011-05-28 21:13:02 +0000391}
392
Bill Wendling79a70e42011-09-15 18:57:19 +0000393llvm::Value *CodeGenFunction::getExceptionFromSlot() {
394 return Builder.CreateLoad(getExceptionSlot(), "exn");
395}
396
397llvm::Value *CodeGenFunction::getSelectorFromSlot() {
398 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
399}
400
Richard Smithea852322013-05-07 21:53:22 +0000401void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
402 bool KeepInsertionPoint) {
David Majnemer7c237072015-03-05 00:46:22 +0000403 if (const Expr *SubExpr = E->getSubExpr()) {
404 QualType ThrowType = SubExpr->getType();
405 if (ThrowType->isObjCObjectPointerType()) {
406 const Stmt *ThrowStmt = E->getSubExpr();
407 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
408 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
409 } else {
410 CGM.getCXXABI().emitThrow(*this, E);
John McCall2e6567a2010-04-22 01:10:34 +0000411 }
David Majnemer7c237072015-03-05 00:46:22 +0000412 } else {
413 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000414 }
Mike Stump75546b82009-12-10 00:06:18 +0000415
John McCall20f6ab82011-01-12 03:41:02 +0000416 // throw is an expression, and the expression emitters expect us
417 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000418 if (KeepInsertionPoint)
419 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000420}
Mike Stump58ef18b2009-11-20 23:44:51 +0000421
Mike Stump1d849212009-12-07 23:38:24 +0000422void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000423 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000424 return;
425
Mike Stump1d849212009-12-07 23:38:24 +0000426 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000427 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000428 // Check if CapturedDecl is nothrow and create terminate scope for it.
429 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
430 if (CD->isNothrow())
431 EHStack.pushTerminate();
432 }
Mike Stump1d849212009-12-07 23:38:24 +0000433 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000434 }
Mike Stump1d849212009-12-07 23:38:24 +0000435 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000436 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000437 return;
438
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000439 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
440 if (isNoexceptExceptionSpec(EST)) {
441 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
442 // noexcept functions are simple terminate scopes.
443 EHStack.pushTerminate();
444 }
445 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000446 // TODO: Revisit exception specifications for the MS ABI. There is a way to
447 // encode these in an object file but MSVC doesn't do anything with it.
448 if (getTarget().getCXXABI().isMicrosoft())
449 return;
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000450 unsigned NumExceptions = Proto->getNumExceptions();
451 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000452
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000453 for (unsigned I = 0; I != NumExceptions; ++I) {
454 QualType Ty = Proto->getExceptionType(I);
455 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
456 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
457 /*ForEH=*/true);
458 Filter->setFilter(I, EHType);
459 }
Mike Stump1d849212009-12-07 23:38:24 +0000460 }
Mike Stump1d849212009-12-07 23:38:24 +0000461}
462
John McCall8e4c74b2011-08-11 02:22:43 +0000463/// Emit the dispatch block for a filter scope if necessary.
464static void emitFilterDispatchBlock(CodeGenFunction &CGF,
465 EHFilterScope &filterScope) {
466 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
467 if (!dispatchBlock) return;
468 if (dispatchBlock->use_empty()) {
469 delete dispatchBlock;
470 return;
471 }
472
John McCall8e4c74b2011-08-11 02:22:43 +0000473 CGF.EmitBlockAfterUses(dispatchBlock);
474
475 // If this isn't a catch-all filter, we need to check whether we got
476 // here because the filter triggered.
477 if (filterScope.getNumFilters()) {
478 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000479 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000480 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
481
482 llvm::Value *zero = CGF.Builder.getInt32(0);
483 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000484 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
485 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
486 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000487
488 CGF.EmitBlock(unexpectedBB);
489 }
490
491 // Call __cxa_call_unexpected. This doesn't need to be an invoke
492 // because __cxa_call_unexpected magically filters exceptions
493 // according to the last landing pad the exception was thrown
494 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000495 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000496 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000497 ->setDoesNotReturn();
498 CGF.Builder.CreateUnreachable();
499}
500
Mike Stump1d849212009-12-07 23:38:24 +0000501void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000502 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000503 return;
504
Mike Stump1d849212009-12-07 23:38:24 +0000505 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000506 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000507 // Check if CapturedDecl is nothrow and pop terminate scope for it.
508 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
509 if (CD->isNothrow())
510 EHStack.popTerminate();
511 }
Mike Stump1d849212009-12-07 23:38:24 +0000512 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000513 }
Mike Stump1d849212009-12-07 23:38:24 +0000514 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000515 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000516 return;
517
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000518 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
519 if (isNoexceptExceptionSpec(EST)) {
520 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
521 EHStack.popTerminate();
522 }
523 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000524 // TODO: Revisit exception specifications for the MS ABI. There is a way to
525 // encode these in an object file but MSVC doesn't do anything with it.
526 if (getTarget().getCXXABI().isMicrosoft())
527 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000528 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
529 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000530 EHStack.popFilter();
531 }
Mike Stump1d849212009-12-07 23:38:24 +0000532}
533
Mike Stump58ef18b2009-11-20 23:44:51 +0000534void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000535 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000536 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000537 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000538}
539
John McCallb609d3f2010-07-07 06:56:46 +0000540void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000541 unsigned NumHandlers = S.getNumHandlers();
542 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000543
John McCallbd309292010-07-06 01:34:17 +0000544 for (unsigned I = 0; I != NumHandlers; ++I) {
545 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000546
John McCallbd309292010-07-06 01:34:17 +0000547 llvm::BasicBlock *Handler = createBasicBlock("catch");
548 if (C->getExceptionDecl()) {
549 // FIXME: Dropping the reference type on the type into makes it
550 // impossible to correctly implement catch-by-reference
551 // semantics for pointers. Unfortunately, this is what all
552 // existing compilers do, and it's not clear that the standard
553 // personality routine is capable of doing this right. See C++ DR 388:
554 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000555 Qualifiers CaughtTypeQuals;
556 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
557 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000558
Reid Kleckner10aa7702015-09-16 20:15:55 +0000559 CatchTypeInfo TypeInfo{nullptr, 0};
John McCall2ca705e2010-07-24 00:37:23 +0000560 if (CaughtType->isObjCObjectPointerType())
Reid Kleckner10aa7702015-09-16 20:15:55 +0000561 TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000562 else
Reid Kleckner10aa7702015-09-16 20:15:55 +0000563 TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
564 CaughtType, C->getCaughtType());
John McCallbd309292010-07-06 01:34:17 +0000565 CatchScope->setHandler(I, TypeInfo, Handler);
566 } else {
567 // No exception decl indicates '...', a catch-all.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000568 CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
John McCallbd309292010-07-06 01:34:17 +0000569 }
570 }
John McCallbd309292010-07-06 01:34:17 +0000571}
572
John McCall8e4c74b2011-08-11 02:22:43 +0000573llvm::BasicBlock *
574CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
David Majnemerdbf10452015-07-31 17:58:45 +0000575 if (CGM.getCodeGenOpts().NewMSEH &&
576 EHPersonality::get(*this).isMSVCPersonality())
577 return getMSVCDispatchBlock(si);
578
John McCall8e4c74b2011-08-11 02:22:43 +0000579 // The dispatch block for the end of the scope chain is a block that
580 // just resumes unwinding.
581 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000582 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000583
584 // Otherwise, we should look at the actual scope.
585 EHScope &scope = *EHStack.find(si);
586
587 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
588 if (!dispatchBlock) {
589 switch (scope.getKind()) {
590 case EHScope::Catch: {
591 // Apply a special case to a single catch-all.
592 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
593 if (catchScope.getNumHandlers() == 1 &&
594 catchScope.getHandler(0).isCatchAll()) {
595 dispatchBlock = catchScope.getHandler(0).Block;
596
597 // Otherwise, make a dispatch block.
598 } else {
599 dispatchBlock = createBasicBlock("catch.dispatch");
600 }
601 break;
602 }
603
604 case EHScope::Cleanup:
605 dispatchBlock = createBasicBlock("ehcleanup");
606 break;
607
608 case EHScope::Filter:
609 dispatchBlock = createBasicBlock("filter.dispatch");
610 break;
611
612 case EHScope::Terminate:
613 dispatchBlock = getTerminateHandler();
614 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000615
Reid Kleckner2586aac2015-09-10 22:11:13 +0000616 case EHScope::PadEnd:
617 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCall8e4c74b2011-08-11 02:22:43 +0000618 }
619 scope.setCachedEHDispatchBlock(dispatchBlock);
620 }
621 return dispatchBlock;
622}
623
David Majnemerdbf10452015-07-31 17:58:45 +0000624llvm::BasicBlock *
625CodeGenFunction::getMSVCDispatchBlock(EHScopeStack::stable_iterator SI) {
626 // Returning nullptr indicates that the previous dispatch block should unwind
627 // to caller.
628 if (SI == EHStack.stable_end())
629 return nullptr;
630
631 // Otherwise, we should look at the actual scope.
632 EHScope &EHS = *EHStack.find(SI);
633
634 llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
635 if (DispatchBlock)
636 return DispatchBlock;
637
638 if (EHS.getKind() == EHScope::Terminate)
639 DispatchBlock = getTerminateHandler();
640 else
641 DispatchBlock = createBasicBlock();
John McCall7f416cc2015-09-08 08:05:57 +0000642 CGBuilderTy Builder(*this, DispatchBlock);
David Majnemerdbf10452015-07-31 17:58:45 +0000643
644 switch (EHS.getKind()) {
645 case EHScope::Catch:
646 DispatchBlock->setName("catch.dispatch");
647 break;
648
649 case EHScope::Cleanup:
650 DispatchBlock->setName("ehcleanup");
651 break;
652
653 case EHScope::Filter:
654 llvm_unreachable("exception specifications not handled yet!");
655
656 case EHScope::Terminate:
657 DispatchBlock->setName("terminate");
658 break;
659
Reid Kleckner2586aac2015-09-10 22:11:13 +0000660 case EHScope::PadEnd:
661 llvm_unreachable("PadEnd dispatch block missing!");
David Majnemerdbf10452015-07-31 17:58:45 +0000662 }
663 EHS.setCachedEHDispatchBlock(DispatchBlock);
664 return DispatchBlock;
665}
666
John McCallbd309292010-07-06 01:34:17 +0000667/// Check whether this is a non-EH scope, i.e. a scope which doesn't
668/// affect exception handling. Currently, the only non-EH scopes are
669/// normal-only cleanup scopes.
670static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000671 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000672 case EHScope::Cleanup:
673 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000674 case EHScope::Filter:
675 case EHScope::Catch:
676 case EHScope::Terminate:
Reid Kleckner2586aac2015-09-10 22:11:13 +0000677 case EHScope::PadEnd:
John McCall2b7fc382010-07-13 20:32:21 +0000678 return false;
679 }
680
David Blaikiee4d798f2012-01-20 21:50:17 +0000681 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000682}
683
684llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
685 assert(EHStack.requiresLandingPad());
686 assert(!EHStack.empty());
687
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000688 // If exceptions are disabled, there are usually no landingpads. However, when
689 // SEH is enabled, functions using SEH still get landingpads.
690 const LangOptions &LO = CGM.getLangOpts();
691 if (!LO.Exceptions) {
692 if (!LO.Borland && !LO.MicrosoftExt)
693 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000694 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000695 return nullptr;
696 }
John McCall2b7fc382010-07-13 20:32:21 +0000697
John McCallbd309292010-07-06 01:34:17 +0000698 // Check the innermost scope for a cached landing pad. If this is
699 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
700 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
701 if (LP) return LP;
702
David Majnemerdbf10452015-07-31 17:58:45 +0000703 const EHPersonality &Personality = EHPersonality::get(*this);
704
705 if (!CurFn->hasPersonalityFn())
706 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
707
708 if (CGM.getCodeGenOpts().NewMSEH && Personality.isMSVCPersonality()) {
709 // We don't need separate landing pads in the MSVC model.
710 LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
711 } else {
712 // Build the landing pad for this scope.
713 LP = EmitLandingPad();
714 }
715
John McCallbd309292010-07-06 01:34:17 +0000716 assert(LP);
717
718 // Cache the landing pad on the innermost scope. If this is a
719 // non-EH scope, cache the landing pad on the enclosing scope, too.
720 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
721 ir->setCachedLandingPad(LP);
722 if (!isNonEHScope(*ir)) break;
723 }
724
725 return LP;
726}
727
728llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
729 assert(EHStack.requiresLandingPad());
730
John McCall8e4c74b2011-08-11 02:22:43 +0000731 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
732 switch (innermostEHScope.getKind()) {
733 case EHScope::Terminate:
734 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000735
Reid Kleckner2586aac2015-09-10 22:11:13 +0000736 case EHScope::PadEnd:
737 llvm_unreachable("PadEnd unnecessary for Itanium!");
David Majnemerdbf10452015-07-31 17:58:45 +0000738
John McCall8e4c74b2011-08-11 02:22:43 +0000739 case EHScope::Catch:
740 case EHScope::Cleanup:
741 case EHScope::Filter:
742 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
743 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000744 }
745
746 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000747 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantl95b24e92015-02-03 20:00:54 +0000748 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000749
750 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000751 llvm::BasicBlock *lpad = createBasicBlock("lpad");
752 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000753
David Majnemerfcbdb6e2015-06-17 20:53:19 +0000754 llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
755 llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +0000756
757 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
758 Builder.CreateStore(LPadExn, getExceptionSlot());
759 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
760 Builder.CreateStore(LPadSel, getEHSelectorSlot());
761
John McCallbd309292010-07-06 01:34:17 +0000762 // Save the exception pointer. It's safe to use a single exception
763 // pointer per function because EH cleanups can never have nested
764 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000765 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000766
767 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000768 bool hasCatchAll = false;
769 bool hasCleanup = false;
770 bool hasFilter = false;
771 SmallVector<llvm::Value*, 4> filterTypes;
772 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Nico Webere68b9f32015-02-25 16:25:00 +0000773 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
774 ++I) {
John McCallbd309292010-07-06 01:34:17 +0000775
776 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000777 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000778 // If we have a cleanup, remember that.
779 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000780 continue;
781
John McCallbd309292010-07-06 01:34:17 +0000782 case EHScope::Filter: {
783 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000784 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000785
Bill Wendlingf0724e82011-09-19 20:31:14 +0000786 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000787 EHFilterScope &filter = cast<EHFilterScope>(*I);
788 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000789
Bill Wendling8c4b7162011-09-22 20:32:54 +0000790 // Add all the filter values.
791 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
792 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000793 goto done;
794 }
795
796 case EHScope::Terminate:
797 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000798 assert(!hasCatchAll);
799 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000800 goto done;
801
802 case EHScope::Catch:
803 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000804
Reid Kleckner2586aac2015-09-10 22:11:13 +0000805 case EHScope::PadEnd:
806 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCallbd309292010-07-06 01:34:17 +0000807 }
808
John McCall8e4c74b2011-08-11 02:22:43 +0000809 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
810 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
811 EHCatchScope::Handler handler = catchScope.getHandler(hi);
Reid Kleckner10aa7702015-09-16 20:15:55 +0000812 assert(handler.Type.Flags == 0 &&
813 "landingpads do not support catch handler flags");
John McCallbd309292010-07-06 01:34:17 +0000814
John McCall8e4c74b2011-08-11 02:22:43 +0000815 // If this is a catch-all, register that and abort.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000816 if (!handler.Type.RTTI) {
John McCall8e4c74b2011-08-11 02:22:43 +0000817 assert(!hasCatchAll);
818 hasCatchAll = true;
819 goto done;
John McCallbd309292010-07-06 01:34:17 +0000820 }
821
822 // Check whether we already have a handler for this type.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000823 if (catchTypes.insert(handler.Type.RTTI).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000824 // If not, add it directly to the landingpad.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000825 LPadInst->addClause(handler.Type.RTTI);
John McCallbd309292010-07-06 01:34:17 +0000826 }
John McCallbd309292010-07-06 01:34:17 +0000827 }
828
829 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000830 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000831 assert(!(hasCatchAll && hasFilter));
832 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000833 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000834
835 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000836 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000837 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000838 // Create a filter expression: a constant array indicating which filter
839 // types there are. The personality routine only lands here if the filter
840 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000841 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000842 llvm::ArrayType *AType =
843 llvm::ArrayType::get(!filterTypes.empty() ?
844 filterTypes[0]->getType() : Int8PtrTy,
845 filterTypes.size());
846
847 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
848 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
849 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
850 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000851
852 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000853 if (hasCleanup)
854 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000855
856 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000857 } else if (hasCleanup) {
858 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000859 }
860
Bill Wendlingf0724e82011-09-19 20:31:14 +0000861 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
862 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000863
864 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000865 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000866
867 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000868 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000869
John McCall8e4c74b2011-08-11 02:22:43 +0000870 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000871}
872
David Majnemerdbf10452015-07-31 17:58:45 +0000873static llvm::BasicBlock *emitMSVCCatchDispatchBlock(CodeGenFunction &CGF,
874 EHCatchScope &CatchScope) {
875 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
876 assert(DispatchBlock);
877
878 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
879 CGF.EmitBlockAfterUses(DispatchBlock);
880
881 // Figure out the next block.
882 llvm::BasicBlock *NextBlock = nullptr;
883
884 // Test against each of the exception types we claim to catch.
885 for (unsigned I = 0, E = CatchScope.getNumHandlers(); I < E; ++I) {
886 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
887
Reid Kleckner10aa7702015-09-16 20:15:55 +0000888 CatchTypeInfo TypeInfo = Handler.Type;
889 if (!TypeInfo.RTTI)
890 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
David Majnemerdbf10452015-07-31 17:58:45 +0000891
892 // If this is the last handler, we're at the end, and the next
893 // block is the block for the enclosing EH scope.
894 if (I + 1 == E) {
895 NextBlock = CGF.createBasicBlock("catchendblock");
John McCall7f416cc2015-09-08 08:05:57 +0000896 CGBuilderTy(CGF, NextBlock).CreateCatchEndPad(
David Majnemerdbf10452015-07-31 17:58:45 +0000897 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope()));
898 } else {
899 NextBlock = CGF.createBasicBlock("catch.dispatch");
900 }
901
902 if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000903 CGF.Builder.CreateCatchPad(Handler.Block, NextBlock,
904 {TypeInfo.RTTI,
905 CGF.Builder.getInt32(TypeInfo.Flags),
906 llvm::Constant::getNullValue(CGF.VoidPtrTy)});
David Majnemerdbf10452015-07-31 17:58:45 +0000907 } else {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000908 CGF.Builder.CreateCatchPad(Handler.Block, NextBlock, {TypeInfo.RTTI});
David Majnemerdbf10452015-07-31 17:58:45 +0000909 }
910
911 // Otherwise we need to emit and continue at that block.
912 CGF.EmitBlock(NextBlock);
913 }
914 CGF.Builder.restoreIP(SavedIP);
915
916 return NextBlock;
917}
918
John McCall8e4c74b2011-08-11 02:22:43 +0000919/// Emit the structure of the dispatch block for the given catch scope.
920/// It is an invariant that the dispatch block already exists.
David Majnemerdbf10452015-07-31 17:58:45 +0000921/// If the catchblock instructions are used for EH dispatch, then the basic
922/// block holding the final catchendblock instruction is returned.
923static llvm::BasicBlock *emitCatchDispatchBlock(CodeGenFunction &CGF,
924 EHCatchScope &catchScope) {
925 if (CGF.CGM.getCodeGenOpts().NewMSEH &&
926 EHPersonality::get(CGF).isMSVCPersonality())
927 return emitMSVCCatchDispatchBlock(CGF, catchScope);
928
John McCall8e4c74b2011-08-11 02:22:43 +0000929 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
930 assert(dispatchBlock);
931
932 // If there's only a single catch-all, getEHDispatchBlock returned
933 // that catch-all as the dispatch block.
934 if (catchScope.getNumHandlers() == 1 &&
935 catchScope.getHandler(0).isCatchAll()) {
936 assert(dispatchBlock == catchScope.getHandler(0).Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000937 return nullptr;
John McCall8e4c74b2011-08-11 02:22:43 +0000938 }
939
940 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
941 CGF.EmitBlockAfterUses(dispatchBlock);
942
943 // Select the right handler.
944 llvm::Value *llvm_eh_typeid_for =
945 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
946
947 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000948 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000949
950 // Test against each of the exception types we claim to catch.
951 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
952 assert(i < e && "ran off end of handlers!");
953 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
954
Reid Kleckner10aa7702015-09-16 20:15:55 +0000955 llvm::Value *typeValue = handler.Type.RTTI;
956 assert(handler.Type.Flags == 0 &&
957 "landingpads do not support catch handler flags");
John McCall8e4c74b2011-08-11 02:22:43 +0000958 assert(typeValue && "fell into catch-all case!");
959 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
960
961 // Figure out the next block.
962 bool nextIsEnd;
963 llvm::BasicBlock *nextBlock;
964
965 // If this is the last handler, we're at the end, and the next
966 // block is the block for the enclosing EH scope.
967 if (i + 1 == e) {
968 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
969 nextIsEnd = true;
970
971 // If the next handler is a catch-all, we're at the end, and the
972 // next block is that handler.
973 } else if (catchScope.getHandler(i+1).isCatchAll()) {
974 nextBlock = catchScope.getHandler(i+1).Block;
975 nextIsEnd = true;
976
977 // Otherwise, we're not at the end and we need a new block.
978 } else {
979 nextBlock = CGF.createBasicBlock("catch.fallthrough");
980 nextIsEnd = false;
981 }
982
983 // Figure out the catch type's index in the LSDA's type table.
984 llvm::CallInst *typeIndex =
985 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
986 typeIndex->setDoesNotThrow();
987
988 llvm::Value *matchesTypeIndex =
989 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
990 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
991
992 // If the next handler is a catch-all, we're completely done.
993 if (nextIsEnd) {
994 CGF.Builder.restoreIP(savedIP);
David Majnemerdbf10452015-07-31 17:58:45 +0000995 return nullptr;
John McCall8e4c74b2011-08-11 02:22:43 +0000996 }
Ahmed Charles289896d2012-02-19 11:57:29 +0000997 // Otherwise we need to emit and continue at that block.
998 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +0000999 }
David Majnemerdbf10452015-07-31 17:58:45 +00001000 return nullptr;
John McCall8e4c74b2011-08-11 02:22:43 +00001001}
1002
1003void CodeGenFunction::popCatchScope() {
1004 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1005 if (catchScope.hasEHBranches())
1006 emitCatchDispatchBlock(*this, catchScope);
1007 EHStack.popCatch();
1008}
1009
John McCallb609d3f2010-07-07 06:56:46 +00001010void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001011 unsigned NumHandlers = S.getNumHandlers();
1012 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1013 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001014
John McCall8e4c74b2011-08-11 02:22:43 +00001015 // If the catch was not required, bail out now.
1016 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001017 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001018 EHStack.popCatch();
1019 return;
1020 }
1021
1022 // Emit the structure of the EH dispatch for this catch.
David Majnemerdbf10452015-07-31 17:58:45 +00001023 llvm::BasicBlock *CatchEndBlockBB = emitCatchDispatchBlock(*this, CatchScope);
John McCall8e4c74b2011-08-11 02:22:43 +00001024
John McCallbd309292010-07-06 01:34:17 +00001025 // Copy the handler blocks off before we pop the EH stack. Emitting
1026 // the handlers might scribble on this memory.
Benjamin Kramerda32cf82015-08-04 15:38:49 +00001027 SmallVector<EHCatchScope::Handler, 8> Handlers(
1028 CatchScope.begin(), CatchScope.begin() + NumHandlers);
John McCall8e4c74b2011-08-11 02:22:43 +00001029
John McCallbd309292010-07-06 01:34:17 +00001030 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001031
John McCallbd309292010-07-06 01:34:17 +00001032 // The fall-through block.
1033 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001034
John McCallbd309292010-07-06 01:34:17 +00001035 // We just emitted the body of the try; jump to the continue block.
1036 if (HaveInsertPoint())
1037 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001038
John McCalld8d00be2012-06-15 05:27:05 +00001039 // Determine if we need an implicit rethrow for all these catch handlers;
1040 // see the comment below.
1041 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001042 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001043 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1044 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001045
David Majnemerdbf10452015-07-31 17:58:45 +00001046 if (CatchEndBlockBB)
Reid Kleckner2586aac2015-09-10 22:11:13 +00001047 EHStack.pushPadEnd(CatchEndBlockBB);
David Majnemerdbf10452015-07-31 17:58:45 +00001048
John McCall8e4c74b2011-08-11 02:22:43 +00001049 // Perversely, we emit the handlers backwards precisely because we
1050 // want them to appear in source order. In all of these cases, the
1051 // catch block will have exactly one predecessor, which will be a
1052 // particular block in the catch dispatch. However, in the case of
1053 // a catch-all, one of the dispatch blocks will branch to two
1054 // different handlers, and EmitBlockAfterUses will cause the second
1055 // handler to be moved before the first.
1056 for (unsigned I = NumHandlers; I != 0; --I) {
1057 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1058 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001059
John McCallbd309292010-07-06 01:34:17 +00001060 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001061 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001062
John McCallbd309292010-07-06 01:34:17 +00001063 // Enter a cleanup scope, including the catch variable and the
1064 // end-catch.
1065 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001066
John McCallbd309292010-07-06 01:34:17 +00001067 // Initialize the catch variable and set up the cleanups.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001068 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallbd309292010-07-06 01:34:17 +00001069
Justin Bognerea278c32014-01-07 00:20:28 +00001070 // Emit the PGO counter increment.
Justin Bogner66242d62015-04-23 23:06:47 +00001071 incrementProfileCounter(C);
Justin Bogneref512b92014-01-06 22:27:43 +00001072
John McCallbd309292010-07-06 01:34:17 +00001073 // Perform the body of the catch.
1074 EmitStmt(C->getHandlerBlock());
1075
John McCalld8d00be2012-06-15 05:27:05 +00001076 // [except.handle]p11:
1077 // The currently handled exception is rethrown if control
1078 // reaches the end of a handler of the function-try-block of a
1079 // constructor or destructor.
1080
1081 // It is important that we only do this on fallthrough and not on
1082 // return. Note that it's illegal to put a return in a
1083 // constructor function-try-block's catch handler (p14), so this
1084 // really only applies to destructors.
1085 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +00001086 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +00001087 Builder.CreateUnreachable();
1088 Builder.ClearInsertionPoint();
1089 }
1090
John McCallbd309292010-07-06 01:34:17 +00001091 // Fall out through the catch cleanups.
1092 CatchScope.ForceCleanup();
1093
1094 // Branch out of the try.
1095 if (HaveInsertPoint())
1096 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001097 }
1098
John McCallbd309292010-07-06 01:34:17 +00001099 EmitBlock(ContBB);
Justin Bogner66242d62015-04-23 23:06:47 +00001100 incrementProfileCounter(&S);
David Majnemerdbf10452015-07-31 17:58:45 +00001101 if (CatchEndBlockBB)
Reid Kleckner2586aac2015-09-10 22:11:13 +00001102 EHStack.popPadEnd();
Mike Stump58ef18b2009-11-20 23:44:51 +00001103}
Mike Stumpaff69af2009-12-09 03:35:49 +00001104
John McCall1e670402010-07-21 00:52:03 +00001105namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001106 struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001107 llvm::Value *ForEHVar;
1108 llvm::Value *EndCatchFn;
1109 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1110 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1111
Craig Topper4f12f102014-03-12 06:41:41 +00001112 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001113 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1114 llvm::BasicBlock *CleanupContBB =
1115 CGF.createBasicBlock("finally.cleanup.cont");
1116
1117 llvm::Value *ShouldEndCatch =
John McCall7f416cc2015-09-08 08:05:57 +00001118 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
John McCall1e670402010-07-21 00:52:03 +00001119 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1120 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001121 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001122 CGF.EmitBlock(CleanupContBB);
1123 }
1124 };
John McCall906da4b2010-07-21 05:47:49 +00001125
David Blaikie7e70d682015-08-18 22:40:54 +00001126 struct PerformFinally final : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001127 const Stmt *Body;
1128 llvm::Value *ForEHVar;
1129 llvm::Value *EndCatchFn;
1130 llvm::Value *RethrowFn;
1131 llvm::Value *SavedExnVar;
1132
1133 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1134 llvm::Value *EndCatchFn,
1135 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1136 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1137 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1138
Craig Topper4f12f102014-03-12 06:41:41 +00001139 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001140 // Enter a cleanup to call the end-catch function if one was provided.
1141 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001142 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1143 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001144
John McCallcebe0ca2010-08-11 00:16:14 +00001145 // Save the current cleanup destination in case there are
1146 // cleanups in the finally block.
1147 llvm::Value *SavedCleanupDest =
1148 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1149 "cleanup.dest.saved");
1150
John McCall906da4b2010-07-21 05:47:49 +00001151 // Emit the finally block.
1152 CGF.EmitStmt(Body);
1153
1154 // If the end of the finally is reachable, check whether this was
1155 // for EH. If so, rethrow.
1156 if (CGF.HaveInsertPoint()) {
1157 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1158 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1159
1160 llvm::Value *ShouldRethrow =
John McCall7f416cc2015-09-08 08:05:57 +00001161 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
John McCall906da4b2010-07-21 05:47:49 +00001162 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1163
1164 CGF.EmitBlock(RethrowBB);
1165 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001166 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
John McCall7f416cc2015-09-08 08:05:57 +00001167 CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
John McCall906da4b2010-07-21 05:47:49 +00001168 } else {
John McCall882987f2013-02-28 19:01:20 +00001169 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001170 }
1171 CGF.Builder.CreateUnreachable();
1172
1173 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001174
1175 // Restore the cleanup destination.
1176 CGF.Builder.CreateStore(SavedCleanupDest,
1177 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001178 }
1179
1180 // Leave the end-catch cleanup. As an optimization, pretend that
1181 // the fallthrough path was inaccessible; we've dynamically proven
1182 // that we're not in the EH case along that path.
1183 if (EndCatchFn) {
1184 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1185 CGF.PopCleanupBlock();
1186 CGF.Builder.restoreIP(SavedIP);
1187 }
1188
1189 // Now make sure we actually have an insertion point or the
1190 // cleanup gods will hate us.
1191 CGF.EnsureInsertPoint();
1192 }
1193 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001194} // end anonymous namespace
John McCall1e670402010-07-21 00:52:03 +00001195
John McCallbd309292010-07-06 01:34:17 +00001196/// Enters a finally block for an implementation using zero-cost
1197/// exceptions. This is mostly general, but hard-codes some
1198/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001199void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1200 const Stmt *body,
1201 llvm::Constant *beginCatchFn,
1202 llvm::Constant *endCatchFn,
1203 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001204 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001205 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001206 assert(rethrowFn && "rethrow function is required");
1207
1208 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001209
John McCallbd309292010-07-06 01:34:17 +00001210 // The rethrow function has one of the following two types:
1211 // void (*)()
1212 // void (*)(void*)
1213 // In the latter case we need to pass it the exception object.
1214 // But we can't use the exception slot because the @finally might
1215 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001216 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001217 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001218 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001219 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001220 if (rethrowFnTy->getNumParams())
1221 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001222
John McCallbd309292010-07-06 01:34:17 +00001223 // A finally block is a statement which must be executed on any edge
1224 // out of a given scope. Unlike a cleanup, the finally block may
1225 // contain arbitrary control flow leading out of itself. In
1226 // addition, finally blocks should always be executed, even if there
1227 // are no catch handlers higher on the stack. Therefore, we
1228 // surround the protected scope with a combination of a normal
1229 // cleanup (to catch attempts to break out of the block via normal
1230 // control flow) and an EH catch-all (semantically "outside" any try
1231 // statement to which the finally block might have been attached).
1232 // The finally block itself is generated in the context of a cleanup
1233 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001234
John McCallbd309292010-07-06 01:34:17 +00001235 // Jump destination for performing the finally block on an exception
1236 // edge. We'll never actually reach this block, so unreachable is
1237 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001238 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001239
John McCallbd309292010-07-06 01:34:17 +00001240 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001241 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
John McCall7f416cc2015-09-08 08:05:57 +00001242 CGF.Builder.CreateFlagStore(false, ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001243
John McCallbd309292010-07-06 01:34:17 +00001244 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001245 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1246 ForEHVar, endCatchFn,
1247 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001248
1249 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001250 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1251 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1252 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001253}
1254
John McCall6b0feb72011-06-22 02:32:12 +00001255void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001256 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001257 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1258 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001259
1260 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001261
John McCall6b0feb72011-06-22 02:32:12 +00001262 // If there are any references to the catch-all block, emit it.
1263 if (catchBB->use_empty()) {
1264 delete catchBB;
1265 } else {
1266 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1267 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001268
Craig Topper8a13c412014-05-21 05:09:00 +00001269 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001270
John McCall6b0feb72011-06-22 02:32:12 +00001271 // If there's a begin-catch function, call it.
1272 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001273 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001274 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001275 }
1276
1277 // If we need to remember the exception pointer to rethrow later, do so.
1278 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001279 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall7f416cc2015-09-08 08:05:57 +00001280 CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
John McCall6b0feb72011-06-22 02:32:12 +00001281 }
1282
1283 // Tell the cleanups in the finally block that we're do this for EH.
John McCall7f416cc2015-09-08 08:05:57 +00001284 CGF.Builder.CreateFlagStore(true, ForEHVar);
John McCall6b0feb72011-06-22 02:32:12 +00001285
1286 // Thread a jump through the finally cleanup.
1287 CGF.EmitBranchThroughCleanup(RethrowDest);
1288
1289 CGF.Builder.restoreIP(savedIP);
1290 }
1291
1292 // Finally, leave the @finally cleanup.
1293 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001294}
1295
1296llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1297 if (TerminateLandingPad)
1298 return TerminateLandingPad;
1299
1300 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1301
1302 // This will get inserted at the end of the function.
1303 TerminateLandingPad = createBasicBlock("terminate.lpad");
1304 Builder.SetInsertPoint(TerminateLandingPad);
1305
1306 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001307 const EHPersonality &Personality = EHPersonality::get(*this);
David Majnemerfcbdb6e2015-06-17 20:53:19 +00001308
1309 if (!CurFn->hasPersonalityFn())
1310 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1311
1312 llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
1313 llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001314 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001315
Hans Wennborgdcfba332015-10-06 23:40:43 +00001316 llvm::Value *Exn = nullptr;
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001317 if (getLangOpts().CPlusPlus)
1318 Exn = Builder.CreateExtractValue(LPadInst, 0);
1319 llvm::CallInst *terminateCall =
1320 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCalle142ad52013-02-12 03:51:46 +00001321 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001322 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001323
John McCallbd309292010-07-06 01:34:17 +00001324 // Restore the saved insertion state.
1325 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001326
John McCallbd309292010-07-06 01:34:17 +00001327 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001328}
Mike Stump2b488872009-12-09 22:59:31 +00001329
1330llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001331 if (TerminateHandler)
1332 return TerminateHandler;
1333
John McCallbd309292010-07-06 01:34:17 +00001334 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001335
John McCallbd309292010-07-06 01:34:17 +00001336 // Set up the terminate handler. This block is inserted at the very
1337 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001338 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001339 Builder.SetInsertPoint(TerminateHandler);
David Majnemerdbf10452015-07-31 17:58:45 +00001340 if (CGM.getCodeGenOpts().NewMSEH &&
1341 EHPersonality::get(*this).isMSVCPersonality()) {
1342 Builder.CreateTerminatePad(/*UnwindBB=*/nullptr, CGM.getTerminateFn());
1343 } else {
Hans Wennborgdcfba332015-10-06 23:40:43 +00001344 llvm::Value *Exn = nullptr;
David Majnemerdbf10452015-07-31 17:58:45 +00001345 if (getLangOpts().CPlusPlus)
1346 Exn = getExceptionFromSlot();
1347 llvm::CallInst *terminateCall =
1348 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1349 terminateCall->setDoesNotReturn();
1350 Builder.CreateUnreachable();
1351 }
Mike Stump2b488872009-12-09 22:59:31 +00001352
John McCall21886962010-04-21 10:05:39 +00001353 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001354 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001355
Mike Stump2b488872009-12-09 22:59:31 +00001356 return TerminateHandler;
1357}
John McCallbd309292010-07-06 01:34:17 +00001358
David Chisnall9a837be2012-11-07 16:50:40 +00001359llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001360 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001361
1362 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1363
1364 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001365 EHResumeBlock = createBasicBlock("eh.resume");
1366 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001367
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001368 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001369
1370 // This can always be a call because we necessarily didn't find
1371 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001372 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001373 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001374 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Nico Weberff62a6a2015-02-26 22:34:33 +00001375 getExceptionFromSlot())->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001376 Builder.CreateUnreachable();
1377 Builder.restoreIP(SavedIP);
1378 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001379 }
1380
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001381 // Recreate the landingpad's return value for the 'resume' instruction.
1382 llvm::Value *Exn = getExceptionFromSlot();
1383 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001384
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001385 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
Reid Kleckneree7cf842014-12-01 22:02:27 +00001386 Sel->getType(), nullptr);
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001387 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1388 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1389 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1390
1391 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001392 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001393 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001394}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001395
1396void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001397 EnterSEHTryStmt(S);
Reid Klecknera5930002015-02-11 21:40:48 +00001398 {
Nico Weber5779f842015-02-12 23:16:11 +00001399 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
Nico Weber5779f842015-02-12 23:16:11 +00001400
Reid Kleckner11c033e2015-02-12 23:40:45 +00001401 SEHTryEpilogueStack.push_back(&TryExit);
Reid Klecknera5930002015-02-11 21:40:48 +00001402 EmitStmt(S.getTryBlock());
Reid Kleckner11c033e2015-02-12 23:40:45 +00001403 SEHTryEpilogueStack.pop_back();
Nico Weber5779f842015-02-12 23:16:11 +00001404
1405 if (!TryExit.getBlock()->use_empty())
1406 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1407 else
1408 delete TryExit.getBlock();
Reid Klecknera5930002015-02-11 21:40:48 +00001409 }
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001410 ExitSEHTryStmt(S);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001411}
1412
1413namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001414struct PerformSEHFinally final : EHScopeStack::Cleanup {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001415 llvm::Function *OutlinedFinally;
Reid Kleckner2586aac2015-09-10 22:11:13 +00001416 EHScopeStack::stable_iterator EnclosingScope;
1417 PerformSEHFinally(llvm::Function *OutlinedFinally,
1418 EHScopeStack::stable_iterator EnclosingScope)
1419 : OutlinedFinally(OutlinedFinally), EnclosingScope(EnclosingScope) {}
Reid Kleckneraca01db2015-02-04 22:37:07 +00001420
Reid Kleckner1d59f992015-01-22 01:36:17 +00001421 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001422 ASTContext &Context = CGF.getContext();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001423 CodeGenModule &CGM = CGF.CGM;
Reid Kleckner65870442015-06-09 17:47:50 +00001424
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001425 CallArgList Args;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001426
1427 // Compute the two argument values.
1428 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
Reid Kleckner15d152d2015-07-07 23:23:31 +00001429 llvm::Value *LocalAddrFn = CGM.getIntrinsic(llvm::Intrinsic::localaddress);
David Blaikie4ba525b2015-07-14 17:27:39 +00001430 llvm::Value *FP = CGF.Builder.CreateCall(LocalAddrFn);
Reid Klecknereb11c412015-07-01 21:00:00 +00001431 llvm::Value *IsForEH =
1432 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1433 Args.add(RValue::get(IsForEH), ArgTys[0]);
1434 Args.add(RValue::get(FP), ArgTys[1]);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001435
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001436 // Arrange a two-arg function info and type.
1437 FunctionProtoType::ExtProtoInfo EPI;
1438 const auto *FPT = cast<FunctionProtoType>(
1439 Context.getFunctionType(Context.VoidTy, ArgTys, EPI));
Reid Klecknereb11c412015-07-01 21:00:00 +00001440 const CGFunctionInfo &FnInfo =
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001441 CGM.getTypes().arrangeFreeFunctionCall(Args, FPT,
1442 /*chainCall=*/false);
1443
Reid Kleckner2586aac2015-09-10 22:11:13 +00001444 // If this is the normal cleanup or using the old EH IR, just emit the call.
1445 if (!F.isForEHCleanup() || !CGM.getCodeGenOpts().NewMSEH) {
1446 CGF.EmitCall(FnInfo, OutlinedFinally, ReturnValueSlot(), Args);
1447 return;
1448 }
1449
1450 // Build a cleanupendpad to unwind through.
1451 llvm::BasicBlock *CleanupBB = CGF.Builder.GetInsertBlock();
1452 llvm::BasicBlock *CleanupEndBB = CGF.createBasicBlock("ehcleanup.end");
1453 llvm::Instruction *PadInst = CleanupBB->getFirstNonPHI();
1454 auto *CPI = cast<llvm::CleanupPadInst>(PadInst);
1455 CGBuilderTy(CGF, CleanupEndBB)
1456 .CreateCleanupEndPad(CPI, CGF.getEHDispatchBlock(EnclosingScope));
1457
1458 // Push and pop the cleanupendpad around the call.
1459 CGF.EHStack.pushPadEnd(CleanupEndBB);
Reid Klecknereb11c412015-07-01 21:00:00 +00001460 CGF.EmitCall(FnInfo, OutlinedFinally, ReturnValueSlot(), Args);
Reid Kleckner2586aac2015-09-10 22:11:13 +00001461 CGF.EHStack.popPadEnd();
1462
1463 // Insert the catchendpad block here.
1464 CGF.CurFn->getBasicBlockList().insertAfter(CGF.Builder.GetInsertBlock(),
1465 CleanupEndBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001466 }
1467};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001468} // end anonymous namespace
Reid Kleckner1d59f992015-01-22 01:36:17 +00001469
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001470namespace {
1471/// Find all local variable captures in the statement.
1472struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1473 CodeGenFunction &ParentCGF;
1474 const VarDecl *ParentThis;
John McCall0a490152015-09-08 21:15:22 +00001475 llvm::SmallSetVector<const VarDecl *, 4> Captures;
John McCall7f416cc2015-09-08 08:05:57 +00001476 Address SEHCodeSlot = Address::invalid();
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001477 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1478 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1479
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001480 // Return true if we need to do any capturing work.
1481 bool foundCaptures() {
John McCall7f416cc2015-09-08 08:05:57 +00001482 return !Captures.empty() || SEHCodeSlot.isValid();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001483 }
1484
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001485 void Visit(const Stmt *S) {
1486 // See if this is a capture, then recurse.
1487 ConstStmtVisitor<CaptureFinder>::Visit(S);
1488 for (const Stmt *Child : S->children())
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001489 if (Child)
1490 Visit(Child);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001491 }
1492
1493 void VisitDeclRefExpr(const DeclRefExpr *E) {
1494 // If this is already a capture, just make sure we capture 'this'.
1495 if (E->refersToEnclosingVariableOrCapture()) {
John McCall0a490152015-09-08 21:15:22 +00001496 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001497 return;
1498 }
1499
1500 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1501 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
John McCall0a490152015-09-08 21:15:22 +00001502 Captures.insert(D);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001503 }
1504
1505 void VisitCXXThisExpr(const CXXThisExpr *E) {
John McCall0a490152015-09-08 21:15:22 +00001506 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001507 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001508
1509 void VisitCallExpr(const CallExpr *E) {
1510 // We only need to add parent frame allocations for these builtins in x86.
1511 if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1512 return;
1513
1514 unsigned ID = E->getBuiltinCallee();
1515 switch (ID) {
1516 case Builtin::BI__exception_code:
1517 case Builtin::BI_exception_code:
1518 // This is the simple case where we are the outermost finally. All we
1519 // have to do here is make sure we escape this and recover it in the
1520 // outlined handler.
John McCall7f416cc2015-09-08 08:05:57 +00001521 if (!SEHCodeSlot.isValid())
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001522 SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1523 break;
1524 }
1525 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001526};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001527} // end anonymous namespace
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001528
John McCall7f416cc2015-09-08 08:05:57 +00001529Address CodeGenFunction::recoverAddrOfEscapedLocal(
1530 CodeGenFunction &ParentCGF, Address ParentVar, llvm::Value *ParentFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001531 llvm::CallInst *RecoverCall = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00001532 CGBuilderTy Builder(*this, AllocaInsertPt);
1533 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001534 // Mark the variable escaped if nobody else referenced it and compute the
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001535 // localescape index.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001536 auto InsertPair = ParentCGF.EscapedLocals.insert(
1537 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1538 int FrameEscapeIdx = InsertPair.first->second;
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001539 // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001540 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001541 &CGM.getModule(), llvm::Intrinsic::localrecover);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001542 llvm::Constant *ParentI8Fn =
1543 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1544 RecoverCall = Builder.CreateCall(
1545 FrameRecoverFn, {ParentI8Fn, ParentFP,
1546 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1547
1548 } else {
1549 // If the parent didn't have an alloca, we're doing some nested outlining.
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001550 // Just clone the existing localrecover call, but tweak the FP argument to
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001551 // use our FP value. All other arguments are constants.
1552 auto *ParentRecover =
John McCall7f416cc2015-09-08 08:05:57 +00001553 cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001554 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1555 "expected alloca or localrecover in parent LocalDeclMap");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001556 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1557 RecoverCall->setArgOperand(1, ParentFP);
1558 RecoverCall->insertBefore(AllocaInsertPt);
1559 }
1560
1561 // Bitcast the variable, rename it, and insert it in the local decl map.
1562 llvm::Value *ChildVar =
John McCall7f416cc2015-09-08 08:05:57 +00001563 Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1564 ChildVar->setName(ParentVar.getName());
1565 return Address(ChildVar, ParentVar.getAlignment());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001566}
1567
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001568void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
Reid Kleckner0b9bbbf2015-06-09 17:49:42 +00001569 const Stmt *OutlinedStmt,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001570 bool IsFilter) {
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001571 // Find all captures in the Stmt.
1572 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1573 Finder.Visit(OutlinedStmt);
1574
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001575 // We can exit early on x86_64 when there are no captures. We just have to
1576 // save the exception code in filters so that __exception_code() works.
1577 if (!Finder.foundCaptures() &&
1578 CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1579 if (IsFilter)
1580 EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001581 return;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001582 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001583
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001584 llvm::Value *EntryEBP = nullptr;
1585 llvm::Value *ParentFP;
1586 if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1587 // 32-bit SEH filters need to be careful about FP recovery. The end of the
1588 // EH registration is passed in as the EBP physical register. We can
1589 // recover that with llvm.frameaddress(1), and adjust that to recover the
1590 // parent's true frame pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001591 CGBuilderTy Builder(CGM, AllocaInsertPt);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001592 EntryEBP = Builder.CreateCall(
1593 CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
1594 llvm::Function *RecoverFPIntrin =
1595 CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
1596 llvm::Constant *ParentI8Fn =
1597 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1598 ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryEBP});
1599 } else {
1600 // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1601 // second parameter.
1602 auto AI = CurFn->arg_begin();
1603 ++AI;
1604 ParentFP = AI;
1605 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001606
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001607 // Create llvm.localrecover calls for all captures.
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001608 for (const VarDecl *VD : Finder.Captures) {
1609 if (isa<ImplicitParamDecl>(VD)) {
1610 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1611 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1612 continue;
1613 }
1614 if (VD->getType()->isVariablyModifiedType()) {
1615 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1616 continue;
1617 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001618 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1619 "captured non-local variable");
1620
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001621 // If this decl hasn't been declared yet, it will be declared in the
1622 // OutlinedStmt.
1623 auto I = ParentCGF.LocalDeclMap.find(VD);
1624 if (I == ParentCGF.LocalDeclMap.end())
1625 continue;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001626
John McCall7f416cc2015-09-08 08:05:57 +00001627 Address ParentVar = I->second;
1628 setAddrOfLocalVar(VD,
1629 recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
Nico Webere4f974c2015-07-02 06:10:53 +00001630 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001631
John McCall7f416cc2015-09-08 08:05:57 +00001632 if (Finder.SEHCodeSlot.isValid()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001633 SEHCodeSlotStack.push_back(
1634 recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1635 }
1636
1637 if (IsFilter)
1638 EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryEBP);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001639}
1640
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001641/// Arrange a function prototype that can be called by Windows exception
1642/// handling personalities. On Win64, the prototype looks like:
1643/// RetTy func(void *EHPtrs, void *ParentFP);
1644void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001645 bool IsFilter,
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001646 const Stmt *OutlinedStmt) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001647 SourceLocation StartLoc = OutlinedStmt->getLocStart();
1648
1649 // Get the mangled function name.
1650 SmallString<128> Name;
1651 {
1652 llvm::raw_svector_ostream OS(Name);
1653 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1654 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1655 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1656 MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1657 if (IsFilter)
1658 Mangler.mangleSEHFilterExpression(Parent, OS);
1659 else
1660 Mangler.mangleSEHFinallyBlock(Parent, OS);
1661 }
1662
1663 FunctionArgList Args;
1664 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1665 // All SEH finally functions take two parameters. Win64 filters take two
1666 // parameters. Win32 filters take no parameters.
1667 if (IsFilter) {
1668 Args.push_back(ImplicitParamDecl::Create(
1669 getContext(), nullptr, StartLoc,
1670 &getContext().Idents.get("exception_pointers"),
1671 getContext().VoidPtrTy));
1672 } else {
1673 Args.push_back(ImplicitParamDecl::Create(
1674 getContext(), nullptr, StartLoc,
1675 &getContext().Idents.get("abnormal_termination"),
1676 getContext().UnsignedCharTy));
1677 }
1678 Args.push_back(ImplicitParamDecl::Create(
1679 getContext(), nullptr, StartLoc,
1680 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1681 }
1682
1683 QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1684
Reid Kleckner1d59f992015-01-22 01:36:17 +00001685 llvm::Function *ParentFn = ParentCGF.CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001686 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1687 RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001688
Reid Kleckner1d59f992015-01-22 01:36:17 +00001689 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001690 llvm::Function *Fn = llvm::Function::Create(
1691 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001692 // The filter is either in the same comdat as the function, or it's internal.
1693 if (llvm::Comdat *C = ParentFn->getComdat()) {
1694 Fn->setComdat(C);
1695 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001696 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1697 ParentFn->setComdat(C);
1698 Fn->setComdat(C);
1699 } else {
1700 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1701 }
1702
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001703 IsOutlinedSEHHelper = true;
Nico Weberf2a39a72015-04-13 20:03:03 +00001704
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001705 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1706 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
1707
1708 CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001709 EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001710}
1711
1712/// Create a stub filter function that will ultimately hold the code of the
1713/// filter expression. The EH preparation passes in LLVM will outline the code
1714/// from the main function body into this stub.
1715llvm::Function *
1716CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1717 const SEHExceptStmt &Except) {
1718 const Expr *FilterExpr = Except.getFilterExpr();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001719 startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001720
1721 // Emit the original filter expression, convert to i32, and return.
1722 llvm::Value *R = EmitScalarExpr(FilterExpr);
David Majnemer2ccba832015-04-17 06:57:25 +00001723 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
Reid Kleckner1d59f992015-01-22 01:36:17 +00001724 FilterExpr->getType()->isSignedIntegerType());
1725 Builder.CreateStore(R, ReturnValue);
1726
1727 FinishFunction(FilterExpr->getLocEnd());
1728
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001729 return CurFn;
1730}
1731
1732llvm::Function *
1733CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1734 const SEHFinallyStmt &Finally) {
1735 const Stmt *FinallyBlock = Finally.getBlock();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001736 startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001737
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001738 // Mark finally block calls as nounwind and noinline to make LLVM's job a
1739 // little easier.
1740 // FIXME: Remove these restrictions in the future.
1741 CurFn->addFnAttr(llvm::Attribute::NoUnwind);
1742 CurFn->addFnAttr(llvm::Attribute::NoInline);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001743
1744 // Emit the original filter expression, convert to i32, and return.
1745 EmitStmt(FinallyBlock);
1746
1747 FinishFunction(FinallyBlock->getLocEnd());
1748
1749 return CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001750}
1751
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001752void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1753 llvm::Value *ParentFP,
1754 llvm::Value *EntryEBP) {
1755 // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1756 // __exception_info intrinsic.
1757 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1758 // On Win64, the info is passed as the first parameter to the filter.
1759 auto AI = CurFn->arg_begin();
1760 SEHInfo = AI;
1761 SEHCodeSlotStack.push_back(
1762 CreateMemTemp(getContext().IntTy, "__exception_code"));
1763 } else {
1764 // On Win32, the EBP on entry to the filter points to the end of an
1765 // exception registration object. It contains 6 32-bit fields, and the info
1766 // pointer is stored in the second field. So, GEP 20 bytes backwards and
1767 // load the pointer.
1768 SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryEBP, -20);
1769 SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001770 SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001771 SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1772 ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1773 }
1774
Reid Kleckner1d59f992015-01-22 01:36:17 +00001775 // Save the exception code in the exception slot to unify exception access in
1776 // the filter function and the landing pad.
1777 // struct EXCEPTION_POINTERS {
1778 // EXCEPTION_RECORD *ExceptionRecord;
1779 // CONTEXT *ContextRecord;
1780 // };
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001781 // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001782 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1783 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001784 llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
David Blaikie1ed728c2015-04-05 22:45:47 +00001785 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001786 Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
1787 llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001788 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1789 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001790}
1791
1792llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1793 // Sema should diagnose calling this builtin outside of a filter context, but
1794 // don't crash if we screw up.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001795 if (!SEHInfo)
Reid Kleckner1d59f992015-01-22 01:36:17 +00001796 return llvm::UndefValue::get(Int8PtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001797 assert(SEHInfo->getType() == Int8PtrTy);
1798 return SEHInfo;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001799}
1800
1801llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001802 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
John McCall7f416cc2015-09-08 08:05:57 +00001803 return Builder.CreateLoad(SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001804}
1805
Reid Kleckneraca01db2015-02-04 22:37:07 +00001806llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001807 // Abnormal termination is just the first parameter to the outlined finally
1808 // helper.
1809 auto AI = CurFn->arg_begin();
1810 return Builder.CreateZExt(&*AI, Int32Ty);
Reid Kleckneraca01db2015-02-04 22:37:07 +00001811}
1812
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001813void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1814 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1815 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001816 // Outline the finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001817 llvm::Function *FinallyFunc =
1818 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001819
1820 // Push a cleanup for __finally blocks.
Reid Kleckner2586aac2015-09-10 22:11:13 +00001821 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc,
1822 EHStack.getInnermostEHScope());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001823 return;
1824 }
1825
1826 // Otherwise, we must have an __except block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001827 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001828 assert(Except);
1829 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001830 SEHCodeSlotStack.push_back(
1831 CreateMemTemp(getContext().IntTy, "__exception_code"));
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001832
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001833 // If the filter is known to evaluate to 1, then we can use the clause
1834 // "catch i8* null". We can't do this on x86 because the filter has to save
1835 // the exception code.
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001836 llvm::Constant *C =
1837 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001838 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
1839 C->isOneValue()) {
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001840 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1841 return;
1842 }
1843
1844 // In general, we have to emit an outlined filter function. Use the function
1845 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00001846 llvm::Function *FilterFunc =
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001847 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001848 llvm::Constant *OpaqueFunc =
1849 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
Reid Kleckner8be18472015-09-16 21:06:09 +00001850 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
Reid Kleckner1d59f992015-01-22 01:36:17 +00001851}
1852
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001853void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001854 // Just pop the cleanup if it's a __finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001855 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001856 PopCleanupBlock();
1857 return;
1858 }
1859
1860 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001861 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001862 assert(Except && "__try must have __finally xor __except");
1863 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1864
1865 // Don't emit the __except block if the __try block lacked invokes.
1866 // TODO: Model unwind edges from instructions, either with iload / istore or
1867 // a try body function.
1868 if (!CatchScope.hasEHBranches()) {
1869 CatchScope.clearHandlerBlocks();
1870 EHStack.popCatch();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001871 SEHCodeSlotStack.pop_back();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001872 return;
1873 }
1874
1875 // The fall-through block.
1876 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1877
1878 // We just emitted the body of the __try; jump to the continue block.
1879 if (HaveInsertPoint())
1880 Builder.CreateBr(ContBB);
1881
1882 // Check if our filter function returned true.
1883 emitCatchDispatchBlock(*this, CatchScope);
1884
1885 // Grab the block before we pop the handler.
1886 llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1887 EHStack.popCatch();
1888
1889 EmitBlockAfterUses(ExceptBB);
1890
Reid Klecknerbb34b602015-09-10 18:39:41 +00001891 if (CGM.getCodeGenOpts().NewMSEH) {
1892 // __except blocks don't get outlined into funclets, so immediately do a
1893 // catchret.
1894 llvm::BasicBlock *CatchPadBB = ExceptBB->getSinglePredecessor();
1895 assert(CatchPadBB && "only ExceptBB pred should be catchpad");
1896 llvm::CatchPadInst *CPI =
1897 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
1898 ExceptBB = createBasicBlock("__except");
1899 Builder.CreateCatchRet(CPI, ExceptBB);
1900 EmitBlock(ExceptBB);
1901 }
1902
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001903 // On Win64, the exception pointer is the exception code. Copy it to the slot.
1904 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1905 llvm::Value *Code =
1906 Builder.CreatePtrToInt(getExceptionFromSlot(), IntPtrTy);
1907 Code = Builder.CreateTrunc(Code, Int32Ty);
1908 Builder.CreateStore(Code, SEHCodeSlotStack.back());
1909 }
1910
Reid Kleckner1d59f992015-01-22 01:36:17 +00001911 // Emit the __except body.
1912 EmitStmt(Except->getBlock());
1913
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001914 // End the lifetime of the exception code.
1915 SEHCodeSlotStack.pop_back();
1916
Reid Kleckner3a417c32015-01-30 22:16:45 +00001917 if (HaveInsertPoint())
1918 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001919
1920 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00001921}
Nico Weber9b982072014-07-07 00:12:30 +00001922
1923void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00001924 // If this code is reachable then emit a stop point (if generating
1925 // debug info). We have to do this ourselves because we are on the
1926 // "simple" statement path.
1927 if (HaveInsertPoint())
1928 EmitStopPoint(&S);
1929
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001930 // This must be a __leave from a __finally block, which we warn on and is UB.
1931 // Just emit unreachable.
1932 if (!isSEHTryScope()) {
1933 Builder.CreateUnreachable();
1934 Builder.ClearInsertionPoint();
1935 return;
1936 }
1937
Nico Weber5779f842015-02-12 23:16:11 +00001938 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00001939}