blob: ff12a9ab829e4c1e43925a6b5c9ac988e615fdd5 [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"
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -070022#include "clang/AST/StmtVisitor.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070023#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000024#include "llvm/IR/Intrinsics.h"
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -070025#include "llvm/IR/IntrinsicInst.h"
26#include "llvm/Support/SaveAndRestore.h"
John McCallf1549f62010-07-06 01:34:17 +000027
Anders Carlsson756b5c42009-10-30 01:42:31 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall629df012013-02-12 03:51:38 +000031static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump99533832009-12-02 07:41:41 +000032 // void __cxa_free_exception(void *thrown_exception);
Mike Stump8755ec32009-12-10 00:06:18 +000033
Chris Lattner2acc6e32011-07-18 04:24:23 +000034 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000035 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000036
John McCall629df012013-02-12 03:51:38 +000037 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump99533832009-12-02 07:41:41 +000038}
39
John McCall629df012013-02-12 03:51:38 +000040static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith14b0e4b2013-06-20 23:03:35 +000041 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stumpcce3d4f2009-12-07 23:38:24 +000042
Chris Lattner2acc6e32011-07-18 04:24:23 +000043 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000044 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000045
John McCall629df012013-02-12 03:51:38 +000046 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stumpcce3d4f2009-12-07 23:38:24 +000047}
48
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070049llvm::Constant *CodeGenModule::getTerminateFn() {
Mike Stump99533832009-12-02 07:41:41 +000050 // void __terminate();
51
Chris Lattner2acc6e32011-07-18 04:24:23 +000052 llvm::FunctionType *FTy =
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070053 llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000054
Chris Lattner5f9e2722011-07-23 10:55:15 +000055 StringRef name;
John McCall256a76e2011-07-06 01:22:26 +000056
57 // In C++, use std::terminate().
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070058 if (getLangOpts().CPlusPlus &&
59 getTarget().getCXXABI().isItaniumFamily()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -070060 name = "_ZSt9terminatev";
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070061 } else if (getLangOpts().CPlusPlus &&
62 getTarget().getCXXABI().isMicrosoft()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -070063 name = "\01?terminate@@YAXXZ";
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070064 } else if (getLangOpts().ObjC1 &&
65 getLangOpts().ObjCRuntime.hasTerminate())
John McCall256a76e2011-07-06 01:22:26 +000066 name = "objc_terminate";
67 else
68 name = "abort";
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070069 return CreateRuntimeFunction(FTy, name);
David Chisnall79a9ad82010-05-17 13:49:20 +000070}
71
John McCall629df012013-02-12 03:51:38 +000072static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner5f9e2722011-07-23 10:55:15 +000073 StringRef Name) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000074 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000075 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall8262b6a2010-07-17 00:43:08 +000076
John McCall629df012013-02-12 03:51:38 +000077 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +000078}
79
Benjamin Krameraf2771b2012-02-08 12:41:24 +000080namespace {
81 /// The exceptions personality for a function.
82 struct EHPersonality {
83 const char *PersonalityFn;
84
85 // If this is non-null, this personality requires a non-standard
86 // function for rethrowing an exception after a catchall cleanup.
87 // This function must have prototype void(void*).
88 const char *CatchallRethrowFn;
89
Stephen Hines0e2c34f2015-03-23 12:09:02 -070090 static const EHPersonality &get(CodeGenModule &CGM,
91 const FunctionDecl *FD);
92 static const EHPersonality &get(CodeGenFunction &CGF) {
93 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
94 }
95
Benjamin Krameraf2771b2012-02-08 12:41:24 +000096 static const EHPersonality GNU_C;
97 static const EHPersonality GNU_C_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -080098 static const EHPersonality GNU_C_SEH;
Benjamin Krameraf2771b2012-02-08 12:41:24 +000099 static const EHPersonality GNU_ObjC;
David Chisnall65bd4ac2013-01-11 15:33:01 +0000100 static const EHPersonality GNUstep_ObjC;
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000101 static const EHPersonality GNU_ObjCXX;
102 static const EHPersonality NeXT_ObjC;
103 static const EHPersonality GNU_CPlusPlus;
104 static const EHPersonality GNU_CPlusPlus_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800105 static const EHPersonality GNU_CPlusPlus_SEH;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700106 static const EHPersonality MSVC_except_handler;
107 static const EHPersonality MSVC_C_specific_handler;
108 static const EHPersonality MSVC_CxxFrameHandler3;
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000109 };
110}
111
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700112const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000113const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700114EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
115const EHPersonality
Stephen Hines176edba2014-12-01 14:53:08 -0800116EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
117const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700118EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
119const EHPersonality
120EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
121const EHPersonality
122EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000123const EHPersonality
Stephen Hines176edba2014-12-01 14:53:08 -0800124EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
125const EHPersonality
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000126EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
127const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700128EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall65bd4ac2013-01-11 15:33:01 +0000129const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700130EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700131const EHPersonality
132EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
133const EHPersonality
134EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
135const EHPersonality
136EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
John McCall8262b6a2010-07-17 00:43:08 +0000137
Stephen Hines176edba2014-12-01 14:53:08 -0800138/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
139/// other platforms, unless the user asked for SjLj exceptions.
140static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
141 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
142}
143
144static const EHPersonality &getCPersonality(const llvm::Triple &T,
145 const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000146 if (L.SjLjExceptions)
147 return EHPersonality::GNU_C_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800148 else if (useLibGCCSEHPersonality(T))
149 return EHPersonality::GNU_C_SEH;
John McCall8262b6a2010-07-17 00:43:08 +0000150 return EHPersonality::GNU_C;
151}
152
Stephen Hines176edba2014-12-01 14:53:08 -0800153static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
154 const LangOptions &L) {
John McCall260611a2012-06-20 06:18:46 +0000155 switch (L.ObjCRuntime.getKind()) {
156 case ObjCRuntime::FragileMacOSX:
Stephen Hines176edba2014-12-01 14:53:08 -0800157 return getCPersonality(T, L);
John McCall260611a2012-06-20 06:18:46 +0000158 case ObjCRuntime::MacOSX:
159 case ObjCRuntime::iOS:
160 return EHPersonality::NeXT_ObjC;
David Chisnall11d3f4c2012-07-03 20:49:52 +0000161 case ObjCRuntime::GNUstep:
David Chisnall65bd4ac2013-01-11 15:33:01 +0000162 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
163 return EHPersonality::GNUstep_ObjC;
164 // fallthrough
David Chisnall11d3f4c2012-07-03 20:49:52 +0000165 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000166 case ObjCRuntime::ObjFW:
John McCall8262b6a2010-07-17 00:43:08 +0000167 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000168 }
John McCall260611a2012-06-20 06:18:46 +0000169 llvm_unreachable("bad runtime kind");
John McCallf1549f62010-07-06 01:34:17 +0000170}
171
Stephen Hines176edba2014-12-01 14:53:08 -0800172static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
173 const LangOptions &L) {
John McCall8262b6a2010-07-17 00:43:08 +0000174 if (L.SjLjExceptions)
175 return EHPersonality::GNU_CPlusPlus_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800176 else if (useLibGCCSEHPersonality(T))
177 return EHPersonality::GNU_CPlusPlus_SEH;
178 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000179}
180
181/// Determines the personality function to use when both C++
182/// and Objective-C exceptions are being caught.
Stephen Hines176edba2014-12-01 14:53:08 -0800183static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
184 const LangOptions &L) {
John McCall260611a2012-06-20 06:18:46 +0000185 switch (L.ObjCRuntime.getKind()) {
John McCallf1549f62010-07-06 01:34:17 +0000186 // The ObjC personality defers to the C++ personality for non-ObjC
187 // handlers. Unlike the C++ case, we use the same personality
188 // function on targets using (backend-driven) SJLJ EH.
John McCall260611a2012-06-20 06:18:46 +0000189 case ObjCRuntime::MacOSX:
190 case ObjCRuntime::iOS:
191 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000192
John McCall260611a2012-06-20 06:18:46 +0000193 // In the fragile ABI, just use C++ exception handling and hope
194 // they're not doing crazy exception mixing.
195 case ObjCRuntime::FragileMacOSX:
Stephen Hines176edba2014-12-01 14:53:08 -0800196 return getCXXPersonality(T, L);
David Chisnall79a9ad82010-05-17 13:49:20 +0000197
David Chisnall11d3f4c2012-07-03 20:49:52 +0000198 // The GCC runtime's personality function inherently doesn't support
John McCall8262b6a2010-07-17 00:43:08 +0000199 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnall11d3f4c2012-07-03 20:49:52 +0000200 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000201 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnall11d3f4c2012-07-03 20:49:52 +0000202 return EHPersonality::GNU_ObjC;
203 case ObjCRuntime::GNUstep:
John McCall260611a2012-06-20 06:18:46 +0000204 return EHPersonality::GNU_ObjCXX;
205 }
206 llvm_unreachable("bad runtime kind");
John McCallf1549f62010-07-06 01:34:17 +0000207}
208
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700209static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
210 if (T.getArch() == llvm::Triple::x86)
211 return EHPersonality::MSVC_except_handler;
212 return EHPersonality::MSVC_C_specific_handler;
213}
214
215const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
216 const FunctionDecl *FD) {
Stephen Hines176edba2014-12-01 14:53:08 -0800217 const llvm::Triple &T = CGM.getTarget().getTriple();
218 const LangOptions &L = CGM.getLangOpts();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700219
220 // Try to pick a personality function that is compatible with MSVC if we're
221 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
222 // the GCC-style personality function.
223 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
224 if (L.SjLjExceptions)
225 return EHPersonality::GNU_CPlusPlus_SJLJ;
226 else if (FD && FD->usesSEHTry())
227 return getSEHPersonalityMSVC(T);
228 else
229 return EHPersonality::MSVC_CxxFrameHandler3;
230 }
231
John McCall8262b6a2010-07-17 00:43:08 +0000232 if (L.CPlusPlus && L.ObjC1)
Stephen Hines176edba2014-12-01 14:53:08 -0800233 return getObjCXXPersonality(T, L);
John McCall8262b6a2010-07-17 00:43:08 +0000234 else if (L.CPlusPlus)
Stephen Hines176edba2014-12-01 14:53:08 -0800235 return getCXXPersonality(T, L);
John McCall8262b6a2010-07-17 00:43:08 +0000236 else if (L.ObjC1)
Stephen Hines176edba2014-12-01 14:53:08 -0800237 return getObjCPersonality(T, L);
John McCallf1549f62010-07-06 01:34:17 +0000238 else
Stephen Hines176edba2014-12-01 14:53:08 -0800239 return getCPersonality(T, L);
John McCall8262b6a2010-07-17 00:43:08 +0000240}
John McCallf1549f62010-07-06 01:34:17 +0000241
John McCallb2593832010-09-16 06:16:50 +0000242static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000243 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000244 llvm::Constant *Fn =
Chris Lattner8b418682012-02-07 00:39:47 +0000245 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000246 Personality.PersonalityFn);
John McCallb2593832010-09-16 06:16:50 +0000247 return Fn;
248}
249
250static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
251 const EHPersonality &Personality) {
252 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCalld16c2cf2011-02-08 08:22:06 +0000253 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCallb2593832010-09-16 06:16:50 +0000254}
255
256/// Check whether a personality function could reasonably be swapped
257/// for a C++ personality function.
258static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700259 for (llvm::User *U : Fn->users()) {
John McCallb2593832010-09-16 06:16:50 +0000260 // Conditionally white-list bitcasts.
Stephen Hines651f13c2014-04-23 16:59:28 -0700261 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCallb2593832010-09-16 06:16:50 +0000262 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
263 if (!PersonalityHasOnlyCXXUses(CE))
264 return false;
265 continue;
266 }
267
Bill Wendling40ccacc2011-09-19 22:08:36 +0000268 // Otherwise, it has to be a landingpad instruction.
Stephen Hines651f13c2014-04-23 16:59:28 -0700269 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling40ccacc2011-09-19 22:08:36 +0000270 if (!LPI) return false;
John McCallb2593832010-09-16 06:16:50 +0000271
Bill Wendling40ccacc2011-09-19 22:08:36 +0000272 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCallb2593832010-09-16 06:16:50 +0000273 // Look for something that would've been returned by the ObjC
274 // runtime's GetEHType() method.
Bill Wendling40ccacc2011-09-19 22:08:36 +0000275 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
276 if (LPI->isCatch(I)) {
277 // Check if the catch value has the ObjC prefix.
Bill Wendlingeecb6a12011-09-20 00:40:19 +0000278 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
279 // ObjC EH selector entries are always global variables with
280 // names starting like this.
281 if (GV->getName().startswith("OBJC_EHTYPE"))
282 return false;
Bill Wendling40ccacc2011-09-19 22:08:36 +0000283 } else {
284 // Check if any of the filter values have the ObjC prefix.
285 llvm::Constant *CVal = cast<llvm::Constant>(Val);
286 for (llvm::User::op_iterator
287 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendlingeecb6a12011-09-20 00:40:19 +0000288 if (llvm::GlobalVariable *GV =
289 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
290 // ObjC EH selector entries are always global variables with
291 // names starting like this.
292 if (GV->getName().startswith("OBJC_EHTYPE"))
293 return false;
Bill Wendling40ccacc2011-09-19 22:08:36 +0000294 }
295 }
John McCallb2593832010-09-16 06:16:50 +0000296 }
297 }
298
299 return true;
300}
301
302/// Try to use the C++ personality function in ObjC++. Not doing this
303/// can cause some incompatibilities with gcc, which is more
304/// aggressive about only using the ObjC++ personality in a function
305/// when it really needs it.
306void CodeGenModule::SimplifyPersonality() {
John McCallb2593832010-09-16 06:16:50 +0000307 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCallb2593832010-09-16 06:16:50 +0000309 return;
310
John McCall70cd6192012-11-14 17:48:31 +0000311 // Both the problem this endeavors to fix and the way the logic
312 // above works is specific to the NeXT runtime.
313 if (!LangOpts.ObjCRuntime.isNeXTFamily())
314 return;
315
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700316 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Stephen Hines176edba2014-12-01 14:53:08 -0800317 const EHPersonality &CXX =
318 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000319 if (&ObjCXX == &CXX)
John McCallb2593832010-09-16 06:16:50 +0000320 return;
321
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000322 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
323 "Different EHPersonalities using the same personality function.");
324
325 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCallb2593832010-09-16 06:16:50 +0000326
327 // Nothing to do if it's unused.
328 if (!Fn || Fn->use_empty()) return;
329
330 // Can't do the optimization if it has non-C++ uses.
331 if (!PersonalityHasOnlyCXXUses(Fn)) return;
332
333 // Create the C++ personality function and kill off the old
334 // function.
335 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
336
337 // This can happen if the user is screwing with us.
338 if (Fn->getType() != CXXFn->getType()) return;
339
340 Fn->replaceAllUsesWith(CXXFn);
341 Fn->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000342}
343
344/// Returns the value to inject into a selector to indicate the
345/// presence of a catch-all.
346static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
347 // Possibly we should use @llvm.eh.catch.all.value here.
John McCalld16c2cf2011-02-08 08:22:06 +0000348 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallf1549f62010-07-06 01:34:17 +0000349}
350
John McCall09faeab2010-07-13 21:17:51 +0000351namespace {
352 /// A cleanup to free the exception object if its initialization
353 /// throws.
John McCallc4a1a842011-07-12 00:15:30 +0000354 struct FreeException : EHScopeStack::Cleanup {
355 llvm::Value *exn;
356 FreeException(llvm::Value *exn) : exn(exn) {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700357 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallbd7370a2013-02-28 19:01:20 +0000358 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCall09faeab2010-07-13 21:17:51 +0000359 }
360 };
361}
362
John McCallac418162010-04-22 01:10:34 +0000363// Emits an exception expression into the given location. This
364// differs from EmitAnyExprToMem only in that, if a final copy-ctor
365// call is required, an exception within that copy ctor causes
366// std::terminate to be invoked.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700367void CodeGenFunction::EmitAnyExprToExn(const Expr *e, llvm::Value *addr) {
John McCallf1549f62010-07-06 01:34:17 +0000368 // Make sure the exception object is cleaned up if there's an
369 // exception during initialization.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700370 pushFullExprCleanup<FreeException>(EHCleanup, addr);
371 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000372
373 // __cxa_allocate_exception returns a void*; we need to cast this
374 // to the appropriate type for the object.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700375 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
376 llvm::Value *typedAddr = Builder.CreateBitCast(addr, ty);
John McCallac418162010-04-22 01:10:34 +0000377
378 // FIXME: this isn't quite right! If there's a final unelided call
379 // to a copy constructor, then according to [except.terminate]p1 we
380 // must call std::terminate() if that constructor throws, because
381 // technically that copy occurs after the exception expression is
382 // evaluated but before the exception is caught. But the best way
383 // to handle that is to teach EmitAggExpr to do the final copy
384 // differently if it can't be elided.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700385 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
386 /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000387
John McCall3ad32c82011-01-28 08:37:24 +0000388 // Deactivate the cleanup block.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700389 DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump0f590be2009-12-01 03:41:18 +0000390}
391
John McCallf1549f62010-07-06 01:34:17 +0000392llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall93c332a2011-05-28 21:13:02 +0000393 if (!ExceptionSlot)
394 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallf1549f62010-07-06 01:34:17 +0000395 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000396}
397
John McCall93c332a2011-05-28 21:13:02 +0000398llvm::Value *CodeGenFunction::getEHSelectorSlot() {
399 if (!EHSelectorSlot)
400 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
401 return EHSelectorSlot;
402}
403
Bill Wendlingae270592011-09-15 18:57:19 +0000404llvm::Value *CodeGenFunction::getExceptionFromSlot() {
405 return Builder.CreateLoad(getExceptionSlot(), "exn");
406}
407
408llvm::Value *CodeGenFunction::getSelectorFromSlot() {
409 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
410}
411
Richard Smith4c71b8c2013-05-07 21:53:22 +0000412void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
413 bool KeepInsertionPoint) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700414 if (const Expr *SubExpr = E->getSubExpr()) {
415 QualType ThrowType = SubExpr->getType();
416 if (ThrowType->isObjCObjectPointerType()) {
417 const Stmt *ThrowStmt = E->getSubExpr();
418 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
419 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
420 } else {
421 CGM.getCXXABI().emitThrow(*this, E);
John McCallac418162010-04-22 01:10:34 +0000422 }
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700423 } else {
424 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCallac418162010-04-22 01:10:34 +0000425 }
Mike Stump8755ec32009-12-10 00:06:18 +0000426
John McCallcd5b22e2011-01-12 03:41:02 +0000427 // throw is an expression, and the expression emitters expect us
428 // to leave ourselves at a valid insertion point.
Richard Smith4c71b8c2013-05-07 21:53:22 +0000429 if (KeepInsertionPoint)
430 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000431}
Mike Stump2bf701e2009-11-20 23:44:51 +0000432
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000433void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000434 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000435 return;
436
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000437 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700438 if (!FD) {
439 // Check if CapturedDecl is nothrow and create terminate scope for it.
440 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
441 if (CD->isNothrow())
442 EHStack.pushTerminate();
443 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000444 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700445 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000446 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700447 if (!Proto)
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000448 return;
449
Sebastian Redla968e972011-03-15 18:42:48 +0000450 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
451 if (isNoexceptExceptionSpec(EST)) {
452 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
453 // noexcept functions are simple terminate scopes.
454 EHStack.pushTerminate();
455 }
456 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700457 // TODO: Revisit exception specifications for the MS ABI. There is a way to
458 // encode these in an object file but MSVC doesn't do anything with it.
459 if (getTarget().getCXXABI().isMicrosoft())
460 return;
Sebastian Redla968e972011-03-15 18:42:48 +0000461 unsigned NumExceptions = Proto->getNumExceptions();
462 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000463
Sebastian Redla968e972011-03-15 18:42:48 +0000464 for (unsigned I = 0; I != NumExceptions; ++I) {
465 QualType Ty = Proto->getExceptionType(I);
466 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
467 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
468 /*ForEH=*/true);
469 Filter->setFilter(I, EHType);
470 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000471 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000472}
473
John McCall777d6e52011-08-11 02:22:43 +0000474/// Emit the dispatch block for a filter scope if necessary.
475static void emitFilterDispatchBlock(CodeGenFunction &CGF,
476 EHFilterScope &filterScope) {
477 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
478 if (!dispatchBlock) return;
479 if (dispatchBlock->use_empty()) {
480 delete dispatchBlock;
481 return;
482 }
483
John McCall777d6e52011-08-11 02:22:43 +0000484 CGF.EmitBlockAfterUses(dispatchBlock);
485
486 // If this isn't a catch-all filter, we need to check whether we got
487 // here because the filter triggered.
488 if (filterScope.getNumFilters()) {
489 // Load the selector value.
Bill Wendlingae270592011-09-15 18:57:19 +0000490 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall777d6e52011-08-11 02:22:43 +0000491 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
492
493 llvm::Value *zero = CGF.Builder.getInt32(0);
494 llvm::Value *failsFilter =
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700495 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
496 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
497 CGF.getEHResumeBlock(false));
John McCall777d6e52011-08-11 02:22:43 +0000498
499 CGF.EmitBlock(unexpectedBB);
500 }
501
502 // Call __cxa_call_unexpected. This doesn't need to be an invoke
503 // because __cxa_call_unexpected magically filters exceptions
504 // according to the last landing pad the exception was thrown
505 // into. Seriously.
Bill Wendlingae270592011-09-15 18:57:19 +0000506 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCallbd7370a2013-02-28 19:01:20 +0000507 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall777d6e52011-08-11 02:22:43 +0000508 ->setDoesNotReturn();
509 CGF.Builder.CreateUnreachable();
510}
511
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000512void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000513 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000514 return;
515
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000516 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700517 if (!FD) {
518 // Check if CapturedDecl is nothrow and pop terminate scope for it.
519 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
520 if (CD->isNothrow())
521 EHStack.popTerminate();
522 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000523 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700524 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000525 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700526 if (!Proto)
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000527 return;
528
Sebastian Redla968e972011-03-15 18:42:48 +0000529 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
530 if (isNoexceptExceptionSpec(EST)) {
531 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
532 EHStack.popTerminate();
533 }
534 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700535 // TODO: Revisit exception specifications for the MS ABI. There is a way to
536 // encode these in an object file but MSVC doesn't do anything with it.
537 if (getTarget().getCXXABI().isMicrosoft())
538 return;
John McCall777d6e52011-08-11 02:22:43 +0000539 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
540 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redla968e972011-03-15 18:42:48 +0000541 EHStack.popFilter();
542 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000543}
544
Mike Stump2bf701e2009-11-20 23:44:51 +0000545void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000546 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000547 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000548 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000549}
550
John McCall59a70002010-07-07 06:56:46 +0000551void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000552 unsigned NumHandlers = S.getNumHandlers();
553 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000554
John McCallf1549f62010-07-06 01:34:17 +0000555 for (unsigned I = 0; I != NumHandlers; ++I) {
556 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000557
John McCallf1549f62010-07-06 01:34:17 +0000558 llvm::BasicBlock *Handler = createBasicBlock("catch");
559 if (C->getExceptionDecl()) {
560 // FIXME: Dropping the reference type on the type into makes it
561 // impossible to correctly implement catch-by-reference
562 // semantics for pointers. Unfortunately, this is what all
563 // existing compilers do, and it's not clear that the standard
564 // personality routine is capable of doing this right. See C++ DR 388:
565 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
Stephen Hines176edba2014-12-01 14:53:08 -0800566 Qualifiers CaughtTypeQuals;
567 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
568 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall5a180392010-07-24 00:37:23 +0000569
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700570 llvm::Constant *TypeInfo = nullptr;
John McCall5a180392010-07-24 00:37:23 +0000571 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000572 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall5a180392010-07-24 00:37:23 +0000573 else
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700574 TypeInfo =
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700575 CGM.getAddrOfCXXCatchHandlerType(CaughtType, C->getCaughtType());
John McCallf1549f62010-07-06 01:34:17 +0000576 CatchScope->setHandler(I, TypeInfo, Handler);
577 } else {
578 // No exception decl indicates '...', a catch-all.
579 CatchScope->setCatchAllHandler(I, Handler);
580 }
581 }
John McCallf1549f62010-07-06 01:34:17 +0000582}
583
John McCall777d6e52011-08-11 02:22:43 +0000584llvm::BasicBlock *
585CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
586 // The dispatch block for the end of the scope chain is a block that
587 // just resumes unwinding.
588 if (si == EHStack.stable_end())
David Chisnallc6860042012-11-07 16:50:40 +0000589 return getEHResumeBlock(true);
John McCall777d6e52011-08-11 02:22:43 +0000590
591 // Otherwise, we should look at the actual scope.
592 EHScope &scope = *EHStack.find(si);
593
594 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
595 if (!dispatchBlock) {
596 switch (scope.getKind()) {
597 case EHScope::Catch: {
598 // Apply a special case to a single catch-all.
599 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
600 if (catchScope.getNumHandlers() == 1 &&
601 catchScope.getHandler(0).isCatchAll()) {
602 dispatchBlock = catchScope.getHandler(0).Block;
603
604 // Otherwise, make a dispatch block.
605 } else {
606 dispatchBlock = createBasicBlock("catch.dispatch");
607 }
608 break;
609 }
610
611 case EHScope::Cleanup:
612 dispatchBlock = createBasicBlock("ehcleanup");
613 break;
614
615 case EHScope::Filter:
616 dispatchBlock = createBasicBlock("filter.dispatch");
617 break;
618
619 case EHScope::Terminate:
620 dispatchBlock = getTerminateHandler();
621 break;
622 }
623 scope.setCachedEHDispatchBlock(dispatchBlock);
624 }
625 return dispatchBlock;
626}
627
John McCallf1549f62010-07-06 01:34:17 +0000628/// Check whether this is a non-EH scope, i.e. a scope which doesn't
629/// affect exception handling. Currently, the only non-EH scopes are
630/// normal-only cleanup scopes.
631static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000632 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000633 case EHScope::Cleanup:
634 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000635 case EHScope::Filter:
636 case EHScope::Catch:
637 case EHScope::Terminate:
638 return false;
639 }
640
David Blaikie30263482012-01-20 21:50:17 +0000641 llvm_unreachable("Invalid EHScope Kind!");
John McCallf1549f62010-07-06 01:34:17 +0000642}
643
644llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
645 assert(EHStack.requiresLandingPad());
646 assert(!EHStack.empty());
647
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700648 // If exceptions are disabled, there are usually no landingpads. However, when
649 // SEH is enabled, functions using SEH still get landingpads.
650 const LangOptions &LO = CGM.getLangOpts();
651 if (!LO.Exceptions) {
652 if (!LO.Borland && !LO.MicrosoftExt)
653 return nullptr;
654 if (!currentFunctionUsesSEHTry())
655 return nullptr;
656 }
John McCallda65ea82010-07-13 20:32:21 +0000657
John McCallf1549f62010-07-06 01:34:17 +0000658 // Check the innermost scope for a cached landing pad. If this is
659 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
660 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
661 if (LP) return LP;
662
663 // Build the landing pad for this scope.
664 LP = EmitLandingPad();
665 assert(LP);
666
667 // Cache the landing pad on the innermost scope. If this is a
668 // non-EH scope, cache the landing pad on the enclosing scope, too.
669 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
670 ir->setCachedLandingPad(LP);
671 if (!isNonEHScope(*ir)) break;
672 }
673
674 return LP;
675}
676
677llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
678 assert(EHStack.requiresLandingPad());
679
John McCall777d6e52011-08-11 02:22:43 +0000680 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
681 switch (innermostEHScope.getKind()) {
682 case EHScope::Terminate:
683 return getTerminateLandingPad();
John McCallf1549f62010-07-06 01:34:17 +0000684
John McCall777d6e52011-08-11 02:22:43 +0000685 case EHScope::Catch:
686 case EHScope::Cleanup:
687 case EHScope::Filter:
688 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
689 return lpad;
John McCallf1549f62010-07-06 01:34:17 +0000690 }
691
692 // Save the current IR generation state.
John McCall777d6e52011-08-11 02:22:43 +0000693 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700694 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallf1549f62010-07-06 01:34:17 +0000695
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700696 const EHPersonality &personality = EHPersonality::get(*this);
John McCall8262b6a2010-07-17 00:43:08 +0000697
John McCallf1549f62010-07-06 01:34:17 +0000698 // Create and configure the landing pad.
John McCall777d6e52011-08-11 02:22:43 +0000699 llvm::BasicBlock *lpad = createBasicBlock("lpad");
700 EmitBlock(lpad);
John McCallf1549f62010-07-06 01:34:17 +0000701
Bill Wendling285cfd82011-09-19 20:31:14 +0000702 llvm::LandingPadInst *LPadInst =
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700703 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendling285cfd82011-09-19 20:31:14 +0000704 getOpaquePersonalityFn(CGM, personality), 0);
705
706 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
707 Builder.CreateStore(LPadExn, getExceptionSlot());
708 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
709 Builder.CreateStore(LPadSel, getEHSelectorSlot());
710
John McCallf1549f62010-07-06 01:34:17 +0000711 // Save the exception pointer. It's safe to use a single exception
712 // pointer per function because EH cleanups can never have nested
713 // try/catches.
Bill Wendling285cfd82011-09-19 20:31:14 +0000714 // Build the landingpad instruction.
John McCallf1549f62010-07-06 01:34:17 +0000715
716 // Accumulate all the handlers in scope.
John McCall777d6e52011-08-11 02:22:43 +0000717 bool hasCatchAll = false;
718 bool hasCleanup = false;
719 bool hasFilter = false;
720 SmallVector<llvm::Value*, 4> filterTypes;
721 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700722 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
723 ++I) {
John McCallf1549f62010-07-06 01:34:17 +0000724
725 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000726 case EHScope::Cleanup:
John McCall777d6e52011-08-11 02:22:43 +0000727 // If we have a cleanup, remember that.
728 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCallda65ea82010-07-13 20:32:21 +0000729 continue;
730
John McCallf1549f62010-07-06 01:34:17 +0000731 case EHScope::Filter: {
732 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall777d6e52011-08-11 02:22:43 +0000733 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000734
Bill Wendling285cfd82011-09-19 20:31:14 +0000735 // Filter scopes get added to the landingpad in weird ways.
John McCall777d6e52011-08-11 02:22:43 +0000736 EHFilterScope &filter = cast<EHFilterScope>(*I);
737 hasFilter = true;
John McCallf1549f62010-07-06 01:34:17 +0000738
Bill Wendling8990daf2011-09-22 20:32:54 +0000739 // Add all the filter values.
740 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
741 filterTypes.push_back(filter.getFilter(i));
John McCallf1549f62010-07-06 01:34:17 +0000742 goto done;
743 }
744
745 case EHScope::Terminate:
746 // Terminate scopes are basically catch-alls.
John McCall777d6e52011-08-11 02:22:43 +0000747 assert(!hasCatchAll);
748 hasCatchAll = true;
John McCallf1549f62010-07-06 01:34:17 +0000749 goto done;
750
751 case EHScope::Catch:
752 break;
753 }
754
John McCall777d6e52011-08-11 02:22:43 +0000755 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
756 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
757 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallf1549f62010-07-06 01:34:17 +0000758
John McCall777d6e52011-08-11 02:22:43 +0000759 // If this is a catch-all, register that and abort.
760 if (!handler.Type) {
761 assert(!hasCatchAll);
762 hasCatchAll = true;
763 goto done;
John McCallf1549f62010-07-06 01:34:17 +0000764 }
765
766 // Check whether we already have a handler for this type.
Stephen Hines176edba2014-12-01 14:53:08 -0800767 if (catchTypes.insert(handler.Type).second)
Bill Wendling285cfd82011-09-19 20:31:14 +0000768 // If not, add it directly to the landingpad.
769 LPadInst->addClause(handler.Type);
John McCallf1549f62010-07-06 01:34:17 +0000770 }
John McCallf1549f62010-07-06 01:34:17 +0000771 }
772
773 done:
Bill Wendling285cfd82011-09-19 20:31:14 +0000774 // If we have a catch-all, add null to the landingpad.
John McCall777d6e52011-08-11 02:22:43 +0000775 assert(!(hasCatchAll && hasFilter));
776 if (hasCatchAll) {
Bill Wendling285cfd82011-09-19 20:31:14 +0000777 LPadInst->addClause(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000778
779 // If we have an EH filter, we need to add those handlers in the
Bill Wendling285cfd82011-09-19 20:31:14 +0000780 // right place in the landingpad, which is to say, at the end.
John McCall777d6e52011-08-11 02:22:43 +0000781 } else if (hasFilter) {
Bill Wendling40ccacc2011-09-19 22:08:36 +0000782 // Create a filter expression: a constant array indicating which filter
783 // types there are. The personality routine only lands here if the filter
784 // doesn't match.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000785 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendling285cfd82011-09-19 20:31:14 +0000786 llvm::ArrayType *AType =
787 llvm::ArrayType::get(!filterTypes.empty() ?
788 filterTypes[0]->getType() : Int8PtrTy,
789 filterTypes.size());
790
791 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
792 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
793 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
794 LPadInst->addClause(FilterArray);
John McCallf1549f62010-07-06 01:34:17 +0000795
796 // Also check whether we need a cleanup.
Bill Wendling285cfd82011-09-19 20:31:14 +0000797 if (hasCleanup)
798 LPadInst->setCleanup(true);
John McCallf1549f62010-07-06 01:34:17 +0000799
800 // Otherwise, signal that we at least have cleanups.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700801 } else if (hasCleanup) {
802 LPadInst->setCleanup(true);
John McCallf1549f62010-07-06 01:34:17 +0000803 }
804
Bill Wendling285cfd82011-09-19 20:31:14 +0000805 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
806 "landingpad instruction has no clauses!");
John McCallf1549f62010-07-06 01:34:17 +0000807
808 // Tell the backend how to generate the landing pad.
John McCall777d6e52011-08-11 02:22:43 +0000809 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallf1549f62010-07-06 01:34:17 +0000810
811 // Restore the old IR generation state.
John McCall777d6e52011-08-11 02:22:43 +0000812 Builder.restoreIP(savedIP);
John McCallf1549f62010-07-06 01:34:17 +0000813
John McCall777d6e52011-08-11 02:22:43 +0000814 return lpad;
John McCallf1549f62010-07-06 01:34:17 +0000815}
816
John McCall777d6e52011-08-11 02:22:43 +0000817/// Emit the structure of the dispatch block for the given catch scope.
818/// It is an invariant that the dispatch block already exists.
819static void emitCatchDispatchBlock(CodeGenFunction &CGF,
820 EHCatchScope &catchScope) {
821 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
822 assert(dispatchBlock);
823
824 // If there's only a single catch-all, getEHDispatchBlock returned
825 // that catch-all as the dispatch block.
826 if (catchScope.getNumHandlers() == 1 &&
827 catchScope.getHandler(0).isCatchAll()) {
828 assert(dispatchBlock == catchScope.getHandler(0).Block);
829 return;
830 }
831
832 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
833 CGF.EmitBlockAfterUses(dispatchBlock);
834
835 // Select the right handler.
836 llvm::Value *llvm_eh_typeid_for =
837 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
838
839 // Load the selector value.
Bill Wendlingae270592011-09-15 18:57:19 +0000840 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall777d6e52011-08-11 02:22:43 +0000841
842 // Test against each of the exception types we claim to catch.
843 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
844 assert(i < e && "ran off end of handlers!");
845 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
846
847 llvm::Value *typeValue = handler.Type;
848 assert(typeValue && "fell into catch-all case!");
849 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
850
851 // Figure out the next block.
852 bool nextIsEnd;
853 llvm::BasicBlock *nextBlock;
854
855 // If this is the last handler, we're at the end, and the next
856 // block is the block for the enclosing EH scope.
857 if (i + 1 == e) {
858 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
859 nextIsEnd = true;
860
861 // If the next handler is a catch-all, we're at the end, and the
862 // next block is that handler.
863 } else if (catchScope.getHandler(i+1).isCatchAll()) {
864 nextBlock = catchScope.getHandler(i+1).Block;
865 nextIsEnd = true;
866
867 // Otherwise, we're not at the end and we need a new block.
868 } else {
869 nextBlock = CGF.createBasicBlock("catch.fallthrough");
870 nextIsEnd = false;
871 }
872
873 // Figure out the catch type's index in the LSDA's type table.
874 llvm::CallInst *typeIndex =
875 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
876 typeIndex->setDoesNotThrow();
877
878 llvm::Value *matchesTypeIndex =
879 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
880 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
881
882 // If the next handler is a catch-all, we're completely done.
883 if (nextIsEnd) {
884 CGF.Builder.restoreIP(savedIP);
885 return;
John McCall777d6e52011-08-11 02:22:43 +0000886 }
Ahmed Charlese8e92b92012-02-19 11:57:29 +0000887 // Otherwise we need to emit and continue at that block.
888 CGF.EmitBlock(nextBlock);
John McCall777d6e52011-08-11 02:22:43 +0000889 }
John McCall777d6e52011-08-11 02:22:43 +0000890}
891
892void CodeGenFunction::popCatchScope() {
893 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
894 if (catchScope.hasEHBranches())
895 emitCatchDispatchBlock(*this, catchScope);
896 EHStack.popCatch();
897}
898
John McCall59a70002010-07-07 06:56:46 +0000899void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000900 unsigned NumHandlers = S.getNumHandlers();
901 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
902 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +0000903
John McCall777d6e52011-08-11 02:22:43 +0000904 // If the catch was not required, bail out now.
905 if (!CatchScope.hasEHBranches()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700906 CatchScope.clearHandlerBlocks();
John McCall777d6e52011-08-11 02:22:43 +0000907 EHStack.popCatch();
908 return;
909 }
910
911 // Emit the structure of the EH dispatch for this catch.
912 emitCatchDispatchBlock(*this, CatchScope);
913
John McCallf1549f62010-07-06 01:34:17 +0000914 // Copy the handler blocks off before we pop the EH stack. Emitting
915 // the handlers might scribble on this memory.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000916 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallf1549f62010-07-06 01:34:17 +0000917 memcpy(Handlers.data(), CatchScope.begin(),
918 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall777d6e52011-08-11 02:22:43 +0000919
John McCallf1549f62010-07-06 01:34:17 +0000920 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +0000921
John McCallf1549f62010-07-06 01:34:17 +0000922 // The fall-through block.
923 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +0000924
John McCallf1549f62010-07-06 01:34:17 +0000925 // We just emitted the body of the try; jump to the continue block.
926 if (HaveInsertPoint())
927 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +0000928
John McCallf5533012012-06-15 05:27:05 +0000929 // Determine if we need an implicit rethrow for all these catch handlers;
930 // see the comment below.
931 bool doImplicitRethrow = false;
John McCall59a70002010-07-07 06:56:46 +0000932 if (IsFnTryBlock)
John McCallf5533012012-06-15 05:27:05 +0000933 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
934 isa<CXXConstructorDecl>(CurCodeDecl);
John McCall59a70002010-07-07 06:56:46 +0000935
John McCall777d6e52011-08-11 02:22:43 +0000936 // Perversely, we emit the handlers backwards precisely because we
937 // want them to appear in source order. In all of these cases, the
938 // catch block will have exactly one predecessor, which will be a
939 // particular block in the catch dispatch. However, in the case of
940 // a catch-all, one of the dispatch blocks will branch to two
941 // different handlers, and EmitBlockAfterUses will cause the second
942 // handler to be moved before the first.
943 for (unsigned I = NumHandlers; I != 0; --I) {
944 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
945 EmitBlockAfterUses(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +0000946
John McCallf1549f62010-07-06 01:34:17 +0000947 // Catch the exception if this isn't a catch-all.
John McCall777d6e52011-08-11 02:22:43 +0000948 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump2bf701e2009-11-20 23:44:51 +0000949
John McCallf1549f62010-07-06 01:34:17 +0000950 // Enter a cleanup scope, including the catch variable and the
951 // end-catch.
952 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +0000953
John McCallf1549f62010-07-06 01:34:17 +0000954 // Initialize the catch variable and set up the cleanups.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700955 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallf1549f62010-07-06 01:34:17 +0000956
Stephen Hines651f13c2014-04-23 16:59:28 -0700957 // Emit the PGO counter increment.
958 RegionCounter CatchCnt = getPGORegionCounter(C);
959 CatchCnt.beginRegion(Builder);
960
John McCallf1549f62010-07-06 01:34:17 +0000961 // Perform the body of the catch.
962 EmitStmt(C->getHandlerBlock());
963
John McCallf5533012012-06-15 05:27:05 +0000964 // [except.handle]p11:
965 // The currently handled exception is rethrown if control
966 // reaches the end of a handler of the function-try-block of a
967 // constructor or destructor.
968
969 // It is important that we only do this on fallthrough and not on
970 // return. Note that it's illegal to put a return in a
971 // constructor function-try-block's catch handler (p14), so this
972 // really only applies to destructors.
973 if (doImplicitRethrow && HaveInsertPoint()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700974 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCallf5533012012-06-15 05:27:05 +0000975 Builder.CreateUnreachable();
976 Builder.ClearInsertionPoint();
977 }
978
John McCallf1549f62010-07-06 01:34:17 +0000979 // Fall out through the catch cleanups.
980 CatchScope.ForceCleanup();
981
982 // Branch out of the try.
983 if (HaveInsertPoint())
984 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +0000985 }
986
Stephen Hines651f13c2014-04-23 16:59:28 -0700987 RegionCounter ContCnt = getPGORegionCounter(&S);
John McCallf1549f62010-07-06 01:34:17 +0000988 EmitBlock(ContBB);
Stephen Hines651f13c2014-04-23 16:59:28 -0700989 ContCnt.beginRegion(Builder);
Mike Stump2bf701e2009-11-20 23:44:51 +0000990}
Mike Stumpd88ea562009-12-09 03:35:49 +0000991
John McCall55b20fc2010-07-21 00:52:03 +0000992namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000993 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +0000994 llvm::Value *ForEHVar;
995 llvm::Value *EndCatchFn;
996 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
997 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
998
Stephen Hines651f13c2014-04-23 16:59:28 -0700999 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall55b20fc2010-07-21 00:52:03 +00001000 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1001 llvm::BasicBlock *CleanupContBB =
1002 CGF.createBasicBlock("finally.cleanup.cont");
1003
1004 llvm::Value *ShouldEndCatch =
1005 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1006 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1007 CGF.EmitBlock(EndCatchBB);
John McCallbd7370a2013-02-28 19:01:20 +00001008 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall55b20fc2010-07-21 00:52:03 +00001009 CGF.EmitBlock(CleanupContBB);
1010 }
1011 };
John McCall77199712010-07-21 05:47:49 +00001012
John McCall1f0fca52010-07-21 07:22:38 +00001013 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001014 const Stmt *Body;
1015 llvm::Value *ForEHVar;
1016 llvm::Value *EndCatchFn;
1017 llvm::Value *RethrowFn;
1018 llvm::Value *SavedExnVar;
1019
1020 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1021 llvm::Value *EndCatchFn,
1022 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1023 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1024 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1025
Stephen Hines651f13c2014-04-23 16:59:28 -07001026 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall77199712010-07-21 05:47:49 +00001027 // Enter a cleanup to call the end-catch function if one was provided.
1028 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001029 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1030 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001031
John McCalld96a8e72010-08-11 00:16:14 +00001032 // Save the current cleanup destination in case there are
1033 // cleanups in the finally block.
1034 llvm::Value *SavedCleanupDest =
1035 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1036 "cleanup.dest.saved");
1037
John McCall77199712010-07-21 05:47:49 +00001038 // Emit the finally block.
1039 CGF.EmitStmt(Body);
1040
1041 // If the end of the finally is reachable, check whether this was
1042 // for EH. If so, rethrow.
1043 if (CGF.HaveInsertPoint()) {
1044 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1045 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1046
1047 llvm::Value *ShouldRethrow =
1048 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1049 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1050
1051 CGF.EmitBlock(RethrowBB);
1052 if (SavedExnVar) {
John McCallbd7370a2013-02-28 19:01:20 +00001053 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1054 CGF.Builder.CreateLoad(SavedExnVar));
John McCall77199712010-07-21 05:47:49 +00001055 } else {
John McCallbd7370a2013-02-28 19:01:20 +00001056 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall77199712010-07-21 05:47:49 +00001057 }
1058 CGF.Builder.CreateUnreachable();
1059
1060 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001061
1062 // Restore the cleanup destination.
1063 CGF.Builder.CreateStore(SavedCleanupDest,
1064 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001065 }
1066
1067 // Leave the end-catch cleanup. As an optimization, pretend that
1068 // the fallthrough path was inaccessible; we've dynamically proven
1069 // that we're not in the EH case along that path.
1070 if (EndCatchFn) {
1071 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1072 CGF.PopCleanupBlock();
1073 CGF.Builder.restoreIP(SavedIP);
1074 }
1075
1076 // Now make sure we actually have an insertion point or the
1077 // cleanup gods will hate us.
1078 CGF.EnsureInsertPoint();
1079 }
1080 };
John McCall55b20fc2010-07-21 00:52:03 +00001081}
1082
John McCallf1549f62010-07-06 01:34:17 +00001083/// Enters a finally block for an implementation using zero-cost
1084/// exceptions. This is mostly general, but hard-codes some
1085/// language/ABI-specific behavior in the catch-all sections.
John McCalld768e9d2011-06-22 02:32:12 +00001086void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1087 const Stmt *body,
1088 llvm::Constant *beginCatchFn,
1089 llvm::Constant *endCatchFn,
1090 llvm::Constant *rethrowFn) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001091 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallf1549f62010-07-06 01:34:17 +00001092 "begin/end catch functions not paired");
John McCalld768e9d2011-06-22 02:32:12 +00001093 assert(rethrowFn && "rethrow function is required");
1094
1095 BeginCatchFn = beginCatchFn;
Mike Stumpd88ea562009-12-09 03:35:49 +00001096
John McCallf1549f62010-07-06 01:34:17 +00001097 // The rethrow function has one of the following two types:
1098 // void (*)()
1099 // void (*)(void*)
1100 // In the latter case we need to pass it the exception object.
1101 // But we can't use the exception slot because the @finally might
1102 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2acc6e32011-07-18 04:24:23 +00001103 llvm::FunctionType *rethrowFnTy =
John McCallf1549f62010-07-06 01:34:17 +00001104 cast<llvm::FunctionType>(
John McCalld768e9d2011-06-22 02:32:12 +00001105 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001106 SavedExnVar = nullptr;
John McCalld768e9d2011-06-22 02:32:12 +00001107 if (rethrowFnTy->getNumParams())
1108 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001109
John McCallf1549f62010-07-06 01:34:17 +00001110 // A finally block is a statement which must be executed on any edge
1111 // out of a given scope. Unlike a cleanup, the finally block may
1112 // contain arbitrary control flow leading out of itself. In
1113 // addition, finally blocks should always be executed, even if there
1114 // are no catch handlers higher on the stack. Therefore, we
1115 // surround the protected scope with a combination of a normal
1116 // cleanup (to catch attempts to break out of the block via normal
1117 // control flow) and an EH catch-all (semantically "outside" any try
1118 // statement to which the finally block might have been attached).
1119 // The finally block itself is generated in the context of a cleanup
1120 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001121
John McCallf1549f62010-07-06 01:34:17 +00001122 // Jump destination for performing the finally block on an exception
1123 // edge. We'll never actually reach this block, so unreachable is
1124 // fine.
John McCalld768e9d2011-06-22 02:32:12 +00001125 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001126
John McCallf1549f62010-07-06 01:34:17 +00001127 // Whether the finally block is being executed for EH purposes.
John McCalld768e9d2011-06-22 02:32:12 +00001128 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1129 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpd88ea562009-12-09 03:35:49 +00001130
John McCallf1549f62010-07-06 01:34:17 +00001131 // Enter a normal cleanup which will perform the @finally block.
John McCalld768e9d2011-06-22 02:32:12 +00001132 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1133 ForEHVar, endCatchFn,
1134 rethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001135
1136 // Enter a catch-all scope.
John McCalld768e9d2011-06-22 02:32:12 +00001137 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1138 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1139 catchScope->setCatchAllHandler(0, catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001140}
1141
John McCalld768e9d2011-06-22 02:32:12 +00001142void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +00001143 // Leave the finally catch-all.
John McCalld768e9d2011-06-22 02:32:12 +00001144 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1145 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall777d6e52011-08-11 02:22:43 +00001146
1147 CGF.popCatchScope();
John McCallf1549f62010-07-06 01:34:17 +00001148
John McCalld768e9d2011-06-22 02:32:12 +00001149 // If there are any references to the catch-all block, emit it.
1150 if (catchBB->use_empty()) {
1151 delete catchBB;
1152 } else {
1153 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1154 CGF.EmitBlock(catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001155
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001156 llvm::Value *exn = nullptr;
John McCallf1549f62010-07-06 01:34:17 +00001157
John McCalld768e9d2011-06-22 02:32:12 +00001158 // If there's a begin-catch function, call it.
1159 if (BeginCatchFn) {
Bill Wendlingae270592011-09-15 18:57:19 +00001160 exn = CGF.getExceptionFromSlot();
John McCallbd7370a2013-02-28 19:01:20 +00001161 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCalld768e9d2011-06-22 02:32:12 +00001162 }
1163
1164 // If we need to remember the exception pointer to rethrow later, do so.
1165 if (SavedExnVar) {
Bill Wendlingae270592011-09-15 18:57:19 +00001166 if (!exn) exn = CGF.getExceptionFromSlot();
John McCalld768e9d2011-06-22 02:32:12 +00001167 CGF.Builder.CreateStore(exn, SavedExnVar);
1168 }
1169
1170 // Tell the cleanups in the finally block that we're do this for EH.
1171 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1172
1173 // Thread a jump through the finally cleanup.
1174 CGF.EmitBranchThroughCleanup(RethrowDest);
1175
1176 CGF.Builder.restoreIP(savedIP);
1177 }
1178
1179 // Finally, leave the @finally cleanup.
1180 CGF.PopCleanupBlock();
John McCallf1549f62010-07-06 01:34:17 +00001181}
1182
1183llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1184 if (TerminateLandingPad)
1185 return TerminateLandingPad;
1186
1187 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1188
1189 // This will get inserted at the end of the function.
1190 TerminateLandingPad = createBasicBlock("terminate.lpad");
1191 Builder.SetInsertPoint(TerminateLandingPad);
1192
1193 // Tell the backend that this is a landing pad.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001194 const EHPersonality &Personality = EHPersonality::get(*this);
Bill Wendling285cfd82011-09-19 20:31:14 +00001195 llvm::LandingPadInst *LPadInst =
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001196 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendling285cfd82011-09-19 20:31:14 +00001197 getOpaquePersonalityFn(CGM, Personality), 0);
1198 LPadInst->addClause(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +00001199
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001200 llvm::Value *Exn = 0;
1201 if (getLangOpts().CPlusPlus)
1202 Exn = Builder.CreateExtractValue(LPadInst, 0);
1203 llvm::CallInst *terminateCall =
1204 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCall66b22772013-02-12 03:51:46 +00001205 terminateCall->setDoesNotReturn();
John McCalld16c2cf2011-02-08 08:22:06 +00001206 Builder.CreateUnreachable();
Mike Stumpd88ea562009-12-09 03:35:49 +00001207
John McCallf1549f62010-07-06 01:34:17 +00001208 // Restore the saved insertion state.
1209 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001210
John McCallf1549f62010-07-06 01:34:17 +00001211 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001212}
Mike Stump9b39c512009-12-09 22:59:31 +00001213
1214llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001215 if (TerminateHandler)
1216 return TerminateHandler;
1217
John McCallf1549f62010-07-06 01:34:17 +00001218 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001219
John McCallf1549f62010-07-06 01:34:17 +00001220 // Set up the terminate handler. This block is inserted at the very
1221 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001222 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001223 Builder.SetInsertPoint(TerminateHandler);
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001224 llvm::Value *Exn = 0;
1225 if (getLangOpts().CPlusPlus)
1226 Exn = getExceptionFromSlot();
1227 llvm::CallInst *terminateCall =
1228 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCall45ff3802013-06-20 21:37:43 +00001229 terminateCall->setDoesNotReturn();
Mike Stump9b39c512009-12-09 22:59:31 +00001230 Builder.CreateUnreachable();
1231
John McCall3d3ec1c2010-04-21 10:05:39 +00001232 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001233 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001234
Mike Stump9b39c512009-12-09 22:59:31 +00001235 return TerminateHandler;
1236}
John McCallf1549f62010-07-06 01:34:17 +00001237
David Chisnallc6860042012-11-07 16:50:40 +00001238llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall777d6e52011-08-11 02:22:43 +00001239 if (EHResumeBlock) return EHResumeBlock;
John McCallff8e1152010-07-23 21:56:41 +00001240
1241 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1242
1243 // We emit a jump to a notional label at the outermost unwind state.
John McCall777d6e52011-08-11 02:22:43 +00001244 EHResumeBlock = createBasicBlock("eh.resume");
1245 Builder.SetInsertPoint(EHResumeBlock);
John McCallff8e1152010-07-23 21:56:41 +00001246
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001247 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallff8e1152010-07-23 21:56:41 +00001248
1249 // This can always be a call because we necessarily didn't find
1250 // anything on the EH stack which needs our help.
Benjamin Krameraf2771b2012-02-08 12:41:24 +00001251 const char *RethrowName = Personality.CatchallRethrowFn;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001252 if (RethrowName != nullptr && !isCleanup) {
John McCallbd7370a2013-02-28 19:01:20 +00001253 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001254 getExceptionFromSlot())->setDoesNotReturn();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001255 Builder.CreateUnreachable();
1256 Builder.restoreIP(SavedIP);
1257 return EHResumeBlock;
John McCall93c332a2011-05-28 21:13:02 +00001258 }
1259
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001260 // Recreate the landingpad's return value for the 'resume' instruction.
1261 llvm::Value *Exn = getExceptionFromSlot();
1262 llvm::Value *Sel = getSelectorFromSlot();
John McCallff8e1152010-07-23 21:56:41 +00001263
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001264 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001265 Sel->getType(), nullptr);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001266 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1267 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1268 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1269
1270 Builder.CreateResume(LPadVal);
John McCallff8e1152010-07-23 21:56:41 +00001271 Builder.restoreIP(SavedIP);
John McCall777d6e52011-08-11 02:22:43 +00001272 return EHResumeBlock;
John McCallff8e1152010-07-23 21:56:41 +00001273}
Reid Kleckner98592d92013-09-16 21:46:30 +00001274
1275void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001276 // FIXME: Implement SEH on other architectures.
1277 const llvm::Triple &T = CGM.getTarget().getTriple();
1278 if (T.getArch() != llvm::Triple::x86_64 ||
1279 !T.isKnownWindowsMSVCEnvironment()) {
1280 ErrorUnsupported(&S, "__try statement");
1281 return;
1282 }
1283
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001284 EnterSEHTryStmt(S);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001285 {
1286 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1287
1288 SEHTryEpilogueStack.push_back(&TryExit);
1289 EmitStmt(S.getTryBlock());
1290 SEHTryEpilogueStack.pop_back();
1291
1292 if (!TryExit.getBlock()->use_empty())
1293 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1294 else
1295 delete TryExit.getBlock();
1296 }
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001297 ExitSEHTryStmt(S);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001298}
1299
1300namespace {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001301struct PerformSEHFinally : EHScopeStack::Cleanup {
1302 llvm::Function *OutlinedFinally;
1303 PerformSEHFinally(llvm::Function *OutlinedFinally)
1304 : OutlinedFinally(OutlinedFinally) {}
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001305
1306 void Emit(CodeGenFunction &CGF, Flags F) override {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001307 ASTContext &Context = CGF.getContext();
1308 QualType ArgTys[2] = {Context.BoolTy, Context.VoidPtrTy};
1309 FunctionProtoType::ExtProtoInfo EPI;
1310 const auto *FTP = cast<FunctionType>(
1311 Context.getFunctionType(Context.VoidTy, ArgTys, EPI));
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001312
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001313 CallArgList Args;
1314 llvm::Value *IsForEH =
1315 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1316 Args.add(RValue::get(IsForEH), ArgTys[0]);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001317
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001318 CodeGenModule &CGM = CGF.CGM;
1319 llvm::Value *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0);
1320 llvm::Value *FrameAddr = CGM.getIntrinsic(llvm::Intrinsic::frameaddress);
1321 llvm::Value *FP = CGF.Builder.CreateCall(FrameAddr, Zero);
1322 Args.add(RValue::get(FP), ArgTys[1]);
1323
1324 const CGFunctionInfo &FnInfo =
1325 CGM.getTypes().arrangeFreeFunctionCall(Args, FTP, /*chainCall=*/false);
1326 CGF.EmitCall(FnInfo, OutlinedFinally, ReturnValueSlot(), Args);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001327 }
1328};
1329}
1330
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001331namespace {
1332/// Find all local variable captures in the statement.
1333struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1334 CodeGenFunction &ParentCGF;
1335 const VarDecl *ParentThis;
1336 SmallVector<const VarDecl *, 4> Captures;
1337 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1338 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1339
1340 void Visit(const Stmt *S) {
1341 // See if this is a capture, then recurse.
1342 ConstStmtVisitor<CaptureFinder>::Visit(S);
1343 for (const Stmt *Child : S->children())
1344 if (Child)
1345 Visit(Child);
1346 }
1347
1348 void VisitDeclRefExpr(const DeclRefExpr *E) {
1349 // If this is already a capture, just make sure we capture 'this'.
1350 if (E->refersToEnclosingVariableOrCapture()) {
1351 Captures.push_back(ParentThis);
1352 return;
1353 }
1354
1355 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1356 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1357 Captures.push_back(D);
1358 }
1359
1360 void VisitCXXThisExpr(const CXXThisExpr *E) {
1361 Captures.push_back(ParentThis);
1362 }
1363};
1364}
1365
1366void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
1367 const Stmt *OutlinedStmt,
1368 llvm::Value *ParentFP) {
1369 // Find all captures in the Stmt.
1370 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1371 Finder.Visit(OutlinedStmt);
1372
1373 // Typically there are no captures and we can exit early.
1374 if (Finder.Captures.empty())
1375 return;
1376
1377 // Prepare the first two arguments to llvm.framerecover.
1378 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1379 &CGM.getModule(), llvm::Intrinsic::framerecover);
1380 llvm::Constant *ParentI8Fn =
1381 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1382
1383 // Create llvm.framerecover calls for all captures.
1384 for (const VarDecl *VD : Finder.Captures) {
1385 if (isa<ImplicitParamDecl>(VD)) {
1386 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1387 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1388 continue;
1389 }
1390 if (VD->getType()->isVariablyModifiedType()) {
1391 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1392 continue;
1393 }
1394 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1395 "captured non-local variable");
1396
1397 // If this decl hasn't been declared yet, it will be declared in the
1398 // OutlinedStmt.
1399 auto I = ParentCGF.LocalDeclMap.find(VD);
1400 if (I == ParentCGF.LocalDeclMap.end())
1401 continue;
1402 llvm::Value *ParentVar = I->second;
1403
1404 llvm::CallInst *RecoverCall = nullptr;
1405 CGBuilderTy Builder(AllocaInsertPt);
1406 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar)) {
1407 // Mark the variable escaped if nobody else referenced it and compute the
1408 // frameescape index.
1409 auto InsertPair =
1410 ParentCGF.EscapedLocals.insert(std::make_pair(ParentAlloca, -1));
1411 if (InsertPair.second)
1412 InsertPair.first->second = ParentCGF.EscapedLocals.size() - 1;
1413 int FrameEscapeIdx = InsertPair.first->second;
1414 // call i8* @llvm.framerecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
1415 RecoverCall =
1416 Builder.CreateCall3(FrameRecoverFn, ParentI8Fn, ParentFP,
1417 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx));
1418
1419 } else {
1420 // If the parent didn't have an alloca, we're doing some nested outlining.
1421 // Just clone the existing framerecover call, but tweak the FP argument to
1422 // use our FP value. All other arguments are constants.
1423 auto *ParentRecover =
1424 cast<llvm::IntrinsicInst>(ParentVar->stripPointerCasts());
1425 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::framerecover &&
1426 "expected alloca or framerecover in parent LocalDeclMap");
1427 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1428 RecoverCall->setArgOperand(1, ParentFP);
1429 RecoverCall->insertBefore(AllocaInsertPt);
1430 }
1431
1432 // Bitcast the variable, rename it, and insert it in the local decl map.
1433 llvm::Value *ChildVar =
1434 Builder.CreateBitCast(RecoverCall, ParentVar->getType());
1435 ChildVar->setName(ParentVar->getName());
1436 LocalDeclMap[VD] = ChildVar;
1437 }
1438}
1439
1440/// Arrange a function prototype that can be called by Windows exception
1441/// handling personalities. On Win64, the prototype looks like:
1442/// RetTy func(void *EHPtrs, void *ParentFP);
1443void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
1444 StringRef Name, QualType RetTy,
1445 FunctionArgList &Args,
1446 const Stmt *OutlinedStmt) {
1447 llvm::Function *ParentFn = ParentCGF.CurFn;
1448 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1449 RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
1450
1451 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1452 llvm::Function *Fn = llvm::Function::Create(
1453 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
1454 // The filter is either in the same comdat as the function, or it's internal.
1455 if (llvm::Comdat *C = ParentFn->getComdat()) {
1456 Fn->setComdat(C);
1457 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
1458 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1459 ParentFn->setComdat(C);
1460 Fn->setComdat(C);
1461 } else {
1462 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1463 }
1464
1465 IsOutlinedSEHHelper = true;
1466
1467 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1468 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
1469
1470 CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
1471
1472 auto AI = Fn->arg_begin();
1473 ++AI;
1474 EmitCapturedLocals(ParentCGF, OutlinedStmt, &*AI);
1475}
1476
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001477/// Create a stub filter function that will ultimately hold the code of the
1478/// filter expression. The EH preparation passes in LLVM will outline the code
1479/// from the main function body into this stub.
1480llvm::Function *
1481CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1482 const SEHExceptStmt &Except) {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001483 const Expr *FilterExpr = Except.getFilterExpr();
1484 SourceLocation StartLoc = FilterExpr->getLocStart();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001485
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001486 SEHPointersDecl = ImplicitParamDecl::Create(
1487 getContext(), nullptr, StartLoc,
1488 &getContext().Idents.get("exception_pointers"), getContext().VoidPtrTy);
1489 FunctionArgList Args;
1490 Args.push_back(SEHPointersDecl);
1491 Args.push_back(ImplicitParamDecl::Create(
1492 getContext(), nullptr, StartLoc,
1493 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001494
1495 // Get the mangled function name.
1496 SmallString<128> Name;
1497 {
1498 llvm::raw_svector_ostream OS(Name);
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001499 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001500 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1501 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1502 CGM.getCXXABI().getMangleContext().mangleSEHFilterExpression(Parent, OS);
1503 }
1504
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001505 startOutlinedSEHHelper(ParentCGF, Name, getContext().IntTy, Args, FilterExpr);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001506
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001507 // Mark finally block calls as nounwind and noinline to make LLVM's job a
1508 // little easier.
1509 // FIXME: Remove these restrictions in the future.
1510 CurFn->addFnAttr(llvm::Attribute::NoUnwind);
1511 CurFn->addFnAttr(llvm::Attribute::NoInline);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001512
1513 EmitSEHExceptionCodeSave();
1514
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001515 // Emit the original filter expression, convert to i32, and return.
1516 llvm::Value *R = EmitScalarExpr(FilterExpr);
1517 R = Builder.CreateIntCast(R, CGM.IntTy,
1518 FilterExpr->getType()->isSignedIntegerType());
1519 Builder.CreateStore(R, ReturnValue);
1520
1521 FinishFunction(FilterExpr->getLocEnd());
1522
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001523 return CurFn;
1524}
1525
1526llvm::Function *
1527CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1528 const SEHFinallyStmt &Finally) {
1529 const Stmt *FinallyBlock = Finally.getBlock();
1530 SourceLocation StartLoc = FinallyBlock->getLocStart();
1531
1532 FunctionArgList Args;
1533 Args.push_back(ImplicitParamDecl::Create(
1534 getContext(), nullptr, StartLoc,
1535 &getContext().Idents.get("abnormal_termination"), getContext().BoolTy));
1536 Args.push_back(ImplicitParamDecl::Create(
1537 getContext(), nullptr, StartLoc,
1538 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1539
1540 // Get the mangled function name.
1541 SmallString<128> Name;
1542 {
1543 llvm::raw_svector_ostream OS(Name);
1544 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1545 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1546 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1547 CGM.getCXXABI().getMangleContext().mangleSEHFinallyBlock(Parent, OS);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001548 }
1549
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001550 startOutlinedSEHHelper(ParentCGF, Name, getContext().VoidTy, Args,
1551 FinallyBlock);
1552
1553 // Emit the original filter expression, convert to i32, and return.
1554 EmitStmt(FinallyBlock);
1555
1556 FinishFunction(FinallyBlock->getLocEnd());
1557
1558 return CurFn;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001559}
1560
1561void CodeGenFunction::EmitSEHExceptionCodeSave() {
1562 // Save the exception code in the exception slot to unify exception access in
1563 // the filter function and the landing pad.
1564 // struct EXCEPTION_POINTERS {
1565 // EXCEPTION_RECORD *ExceptionRecord;
1566 // CONTEXT *ContextRecord;
1567 // };
1568 // void *exn.slot =
1569 // (void *)(uintptr_t)exception_pointers->ExceptionRecord->ExceptionCode;
1570 llvm::Value *Ptrs = Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1571 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1572 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
1573 Ptrs = Builder.CreateBitCast(Ptrs, PtrsTy->getPointerTo());
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001574 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001575 Rec = Builder.CreateLoad(Rec);
1576 llvm::Value *Code = Builder.CreateLoad(Rec);
1577 Code = Builder.CreateZExt(Code, CGM.IntPtrTy);
1578 // FIXME: Change landing pads to produce {i32, i32} and make the exception
1579 // slot an i32.
1580 Code = Builder.CreateIntToPtr(Code, CGM.VoidPtrTy);
1581 Builder.CreateStore(Code, getExceptionSlot());
1582}
1583
1584llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1585 // Sema should diagnose calling this builtin outside of a filter context, but
1586 // don't crash if we screw up.
1587 if (!SEHPointersDecl)
1588 return llvm::UndefValue::get(Int8PtrTy);
1589 return Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1590}
1591
1592llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
1593 // If we're in a landing pad or filter function, the exception slot contains
1594 // the code.
1595 assert(ExceptionSlot);
1596 llvm::Value *Code =
1597 Builder.CreatePtrToInt(getExceptionFromSlot(), CGM.IntPtrTy);
1598 return Builder.CreateTrunc(Code, CGM.Int32Ty);
1599}
1600
1601llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001602 // Abnormal termination is just the first parameter to the outlined finally
1603 // helper.
1604 auto AI = CurFn->arg_begin();
1605 return Builder.CreateZExt(&*AI, Int32Ty);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001606}
1607
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001608void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1609 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1610 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001611 // Push a cleanup for __finally blocks.
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001612 llvm::Function *FinallyFunc =
1613 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
1614 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001615 return;
1616 }
1617
1618 // Otherwise, we must have an __except block.
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001619 const SEHExceptStmt *Except = S.getExceptHandler();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001620 assert(Except);
1621 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1622
1623 // If the filter is known to evaluate to 1, then we can use the clause "catch
1624 // i8* null".
1625 llvm::Constant *C =
1626 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1627 if (C && C->isOneValue()) {
1628 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1629 return;
1630 }
1631
1632 // In general, we have to emit an outlined filter function. Use the function
1633 // in place of the RTTI typeinfo global that C++ EH uses.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001634 llvm::Function *FilterFunc =
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001635 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001636 llvm::Constant *OpaqueFunc =
1637 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1638 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except"));
1639}
1640
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001641void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001642 // Just pop the cleanup if it's a __finally block.
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001643 if (S.getFinallyHandler()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001644 PopCleanupBlock();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001645 return;
1646 }
1647
1648 // Otherwise, we must have an __except block.
1649 const SEHExceptStmt *Except = S.getExceptHandler();
1650 assert(Except && "__try must have __finally xor __except");
1651 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1652
1653 // Don't emit the __except block if the __try block lacked invokes.
1654 // TODO: Model unwind edges from instructions, either with iload / istore or
1655 // a try body function.
1656 if (!CatchScope.hasEHBranches()) {
1657 CatchScope.clearHandlerBlocks();
1658 EHStack.popCatch();
1659 return;
1660 }
1661
1662 // The fall-through block.
1663 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1664
1665 // We just emitted the body of the __try; jump to the continue block.
1666 if (HaveInsertPoint())
1667 Builder.CreateBr(ContBB);
1668
1669 // Check if our filter function returned true.
1670 emitCatchDispatchBlock(*this, CatchScope);
1671
1672 // Grab the block before we pop the handler.
1673 llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1674 EHStack.popCatch();
1675
1676 EmitBlockAfterUses(ExceptBB);
1677
1678 // Emit the __except body.
1679 EmitStmt(Except->getBlock());
1680
1681 if (HaveInsertPoint())
1682 Builder.CreateBr(ContBB);
1683
1684 EmitBlock(ContBB);
Reid Kleckner98592d92013-09-16 21:46:30 +00001685}
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001686
1687void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001688 // If this code is reachable then emit a stop point (if generating
1689 // debug info). We have to do this ourselves because we are on the
1690 // "simple" statement path.
1691 if (HaveInsertPoint())
1692 EmitStopPoint(&S);
1693
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001694 // This must be a __leave from a __finally block, which we warn on and is UB.
1695 // Just emit unreachable.
1696 if (!isSEHTryScope()) {
1697 Builder.CreateUnreachable();
1698 Builder.ClearInsertionPoint();
1699 return;
1700 }
1701
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001702 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001703}