blob: 35429e3b8415de1048464e33f6726188f01cf30b [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
John McCall61c16012011-07-10 20:11:30 +000032 llvm::Type *ArgTys[] = { CGF.SizeTy };
Mike Stump8755ec32009-12-10 00:06:18 +000033 const llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +000034 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTys, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000035
Anders Carlssond3379292009-10-30 02:27:02 +000036 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
37}
38
Mike Stump99533832009-12-02 07:41:41 +000039static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
40 // void __cxa_free_exception(void *thrown_exception);
Mike Stump8755ec32009-12-10 00:06:18 +000041
John McCall61c16012011-07-10 20:11:30 +000042 llvm::Type *ArgTys[] = { CGF.Int8PtrTy };
Mike Stump8755ec32009-12-10 00:06:18 +000043 const llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +000044 llvm::FunctionType::get(CGF.VoidTy, ArgTys, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000045
Mike Stump99533832009-12-02 07:41:41 +000046 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
47}
48
Anders Carlssond3379292009-10-30 02:27:02 +000049static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +000050 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +000051 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +000052
John McCall61c16012011-07-10 20:11:30 +000053 llvm::Type *Args[3] = { CGF.Int8PtrTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
Mike Stump8755ec32009-12-10 00:06:18 +000054 const llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +000055 llvm::FunctionType::get(CGF.VoidTy, Args, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000056
Anders Carlssond3379292009-10-30 02:27:02 +000057 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
58}
59
Mike Stumpb4eea692009-11-20 00:56:31 +000060static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +000061 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +000062
Mike Stump8755ec32009-12-10 00:06:18 +000063 const llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +000064 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000065
Mike Stumpb4eea692009-11-20 00:56:31 +000066 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
67}
68
John McCallf1549f62010-07-06 01:34:17 +000069static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
70 // void *__cxa_get_exception_ptr(void*);
John McCallf1549f62010-07-06 01:34:17 +000071
John McCall61c16012011-07-10 20:11:30 +000072 llvm::Type *ArgTys[] = { CGF.Int8PtrTy };
John McCallf1549f62010-07-06 01:34:17 +000073 const llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +000074 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTys, /*IsVarArgs=*/false);
John McCallf1549f62010-07-06 01:34:17 +000075
76 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
77}
78
Mike Stump2bf701e2009-11-20 23:44:51 +000079static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +000080 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +000081
John McCall61c16012011-07-10 20:11:30 +000082 llvm::Type *ArgTys[] = { CGF.Int8PtrTy };
Mike Stump8755ec32009-12-10 00:06:18 +000083 const llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +000084 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTys, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000085
Mike Stump2bf701e2009-11-20 23:44:51 +000086 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
87}
88
89static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +000090 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +000091
Mike Stump8755ec32009-12-10 00:06:18 +000092 const llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +000093 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000094
Mike Stump2bf701e2009-11-20 23:44:51 +000095 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
96}
97
Mike Stumpcce3d4f2009-12-07 23:38:24 +000098static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
99 // void __cxa_call_unexepcted(void *thrown_exception);
100
John McCall61c16012011-07-10 20:11:30 +0000101 llvm::Type *ArgTys[] = { CGF.Int8PtrTy };
Mike Stump8755ec32009-12-10 00:06:18 +0000102 const llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +0000103 llvm::FunctionType::get(CGF.VoidTy, ArgTys, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000104
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000105 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
106}
107
John McCall93c332a2011-05-28 21:13:02 +0000108llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000109 llvm::Type *ArgTys[] = { Int8PtrTy };
John McCall09034212011-05-27 20:01:14 +0000110 const llvm::FunctionType *FTy =
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000111 llvm::FunctionType::get(VoidTy, ArgTys, /*IsVarArgs=*/false);
John McCall93c332a2011-05-28 21:13:02 +0000112
113 if (CGM.getLangOptions().SjLjExceptions)
114 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
115 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
116}
117
118llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000119 llvm::Type *ArgTys[] = { Int8PtrTy };
John McCall93c332a2011-05-28 21:13:02 +0000120 const llvm::FunctionType *FTy =
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000121 llvm::FunctionType::get(VoidTy, ArgTys, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000122
Douglas Gregor86a3a032010-05-16 01:24:12 +0000123 if (CGM.getLangOptions().SjLjExceptions)
John McCalla5f2de22010-08-11 20:59:53 +0000124 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor86a3a032010-05-16 01:24:12 +0000125 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000126}
127
Mike Stump99533832009-12-02 07:41:41 +0000128static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
129 // void __terminate();
130
Mike Stump8755ec32009-12-10 00:06:18 +0000131 const llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +0000132 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000133
John McCall256a76e2011-07-06 01:22:26 +0000134 llvm::StringRef name;
135
136 // In C++, use std::terminate().
137 if (CGF.getLangOptions().CPlusPlus)
138 name = "_ZSt9terminatev"; // FIXME: mangling!
139 else if (CGF.getLangOptions().ObjC1 &&
140 CGF.CGM.getCodeGenOpts().ObjCRuntimeHasTerminate)
141 name = "objc_terminate";
142 else
143 name = "abort";
144 return CGF.CGM.CreateRuntimeFunction(FTy, name);
David Chisnall79a9ad82010-05-17 13:49:20 +0000145}
146
John McCall8262b6a2010-07-17 00:43:08 +0000147static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
John McCallb2593832010-09-16 06:16:50 +0000148 llvm::StringRef Name) {
John McCall61c16012011-07-10 20:11:30 +0000149 llvm::Type *ArgTys[] = { CGF.Int8PtrTy };
150 const llvm::FunctionType *FTy =
151 llvm::FunctionType::get(CGF.VoidTy, ArgTys, /*IsVarArgs=*/false);
John McCall8262b6a2010-07-17 00:43:08 +0000152
153 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000154}
155
John McCall8262b6a2010-07-17 00:43:08 +0000156const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
John McCall44680782010-11-07 02:35:25 +0000157const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
John McCall8262b6a2010-07-17 00:43:08 +0000158const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
159const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
160const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
161const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
162 "objc_exception_throw");
David Chisnall80558d22011-03-20 21:35:39 +0000163const EHPersonality EHPersonality::GNU_ObjCXX("__gnustep_objcxx_personality_v0");
John McCall8262b6a2010-07-17 00:43:08 +0000164
165static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000166 if (L.SjLjExceptions)
167 return EHPersonality::GNU_C_SJLJ;
John McCall8262b6a2010-07-17 00:43:08 +0000168 return EHPersonality::GNU_C;
169}
170
171static const EHPersonality &getObjCPersonality(const LangOptions &L) {
172 if (L.NeXTRuntime) {
173 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
174 else return getCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000175 } else {
John McCall8262b6a2010-07-17 00:43:08 +0000176 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000177 }
178}
179
John McCall8262b6a2010-07-17 00:43:08 +0000180static const EHPersonality &getCXXPersonality(const LangOptions &L) {
181 if (L.SjLjExceptions)
182 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000183 else
John McCall8262b6a2010-07-17 00:43:08 +0000184 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000185}
186
187/// Determines the personality function to use when both C++
188/// and Objective-C exceptions are being caught.
John McCall8262b6a2010-07-17 00:43:08 +0000189static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallf1549f62010-07-06 01:34:17 +0000190 // The ObjC personality defers to the C++ personality for non-ObjC
191 // handlers. Unlike the C++ case, we use the same personality
192 // function on targets using (backend-driven) SJLJ EH.
John McCall8262b6a2010-07-17 00:43:08 +0000193 if (L.NeXTRuntime) {
194 if (L.ObjCNonFragileABI)
195 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000196
197 // In the fragile ABI, just use C++ exception handling and hope
198 // they're not doing crazy exception mixing.
199 else
John McCall8262b6a2010-07-17 00:43:08 +0000200 return getCXXPersonality(L);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000201 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000202
John McCall8262b6a2010-07-17 00:43:08 +0000203 // The GNU runtime's personality function inherently doesn't support
204 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnall80558d22011-03-20 21:35:39 +0000205 return EHPersonality::GNU_ObjCXX;
John McCallf1549f62010-07-06 01:34:17 +0000206}
207
John McCall8262b6a2010-07-17 00:43:08 +0000208const EHPersonality &EHPersonality::get(const LangOptions &L) {
209 if (L.CPlusPlus && L.ObjC1)
210 return getObjCXXPersonality(L);
211 else if (L.CPlusPlus)
212 return getCXXPersonality(L);
213 else if (L.ObjC1)
214 return getObjCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000215 else
John McCall8262b6a2010-07-17 00:43:08 +0000216 return getCPersonality(L);
217}
John McCallf1549f62010-07-06 01:34:17 +0000218
John McCallb2593832010-09-16 06:16:50 +0000219static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000220 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000221 llvm::Constant *Fn =
John McCallb2593832010-09-16 06:16:50 +0000222 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
223 llvm::Type::getInt32Ty(CGM.getLLVMContext()),
224 true),
225 Personality.getPersonalityFnName());
226 return Fn;
227}
228
229static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
230 const EHPersonality &Personality) {
231 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCalld16c2cf2011-02-08 08:22:06 +0000232 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCallb2593832010-09-16 06:16:50 +0000233}
234
235/// Check whether a personality function could reasonably be swapped
236/// for a C++ personality function.
237static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
238 for (llvm::Constant::use_iterator
239 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
240 llvm::User *User = *I;
241
242 // Conditionally white-list bitcasts.
243 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
244 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
245 if (!PersonalityHasOnlyCXXUses(CE))
246 return false;
247 continue;
248 }
249
250 // Otherwise, it has to be a selector call.
251 if (!isa<llvm::EHSelectorInst>(User)) return false;
252
253 llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
254 for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
255 // Look for something that would've been returned by the ObjC
256 // runtime's GetEHType() method.
257 llvm::GlobalVariable *GV
258 = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
259 if (!GV) continue;
260
261 // ObjC EH selector entries are always global variables with
262 // names starting like this.
263 if (GV->getName().startswith("OBJC_EHTYPE"))
264 return false;
265 }
266 }
267
268 return true;
269}
270
271/// Try to use the C++ personality function in ObjC++. Not doing this
272/// can cause some incompatibilities with gcc, which is more
273/// aggressive about only using the ObjC++ personality in a function
274/// when it really needs it.
275void CodeGenModule::SimplifyPersonality() {
276 // For now, this is really a Darwin-specific operation.
Daniel Dunbareab80782011-04-26 19:43:00 +0000277 if (!Context.Target.getTriple().isOSDarwin())
John McCallb2593832010-09-16 06:16:50 +0000278 return;
279
280 // If we're not in ObjC++ -fexceptions, there's nothing to do.
281 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
282 return;
283
284 const EHPersonality &ObjCXX = EHPersonality::get(Features);
285 const EHPersonality &CXX = getCXXPersonality(Features);
286 if (&ObjCXX == &CXX ||
287 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
288 return;
289
290 llvm::Function *Fn =
291 getModule().getFunction(ObjCXX.getPersonalityFnName());
292
293 // Nothing to do if it's unused.
294 if (!Fn || Fn->use_empty()) return;
295
296 // Can't do the optimization if it has non-C++ uses.
297 if (!PersonalityHasOnlyCXXUses(Fn)) return;
298
299 // Create the C++ personality function and kill off the old
300 // function.
301 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
302
303 // This can happen if the user is screwing with us.
304 if (Fn->getType() != CXXFn->getType()) return;
305
306 Fn->replaceAllUsesWith(CXXFn);
307 Fn->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000308}
309
310/// Returns the value to inject into a selector to indicate the
311/// presence of a catch-all.
312static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
313 // Possibly we should use @llvm.eh.catch.all.value here.
John McCalld16c2cf2011-02-08 08:22:06 +0000314 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallf1549f62010-07-06 01:34:17 +0000315}
316
317/// Returns the value to inject into a selector to indicate the
318/// presence of a cleanup.
319static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
320 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000321}
322
John McCall09faeab2010-07-13 21:17:51 +0000323namespace {
324 /// A cleanup to free the exception object if its initialization
325 /// throws.
John McCall3ad32c82011-01-28 08:37:24 +0000326 struct FreeException {
327 static void Emit(CodeGenFunction &CGF, bool forEH,
328 llvm::Value *exn) {
329 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
John McCall09faeab2010-07-13 21:17:51 +0000330 ->setDoesNotThrow();
John McCall09faeab2010-07-13 21:17:51 +0000331 }
332 };
333}
334
John McCallac418162010-04-22 01:10:34 +0000335// Emits an exception expression into the given location. This
336// differs from EmitAnyExprToMem only in that, if a final copy-ctor
337// call is required, an exception within that copy ctor causes
338// std::terminate to be invoked.
John McCall3ad32c82011-01-28 08:37:24 +0000339static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
340 llvm::Value *addr) {
John McCallf1549f62010-07-06 01:34:17 +0000341 // Make sure the exception object is cleaned up if there's an
342 // exception during initialization.
John McCall3ad32c82011-01-28 08:37:24 +0000343 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
344 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000345
346 // __cxa_allocate_exception returns a void*; we need to cast this
347 // to the appropriate type for the object.
John McCall3ad32c82011-01-28 08:37:24 +0000348 const llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
349 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCallac418162010-04-22 01:10:34 +0000350
351 // FIXME: this isn't quite right! If there's a final unelided call
352 // to a copy constructor, then according to [except.terminate]p1 we
353 // must call std::terminate() if that constructor throws, because
354 // technically that copy occurs after the exception expression is
355 // evaluated but before the exception is caught. But the best way
356 // to handle that is to teach EmitAggExpr to do the final copy
357 // differently if it can't be elided.
John McCallf85e1932011-06-15 23:02:42 +0000358 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
359 /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000360
John McCall3ad32c82011-01-28 08:37:24 +0000361 // Deactivate the cleanup block.
362 CGF.DeactivateCleanupBlock(cleanup);
Mike Stump0f590be2009-12-01 03:41:18 +0000363}
364
John McCallf1549f62010-07-06 01:34:17 +0000365llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall93c332a2011-05-28 21:13:02 +0000366 if (!ExceptionSlot)
367 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallf1549f62010-07-06 01:34:17 +0000368 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000369}
370
John McCall93c332a2011-05-28 21:13:02 +0000371llvm::Value *CodeGenFunction::getEHSelectorSlot() {
372 if (!EHSelectorSlot)
373 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
374 return EHSelectorSlot;
375}
376
Anders Carlsson756b5c42009-10-30 01:42:31 +0000377void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000378 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000379 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000380 Builder.CreateInvoke(getReThrowFn(*this),
381 getUnreachableBlock(),
382 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000383 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000384 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000385 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000386 Builder.CreateUnreachable();
387 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000388
John McCallcd5b22e2011-01-12 03:41:02 +0000389 // throw is an expression, and the expression emitters expect us
390 // to leave ourselves at a valid insertion point.
391 EmitBlock(createBasicBlock("throw.cont"));
392
Anders Carlssond3379292009-10-30 02:27:02 +0000393 return;
394 }
Mike Stump8755ec32009-12-10 00:06:18 +0000395
Anders Carlssond3379292009-10-30 02:27:02 +0000396 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000397
Anders Carlssond3379292009-10-30 02:27:02 +0000398 // Now allocate the exception object.
399 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000400 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000401
Anders Carlssond3379292009-10-30 02:27:02 +0000402 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000403 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000404 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000405 llvm::ConstantInt::get(SizeTy, TypeSize),
406 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000407 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000408
John McCallac418162010-04-22 01:10:34 +0000409 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000410
Anders Carlssond3379292009-10-30 02:27:02 +0000411 // Now throw the exception.
Anders Carlsson82a113a2011-01-24 01:59:49 +0000412 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
413 /*ForEH=*/true);
John McCallac418162010-04-22 01:10:34 +0000414
415 // The address of the destructor. If the exception type has a
416 // trivial destructor (or isn't a record), we just pass null.
417 llvm::Constant *Dtor = 0;
418 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
419 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
420 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000421 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000422 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
423 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
424 }
425 }
426 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000427
Mike Stump0a3816e2009-12-04 01:51:45 +0000428 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000429 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000430 Builder.CreateInvoke3(getThrowFn(*this),
431 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000432 ExceptionPtr, TypeInfo, Dtor);
433 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000434 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000435 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000436 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
437 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000438 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000439 }
Mike Stump8755ec32009-12-10 00:06:18 +0000440
John McCallcd5b22e2011-01-12 03:41:02 +0000441 // throw is an expression, and the expression emitters expect us
442 // to leave ourselves at a valid insertion point.
443 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000444}
Mike Stump2bf701e2009-11-20 23:44:51 +0000445
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000446void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlsson15348ae2011-02-28 02:27:16 +0000447 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000448 return;
449
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000450 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
451 if (FD == 0)
452 return;
453 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
454 if (Proto == 0)
455 return;
456
Sebastian Redla968e972011-03-15 18:42:48 +0000457 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
458 if (isNoexceptExceptionSpec(EST)) {
459 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
460 // noexcept functions are simple terminate scopes.
461 EHStack.pushTerminate();
462 }
463 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
464 unsigned NumExceptions = Proto->getNumExceptions();
465 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000466
Sebastian Redla968e972011-03-15 18:42:48 +0000467 for (unsigned I = 0; I != NumExceptions; ++I) {
468 QualType Ty = Proto->getExceptionType(I);
469 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
470 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
471 /*ForEH=*/true);
472 Filter->setFilter(I, EHType);
473 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000474 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000475}
476
477void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlsson15348ae2011-02-28 02:27:16 +0000478 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000479 return;
480
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000481 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
482 if (FD == 0)
483 return;
484 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
485 if (Proto == 0)
486 return;
487
Sebastian Redla968e972011-03-15 18:42:48 +0000488 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
489 if (isNoexceptExceptionSpec(EST)) {
490 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
491 EHStack.popTerminate();
492 }
493 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
494 EHStack.popFilter();
495 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000496}
497
Mike Stump2bf701e2009-11-20 23:44:51 +0000498void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000499 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000500 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000501 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000502}
503
John McCall59a70002010-07-07 06:56:46 +0000504void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000505 unsigned NumHandlers = S.getNumHandlers();
506 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000507
John McCallf1549f62010-07-06 01:34:17 +0000508 for (unsigned I = 0; I != NumHandlers; ++I) {
509 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000510
John McCallf1549f62010-07-06 01:34:17 +0000511 llvm::BasicBlock *Handler = createBasicBlock("catch");
512 if (C->getExceptionDecl()) {
513 // FIXME: Dropping the reference type on the type into makes it
514 // impossible to correctly implement catch-by-reference
515 // semantics for pointers. Unfortunately, this is what all
516 // existing compilers do, and it's not clear that the standard
517 // personality routine is capable of doing this right. See C++ DR 388:
518 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
519 QualType CaughtType = C->getCaughtType();
520 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall5a180392010-07-24 00:37:23 +0000521
522 llvm::Value *TypeInfo = 0;
523 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000524 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall5a180392010-07-24 00:37:23 +0000525 else
Anders Carlsson82a113a2011-01-24 01:59:49 +0000526 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallf1549f62010-07-06 01:34:17 +0000527 CatchScope->setHandler(I, TypeInfo, Handler);
528 } else {
529 // No exception decl indicates '...', a catch-all.
530 CatchScope->setCatchAllHandler(I, Handler);
531 }
532 }
John McCallf1549f62010-07-06 01:34:17 +0000533}
534
535/// Check whether this is a non-EH scope, i.e. a scope which doesn't
536/// affect exception handling. Currently, the only non-EH scopes are
537/// normal-only cleanup scopes.
538static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000539 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000540 case EHScope::Cleanup:
541 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000542 case EHScope::Filter:
543 case EHScope::Catch:
544 case EHScope::Terminate:
545 return false;
546 }
547
548 // Suppress warning.
549 return false;
John McCallf1549f62010-07-06 01:34:17 +0000550}
551
552llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
553 assert(EHStack.requiresLandingPad());
554 assert(!EHStack.empty());
555
Anders Carlsson7a178512011-02-28 00:33:03 +0000556 if (!CGM.getLangOptions().Exceptions)
John McCallda65ea82010-07-13 20:32:21 +0000557 return 0;
558
John McCallf1549f62010-07-06 01:34:17 +0000559 // Check the innermost scope for a cached landing pad. If this is
560 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
561 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
562 if (LP) return LP;
563
564 // Build the landing pad for this scope.
565 LP = EmitLandingPad();
566 assert(LP);
567
568 // Cache the landing pad on the innermost scope. If this is a
569 // non-EH scope, cache the landing pad on the enclosing scope, too.
570 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
571 ir->setCachedLandingPad(LP);
572 if (!isNonEHScope(*ir)) break;
573 }
574
575 return LP;
576}
577
John McCall93c332a2011-05-28 21:13:02 +0000578// This code contains a hack to work around a design flaw in
579// LLVM's EH IR which breaks semantics after inlining. This same
580// hack is implemented in llvm-gcc.
581//
582// The LLVM EH abstraction is basically a thin veneer over the
583// traditional GCC zero-cost design: for each range of instructions
584// in the function, there is (at most) one "landing pad" with an
585// associated chain of EH actions. A language-specific personality
586// function interprets this chain of actions and (1) decides whether
587// or not to resume execution at the landing pad and (2) if so,
588// provides an integer indicating why it's stopping. In LLVM IR,
589// the association of a landing pad with a range of instructions is
590// achieved via an invoke instruction, the chain of actions becomes
591// the arguments to the @llvm.eh.selector call, and the selector
592// call returns the integer indicator. Other than the required
593// presence of two intrinsic function calls in the landing pad,
594// the IR exactly describes the layout of the output code.
595//
596// A principal advantage of this design is that it is completely
597// language-agnostic; in theory, the LLVM optimizers can treat
598// landing pads neutrally, and targets need only know how to lower
599// the intrinsics to have a functioning exceptions system (assuming
600// that platform exceptions follow something approximately like the
601// GCC design). Unfortunately, landing pads cannot be combined in a
602// language-agnostic way: given selectors A and B, there is no way
603// to make a single landing pad which faithfully represents the
604// semantics of propagating an exception first through A, then
605// through B, without knowing how the personality will interpret the
606// (lowered form of the) selectors. This means that inlining has no
607// choice but to crudely chain invokes (i.e., to ignore invokes in
608// the inlined function, but to turn all unwindable calls into
609// invokes), which is only semantically valid if every unwind stops
610// at every landing pad.
611//
612// Therefore, the invoke-inline hack is to guarantee that every
613// landing pad has a catch-all.
614enum CleanupHackLevel_t {
615 /// A level of hack that requires that all landing pads have
616 /// catch-alls.
617 CHL_MandatoryCatchall,
618
619 /// A level of hack that requires that all landing pads handle
620 /// cleanups.
621 CHL_MandatoryCleanup,
622
623 /// No hacks at all; ideal IR generation.
624 CHL_Ideal
625};
626const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
627
John McCallf1549f62010-07-06 01:34:17 +0000628llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
629 assert(EHStack.requiresLandingPad());
630
John McCallf1549f62010-07-06 01:34:17 +0000631 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
632 assert(ir != EHStack.end() &&
633 "stack requiring landing pad is nothing but non-EH scopes?");
634
635 // If this is a terminate scope, just use the singleton terminate
636 // landing pad.
637 if (isa<EHTerminateScope>(*ir))
638 return getTerminateLandingPad();
639
640 // If this isn't an EH scope, iterate; otherwise break out.
641 if (!isNonEHScope(*ir)) break;
642 ++ir;
643
644 // We haven't checked this scope for a cached landing pad yet.
645 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
646 return LP;
647 }
648
649 // Save the current IR generation state.
650 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
651
John McCalld16c2cf2011-02-08 08:22:06 +0000652 const EHPersonality &Personality = EHPersonality::get(getLangOptions());
John McCall8262b6a2010-07-17 00:43:08 +0000653
John McCallf1549f62010-07-06 01:34:17 +0000654 // Create and configure the landing pad.
655 llvm::BasicBlock *LP = createBasicBlock("lpad");
656 EmitBlock(LP);
657
658 // Save the exception pointer. It's safe to use a single exception
659 // pointer per function because EH cleanups can never have nested
660 // try/catches.
661 llvm::CallInst *Exn =
662 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
663 Exn->setDoesNotThrow();
664 Builder.CreateStore(Exn, getExceptionSlot());
665
666 // Build the selector arguments.
667 llvm::SmallVector<llvm::Value*, 8> EHSelector;
668 EHSelector.push_back(Exn);
John McCallb2593832010-09-16 06:16:50 +0000669 EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
John McCallf1549f62010-07-06 01:34:17 +0000670
671 // Accumulate all the handlers in scope.
John McCallff8e1152010-07-23 21:56:41 +0000672 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
673 UnwindDest CatchAll;
John McCallf1549f62010-07-06 01:34:17 +0000674 bool HasEHCleanup = false;
675 bool HasEHFilter = false;
676 llvm::SmallVector<llvm::Value*, 8> EHFilters;
677 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
678 I != E; ++I) {
679
680 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000681 case EHScope::Cleanup:
John McCallda65ea82010-07-13 20:32:21 +0000682 if (!HasEHCleanup)
John McCall1f0fca52010-07-21 07:22:38 +0000683 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000684 // We otherwise don't care about cleanups.
685 continue;
686
John McCallf1549f62010-07-06 01:34:17 +0000687 case EHScope::Filter: {
688 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallff8e1152010-07-23 21:56:41 +0000689 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000690
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000691 // Filter scopes get added to the selector in weird ways.
John McCallf1549f62010-07-06 01:34:17 +0000692 EHFilterScope &Filter = cast<EHFilterScope>(*I);
693 HasEHFilter = true;
694
695 // Add all the filter values which we aren't already explicitly
696 // catching.
697 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
698 llvm::Value *FV = Filter.getFilter(I);
699 if (!EHHandlers.count(FV))
700 EHFilters.push_back(FV);
701 }
702 goto done;
703 }
704
705 case EHScope::Terminate:
706 // Terminate scopes are basically catch-alls.
John McCallff8e1152010-07-23 21:56:41 +0000707 assert(!CatchAll.isValid());
708 CatchAll = UnwindDest(getTerminateHandler(),
709 EHStack.getEnclosingEHCleanup(I),
710 cast<EHTerminateScope>(*I).getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000711 goto done;
712
713 case EHScope::Catch:
714 break;
715 }
716
717 EHCatchScope &Catch = cast<EHCatchScope>(*I);
718 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
719 EHCatchScope::Handler Handler = Catch.getHandler(HI);
720
721 // Catch-all. We should only have one of these per catch.
722 if (!Handler.Type) {
John McCallff8e1152010-07-23 21:56:41 +0000723 assert(!CatchAll.isValid());
724 CatchAll = UnwindDest(Handler.Block,
725 EHStack.getEnclosingEHCleanup(I),
726 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000727 continue;
728 }
729
730 // Check whether we already have a handler for this type.
John McCallff8e1152010-07-23 21:56:41 +0000731 UnwindDest &Dest = EHHandlers[Handler.Type];
732 if (Dest.isValid()) continue;
John McCallf1549f62010-07-06 01:34:17 +0000733
734 EHSelector.push_back(Handler.Type);
John McCallff8e1152010-07-23 21:56:41 +0000735 Dest = UnwindDest(Handler.Block,
736 EHStack.getEnclosingEHCleanup(I),
737 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000738 }
739
740 // Stop if we found a catch-all.
John McCallff8e1152010-07-23 21:56:41 +0000741 if (CatchAll.isValid()) break;
John McCallf1549f62010-07-06 01:34:17 +0000742 }
743
744 done:
745 unsigned LastToEmitInLoop = EHSelector.size();
746
747 // If we have a catch-all, add null to the selector.
John McCallff8e1152010-07-23 21:56:41 +0000748 if (CatchAll.isValid()) {
John McCalld16c2cf2011-02-08 08:22:06 +0000749 EHSelector.push_back(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000750
751 // If we have an EH filter, we need to add those handlers in the
752 // right place in the selector, which is to say, at the end.
753 } else if (HasEHFilter) {
754 // Create a filter expression: an integer constant saying how many
755 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
756 // followed by the filter types. The personality routine only
757 // lands here if the filter doesn't match.
758 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
759 EHFilters.size() + 1));
760 EHSelector.append(EHFilters.begin(), EHFilters.end());
761
762 // Also check whether we need a cleanup.
John McCall93c332a2011-05-28 21:13:02 +0000763 if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup)
764 EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
John McCalld16c2cf2011-02-08 08:22:06 +0000765 ? getCatchAllValue(*this)
766 : getCleanupValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000767
768 // Otherwise, signal that we at least have cleanups.
John McCall93c332a2011-05-28 21:13:02 +0000769 } else if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup) {
770 EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
John McCalld16c2cf2011-02-08 08:22:06 +0000771 ? getCatchAllValue(*this)
772 : getCleanupValue(*this));
John McCall93c332a2011-05-28 21:13:02 +0000773
774 // At the MandatoryCleanup hack level, we don't need to actually
775 // spuriously tell the unwinder that we have cleanups, but we do
776 // need to always be prepared to handle cleanups.
777 } else if (CleanupHackLevel == CHL_MandatoryCleanup) {
778 // Just don't decrement LastToEmitInLoop.
779
John McCallf1549f62010-07-06 01:34:17 +0000780 } else {
781 assert(LastToEmitInLoop > 2);
782 LastToEmitInLoop--;
783 }
784
785 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
786
787 // Tell the backend how to generate the landing pad.
788 llvm::CallInst *Selection =
789 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
790 EHSelector.begin(), EHSelector.end(), "eh.selector");
791 Selection->setDoesNotThrow();
John McCall93c332a2011-05-28 21:13:02 +0000792
793 // Save the selector value in mandatory-cleanup mode.
794 if (CleanupHackLevel == CHL_MandatoryCleanup)
795 Builder.CreateStore(Selection, getEHSelectorSlot());
John McCallf1549f62010-07-06 01:34:17 +0000796
797 // Select the right handler.
798 llvm::Value *llvm_eh_typeid_for =
799 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
800
801 // The results of llvm_eh_typeid_for aren't reliable --- at least
802 // not locally --- so we basically have to do this as an 'if' chain.
803 // We walk through the first N-1 catch clauses, testing and chaining,
804 // and then fall into the final clause (which is either a cleanup, a
805 // filter (possibly with a cleanup), a catch-all, or another catch).
806 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
807 llvm::Value *Type = EHSelector[I];
John McCallff8e1152010-07-23 21:56:41 +0000808 UnwindDest Dest = EHHandlers[Type];
809 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallf1549f62010-07-06 01:34:17 +0000810
811 // Figure out where to branch on a match. As a debug code-size
812 // optimization, if the scope depth matches the innermost cleanup,
813 // we branch directly to the catch handler.
John McCallff8e1152010-07-23 21:56:41 +0000814 llvm::BasicBlock *Match = Dest.getBlock();
815 bool MatchNeedsCleanup =
816 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +0000817 if (MatchNeedsCleanup)
818 Match = createBasicBlock("eh.match");
819
820 llvm::BasicBlock *Next = createBasicBlock("eh.next");
821
822 // Check whether the exception matches.
823 llvm::CallInst *Id
824 = Builder.CreateCall(llvm_eh_typeid_for,
John McCalld16c2cf2011-02-08 08:22:06 +0000825 Builder.CreateBitCast(Type, Int8PtrTy));
John McCallf1549f62010-07-06 01:34:17 +0000826 Id->setDoesNotThrow();
827 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
828 Match, Next);
829
830 // Emit match code if necessary.
831 if (MatchNeedsCleanup) {
832 EmitBlock(Match);
833 EmitBranchThroughEHCleanup(Dest);
834 }
835
836 // Continue to the next match.
837 EmitBlock(Next);
838 }
839
840 // Emit the final case in the selector.
841 // This might be a catch-all....
John McCallff8e1152010-07-23 21:56:41 +0000842 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000843 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
844 EmitBranchThroughEHCleanup(CatchAll);
845
846 // ...or an EH filter...
847 } else if (HasEHFilter) {
848 llvm::Value *SavedSelection = Selection;
849
850 // First, unwind out to the outermost scope if necessary.
851 if (EHStack.hasEHCleanups()) {
852 // The end here might not dominate the beginning, so we might need to
853 // save the selector if we need it.
854 llvm::AllocaInst *SelectorVar = 0;
855 if (HasEHCleanup) {
856 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
857 Builder.CreateStore(Selection, SelectorVar);
858 }
859
860 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallff8e1152010-07-23 21:56:41 +0000861 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
862 EHStack.getNextEHDestIndex()));
John McCallf1549f62010-07-06 01:34:17 +0000863 EmitBlock(CleanupContBB);
864
865 if (HasEHCleanup)
866 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
867 }
868
869 // If there was a cleanup, we'll need to actually check whether we
870 // landed here because the filter triggered.
John McCall93c332a2011-05-28 21:13:02 +0000871 if (CleanupHackLevel != CHL_Ideal || HasEHCleanup) {
John McCallf1549f62010-07-06 01:34:17 +0000872 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
873
John McCall93c332a2011-05-28 21:13:02 +0000874 llvm::Constant *Zero = llvm::ConstantInt::get(Int32Ty, 0);
John McCallf1549f62010-07-06 01:34:17 +0000875 llvm::Value *FailsFilter =
876 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
John McCall93c332a2011-05-28 21:13:02 +0000877 Builder.CreateCondBr(FailsFilter, UnexpectedBB, getRethrowDest().getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000878
879 EmitBlock(UnexpectedBB);
880 }
881
882 // Call __cxa_call_unexpected. This doesn't need to be an invoke
883 // because __cxa_call_unexpected magically filters exceptions
884 // according to the last landing pad the exception was thrown
885 // into. Seriously.
886 Builder.CreateCall(getUnexpectedFn(*this),
887 Builder.CreateLoad(getExceptionSlot()))
888 ->setDoesNotReturn();
889 Builder.CreateUnreachable();
890
891 // ...or a normal catch handler...
John McCall93c332a2011-05-28 21:13:02 +0000892 } else if (CleanupHackLevel == CHL_Ideal && !HasEHCleanup) {
John McCallf1549f62010-07-06 01:34:17 +0000893 llvm::Value *Type = EHSelector.back();
894 EmitBranchThroughEHCleanup(EHHandlers[Type]);
895
896 // ...or a cleanup.
897 } else {
John McCallff8e1152010-07-23 21:56:41 +0000898 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallf1549f62010-07-06 01:34:17 +0000899 }
900
901 // Restore the old IR generation state.
902 Builder.restoreIP(SavedIP);
903
904 return LP;
905}
906
John McCall8e3f8612010-07-13 22:12:14 +0000907namespace {
908 /// A cleanup to call __cxa_end_catch. In many cases, the caught
909 /// exception type lets us state definitively that the thrown exception
910 /// type does not have a destructor. In particular:
911 /// - Catch-alls tell us nothing, so we have to conservatively
912 /// assume that the thrown exception might have a destructor.
913 /// - Catches by reference behave according to their base types.
914 /// - Catches of non-record types will only trigger for exceptions
915 /// of non-record types, which never have destructors.
916 /// - Catches of record types can trigger for arbitrary subclasses
917 /// of the caught type, so we have to assume the actual thrown
918 /// exception type might have a throwing destructor, even if the
919 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +0000920 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +0000921 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
922 bool MightThrow;
923
924 void Emit(CodeGenFunction &CGF, bool IsForEH) {
925 if (!MightThrow) {
926 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
927 return;
928 }
929
930 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
931 }
932 };
933}
934
John McCallf1549f62010-07-06 01:34:17 +0000935/// Emits a call to __cxa_begin_catch and enters a cleanup to call
936/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +0000937///
938/// \param EndMightThrow - true if __cxa_end_catch might throw
939static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
940 llvm::Value *Exn,
941 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +0000942 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
943 Call->setDoesNotThrow();
944
John McCall1f0fca52010-07-21 07:22:38 +0000945 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +0000946
947 return Call;
948}
949
950/// A "special initializer" callback for initializing a catch
951/// parameter during catch initialization.
952static void InitCatchParam(CodeGenFunction &CGF,
953 const VarDecl &CatchParam,
954 llvm::Value *ParamAddr) {
955 // Load the exception from where the landing pad saved it.
956 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
957
958 CanQualType CatchType =
959 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
960 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
961
962 // If we're catching by reference, we can just cast the object
963 // pointer to the appropriate pointer.
964 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +0000965 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
966 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +0000967
John McCallf1549f62010-07-06 01:34:17 +0000968 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +0000969 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +0000970
971 // We have no way to tell the personality function that we're
972 // catching by reference, so if we're catching a pointer,
973 // __cxa_begin_catch will actually return that pointer by value.
974 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
975 QualType PointeeType = PT->getPointeeType();
976
977 // When catching by reference, generally we should just ignore
978 // this by-value pointer and use the exception object instead.
979 if (!PointeeType->isRecordType()) {
980
981 // Exn points to the struct _Unwind_Exception header, which
982 // we have to skip past in order to reach the exception data.
983 unsigned HeaderSize =
984 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
985 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
986
987 // However, if we're catching a pointer-to-record type that won't
988 // work, because the personality function might have adjusted
989 // the pointer. There's actually no way for us to fully satisfy
990 // the language/ABI contract here: we can't use Exn because it
991 // might have the wrong adjustment, but we can't use the by-value
992 // pointer because it's off by a level of abstraction.
993 //
994 // The current solution is to dump the adjusted pointer into an
995 // alloca, which breaks language semantics (because changing the
996 // pointer doesn't change the exception) but at least works.
997 // The better solution would be to filter out non-exact matches
998 // and rethrow them, but this is tricky because the rethrow
999 // really needs to be catchable by other sites at this landing
1000 // pad. The best solution is to fix the personality function.
1001 } else {
1002 // Pull the pointer for the reference type off.
1003 const llvm::Type *PtrTy =
1004 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1005
1006 // Create the temporary and write the adjusted pointer into it.
1007 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1008 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1009 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1010
1011 // Bind the reference to the temporary.
1012 AdjustedExn = ExnPtrTmp;
1013 }
1014 }
1015
John McCallf1549f62010-07-06 01:34:17 +00001016 llvm::Value *ExnCast =
1017 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1018 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1019 return;
1020 }
1021
1022 // Non-aggregates (plus complexes).
1023 bool IsComplex = false;
1024 if (!CGF.hasAggregateLLVMType(CatchType) ||
1025 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +00001026 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001027
1028 // If the catch type is a pointer type, __cxa_begin_catch returns
1029 // the pointer by value.
1030 if (CatchType->hasPointerRepresentation()) {
1031 llvm::Value *CastExn =
1032 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1033 CGF.Builder.CreateStore(CastExn, ParamAddr);
1034 return;
1035 }
1036
1037 // Otherwise, it returns a pointer into the exception object.
1038
1039 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1040 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1041
1042 if (IsComplex) {
1043 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1044 ParamAddr, /*volatile*/ false);
1045 } else {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001046 unsigned Alignment =
1047 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallf1549f62010-07-06 01:34:17 +00001048 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001049 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1050 CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001051 }
1052 return;
1053 }
1054
John McCallacff6962011-02-16 08:39:19 +00001055 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallf1549f62010-07-06 01:34:17 +00001056
1057 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1058
John McCallacff6962011-02-16 08:39:19 +00001059 // Check for a copy expression. If we don't have a copy expression,
1060 // that means a trivial copy is okay.
John McCalle996ffd2011-02-16 08:02:54 +00001061 const Expr *copyExpr = CatchParam.getInit();
1062 if (!copyExpr) {
John McCallacff6962011-02-16 08:39:19 +00001063 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1064 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1065 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001066 return;
1067 }
1068
1069 // We have to call __cxa_get_exception_ptr to get the adjusted
1070 // pointer before copying.
John McCalle996ffd2011-02-16 08:02:54 +00001071 llvm::CallInst *rawAdjustedExn =
John McCallf1549f62010-07-06 01:34:17 +00001072 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
John McCalle996ffd2011-02-16 08:02:54 +00001073 rawAdjustedExn->setDoesNotThrow();
John McCallf1549f62010-07-06 01:34:17 +00001074
John McCalle996ffd2011-02-16 08:02:54 +00001075 // Cast that to the appropriate type.
1076 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallf1549f62010-07-06 01:34:17 +00001077
John McCalle996ffd2011-02-16 08:02:54 +00001078 // The copy expression is defined in terms of an OpaqueValueExpr.
1079 // Find it and map it to the adjusted expression.
1080 CodeGenFunction::OpaqueValueMapping
John McCall56ca35d2011-02-17 10:25:35 +00001081 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1082 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallf1549f62010-07-06 01:34:17 +00001083
1084 // Call the copy ctor in a terminate scope.
1085 CGF.EHStack.pushTerminate();
John McCalle996ffd2011-02-16 08:02:54 +00001086
1087 // Perform the copy construction.
John McCallf85e1932011-06-15 23:02:42 +00001088 CGF.EmitAggExpr(copyExpr, AggValueSlot::forAddr(ParamAddr, Qualifiers(),
1089 false));
John McCalle996ffd2011-02-16 08:02:54 +00001090
1091 // Leave the terminate scope.
John McCallf1549f62010-07-06 01:34:17 +00001092 CGF.EHStack.popTerminate();
1093
John McCalle996ffd2011-02-16 08:02:54 +00001094 // Undo the opaque value mapping.
1095 opaque.pop();
1096
John McCallf1549f62010-07-06 01:34:17 +00001097 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001098 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001099}
1100
1101/// Begins a catch statement by initializing the catch variable and
1102/// calling __cxa_begin_catch.
John McCalle996ffd2011-02-16 08:02:54 +00001103static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallf1549f62010-07-06 01:34:17 +00001104 // We have to be very careful with the ordering of cleanups here:
1105 // C++ [except.throw]p4:
1106 // The destruction [of the exception temporary] occurs
1107 // immediately after the destruction of the object declared in
1108 // the exception-declaration in the handler.
1109 //
1110 // So the precise ordering is:
1111 // 1. Construct catch variable.
1112 // 2. __cxa_begin_catch
1113 // 3. Enter __cxa_end_catch cleanup
1114 // 4. Enter dtor cleanup
1115 //
John McCall34695852011-02-22 06:44:22 +00001116 // We do this by using a slightly abnormal initialization process.
1117 // Delegation sequence:
John McCallf1549f62010-07-06 01:34:17 +00001118 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCall34695852011-02-22 06:44:22 +00001119 // - EmitAutoVarAlloca creates the variable and debug info
John McCallf1549f62010-07-06 01:34:17 +00001120 // - InitCatchParam initializes the variable from the exception
John McCall34695852011-02-22 06:44:22 +00001121 // - CallBeginCatch calls __cxa_begin_catch
1122 // - CallBeginCatch enters the __cxa_end_catch cleanup
1123 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallf1549f62010-07-06 01:34:17 +00001124 // - EmitCXXTryStmt emits the code for the catch body
1125 // - EmitCXXTryStmt close the RunCleanupsScope
1126
1127 VarDecl *CatchParam = S->getExceptionDecl();
1128 if (!CatchParam) {
1129 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall8e3f8612010-07-13 22:12:14 +00001130 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001131 return;
1132 }
1133
1134 // Emit the local.
John McCall34695852011-02-22 06:44:22 +00001135 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1136 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
1137 CGF.EmitAutoVarCleanups(var);
John McCall9fc6a772010-02-19 09:25:03 +00001138}
1139
John McCallfcd5c0c2010-07-13 22:24:23 +00001140namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001141 struct CallRethrow : EHScopeStack::Cleanup {
John McCallfcd5c0c2010-07-13 22:24:23 +00001142 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1143 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1144 }
1145 };
1146}
1147
John McCall59a70002010-07-07 06:56:46 +00001148void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001149 unsigned NumHandlers = S.getNumHandlers();
1150 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1151 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001152
John McCallf1549f62010-07-06 01:34:17 +00001153 // Copy the handler blocks off before we pop the EH stack. Emitting
1154 // the handlers might scribble on this memory.
1155 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1156 memcpy(Handlers.data(), CatchScope.begin(),
1157 NumHandlers * sizeof(EHCatchScope::Handler));
1158 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001159
John McCallf1549f62010-07-06 01:34:17 +00001160 // The fall-through block.
1161 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001162
John McCallf1549f62010-07-06 01:34:17 +00001163 // We just emitted the body of the try; jump to the continue block.
1164 if (HaveInsertPoint())
1165 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001166
John McCall59a70002010-07-07 06:56:46 +00001167 // Determine if we need an implicit rethrow for all these catch handlers.
1168 bool ImplicitRethrow = false;
1169 if (IsFnTryBlock)
1170 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1171 isa<CXXConstructorDecl>(CurCodeDecl);
1172
John McCallf1549f62010-07-06 01:34:17 +00001173 for (unsigned I = 0; I != NumHandlers; ++I) {
1174 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1175 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001176
John McCallf1549f62010-07-06 01:34:17 +00001177 // Catch the exception if this isn't a catch-all.
1178 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001179
John McCallf1549f62010-07-06 01:34:17 +00001180 // Enter a cleanup scope, including the catch variable and the
1181 // end-catch.
1182 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001183
John McCallf1549f62010-07-06 01:34:17 +00001184 // Initialize the catch variable and set up the cleanups.
1185 BeginCatch(*this, C);
1186
John McCall59a70002010-07-07 06:56:46 +00001187 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001188 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1189 // called, and so it is pushed after BeginCatch.
1190 if (ImplicitRethrow)
John McCall1f0fca52010-07-21 07:22:38 +00001191 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001192
John McCallf1549f62010-07-06 01:34:17 +00001193 // Perform the body of the catch.
1194 EmitStmt(C->getHandlerBlock());
1195
1196 // Fall out through the catch cleanups.
1197 CatchScope.ForceCleanup();
1198
1199 // Branch out of the try.
1200 if (HaveInsertPoint())
1201 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001202 }
1203
John McCallf1549f62010-07-06 01:34:17 +00001204 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001205}
Mike Stumpd88ea562009-12-09 03:35:49 +00001206
John McCall55b20fc2010-07-21 00:52:03 +00001207namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001208 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001209 llvm::Value *ForEHVar;
1210 llvm::Value *EndCatchFn;
1211 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1212 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1213
1214 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1215 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1216 llvm::BasicBlock *CleanupContBB =
1217 CGF.createBasicBlock("finally.cleanup.cont");
1218
1219 llvm::Value *ShouldEndCatch =
1220 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1221 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1222 CGF.EmitBlock(EndCatchBB);
1223 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1224 CGF.EmitBlock(CleanupContBB);
1225 }
1226 };
John McCall77199712010-07-21 05:47:49 +00001227
John McCall1f0fca52010-07-21 07:22:38 +00001228 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001229 const Stmt *Body;
1230 llvm::Value *ForEHVar;
1231 llvm::Value *EndCatchFn;
1232 llvm::Value *RethrowFn;
1233 llvm::Value *SavedExnVar;
1234
1235 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1236 llvm::Value *EndCatchFn,
1237 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1238 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1239 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1240
1241 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1242 // Enter a cleanup to call the end-catch function if one was provided.
1243 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001244 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1245 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001246
John McCalld96a8e72010-08-11 00:16:14 +00001247 // Save the current cleanup destination in case there are
1248 // cleanups in the finally block.
1249 llvm::Value *SavedCleanupDest =
1250 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1251 "cleanup.dest.saved");
1252
John McCall77199712010-07-21 05:47:49 +00001253 // Emit the finally block.
1254 CGF.EmitStmt(Body);
1255
1256 // If the end of the finally is reachable, check whether this was
1257 // for EH. If so, rethrow.
1258 if (CGF.HaveInsertPoint()) {
1259 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1260 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1261
1262 llvm::Value *ShouldRethrow =
1263 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1264 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1265
1266 CGF.EmitBlock(RethrowBB);
1267 if (SavedExnVar) {
1268 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1269 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1270 } else {
1271 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1272 }
1273 CGF.Builder.CreateUnreachable();
1274
1275 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001276
1277 // Restore the cleanup destination.
1278 CGF.Builder.CreateStore(SavedCleanupDest,
1279 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001280 }
1281
1282 // Leave the end-catch cleanup. As an optimization, pretend that
1283 // the fallthrough path was inaccessible; we've dynamically proven
1284 // that we're not in the EH case along that path.
1285 if (EndCatchFn) {
1286 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1287 CGF.PopCleanupBlock();
1288 CGF.Builder.restoreIP(SavedIP);
1289 }
1290
1291 // Now make sure we actually have an insertion point or the
1292 // cleanup gods will hate us.
1293 CGF.EnsureInsertPoint();
1294 }
1295 };
John McCall55b20fc2010-07-21 00:52:03 +00001296}
1297
John McCallf1549f62010-07-06 01:34:17 +00001298/// Enters a finally block for an implementation using zero-cost
1299/// exceptions. This is mostly general, but hard-codes some
1300/// language/ABI-specific behavior in the catch-all sections.
John McCalld768e9d2011-06-22 02:32:12 +00001301void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1302 const Stmt *body,
1303 llvm::Constant *beginCatchFn,
1304 llvm::Constant *endCatchFn,
1305 llvm::Constant *rethrowFn) {
1306 assert((beginCatchFn != 0) == (endCatchFn != 0) &&
John McCallf1549f62010-07-06 01:34:17 +00001307 "begin/end catch functions not paired");
John McCalld768e9d2011-06-22 02:32:12 +00001308 assert(rethrowFn && "rethrow function is required");
1309
1310 BeginCatchFn = beginCatchFn;
Mike Stumpd88ea562009-12-09 03:35:49 +00001311
John McCallf1549f62010-07-06 01:34:17 +00001312 // The rethrow function has one of the following two types:
1313 // void (*)()
1314 // void (*)(void*)
1315 // In the latter case we need to pass it the exception object.
1316 // But we can't use the exception slot because the @finally might
1317 // have a landing pad (which would overwrite the exception slot).
John McCalld768e9d2011-06-22 02:32:12 +00001318 const llvm::FunctionType *rethrowFnTy =
John McCallf1549f62010-07-06 01:34:17 +00001319 cast<llvm::FunctionType>(
John McCalld768e9d2011-06-22 02:32:12 +00001320 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1321 SavedExnVar = 0;
1322 if (rethrowFnTy->getNumParams())
1323 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001324
John McCallf1549f62010-07-06 01:34:17 +00001325 // A finally block is a statement which must be executed on any edge
1326 // out of a given scope. Unlike a cleanup, the finally block may
1327 // contain arbitrary control flow leading out of itself. In
1328 // addition, finally blocks should always be executed, even if there
1329 // are no catch handlers higher on the stack. Therefore, we
1330 // surround the protected scope with a combination of a normal
1331 // cleanup (to catch attempts to break out of the block via normal
1332 // control flow) and an EH catch-all (semantically "outside" any try
1333 // statement to which the finally block might have been attached).
1334 // The finally block itself is generated in the context of a cleanup
1335 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001336
John McCallf1549f62010-07-06 01:34:17 +00001337 // Jump destination for performing the finally block on an exception
1338 // edge. We'll never actually reach this block, so unreachable is
1339 // fine.
John McCalld768e9d2011-06-22 02:32:12 +00001340 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001341
John McCallf1549f62010-07-06 01:34:17 +00001342 // Whether the finally block is being executed for EH purposes.
John McCalld768e9d2011-06-22 02:32:12 +00001343 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1344 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpd88ea562009-12-09 03:35:49 +00001345
John McCallf1549f62010-07-06 01:34:17 +00001346 // Enter a normal cleanup which will perform the @finally block.
John McCalld768e9d2011-06-22 02:32:12 +00001347 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1348 ForEHVar, endCatchFn,
1349 rethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001350
1351 // Enter a catch-all scope.
John McCalld768e9d2011-06-22 02:32:12 +00001352 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1353 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1354 catchScope->setCatchAllHandler(0, catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001355}
1356
John McCalld768e9d2011-06-22 02:32:12 +00001357void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +00001358 // Leave the finally catch-all.
John McCalld768e9d2011-06-22 02:32:12 +00001359 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1360 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1361 CGF.EHStack.popCatch();
John McCallf1549f62010-07-06 01:34:17 +00001362
John McCalld768e9d2011-06-22 02:32:12 +00001363 // If there are any references to the catch-all block, emit it.
1364 if (catchBB->use_empty()) {
1365 delete catchBB;
1366 } else {
1367 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1368 CGF.EmitBlock(catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001369
John McCalld768e9d2011-06-22 02:32:12 +00001370 llvm::Value *exn = 0;
John McCallf1549f62010-07-06 01:34:17 +00001371
John McCalld768e9d2011-06-22 02:32:12 +00001372 // If there's a begin-catch function, call it.
1373 if (BeginCatchFn) {
1374 exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
1375 CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
1376 }
1377
1378 // If we need to remember the exception pointer to rethrow later, do so.
1379 if (SavedExnVar) {
1380 if (!exn) exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
1381 CGF.Builder.CreateStore(exn, SavedExnVar);
1382 }
1383
1384 // Tell the cleanups in the finally block that we're do this for EH.
1385 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1386
1387 // Thread a jump through the finally cleanup.
1388 CGF.EmitBranchThroughCleanup(RethrowDest);
1389
1390 CGF.Builder.restoreIP(savedIP);
1391 }
1392
1393 // Finally, leave the @finally cleanup.
1394 CGF.PopCleanupBlock();
John McCallf1549f62010-07-06 01:34:17 +00001395}
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 McCall8262b6a2010-07-17 00:43:08 +00001411
1412 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallf1549f62010-07-06 01:34:17 +00001413
1414 // Tell the backend what the exception table should be:
1415 // nothing but a catch-all.
John McCallb2593832010-09-16 06:16:50 +00001416 llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
John McCallf1549f62010-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 McCalld16c2cf2011-02-08 08:22:06 +00001425 Builder.CreateUnreachable();
Mike Stumpd88ea562009-12-09 03:35:49 +00001426
John McCallf1549f62010-07-06 01:34:17 +00001427 // Restore the saved insertion state.
1428 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001429
John McCallf1549f62010-07-06 01:34:17 +00001430 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001431}
Mike Stump9b39c512009-12-09 22:59:31 +00001432
1433llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001434 if (TerminateHandler)
1435 return TerminateHandler;
1436
John McCallf1549f62010-07-06 01:34:17 +00001437 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001438
John McCallf1549f62010-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 Stump182f3832009-12-10 00:02:42 +00001441 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001442 Builder.SetInsertPoint(TerminateHandler);
1443 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001444 TerminateCall->setDoesNotReturn();
1445 TerminateCall->setDoesNotThrow();
1446 Builder.CreateUnreachable();
1447
John McCall3d3ec1c2010-04-21 10:05:39 +00001448 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001449 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001450
Mike Stump9b39c512009-12-09 22:59:31 +00001451 return TerminateHandler;
1452}
John McCallf1549f62010-07-06 01:34:17 +00001453
John McCallff8e1152010-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 McCallb2593832010-09-16 06:16:50 +00001467 llvm::StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCall93c332a2011-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 McCallff8e1152010-07-23 21:56:41 +00001474
John McCall93c332a2011-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 McCallff8e1152010-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