blob: 4e9eb326c10c78cbf6dde8404d554f65764237a9 [file] [log] [blame]
Anders Carlsson756b5c42009-10-30 01:42:31 +00001//===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===//
2//
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"
Stephen Hines0e2c34f2015-03-23 12:09:02 -070015#include "CGCXXABI.h"
John McCall36f893c2011-01-28 11:13:47 +000016#include "CGCleanup.h"
Benjamin Krameraf2771b2012-02-08 12:41:24 +000017#include "CGObjCRuntime.h"
John McCall204b0752010-07-20 22:17:55 +000018#include "TargetInfo.h"
Stephen Hines0e2c34f2015-03-23 12:09:02 -070019#include "clang/AST/Mangle.h"
Benjamin Krameraf2771b2012-02-08 12:41:24 +000020#include "clang/AST/StmtCXX.h"
Chandler Carruthb1ba0ef2013-01-19 08:09:44 +000021#include "clang/AST/StmtObjC.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070022#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000023#include "llvm/IR/Intrinsics.h"
John McCallf1549f62010-07-06 01:34:17 +000024
Anders Carlsson756b5c42009-10-30 01:42:31 +000025using namespace clang;
26using namespace CodeGen;
27
John McCall629df012013-02-12 03:51:38 +000028static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
Anders Carlssond3379292009-10-30 02:27:02 +000029 // void *__cxa_allocate_exception(size_t thrown_size);
Mike Stump8755ec32009-12-10 00:06:18 +000030
Chris Lattner2acc6e32011-07-18 04:24:23 +000031 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000032 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000033
John McCall629df012013-02-12 03:51:38 +000034 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
Anders Carlssond3379292009-10-30 02:27:02 +000035}
36
John McCall629df012013-02-12 03:51:38 +000037static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump99533832009-12-02 07:41:41 +000038 // void __cxa_free_exception(void *thrown_exception);
Mike Stump8755ec32009-12-10 00:06:18 +000039
Chris Lattner2acc6e32011-07-18 04:24:23 +000040 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000041 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000042
John McCall629df012013-02-12 03:51:38 +000043 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump99533832009-12-02 07:41:41 +000044}
45
John McCall629df012013-02-12 03:51:38 +000046static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
Mike Stump8755ec32009-12-10 00:06:18 +000047 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +000048 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +000049
John McCall629df012013-02-12 03:51:38 +000050 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +000051 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000052 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000053
John McCall629df012013-02-12 03:51:38 +000054 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
Anders Carlssond3379292009-10-30 02:27:02 +000055}
56
John McCall629df012013-02-12 03:51:38 +000057static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
John McCallf1549f62010-07-06 01:34:17 +000058 // void *__cxa_get_exception_ptr(void*);
John McCallf1549f62010-07-06 01:34:17 +000059
Chris Lattner2acc6e32011-07-18 04:24:23 +000060 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000061 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCallf1549f62010-07-06 01:34:17 +000062
John McCall629df012013-02-12 03:51:38 +000063 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
John McCallf1549f62010-07-06 01:34:17 +000064}
65
John McCall629df012013-02-12 03:51:38 +000066static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -070067 if (CGM.getTarget().getCXXABI().isMicrosoft())
68 return CGM.getIntrinsic(llvm::Intrinsic::eh_begincatch);
69
John McCallf1549f62010-07-06 01:34:17 +000070 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +000071
Chris Lattner2acc6e32011-07-18 04:24:23 +000072 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000073 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000074
John McCall629df012013-02-12 03:51:38 +000075 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
Mike Stump2bf701e2009-11-20 23:44:51 +000076}
77
John McCall629df012013-02-12 03:51:38 +000078static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -070079 if (CGM.getTarget().getCXXABI().isMicrosoft())
80 return CGM.getIntrinsic(llvm::Intrinsic::eh_endcatch);
81
Mike Stump99533832009-12-02 07:41:41 +000082 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +000083
Chris Lattner2acc6e32011-07-18 04:24:23 +000084 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000085 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000086
John McCall629df012013-02-12 03:51:38 +000087 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
Mike Stump2bf701e2009-11-20 23:44:51 +000088}
89
John McCall629df012013-02-12 03:51:38 +000090static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith14b0e4b2013-06-20 23:03:35 +000091 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stumpcce3d4f2009-12-07 23:38:24 +000092
Chris Lattner2acc6e32011-07-18 04:24:23 +000093 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000094 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000095
John McCall629df012013-02-12 03:51:38 +000096 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stumpcce3d4f2009-12-07 23:38:24 +000097}
98
John McCall629df012013-02-12 03:51:38 +000099static llvm::Constant *getTerminateFn(CodeGenModule &CGM) {
Mike Stump99533832009-12-02 07:41:41 +0000100 // void __terminate();
101
Chris Lattner2acc6e32011-07-18 04:24:23 +0000102 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +0000103 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000104
Chris Lattner5f9e2722011-07-23 10:55:15 +0000105 StringRef name;
John McCall256a76e2011-07-06 01:22:26 +0000106
107 // In C++, use std::terminate().
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700108 if (CGM.getLangOpts().CPlusPlus &&
109 CGM.getTarget().getCXXABI().isItaniumFamily()) {
110 name = "_ZSt9terminatev";
111 } else if (CGM.getLangOpts().CPlusPlus &&
112 CGM.getTarget().getCXXABI().isMicrosoft()) {
113 name = "\01?terminate@@YAXXZ";
114 } else if (CGM.getLangOpts().ObjC1 &&
115 CGM.getLangOpts().ObjCRuntime.hasTerminate())
John McCall256a76e2011-07-06 01:22:26 +0000116 name = "objc_terminate";
117 else
118 name = "abort";
John McCall629df012013-02-12 03:51:38 +0000119 return CGM.CreateRuntimeFunction(FTy, name);
David Chisnall79a9ad82010-05-17 13:49:20 +0000120}
121
John McCall629df012013-02-12 03:51:38 +0000122static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000123 StringRef Name) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000124 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +0000125 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall8262b6a2010-07-17 00:43:08 +0000126
John McCall629df012013-02-12 03:51:38 +0000127 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000128}
129
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000130namespace {
131 /// The exceptions personality for a function.
132 struct EHPersonality {
133 const char *PersonalityFn;
134
135 // If this is non-null, this personality requires a non-standard
136 // function for rethrowing an exception after a catchall cleanup.
137 // This function must have prototype void(void*).
138 const char *CatchallRethrowFn;
139
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700140 static const EHPersonality &get(CodeGenModule &CGM,
141 const FunctionDecl *FD);
142 static const EHPersonality &get(CodeGenFunction &CGF) {
143 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
144 }
145
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000146 static const EHPersonality GNU_C;
147 static const EHPersonality GNU_C_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800148 static const EHPersonality GNU_C_SEH;
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000149 static const EHPersonality GNU_ObjC;
David Chisnall65bd4ac2013-01-11 15:33:01 +0000150 static const EHPersonality GNUstep_ObjC;
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000151 static const EHPersonality GNU_ObjCXX;
152 static const EHPersonality NeXT_ObjC;
153 static const EHPersonality GNU_CPlusPlus;
154 static const EHPersonality GNU_CPlusPlus_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800155 static const EHPersonality GNU_CPlusPlus_SEH;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700156 static const EHPersonality MSVC_except_handler;
157 static const EHPersonality MSVC_C_specific_handler;
158 static const EHPersonality MSVC_CxxFrameHandler3;
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000159 };
160}
161
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700162const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000163const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700164EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
165const EHPersonality
Stephen Hines176edba2014-12-01 14:53:08 -0800166EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
167const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700168EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
169const EHPersonality
170EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
171const EHPersonality
172EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000173const EHPersonality
Stephen Hines176edba2014-12-01 14:53:08 -0800174EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
175const EHPersonality
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000176EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
177const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700178EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall65bd4ac2013-01-11 15:33:01 +0000179const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700180EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700181const EHPersonality
182EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
183const EHPersonality
184EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
185const EHPersonality
186EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
John McCall8262b6a2010-07-17 00:43:08 +0000187
Stephen Hines176edba2014-12-01 14:53:08 -0800188/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
189/// other platforms, unless the user asked for SjLj exceptions.
190static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
191 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
192}
193
194static const EHPersonality &getCPersonality(const llvm::Triple &T,
195 const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000196 if (L.SjLjExceptions)
197 return EHPersonality::GNU_C_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800198 else if (useLibGCCSEHPersonality(T))
199 return EHPersonality::GNU_C_SEH;
John McCall8262b6a2010-07-17 00:43:08 +0000200 return EHPersonality::GNU_C;
201}
202
Stephen Hines176edba2014-12-01 14:53:08 -0800203static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
204 const LangOptions &L) {
John McCall260611a2012-06-20 06:18:46 +0000205 switch (L.ObjCRuntime.getKind()) {
206 case ObjCRuntime::FragileMacOSX:
Stephen Hines176edba2014-12-01 14:53:08 -0800207 return getCPersonality(T, L);
John McCall260611a2012-06-20 06:18:46 +0000208 case ObjCRuntime::MacOSX:
209 case ObjCRuntime::iOS:
210 return EHPersonality::NeXT_ObjC;
David Chisnall11d3f4c2012-07-03 20:49:52 +0000211 case ObjCRuntime::GNUstep:
David Chisnall65bd4ac2013-01-11 15:33:01 +0000212 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
213 return EHPersonality::GNUstep_ObjC;
214 // fallthrough
David Chisnall11d3f4c2012-07-03 20:49:52 +0000215 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000216 case ObjCRuntime::ObjFW:
John McCall8262b6a2010-07-17 00:43:08 +0000217 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000218 }
John McCall260611a2012-06-20 06:18:46 +0000219 llvm_unreachable("bad runtime kind");
John McCallf1549f62010-07-06 01:34:17 +0000220}
221
Stephen Hines176edba2014-12-01 14:53:08 -0800222static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
223 const LangOptions &L) {
John McCall8262b6a2010-07-17 00:43:08 +0000224 if (L.SjLjExceptions)
225 return EHPersonality::GNU_CPlusPlus_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800226 else if (useLibGCCSEHPersonality(T))
227 return EHPersonality::GNU_CPlusPlus_SEH;
228 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000229}
230
231/// Determines the personality function to use when both C++
232/// and Objective-C exceptions are being caught.
Stephen Hines176edba2014-12-01 14:53:08 -0800233static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
234 const LangOptions &L) {
John McCall260611a2012-06-20 06:18:46 +0000235 switch (L.ObjCRuntime.getKind()) {
John McCallf1549f62010-07-06 01:34:17 +0000236 // The ObjC personality defers to the C++ personality for non-ObjC
237 // handlers. Unlike the C++ case, we use the same personality
238 // function on targets using (backend-driven) SJLJ EH.
John McCall260611a2012-06-20 06:18:46 +0000239 case ObjCRuntime::MacOSX:
240 case ObjCRuntime::iOS:
241 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000242
John McCall260611a2012-06-20 06:18:46 +0000243 // In the fragile ABI, just use C++ exception handling and hope
244 // they're not doing crazy exception mixing.
245 case ObjCRuntime::FragileMacOSX:
Stephen Hines176edba2014-12-01 14:53:08 -0800246 return getCXXPersonality(T, L);
David Chisnall79a9ad82010-05-17 13:49:20 +0000247
David Chisnall11d3f4c2012-07-03 20:49:52 +0000248 // The GCC runtime's personality function inherently doesn't support
John McCall8262b6a2010-07-17 00:43:08 +0000249 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnall11d3f4c2012-07-03 20:49:52 +0000250 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000251 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnall11d3f4c2012-07-03 20:49:52 +0000252 return EHPersonality::GNU_ObjC;
253 case ObjCRuntime::GNUstep:
John McCall260611a2012-06-20 06:18:46 +0000254 return EHPersonality::GNU_ObjCXX;
255 }
256 llvm_unreachable("bad runtime kind");
John McCallf1549f62010-07-06 01:34:17 +0000257}
258
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700259static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
260 if (T.getArch() == llvm::Triple::x86)
261 return EHPersonality::MSVC_except_handler;
262 return EHPersonality::MSVC_C_specific_handler;
263}
264
265const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
266 const FunctionDecl *FD) {
Stephen Hines176edba2014-12-01 14:53:08 -0800267 const llvm::Triple &T = CGM.getTarget().getTriple();
268 const LangOptions &L = CGM.getLangOpts();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700269
270 // Try to pick a personality function that is compatible with MSVC if we're
271 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
272 // the GCC-style personality function.
273 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
274 if (L.SjLjExceptions)
275 return EHPersonality::GNU_CPlusPlus_SJLJ;
276 else if (FD && FD->usesSEHTry())
277 return getSEHPersonalityMSVC(T);
278 else
279 return EHPersonality::MSVC_CxxFrameHandler3;
280 }
281
John McCall8262b6a2010-07-17 00:43:08 +0000282 if (L.CPlusPlus && L.ObjC1)
Stephen Hines176edba2014-12-01 14:53:08 -0800283 return getObjCXXPersonality(T, L);
John McCall8262b6a2010-07-17 00:43:08 +0000284 else if (L.CPlusPlus)
Stephen Hines176edba2014-12-01 14:53:08 -0800285 return getCXXPersonality(T, L);
John McCall8262b6a2010-07-17 00:43:08 +0000286 else if (L.ObjC1)
Stephen Hines176edba2014-12-01 14:53:08 -0800287 return getObjCPersonality(T, L);
John McCallf1549f62010-07-06 01:34:17 +0000288 else
Stephen Hines176edba2014-12-01 14:53:08 -0800289 return getCPersonality(T, L);
John McCall8262b6a2010-07-17 00:43:08 +0000290}
John McCallf1549f62010-07-06 01:34:17 +0000291
John McCallb2593832010-09-16 06:16:50 +0000292static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000293 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000294 llvm::Constant *Fn =
Chris Lattner8b418682012-02-07 00:39:47 +0000295 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000296 Personality.PersonalityFn);
John McCallb2593832010-09-16 06:16:50 +0000297 return Fn;
298}
299
300static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
301 const EHPersonality &Personality) {
302 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCalld16c2cf2011-02-08 08:22:06 +0000303 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCallb2593832010-09-16 06:16:50 +0000304}
305
306/// Check whether a personality function could reasonably be swapped
307/// for a C++ personality function.
308static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700309 for (llvm::User *U : Fn->users()) {
John McCallb2593832010-09-16 06:16:50 +0000310 // Conditionally white-list bitcasts.
Stephen Hines651f13c2014-04-23 16:59:28 -0700311 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCallb2593832010-09-16 06:16:50 +0000312 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
313 if (!PersonalityHasOnlyCXXUses(CE))
314 return false;
315 continue;
316 }
317
Bill Wendling40ccacc2011-09-19 22:08:36 +0000318 // Otherwise, it has to be a landingpad instruction.
Stephen Hines651f13c2014-04-23 16:59:28 -0700319 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling40ccacc2011-09-19 22:08:36 +0000320 if (!LPI) return false;
John McCallb2593832010-09-16 06:16:50 +0000321
Bill Wendling40ccacc2011-09-19 22:08:36 +0000322 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCallb2593832010-09-16 06:16:50 +0000323 // Look for something that would've been returned by the ObjC
324 // runtime's GetEHType() method.
Bill Wendling40ccacc2011-09-19 22:08:36 +0000325 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
326 if (LPI->isCatch(I)) {
327 // Check if the catch value has the ObjC prefix.
Bill Wendlingeecb6a12011-09-20 00:40:19 +0000328 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
329 // ObjC EH selector entries are always global variables with
330 // names starting like this.
331 if (GV->getName().startswith("OBJC_EHTYPE"))
332 return false;
Bill Wendling40ccacc2011-09-19 22:08:36 +0000333 } else {
334 // Check if any of the filter values have the ObjC prefix.
335 llvm::Constant *CVal = cast<llvm::Constant>(Val);
336 for (llvm::User::op_iterator
337 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendlingeecb6a12011-09-20 00:40:19 +0000338 if (llvm::GlobalVariable *GV =
339 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
340 // ObjC EH selector entries are always global variables with
341 // names starting like this.
342 if (GV->getName().startswith("OBJC_EHTYPE"))
343 return false;
Bill Wendling40ccacc2011-09-19 22:08:36 +0000344 }
345 }
John McCallb2593832010-09-16 06:16:50 +0000346 }
347 }
348
349 return true;
350}
351
352/// Try to use the C++ personality function in ObjC++. Not doing this
353/// can cause some incompatibilities with gcc, which is more
354/// aggressive about only using the ObjC++ personality in a function
355/// when it really needs it.
356void CodeGenModule::SimplifyPersonality() {
John McCallb2593832010-09-16 06:16:50 +0000357 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikie4e4d0842012-03-11 07:00:24 +0000358 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCallb2593832010-09-16 06:16:50 +0000359 return;
360
John McCall70cd6192012-11-14 17:48:31 +0000361 // Both the problem this endeavors to fix and the way the logic
362 // above works is specific to the NeXT runtime.
363 if (!LangOpts.ObjCRuntime.isNeXTFamily())
364 return;
365
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700366 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Stephen Hines176edba2014-12-01 14:53:08 -0800367 const EHPersonality &CXX =
368 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000369 if (&ObjCXX == &CXX)
John McCallb2593832010-09-16 06:16:50 +0000370 return;
371
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000372 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
373 "Different EHPersonalities using the same personality function.");
374
375 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCallb2593832010-09-16 06:16:50 +0000376
377 // Nothing to do if it's unused.
378 if (!Fn || Fn->use_empty()) return;
379
380 // Can't do the optimization if it has non-C++ uses.
381 if (!PersonalityHasOnlyCXXUses(Fn)) return;
382
383 // Create the C++ personality function and kill off the old
384 // function.
385 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
386
387 // This can happen if the user is screwing with us.
388 if (Fn->getType() != CXXFn->getType()) return;
389
390 Fn->replaceAllUsesWith(CXXFn);
391 Fn->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000392}
393
394/// Returns the value to inject into a selector to indicate the
395/// presence of a catch-all.
396static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
397 // Possibly we should use @llvm.eh.catch.all.value here.
John McCalld16c2cf2011-02-08 08:22:06 +0000398 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallf1549f62010-07-06 01:34:17 +0000399}
400
John McCall09faeab2010-07-13 21:17:51 +0000401namespace {
402 /// A cleanup to free the exception object if its initialization
403 /// throws.
John McCallc4a1a842011-07-12 00:15:30 +0000404 struct FreeException : EHScopeStack::Cleanup {
405 llvm::Value *exn;
406 FreeException(llvm::Value *exn) : exn(exn) {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700407 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallbd7370a2013-02-28 19:01:20 +0000408 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCall09faeab2010-07-13 21:17:51 +0000409 }
410 };
411}
412
John McCallac418162010-04-22 01:10:34 +0000413// Emits an exception expression into the given location. This
414// differs from EmitAnyExprToMem only in that, if a final copy-ctor
415// call is required, an exception within that copy ctor causes
416// std::terminate to be invoked.
John McCall3ad32c82011-01-28 08:37:24 +0000417static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
418 llvm::Value *addr) {
John McCallf1549f62010-07-06 01:34:17 +0000419 // Make sure the exception object is cleaned up if there's an
420 // exception during initialization.
John McCall3ad32c82011-01-28 08:37:24 +0000421 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
422 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000423
424 // __cxa_allocate_exception returns a void*; we need to cast this
425 // to the appropriate type for the object.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000426 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
John McCall3ad32c82011-01-28 08:37:24 +0000427 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCallac418162010-04-22 01:10:34 +0000428
429 // FIXME: this isn't quite right! If there's a final unelided call
430 // to a copy constructor, then according to [except.terminate]p1 we
431 // must call std::terminate() if that constructor throws, because
432 // technically that copy occurs after the exception expression is
433 // evaluated but before the exception is caught. But the best way
434 // to handle that is to teach EmitAggExpr to do the final copy
435 // differently if it can't be elided.
Chad Rosier649b4a12012-03-29 17:37:10 +0000436 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
437 /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000438
John McCall3ad32c82011-01-28 08:37:24 +0000439 // Deactivate the cleanup block.
John McCall6f103ba2011-11-10 10:43:54 +0000440 CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump0f590be2009-12-01 03:41:18 +0000441}
442
John McCallf1549f62010-07-06 01:34:17 +0000443llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall93c332a2011-05-28 21:13:02 +0000444 if (!ExceptionSlot)
445 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallf1549f62010-07-06 01:34:17 +0000446 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000447}
448
John McCall93c332a2011-05-28 21:13:02 +0000449llvm::Value *CodeGenFunction::getEHSelectorSlot() {
450 if (!EHSelectorSlot)
451 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
452 return EHSelectorSlot;
453}
454
Bill Wendlingae270592011-09-15 18:57:19 +0000455llvm::Value *CodeGenFunction::getExceptionFromSlot() {
456 return Builder.CreateLoad(getExceptionSlot(), "exn");
457}
458
459llvm::Value *CodeGenFunction::getSelectorFromSlot() {
460 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
461}
462
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700463llvm::Value *CodeGenFunction::getAbnormalTerminationSlot() {
464 if (!AbnormalTerminationSlot)
465 AbnormalTerminationSlot =
466 CreateTempAlloca(Int8Ty, "abnormal.termination.slot");
467 return AbnormalTerminationSlot;
468}
469
Richard Smith4c71b8c2013-05-07 21:53:22 +0000470void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
471 bool KeepInsertionPoint) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700472 if (!E->getSubExpr()) {
473 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/true);
474
475 // throw is an expression, and the expression emitters expect us
476 // to leave ourselves at a valid insertion point.
477 if (KeepInsertionPoint)
478 EmitBlock(createBasicBlock("throw.cont"));
479
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700480 return;
481 }
482
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700483 if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) {
484 // Call std::terminate().
485 llvm::CallInst *TermCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
486 TermCall->setDoesNotReturn();
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000487
John McCallcd5b22e2011-01-12 03:41:02 +0000488 // throw is an expression, and the expression emitters expect us
489 // to leave ourselves at a valid insertion point.
Richard Smith4c71b8c2013-05-07 21:53:22 +0000490 if (KeepInsertionPoint)
491 EmitBlock(createBasicBlock("throw.cont"));
John McCallcd5b22e2011-01-12 03:41:02 +0000492
Anders Carlssond3379292009-10-30 02:27:02 +0000493 return;
494 }
Mike Stump8755ec32009-12-10 00:06:18 +0000495
Anders Carlssond3379292009-10-30 02:27:02 +0000496 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000497
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +0000498 if (ThrowType->isObjCObjectPointerType()) {
499 const Stmt *ThrowStmt = E->getSubExpr();
500 const ObjCAtThrowStmt S(E->getExprLoc(),
501 const_cast<Stmt *>(ThrowStmt));
502 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
503 // This will clear insertion point which was not cleared in
504 // call to EmitThrowStmt.
Richard Smith4c71b8c2013-05-07 21:53:22 +0000505 if (KeepInsertionPoint)
506 EmitBlock(createBasicBlock("throw.cont"));
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +0000507 return;
508 }
509
Anders Carlssond3379292009-10-30 02:27:02 +0000510 // Now allocate the exception object.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000511 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000512 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000513
John McCall629df012013-02-12 03:51:38 +0000514 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
John McCallf1549f62010-07-06 01:34:17 +0000515 llvm::CallInst *ExceptionPtr =
John McCallbd7370a2013-02-28 19:01:20 +0000516 EmitNounwindRuntimeCall(AllocExceptionFn,
517 llvm::ConstantInt::get(SizeTy, TypeSize),
518 "exception");
Anders Carlsson8370c582009-12-11 00:32:37 +0000519
John McCallac418162010-04-22 01:10:34 +0000520 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000521
Anders Carlssond3379292009-10-30 02:27:02 +0000522 // Now throw the exception.
Anders Carlsson82a113a2011-01-24 01:59:49 +0000523 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
524 /*ForEH=*/true);
John McCallac418162010-04-22 01:10:34 +0000525
526 // The address of the destructor. If the exception type has a
527 // trivial destructor (or isn't a record), we just pass null.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700528 llvm::Constant *Dtor = nullptr;
John McCallac418162010-04-22 01:10:34 +0000529 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
530 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
531 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000532 CXXDestructorDecl *DtorD = Record->getDestructor();
Stephen Hines176edba2014-12-01 14:53:08 -0800533 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
John McCallac418162010-04-22 01:10:34 +0000534 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
535 }
536 }
537 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000538
John McCallbd7370a2013-02-28 19:01:20 +0000539 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
540 EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
Mike Stump8755ec32009-12-10 00:06:18 +0000541
John McCallcd5b22e2011-01-12 03:41:02 +0000542 // throw is an expression, and the expression emitters expect us
543 // to leave ourselves at a valid insertion point.
Richard Smith4c71b8c2013-05-07 21:53:22 +0000544 if (KeepInsertionPoint)
545 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000546}
Mike Stump2bf701e2009-11-20 23:44:51 +0000547
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000548void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000549 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000550 return;
551
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000552 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700553 if (!FD) {
554 // Check if CapturedDecl is nothrow and create terminate scope for it.
555 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
556 if (CD->isNothrow())
557 EHStack.pushTerminate();
558 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000559 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700560 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000561 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700562 if (!Proto)
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000563 return;
564
Sebastian Redla968e972011-03-15 18:42:48 +0000565 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
566 if (isNoexceptExceptionSpec(EST)) {
567 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
568 // noexcept functions are simple terminate scopes.
569 EHStack.pushTerminate();
570 }
571 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
572 unsigned NumExceptions = Proto->getNumExceptions();
573 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000574
Sebastian Redla968e972011-03-15 18:42:48 +0000575 for (unsigned I = 0; I != NumExceptions; ++I) {
576 QualType Ty = Proto->getExceptionType(I);
577 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
578 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
579 /*ForEH=*/true);
580 Filter->setFilter(I, EHType);
581 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000582 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000583}
584
John McCall777d6e52011-08-11 02:22:43 +0000585/// Emit the dispatch block for a filter scope if necessary.
586static void emitFilterDispatchBlock(CodeGenFunction &CGF,
587 EHFilterScope &filterScope) {
588 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
589 if (!dispatchBlock) return;
590 if (dispatchBlock->use_empty()) {
591 delete dispatchBlock;
592 return;
593 }
594
John McCall777d6e52011-08-11 02:22:43 +0000595 CGF.EmitBlockAfterUses(dispatchBlock);
596
597 // If this isn't a catch-all filter, we need to check whether we got
598 // here because the filter triggered.
599 if (filterScope.getNumFilters()) {
600 // Load the selector value.
Bill Wendlingae270592011-09-15 18:57:19 +0000601 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall777d6e52011-08-11 02:22:43 +0000602 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
603
604 llvm::Value *zero = CGF.Builder.getInt32(0);
605 llvm::Value *failsFilter =
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700606 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
607 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
608 CGF.getEHResumeBlock(false));
John McCall777d6e52011-08-11 02:22:43 +0000609
610 CGF.EmitBlock(unexpectedBB);
611 }
612
613 // Call __cxa_call_unexpected. This doesn't need to be an invoke
614 // because __cxa_call_unexpected magically filters exceptions
615 // according to the last landing pad the exception was thrown
616 // into. Seriously.
Bill Wendlingae270592011-09-15 18:57:19 +0000617 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCallbd7370a2013-02-28 19:01:20 +0000618 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall777d6e52011-08-11 02:22:43 +0000619 ->setDoesNotReturn();
620 CGF.Builder.CreateUnreachable();
621}
622
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000623void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000624 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000625 return;
626
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000627 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700628 if (!FD) {
629 // Check if CapturedDecl is nothrow and pop terminate scope for it.
630 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
631 if (CD->isNothrow())
632 EHStack.popTerminate();
633 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000634 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700635 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000636 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700637 if (!Proto)
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000638 return;
639
Sebastian Redla968e972011-03-15 18:42:48 +0000640 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
641 if (isNoexceptExceptionSpec(EST)) {
642 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
643 EHStack.popTerminate();
644 }
645 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
John McCall777d6e52011-08-11 02:22:43 +0000646 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
647 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redla968e972011-03-15 18:42:48 +0000648 EHStack.popFilter();
649 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000650}
651
Mike Stump2bf701e2009-11-20 23:44:51 +0000652void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000653 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000654 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000655 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000656}
657
John McCall59a70002010-07-07 06:56:46 +0000658void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000659 unsigned NumHandlers = S.getNumHandlers();
660 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000661
John McCallf1549f62010-07-06 01:34:17 +0000662 for (unsigned I = 0; I != NumHandlers; ++I) {
663 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000664
John McCallf1549f62010-07-06 01:34:17 +0000665 llvm::BasicBlock *Handler = createBasicBlock("catch");
666 if (C->getExceptionDecl()) {
667 // FIXME: Dropping the reference type on the type into makes it
668 // impossible to correctly implement catch-by-reference
669 // semantics for pointers. Unfortunately, this is what all
670 // existing compilers do, and it's not clear that the standard
671 // personality routine is capable of doing this right. See C++ DR 388:
672 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
Stephen Hines176edba2014-12-01 14:53:08 -0800673 Qualifiers CaughtTypeQuals;
674 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
675 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall5a180392010-07-24 00:37:23 +0000676
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700677 llvm::Constant *TypeInfo = nullptr;
John McCall5a180392010-07-24 00:37:23 +0000678 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000679 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall5a180392010-07-24 00:37:23 +0000680 else
Anders Carlsson82a113a2011-01-24 01:59:49 +0000681 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallf1549f62010-07-06 01:34:17 +0000682 CatchScope->setHandler(I, TypeInfo, Handler);
683 } else {
684 // No exception decl indicates '...', a catch-all.
685 CatchScope->setCatchAllHandler(I, Handler);
686 }
687 }
John McCallf1549f62010-07-06 01:34:17 +0000688}
689
John McCall777d6e52011-08-11 02:22:43 +0000690llvm::BasicBlock *
691CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
692 // The dispatch block for the end of the scope chain is a block that
693 // just resumes unwinding.
694 if (si == EHStack.stable_end())
David Chisnallc6860042012-11-07 16:50:40 +0000695 return getEHResumeBlock(true);
John McCall777d6e52011-08-11 02:22:43 +0000696
697 // Otherwise, we should look at the actual scope.
698 EHScope &scope = *EHStack.find(si);
699
700 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
701 if (!dispatchBlock) {
702 switch (scope.getKind()) {
703 case EHScope::Catch: {
704 // Apply a special case to a single catch-all.
705 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
706 if (catchScope.getNumHandlers() == 1 &&
707 catchScope.getHandler(0).isCatchAll()) {
708 dispatchBlock = catchScope.getHandler(0).Block;
709
710 // Otherwise, make a dispatch block.
711 } else {
712 dispatchBlock = createBasicBlock("catch.dispatch");
713 }
714 break;
715 }
716
717 case EHScope::Cleanup:
718 dispatchBlock = createBasicBlock("ehcleanup");
719 break;
720
721 case EHScope::Filter:
722 dispatchBlock = createBasicBlock("filter.dispatch");
723 break;
724
725 case EHScope::Terminate:
726 dispatchBlock = getTerminateHandler();
727 break;
728 }
729 scope.setCachedEHDispatchBlock(dispatchBlock);
730 }
731 return dispatchBlock;
732}
733
John McCallf1549f62010-07-06 01:34:17 +0000734/// Check whether this is a non-EH scope, i.e. a scope which doesn't
735/// affect exception handling. Currently, the only non-EH scopes are
736/// normal-only cleanup scopes.
737static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000738 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000739 case EHScope::Cleanup:
740 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000741 case EHScope::Filter:
742 case EHScope::Catch:
743 case EHScope::Terminate:
744 return false;
745 }
746
David Blaikie30263482012-01-20 21:50:17 +0000747 llvm_unreachable("Invalid EHScope Kind!");
John McCallf1549f62010-07-06 01:34:17 +0000748}
749
750llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
751 assert(EHStack.requiresLandingPad());
752 assert(!EHStack.empty());
753
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700754 // If exceptions are disabled, there are usually no landingpads. However, when
755 // SEH is enabled, functions using SEH still get landingpads.
756 const LangOptions &LO = CGM.getLangOpts();
757 if (!LO.Exceptions) {
758 if (!LO.Borland && !LO.MicrosoftExt)
759 return nullptr;
760 if (!currentFunctionUsesSEHTry())
761 return nullptr;
762 }
John McCallda65ea82010-07-13 20:32:21 +0000763
John McCallf1549f62010-07-06 01:34:17 +0000764 // Check the innermost scope for a cached landing pad. If this is
765 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
766 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
767 if (LP) return LP;
768
769 // Build the landing pad for this scope.
770 LP = EmitLandingPad();
771 assert(LP);
772
773 // Cache the landing pad on the innermost scope. If this is a
774 // non-EH scope, cache the landing pad on the enclosing scope, too.
775 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
776 ir->setCachedLandingPad(LP);
777 if (!isNonEHScope(*ir)) break;
778 }
779
780 return LP;
781}
782
783llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
784 assert(EHStack.requiresLandingPad());
785
John McCall777d6e52011-08-11 02:22:43 +0000786 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
787 switch (innermostEHScope.getKind()) {
788 case EHScope::Terminate:
789 return getTerminateLandingPad();
John McCallf1549f62010-07-06 01:34:17 +0000790
John McCall777d6e52011-08-11 02:22:43 +0000791 case EHScope::Catch:
792 case EHScope::Cleanup:
793 case EHScope::Filter:
794 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
795 return lpad;
John McCallf1549f62010-07-06 01:34:17 +0000796 }
797
798 // Save the current IR generation state.
John McCall777d6e52011-08-11 02:22:43 +0000799 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700800 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallf1549f62010-07-06 01:34:17 +0000801
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700802 const EHPersonality &personality = EHPersonality::get(*this);
John McCall8262b6a2010-07-17 00:43:08 +0000803
John McCallf1549f62010-07-06 01:34:17 +0000804 // Create and configure the landing pad.
John McCall777d6e52011-08-11 02:22:43 +0000805 llvm::BasicBlock *lpad = createBasicBlock("lpad");
806 EmitBlock(lpad);
John McCallf1549f62010-07-06 01:34:17 +0000807
Bill Wendling285cfd82011-09-19 20:31:14 +0000808 llvm::LandingPadInst *LPadInst =
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700809 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendling285cfd82011-09-19 20:31:14 +0000810 getOpaquePersonalityFn(CGM, personality), 0);
811
812 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
813 Builder.CreateStore(LPadExn, getExceptionSlot());
814 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
815 Builder.CreateStore(LPadSel, getEHSelectorSlot());
816
John McCallf1549f62010-07-06 01:34:17 +0000817 // Save the exception pointer. It's safe to use a single exception
818 // pointer per function because EH cleanups can never have nested
819 // try/catches.
Bill Wendling285cfd82011-09-19 20:31:14 +0000820 // Build the landingpad instruction.
John McCallf1549f62010-07-06 01:34:17 +0000821
822 // Accumulate all the handlers in scope.
John McCall777d6e52011-08-11 02:22:43 +0000823 bool hasCatchAll = false;
824 bool hasCleanup = false;
825 bool hasFilter = false;
826 SmallVector<llvm::Value*, 4> filterTypes;
827 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700828 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
829 ++I) {
John McCallf1549f62010-07-06 01:34:17 +0000830
831 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000832 case EHScope::Cleanup:
John McCall777d6e52011-08-11 02:22:43 +0000833 // If we have a cleanup, remember that.
834 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCallda65ea82010-07-13 20:32:21 +0000835 continue;
836
John McCallf1549f62010-07-06 01:34:17 +0000837 case EHScope::Filter: {
838 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall777d6e52011-08-11 02:22:43 +0000839 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000840
Bill Wendling285cfd82011-09-19 20:31:14 +0000841 // Filter scopes get added to the landingpad in weird ways.
John McCall777d6e52011-08-11 02:22:43 +0000842 EHFilterScope &filter = cast<EHFilterScope>(*I);
843 hasFilter = true;
John McCallf1549f62010-07-06 01:34:17 +0000844
Bill Wendling8990daf2011-09-22 20:32:54 +0000845 // Add all the filter values.
846 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
847 filterTypes.push_back(filter.getFilter(i));
John McCallf1549f62010-07-06 01:34:17 +0000848 goto done;
849 }
850
851 case EHScope::Terminate:
852 // Terminate scopes are basically catch-alls.
John McCall777d6e52011-08-11 02:22:43 +0000853 assert(!hasCatchAll);
854 hasCatchAll = true;
John McCallf1549f62010-07-06 01:34:17 +0000855 goto done;
856
857 case EHScope::Catch:
858 break;
859 }
860
John McCall777d6e52011-08-11 02:22:43 +0000861 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
862 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
863 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallf1549f62010-07-06 01:34:17 +0000864
John McCall777d6e52011-08-11 02:22:43 +0000865 // If this is a catch-all, register that and abort.
866 if (!handler.Type) {
867 assert(!hasCatchAll);
868 hasCatchAll = true;
869 goto done;
John McCallf1549f62010-07-06 01:34:17 +0000870 }
871
872 // Check whether we already have a handler for this type.
Stephen Hines176edba2014-12-01 14:53:08 -0800873 if (catchTypes.insert(handler.Type).second)
Bill Wendling285cfd82011-09-19 20:31:14 +0000874 // If not, add it directly to the landingpad.
875 LPadInst->addClause(handler.Type);
John McCallf1549f62010-07-06 01:34:17 +0000876 }
John McCallf1549f62010-07-06 01:34:17 +0000877 }
878
879 done:
Bill Wendling285cfd82011-09-19 20:31:14 +0000880 // If we have a catch-all, add null to the landingpad.
John McCall777d6e52011-08-11 02:22:43 +0000881 assert(!(hasCatchAll && hasFilter));
882 if (hasCatchAll) {
Bill Wendling285cfd82011-09-19 20:31:14 +0000883 LPadInst->addClause(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000884
885 // If we have an EH filter, we need to add those handlers in the
Bill Wendling285cfd82011-09-19 20:31:14 +0000886 // right place in the landingpad, which is to say, at the end.
John McCall777d6e52011-08-11 02:22:43 +0000887 } else if (hasFilter) {
Bill Wendling40ccacc2011-09-19 22:08:36 +0000888 // Create a filter expression: a constant array indicating which filter
889 // types there are. The personality routine only lands here if the filter
890 // doesn't match.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000891 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendling285cfd82011-09-19 20:31:14 +0000892 llvm::ArrayType *AType =
893 llvm::ArrayType::get(!filterTypes.empty() ?
894 filterTypes[0]->getType() : Int8PtrTy,
895 filterTypes.size());
896
897 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
898 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
899 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
900 LPadInst->addClause(FilterArray);
John McCallf1549f62010-07-06 01:34:17 +0000901
902 // Also check whether we need a cleanup.
Bill Wendling285cfd82011-09-19 20:31:14 +0000903 if (hasCleanup)
904 LPadInst->setCleanup(true);
John McCallf1549f62010-07-06 01:34:17 +0000905
906 // Otherwise, signal that we at least have cleanups.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700907 } else if (hasCleanup) {
908 LPadInst->setCleanup(true);
John McCallf1549f62010-07-06 01:34:17 +0000909 }
910
Bill Wendling285cfd82011-09-19 20:31:14 +0000911 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
912 "landingpad instruction has no clauses!");
John McCallf1549f62010-07-06 01:34:17 +0000913
914 // Tell the backend how to generate the landing pad.
John McCall777d6e52011-08-11 02:22:43 +0000915 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallf1549f62010-07-06 01:34:17 +0000916
917 // Restore the old IR generation state.
John McCall777d6e52011-08-11 02:22:43 +0000918 Builder.restoreIP(savedIP);
John McCallf1549f62010-07-06 01:34:17 +0000919
John McCall777d6e52011-08-11 02:22:43 +0000920 return lpad;
John McCallf1549f62010-07-06 01:34:17 +0000921}
922
John McCall8e3f8612010-07-13 22:12:14 +0000923namespace {
924 /// A cleanup to call __cxa_end_catch. In many cases, the caught
925 /// exception type lets us state definitively that the thrown exception
926 /// type does not have a destructor. In particular:
927 /// - Catch-alls tell us nothing, so we have to conservatively
928 /// assume that the thrown exception might have a destructor.
929 /// - Catches by reference behave according to their base types.
930 /// - Catches of non-record types will only trigger for exceptions
931 /// of non-record types, which never have destructors.
932 /// - Catches of record types can trigger for arbitrary subclasses
933 /// of the caught type, so we have to assume the actual thrown
934 /// exception type might have a throwing destructor, even if the
935 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +0000936 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +0000937 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
938 bool MightThrow;
939
Stephen Hines651f13c2014-04-23 16:59:28 -0700940 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8e3f8612010-07-13 22:12:14 +0000941 if (!MightThrow) {
John McCallbd7370a2013-02-28 19:01:20 +0000942 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
John McCall8e3f8612010-07-13 22:12:14 +0000943 return;
944 }
945
John McCallbd7370a2013-02-28 19:01:20 +0000946 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
John McCall8e3f8612010-07-13 22:12:14 +0000947 }
948 };
949}
950
John McCallf1549f62010-07-06 01:34:17 +0000951/// Emits a call to __cxa_begin_catch and enters a cleanup to call
952/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +0000953///
954/// \param EndMightThrow - true if __cxa_end_catch might throw
955static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
956 llvm::Value *Exn,
957 bool EndMightThrow) {
John McCallbd7370a2013-02-28 19:01:20 +0000958 llvm::CallInst *call =
959 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
John McCallf1549f62010-07-06 01:34:17 +0000960
John McCall1f0fca52010-07-21 07:22:38 +0000961 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +0000962
John McCallbd7370a2013-02-28 19:01:20 +0000963 return call;
John McCallf1549f62010-07-06 01:34:17 +0000964}
965
966/// A "special initializer" callback for initializing a catch
967/// parameter during catch initialization.
968static void InitCatchParam(CodeGenFunction &CGF,
969 const VarDecl &CatchParam,
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000970 llvm::Value *ParamAddr,
971 SourceLocation Loc) {
John McCallf1549f62010-07-06 01:34:17 +0000972 // Load the exception from where the landing pad saved it.
Bill Wendlingae270592011-09-15 18:57:19 +0000973 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCallf1549f62010-07-06 01:34:17 +0000974
975 CanQualType CatchType =
976 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
Chris Lattner2acc6e32011-07-18 04:24:23 +0000977 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
John McCallf1549f62010-07-06 01:34:17 +0000978
979 // If we're catching by reference, we can just cast the object
980 // pointer to the appropriate pointer.
981 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +0000982 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
983 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +0000984
John McCallf1549f62010-07-06 01:34:17 +0000985 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +0000986 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +0000987
988 // We have no way to tell the personality function that we're
989 // catching by reference, so if we're catching a pointer,
990 // __cxa_begin_catch will actually return that pointer by value.
991 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
992 QualType PointeeType = PT->getPointeeType();
993
994 // When catching by reference, generally we should just ignore
995 // this by-value pointer and use the exception object instead.
996 if (!PointeeType->isRecordType()) {
997
998 // Exn points to the struct _Unwind_Exception header, which
999 // we have to skip past in order to reach the exception data.
1000 unsigned HeaderSize =
1001 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
1002 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
1003
1004 // However, if we're catching a pointer-to-record type that won't
1005 // work, because the personality function might have adjusted
1006 // the pointer. There's actually no way for us to fully satisfy
1007 // the language/ABI contract here: we can't use Exn because it
1008 // might have the wrong adjustment, but we can't use the by-value
1009 // pointer because it's off by a level of abstraction.
1010 //
1011 // The current solution is to dump the adjusted pointer into an
1012 // alloca, which breaks language semantics (because changing the
1013 // pointer doesn't change the exception) but at least works.
1014 // The better solution would be to filter out non-exact matches
1015 // and rethrow them, but this is tricky because the rethrow
1016 // really needs to be catchable by other sites at this landing
1017 // pad. The best solution is to fix the personality function.
1018 } else {
1019 // Pull the pointer for the reference type off.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001020 llvm::Type *PtrTy =
John McCall204b0752010-07-20 22:17:55 +00001021 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1022
1023 // Create the temporary and write the adjusted pointer into it.
1024 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1025 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1026 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1027
1028 // Bind the reference to the temporary.
1029 AdjustedExn = ExnPtrTmp;
1030 }
1031 }
1032
John McCallf1549f62010-07-06 01:34:17 +00001033 llvm::Value *ExnCast =
1034 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1035 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1036 return;
1037 }
1038
John McCall9d232c82013-03-07 21:37:08 +00001039 // Scalars and complexes.
1040 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
1041 if (TEK != TEK_Aggregate) {
John McCall8e3f8612010-07-13 22:12:14 +00001042 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001043
1044 // If the catch type is a pointer type, __cxa_begin_catch returns
1045 // the pointer by value.
1046 if (CatchType->hasPointerRepresentation()) {
1047 llvm::Value *CastExn =
1048 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
John McCallb29b12d2012-01-17 20:16:56 +00001049
1050 switch (CatchType.getQualifiers().getObjCLifetime()) {
1051 case Qualifiers::OCL_Strong:
1052 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
1053 // fallthrough
1054
1055 case Qualifiers::OCL_None:
1056 case Qualifiers::OCL_ExplicitNone:
1057 case Qualifiers::OCL_Autoreleasing:
1058 CGF.Builder.CreateStore(CastExn, ParamAddr);
1059 return;
1060
1061 case Qualifiers::OCL_Weak:
1062 CGF.EmitARCInitWeak(ParamAddr, CastExn);
1063 return;
1064 }
1065 llvm_unreachable("bad ownership qualifier!");
John McCallf1549f62010-07-06 01:34:17 +00001066 }
1067
1068 // Otherwise, it returns a pointer into the exception object.
1069
Chris Lattner2acc6e32011-07-18 04:24:23 +00001070 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallf1549f62010-07-06 01:34:17 +00001071 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1072
John McCall9d232c82013-03-07 21:37:08 +00001073 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
1074 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
1075 CGF.getContext().getDeclAlign(&CatchParam));
1076 switch (TEK) {
1077 case TEK_Complex:
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001078 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
John McCall9d232c82013-03-07 21:37:08 +00001079 /*init*/ true);
1080 return;
1081 case TEK_Scalar: {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001082 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
John McCall9d232c82013-03-07 21:37:08 +00001083 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
1084 return;
John McCallf1549f62010-07-06 01:34:17 +00001085 }
John McCall9d232c82013-03-07 21:37:08 +00001086 case TEK_Aggregate:
1087 llvm_unreachable("evaluation kind filtered out!");
1088 }
1089 llvm_unreachable("bad evaluation kind");
John McCallf1549f62010-07-06 01:34:17 +00001090 }
1091
John McCallacff6962011-02-16 08:39:19 +00001092 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallf1549f62010-07-06 01:34:17 +00001093
Chris Lattner2acc6e32011-07-18 04:24:23 +00001094 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallf1549f62010-07-06 01:34:17 +00001095
John McCallacff6962011-02-16 08:39:19 +00001096 // Check for a copy expression. If we don't have a copy expression,
1097 // that means a trivial copy is okay.
John McCalle996ffd2011-02-16 08:02:54 +00001098 const Expr *copyExpr = CatchParam.getInit();
1099 if (!copyExpr) {
John McCallacff6962011-02-16 08:39:19 +00001100 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1101 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
Chad Rosier649b4a12012-03-29 17:37:10 +00001102 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001103 return;
1104 }
1105
1106 // We have to call __cxa_get_exception_ptr to get the adjusted
1107 // pointer before copying.
John McCalle996ffd2011-02-16 08:02:54 +00001108 llvm::CallInst *rawAdjustedExn =
John McCallbd7370a2013-02-28 19:01:20 +00001109 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
John McCallf1549f62010-07-06 01:34:17 +00001110
John McCalle996ffd2011-02-16 08:02:54 +00001111 // Cast that to the appropriate type.
1112 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallf1549f62010-07-06 01:34:17 +00001113
John McCalle996ffd2011-02-16 08:02:54 +00001114 // The copy expression is defined in terms of an OpaqueValueExpr.
1115 // Find it and map it to the adjusted expression.
1116 CodeGenFunction::OpaqueValueMapping
John McCall56ca35d2011-02-17 10:25:35 +00001117 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1118 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallf1549f62010-07-06 01:34:17 +00001119
1120 // Call the copy ctor in a terminate scope.
1121 CGF.EHStack.pushTerminate();
John McCalle996ffd2011-02-16 08:02:54 +00001122
1123 // Perform the copy construction.
Eli Friedmand7722d92011-12-03 02:13:40 +00001124 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
Eli Friedmanf3940782011-12-03 00:54:26 +00001125 CGF.EmitAggExpr(copyExpr,
1126 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1127 AggValueSlot::IsNotDestructed,
1128 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001129 AggValueSlot::IsNotAliased));
John McCalle996ffd2011-02-16 08:02:54 +00001130
1131 // Leave the terminate scope.
John McCallf1549f62010-07-06 01:34:17 +00001132 CGF.EHStack.popTerminate();
1133
John McCalle996ffd2011-02-16 08:02:54 +00001134 // Undo the opaque value mapping.
1135 opaque.pop();
1136
John McCallf1549f62010-07-06 01:34:17 +00001137 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001138 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001139}
1140
1141/// Begins a catch statement by initializing the catch variable and
1142/// calling __cxa_begin_catch.
John McCalle996ffd2011-02-16 08:02:54 +00001143static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallf1549f62010-07-06 01:34:17 +00001144 // We have to be very careful with the ordering of cleanups here:
1145 // C++ [except.throw]p4:
1146 // The destruction [of the exception temporary] occurs
1147 // immediately after the destruction of the object declared in
1148 // the exception-declaration in the handler.
1149 //
1150 // So the precise ordering is:
1151 // 1. Construct catch variable.
1152 // 2. __cxa_begin_catch
1153 // 3. Enter __cxa_end_catch cleanup
1154 // 4. Enter dtor cleanup
1155 //
John McCall34695852011-02-22 06:44:22 +00001156 // We do this by using a slightly abnormal initialization process.
1157 // Delegation sequence:
John McCallf1549f62010-07-06 01:34:17 +00001158 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCall34695852011-02-22 06:44:22 +00001159 // - EmitAutoVarAlloca creates the variable and debug info
John McCallf1549f62010-07-06 01:34:17 +00001160 // - InitCatchParam initializes the variable from the exception
John McCall34695852011-02-22 06:44:22 +00001161 // - CallBeginCatch calls __cxa_begin_catch
1162 // - CallBeginCatch enters the __cxa_end_catch cleanup
1163 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallf1549f62010-07-06 01:34:17 +00001164 // - EmitCXXTryStmt emits the code for the catch body
1165 // - EmitCXXTryStmt close the RunCleanupsScope
1166
1167 VarDecl *CatchParam = S->getExceptionDecl();
1168 if (!CatchParam) {
Bill Wendlingae270592011-09-15 18:57:19 +00001169 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCall8e3f8612010-07-13 22:12:14 +00001170 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001171 return;
1172 }
1173
1174 // Emit the local.
John McCall34695852011-02-22 06:44:22 +00001175 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001176 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
John McCall34695852011-02-22 06:44:22 +00001177 CGF.EmitAutoVarCleanups(var);
John McCall9fc6a772010-02-19 09:25:03 +00001178}
1179
John McCall777d6e52011-08-11 02:22:43 +00001180/// Emit the structure of the dispatch block for the given catch scope.
1181/// It is an invariant that the dispatch block already exists.
1182static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1183 EHCatchScope &catchScope) {
1184 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1185 assert(dispatchBlock);
1186
1187 // If there's only a single catch-all, getEHDispatchBlock returned
1188 // that catch-all as the dispatch block.
1189 if (catchScope.getNumHandlers() == 1 &&
1190 catchScope.getHandler(0).isCatchAll()) {
1191 assert(dispatchBlock == catchScope.getHandler(0).Block);
1192 return;
1193 }
1194
1195 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1196 CGF.EmitBlockAfterUses(dispatchBlock);
1197
1198 // Select the right handler.
1199 llvm::Value *llvm_eh_typeid_for =
1200 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1201
1202 // Load the selector value.
Bill Wendlingae270592011-09-15 18:57:19 +00001203 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall777d6e52011-08-11 02:22:43 +00001204
1205 // Test against each of the exception types we claim to catch.
1206 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1207 assert(i < e && "ran off end of handlers!");
1208 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1209
1210 llvm::Value *typeValue = handler.Type;
1211 assert(typeValue && "fell into catch-all case!");
1212 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1213
1214 // Figure out the next block.
1215 bool nextIsEnd;
1216 llvm::BasicBlock *nextBlock;
1217
1218 // If this is the last handler, we're at the end, and the next
1219 // block is the block for the enclosing EH scope.
1220 if (i + 1 == e) {
1221 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1222 nextIsEnd = true;
1223
1224 // If the next handler is a catch-all, we're at the end, and the
1225 // next block is that handler.
1226 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1227 nextBlock = catchScope.getHandler(i+1).Block;
1228 nextIsEnd = true;
1229
1230 // Otherwise, we're not at the end and we need a new block.
1231 } else {
1232 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1233 nextIsEnd = false;
1234 }
1235
1236 // Figure out the catch type's index in the LSDA's type table.
1237 llvm::CallInst *typeIndex =
1238 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1239 typeIndex->setDoesNotThrow();
1240
1241 llvm::Value *matchesTypeIndex =
1242 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1243 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1244
1245 // If the next handler is a catch-all, we're completely done.
1246 if (nextIsEnd) {
1247 CGF.Builder.restoreIP(savedIP);
1248 return;
John McCall777d6e52011-08-11 02:22:43 +00001249 }
Ahmed Charlese8e92b92012-02-19 11:57:29 +00001250 // Otherwise we need to emit and continue at that block.
1251 CGF.EmitBlock(nextBlock);
John McCall777d6e52011-08-11 02:22:43 +00001252 }
John McCall777d6e52011-08-11 02:22:43 +00001253}
1254
1255void CodeGenFunction::popCatchScope() {
1256 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1257 if (catchScope.hasEHBranches())
1258 emitCatchDispatchBlock(*this, catchScope);
1259 EHStack.popCatch();
1260}
1261
John McCall59a70002010-07-07 06:56:46 +00001262void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001263 unsigned NumHandlers = S.getNumHandlers();
1264 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1265 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001266
John McCall777d6e52011-08-11 02:22:43 +00001267 // If the catch was not required, bail out now.
1268 if (!CatchScope.hasEHBranches()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001269 CatchScope.clearHandlerBlocks();
John McCall777d6e52011-08-11 02:22:43 +00001270 EHStack.popCatch();
1271 return;
1272 }
1273
1274 // Emit the structure of the EH dispatch for this catch.
1275 emitCatchDispatchBlock(*this, CatchScope);
1276
John McCallf1549f62010-07-06 01:34:17 +00001277 // Copy the handler blocks off before we pop the EH stack. Emitting
1278 // the handlers might scribble on this memory.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001279 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallf1549f62010-07-06 01:34:17 +00001280 memcpy(Handlers.data(), CatchScope.begin(),
1281 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall777d6e52011-08-11 02:22:43 +00001282
John McCallf1549f62010-07-06 01:34:17 +00001283 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001284
John McCallf1549f62010-07-06 01:34:17 +00001285 // The fall-through block.
1286 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001287
John McCallf1549f62010-07-06 01:34:17 +00001288 // We just emitted the body of the try; jump to the continue block.
1289 if (HaveInsertPoint())
1290 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001291
John McCallf5533012012-06-15 05:27:05 +00001292 // Determine if we need an implicit rethrow for all these catch handlers;
1293 // see the comment below.
1294 bool doImplicitRethrow = false;
John McCall59a70002010-07-07 06:56:46 +00001295 if (IsFnTryBlock)
John McCallf5533012012-06-15 05:27:05 +00001296 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1297 isa<CXXConstructorDecl>(CurCodeDecl);
John McCall59a70002010-07-07 06:56:46 +00001298
John McCall777d6e52011-08-11 02:22:43 +00001299 // Perversely, we emit the handlers backwards precisely because we
1300 // want them to appear in source order. In all of these cases, the
1301 // catch block will have exactly one predecessor, which will be a
1302 // particular block in the catch dispatch. However, in the case of
1303 // a catch-all, one of the dispatch blocks will branch to two
1304 // different handlers, and EmitBlockAfterUses will cause the second
1305 // handler to be moved before the first.
1306 for (unsigned I = NumHandlers; I != 0; --I) {
1307 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1308 EmitBlockAfterUses(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001309
John McCallf1549f62010-07-06 01:34:17 +00001310 // Catch the exception if this isn't a catch-all.
John McCall777d6e52011-08-11 02:22:43 +00001311 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump2bf701e2009-11-20 23:44:51 +00001312
John McCallf1549f62010-07-06 01:34:17 +00001313 // Enter a cleanup scope, including the catch variable and the
1314 // end-catch.
1315 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001316
John McCallf1549f62010-07-06 01:34:17 +00001317 // Initialize the catch variable and set up the cleanups.
1318 BeginCatch(*this, C);
1319
Stephen Hines651f13c2014-04-23 16:59:28 -07001320 // Emit the PGO counter increment.
1321 RegionCounter CatchCnt = getPGORegionCounter(C);
1322 CatchCnt.beginRegion(Builder);
1323
John McCallf1549f62010-07-06 01:34:17 +00001324 // Perform the body of the catch.
1325 EmitStmt(C->getHandlerBlock());
1326
John McCallf5533012012-06-15 05:27:05 +00001327 // [except.handle]p11:
1328 // The currently handled exception is rethrown if control
1329 // reaches the end of a handler of the function-try-block of a
1330 // constructor or destructor.
1331
1332 // It is important that we only do this on fallthrough and not on
1333 // return. Note that it's illegal to put a return in a
1334 // constructor function-try-block's catch handler (p14), so this
1335 // really only applies to destructors.
1336 if (doImplicitRethrow && HaveInsertPoint()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001337 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCallf5533012012-06-15 05:27:05 +00001338 Builder.CreateUnreachable();
1339 Builder.ClearInsertionPoint();
1340 }
1341
John McCallf1549f62010-07-06 01:34:17 +00001342 // Fall out through the catch cleanups.
1343 CatchScope.ForceCleanup();
1344
1345 // Branch out of the try.
1346 if (HaveInsertPoint())
1347 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001348 }
1349
Stephen Hines651f13c2014-04-23 16:59:28 -07001350 RegionCounter ContCnt = getPGORegionCounter(&S);
John McCallf1549f62010-07-06 01:34:17 +00001351 EmitBlock(ContBB);
Stephen Hines651f13c2014-04-23 16:59:28 -07001352 ContCnt.beginRegion(Builder);
Mike Stump2bf701e2009-11-20 23:44:51 +00001353}
Mike Stumpd88ea562009-12-09 03:35:49 +00001354
John McCall55b20fc2010-07-21 00:52:03 +00001355namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001356 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001357 llvm::Value *ForEHVar;
1358 llvm::Value *EndCatchFn;
1359 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1360 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1361
Stephen Hines651f13c2014-04-23 16:59:28 -07001362 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall55b20fc2010-07-21 00:52:03 +00001363 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1364 llvm::BasicBlock *CleanupContBB =
1365 CGF.createBasicBlock("finally.cleanup.cont");
1366
1367 llvm::Value *ShouldEndCatch =
1368 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1369 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1370 CGF.EmitBlock(EndCatchBB);
John McCallbd7370a2013-02-28 19:01:20 +00001371 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall55b20fc2010-07-21 00:52:03 +00001372 CGF.EmitBlock(CleanupContBB);
1373 }
1374 };
John McCall77199712010-07-21 05:47:49 +00001375
John McCall1f0fca52010-07-21 07:22:38 +00001376 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001377 const Stmt *Body;
1378 llvm::Value *ForEHVar;
1379 llvm::Value *EndCatchFn;
1380 llvm::Value *RethrowFn;
1381 llvm::Value *SavedExnVar;
1382
1383 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1384 llvm::Value *EndCatchFn,
1385 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1386 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1387 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1388
Stephen Hines651f13c2014-04-23 16:59:28 -07001389 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall77199712010-07-21 05:47:49 +00001390 // Enter a cleanup to call the end-catch function if one was provided.
1391 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001392 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1393 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001394
John McCalld96a8e72010-08-11 00:16:14 +00001395 // Save the current cleanup destination in case there are
1396 // cleanups in the finally block.
1397 llvm::Value *SavedCleanupDest =
1398 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1399 "cleanup.dest.saved");
1400
John McCall77199712010-07-21 05:47:49 +00001401 // Emit the finally block.
1402 CGF.EmitStmt(Body);
1403
1404 // If the end of the finally is reachable, check whether this was
1405 // for EH. If so, rethrow.
1406 if (CGF.HaveInsertPoint()) {
1407 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1408 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1409
1410 llvm::Value *ShouldRethrow =
1411 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1412 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1413
1414 CGF.EmitBlock(RethrowBB);
1415 if (SavedExnVar) {
John McCallbd7370a2013-02-28 19:01:20 +00001416 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1417 CGF.Builder.CreateLoad(SavedExnVar));
John McCall77199712010-07-21 05:47:49 +00001418 } else {
John McCallbd7370a2013-02-28 19:01:20 +00001419 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall77199712010-07-21 05:47:49 +00001420 }
1421 CGF.Builder.CreateUnreachable();
1422
1423 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001424
1425 // Restore the cleanup destination.
1426 CGF.Builder.CreateStore(SavedCleanupDest,
1427 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001428 }
1429
1430 // Leave the end-catch cleanup. As an optimization, pretend that
1431 // the fallthrough path was inaccessible; we've dynamically proven
1432 // that we're not in the EH case along that path.
1433 if (EndCatchFn) {
1434 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1435 CGF.PopCleanupBlock();
1436 CGF.Builder.restoreIP(SavedIP);
1437 }
1438
1439 // Now make sure we actually have an insertion point or the
1440 // cleanup gods will hate us.
1441 CGF.EnsureInsertPoint();
1442 }
1443 };
John McCall55b20fc2010-07-21 00:52:03 +00001444}
1445
John McCallf1549f62010-07-06 01:34:17 +00001446/// Enters a finally block for an implementation using zero-cost
1447/// exceptions. This is mostly general, but hard-codes some
1448/// language/ABI-specific behavior in the catch-all sections.
John McCalld768e9d2011-06-22 02:32:12 +00001449void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1450 const Stmt *body,
1451 llvm::Constant *beginCatchFn,
1452 llvm::Constant *endCatchFn,
1453 llvm::Constant *rethrowFn) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001454 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallf1549f62010-07-06 01:34:17 +00001455 "begin/end catch functions not paired");
John McCalld768e9d2011-06-22 02:32:12 +00001456 assert(rethrowFn && "rethrow function is required");
1457
1458 BeginCatchFn = beginCatchFn;
Mike Stumpd88ea562009-12-09 03:35:49 +00001459
John McCallf1549f62010-07-06 01:34:17 +00001460 // The rethrow function has one of the following two types:
1461 // void (*)()
1462 // void (*)(void*)
1463 // In the latter case we need to pass it the exception object.
1464 // But we can't use the exception slot because the @finally might
1465 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2acc6e32011-07-18 04:24:23 +00001466 llvm::FunctionType *rethrowFnTy =
John McCallf1549f62010-07-06 01:34:17 +00001467 cast<llvm::FunctionType>(
John McCalld768e9d2011-06-22 02:32:12 +00001468 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001469 SavedExnVar = nullptr;
John McCalld768e9d2011-06-22 02:32:12 +00001470 if (rethrowFnTy->getNumParams())
1471 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001472
John McCallf1549f62010-07-06 01:34:17 +00001473 // A finally block is a statement which must be executed on any edge
1474 // out of a given scope. Unlike a cleanup, the finally block may
1475 // contain arbitrary control flow leading out of itself. In
1476 // addition, finally blocks should always be executed, even if there
1477 // are no catch handlers higher on the stack. Therefore, we
1478 // surround the protected scope with a combination of a normal
1479 // cleanup (to catch attempts to break out of the block via normal
1480 // control flow) and an EH catch-all (semantically "outside" any try
1481 // statement to which the finally block might have been attached).
1482 // The finally block itself is generated in the context of a cleanup
1483 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001484
John McCallf1549f62010-07-06 01:34:17 +00001485 // Jump destination for performing the finally block on an exception
1486 // edge. We'll never actually reach this block, so unreachable is
1487 // fine.
John McCalld768e9d2011-06-22 02:32:12 +00001488 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001489
John McCallf1549f62010-07-06 01:34:17 +00001490 // Whether the finally block is being executed for EH purposes.
John McCalld768e9d2011-06-22 02:32:12 +00001491 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1492 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpd88ea562009-12-09 03:35:49 +00001493
John McCallf1549f62010-07-06 01:34:17 +00001494 // Enter a normal cleanup which will perform the @finally block.
John McCalld768e9d2011-06-22 02:32:12 +00001495 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1496 ForEHVar, endCatchFn,
1497 rethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001498
1499 // Enter a catch-all scope.
John McCalld768e9d2011-06-22 02:32:12 +00001500 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1501 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1502 catchScope->setCatchAllHandler(0, catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001503}
1504
John McCalld768e9d2011-06-22 02:32:12 +00001505void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +00001506 // Leave the finally catch-all.
John McCalld768e9d2011-06-22 02:32:12 +00001507 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1508 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall777d6e52011-08-11 02:22:43 +00001509
1510 CGF.popCatchScope();
John McCallf1549f62010-07-06 01:34:17 +00001511
John McCalld768e9d2011-06-22 02:32:12 +00001512 // If there are any references to the catch-all block, emit it.
1513 if (catchBB->use_empty()) {
1514 delete catchBB;
1515 } else {
1516 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1517 CGF.EmitBlock(catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001518
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001519 llvm::Value *exn = nullptr;
John McCallf1549f62010-07-06 01:34:17 +00001520
John McCalld768e9d2011-06-22 02:32:12 +00001521 // If there's a begin-catch function, call it.
1522 if (BeginCatchFn) {
Bill Wendlingae270592011-09-15 18:57:19 +00001523 exn = CGF.getExceptionFromSlot();
John McCallbd7370a2013-02-28 19:01:20 +00001524 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCalld768e9d2011-06-22 02:32:12 +00001525 }
1526
1527 // If we need to remember the exception pointer to rethrow later, do so.
1528 if (SavedExnVar) {
Bill Wendlingae270592011-09-15 18:57:19 +00001529 if (!exn) exn = CGF.getExceptionFromSlot();
John McCalld768e9d2011-06-22 02:32:12 +00001530 CGF.Builder.CreateStore(exn, SavedExnVar);
1531 }
1532
1533 // Tell the cleanups in the finally block that we're do this for EH.
1534 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1535
1536 // Thread a jump through the finally cleanup.
1537 CGF.EmitBranchThroughCleanup(RethrowDest);
1538
1539 CGF.Builder.restoreIP(savedIP);
1540 }
1541
1542 // Finally, leave the @finally cleanup.
1543 CGF.PopCleanupBlock();
John McCallf1549f62010-07-06 01:34:17 +00001544}
1545
John McCall66b22772013-02-12 03:51:46 +00001546/// In a terminate landing pad, should we use __clang__call_terminate
1547/// or just a naked call to std::terminate?
1548///
1549/// __clang_call_terminate calls __cxa_begin_catch, which then allows
1550/// std::terminate to usefully report something about the
1551/// violating exception.
1552static bool useClangCallTerminate(CodeGenModule &CGM) {
1553 // Only do this for Itanium-family ABIs in C++ mode.
1554 return (CGM.getLangOpts().CPlusPlus &&
1555 CGM.getTarget().getCXXABI().isItaniumFamily());
1556}
1557
1558/// Get or define the following function:
1559/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
1560/// This code is used only in C++.
1561static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
1562 llvm::FunctionType *fnTy =
1563 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
1564 llvm::Constant *fnRef =
1565 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
1566
1567 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
1568 if (fn && fn->empty()) {
1569 fn->setDoesNotThrow();
1570 fn->setDoesNotReturn();
1571
1572 // What we really want is to massively penalize inlining without
1573 // forbidding it completely. The difference between that and
1574 // 'noinline' is negligible.
1575 fn->addFnAttr(llvm::Attribute::NoInline);
1576
1577 // Allow this function to be shared across translation units, but
1578 // we don't want it to turn into an exported symbol.
1579 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
1580 fn->setVisibility(llvm::Function::HiddenVisibility);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001581 if (CGM.supportsCOMDAT())
1582 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
John McCall66b22772013-02-12 03:51:46 +00001583
1584 // Set up the function.
1585 llvm::BasicBlock *entry =
1586 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
1587 CGBuilderTy builder(entry);
1588
1589 // Pull the exception pointer out of the parameter list.
1590 llvm::Value *exn = &*fn->arg_begin();
1591
1592 // Call __cxa_begin_catch(exn).
John McCallbd7370a2013-02-28 19:01:20 +00001593 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
1594 catchCall->setDoesNotThrow();
1595 catchCall->setCallingConv(CGM.getRuntimeCC());
John McCall66b22772013-02-12 03:51:46 +00001596
1597 // Call std::terminate().
1598 llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM));
1599 termCall->setDoesNotThrow();
1600 termCall->setDoesNotReturn();
John McCallbd7370a2013-02-28 19:01:20 +00001601 termCall->setCallingConv(CGM.getRuntimeCC());
John McCall66b22772013-02-12 03:51:46 +00001602
1603 // std::terminate cannot return.
1604 builder.CreateUnreachable();
1605 }
1606
1607 return fnRef;
1608}
1609
John McCallf1549f62010-07-06 01:34:17 +00001610llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1611 if (TerminateLandingPad)
1612 return TerminateLandingPad;
1613
1614 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1615
1616 // This will get inserted at the end of the function.
1617 TerminateLandingPad = createBasicBlock("terminate.lpad");
1618 Builder.SetInsertPoint(TerminateLandingPad);
1619
1620 // Tell the backend that this is a landing pad.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001621 const EHPersonality &Personality = EHPersonality::get(*this);
Bill Wendling285cfd82011-09-19 20:31:14 +00001622 llvm::LandingPadInst *LPadInst =
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001623 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendling285cfd82011-09-19 20:31:14 +00001624 getOpaquePersonalityFn(CGM, Personality), 0);
1625 LPadInst->addClause(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +00001626
John McCall66b22772013-02-12 03:51:46 +00001627 llvm::CallInst *terminateCall;
1628 if (useClangCallTerminate(CGM)) {
1629 // Extract out the exception pointer.
1630 llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0);
John McCallbd7370a2013-02-28 19:01:20 +00001631 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
John McCall66b22772013-02-12 03:51:46 +00001632 } else {
John McCallbd7370a2013-02-28 19:01:20 +00001633 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
John McCall66b22772013-02-12 03:51:46 +00001634 }
1635 terminateCall->setDoesNotReturn();
John McCalld16c2cf2011-02-08 08:22:06 +00001636 Builder.CreateUnreachable();
Mike Stumpd88ea562009-12-09 03:35:49 +00001637
John McCallf1549f62010-07-06 01:34:17 +00001638 // Restore the saved insertion state.
1639 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001640
John McCallf1549f62010-07-06 01:34:17 +00001641 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001642}
Mike Stump9b39c512009-12-09 22:59:31 +00001643
1644llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001645 if (TerminateHandler)
1646 return TerminateHandler;
1647
John McCallf1549f62010-07-06 01:34:17 +00001648 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001649
John McCallf1549f62010-07-06 01:34:17 +00001650 // Set up the terminate handler. This block is inserted at the very
1651 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001652 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001653 Builder.SetInsertPoint(TerminateHandler);
John McCall45ff3802013-06-20 21:37:43 +00001654 llvm::CallInst *terminateCall;
1655 if (useClangCallTerminate(CGM)) {
1656 // Load the exception pointer.
1657 llvm::Value *exn = getExceptionFromSlot();
1658 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1659 } else {
1660 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1661 }
1662 terminateCall->setDoesNotReturn();
Mike Stump9b39c512009-12-09 22:59:31 +00001663 Builder.CreateUnreachable();
1664
John McCall3d3ec1c2010-04-21 10:05:39 +00001665 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001666 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001667
Mike Stump9b39c512009-12-09 22:59:31 +00001668 return TerminateHandler;
1669}
John McCallf1549f62010-07-06 01:34:17 +00001670
David Chisnallc6860042012-11-07 16:50:40 +00001671llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall777d6e52011-08-11 02:22:43 +00001672 if (EHResumeBlock) return EHResumeBlock;
John McCallff8e1152010-07-23 21:56:41 +00001673
1674 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1675
1676 // We emit a jump to a notional label at the outermost unwind state.
John McCall777d6e52011-08-11 02:22:43 +00001677 EHResumeBlock = createBasicBlock("eh.resume");
1678 Builder.SetInsertPoint(EHResumeBlock);
John McCallff8e1152010-07-23 21:56:41 +00001679
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001680 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallff8e1152010-07-23 21:56:41 +00001681
1682 // This can always be a call because we necessarily didn't find
1683 // anything on the EH stack which needs our help.
Benjamin Krameraf2771b2012-02-08 12:41:24 +00001684 const char *RethrowName = Personality.CatchallRethrowFn;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001685 if (RethrowName != nullptr && !isCleanup) {
John McCallbd7370a2013-02-28 19:01:20 +00001686 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001687 getExceptionFromSlot())->setDoesNotReturn();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001688 Builder.CreateUnreachable();
1689 Builder.restoreIP(SavedIP);
1690 return EHResumeBlock;
John McCall93c332a2011-05-28 21:13:02 +00001691 }
1692
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001693 // Recreate the landingpad's return value for the 'resume' instruction.
1694 llvm::Value *Exn = getExceptionFromSlot();
1695 llvm::Value *Sel = getSelectorFromSlot();
John McCallff8e1152010-07-23 21:56:41 +00001696
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001697 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001698 Sel->getType(), nullptr);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001699 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1700 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1701 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1702
1703 Builder.CreateResume(LPadVal);
John McCallff8e1152010-07-23 21:56:41 +00001704 Builder.restoreIP(SavedIP);
John McCall777d6e52011-08-11 02:22:43 +00001705 return EHResumeBlock;
John McCallff8e1152010-07-23 21:56:41 +00001706}
Reid Kleckner98592d92013-09-16 21:46:30 +00001707
1708void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001709 // FIXME: Implement SEH on other architectures.
1710 const llvm::Triple &T = CGM.getTarget().getTriple();
1711 if (T.getArch() != llvm::Triple::x86_64 ||
1712 !T.isKnownWindowsMSVCEnvironment()) {
1713 ErrorUnsupported(&S, "__try statement");
1714 return;
1715 }
1716
1717 SEHFinallyInfo FI;
1718 EnterSEHTryStmt(S, FI);
1719 {
1720 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1721
1722 SEHTryEpilogueStack.push_back(&TryExit);
1723 EmitStmt(S.getTryBlock());
1724 SEHTryEpilogueStack.pop_back();
1725
1726 if (!TryExit.getBlock()->use_empty())
1727 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1728 else
1729 delete TryExit.getBlock();
1730 }
1731 ExitSEHTryStmt(S, FI);
1732}
1733
1734namespace {
1735struct PerformSEHFinally : EHScopeStack::Cleanup {
1736 CodeGenFunction::SEHFinallyInfo *FI;
1737 PerformSEHFinally(CodeGenFunction::SEHFinallyInfo *FI) : FI(FI) {}
1738
1739 void Emit(CodeGenFunction &CGF, Flags F) override {
1740 // Cleanups are emitted at most twice: once for normal control flow and once
1741 // for exception control flow. Branch into the finally block, and remember
1742 // the continuation block so we can branch out later.
1743 if (!FI->FinallyBB) {
1744 FI->FinallyBB = CGF.createBasicBlock("__finally");
1745 FI->FinallyBB->insertInto(CGF.CurFn);
1746 FI->FinallyBB->moveAfter(CGF.Builder.GetInsertBlock());
1747 }
1748
1749 // Set the termination status and branch in.
1750 CGF.Builder.CreateStore(
1751 llvm::ConstantInt::get(CGF.Int8Ty, F.isForEHCleanup()),
1752 CGF.getAbnormalTerminationSlot());
1753 CGF.Builder.CreateBr(FI->FinallyBB);
1754
1755 // Create a continuation block for normal or exceptional control.
1756 if (F.isForEHCleanup()) {
1757 assert(!FI->ResumeBB && "double emission for EH");
1758 FI->ResumeBB = CGF.createBasicBlock("__finally.resume");
1759 CGF.EmitBlock(FI->ResumeBB);
1760 } else {
1761 assert(F.isForNormalCleanup() && !FI->ContBB && "double normal emission");
1762 FI->ContBB = CGF.createBasicBlock("__finally.cont");
1763 CGF.EmitBlock(FI->ContBB);
1764 // Try to keep source order.
1765 FI->ContBB->moveAfter(FI->FinallyBB);
1766 }
1767 }
1768};
1769}
1770
1771/// Create a stub filter function that will ultimately hold the code of the
1772/// filter expression. The EH preparation passes in LLVM will outline the code
1773/// from the main function body into this stub.
1774llvm::Function *
1775CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1776 const SEHExceptStmt &Except) {
1777 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1778 llvm::Function *ParentFn = ParentCGF.CurFn;
1779
1780 Expr *FilterExpr = Except.getFilterExpr();
1781
1782 // Get the mangled function name.
1783 SmallString<128> Name;
1784 {
1785 llvm::raw_svector_ostream OS(Name);
1786 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1787 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1788 CGM.getCXXABI().getMangleContext().mangleSEHFilterExpression(Parent, OS);
1789 }
1790
1791 // Arrange a function with the declaration:
1792 // int filt(EXCEPTION_POINTERS *exception_pointers, void *frame_pointer)
1793 QualType RetTy = getContext().IntTy;
1794 FunctionArgList Args;
1795 SEHPointersDecl = ImplicitParamDecl::Create(
1796 getContext(), nullptr, FilterExpr->getLocStart(),
1797 &getContext().Idents.get("exception_pointers"), getContext().VoidPtrTy);
1798 Args.push_back(SEHPointersDecl);
1799 Args.push_back(ImplicitParamDecl::Create(
1800 getContext(), nullptr, FilterExpr->getLocStart(),
1801 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1802 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1803 RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
1804 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1805 llvm::Function *Fn = llvm::Function::Create(FnTy, ParentFn->getLinkage(),
1806 Name.str(), &CGM.getModule());
1807 // The filter is either in the same comdat as the function, or it's internal.
1808 if (llvm::Comdat *C = ParentFn->getComdat()) {
1809 Fn->setComdat(C);
1810 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
1811 // FIXME: Unreachable with Rafael's changes?
1812 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1813 ParentFn->setComdat(C);
1814 Fn->setComdat(C);
1815 } else {
1816 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1817 }
1818
1819 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1820 FilterExpr->getLocStart(), FilterExpr->getLocStart());
1821
1822 EmitSEHExceptionCodeSave();
1823
1824 // Insert dummy allocas for every local variable in scope. We'll initialize
1825 // them and prune the unused ones after we find out which ones were
1826 // referenced.
1827 for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
1828 const Decl *VD = DeclPtrs.first;
1829 llvm::Value *Ptr = DeclPtrs.second;
1830 auto *ValTy = cast<llvm::PointerType>(Ptr->getType())->getElementType();
1831 LocalDeclMap[VD] = CreateTempAlloca(ValTy, Ptr->getName() + ".filt");
1832 }
1833
1834 // Emit the original filter expression, convert to i32, and return.
1835 llvm::Value *R = EmitScalarExpr(FilterExpr);
1836 R = Builder.CreateIntCast(R, CGM.IntTy,
1837 FilterExpr->getType()->isSignedIntegerType());
1838 Builder.CreateStore(R, ReturnValue);
1839
1840 FinishFunction(FilterExpr->getLocEnd());
1841
1842 for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
1843 const Decl *VD = DeclPtrs.first;
1844 auto *Alloca = cast<llvm::AllocaInst>(LocalDeclMap[VD]);
1845 if (Alloca->hasNUses(0)) {
1846 Alloca->eraseFromParent();
1847 continue;
1848 }
1849 ErrorUnsupported(FilterExpr,
1850 "SEH filter expression local variable capture");
1851 }
1852
1853 return Fn;
1854}
1855
1856void CodeGenFunction::EmitSEHExceptionCodeSave() {
1857 // Save the exception code in the exception slot to unify exception access in
1858 // the filter function and the landing pad.
1859 // struct EXCEPTION_POINTERS {
1860 // EXCEPTION_RECORD *ExceptionRecord;
1861 // CONTEXT *ContextRecord;
1862 // };
1863 // void *exn.slot =
1864 // (void *)(uintptr_t)exception_pointers->ExceptionRecord->ExceptionCode;
1865 llvm::Value *Ptrs = Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1866 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1867 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
1868 Ptrs = Builder.CreateBitCast(Ptrs, PtrsTy->getPointerTo());
1869 llvm::Value *Rec = Builder.CreateStructGEP(Ptrs, 0);
1870 Rec = Builder.CreateLoad(Rec);
1871 llvm::Value *Code = Builder.CreateLoad(Rec);
1872 Code = Builder.CreateZExt(Code, CGM.IntPtrTy);
1873 // FIXME: Change landing pads to produce {i32, i32} and make the exception
1874 // slot an i32.
1875 Code = Builder.CreateIntToPtr(Code, CGM.VoidPtrTy);
1876 Builder.CreateStore(Code, getExceptionSlot());
1877}
1878
1879llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1880 // Sema should diagnose calling this builtin outside of a filter context, but
1881 // don't crash if we screw up.
1882 if (!SEHPointersDecl)
1883 return llvm::UndefValue::get(Int8PtrTy);
1884 return Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1885}
1886
1887llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
1888 // If we're in a landing pad or filter function, the exception slot contains
1889 // the code.
1890 assert(ExceptionSlot);
1891 llvm::Value *Code =
1892 Builder.CreatePtrToInt(getExceptionFromSlot(), CGM.IntPtrTy);
1893 return Builder.CreateTrunc(Code, CGM.Int32Ty);
1894}
1895
1896llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
1897 // Load from the abnormal termination slot. It will be uninitialized outside
1898 // of __finally blocks, which we should warn or error on.
1899 llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot());
1900 return Builder.CreateZExt(IsEH, Int32Ty);
1901}
1902
1903void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
1904 if (S.getFinallyHandler()) {
1905 // Push a cleanup for __finally blocks.
1906 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, &FI);
1907 return;
1908 }
1909
1910 // Otherwise, we must have an __except block.
1911 SEHExceptStmt *Except = S.getExceptHandler();
1912 assert(Except);
1913 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1914
1915 // If the filter is known to evaluate to 1, then we can use the clause "catch
1916 // i8* null".
1917 llvm::Constant *C =
1918 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1919 if (C && C->isOneValue()) {
1920 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1921 return;
1922 }
1923
1924 // In general, we have to emit an outlined filter function. Use the function
1925 // in place of the RTTI typeinfo global that C++ EH uses.
1926 CodeGenFunction FilterCGF(CGM, /*suppressNewContext=*/true);
1927 llvm::Function *FilterFunc =
1928 FilterCGF.GenerateSEHFilterFunction(*this, *Except);
1929 llvm::Constant *OpaqueFunc =
1930 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1931 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except"));
1932}
1933
1934void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
1935 // Just pop the cleanup if it's a __finally block.
1936 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
1937 PopCleanupBlock();
1938 assert(FI.ContBB && "did not emit normal cleanup");
1939
1940 // Emit the code into FinallyBB.
1941 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1942 Builder.SetInsertPoint(FI.FinallyBB);
1943 EmitStmt(Finally->getBlock());
1944
1945 if (HaveInsertPoint()) {
1946 if (FI.ResumeBB) {
1947 llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot(),
1948 "abnormal.termination");
1949 IsEH = Builder.CreateICmpEQ(IsEH, llvm::ConstantInt::get(Int8Ty, 0));
1950 Builder.CreateCondBr(IsEH, FI.ContBB, FI.ResumeBB);
1951 } else {
1952 // There was nothing exceptional in the try body, so we only have normal
1953 // control flow.
1954 Builder.CreateBr(FI.ContBB);
1955 }
1956 }
1957
1958 Builder.restoreIP(SavedIP);
1959
1960 return;
1961 }
1962
1963 // Otherwise, we must have an __except block.
1964 const SEHExceptStmt *Except = S.getExceptHandler();
1965 assert(Except && "__try must have __finally xor __except");
1966 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1967
1968 // Don't emit the __except block if the __try block lacked invokes.
1969 // TODO: Model unwind edges from instructions, either with iload / istore or
1970 // a try body function.
1971 if (!CatchScope.hasEHBranches()) {
1972 CatchScope.clearHandlerBlocks();
1973 EHStack.popCatch();
1974 return;
1975 }
1976
1977 // The fall-through block.
1978 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1979
1980 // We just emitted the body of the __try; jump to the continue block.
1981 if (HaveInsertPoint())
1982 Builder.CreateBr(ContBB);
1983
1984 // Check if our filter function returned true.
1985 emitCatchDispatchBlock(*this, CatchScope);
1986
1987 // Grab the block before we pop the handler.
1988 llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1989 EHStack.popCatch();
1990
1991 EmitBlockAfterUses(ExceptBB);
1992
1993 // Emit the __except body.
1994 EmitStmt(Except->getBlock());
1995
1996 if (HaveInsertPoint())
1997 Builder.CreateBr(ContBB);
1998
1999 EmitBlock(ContBB);
Reid Kleckner98592d92013-09-16 21:46:30 +00002000}
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002001
2002void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002003 // If this code is reachable then emit a stop point (if generating
2004 // debug info). We have to do this ourselves because we are on the
2005 // "simple" statement path.
2006 if (HaveInsertPoint())
2007 EmitStopPoint(&S);
2008
2009 assert(!SEHTryEpilogueStack.empty() &&
2010 "sema should have rejected this __leave");
2011 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002012}