blob: e8ad6da2f98079f4b82b69be6c66a01dcae04895 [file] [log] [blame]
Anders Carlsson4b08db72009-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
Mike Stump58ef18b2009-11-20 23:44:51 +000014#include "clang/AST/StmtCXX.h"
15
16#include "llvm/Intrinsics.h"
John McCall0bdb1fd2010-09-16 06:16:50 +000017#include "llvm/IntrinsicInst.h"
John McCallbd309292010-07-06 01:34:17 +000018#include "llvm/Support/CallSite.h"
Mike Stump58ef18b2009-11-20 23:44:51 +000019
John McCall2ca705e2010-07-24 00:37:23 +000020#include "CGObjCRuntime.h"
Anders Carlsson4b08db72009-10-30 01:42:31 +000021#include "CodeGenFunction.h"
John McCallbd309292010-07-06 01:34:17 +000022#include "CGException.h"
John McCalled1ae862011-01-28 11:13:47 +000023#include "CGCleanup.h"
John McCall5add20c2010-07-20 22:17:55 +000024#include "TargetInfo.h"
John McCallbd309292010-07-06 01:34:17 +000025
Anders Carlsson4b08db72009-10-30 01:42:31 +000026using namespace clang;
27using namespace CodeGen;
28
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000029static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
30 // void *__cxa_allocate_exception(size_t thrown_size);
Mike Stump75546b82009-12-10 00:06:18 +000031
Anders Carlsson566ae672011-04-18 14:24:10 +000032 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
Mike Stump75546b82009-12-10 00:06:18 +000033 const llvm::FunctionType *FTy =
Anders Carlsson566ae672011-04-18 14:24:10 +000034 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
35 SizeTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000036
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000037 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
38}
39
Mike Stump33270212009-12-02 07:41:41 +000040static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
41 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000042
Anders Carlsson566ae672011-04-18 14:24:10 +000043 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Mike Stump75546b82009-12-10 00:06:18 +000044 const llvm::FunctionType *FTy =
Anders Carlsson566ae672011-04-18 14:24:10 +000045 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
46 Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000047
Mike Stump33270212009-12-02 07:41:41 +000048 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
49}
50
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000051static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump75546b82009-12-10 00:06:18 +000052 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump33270212009-12-02 07:41:41 +000053 // void (*dest) (void *));
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000054
55 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Anders Carlsson566ae672011-04-18 14:24:10 +000056 const llvm::Type *Args[3] = { Int8PtrTy, Int8PtrTy, Int8PtrTy };
Mike Stump75546b82009-12-10 00:06:18 +000057 const llvm::FunctionType *FTy =
Mike Stumpd1782cc2009-11-20 00:56:31 +000058 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
Anders Carlsson566ae672011-04-18 14:24:10 +000059 Args, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000060
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000061 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
62}
63
Mike Stumpd1782cc2009-11-20 00:56:31 +000064static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump33270212009-12-02 07:41:41 +000065 // void __cxa_rethrow();
Mike Stumpd1782cc2009-11-20 00:56:31 +000066
Mike Stump75546b82009-12-10 00:06:18 +000067 const llvm::FunctionType *FTy =
Anders Carlsson566ae672011-04-18 14:24:10 +000068 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
69 /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000070
Mike Stumpd1782cc2009-11-20 00:56:31 +000071 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
72}
73
John McCallbd309292010-07-06 01:34:17 +000074static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
75 // void *__cxa_get_exception_ptr(void*);
John McCallbd309292010-07-06 01:34:17 +000076
Anders Carlsson566ae672011-04-18 14:24:10 +000077 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
John McCallbd309292010-07-06 01:34:17 +000078 const llvm::FunctionType *FTy =
Anders Carlsson566ae672011-04-18 14:24:10 +000079 llvm::FunctionType::get(Int8PtrTy, Int8PtrTy, /*IsVarArgs=*/false);
John McCallbd309292010-07-06 01:34:17 +000080
81 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
82}
83
Mike Stump58ef18b2009-11-20 23:44:51 +000084static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +000085 // void *__cxa_begin_catch(void*);
Mike Stump58ef18b2009-11-20 23:44:51 +000086
87 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Mike Stump75546b82009-12-10 00:06:18 +000088 const llvm::FunctionType *FTy =
Anders Carlsson566ae672011-04-18 14:24:10 +000089 llvm::FunctionType::get(Int8PtrTy, Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000090
Mike Stump58ef18b2009-11-20 23:44:51 +000091 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
92}
93
94static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump33270212009-12-02 07:41:41 +000095 // void __cxa_end_catch();
Mike Stump58ef18b2009-11-20 23:44:51 +000096
Mike Stump75546b82009-12-10 00:06:18 +000097 const llvm::FunctionType *FTy =
Anders Carlsson566ae672011-04-18 14:24:10 +000098 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
99 /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +0000100
Mike Stump58ef18b2009-11-20 23:44:51 +0000101 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
102}
103
Mike Stump1d849212009-12-07 23:38:24 +0000104static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
105 // void __cxa_call_unexepcted(void *thrown_exception);
106
107 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Mike Stump75546b82009-12-10 00:06:18 +0000108 const llvm::FunctionType *FTy =
Mike Stump1d849212009-12-07 23:38:24 +0000109 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
Anders Carlsson566ae672011-04-18 14:24:10 +0000110 Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +0000111
Mike Stump1d849212009-12-07 23:38:24 +0000112 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
113}
114
John McCall9b382dd2011-05-28 21:13:02 +0000115llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
John McCall63fb3332011-05-27 20:01:14 +0000116 const llvm::FunctionType *FTy =
John McCall9b382dd2011-05-28 21:13:02 +0000117 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
118
119 if (CGM.getLangOptions().SjLjExceptions)
120 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
121 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
122}
123
124llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
125 const llvm::FunctionType *FTy =
126 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +0000127
Douglas Gregor51150ab2010-05-16 01:24:12 +0000128 if (CGM.getLangOptions().SjLjExceptions)
John McCallffe46302010-08-11 20:59:53 +0000129 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor51150ab2010-05-16 01:24:12 +0000130 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump54066142009-12-01 03:41:18 +0000131}
132
Mike Stump33270212009-12-02 07:41:41 +0000133static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
134 // void __terminate();
135
Mike Stump75546b82009-12-10 00:06:18 +0000136 const llvm::FunctionType *FTy =
Anders Carlsson566ae672011-04-18 14:24:10 +0000137 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
138 /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +0000139
David Chisnallf9c42252010-05-17 13:49:20 +0000140 return CGF.CGM.CreateRuntimeFunction(FTy,
141 CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
142}
143
John McCall36ea3722010-07-17 00:43:08 +0000144static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
John McCall0bdb1fd2010-09-16 06:16:50 +0000145 llvm::StringRef Name) {
John McCall36ea3722010-07-17 00:43:08 +0000146 const llvm::Type *Int8PtrTy =
147 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
John McCall36ea3722010-07-17 00:43:08 +0000148 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
Anders Carlsson566ae672011-04-18 14:24:10 +0000149 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, Int8PtrTy,
150 /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +0000151
152 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +0000153}
154
John McCall36ea3722010-07-17 00:43:08 +0000155const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
John McCall2faab302010-11-07 02:35:25 +0000156const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
John McCall36ea3722010-07-17 00:43:08 +0000157const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
158const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
159const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
160const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
161 "objc_exception_throw");
David Chisnalle1d2584d2011-03-20 21:35:39 +0000162const EHPersonality EHPersonality::GNU_ObjCXX("__gnustep_objcxx_personality_v0");
John McCall36ea3722010-07-17 00:43:08 +0000163
164static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000165 if (L.SjLjExceptions)
166 return EHPersonality::GNU_C_SJLJ;
John McCall36ea3722010-07-17 00:43:08 +0000167 return EHPersonality::GNU_C;
168}
169
170static const EHPersonality &getObjCPersonality(const LangOptions &L) {
171 if (L.NeXTRuntime) {
172 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
173 else return getCPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000174 } else {
John McCall36ea3722010-07-17 00:43:08 +0000175 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000176 }
177}
178
John McCall36ea3722010-07-17 00:43:08 +0000179static const EHPersonality &getCXXPersonality(const LangOptions &L) {
180 if (L.SjLjExceptions)
181 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallbd309292010-07-06 01:34:17 +0000182 else
John McCall36ea3722010-07-17 00:43:08 +0000183 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000184}
185
186/// Determines the personality function to use when both C++
187/// and Objective-C exceptions are being caught.
John McCall36ea3722010-07-17 00:43:08 +0000188static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallbd309292010-07-06 01:34:17 +0000189 // The ObjC personality defers to the C++ personality for non-ObjC
190 // handlers. Unlike the C++ case, we use the same personality
191 // function on targets using (backend-driven) SJLJ EH.
John McCall36ea3722010-07-17 00:43:08 +0000192 if (L.NeXTRuntime) {
193 if (L.ObjCNonFragileABI)
194 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000195
196 // In the fragile ABI, just use C++ exception handling and hope
197 // they're not doing crazy exception mixing.
198 else
John McCall36ea3722010-07-17 00:43:08 +0000199 return getCXXPersonality(L);
Chandler Carruth0450cc62010-05-17 20:58:49 +0000200 }
David Chisnallf9c42252010-05-17 13:49:20 +0000201
John McCall36ea3722010-07-17 00:43:08 +0000202 // The GNU runtime's personality function inherently doesn't support
203 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnalle1d2584d2011-03-20 21:35:39 +0000204 return EHPersonality::GNU_ObjCXX;
John McCallbd309292010-07-06 01:34:17 +0000205}
206
John McCall36ea3722010-07-17 00:43:08 +0000207const EHPersonality &EHPersonality::get(const LangOptions &L) {
208 if (L.CPlusPlus && L.ObjC1)
209 return getObjCXXPersonality(L);
210 else if (L.CPlusPlus)
211 return getCXXPersonality(L);
212 else if (L.ObjC1)
213 return getObjCPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000214 else
John McCall36ea3722010-07-17 00:43:08 +0000215 return getCPersonality(L);
216}
John McCallbd309292010-07-06 01:34:17 +0000217
John McCall0bdb1fd2010-09-16 06:16:50 +0000218static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000219 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000220 llvm::Constant *Fn =
John McCall0bdb1fd2010-09-16 06:16:50 +0000221 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
222 llvm::Type::getInt32Ty(CGM.getLLVMContext()),
223 true),
224 Personality.getPersonalityFnName());
225 return Fn;
226}
227
228static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
229 const EHPersonality &Personality) {
230 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000231 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000232}
233
234/// Check whether a personality function could reasonably be swapped
235/// for a C++ personality function.
236static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
237 for (llvm::Constant::use_iterator
238 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
239 llvm::User *User = *I;
240
241 // Conditionally white-list bitcasts.
242 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
243 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
244 if (!PersonalityHasOnlyCXXUses(CE))
245 return false;
246 continue;
247 }
248
249 // Otherwise, it has to be a selector call.
250 if (!isa<llvm::EHSelectorInst>(User)) return false;
251
252 llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
253 for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
254 // Look for something that would've been returned by the ObjC
255 // runtime's GetEHType() method.
256 llvm::GlobalVariable *GV
257 = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
258 if (!GV) continue;
259
260 // ObjC EH selector entries are always global variables with
261 // names starting like this.
262 if (GV->getName().startswith("OBJC_EHTYPE"))
263 return false;
264 }
265 }
266
267 return true;
268}
269
270/// Try to use the C++ personality function in ObjC++. Not doing this
271/// can cause some incompatibilities with gcc, which is more
272/// aggressive about only using the ObjC++ personality in a function
273/// when it really needs it.
274void CodeGenModule::SimplifyPersonality() {
275 // For now, this is really a Darwin-specific operation.
Daniel Dunbara59b0a62011-04-26 19:43:00 +0000276 if (!Context.Target.getTriple().isOSDarwin())
John McCall0bdb1fd2010-09-16 06:16:50 +0000277 return;
278
279 // If we're not in ObjC++ -fexceptions, there's nothing to do.
280 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
281 return;
282
283 const EHPersonality &ObjCXX = EHPersonality::get(Features);
284 const EHPersonality &CXX = getCXXPersonality(Features);
285 if (&ObjCXX == &CXX ||
286 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
287 return;
288
289 llvm::Function *Fn =
290 getModule().getFunction(ObjCXX.getPersonalityFnName());
291
292 // Nothing to do if it's unused.
293 if (!Fn || Fn->use_empty()) return;
294
295 // Can't do the optimization if it has non-C++ uses.
296 if (!PersonalityHasOnlyCXXUses(Fn)) return;
297
298 // Create the C++ personality function and kill off the old
299 // function.
300 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
301
302 // This can happen if the user is screwing with us.
303 if (Fn->getType() != CXXFn->getType()) return;
304
305 Fn->replaceAllUsesWith(CXXFn);
306 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000307}
308
309/// Returns the value to inject into a selector to indicate the
310/// presence of a catch-all.
311static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
312 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000313 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000314}
315
316/// Returns the value to inject into a selector to indicate the
317/// presence of a cleanup.
318static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
319 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump33270212009-12-02 07:41:41 +0000320}
321
John McCallbb026012010-07-13 21:17:51 +0000322namespace {
323 /// A cleanup to free the exception object if its initialization
324 /// throws.
John McCalle4df6c82011-01-28 08:37:24 +0000325 struct FreeException {
326 static void Emit(CodeGenFunction &CGF, bool forEH,
327 llvm::Value *exn) {
328 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
John McCallbb026012010-07-13 21:17:51 +0000329 ->setDoesNotThrow();
John McCallbb026012010-07-13 21:17:51 +0000330 }
331 };
332}
333
John McCall2e6567a2010-04-22 01:10:34 +0000334// Emits an exception expression into the given location. This
335// differs from EmitAnyExprToMem only in that, if a final copy-ctor
336// call is required, an exception within that copy ctor causes
337// std::terminate to be invoked.
John McCalle4df6c82011-01-28 08:37:24 +0000338static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
339 llvm::Value *addr) {
John McCallbd309292010-07-06 01:34:17 +0000340 // Make sure the exception object is cleaned up if there's an
341 // exception during initialization.
John McCalle4df6c82011-01-28 08:37:24 +0000342 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
343 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000344
345 // __cxa_allocate_exception returns a void*; we need to cast this
346 // to the appropriate type for the object.
John McCalle4df6c82011-01-28 08:37:24 +0000347 const llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
348 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000349
350 // FIXME: this isn't quite right! If there's a final unelided call
351 // to a copy constructor, then according to [except.terminate]p1 we
352 // must call std::terminate() if that constructor throws, because
353 // technically that copy occurs after the exception expression is
354 // evaluated but before the exception is caught. But the best way
355 // to handle that is to teach EmitAggExpr to do the final copy
356 // differently if it can't be elided.
John McCalle4df6c82011-01-28 08:37:24 +0000357 CGF.EmitAnyExprToMem(e, typedAddr, /*Volatile*/ false, /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000358
John McCalle4df6c82011-01-28 08:37:24 +0000359 // Deactivate the cleanup block.
360 CGF.DeactivateCleanupBlock(cleanup);
Mike Stump54066142009-12-01 03:41:18 +0000361}
362
John McCallbd309292010-07-06 01:34:17 +0000363llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000364 if (!ExceptionSlot)
365 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallbd309292010-07-06 01:34:17 +0000366 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000367}
368
John McCall9b382dd2011-05-28 21:13:02 +0000369llvm::Value *CodeGenFunction::getEHSelectorSlot() {
370 if (!EHSelectorSlot)
371 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
372 return EHSelectorSlot;
373}
374
Anders Carlsson4b08db72009-10-30 01:42:31 +0000375void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000376 if (!E->getSubExpr()) {
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000377 if (getInvokeDest()) {
John McCallbd309292010-07-06 01:34:17 +0000378 Builder.CreateInvoke(getReThrowFn(*this),
379 getUnreachableBlock(),
380 getInvokeDest())
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000381 ->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000382 } else {
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000383 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000384 Builder.CreateUnreachable();
385 }
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000386
John McCall20f6ab82011-01-12 03:41:02 +0000387 // throw is an expression, and the expression emitters expect us
388 // to leave ourselves at a valid insertion point.
389 EmitBlock(createBasicBlock("throw.cont"));
390
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000391 return;
392 }
Mike Stump75546b82009-12-10 00:06:18 +0000393
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000394 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump75546b82009-12-10 00:06:18 +0000395
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000396 // Now allocate the exception object.
397 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall21886962010-04-21 10:05:39 +0000398 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump75546b82009-12-10 00:06:18 +0000399
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000400 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallbd309292010-07-06 01:34:17 +0000401 llvm::CallInst *ExceptionPtr =
Mike Stump75546b82009-12-10 00:06:18 +0000402 Builder.CreateCall(AllocExceptionFn,
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000403 llvm::ConstantInt::get(SizeTy, TypeSize),
404 "exception");
John McCallbd309292010-07-06 01:34:17 +0000405 ExceptionPtr->setDoesNotThrow();
Anders Carlssonafd1edb2009-12-11 00:32:37 +0000406
John McCall2e6567a2010-04-22 01:10:34 +0000407 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump75546b82009-12-10 00:06:18 +0000408
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000409 // Now throw the exception.
410 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Anders Carlssonba840fb2011-01-24 01:59:49 +0000411 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
412 /*ForEH=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000413
414 // The address of the destructor. If the exception type has a
415 // trivial destructor (or isn't a record), we just pass null.
416 llvm::Constant *Dtor = 0;
417 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
418 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
419 if (!Record->hasTrivialDestructor()) {
Douglas Gregorbac74902010-07-01 14:13:13 +0000420 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCall2e6567a2010-04-22 01:10:34 +0000421 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
422 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
423 }
424 }
425 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000426
Mike Stump114ab9f2009-12-04 01:51:45 +0000427 if (getInvokeDest()) {
Mike Stump75546b82009-12-10 00:06:18 +0000428 llvm::InvokeInst *ThrowCall =
John McCallbd309292010-07-06 01:34:17 +0000429 Builder.CreateInvoke3(getThrowFn(*this),
430 getUnreachableBlock(), getInvokeDest(),
Mike Stump114ab9f2009-12-04 01:51:45 +0000431 ExceptionPtr, TypeInfo, Dtor);
432 ThrowCall->setDoesNotReturn();
Mike Stump114ab9f2009-12-04 01:51:45 +0000433 } else {
Mike Stump75546b82009-12-10 00:06:18 +0000434 llvm::CallInst *ThrowCall =
Mike Stump114ab9f2009-12-04 01:51:45 +0000435 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
436 ThrowCall->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000437 Builder.CreateUnreachable();
Mike Stump114ab9f2009-12-04 01:51:45 +0000438 }
Mike Stump75546b82009-12-10 00:06:18 +0000439
John McCall20f6ab82011-01-12 03:41:02 +0000440 // throw is an expression, and the expression emitters expect us
441 // to leave ourselves at a valid insertion point.
442 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000443}
Mike Stump58ef18b2009-11-20 23:44:51 +0000444
Mike Stump1d849212009-12-07 23:38:24 +0000445void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlssone96ab552011-02-28 02:27:16 +0000446 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000447 return;
448
Mike Stump1d849212009-12-07 23:38:24 +0000449 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
450 if (FD == 0)
451 return;
452 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
453 if (Proto == 0)
454 return;
455
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000456 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
457 if (isNoexceptExceptionSpec(EST)) {
458 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
459 // noexcept functions are simple terminate scopes.
460 EHStack.pushTerminate();
461 }
462 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
463 unsigned NumExceptions = Proto->getNumExceptions();
464 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000465
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000466 for (unsigned I = 0; I != NumExceptions; ++I) {
467 QualType Ty = Proto->getExceptionType(I);
468 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
469 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
470 /*ForEH=*/true);
471 Filter->setFilter(I, EHType);
472 }
Mike Stump1d849212009-12-07 23:38:24 +0000473 }
Mike Stump1d849212009-12-07 23:38:24 +0000474}
475
476void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlssone96ab552011-02-28 02:27:16 +0000477 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000478 return;
479
Mike Stump1d849212009-12-07 23:38:24 +0000480 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
481 if (FD == 0)
482 return;
483 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
484 if (Proto == 0)
485 return;
486
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000487 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
488 if (isNoexceptExceptionSpec(EST)) {
489 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
490 EHStack.popTerminate();
491 }
492 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
493 EHStack.popFilter();
494 }
Mike Stump1d849212009-12-07 23:38:24 +0000495}
496
Mike Stump58ef18b2009-11-20 23:44:51 +0000497void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000498 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000499 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000500 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000501}
502
John McCallb609d3f2010-07-07 06:56:46 +0000503void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000504 unsigned NumHandlers = S.getNumHandlers();
505 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000506
John McCallbd309292010-07-06 01:34:17 +0000507 for (unsigned I = 0; I != NumHandlers; ++I) {
508 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000509
John McCallbd309292010-07-06 01:34:17 +0000510 llvm::BasicBlock *Handler = createBasicBlock("catch");
511 if (C->getExceptionDecl()) {
512 // FIXME: Dropping the reference type on the type into makes it
513 // impossible to correctly implement catch-by-reference
514 // semantics for pointers. Unfortunately, this is what all
515 // existing compilers do, and it's not clear that the standard
516 // personality routine is capable of doing this right. See C++ DR 388:
517 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
518 QualType CaughtType = C->getCaughtType();
519 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall2ca705e2010-07-24 00:37:23 +0000520
521 llvm::Value *TypeInfo = 0;
522 if (CaughtType->isObjCObjectPointerType())
523 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
524 else
Anders Carlssonba840fb2011-01-24 01:59:49 +0000525 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallbd309292010-07-06 01:34:17 +0000526 CatchScope->setHandler(I, TypeInfo, Handler);
527 } else {
528 // No exception decl indicates '...', a catch-all.
529 CatchScope->setCatchAllHandler(I, Handler);
530 }
531 }
John McCallbd309292010-07-06 01:34:17 +0000532}
533
534/// Check whether this is a non-EH scope, i.e. a scope which doesn't
535/// affect exception handling. Currently, the only non-EH scopes are
536/// normal-only cleanup scopes.
537static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000538 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000539 case EHScope::Cleanup:
540 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000541 case EHScope::Filter:
542 case EHScope::Catch:
543 case EHScope::Terminate:
544 return false;
545 }
546
547 // Suppress warning.
548 return false;
John McCallbd309292010-07-06 01:34:17 +0000549}
550
551llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
552 assert(EHStack.requiresLandingPad());
553 assert(!EHStack.empty());
554
Anders Carlsson6dc07d42011-02-28 00:33:03 +0000555 if (!CGM.getLangOptions().Exceptions)
John McCall2b7fc382010-07-13 20:32:21 +0000556 return 0;
557
John McCallbd309292010-07-06 01:34:17 +0000558 // Check the innermost scope for a cached landing pad. If this is
559 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
560 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
561 if (LP) return LP;
562
563 // Build the landing pad for this scope.
564 LP = EmitLandingPad();
565 assert(LP);
566
567 // Cache the landing pad on the innermost scope. If this is a
568 // non-EH scope, cache the landing pad on the enclosing scope, too.
569 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
570 ir->setCachedLandingPad(LP);
571 if (!isNonEHScope(*ir)) break;
572 }
573
574 return LP;
575}
576
John McCall9b382dd2011-05-28 21:13:02 +0000577// This code contains a hack to work around a design flaw in
578// LLVM's EH IR which breaks semantics after inlining. This same
579// hack is implemented in llvm-gcc.
580//
581// The LLVM EH abstraction is basically a thin veneer over the
582// traditional GCC zero-cost design: for each range of instructions
583// in the function, there is (at most) one "landing pad" with an
584// associated chain of EH actions. A language-specific personality
585// function interprets this chain of actions and (1) decides whether
586// or not to resume execution at the landing pad and (2) if so,
587// provides an integer indicating why it's stopping. In LLVM IR,
588// the association of a landing pad with a range of instructions is
589// achieved via an invoke instruction, the chain of actions becomes
590// the arguments to the @llvm.eh.selector call, and the selector
591// call returns the integer indicator. Other than the required
592// presence of two intrinsic function calls in the landing pad,
593// the IR exactly describes the layout of the output code.
594//
595// A principal advantage of this design is that it is completely
596// language-agnostic; in theory, the LLVM optimizers can treat
597// landing pads neutrally, and targets need only know how to lower
598// the intrinsics to have a functioning exceptions system (assuming
599// that platform exceptions follow something approximately like the
600// GCC design). Unfortunately, landing pads cannot be combined in a
601// language-agnostic way: given selectors A and B, there is no way
602// to make a single landing pad which faithfully represents the
603// semantics of propagating an exception first through A, then
604// through B, without knowing how the personality will interpret the
605// (lowered form of the) selectors. This means that inlining has no
606// choice but to crudely chain invokes (i.e., to ignore invokes in
607// the inlined function, but to turn all unwindable calls into
608// invokes), which is only semantically valid if every unwind stops
609// at every landing pad.
610//
611// Therefore, the invoke-inline hack is to guarantee that every
612// landing pad has a catch-all.
613enum CleanupHackLevel_t {
614 /// A level of hack that requires that all landing pads have
615 /// catch-alls.
616 CHL_MandatoryCatchall,
617
618 /// A level of hack that requires that all landing pads handle
619 /// cleanups.
620 CHL_MandatoryCleanup,
621
622 /// No hacks at all; ideal IR generation.
623 CHL_Ideal
624};
625const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
626
John McCallbd309292010-07-06 01:34:17 +0000627llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
628 assert(EHStack.requiresLandingPad());
629
John McCallbd309292010-07-06 01:34:17 +0000630 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
631 assert(ir != EHStack.end() &&
632 "stack requiring landing pad is nothing but non-EH scopes?");
633
634 // If this is a terminate scope, just use the singleton terminate
635 // landing pad.
636 if (isa<EHTerminateScope>(*ir))
637 return getTerminateLandingPad();
638
639 // If this isn't an EH scope, iterate; otherwise break out.
640 if (!isNonEHScope(*ir)) break;
641 ++ir;
642
643 // We haven't checked this scope for a cached landing pad yet.
644 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
645 return LP;
646 }
647
648 // Save the current IR generation state.
649 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
650
John McCallad7c5c12011-02-08 08:22:06 +0000651 const EHPersonality &Personality = EHPersonality::get(getLangOptions());
John McCall36ea3722010-07-17 00:43:08 +0000652
John McCallbd309292010-07-06 01:34:17 +0000653 // Create and configure the landing pad.
654 llvm::BasicBlock *LP = createBasicBlock("lpad");
655 EmitBlock(LP);
656
657 // Save the exception pointer. It's safe to use a single exception
658 // pointer per function because EH cleanups can never have nested
659 // try/catches.
660 llvm::CallInst *Exn =
661 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
662 Exn->setDoesNotThrow();
663 Builder.CreateStore(Exn, getExceptionSlot());
664
665 // Build the selector arguments.
666 llvm::SmallVector<llvm::Value*, 8> EHSelector;
667 EHSelector.push_back(Exn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000668 EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
John McCallbd309292010-07-06 01:34:17 +0000669
670 // Accumulate all the handlers in scope.
John McCallad5d61e2010-07-23 21:56:41 +0000671 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
672 UnwindDest CatchAll;
John McCallbd309292010-07-06 01:34:17 +0000673 bool HasEHCleanup = false;
674 bool HasEHFilter = false;
675 llvm::SmallVector<llvm::Value*, 8> EHFilters;
676 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
677 I != E; ++I) {
678
679 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000680 case EHScope::Cleanup:
John McCall2b7fc382010-07-13 20:32:21 +0000681 if (!HasEHCleanup)
John McCallcda666c2010-07-21 07:22:38 +0000682 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000683 // We otherwise don't care about cleanups.
684 continue;
685
John McCallbd309292010-07-06 01:34:17 +0000686 case EHScope::Filter: {
687 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallad5d61e2010-07-23 21:56:41 +0000688 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000689
Chris Lattner57540c52011-04-15 05:22:18 +0000690 // Filter scopes get added to the selector in weird ways.
John McCallbd309292010-07-06 01:34:17 +0000691 EHFilterScope &Filter = cast<EHFilterScope>(*I);
692 HasEHFilter = true;
693
694 // Add all the filter values which we aren't already explicitly
695 // catching.
696 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
697 llvm::Value *FV = Filter.getFilter(I);
698 if (!EHHandlers.count(FV))
699 EHFilters.push_back(FV);
700 }
701 goto done;
702 }
703
704 case EHScope::Terminate:
705 // Terminate scopes are basically catch-alls.
John McCallad5d61e2010-07-23 21:56:41 +0000706 assert(!CatchAll.isValid());
707 CatchAll = UnwindDest(getTerminateHandler(),
708 EHStack.getEnclosingEHCleanup(I),
709 cast<EHTerminateScope>(*I).getDestIndex());
John McCallbd309292010-07-06 01:34:17 +0000710 goto done;
711
712 case EHScope::Catch:
713 break;
714 }
715
716 EHCatchScope &Catch = cast<EHCatchScope>(*I);
717 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
718 EHCatchScope::Handler Handler = Catch.getHandler(HI);
719
720 // Catch-all. We should only have one of these per catch.
721 if (!Handler.Type) {
John McCallad5d61e2010-07-23 21:56:41 +0000722 assert(!CatchAll.isValid());
723 CatchAll = UnwindDest(Handler.Block,
724 EHStack.getEnclosingEHCleanup(I),
725 Handler.Index);
John McCallbd309292010-07-06 01:34:17 +0000726 continue;
727 }
728
729 // Check whether we already have a handler for this type.
John McCallad5d61e2010-07-23 21:56:41 +0000730 UnwindDest &Dest = EHHandlers[Handler.Type];
731 if (Dest.isValid()) continue;
John McCallbd309292010-07-06 01:34:17 +0000732
733 EHSelector.push_back(Handler.Type);
John McCallad5d61e2010-07-23 21:56:41 +0000734 Dest = UnwindDest(Handler.Block,
735 EHStack.getEnclosingEHCleanup(I),
736 Handler.Index);
John McCallbd309292010-07-06 01:34:17 +0000737 }
738
739 // Stop if we found a catch-all.
John McCallad5d61e2010-07-23 21:56:41 +0000740 if (CatchAll.isValid()) break;
John McCallbd309292010-07-06 01:34:17 +0000741 }
742
743 done:
744 unsigned LastToEmitInLoop = EHSelector.size();
745
746 // If we have a catch-all, add null to the selector.
John McCallad5d61e2010-07-23 21:56:41 +0000747 if (CatchAll.isValid()) {
John McCallad7c5c12011-02-08 08:22:06 +0000748 EHSelector.push_back(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000749
750 // If we have an EH filter, we need to add those handlers in the
751 // right place in the selector, which is to say, at the end.
752 } else if (HasEHFilter) {
753 // Create a filter expression: an integer constant saying how many
754 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
755 // followed by the filter types. The personality routine only
756 // lands here if the filter doesn't match.
757 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
758 EHFilters.size() + 1));
759 EHSelector.append(EHFilters.begin(), EHFilters.end());
760
761 // Also check whether we need a cleanup.
John McCall9b382dd2011-05-28 21:13:02 +0000762 if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup)
763 EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
John McCallad7c5c12011-02-08 08:22:06 +0000764 ? getCatchAllValue(*this)
765 : getCleanupValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000766
767 // Otherwise, signal that we at least have cleanups.
John McCall9b382dd2011-05-28 21:13:02 +0000768 } else if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup) {
769 EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
John McCallad7c5c12011-02-08 08:22:06 +0000770 ? getCatchAllValue(*this)
771 : getCleanupValue(*this));
John McCall9b382dd2011-05-28 21:13:02 +0000772
773 // At the MandatoryCleanup hack level, we don't need to actually
774 // spuriously tell the unwinder that we have cleanups, but we do
775 // need to always be prepared to handle cleanups.
776 } else if (CleanupHackLevel == CHL_MandatoryCleanup) {
777 // Just don't decrement LastToEmitInLoop.
778
John McCallbd309292010-07-06 01:34:17 +0000779 } else {
780 assert(LastToEmitInLoop > 2);
781 LastToEmitInLoop--;
782 }
783
784 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
785
786 // Tell the backend how to generate the landing pad.
787 llvm::CallInst *Selection =
788 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
789 EHSelector.begin(), EHSelector.end(), "eh.selector");
790 Selection->setDoesNotThrow();
John McCall9b382dd2011-05-28 21:13:02 +0000791
792 // Save the selector value in mandatory-cleanup mode.
793 if (CleanupHackLevel == CHL_MandatoryCleanup)
794 Builder.CreateStore(Selection, getEHSelectorSlot());
John McCallbd309292010-07-06 01:34:17 +0000795
796 // Select the right handler.
797 llvm::Value *llvm_eh_typeid_for =
798 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
799
800 // The results of llvm_eh_typeid_for aren't reliable --- at least
801 // not locally --- so we basically have to do this as an 'if' chain.
802 // We walk through the first N-1 catch clauses, testing and chaining,
803 // and then fall into the final clause (which is either a cleanup, a
804 // filter (possibly with a cleanup), a catch-all, or another catch).
805 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
806 llvm::Value *Type = EHSelector[I];
John McCallad5d61e2010-07-23 21:56:41 +0000807 UnwindDest Dest = EHHandlers[Type];
808 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallbd309292010-07-06 01:34:17 +0000809
810 // Figure out where to branch on a match. As a debug code-size
811 // optimization, if the scope depth matches the innermost cleanup,
812 // we branch directly to the catch handler.
John McCallad5d61e2010-07-23 21:56:41 +0000813 llvm::BasicBlock *Match = Dest.getBlock();
814 bool MatchNeedsCleanup =
815 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallbd309292010-07-06 01:34:17 +0000816 if (MatchNeedsCleanup)
817 Match = createBasicBlock("eh.match");
818
819 llvm::BasicBlock *Next = createBasicBlock("eh.next");
820
821 // Check whether the exception matches.
822 llvm::CallInst *Id
823 = Builder.CreateCall(llvm_eh_typeid_for,
John McCallad7c5c12011-02-08 08:22:06 +0000824 Builder.CreateBitCast(Type, Int8PtrTy));
John McCallbd309292010-07-06 01:34:17 +0000825 Id->setDoesNotThrow();
826 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
827 Match, Next);
828
829 // Emit match code if necessary.
830 if (MatchNeedsCleanup) {
831 EmitBlock(Match);
832 EmitBranchThroughEHCleanup(Dest);
833 }
834
835 // Continue to the next match.
836 EmitBlock(Next);
837 }
838
839 // Emit the final case in the selector.
840 // This might be a catch-all....
John McCallad5d61e2010-07-23 21:56:41 +0000841 if (CatchAll.isValid()) {
John McCallbd309292010-07-06 01:34:17 +0000842 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
843 EmitBranchThroughEHCleanup(CatchAll);
844
845 // ...or an EH filter...
846 } else if (HasEHFilter) {
847 llvm::Value *SavedSelection = Selection;
848
849 // First, unwind out to the outermost scope if necessary.
850 if (EHStack.hasEHCleanups()) {
851 // The end here might not dominate the beginning, so we might need to
852 // save the selector if we need it.
853 llvm::AllocaInst *SelectorVar = 0;
854 if (HasEHCleanup) {
855 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
856 Builder.CreateStore(Selection, SelectorVar);
857 }
858
859 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallad5d61e2010-07-23 21:56:41 +0000860 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
861 EHStack.getNextEHDestIndex()));
John McCallbd309292010-07-06 01:34:17 +0000862 EmitBlock(CleanupContBB);
863
864 if (HasEHCleanup)
865 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
866 }
867
868 // If there was a cleanup, we'll need to actually check whether we
869 // landed here because the filter triggered.
John McCall9b382dd2011-05-28 21:13:02 +0000870 if (CleanupHackLevel != CHL_Ideal || HasEHCleanup) {
John McCallbd309292010-07-06 01:34:17 +0000871 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
872
John McCall9b382dd2011-05-28 21:13:02 +0000873 llvm::Constant *Zero = llvm::ConstantInt::get(Int32Ty, 0);
John McCallbd309292010-07-06 01:34:17 +0000874 llvm::Value *FailsFilter =
875 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
John McCall9b382dd2011-05-28 21:13:02 +0000876 Builder.CreateCondBr(FailsFilter, UnexpectedBB, getRethrowDest().getBlock());
John McCallbd309292010-07-06 01:34:17 +0000877
878 EmitBlock(UnexpectedBB);
879 }
880
881 // Call __cxa_call_unexpected. This doesn't need to be an invoke
882 // because __cxa_call_unexpected magically filters exceptions
883 // according to the last landing pad the exception was thrown
884 // into. Seriously.
885 Builder.CreateCall(getUnexpectedFn(*this),
886 Builder.CreateLoad(getExceptionSlot()))
887 ->setDoesNotReturn();
888 Builder.CreateUnreachable();
889
890 // ...or a normal catch handler...
John McCall9b382dd2011-05-28 21:13:02 +0000891 } else if (CleanupHackLevel == CHL_Ideal && !HasEHCleanup) {
John McCallbd309292010-07-06 01:34:17 +0000892 llvm::Value *Type = EHSelector.back();
893 EmitBranchThroughEHCleanup(EHHandlers[Type]);
894
895 // ...or a cleanup.
896 } else {
John McCallad5d61e2010-07-23 21:56:41 +0000897 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallbd309292010-07-06 01:34:17 +0000898 }
899
900 // Restore the old IR generation state.
901 Builder.restoreIP(SavedIP);
902
903 return LP;
904}
905
John McCall5c08ab92010-07-13 22:12:14 +0000906namespace {
907 /// A cleanup to call __cxa_end_catch. In many cases, the caught
908 /// exception type lets us state definitively that the thrown exception
909 /// type does not have a destructor. In particular:
910 /// - Catch-alls tell us nothing, so we have to conservatively
911 /// assume that the thrown exception might have a destructor.
912 /// - Catches by reference behave according to their base types.
913 /// - Catches of non-record types will only trigger for exceptions
914 /// of non-record types, which never have destructors.
915 /// - Catches of record types can trigger for arbitrary subclasses
916 /// of the caught type, so we have to assume the actual thrown
917 /// exception type might have a throwing destructor, even if the
918 /// caught type's destructor is trivial or nothrow.
John McCallcda666c2010-07-21 07:22:38 +0000919 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall5c08ab92010-07-13 22:12:14 +0000920 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
921 bool MightThrow;
922
923 void Emit(CodeGenFunction &CGF, bool IsForEH) {
924 if (!MightThrow) {
925 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
926 return;
927 }
928
929 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
930 }
931 };
932}
933
John McCallbd309292010-07-06 01:34:17 +0000934/// Emits a call to __cxa_begin_catch and enters a cleanup to call
935/// __cxa_end_catch.
John McCall5c08ab92010-07-13 22:12:14 +0000936///
937/// \param EndMightThrow - true if __cxa_end_catch might throw
938static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
939 llvm::Value *Exn,
940 bool EndMightThrow) {
John McCallbd309292010-07-06 01:34:17 +0000941 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
942 Call->setDoesNotThrow();
943
John McCallcda666c2010-07-21 07:22:38 +0000944 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallbd309292010-07-06 01:34:17 +0000945
946 return Call;
947}
948
949/// A "special initializer" callback for initializing a catch
950/// parameter during catch initialization.
951static void InitCatchParam(CodeGenFunction &CGF,
952 const VarDecl &CatchParam,
953 llvm::Value *ParamAddr) {
954 // Load the exception from where the landing pad saved it.
955 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
956
957 CanQualType CatchType =
958 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
959 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
960
961 // If we're catching by reference, we can just cast the object
962 // pointer to the appropriate pointer.
963 if (isa<ReferenceType>(CatchType)) {
John McCall5add20c2010-07-20 22:17:55 +0000964 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
965 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall5c08ab92010-07-13 22:12:14 +0000966
John McCallbd309292010-07-06 01:34:17 +0000967 // __cxa_begin_catch returns the adjusted object pointer.
John McCall5c08ab92010-07-13 22:12:14 +0000968 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall5add20c2010-07-20 22:17:55 +0000969
970 // We have no way to tell the personality function that we're
971 // catching by reference, so if we're catching a pointer,
972 // __cxa_begin_catch will actually return that pointer by value.
973 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
974 QualType PointeeType = PT->getPointeeType();
975
976 // When catching by reference, generally we should just ignore
977 // this by-value pointer and use the exception object instead.
978 if (!PointeeType->isRecordType()) {
979
980 // Exn points to the struct _Unwind_Exception header, which
981 // we have to skip past in order to reach the exception data.
982 unsigned HeaderSize =
983 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
984 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
985
986 // However, if we're catching a pointer-to-record type that won't
987 // work, because the personality function might have adjusted
988 // the pointer. There's actually no way for us to fully satisfy
989 // the language/ABI contract here: we can't use Exn because it
990 // might have the wrong adjustment, but we can't use the by-value
991 // pointer because it's off by a level of abstraction.
992 //
993 // The current solution is to dump the adjusted pointer into an
994 // alloca, which breaks language semantics (because changing the
995 // pointer doesn't change the exception) but at least works.
996 // The better solution would be to filter out non-exact matches
997 // and rethrow them, but this is tricky because the rethrow
998 // really needs to be catchable by other sites at this landing
999 // pad. The best solution is to fix the personality function.
1000 } else {
1001 // Pull the pointer for the reference type off.
1002 const llvm::Type *PtrTy =
1003 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1004
1005 // Create the temporary and write the adjusted pointer into it.
1006 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1007 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1008 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1009
1010 // Bind the reference to the temporary.
1011 AdjustedExn = ExnPtrTmp;
1012 }
1013 }
1014
John McCallbd309292010-07-06 01:34:17 +00001015 llvm::Value *ExnCast =
1016 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1017 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1018 return;
1019 }
1020
1021 // Non-aggregates (plus complexes).
1022 bool IsComplex = false;
1023 if (!CGF.hasAggregateLLVMType(CatchType) ||
1024 (IsComplex = CatchType->isAnyComplexType())) {
John McCall5c08ab92010-07-13 22:12:14 +00001025 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallbd309292010-07-06 01:34:17 +00001026
1027 // If the catch type is a pointer type, __cxa_begin_catch returns
1028 // the pointer by value.
1029 if (CatchType->hasPointerRepresentation()) {
1030 llvm::Value *CastExn =
1031 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1032 CGF.Builder.CreateStore(CastExn, ParamAddr);
1033 return;
1034 }
1035
1036 // Otherwise, it returns a pointer into the exception object.
1037
1038 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1039 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1040
1041 if (IsComplex) {
1042 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1043 ParamAddr, /*volatile*/ false);
1044 } else {
Daniel Dunbar03816342010-08-21 02:24:36 +00001045 unsigned Alignment =
1046 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallbd309292010-07-06 01:34:17 +00001047 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar03816342010-08-21 02:24:36 +00001048 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1049 CatchType);
John McCallbd309292010-07-06 01:34:17 +00001050 }
1051 return;
1052 }
1053
John McCallb5011ab2011-02-16 08:39:19 +00001054 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallbd309292010-07-06 01:34:17 +00001055
1056 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1057
John McCallb5011ab2011-02-16 08:39:19 +00001058 // Check for a copy expression. If we don't have a copy expression,
1059 // that means a trivial copy is okay.
John McCall1bf58462011-02-16 08:02:54 +00001060 const Expr *copyExpr = CatchParam.getInit();
1061 if (!copyExpr) {
John McCallb5011ab2011-02-16 08:39:19 +00001062 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1063 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1064 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallbd309292010-07-06 01:34:17 +00001065 return;
1066 }
1067
1068 // We have to call __cxa_get_exception_ptr to get the adjusted
1069 // pointer before copying.
John McCall1bf58462011-02-16 08:02:54 +00001070 llvm::CallInst *rawAdjustedExn =
John McCallbd309292010-07-06 01:34:17 +00001071 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
John McCall1bf58462011-02-16 08:02:54 +00001072 rawAdjustedExn->setDoesNotThrow();
John McCallbd309292010-07-06 01:34:17 +00001073
John McCall1bf58462011-02-16 08:02:54 +00001074 // Cast that to the appropriate type.
1075 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallbd309292010-07-06 01:34:17 +00001076
John McCall1bf58462011-02-16 08:02:54 +00001077 // The copy expression is defined in terms of an OpaqueValueExpr.
1078 // Find it and map it to the adjusted expression.
1079 CodeGenFunction::OpaqueValueMapping
John McCallc07a0c72011-02-17 10:25:35 +00001080 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1081 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallbd309292010-07-06 01:34:17 +00001082
1083 // Call the copy ctor in a terminate scope.
1084 CGF.EHStack.pushTerminate();
John McCall1bf58462011-02-16 08:02:54 +00001085
1086 // Perform the copy construction.
1087 CGF.EmitAggExpr(copyExpr, AggValueSlot::forAddr(ParamAddr, false, false));
1088
1089 // Leave the terminate scope.
John McCallbd309292010-07-06 01:34:17 +00001090 CGF.EHStack.popTerminate();
1091
John McCall1bf58462011-02-16 08:02:54 +00001092 // Undo the opaque value mapping.
1093 opaque.pop();
1094
John McCallbd309292010-07-06 01:34:17 +00001095 // Finally we can call __cxa_begin_catch.
John McCall5c08ab92010-07-13 22:12:14 +00001096 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001097}
1098
1099/// Begins a catch statement by initializing the catch variable and
1100/// calling __cxa_begin_catch.
John McCall1bf58462011-02-16 08:02:54 +00001101static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallbd309292010-07-06 01:34:17 +00001102 // We have to be very careful with the ordering of cleanups here:
1103 // C++ [except.throw]p4:
1104 // The destruction [of the exception temporary] occurs
1105 // immediately after the destruction of the object declared in
1106 // the exception-declaration in the handler.
1107 //
1108 // So the precise ordering is:
1109 // 1. Construct catch variable.
1110 // 2. __cxa_begin_catch
1111 // 3. Enter __cxa_end_catch cleanup
1112 // 4. Enter dtor cleanup
1113 //
John McCallc533cb72011-02-22 06:44:22 +00001114 // We do this by using a slightly abnormal initialization process.
1115 // Delegation sequence:
John McCallbd309292010-07-06 01:34:17 +00001116 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCallc533cb72011-02-22 06:44:22 +00001117 // - EmitAutoVarAlloca creates the variable and debug info
John McCallbd309292010-07-06 01:34:17 +00001118 // - InitCatchParam initializes the variable from the exception
John McCallc533cb72011-02-22 06:44:22 +00001119 // - CallBeginCatch calls __cxa_begin_catch
1120 // - CallBeginCatch enters the __cxa_end_catch cleanup
1121 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallbd309292010-07-06 01:34:17 +00001122 // - EmitCXXTryStmt emits the code for the catch body
1123 // - EmitCXXTryStmt close the RunCleanupsScope
1124
1125 VarDecl *CatchParam = S->getExceptionDecl();
1126 if (!CatchParam) {
1127 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall5c08ab92010-07-13 22:12:14 +00001128 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001129 return;
1130 }
1131
1132 // Emit the local.
John McCallc533cb72011-02-22 06:44:22 +00001133 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1134 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
1135 CGF.EmitAutoVarCleanups(var);
John McCallb81884d2010-02-19 09:25:03 +00001136}
1137
John McCall5c0e69e2010-07-13 22:24:23 +00001138namespace {
John McCallcda666c2010-07-21 07:22:38 +00001139 struct CallRethrow : EHScopeStack::Cleanup {
John McCall5c0e69e2010-07-13 22:24:23 +00001140 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1141 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1142 }
1143 };
1144}
1145
John McCallb609d3f2010-07-07 06:56:46 +00001146void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001147 unsigned NumHandlers = S.getNumHandlers();
1148 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1149 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001150
John McCallbd309292010-07-06 01:34:17 +00001151 // Copy the handler blocks off before we pop the EH stack. Emitting
1152 // the handlers might scribble on this memory.
1153 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1154 memcpy(Handlers.data(), CatchScope.begin(),
1155 NumHandlers * sizeof(EHCatchScope::Handler));
1156 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001157
John McCallbd309292010-07-06 01:34:17 +00001158 // The fall-through block.
1159 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001160
John McCallbd309292010-07-06 01:34:17 +00001161 // We just emitted the body of the try; jump to the continue block.
1162 if (HaveInsertPoint())
1163 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001164
John McCallb609d3f2010-07-07 06:56:46 +00001165 // Determine if we need an implicit rethrow for all these catch handlers.
1166 bool ImplicitRethrow = false;
1167 if (IsFnTryBlock)
1168 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1169 isa<CXXConstructorDecl>(CurCodeDecl);
1170
John McCallbd309292010-07-06 01:34:17 +00001171 for (unsigned I = 0; I != NumHandlers; ++I) {
1172 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1173 EmitBlock(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001174
John McCallbd309292010-07-06 01:34:17 +00001175 // Catch the exception if this isn't a catch-all.
1176 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump58ef18b2009-11-20 23:44:51 +00001177
John McCallbd309292010-07-06 01:34:17 +00001178 // Enter a cleanup scope, including the catch variable and the
1179 // end-catch.
1180 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001181
John McCallbd309292010-07-06 01:34:17 +00001182 // Initialize the catch variable and set up the cleanups.
1183 BeginCatch(*this, C);
1184
John McCallb609d3f2010-07-07 06:56:46 +00001185 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCall5c0e69e2010-07-13 22:24:23 +00001186 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1187 // called, and so it is pushed after BeginCatch.
1188 if (ImplicitRethrow)
John McCallcda666c2010-07-21 07:22:38 +00001189 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCallb609d3f2010-07-07 06:56:46 +00001190
John McCallbd309292010-07-06 01:34:17 +00001191 // Perform the body of the catch.
1192 EmitStmt(C->getHandlerBlock());
1193
1194 // Fall out through the catch cleanups.
1195 CatchScope.ForceCleanup();
1196
1197 // Branch out of the try.
1198 if (HaveInsertPoint())
1199 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001200 }
1201
John McCallbd309292010-07-06 01:34:17 +00001202 EmitBlock(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001203}
Mike Stumpaff69af2009-12-09 03:35:49 +00001204
John McCall1e670402010-07-21 00:52:03 +00001205namespace {
John McCallcda666c2010-07-21 07:22:38 +00001206 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001207 llvm::Value *ForEHVar;
1208 llvm::Value *EndCatchFn;
1209 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1210 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1211
1212 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1213 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1214 llvm::BasicBlock *CleanupContBB =
1215 CGF.createBasicBlock("finally.cleanup.cont");
1216
1217 llvm::Value *ShouldEndCatch =
1218 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1219 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1220 CGF.EmitBlock(EndCatchBB);
1221 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1222 CGF.EmitBlock(CleanupContBB);
1223 }
1224 };
John McCall906da4b2010-07-21 05:47:49 +00001225
John McCallcda666c2010-07-21 07:22:38 +00001226 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001227 const Stmt *Body;
1228 llvm::Value *ForEHVar;
1229 llvm::Value *EndCatchFn;
1230 llvm::Value *RethrowFn;
1231 llvm::Value *SavedExnVar;
1232
1233 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1234 llvm::Value *EndCatchFn,
1235 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1236 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1237 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1238
1239 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1240 // Enter a cleanup to call the end-catch function if one was provided.
1241 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001242 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1243 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001244
John McCallcebe0ca2010-08-11 00:16:14 +00001245 // Save the current cleanup destination in case there are
1246 // cleanups in the finally block.
1247 llvm::Value *SavedCleanupDest =
1248 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1249 "cleanup.dest.saved");
1250
John McCall906da4b2010-07-21 05:47:49 +00001251 // Emit the finally block.
1252 CGF.EmitStmt(Body);
1253
1254 // If the end of the finally is reachable, check whether this was
1255 // for EH. If so, rethrow.
1256 if (CGF.HaveInsertPoint()) {
1257 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1258 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1259
1260 llvm::Value *ShouldRethrow =
1261 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1262 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1263
1264 CGF.EmitBlock(RethrowBB);
1265 if (SavedExnVar) {
1266 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1267 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1268 } else {
1269 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1270 }
1271 CGF.Builder.CreateUnreachable();
1272
1273 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001274
1275 // Restore the cleanup destination.
1276 CGF.Builder.CreateStore(SavedCleanupDest,
1277 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001278 }
1279
1280 // Leave the end-catch cleanup. As an optimization, pretend that
1281 // the fallthrough path was inaccessible; we've dynamically proven
1282 // that we're not in the EH case along that path.
1283 if (EndCatchFn) {
1284 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1285 CGF.PopCleanupBlock();
1286 CGF.Builder.restoreIP(SavedIP);
1287 }
1288
1289 // Now make sure we actually have an insertion point or the
1290 // cleanup gods will hate us.
1291 CGF.EnsureInsertPoint();
1292 }
1293 };
John McCall1e670402010-07-21 00:52:03 +00001294}
1295
John McCallbd309292010-07-06 01:34:17 +00001296/// Enters a finally block for an implementation using zero-cost
1297/// exceptions. This is mostly general, but hard-codes some
1298/// language/ABI-specific behavior in the catch-all sections.
1299CodeGenFunction::FinallyInfo
1300CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1301 llvm::Constant *BeginCatchFn,
1302 llvm::Constant *EndCatchFn,
1303 llvm::Constant *RethrowFn) {
1304 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1305 "begin/end catch functions not paired");
1306 assert(RethrowFn && "rethrow function is required");
Mike Stumpaff69af2009-12-09 03:35:49 +00001307
John McCallbd309292010-07-06 01:34:17 +00001308 // The rethrow function has one of the following two types:
1309 // void (*)()
1310 // void (*)(void*)
1311 // In the latter case we need to pass it the exception object.
1312 // But we can't use the exception slot because the @finally might
1313 // have a landing pad (which would overwrite the exception slot).
1314 const llvm::FunctionType *RethrowFnTy =
1315 cast<llvm::FunctionType>(
1316 cast<llvm::PointerType>(RethrowFn->getType())
1317 ->getElementType());
1318 llvm::Value *SavedExnVar = 0;
1319 if (RethrowFnTy->getNumParams())
1320 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001321
John McCallbd309292010-07-06 01:34:17 +00001322 // A finally block is a statement which must be executed on any edge
1323 // out of a given scope. Unlike a cleanup, the finally block may
1324 // contain arbitrary control flow leading out of itself. In
1325 // addition, finally blocks should always be executed, even if there
1326 // are no catch handlers higher on the stack. Therefore, we
1327 // surround the protected scope with a combination of a normal
1328 // cleanup (to catch attempts to break out of the block via normal
1329 // control flow) and an EH catch-all (semantically "outside" any try
1330 // statement to which the finally block might have been attached).
1331 // The finally block itself is generated in the context of a cleanup
1332 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001333
John McCallbd309292010-07-06 01:34:17 +00001334 FinallyInfo Info;
John McCall21886962010-04-21 10:05:39 +00001335
John McCallbd309292010-07-06 01:34:17 +00001336 // Jump destination for performing the finally block on an exception
1337 // edge. We'll never actually reach this block, so unreachable is
1338 // fine.
1339 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001340
John McCallbd309292010-07-06 01:34:17 +00001341 // Whether the finally block is being executed for EH purposes.
John McCallad7c5c12011-02-08 08:22:06 +00001342 llvm::AllocaInst *ForEHVar = CreateTempAlloca(Builder.getInt1Ty(),
John McCallbd309292010-07-06 01:34:17 +00001343 "finally.for-eh");
1344 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpaff69af2009-12-09 03:35:49 +00001345
John McCallbd309292010-07-06 01:34:17 +00001346 // Enter a normal cleanup which will perform the @finally block.
John McCallcda666c2010-07-21 07:22:38 +00001347 EHStack.pushCleanup<PerformFinally>(NormalCleanup, Body,
1348 ForEHVar, EndCatchFn,
1349 RethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001350
1351 // Enter a catch-all scope.
1352 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1353 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1354 Builder.SetInsertPoint(CatchAllBB);
1355
1356 // If there's a begin-catch function, call it.
1357 if (BeginCatchFn) {
1358 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1359 ->setDoesNotThrow();
1360 }
1361
1362 // If we need to remember the exception pointer to rethrow later, do so.
1363 if (SavedExnVar) {
1364 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1365 Builder.CreateStore(SavedExn, SavedExnVar);
1366 }
1367
1368 // Tell the finally block that we're in EH.
1369 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1370
1371 // Thread a jump through the finally cleanup.
1372 EmitBranchThroughCleanup(RethrowDest);
1373
1374 Builder.restoreIP(SavedIP);
1375
1376 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1377 CatchScope->setCatchAllHandler(0, CatchAllBB);
1378
1379 return Info;
1380}
1381
1382void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1383 // Leave the finally catch-all.
1384 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1385 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1386 EHStack.popCatch();
1387
1388 // And leave the normal cleanup.
1389 PopCleanupBlock();
1390
1391 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1392 EmitBlock(CatchAllBB, true);
1393
1394 Builder.restoreIP(SavedIP);
1395}
1396
1397llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1398 if (TerminateLandingPad)
1399 return TerminateLandingPad;
1400
1401 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1402
1403 // This will get inserted at the end of the function.
1404 TerminateLandingPad = createBasicBlock("terminate.lpad");
1405 Builder.SetInsertPoint(TerminateLandingPad);
1406
1407 // Tell the backend that this is a landing pad.
1408 llvm::CallInst *Exn =
1409 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1410 Exn->setDoesNotThrow();
John McCall36ea3722010-07-17 00:43:08 +00001411
1412 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallbd309292010-07-06 01:34:17 +00001413
1414 // Tell the backend what the exception table should be:
1415 // nothing but a catch-all.
John McCall0bdb1fd2010-09-16 06:16:50 +00001416 llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
John McCallbd309292010-07-06 01:34:17 +00001417 getCatchAllValue(*this) };
1418 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1419 Args, Args+3, "eh.selector")
1420 ->setDoesNotThrow();
1421
1422 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1423 TerminateCall->setDoesNotReturn();
1424 TerminateCall->setDoesNotThrow();
John McCallad7c5c12011-02-08 08:22:06 +00001425 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001426
John McCallbd309292010-07-06 01:34:17 +00001427 // Restore the saved insertion state.
1428 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001429
John McCallbd309292010-07-06 01:34:17 +00001430 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001431}
Mike Stump2b488872009-12-09 22:59:31 +00001432
1433llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001434 if (TerminateHandler)
1435 return TerminateHandler;
1436
John McCallbd309292010-07-06 01:34:17 +00001437 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001438
John McCallbd309292010-07-06 01:34:17 +00001439 // Set up the terminate handler. This block is inserted at the very
1440 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001441 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001442 Builder.SetInsertPoint(TerminateHandler);
1443 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump2b488872009-12-09 22:59:31 +00001444 TerminateCall->setDoesNotReturn();
1445 TerminateCall->setDoesNotThrow();
1446 Builder.CreateUnreachable();
1447
John McCall21886962010-04-21 10:05:39 +00001448 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001449 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001450
Mike Stump2b488872009-12-09 22:59:31 +00001451 return TerminateHandler;
1452}
John McCallbd309292010-07-06 01:34:17 +00001453
John McCallad5d61e2010-07-23 21:56:41 +00001454CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1455 if (RethrowBlock.isValid()) return RethrowBlock;
1456
1457 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1458
1459 // We emit a jump to a notional label at the outermost unwind state.
1460 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1461 Builder.SetInsertPoint(Unwind);
1462
1463 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1464
1465 // This can always be a call because we necessarily didn't find
1466 // anything on the EH stack which needs our help.
John McCall0bdb1fd2010-09-16 06:16:50 +00001467 llvm::StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCall9b382dd2011-05-28 21:13:02 +00001468 if (!RethrowName.empty()) {
1469 Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
1470 Builder.CreateLoad(getExceptionSlot()))
1471 ->setDoesNotReturn();
1472 } else {
1473 llvm::Value *Exn = Builder.CreateLoad(getExceptionSlot());
John McCallad5d61e2010-07-23 21:56:41 +00001474
John McCall9b382dd2011-05-28 21:13:02 +00001475 switch (CleanupHackLevel) {
1476 case CHL_MandatoryCatchall:
1477 // In mandatory-catchall mode, we need to use
1478 // _Unwind_Resume_or_Rethrow, or whatever the personality's
1479 // equivalent is.
1480 Builder.CreateCall(getUnwindResumeOrRethrowFn(), Exn)
1481 ->setDoesNotReturn();
1482 break;
1483 case CHL_MandatoryCleanup: {
1484 // In mandatory-cleanup mode, we should use llvm.eh.resume.
1485 llvm::Value *Selector = Builder.CreateLoad(getEHSelectorSlot());
1486 Builder.CreateCall2(CGM.getIntrinsic(llvm::Intrinsic::eh_resume),
1487 Exn, Selector)
1488 ->setDoesNotReturn();
1489 break;
1490 }
1491 case CHL_Ideal:
1492 // In an idealized mode where we don't have to worry about the
1493 // optimizer combining landing pads, we should just use
1494 // _Unwind_Resume (or the personality's equivalent).
1495 Builder.CreateCall(getUnwindResumeFn(), Exn)
1496 ->setDoesNotReturn();
1497 break;
1498 }
1499 }
1500
John McCallad5d61e2010-07-23 21:56:41 +00001501 Builder.CreateUnreachable();
1502
1503 Builder.restoreIP(SavedIP);
1504
1505 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1506 return RethrowBlock;
1507}
1508