blob: af54f396868d4177623ce48d86e296db5260b4da [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
Mike Stump2bf701e2009-11-20 23:44:51 +000014#include "clang/AST/StmtCXX.h"
15
16#include "llvm/Intrinsics.h"
John McCallb2593832010-09-16 06:16:50 +000017#include "llvm/IntrinsicInst.h"
John McCallf1549f62010-07-06 01:34:17 +000018#include "llvm/Support/CallSite.h"
Mike Stump2bf701e2009-11-20 23:44:51 +000019
John McCall5a180392010-07-24 00:37:23 +000020#include "CGObjCRuntime.h"
Anders Carlsson756b5c42009-10-30 01:42:31 +000021#include "CodeGenFunction.h"
John McCallf1549f62010-07-06 01:34:17 +000022#include "CGException.h"
John McCall36f893c2011-01-28 11:13:47 +000023#include "CGCleanup.h"
John McCall204b0752010-07-20 22:17:55 +000024#include "TargetInfo.h"
John McCallf1549f62010-07-06 01:34:17 +000025
Anders Carlsson756b5c42009-10-30 01:42:31 +000026using namespace clang;
27using namespace CodeGen;
28
Anders Carlssond3379292009-10-30 02:27:02 +000029static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
30 // void *__cxa_allocate_exception(size_t thrown_size);
Mike Stump8755ec32009-12-10 00:06:18 +000031
Anders Carlsson2839d6b2011-04-18 14:24:10 +000032 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
Mike Stump8755ec32009-12-10 00:06:18 +000033 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000034 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
35 SizeTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000036
Anders Carlssond3379292009-10-30 02:27:02 +000037 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
38}
39
Mike Stump99533832009-12-02 07:41:41 +000040static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
41 // void __cxa_free_exception(void *thrown_exception);
Mike Stump8755ec32009-12-10 00:06:18 +000042
Anders Carlsson2839d6b2011-04-18 14:24:10 +000043 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Mike Stump8755ec32009-12-10 00:06:18 +000044 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000045 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
46 Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000047
Mike Stump99533832009-12-02 07:41:41 +000048 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
49}
50
Anders Carlssond3379292009-10-30 02:27:02 +000051static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +000052 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +000053 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +000054
55 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Anders Carlsson2839d6b2011-04-18 14:24:10 +000056 const llvm::Type *Args[3] = { Int8PtrTy, Int8PtrTy, Int8PtrTy };
Mike Stump8755ec32009-12-10 00:06:18 +000057 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +000058 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
Anders Carlsson2839d6b2011-04-18 14:24:10 +000059 Args, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000060
Anders Carlssond3379292009-10-30 02:27:02 +000061 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
62}
63
Mike Stumpb4eea692009-11-20 00:56:31 +000064static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +000065 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +000066
Mike Stump8755ec32009-12-10 00:06:18 +000067 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000068 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
69 /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000070
Mike Stumpb4eea692009-11-20 00:56:31 +000071 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
72}
73
John McCallf1549f62010-07-06 01:34:17 +000074static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
75 // void *__cxa_get_exception_ptr(void*);
John McCallf1549f62010-07-06 01:34:17 +000076
Anders Carlsson2839d6b2011-04-18 14:24:10 +000077 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
John McCallf1549f62010-07-06 01:34:17 +000078 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000079 llvm::FunctionType::get(Int8PtrTy, Int8PtrTy, /*IsVarArgs=*/false);
John McCallf1549f62010-07-06 01:34:17 +000080
81 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
82}
83
Mike Stump2bf701e2009-11-20 23:44:51 +000084static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +000085 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +000086
87 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Mike Stump8755ec32009-12-10 00:06:18 +000088 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000089 llvm::FunctionType::get(Int8PtrTy, Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000090
Mike Stump2bf701e2009-11-20 23:44:51 +000091 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
92}
93
94static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +000095 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +000096
Mike Stump8755ec32009-12-10 00:06:18 +000097 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000098 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
99 /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000100
Mike Stump2bf701e2009-11-20 23:44:51 +0000101 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
102}
103
Mike Stumpcce3d4f2009-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 Stump8755ec32009-12-10 00:06:18 +0000108 const llvm::FunctionType *FTy =
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000109 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
Anders Carlsson2839d6b2011-04-18 14:24:10 +0000110 Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000111
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000112 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
113}
114
John McCall93c332a2011-05-28 21:13:02 +0000115llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
John McCall09034212011-05-27 20:01:14 +0000116 const llvm::FunctionType *FTy =
John McCall93c332a2011-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 Stump8755ec32009-12-10 00:06:18 +0000127
Douglas Gregor86a3a032010-05-16 01:24:12 +0000128 if (CGM.getLangOptions().SjLjExceptions)
John McCalla5f2de22010-08-11 20:59:53 +0000129 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor86a3a032010-05-16 01:24:12 +0000130 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000131}
132
Mike Stump99533832009-12-02 07:41:41 +0000133static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
134 // void __terminate();
135
Mike Stump8755ec32009-12-10 00:06:18 +0000136 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +0000137 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
138 /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000139
John McCall256a76e2011-07-06 01:22:26 +0000140 llvm::StringRef name;
141
142 // In C++, use std::terminate().
143 if (CGF.getLangOptions().CPlusPlus)
144 name = "_ZSt9terminatev"; // FIXME: mangling!
145 else if (CGF.getLangOptions().ObjC1 &&
146 CGF.CGM.getCodeGenOpts().ObjCRuntimeHasTerminate)
147 name = "objc_terminate";
148 else
149 name = "abort";
150 return CGF.CGM.CreateRuntimeFunction(FTy, name);
David Chisnall79a9ad82010-05-17 13:49:20 +0000151}
152
John McCall8262b6a2010-07-17 00:43:08 +0000153static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
John McCallb2593832010-09-16 06:16:50 +0000154 llvm::StringRef Name) {
John McCall8262b6a2010-07-17 00:43:08 +0000155 const llvm::Type *Int8PtrTy =
156 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
John McCall8262b6a2010-07-17 00:43:08 +0000157 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
Anders Carlsson2839d6b2011-04-18 14:24:10 +0000158 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, Int8PtrTy,
159 /*IsVarArgs=*/false);
John McCall8262b6a2010-07-17 00:43:08 +0000160
161 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000162}
163
John McCall8262b6a2010-07-17 00:43:08 +0000164const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
John McCall44680782010-11-07 02:35:25 +0000165const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
John McCall8262b6a2010-07-17 00:43:08 +0000166const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
167const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
168const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
169const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
170 "objc_exception_throw");
David Chisnall80558d22011-03-20 21:35:39 +0000171const EHPersonality EHPersonality::GNU_ObjCXX("__gnustep_objcxx_personality_v0");
John McCall8262b6a2010-07-17 00:43:08 +0000172
173static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000174 if (L.SjLjExceptions)
175 return EHPersonality::GNU_C_SJLJ;
John McCall8262b6a2010-07-17 00:43:08 +0000176 return EHPersonality::GNU_C;
177}
178
179static const EHPersonality &getObjCPersonality(const LangOptions &L) {
180 if (L.NeXTRuntime) {
181 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
182 else return getCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000183 } else {
John McCall8262b6a2010-07-17 00:43:08 +0000184 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000185 }
186}
187
John McCall8262b6a2010-07-17 00:43:08 +0000188static const EHPersonality &getCXXPersonality(const LangOptions &L) {
189 if (L.SjLjExceptions)
190 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000191 else
John McCall8262b6a2010-07-17 00:43:08 +0000192 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000193}
194
195/// Determines the personality function to use when both C++
196/// and Objective-C exceptions are being caught.
John McCall8262b6a2010-07-17 00:43:08 +0000197static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallf1549f62010-07-06 01:34:17 +0000198 // The ObjC personality defers to the C++ personality for non-ObjC
199 // handlers. Unlike the C++ case, we use the same personality
200 // function on targets using (backend-driven) SJLJ EH.
John McCall8262b6a2010-07-17 00:43:08 +0000201 if (L.NeXTRuntime) {
202 if (L.ObjCNonFragileABI)
203 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000204
205 // In the fragile ABI, just use C++ exception handling and hope
206 // they're not doing crazy exception mixing.
207 else
John McCall8262b6a2010-07-17 00:43:08 +0000208 return getCXXPersonality(L);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000209 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000210
John McCall8262b6a2010-07-17 00:43:08 +0000211 // The GNU runtime's personality function inherently doesn't support
212 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnall80558d22011-03-20 21:35:39 +0000213 return EHPersonality::GNU_ObjCXX;
John McCallf1549f62010-07-06 01:34:17 +0000214}
215
John McCall8262b6a2010-07-17 00:43:08 +0000216const EHPersonality &EHPersonality::get(const LangOptions &L) {
217 if (L.CPlusPlus && L.ObjC1)
218 return getObjCXXPersonality(L);
219 else if (L.CPlusPlus)
220 return getCXXPersonality(L);
221 else if (L.ObjC1)
222 return getObjCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000223 else
John McCall8262b6a2010-07-17 00:43:08 +0000224 return getCPersonality(L);
225}
John McCallf1549f62010-07-06 01:34:17 +0000226
John McCallb2593832010-09-16 06:16:50 +0000227static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000228 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000229 llvm::Constant *Fn =
John McCallb2593832010-09-16 06:16:50 +0000230 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
231 llvm::Type::getInt32Ty(CGM.getLLVMContext()),
232 true),
233 Personality.getPersonalityFnName());
234 return Fn;
235}
236
237static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
238 const EHPersonality &Personality) {
239 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCalld16c2cf2011-02-08 08:22:06 +0000240 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCallb2593832010-09-16 06:16:50 +0000241}
242
243/// Check whether a personality function could reasonably be swapped
244/// for a C++ personality function.
245static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
246 for (llvm::Constant::use_iterator
247 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
248 llvm::User *User = *I;
249
250 // Conditionally white-list bitcasts.
251 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
252 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
253 if (!PersonalityHasOnlyCXXUses(CE))
254 return false;
255 continue;
256 }
257
258 // Otherwise, it has to be a selector call.
259 if (!isa<llvm::EHSelectorInst>(User)) return false;
260
261 llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
262 for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
263 // Look for something that would've been returned by the ObjC
264 // runtime's GetEHType() method.
265 llvm::GlobalVariable *GV
266 = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
267 if (!GV) continue;
268
269 // ObjC EH selector entries are always global variables with
270 // names starting like this.
271 if (GV->getName().startswith("OBJC_EHTYPE"))
272 return false;
273 }
274 }
275
276 return true;
277}
278
279/// Try to use the C++ personality function in ObjC++. Not doing this
280/// can cause some incompatibilities with gcc, which is more
281/// aggressive about only using the ObjC++ personality in a function
282/// when it really needs it.
283void CodeGenModule::SimplifyPersonality() {
284 // For now, this is really a Darwin-specific operation.
Daniel Dunbareab80782011-04-26 19:43:00 +0000285 if (!Context.Target.getTriple().isOSDarwin())
John McCallb2593832010-09-16 06:16:50 +0000286 return;
287
288 // If we're not in ObjC++ -fexceptions, there's nothing to do.
289 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
290 return;
291
292 const EHPersonality &ObjCXX = EHPersonality::get(Features);
293 const EHPersonality &CXX = getCXXPersonality(Features);
294 if (&ObjCXX == &CXX ||
295 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
296 return;
297
298 llvm::Function *Fn =
299 getModule().getFunction(ObjCXX.getPersonalityFnName());
300
301 // Nothing to do if it's unused.
302 if (!Fn || Fn->use_empty()) return;
303
304 // Can't do the optimization if it has non-C++ uses.
305 if (!PersonalityHasOnlyCXXUses(Fn)) return;
306
307 // Create the C++ personality function and kill off the old
308 // function.
309 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
310
311 // This can happen if the user is screwing with us.
312 if (Fn->getType() != CXXFn->getType()) return;
313
314 Fn->replaceAllUsesWith(CXXFn);
315 Fn->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000316}
317
318/// Returns the value to inject into a selector to indicate the
319/// presence of a catch-all.
320static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
321 // Possibly we should use @llvm.eh.catch.all.value here.
John McCalld16c2cf2011-02-08 08:22:06 +0000322 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallf1549f62010-07-06 01:34:17 +0000323}
324
325/// Returns the value to inject into a selector to indicate the
326/// presence of a cleanup.
327static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
328 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000329}
330
John McCall09faeab2010-07-13 21:17:51 +0000331namespace {
332 /// A cleanup to free the exception object if its initialization
333 /// throws.
John McCall3ad32c82011-01-28 08:37:24 +0000334 struct FreeException {
335 static void Emit(CodeGenFunction &CGF, bool forEH,
336 llvm::Value *exn) {
337 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
John McCall09faeab2010-07-13 21:17:51 +0000338 ->setDoesNotThrow();
John McCall09faeab2010-07-13 21:17:51 +0000339 }
340 };
341}
342
John McCallac418162010-04-22 01:10:34 +0000343// Emits an exception expression into the given location. This
344// differs from EmitAnyExprToMem only in that, if a final copy-ctor
345// call is required, an exception within that copy ctor causes
346// std::terminate to be invoked.
John McCall3ad32c82011-01-28 08:37:24 +0000347static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
348 llvm::Value *addr) {
John McCallf1549f62010-07-06 01:34:17 +0000349 // Make sure the exception object is cleaned up if there's an
350 // exception during initialization.
John McCall3ad32c82011-01-28 08:37:24 +0000351 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
352 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000353
354 // __cxa_allocate_exception returns a void*; we need to cast this
355 // to the appropriate type for the object.
John McCall3ad32c82011-01-28 08:37:24 +0000356 const llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
357 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCallac418162010-04-22 01:10:34 +0000358
359 // FIXME: this isn't quite right! If there's a final unelided call
360 // to a copy constructor, then according to [except.terminate]p1 we
361 // must call std::terminate() if that constructor throws, because
362 // technically that copy occurs after the exception expression is
363 // evaluated but before the exception is caught. But the best way
364 // to handle that is to teach EmitAggExpr to do the final copy
365 // differently if it can't be elided.
John McCallf85e1932011-06-15 23:02:42 +0000366 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
367 /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000368
John McCall3ad32c82011-01-28 08:37:24 +0000369 // Deactivate the cleanup block.
370 CGF.DeactivateCleanupBlock(cleanup);
Mike Stump0f590be2009-12-01 03:41:18 +0000371}
372
John McCallf1549f62010-07-06 01:34:17 +0000373llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall93c332a2011-05-28 21:13:02 +0000374 if (!ExceptionSlot)
375 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallf1549f62010-07-06 01:34:17 +0000376 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000377}
378
John McCall93c332a2011-05-28 21:13:02 +0000379llvm::Value *CodeGenFunction::getEHSelectorSlot() {
380 if (!EHSelectorSlot)
381 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
382 return EHSelectorSlot;
383}
384
Anders Carlsson756b5c42009-10-30 01:42:31 +0000385void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000386 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000387 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000388 Builder.CreateInvoke(getReThrowFn(*this),
389 getUnreachableBlock(),
390 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000391 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000392 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000393 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000394 Builder.CreateUnreachable();
395 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000396
John McCallcd5b22e2011-01-12 03:41:02 +0000397 // throw is an expression, and the expression emitters expect us
398 // to leave ourselves at a valid insertion point.
399 EmitBlock(createBasicBlock("throw.cont"));
400
Anders Carlssond3379292009-10-30 02:27:02 +0000401 return;
402 }
Mike Stump8755ec32009-12-10 00:06:18 +0000403
Anders Carlssond3379292009-10-30 02:27:02 +0000404 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000405
Anders Carlssond3379292009-10-30 02:27:02 +0000406 // Now allocate the exception object.
407 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000408 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000409
Anders Carlssond3379292009-10-30 02:27:02 +0000410 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000411 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000412 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000413 llvm::ConstantInt::get(SizeTy, TypeSize),
414 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000415 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000416
John McCallac418162010-04-22 01:10:34 +0000417 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000418
Anders Carlssond3379292009-10-30 02:27:02 +0000419 // Now throw the exception.
420 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Anders Carlsson82a113a2011-01-24 01:59:49 +0000421 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
422 /*ForEH=*/true);
John McCallac418162010-04-22 01:10:34 +0000423
424 // The address of the destructor. If the exception type has a
425 // trivial destructor (or isn't a record), we just pass null.
426 llvm::Constant *Dtor = 0;
427 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
428 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
429 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000430 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000431 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
432 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
433 }
434 }
435 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000436
Mike Stump0a3816e2009-12-04 01:51:45 +0000437 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000438 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000439 Builder.CreateInvoke3(getThrowFn(*this),
440 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000441 ExceptionPtr, TypeInfo, Dtor);
442 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000443 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000444 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000445 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
446 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000447 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000448 }
Mike Stump8755ec32009-12-10 00:06:18 +0000449
John McCallcd5b22e2011-01-12 03:41:02 +0000450 // throw is an expression, and the expression emitters expect us
451 // to leave ourselves at a valid insertion point.
452 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000453}
Mike Stump2bf701e2009-11-20 23:44:51 +0000454
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000455void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlsson15348ae2011-02-28 02:27:16 +0000456 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000457 return;
458
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000459 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
460 if (FD == 0)
461 return;
462 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
463 if (Proto == 0)
464 return;
465
Sebastian Redla968e972011-03-15 18:42:48 +0000466 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
467 if (isNoexceptExceptionSpec(EST)) {
468 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
469 // noexcept functions are simple terminate scopes.
470 EHStack.pushTerminate();
471 }
472 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
473 unsigned NumExceptions = Proto->getNumExceptions();
474 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000475
Sebastian Redla968e972011-03-15 18:42:48 +0000476 for (unsigned I = 0; I != NumExceptions; ++I) {
477 QualType Ty = Proto->getExceptionType(I);
478 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
479 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
480 /*ForEH=*/true);
481 Filter->setFilter(I, EHType);
482 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000483 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000484}
485
486void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlsson15348ae2011-02-28 02:27:16 +0000487 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000488 return;
489
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000490 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
491 if (FD == 0)
492 return;
493 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
494 if (Proto == 0)
495 return;
496
Sebastian Redla968e972011-03-15 18:42:48 +0000497 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
498 if (isNoexceptExceptionSpec(EST)) {
499 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
500 EHStack.popTerminate();
501 }
502 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
503 EHStack.popFilter();
504 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000505}
506
Mike Stump2bf701e2009-11-20 23:44:51 +0000507void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000508 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000509 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000510 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000511}
512
John McCall59a70002010-07-07 06:56:46 +0000513void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000514 unsigned NumHandlers = S.getNumHandlers();
515 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000516
John McCallf1549f62010-07-06 01:34:17 +0000517 for (unsigned I = 0; I != NumHandlers; ++I) {
518 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000519
John McCallf1549f62010-07-06 01:34:17 +0000520 llvm::BasicBlock *Handler = createBasicBlock("catch");
521 if (C->getExceptionDecl()) {
522 // FIXME: Dropping the reference type on the type into makes it
523 // impossible to correctly implement catch-by-reference
524 // semantics for pointers. Unfortunately, this is what all
525 // existing compilers do, and it's not clear that the standard
526 // personality routine is capable of doing this right. See C++ DR 388:
527 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
528 QualType CaughtType = C->getCaughtType();
529 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall5a180392010-07-24 00:37:23 +0000530
531 llvm::Value *TypeInfo = 0;
532 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000533 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall5a180392010-07-24 00:37:23 +0000534 else
Anders Carlsson82a113a2011-01-24 01:59:49 +0000535 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallf1549f62010-07-06 01:34:17 +0000536 CatchScope->setHandler(I, TypeInfo, Handler);
537 } else {
538 // No exception decl indicates '...', a catch-all.
539 CatchScope->setCatchAllHandler(I, Handler);
540 }
541 }
John McCallf1549f62010-07-06 01:34:17 +0000542}
543
544/// Check whether this is a non-EH scope, i.e. a scope which doesn't
545/// affect exception handling. Currently, the only non-EH scopes are
546/// normal-only cleanup scopes.
547static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000548 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000549 case EHScope::Cleanup:
550 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000551 case EHScope::Filter:
552 case EHScope::Catch:
553 case EHScope::Terminate:
554 return false;
555 }
556
557 // Suppress warning.
558 return false;
John McCallf1549f62010-07-06 01:34:17 +0000559}
560
561llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
562 assert(EHStack.requiresLandingPad());
563 assert(!EHStack.empty());
564
Anders Carlsson7a178512011-02-28 00:33:03 +0000565 if (!CGM.getLangOptions().Exceptions)
John McCallda65ea82010-07-13 20:32:21 +0000566 return 0;
567
John McCallf1549f62010-07-06 01:34:17 +0000568 // Check the innermost scope for a cached landing pad. If this is
569 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
570 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
571 if (LP) return LP;
572
573 // Build the landing pad for this scope.
574 LP = EmitLandingPad();
575 assert(LP);
576
577 // Cache the landing pad on the innermost scope. If this is a
578 // non-EH scope, cache the landing pad on the enclosing scope, too.
579 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
580 ir->setCachedLandingPad(LP);
581 if (!isNonEHScope(*ir)) break;
582 }
583
584 return LP;
585}
586
John McCall93c332a2011-05-28 21:13:02 +0000587// This code contains a hack to work around a design flaw in
588// LLVM's EH IR which breaks semantics after inlining. This same
589// hack is implemented in llvm-gcc.
590//
591// The LLVM EH abstraction is basically a thin veneer over the
592// traditional GCC zero-cost design: for each range of instructions
593// in the function, there is (at most) one "landing pad" with an
594// associated chain of EH actions. A language-specific personality
595// function interprets this chain of actions and (1) decides whether
596// or not to resume execution at the landing pad and (2) if so,
597// provides an integer indicating why it's stopping. In LLVM IR,
598// the association of a landing pad with a range of instructions is
599// achieved via an invoke instruction, the chain of actions becomes
600// the arguments to the @llvm.eh.selector call, and the selector
601// call returns the integer indicator. Other than the required
602// presence of two intrinsic function calls in the landing pad,
603// the IR exactly describes the layout of the output code.
604//
605// A principal advantage of this design is that it is completely
606// language-agnostic; in theory, the LLVM optimizers can treat
607// landing pads neutrally, and targets need only know how to lower
608// the intrinsics to have a functioning exceptions system (assuming
609// that platform exceptions follow something approximately like the
610// GCC design). Unfortunately, landing pads cannot be combined in a
611// language-agnostic way: given selectors A and B, there is no way
612// to make a single landing pad which faithfully represents the
613// semantics of propagating an exception first through A, then
614// through B, without knowing how the personality will interpret the
615// (lowered form of the) selectors. This means that inlining has no
616// choice but to crudely chain invokes (i.e., to ignore invokes in
617// the inlined function, but to turn all unwindable calls into
618// invokes), which is only semantically valid if every unwind stops
619// at every landing pad.
620//
621// Therefore, the invoke-inline hack is to guarantee that every
622// landing pad has a catch-all.
623enum CleanupHackLevel_t {
624 /// A level of hack that requires that all landing pads have
625 /// catch-alls.
626 CHL_MandatoryCatchall,
627
628 /// A level of hack that requires that all landing pads handle
629 /// cleanups.
630 CHL_MandatoryCleanup,
631
632 /// No hacks at all; ideal IR generation.
633 CHL_Ideal
634};
635const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
636
John McCallf1549f62010-07-06 01:34:17 +0000637llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
638 assert(EHStack.requiresLandingPad());
639
John McCallf1549f62010-07-06 01:34:17 +0000640 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
641 assert(ir != EHStack.end() &&
642 "stack requiring landing pad is nothing but non-EH scopes?");
643
644 // If this is a terminate scope, just use the singleton terminate
645 // landing pad.
646 if (isa<EHTerminateScope>(*ir))
647 return getTerminateLandingPad();
648
649 // If this isn't an EH scope, iterate; otherwise break out.
650 if (!isNonEHScope(*ir)) break;
651 ++ir;
652
653 // We haven't checked this scope for a cached landing pad yet.
654 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
655 return LP;
656 }
657
658 // Save the current IR generation state.
659 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
660
John McCalld16c2cf2011-02-08 08:22:06 +0000661 const EHPersonality &Personality = EHPersonality::get(getLangOptions());
John McCall8262b6a2010-07-17 00:43:08 +0000662
John McCallf1549f62010-07-06 01:34:17 +0000663 // Create and configure the landing pad.
664 llvm::BasicBlock *LP = createBasicBlock("lpad");
665 EmitBlock(LP);
666
667 // Save the exception pointer. It's safe to use a single exception
668 // pointer per function because EH cleanups can never have nested
669 // try/catches.
670 llvm::CallInst *Exn =
671 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
672 Exn->setDoesNotThrow();
673 Builder.CreateStore(Exn, getExceptionSlot());
674
675 // Build the selector arguments.
676 llvm::SmallVector<llvm::Value*, 8> EHSelector;
677 EHSelector.push_back(Exn);
John McCallb2593832010-09-16 06:16:50 +0000678 EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
John McCallf1549f62010-07-06 01:34:17 +0000679
680 // Accumulate all the handlers in scope.
John McCallff8e1152010-07-23 21:56:41 +0000681 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
682 UnwindDest CatchAll;
John McCallf1549f62010-07-06 01:34:17 +0000683 bool HasEHCleanup = false;
684 bool HasEHFilter = false;
685 llvm::SmallVector<llvm::Value*, 8> EHFilters;
686 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
687 I != E; ++I) {
688
689 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000690 case EHScope::Cleanup:
John McCallda65ea82010-07-13 20:32:21 +0000691 if (!HasEHCleanup)
John McCall1f0fca52010-07-21 07:22:38 +0000692 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000693 // We otherwise don't care about cleanups.
694 continue;
695
John McCallf1549f62010-07-06 01:34:17 +0000696 case EHScope::Filter: {
697 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallff8e1152010-07-23 21:56:41 +0000698 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000699
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000700 // Filter scopes get added to the selector in weird ways.
John McCallf1549f62010-07-06 01:34:17 +0000701 EHFilterScope &Filter = cast<EHFilterScope>(*I);
702 HasEHFilter = true;
703
704 // Add all the filter values which we aren't already explicitly
705 // catching.
706 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
707 llvm::Value *FV = Filter.getFilter(I);
708 if (!EHHandlers.count(FV))
709 EHFilters.push_back(FV);
710 }
711 goto done;
712 }
713
714 case EHScope::Terminate:
715 // Terminate scopes are basically catch-alls.
John McCallff8e1152010-07-23 21:56:41 +0000716 assert(!CatchAll.isValid());
717 CatchAll = UnwindDest(getTerminateHandler(),
718 EHStack.getEnclosingEHCleanup(I),
719 cast<EHTerminateScope>(*I).getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000720 goto done;
721
722 case EHScope::Catch:
723 break;
724 }
725
726 EHCatchScope &Catch = cast<EHCatchScope>(*I);
727 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
728 EHCatchScope::Handler Handler = Catch.getHandler(HI);
729
730 // Catch-all. We should only have one of these per catch.
731 if (!Handler.Type) {
John McCallff8e1152010-07-23 21:56:41 +0000732 assert(!CatchAll.isValid());
733 CatchAll = UnwindDest(Handler.Block,
734 EHStack.getEnclosingEHCleanup(I),
735 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000736 continue;
737 }
738
739 // Check whether we already have a handler for this type.
John McCallff8e1152010-07-23 21:56:41 +0000740 UnwindDest &Dest = EHHandlers[Handler.Type];
741 if (Dest.isValid()) continue;
John McCallf1549f62010-07-06 01:34:17 +0000742
743 EHSelector.push_back(Handler.Type);
John McCallff8e1152010-07-23 21:56:41 +0000744 Dest = UnwindDest(Handler.Block,
745 EHStack.getEnclosingEHCleanup(I),
746 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000747 }
748
749 // Stop if we found a catch-all.
John McCallff8e1152010-07-23 21:56:41 +0000750 if (CatchAll.isValid()) break;
John McCallf1549f62010-07-06 01:34:17 +0000751 }
752
753 done:
754 unsigned LastToEmitInLoop = EHSelector.size();
755
756 // If we have a catch-all, add null to the selector.
John McCallff8e1152010-07-23 21:56:41 +0000757 if (CatchAll.isValid()) {
John McCalld16c2cf2011-02-08 08:22:06 +0000758 EHSelector.push_back(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000759
760 // If we have an EH filter, we need to add those handlers in the
761 // right place in the selector, which is to say, at the end.
762 } else if (HasEHFilter) {
763 // Create a filter expression: an integer constant saying how many
764 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
765 // followed by the filter types. The personality routine only
766 // lands here if the filter doesn't match.
767 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
768 EHFilters.size() + 1));
769 EHSelector.append(EHFilters.begin(), EHFilters.end());
770
771 // Also check whether we need a cleanup.
John McCall93c332a2011-05-28 21:13:02 +0000772 if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup)
773 EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
John McCalld16c2cf2011-02-08 08:22:06 +0000774 ? getCatchAllValue(*this)
775 : getCleanupValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000776
777 // Otherwise, signal that we at least have cleanups.
John McCall93c332a2011-05-28 21:13:02 +0000778 } else if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup) {
779 EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
John McCalld16c2cf2011-02-08 08:22:06 +0000780 ? getCatchAllValue(*this)
781 : getCleanupValue(*this));
John McCall93c332a2011-05-28 21:13:02 +0000782
783 // At the MandatoryCleanup hack level, we don't need to actually
784 // spuriously tell the unwinder that we have cleanups, but we do
785 // need to always be prepared to handle cleanups.
786 } else if (CleanupHackLevel == CHL_MandatoryCleanup) {
787 // Just don't decrement LastToEmitInLoop.
788
John McCallf1549f62010-07-06 01:34:17 +0000789 } else {
790 assert(LastToEmitInLoop > 2);
791 LastToEmitInLoop--;
792 }
793
794 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
795
796 // Tell the backend how to generate the landing pad.
797 llvm::CallInst *Selection =
798 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
799 EHSelector.begin(), EHSelector.end(), "eh.selector");
800 Selection->setDoesNotThrow();
John McCall93c332a2011-05-28 21:13:02 +0000801
802 // Save the selector value in mandatory-cleanup mode.
803 if (CleanupHackLevel == CHL_MandatoryCleanup)
804 Builder.CreateStore(Selection, getEHSelectorSlot());
John McCallf1549f62010-07-06 01:34:17 +0000805
806 // Select the right handler.
807 llvm::Value *llvm_eh_typeid_for =
808 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
809
810 // The results of llvm_eh_typeid_for aren't reliable --- at least
811 // not locally --- so we basically have to do this as an 'if' chain.
812 // We walk through the first N-1 catch clauses, testing and chaining,
813 // and then fall into the final clause (which is either a cleanup, a
814 // filter (possibly with a cleanup), a catch-all, or another catch).
815 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
816 llvm::Value *Type = EHSelector[I];
John McCallff8e1152010-07-23 21:56:41 +0000817 UnwindDest Dest = EHHandlers[Type];
818 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallf1549f62010-07-06 01:34:17 +0000819
820 // Figure out where to branch on a match. As a debug code-size
821 // optimization, if the scope depth matches the innermost cleanup,
822 // we branch directly to the catch handler.
John McCallff8e1152010-07-23 21:56:41 +0000823 llvm::BasicBlock *Match = Dest.getBlock();
824 bool MatchNeedsCleanup =
825 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +0000826 if (MatchNeedsCleanup)
827 Match = createBasicBlock("eh.match");
828
829 llvm::BasicBlock *Next = createBasicBlock("eh.next");
830
831 // Check whether the exception matches.
832 llvm::CallInst *Id
833 = Builder.CreateCall(llvm_eh_typeid_for,
John McCalld16c2cf2011-02-08 08:22:06 +0000834 Builder.CreateBitCast(Type, Int8PtrTy));
John McCallf1549f62010-07-06 01:34:17 +0000835 Id->setDoesNotThrow();
836 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
837 Match, Next);
838
839 // Emit match code if necessary.
840 if (MatchNeedsCleanup) {
841 EmitBlock(Match);
842 EmitBranchThroughEHCleanup(Dest);
843 }
844
845 // Continue to the next match.
846 EmitBlock(Next);
847 }
848
849 // Emit the final case in the selector.
850 // This might be a catch-all....
John McCallff8e1152010-07-23 21:56:41 +0000851 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000852 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
853 EmitBranchThroughEHCleanup(CatchAll);
854
855 // ...or an EH filter...
856 } else if (HasEHFilter) {
857 llvm::Value *SavedSelection = Selection;
858
859 // First, unwind out to the outermost scope if necessary.
860 if (EHStack.hasEHCleanups()) {
861 // The end here might not dominate the beginning, so we might need to
862 // save the selector if we need it.
863 llvm::AllocaInst *SelectorVar = 0;
864 if (HasEHCleanup) {
865 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
866 Builder.CreateStore(Selection, SelectorVar);
867 }
868
869 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallff8e1152010-07-23 21:56:41 +0000870 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
871 EHStack.getNextEHDestIndex()));
John McCallf1549f62010-07-06 01:34:17 +0000872 EmitBlock(CleanupContBB);
873
874 if (HasEHCleanup)
875 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
876 }
877
878 // If there was a cleanup, we'll need to actually check whether we
879 // landed here because the filter triggered.
John McCall93c332a2011-05-28 21:13:02 +0000880 if (CleanupHackLevel != CHL_Ideal || HasEHCleanup) {
John McCallf1549f62010-07-06 01:34:17 +0000881 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
882
John McCall93c332a2011-05-28 21:13:02 +0000883 llvm::Constant *Zero = llvm::ConstantInt::get(Int32Ty, 0);
John McCallf1549f62010-07-06 01:34:17 +0000884 llvm::Value *FailsFilter =
885 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
John McCall93c332a2011-05-28 21:13:02 +0000886 Builder.CreateCondBr(FailsFilter, UnexpectedBB, getRethrowDest().getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000887
888 EmitBlock(UnexpectedBB);
889 }
890
891 // Call __cxa_call_unexpected. This doesn't need to be an invoke
892 // because __cxa_call_unexpected magically filters exceptions
893 // according to the last landing pad the exception was thrown
894 // into. Seriously.
895 Builder.CreateCall(getUnexpectedFn(*this),
896 Builder.CreateLoad(getExceptionSlot()))
897 ->setDoesNotReturn();
898 Builder.CreateUnreachable();
899
900 // ...or a normal catch handler...
John McCall93c332a2011-05-28 21:13:02 +0000901 } else if (CleanupHackLevel == CHL_Ideal && !HasEHCleanup) {
John McCallf1549f62010-07-06 01:34:17 +0000902 llvm::Value *Type = EHSelector.back();
903 EmitBranchThroughEHCleanup(EHHandlers[Type]);
904
905 // ...or a cleanup.
906 } else {
John McCallff8e1152010-07-23 21:56:41 +0000907 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallf1549f62010-07-06 01:34:17 +0000908 }
909
910 // Restore the old IR generation state.
911 Builder.restoreIP(SavedIP);
912
913 return LP;
914}
915
John McCall8e3f8612010-07-13 22:12:14 +0000916namespace {
917 /// A cleanup to call __cxa_end_catch. In many cases, the caught
918 /// exception type lets us state definitively that the thrown exception
919 /// type does not have a destructor. In particular:
920 /// - Catch-alls tell us nothing, so we have to conservatively
921 /// assume that the thrown exception might have a destructor.
922 /// - Catches by reference behave according to their base types.
923 /// - Catches of non-record types will only trigger for exceptions
924 /// of non-record types, which never have destructors.
925 /// - Catches of record types can trigger for arbitrary subclasses
926 /// of the caught type, so we have to assume the actual thrown
927 /// exception type might have a throwing destructor, even if the
928 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +0000929 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +0000930 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
931 bool MightThrow;
932
933 void Emit(CodeGenFunction &CGF, bool IsForEH) {
934 if (!MightThrow) {
935 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
936 return;
937 }
938
939 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
940 }
941 };
942}
943
John McCallf1549f62010-07-06 01:34:17 +0000944/// Emits a call to __cxa_begin_catch and enters a cleanup to call
945/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +0000946///
947/// \param EndMightThrow - true if __cxa_end_catch might throw
948static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
949 llvm::Value *Exn,
950 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +0000951 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
952 Call->setDoesNotThrow();
953
John McCall1f0fca52010-07-21 07:22:38 +0000954 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +0000955
956 return Call;
957}
958
959/// A "special initializer" callback for initializing a catch
960/// parameter during catch initialization.
961static void InitCatchParam(CodeGenFunction &CGF,
962 const VarDecl &CatchParam,
963 llvm::Value *ParamAddr) {
964 // Load the exception from where the landing pad saved it.
965 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
966
967 CanQualType CatchType =
968 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
969 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
970
971 // If we're catching by reference, we can just cast the object
972 // pointer to the appropriate pointer.
973 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +0000974 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
975 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +0000976
John McCallf1549f62010-07-06 01:34:17 +0000977 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +0000978 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +0000979
980 // We have no way to tell the personality function that we're
981 // catching by reference, so if we're catching a pointer,
982 // __cxa_begin_catch will actually return that pointer by value.
983 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
984 QualType PointeeType = PT->getPointeeType();
985
986 // When catching by reference, generally we should just ignore
987 // this by-value pointer and use the exception object instead.
988 if (!PointeeType->isRecordType()) {
989
990 // Exn points to the struct _Unwind_Exception header, which
991 // we have to skip past in order to reach the exception data.
992 unsigned HeaderSize =
993 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
994 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
995
996 // However, if we're catching a pointer-to-record type that won't
997 // work, because the personality function might have adjusted
998 // the pointer. There's actually no way for us to fully satisfy
999 // the language/ABI contract here: we can't use Exn because it
1000 // might have the wrong adjustment, but we can't use the by-value
1001 // pointer because it's off by a level of abstraction.
1002 //
1003 // The current solution is to dump the adjusted pointer into an
1004 // alloca, which breaks language semantics (because changing the
1005 // pointer doesn't change the exception) but at least works.
1006 // The better solution would be to filter out non-exact matches
1007 // and rethrow them, but this is tricky because the rethrow
1008 // really needs to be catchable by other sites at this landing
1009 // pad. The best solution is to fix the personality function.
1010 } else {
1011 // Pull the pointer for the reference type off.
1012 const llvm::Type *PtrTy =
1013 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1014
1015 // Create the temporary and write the adjusted pointer into it.
1016 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1017 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1018 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1019
1020 // Bind the reference to the temporary.
1021 AdjustedExn = ExnPtrTmp;
1022 }
1023 }
1024
John McCallf1549f62010-07-06 01:34:17 +00001025 llvm::Value *ExnCast =
1026 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1027 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1028 return;
1029 }
1030
1031 // Non-aggregates (plus complexes).
1032 bool IsComplex = false;
1033 if (!CGF.hasAggregateLLVMType(CatchType) ||
1034 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +00001035 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001036
1037 // If the catch type is a pointer type, __cxa_begin_catch returns
1038 // the pointer by value.
1039 if (CatchType->hasPointerRepresentation()) {
1040 llvm::Value *CastExn =
1041 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1042 CGF.Builder.CreateStore(CastExn, ParamAddr);
1043 return;
1044 }
1045
1046 // Otherwise, it returns a pointer into the exception object.
1047
1048 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1049 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1050
1051 if (IsComplex) {
1052 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1053 ParamAddr, /*volatile*/ false);
1054 } else {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001055 unsigned Alignment =
1056 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallf1549f62010-07-06 01:34:17 +00001057 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001058 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1059 CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001060 }
1061 return;
1062 }
1063
John McCallacff6962011-02-16 08:39:19 +00001064 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallf1549f62010-07-06 01:34:17 +00001065
1066 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1067
John McCallacff6962011-02-16 08:39:19 +00001068 // Check for a copy expression. If we don't have a copy expression,
1069 // that means a trivial copy is okay.
John McCalle996ffd2011-02-16 08:02:54 +00001070 const Expr *copyExpr = CatchParam.getInit();
1071 if (!copyExpr) {
John McCallacff6962011-02-16 08:39:19 +00001072 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1073 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1074 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001075 return;
1076 }
1077
1078 // We have to call __cxa_get_exception_ptr to get the adjusted
1079 // pointer before copying.
John McCalle996ffd2011-02-16 08:02:54 +00001080 llvm::CallInst *rawAdjustedExn =
John McCallf1549f62010-07-06 01:34:17 +00001081 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
John McCalle996ffd2011-02-16 08:02:54 +00001082 rawAdjustedExn->setDoesNotThrow();
John McCallf1549f62010-07-06 01:34:17 +00001083
John McCalle996ffd2011-02-16 08:02:54 +00001084 // Cast that to the appropriate type.
1085 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallf1549f62010-07-06 01:34:17 +00001086
John McCalle996ffd2011-02-16 08:02:54 +00001087 // The copy expression is defined in terms of an OpaqueValueExpr.
1088 // Find it and map it to the adjusted expression.
1089 CodeGenFunction::OpaqueValueMapping
John McCall56ca35d2011-02-17 10:25:35 +00001090 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1091 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallf1549f62010-07-06 01:34:17 +00001092
1093 // Call the copy ctor in a terminate scope.
1094 CGF.EHStack.pushTerminate();
John McCalle996ffd2011-02-16 08:02:54 +00001095
1096 // Perform the copy construction.
John McCallf85e1932011-06-15 23:02:42 +00001097 CGF.EmitAggExpr(copyExpr, AggValueSlot::forAddr(ParamAddr, Qualifiers(),
1098 false));
John McCalle996ffd2011-02-16 08:02:54 +00001099
1100 // Leave the terminate scope.
John McCallf1549f62010-07-06 01:34:17 +00001101 CGF.EHStack.popTerminate();
1102
John McCalle996ffd2011-02-16 08:02:54 +00001103 // Undo the opaque value mapping.
1104 opaque.pop();
1105
John McCallf1549f62010-07-06 01:34:17 +00001106 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001107 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001108}
1109
1110/// Begins a catch statement by initializing the catch variable and
1111/// calling __cxa_begin_catch.
John McCalle996ffd2011-02-16 08:02:54 +00001112static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallf1549f62010-07-06 01:34:17 +00001113 // We have to be very careful with the ordering of cleanups here:
1114 // C++ [except.throw]p4:
1115 // The destruction [of the exception temporary] occurs
1116 // immediately after the destruction of the object declared in
1117 // the exception-declaration in the handler.
1118 //
1119 // So the precise ordering is:
1120 // 1. Construct catch variable.
1121 // 2. __cxa_begin_catch
1122 // 3. Enter __cxa_end_catch cleanup
1123 // 4. Enter dtor cleanup
1124 //
John McCall34695852011-02-22 06:44:22 +00001125 // We do this by using a slightly abnormal initialization process.
1126 // Delegation sequence:
John McCallf1549f62010-07-06 01:34:17 +00001127 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCall34695852011-02-22 06:44:22 +00001128 // - EmitAutoVarAlloca creates the variable and debug info
John McCallf1549f62010-07-06 01:34:17 +00001129 // - InitCatchParam initializes the variable from the exception
John McCall34695852011-02-22 06:44:22 +00001130 // - CallBeginCatch calls __cxa_begin_catch
1131 // - CallBeginCatch enters the __cxa_end_catch cleanup
1132 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallf1549f62010-07-06 01:34:17 +00001133 // - EmitCXXTryStmt emits the code for the catch body
1134 // - EmitCXXTryStmt close the RunCleanupsScope
1135
1136 VarDecl *CatchParam = S->getExceptionDecl();
1137 if (!CatchParam) {
1138 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall8e3f8612010-07-13 22:12:14 +00001139 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001140 return;
1141 }
1142
1143 // Emit the local.
John McCall34695852011-02-22 06:44:22 +00001144 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1145 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
1146 CGF.EmitAutoVarCleanups(var);
John McCall9fc6a772010-02-19 09:25:03 +00001147}
1148
John McCallfcd5c0c2010-07-13 22:24:23 +00001149namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001150 struct CallRethrow : EHScopeStack::Cleanup {
John McCallfcd5c0c2010-07-13 22:24:23 +00001151 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1152 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1153 }
1154 };
1155}
1156
John McCall59a70002010-07-07 06:56:46 +00001157void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001158 unsigned NumHandlers = S.getNumHandlers();
1159 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1160 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001161
John McCallf1549f62010-07-06 01:34:17 +00001162 // Copy the handler blocks off before we pop the EH stack. Emitting
1163 // the handlers might scribble on this memory.
1164 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1165 memcpy(Handlers.data(), CatchScope.begin(),
1166 NumHandlers * sizeof(EHCatchScope::Handler));
1167 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001168
John McCallf1549f62010-07-06 01:34:17 +00001169 // The fall-through block.
1170 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001171
John McCallf1549f62010-07-06 01:34:17 +00001172 // We just emitted the body of the try; jump to the continue block.
1173 if (HaveInsertPoint())
1174 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001175
John McCall59a70002010-07-07 06:56:46 +00001176 // Determine if we need an implicit rethrow for all these catch handlers.
1177 bool ImplicitRethrow = false;
1178 if (IsFnTryBlock)
1179 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1180 isa<CXXConstructorDecl>(CurCodeDecl);
1181
John McCallf1549f62010-07-06 01:34:17 +00001182 for (unsigned I = 0; I != NumHandlers; ++I) {
1183 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1184 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001185
John McCallf1549f62010-07-06 01:34:17 +00001186 // Catch the exception if this isn't a catch-all.
1187 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001188
John McCallf1549f62010-07-06 01:34:17 +00001189 // Enter a cleanup scope, including the catch variable and the
1190 // end-catch.
1191 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001192
John McCallf1549f62010-07-06 01:34:17 +00001193 // Initialize the catch variable and set up the cleanups.
1194 BeginCatch(*this, C);
1195
John McCall59a70002010-07-07 06:56:46 +00001196 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001197 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1198 // called, and so it is pushed after BeginCatch.
1199 if (ImplicitRethrow)
John McCall1f0fca52010-07-21 07:22:38 +00001200 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001201
John McCallf1549f62010-07-06 01:34:17 +00001202 // Perform the body of the catch.
1203 EmitStmt(C->getHandlerBlock());
1204
1205 // Fall out through the catch cleanups.
1206 CatchScope.ForceCleanup();
1207
1208 // Branch out of the try.
1209 if (HaveInsertPoint())
1210 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001211 }
1212
John McCallf1549f62010-07-06 01:34:17 +00001213 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001214}
Mike Stumpd88ea562009-12-09 03:35:49 +00001215
John McCall55b20fc2010-07-21 00:52:03 +00001216namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001217 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001218 llvm::Value *ForEHVar;
1219 llvm::Value *EndCatchFn;
1220 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1221 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1222
1223 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1224 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1225 llvm::BasicBlock *CleanupContBB =
1226 CGF.createBasicBlock("finally.cleanup.cont");
1227
1228 llvm::Value *ShouldEndCatch =
1229 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1230 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1231 CGF.EmitBlock(EndCatchBB);
1232 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1233 CGF.EmitBlock(CleanupContBB);
1234 }
1235 };
John McCall77199712010-07-21 05:47:49 +00001236
John McCall1f0fca52010-07-21 07:22:38 +00001237 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001238 const Stmt *Body;
1239 llvm::Value *ForEHVar;
1240 llvm::Value *EndCatchFn;
1241 llvm::Value *RethrowFn;
1242 llvm::Value *SavedExnVar;
1243
1244 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1245 llvm::Value *EndCatchFn,
1246 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1247 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1248 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1249
1250 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1251 // Enter a cleanup to call the end-catch function if one was provided.
1252 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001253 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1254 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001255
John McCalld96a8e72010-08-11 00:16:14 +00001256 // Save the current cleanup destination in case there are
1257 // cleanups in the finally block.
1258 llvm::Value *SavedCleanupDest =
1259 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1260 "cleanup.dest.saved");
1261
John McCall77199712010-07-21 05:47:49 +00001262 // Emit the finally block.
1263 CGF.EmitStmt(Body);
1264
1265 // If the end of the finally is reachable, check whether this was
1266 // for EH. If so, rethrow.
1267 if (CGF.HaveInsertPoint()) {
1268 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1269 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1270
1271 llvm::Value *ShouldRethrow =
1272 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1273 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1274
1275 CGF.EmitBlock(RethrowBB);
1276 if (SavedExnVar) {
1277 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1278 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1279 } else {
1280 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1281 }
1282 CGF.Builder.CreateUnreachable();
1283
1284 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001285
1286 // Restore the cleanup destination.
1287 CGF.Builder.CreateStore(SavedCleanupDest,
1288 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001289 }
1290
1291 // Leave the end-catch cleanup. As an optimization, pretend that
1292 // the fallthrough path was inaccessible; we've dynamically proven
1293 // that we're not in the EH case along that path.
1294 if (EndCatchFn) {
1295 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1296 CGF.PopCleanupBlock();
1297 CGF.Builder.restoreIP(SavedIP);
1298 }
1299
1300 // Now make sure we actually have an insertion point or the
1301 // cleanup gods will hate us.
1302 CGF.EnsureInsertPoint();
1303 }
1304 };
John McCall55b20fc2010-07-21 00:52:03 +00001305}
1306
John McCallf1549f62010-07-06 01:34:17 +00001307/// Enters a finally block for an implementation using zero-cost
1308/// exceptions. This is mostly general, but hard-codes some
1309/// language/ABI-specific behavior in the catch-all sections.
John McCalld768e9d2011-06-22 02:32:12 +00001310void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1311 const Stmt *body,
1312 llvm::Constant *beginCatchFn,
1313 llvm::Constant *endCatchFn,
1314 llvm::Constant *rethrowFn) {
1315 assert((beginCatchFn != 0) == (endCatchFn != 0) &&
John McCallf1549f62010-07-06 01:34:17 +00001316 "begin/end catch functions not paired");
John McCalld768e9d2011-06-22 02:32:12 +00001317 assert(rethrowFn && "rethrow function is required");
1318
1319 BeginCatchFn = beginCatchFn;
Mike Stumpd88ea562009-12-09 03:35:49 +00001320
John McCallf1549f62010-07-06 01:34:17 +00001321 // The rethrow function has one of the following two types:
1322 // void (*)()
1323 // void (*)(void*)
1324 // In the latter case we need to pass it the exception object.
1325 // But we can't use the exception slot because the @finally might
1326 // have a landing pad (which would overwrite the exception slot).
John McCalld768e9d2011-06-22 02:32:12 +00001327 const llvm::FunctionType *rethrowFnTy =
John McCallf1549f62010-07-06 01:34:17 +00001328 cast<llvm::FunctionType>(
John McCalld768e9d2011-06-22 02:32:12 +00001329 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1330 SavedExnVar = 0;
1331 if (rethrowFnTy->getNumParams())
1332 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001333
John McCallf1549f62010-07-06 01:34:17 +00001334 // A finally block is a statement which must be executed on any edge
1335 // out of a given scope. Unlike a cleanup, the finally block may
1336 // contain arbitrary control flow leading out of itself. In
1337 // addition, finally blocks should always be executed, even if there
1338 // are no catch handlers higher on the stack. Therefore, we
1339 // surround the protected scope with a combination of a normal
1340 // cleanup (to catch attempts to break out of the block via normal
1341 // control flow) and an EH catch-all (semantically "outside" any try
1342 // statement to which the finally block might have been attached).
1343 // The finally block itself is generated in the context of a cleanup
1344 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001345
John McCallf1549f62010-07-06 01:34:17 +00001346 // Jump destination for performing the finally block on an exception
1347 // edge. We'll never actually reach this block, so unreachable is
1348 // fine.
John McCalld768e9d2011-06-22 02:32:12 +00001349 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001350
John McCallf1549f62010-07-06 01:34:17 +00001351 // Whether the finally block is being executed for EH purposes.
John McCalld768e9d2011-06-22 02:32:12 +00001352 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1353 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpd88ea562009-12-09 03:35:49 +00001354
John McCallf1549f62010-07-06 01:34:17 +00001355 // Enter a normal cleanup which will perform the @finally block.
John McCalld768e9d2011-06-22 02:32:12 +00001356 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1357 ForEHVar, endCatchFn,
1358 rethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001359
1360 // Enter a catch-all scope.
John McCalld768e9d2011-06-22 02:32:12 +00001361 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1362 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1363 catchScope->setCatchAllHandler(0, catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001364}
1365
John McCalld768e9d2011-06-22 02:32:12 +00001366void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +00001367 // Leave the finally catch-all.
John McCalld768e9d2011-06-22 02:32:12 +00001368 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1369 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1370 CGF.EHStack.popCatch();
John McCallf1549f62010-07-06 01:34:17 +00001371
John McCalld768e9d2011-06-22 02:32:12 +00001372 // If there are any references to the catch-all block, emit it.
1373 if (catchBB->use_empty()) {
1374 delete catchBB;
1375 } else {
1376 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1377 CGF.EmitBlock(catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001378
John McCalld768e9d2011-06-22 02:32:12 +00001379 llvm::Value *exn = 0;
John McCallf1549f62010-07-06 01:34:17 +00001380
John McCalld768e9d2011-06-22 02:32:12 +00001381 // If there's a begin-catch function, call it.
1382 if (BeginCatchFn) {
1383 exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
1384 CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
1385 }
1386
1387 // If we need to remember the exception pointer to rethrow later, do so.
1388 if (SavedExnVar) {
1389 if (!exn) exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
1390 CGF.Builder.CreateStore(exn, SavedExnVar);
1391 }
1392
1393 // Tell the cleanups in the finally block that we're do this for EH.
1394 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1395
1396 // Thread a jump through the finally cleanup.
1397 CGF.EmitBranchThroughCleanup(RethrowDest);
1398
1399 CGF.Builder.restoreIP(savedIP);
1400 }
1401
1402 // Finally, leave the @finally cleanup.
1403 CGF.PopCleanupBlock();
John McCallf1549f62010-07-06 01:34:17 +00001404}
1405
1406llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1407 if (TerminateLandingPad)
1408 return TerminateLandingPad;
1409
1410 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1411
1412 // This will get inserted at the end of the function.
1413 TerminateLandingPad = createBasicBlock("terminate.lpad");
1414 Builder.SetInsertPoint(TerminateLandingPad);
1415
1416 // Tell the backend that this is a landing pad.
1417 llvm::CallInst *Exn =
1418 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1419 Exn->setDoesNotThrow();
John McCall8262b6a2010-07-17 00:43:08 +00001420
1421 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallf1549f62010-07-06 01:34:17 +00001422
1423 // Tell the backend what the exception table should be:
1424 // nothing but a catch-all.
John McCallb2593832010-09-16 06:16:50 +00001425 llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
John McCallf1549f62010-07-06 01:34:17 +00001426 getCatchAllValue(*this) };
1427 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1428 Args, Args+3, "eh.selector")
1429 ->setDoesNotThrow();
1430
1431 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1432 TerminateCall->setDoesNotReturn();
1433 TerminateCall->setDoesNotThrow();
John McCalld16c2cf2011-02-08 08:22:06 +00001434 Builder.CreateUnreachable();
Mike Stumpd88ea562009-12-09 03:35:49 +00001435
John McCallf1549f62010-07-06 01:34:17 +00001436 // Restore the saved insertion state.
1437 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001438
John McCallf1549f62010-07-06 01:34:17 +00001439 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001440}
Mike Stump9b39c512009-12-09 22:59:31 +00001441
1442llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001443 if (TerminateHandler)
1444 return TerminateHandler;
1445
John McCallf1549f62010-07-06 01:34:17 +00001446 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001447
John McCallf1549f62010-07-06 01:34:17 +00001448 // Set up the terminate handler. This block is inserted at the very
1449 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001450 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001451 Builder.SetInsertPoint(TerminateHandler);
1452 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001453 TerminateCall->setDoesNotReturn();
1454 TerminateCall->setDoesNotThrow();
1455 Builder.CreateUnreachable();
1456
John McCall3d3ec1c2010-04-21 10:05:39 +00001457 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001458 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001459
Mike Stump9b39c512009-12-09 22:59:31 +00001460 return TerminateHandler;
1461}
John McCallf1549f62010-07-06 01:34:17 +00001462
John McCallff8e1152010-07-23 21:56:41 +00001463CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1464 if (RethrowBlock.isValid()) return RethrowBlock;
1465
1466 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1467
1468 // We emit a jump to a notional label at the outermost unwind state.
1469 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1470 Builder.SetInsertPoint(Unwind);
1471
1472 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1473
1474 // This can always be a call because we necessarily didn't find
1475 // anything on the EH stack which needs our help.
John McCallb2593832010-09-16 06:16:50 +00001476 llvm::StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCall93c332a2011-05-28 21:13:02 +00001477 if (!RethrowName.empty()) {
1478 Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
1479 Builder.CreateLoad(getExceptionSlot()))
1480 ->setDoesNotReturn();
1481 } else {
1482 llvm::Value *Exn = Builder.CreateLoad(getExceptionSlot());
John McCallff8e1152010-07-23 21:56:41 +00001483
John McCall93c332a2011-05-28 21:13:02 +00001484 switch (CleanupHackLevel) {
1485 case CHL_MandatoryCatchall:
1486 // In mandatory-catchall mode, we need to use
1487 // _Unwind_Resume_or_Rethrow, or whatever the personality's
1488 // equivalent is.
1489 Builder.CreateCall(getUnwindResumeOrRethrowFn(), Exn)
1490 ->setDoesNotReturn();
1491 break;
1492 case CHL_MandatoryCleanup: {
1493 // In mandatory-cleanup mode, we should use llvm.eh.resume.
1494 llvm::Value *Selector = Builder.CreateLoad(getEHSelectorSlot());
1495 Builder.CreateCall2(CGM.getIntrinsic(llvm::Intrinsic::eh_resume),
1496 Exn, Selector)
1497 ->setDoesNotReturn();
1498 break;
1499 }
1500 case CHL_Ideal:
1501 // In an idealized mode where we don't have to worry about the
1502 // optimizer combining landing pads, we should just use
1503 // _Unwind_Resume (or the personality's equivalent).
1504 Builder.CreateCall(getUnwindResumeFn(), Exn)
1505 ->setDoesNotReturn();
1506 break;
1507 }
1508 }
1509
John McCallff8e1152010-07-23 21:56:41 +00001510 Builder.CreateUnreachable();
1511
1512 Builder.restoreIP(SavedIP);
1513
1514 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1515 return RethrowBlock;
1516}
1517