blob: 14a89cff3f97cc09dbd34ef5ec8829ec6edede51 [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
Chris Lattner2acc6e32011-07-18 04:24:23 +000032 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +000033 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.SizeTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000034
Anders Carlssond3379292009-10-30 02:27:02 +000035 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
36}
37
Mike Stump99533832009-12-02 07:41:41 +000038static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
39 // void __cxa_free_exception(void *thrown_exception);
Mike Stump8755ec32009-12-10 00:06:18 +000040
Chris Lattner2acc6e32011-07-18 04:24:23 +000041 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +000042 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000043
Mike Stump99533832009-12-02 07:41:41 +000044 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
45}
46
Anders Carlssond3379292009-10-30 02:27:02 +000047static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +000048 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +000049 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +000050
John McCall61c16012011-07-10 20:11:30 +000051 llvm::Type *Args[3] = { CGF.Int8PtrTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +000052 llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +000053 llvm::FunctionType::get(CGF.VoidTy, Args, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000054
Anders Carlssond3379292009-10-30 02:27:02 +000055 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
56}
57
Mike Stumpb4eea692009-11-20 00:56:31 +000058static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +000059 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +000060
Chris Lattner2acc6e32011-07-18 04:24:23 +000061 llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +000062 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000063
Mike Stumpb4eea692009-11-20 00:56:31 +000064 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
65}
66
John McCallf1549f62010-07-06 01:34:17 +000067static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
68 // void *__cxa_get_exception_ptr(void*);
John McCallf1549f62010-07-06 01:34:17 +000069
Chris Lattner2acc6e32011-07-18 04:24:23 +000070 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +000071 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
John McCallf1549f62010-07-06 01:34:17 +000072
73 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
74}
75
Mike Stump2bf701e2009-11-20 23:44:51 +000076static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +000077 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +000078
Chris Lattner2acc6e32011-07-18 04:24:23 +000079 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +000080 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000081
Mike Stump2bf701e2009-11-20 23:44:51 +000082 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
83}
84
85static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +000086 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +000087
Chris Lattner2acc6e32011-07-18 04:24:23 +000088 llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +000089 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000090
Mike Stump2bf701e2009-11-20 23:44:51 +000091 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
92}
93
Mike Stumpcce3d4f2009-12-07 23:38:24 +000094static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
95 // void __cxa_call_unexepcted(void *thrown_exception);
96
Chris Lattner2acc6e32011-07-18 04:24:23 +000097 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +000098 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000099
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000100 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
101}
102
John McCall93c332a2011-05-28 21:13:02 +0000103llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000104 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +0000105 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
John McCall93c332a2011-05-28 21:13:02 +0000106
107 if (CGM.getLangOptions().SjLjExceptions)
108 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
109 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
110}
111
112llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000113 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +0000114 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000115
Douglas Gregor86a3a032010-05-16 01:24:12 +0000116 if (CGM.getLangOptions().SjLjExceptions)
John McCalla5f2de22010-08-11 20:59:53 +0000117 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor86a3a032010-05-16 01:24:12 +0000118 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000119}
120
Mike Stump99533832009-12-02 07:41:41 +0000121static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
122 // void __terminate();
123
Chris Lattner2acc6e32011-07-18 04:24:23 +0000124 llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +0000125 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000126
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 StringRef name;
John McCall256a76e2011-07-06 01:22:26 +0000128
129 // In C++, use std::terminate().
130 if (CGF.getLangOptions().CPlusPlus)
131 name = "_ZSt9terminatev"; // FIXME: mangling!
132 else if (CGF.getLangOptions().ObjC1 &&
133 CGF.CGM.getCodeGenOpts().ObjCRuntimeHasTerminate)
134 name = "objc_terminate";
135 else
136 name = "abort";
137 return CGF.CGM.CreateRuntimeFunction(FTy, name);
David Chisnall79a9ad82010-05-17 13:49:20 +0000138}
139
John McCall8262b6a2010-07-17 00:43:08 +0000140static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000141 StringRef Name) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000142 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +0000143 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
John McCall8262b6a2010-07-17 00:43:08 +0000144
145 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000146}
147
John McCall8262b6a2010-07-17 00:43:08 +0000148const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
John McCall44680782010-11-07 02:35:25 +0000149const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
John McCall8262b6a2010-07-17 00:43:08 +0000150const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
151const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
152const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
153const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
154 "objc_exception_throw");
David Chisnall80558d22011-03-20 21:35:39 +0000155const EHPersonality EHPersonality::GNU_ObjCXX("__gnustep_objcxx_personality_v0");
John McCall8262b6a2010-07-17 00:43:08 +0000156
157static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000158 if (L.SjLjExceptions)
159 return EHPersonality::GNU_C_SJLJ;
John McCall8262b6a2010-07-17 00:43:08 +0000160 return EHPersonality::GNU_C;
161}
162
163static const EHPersonality &getObjCPersonality(const LangOptions &L) {
164 if (L.NeXTRuntime) {
165 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
166 else return getCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000167 } else {
John McCall8262b6a2010-07-17 00:43:08 +0000168 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000169 }
170}
171
John McCall8262b6a2010-07-17 00:43:08 +0000172static const EHPersonality &getCXXPersonality(const LangOptions &L) {
173 if (L.SjLjExceptions)
174 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000175 else
John McCall8262b6a2010-07-17 00:43:08 +0000176 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000177}
178
179/// Determines the personality function to use when both C++
180/// and Objective-C exceptions are being caught.
John McCall8262b6a2010-07-17 00:43:08 +0000181static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallf1549f62010-07-06 01:34:17 +0000182 // The ObjC personality defers to the C++ personality for non-ObjC
183 // handlers. Unlike the C++ case, we use the same personality
184 // function on targets using (backend-driven) SJLJ EH.
John McCall8262b6a2010-07-17 00:43:08 +0000185 if (L.NeXTRuntime) {
186 if (L.ObjCNonFragileABI)
187 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000188
189 // In the fragile ABI, just use C++ exception handling and hope
190 // they're not doing crazy exception mixing.
191 else
John McCall8262b6a2010-07-17 00:43:08 +0000192 return getCXXPersonality(L);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000193 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000194
John McCall8262b6a2010-07-17 00:43:08 +0000195 // The GNU runtime's personality function inherently doesn't support
196 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnall80558d22011-03-20 21:35:39 +0000197 return EHPersonality::GNU_ObjCXX;
John McCallf1549f62010-07-06 01:34:17 +0000198}
199
John McCall8262b6a2010-07-17 00:43:08 +0000200const EHPersonality &EHPersonality::get(const LangOptions &L) {
201 if (L.CPlusPlus && L.ObjC1)
202 return getObjCXXPersonality(L);
203 else if (L.CPlusPlus)
204 return getCXXPersonality(L);
205 else if (L.ObjC1)
206 return getObjCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000207 else
John McCall8262b6a2010-07-17 00:43:08 +0000208 return getCPersonality(L);
209}
John McCallf1549f62010-07-06 01:34:17 +0000210
John McCallb2593832010-09-16 06:16:50 +0000211static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000212 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000213 llvm::Constant *Fn =
John McCallb2593832010-09-16 06:16:50 +0000214 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
215 llvm::Type::getInt32Ty(CGM.getLLVMContext()),
216 true),
217 Personality.getPersonalityFnName());
218 return Fn;
219}
220
221static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
222 const EHPersonality &Personality) {
223 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCalld16c2cf2011-02-08 08:22:06 +0000224 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCallb2593832010-09-16 06:16:50 +0000225}
226
227/// Check whether a personality function could reasonably be swapped
228/// for a C++ personality function.
229static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
230 for (llvm::Constant::use_iterator
231 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
232 llvm::User *User = *I;
233
234 // Conditionally white-list bitcasts.
235 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
236 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
237 if (!PersonalityHasOnlyCXXUses(CE))
238 return false;
239 continue;
240 }
241
242 // Otherwise, it has to be a selector call.
243 if (!isa<llvm::EHSelectorInst>(User)) return false;
244
245 llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
246 for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
247 // Look for something that would've been returned by the ObjC
248 // runtime's GetEHType() method.
249 llvm::GlobalVariable *GV
250 = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
251 if (!GV) continue;
252
253 // ObjC EH selector entries are always global variables with
254 // names starting like this.
255 if (GV->getName().startswith("OBJC_EHTYPE"))
256 return false;
257 }
258 }
259
260 return true;
261}
262
263/// Try to use the C++ personality function in ObjC++. Not doing this
264/// can cause some incompatibilities with gcc, which is more
265/// aggressive about only using the ObjC++ personality in a function
266/// when it really needs it.
267void CodeGenModule::SimplifyPersonality() {
268 // For now, this is really a Darwin-specific operation.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000269 if (!Context.getTargetInfo().getTriple().isOSDarwin())
John McCallb2593832010-09-16 06:16:50 +0000270 return;
271
272 // If we're not in ObjC++ -fexceptions, there's nothing to do.
273 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
274 return;
275
276 const EHPersonality &ObjCXX = EHPersonality::get(Features);
277 const EHPersonality &CXX = getCXXPersonality(Features);
278 if (&ObjCXX == &CXX ||
279 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
280 return;
281
282 llvm::Function *Fn =
283 getModule().getFunction(ObjCXX.getPersonalityFnName());
284
285 // Nothing to do if it's unused.
286 if (!Fn || Fn->use_empty()) return;
287
288 // Can't do the optimization if it has non-C++ uses.
289 if (!PersonalityHasOnlyCXXUses(Fn)) return;
290
291 // Create the C++ personality function and kill off the old
292 // function.
293 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
294
295 // This can happen if the user is screwing with us.
296 if (Fn->getType() != CXXFn->getType()) return;
297
298 Fn->replaceAllUsesWith(CXXFn);
299 Fn->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000300}
301
302/// Returns the value to inject into a selector to indicate the
303/// presence of a catch-all.
304static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
305 // Possibly we should use @llvm.eh.catch.all.value here.
John McCalld16c2cf2011-02-08 08:22:06 +0000306 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallf1549f62010-07-06 01:34:17 +0000307}
308
John McCall09faeab2010-07-13 21:17:51 +0000309namespace {
310 /// A cleanup to free the exception object if its initialization
311 /// throws.
John McCallc4a1a842011-07-12 00:15:30 +0000312 struct FreeException : EHScopeStack::Cleanup {
313 llvm::Value *exn;
314 FreeException(llvm::Value *exn) : exn(exn) {}
John McCallad346f42011-07-12 20:27:29 +0000315 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall3ad32c82011-01-28 08:37:24 +0000316 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
John McCall09faeab2010-07-13 21:17:51 +0000317 ->setDoesNotThrow();
John McCall09faeab2010-07-13 21:17:51 +0000318 }
319 };
320}
321
John McCallac418162010-04-22 01:10:34 +0000322// Emits an exception expression into the given location. This
323// differs from EmitAnyExprToMem only in that, if a final copy-ctor
324// call is required, an exception within that copy ctor causes
325// std::terminate to be invoked.
John McCall3ad32c82011-01-28 08:37:24 +0000326static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
327 llvm::Value *addr) {
John McCallf1549f62010-07-06 01:34:17 +0000328 // Make sure the exception object is cleaned up if there's an
329 // exception during initialization.
John McCall3ad32c82011-01-28 08:37:24 +0000330 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
331 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000332
333 // __cxa_allocate_exception returns a void*; we need to cast this
334 // to the appropriate type for the object.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000335 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
John McCall3ad32c82011-01-28 08:37:24 +0000336 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCallac418162010-04-22 01:10:34 +0000337
338 // FIXME: this isn't quite right! If there's a final unelided call
339 // to a copy constructor, then according to [except.terminate]p1 we
340 // must call std::terminate() if that constructor throws, because
341 // technically that copy occurs after the exception expression is
342 // evaluated but before the exception is caught. But the best way
343 // to handle that is to teach EmitAggExpr to do the final copy
344 // differently if it can't be elided.
John McCallf85e1932011-06-15 23:02:42 +0000345 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
346 /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000347
John McCall3ad32c82011-01-28 08:37:24 +0000348 // Deactivate the cleanup block.
349 CGF.DeactivateCleanupBlock(cleanup);
Mike Stump0f590be2009-12-01 03:41:18 +0000350}
351
John McCallf1549f62010-07-06 01:34:17 +0000352llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall93c332a2011-05-28 21:13:02 +0000353 if (!ExceptionSlot)
354 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallf1549f62010-07-06 01:34:17 +0000355 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000356}
357
John McCall93c332a2011-05-28 21:13:02 +0000358llvm::Value *CodeGenFunction::getEHSelectorSlot() {
359 if (!EHSelectorSlot)
360 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
361 return EHSelectorSlot;
362}
363
Bill Wendlingae270592011-09-15 18:57:19 +0000364llvm::Value *CodeGenFunction::getExceptionFromSlot() {
365 return Builder.CreateLoad(getExceptionSlot(), "exn");
366}
367
368llvm::Value *CodeGenFunction::getSelectorFromSlot() {
369 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
370}
371
Anders Carlsson756b5c42009-10-30 01:42:31 +0000372void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000373 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000374 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000375 Builder.CreateInvoke(getReThrowFn(*this),
376 getUnreachableBlock(),
377 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000378 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000379 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000380 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000381 Builder.CreateUnreachable();
382 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000383
John McCallcd5b22e2011-01-12 03:41:02 +0000384 // throw is an expression, and the expression emitters expect us
385 // to leave ourselves at a valid insertion point.
386 EmitBlock(createBasicBlock("throw.cont"));
387
Anders Carlssond3379292009-10-30 02:27:02 +0000388 return;
389 }
Mike Stump8755ec32009-12-10 00:06:18 +0000390
Anders Carlssond3379292009-10-30 02:27:02 +0000391 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000392
Anders Carlssond3379292009-10-30 02:27:02 +0000393 // Now allocate the exception object.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000394 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000395 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000396
Anders Carlssond3379292009-10-30 02:27:02 +0000397 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000398 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000399 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000400 llvm::ConstantInt::get(SizeTy, TypeSize),
401 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000402 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000403
John McCallac418162010-04-22 01:10:34 +0000404 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000405
Anders Carlssond3379292009-10-30 02:27:02 +0000406 // Now throw the exception.
Anders Carlsson82a113a2011-01-24 01:59:49 +0000407 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
408 /*ForEH=*/true);
John McCallac418162010-04-22 01:10:34 +0000409
410 // The address of the destructor. If the exception type has a
411 // trivial destructor (or isn't a record), we just pass null.
412 llvm::Constant *Dtor = 0;
413 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
414 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
415 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000416 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000417 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
418 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
419 }
420 }
421 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000422
Mike Stump0a3816e2009-12-04 01:51:45 +0000423 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000424 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000425 Builder.CreateInvoke3(getThrowFn(*this),
426 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000427 ExceptionPtr, TypeInfo, Dtor);
428 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000429 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000430 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000431 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
432 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000433 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000434 }
Mike Stump8755ec32009-12-10 00:06:18 +0000435
John McCallcd5b22e2011-01-12 03:41:02 +0000436 // throw is an expression, and the expression emitters expect us
437 // to leave ourselves at a valid insertion point.
438 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000439}
Mike Stump2bf701e2009-11-20 23:44:51 +0000440
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000441void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlsson15348ae2011-02-28 02:27:16 +0000442 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000443 return;
444
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000445 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
446 if (FD == 0)
447 return;
448 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
449 if (Proto == 0)
450 return;
451
Sebastian Redla968e972011-03-15 18:42:48 +0000452 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
453 if (isNoexceptExceptionSpec(EST)) {
454 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
455 // noexcept functions are simple terminate scopes.
456 EHStack.pushTerminate();
457 }
458 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
459 unsigned NumExceptions = Proto->getNumExceptions();
460 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000461
Sebastian Redla968e972011-03-15 18:42:48 +0000462 for (unsigned I = 0; I != NumExceptions; ++I) {
463 QualType Ty = Proto->getExceptionType(I);
464 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
465 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
466 /*ForEH=*/true);
467 Filter->setFilter(I, EHType);
468 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000469 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000470}
471
John McCall777d6e52011-08-11 02:22:43 +0000472/// Emit the dispatch block for a filter scope if necessary.
473static void emitFilterDispatchBlock(CodeGenFunction &CGF,
474 EHFilterScope &filterScope) {
475 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
476 if (!dispatchBlock) return;
477 if (dispatchBlock->use_empty()) {
478 delete dispatchBlock;
479 return;
480 }
481
John McCall777d6e52011-08-11 02:22:43 +0000482 CGF.EmitBlockAfterUses(dispatchBlock);
483
484 // If this isn't a catch-all filter, we need to check whether we got
485 // here because the filter triggered.
486 if (filterScope.getNumFilters()) {
487 // Load the selector value.
Bill Wendlingae270592011-09-15 18:57:19 +0000488 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall777d6e52011-08-11 02:22:43 +0000489 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
490
491 llvm::Value *zero = CGF.Builder.getInt32(0);
492 llvm::Value *failsFilter =
493 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
494 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock());
495
496 CGF.EmitBlock(unexpectedBB);
497 }
498
499 // Call __cxa_call_unexpected. This doesn't need to be an invoke
500 // because __cxa_call_unexpected magically filters exceptions
501 // according to the last landing pad the exception was thrown
502 // into. Seriously.
Bill Wendlingae270592011-09-15 18:57:19 +0000503 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall777d6e52011-08-11 02:22:43 +0000504 CGF.Builder.CreateCall(getUnexpectedFn(CGF), exn)
505 ->setDoesNotReturn();
506 CGF.Builder.CreateUnreachable();
507}
508
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000509void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlsson15348ae2011-02-28 02:27:16 +0000510 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000511 return;
512
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000513 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
514 if (FD == 0)
515 return;
516 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
517 if (Proto == 0)
518 return;
519
Sebastian Redla968e972011-03-15 18:42:48 +0000520 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
521 if (isNoexceptExceptionSpec(EST)) {
522 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
523 EHStack.popTerminate();
524 }
525 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
John McCall777d6e52011-08-11 02:22:43 +0000526 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
527 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redla968e972011-03-15 18:42:48 +0000528 EHStack.popFilter();
529 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000530}
531
Mike Stump2bf701e2009-11-20 23:44:51 +0000532void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000533 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000534 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000535 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000536}
537
John McCall59a70002010-07-07 06:56:46 +0000538void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000539 unsigned NumHandlers = S.getNumHandlers();
540 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000541
John McCallf1549f62010-07-06 01:34:17 +0000542 for (unsigned I = 0; I != NumHandlers; ++I) {
543 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000544
John McCallf1549f62010-07-06 01:34:17 +0000545 llvm::BasicBlock *Handler = createBasicBlock("catch");
546 if (C->getExceptionDecl()) {
547 // FIXME: Dropping the reference type on the type into makes it
548 // impossible to correctly implement catch-by-reference
549 // semantics for pointers. Unfortunately, this is what all
550 // existing compilers do, and it's not clear that the standard
551 // personality routine is capable of doing this right. See C++ DR 388:
552 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
553 QualType CaughtType = C->getCaughtType();
554 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall5a180392010-07-24 00:37:23 +0000555
556 llvm::Value *TypeInfo = 0;
557 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000558 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall5a180392010-07-24 00:37:23 +0000559 else
Anders Carlsson82a113a2011-01-24 01:59:49 +0000560 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallf1549f62010-07-06 01:34:17 +0000561 CatchScope->setHandler(I, TypeInfo, Handler);
562 } else {
563 // No exception decl indicates '...', a catch-all.
564 CatchScope->setCatchAllHandler(I, Handler);
565 }
566 }
John McCallf1549f62010-07-06 01:34:17 +0000567}
568
John McCall777d6e52011-08-11 02:22:43 +0000569llvm::BasicBlock *
570CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
571 // The dispatch block for the end of the scope chain is a block that
572 // just resumes unwinding.
573 if (si == EHStack.stable_end())
574 return getEHResumeBlock();
575
576 // Otherwise, we should look at the actual scope.
577 EHScope &scope = *EHStack.find(si);
578
579 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
580 if (!dispatchBlock) {
581 switch (scope.getKind()) {
582 case EHScope::Catch: {
583 // Apply a special case to a single catch-all.
584 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
585 if (catchScope.getNumHandlers() == 1 &&
586 catchScope.getHandler(0).isCatchAll()) {
587 dispatchBlock = catchScope.getHandler(0).Block;
588
589 // Otherwise, make a dispatch block.
590 } else {
591 dispatchBlock = createBasicBlock("catch.dispatch");
592 }
593 break;
594 }
595
596 case EHScope::Cleanup:
597 dispatchBlock = createBasicBlock("ehcleanup");
598 break;
599
600 case EHScope::Filter:
601 dispatchBlock = createBasicBlock("filter.dispatch");
602 break;
603
604 case EHScope::Terminate:
605 dispatchBlock = getTerminateHandler();
606 break;
607 }
608 scope.setCachedEHDispatchBlock(dispatchBlock);
609 }
610 return dispatchBlock;
611}
612
John McCallf1549f62010-07-06 01:34:17 +0000613/// Check whether this is a non-EH scope, i.e. a scope which doesn't
614/// affect exception handling. Currently, the only non-EH scopes are
615/// normal-only cleanup scopes.
616static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000617 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000618 case EHScope::Cleanup:
619 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000620 case EHScope::Filter:
621 case EHScope::Catch:
622 case EHScope::Terminate:
623 return false;
624 }
625
626 // Suppress warning.
627 return false;
John McCallf1549f62010-07-06 01:34:17 +0000628}
629
630llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
631 assert(EHStack.requiresLandingPad());
632 assert(!EHStack.empty());
633
Anders Carlsson7a178512011-02-28 00:33:03 +0000634 if (!CGM.getLangOptions().Exceptions)
John McCallda65ea82010-07-13 20:32:21 +0000635 return 0;
636
John McCallf1549f62010-07-06 01:34:17 +0000637 // Check the innermost scope for a cached landing pad. If this is
638 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
639 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
640 if (LP) return LP;
641
642 // Build the landing pad for this scope.
643 LP = EmitLandingPad();
644 assert(LP);
645
646 // Cache the landing pad on the innermost scope. If this is a
647 // non-EH scope, cache the landing pad on the enclosing scope, too.
648 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
649 ir->setCachedLandingPad(LP);
650 if (!isNonEHScope(*ir)) break;
651 }
652
653 return LP;
654}
655
John McCall93c332a2011-05-28 21:13:02 +0000656// This code contains a hack to work around a design flaw in
657// LLVM's EH IR which breaks semantics after inlining. This same
658// hack is implemented in llvm-gcc.
659//
660// The LLVM EH abstraction is basically a thin veneer over the
661// traditional GCC zero-cost design: for each range of instructions
662// in the function, there is (at most) one "landing pad" with an
663// associated chain of EH actions. A language-specific personality
664// function interprets this chain of actions and (1) decides whether
665// or not to resume execution at the landing pad and (2) if so,
666// provides an integer indicating why it's stopping. In LLVM IR,
667// the association of a landing pad with a range of instructions is
668// achieved via an invoke instruction, the chain of actions becomes
669// the arguments to the @llvm.eh.selector call, and the selector
670// call returns the integer indicator. Other than the required
671// presence of two intrinsic function calls in the landing pad,
672// the IR exactly describes the layout of the output code.
673//
674// A principal advantage of this design is that it is completely
675// language-agnostic; in theory, the LLVM optimizers can treat
676// landing pads neutrally, and targets need only know how to lower
677// the intrinsics to have a functioning exceptions system (assuming
678// that platform exceptions follow something approximately like the
679// GCC design). Unfortunately, landing pads cannot be combined in a
680// language-agnostic way: given selectors A and B, there is no way
681// to make a single landing pad which faithfully represents the
682// semantics of propagating an exception first through A, then
683// through B, without knowing how the personality will interpret the
684// (lowered form of the) selectors. This means that inlining has no
685// choice but to crudely chain invokes (i.e., to ignore invokes in
686// the inlined function, but to turn all unwindable calls into
687// invokes), which is only semantically valid if every unwind stops
688// at every landing pad.
689//
690// Therefore, the invoke-inline hack is to guarantee that every
691// landing pad has a catch-all.
692enum CleanupHackLevel_t {
693 /// A level of hack that requires that all landing pads have
694 /// catch-alls.
695 CHL_MandatoryCatchall,
696
697 /// A level of hack that requires that all landing pads handle
698 /// cleanups.
699 CHL_MandatoryCleanup,
700
701 /// No hacks at all; ideal IR generation.
702 CHL_Ideal
703};
704const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
705
John McCallf1549f62010-07-06 01:34:17 +0000706llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
707 assert(EHStack.requiresLandingPad());
708
John McCall777d6e52011-08-11 02:22:43 +0000709 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
710 switch (innermostEHScope.getKind()) {
711 case EHScope::Terminate:
712 return getTerminateLandingPad();
John McCallf1549f62010-07-06 01:34:17 +0000713
John McCall777d6e52011-08-11 02:22:43 +0000714 case EHScope::Catch:
715 case EHScope::Cleanup:
716 case EHScope::Filter:
717 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
718 return lpad;
John McCallf1549f62010-07-06 01:34:17 +0000719 }
720
721 // Save the current IR generation state.
John McCall777d6e52011-08-11 02:22:43 +0000722 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
John McCallf1549f62010-07-06 01:34:17 +0000723
John McCall777d6e52011-08-11 02:22:43 +0000724 const EHPersonality &personality = EHPersonality::get(getLangOptions());
John McCall8262b6a2010-07-17 00:43:08 +0000725
John McCallf1549f62010-07-06 01:34:17 +0000726 // Create and configure the landing pad.
John McCall777d6e52011-08-11 02:22:43 +0000727 llvm::BasicBlock *lpad = createBasicBlock("lpad");
728 EmitBlock(lpad);
John McCallf1549f62010-07-06 01:34:17 +0000729
Bill Wendling285cfd82011-09-19 20:31:14 +0000730 llvm::LandingPadInst *LPadInst =
731 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
732 getOpaquePersonalityFn(CGM, personality), 0);
733
734 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
735 Builder.CreateStore(LPadExn, getExceptionSlot());
736 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
737 Builder.CreateStore(LPadSel, getEHSelectorSlot());
738
John McCallf1549f62010-07-06 01:34:17 +0000739 // Save the exception pointer. It's safe to use a single exception
740 // pointer per function because EH cleanups can never have nested
741 // try/catches.
Bill Wendling285cfd82011-09-19 20:31:14 +0000742 // Build the landingpad instruction.
John McCallf1549f62010-07-06 01:34:17 +0000743
744 // Accumulate all the handlers in scope.
John McCall777d6e52011-08-11 02:22:43 +0000745 bool hasCatchAll = false;
746 bool hasCleanup = false;
747 bool hasFilter = false;
748 SmallVector<llvm::Value*, 4> filterTypes;
749 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
John McCallf1549f62010-07-06 01:34:17 +0000750 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
751 I != E; ++I) {
752
753 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000754 case EHScope::Cleanup:
John McCall777d6e52011-08-11 02:22:43 +0000755 // If we have a cleanup, remember that.
756 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCallda65ea82010-07-13 20:32:21 +0000757 continue;
758
John McCallf1549f62010-07-06 01:34:17 +0000759 case EHScope::Filter: {
760 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall777d6e52011-08-11 02:22:43 +0000761 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000762
Bill Wendling285cfd82011-09-19 20:31:14 +0000763 // Filter scopes get added to the landingpad in weird ways.
John McCall777d6e52011-08-11 02:22:43 +0000764 EHFilterScope &filter = cast<EHFilterScope>(*I);
765 hasFilter = true;
John McCallf1549f62010-07-06 01:34:17 +0000766
767 // Add all the filter values which we aren't already explicitly
768 // catching.
John McCall777d6e52011-08-11 02:22:43 +0000769 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i) {
770 llvm::Value *filterType = filter.getFilter(i);
771 if (!catchTypes.count(filterType))
772 filterTypes.push_back(filterType);
John McCallf1549f62010-07-06 01:34:17 +0000773 }
774 goto done;
775 }
776
777 case EHScope::Terminate:
778 // Terminate scopes are basically catch-alls.
John McCall777d6e52011-08-11 02:22:43 +0000779 assert(!hasCatchAll);
780 hasCatchAll = true;
John McCallf1549f62010-07-06 01:34:17 +0000781 goto done;
782
783 case EHScope::Catch:
784 break;
785 }
786
John McCall777d6e52011-08-11 02:22:43 +0000787 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
788 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
789 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallf1549f62010-07-06 01:34:17 +0000790
John McCall777d6e52011-08-11 02:22:43 +0000791 // If this is a catch-all, register that and abort.
792 if (!handler.Type) {
793 assert(!hasCatchAll);
794 hasCatchAll = true;
795 goto done;
John McCallf1549f62010-07-06 01:34:17 +0000796 }
797
798 // Check whether we already have a handler for this type.
Bill Wendling285cfd82011-09-19 20:31:14 +0000799 if (catchTypes.insert(handler.Type))
800 // If not, add it directly to the landingpad.
801 LPadInst->addClause(handler.Type);
John McCallf1549f62010-07-06 01:34:17 +0000802 }
John McCallf1549f62010-07-06 01:34:17 +0000803 }
804
805 done:
Bill Wendling285cfd82011-09-19 20:31:14 +0000806 // If we have a catch-all, add null to the landingpad.
John McCall777d6e52011-08-11 02:22:43 +0000807 assert(!(hasCatchAll && hasFilter));
808 if (hasCatchAll) {
Bill Wendling285cfd82011-09-19 20:31:14 +0000809 LPadInst->addClause(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000810
811 // If we have an EH filter, we need to add those handlers in the
Bill Wendling285cfd82011-09-19 20:31:14 +0000812 // right place in the landingpad, which is to say, at the end.
John McCall777d6e52011-08-11 02:22:43 +0000813 } else if (hasFilter) {
John McCallf1549f62010-07-06 01:34:17 +0000814 // Create a filter expression: an integer constant saying how many
815 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
816 // followed by the filter types. The personality routine only
817 // lands here if the filter doesn't match.
Bill Wendling285cfd82011-09-19 20:31:14 +0000818 llvm::SmallVector<llvm::Constant*, 8> Filters;
819 llvm::ArrayType *AType =
820 llvm::ArrayType::get(!filterTypes.empty() ?
821 filterTypes[0]->getType() : Int8PtrTy,
822 filterTypes.size());
823
824 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
825 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
826 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
827 LPadInst->addClause(FilterArray);
John McCallf1549f62010-07-06 01:34:17 +0000828
829 // Also check whether we need a cleanup.
Bill Wendling285cfd82011-09-19 20:31:14 +0000830 if (hasCleanup)
831 LPadInst->setCleanup(true);
John McCallf1549f62010-07-06 01:34:17 +0000832
833 // Otherwise, signal that we at least have cleanups.
John McCall777d6e52011-08-11 02:22:43 +0000834 } else if (CleanupHackLevel == CHL_MandatoryCatchall || hasCleanup) {
Bill Wendling285cfd82011-09-19 20:31:14 +0000835 if (CleanupHackLevel == CHL_MandatoryCatchall)
836 LPadInst->addClause(getCatchAllValue(*this));
837 else
838 LPadInst->setCleanup(true);
John McCallf1549f62010-07-06 01:34:17 +0000839 }
840
Bill Wendling285cfd82011-09-19 20:31:14 +0000841 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
842 "landingpad instruction has no clauses!");
John McCallf1549f62010-07-06 01:34:17 +0000843
844 // Tell the backend how to generate the landing pad.
John McCall777d6e52011-08-11 02:22:43 +0000845 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallf1549f62010-07-06 01:34:17 +0000846
847 // Restore the old IR generation state.
John McCall777d6e52011-08-11 02:22:43 +0000848 Builder.restoreIP(savedIP);
John McCallf1549f62010-07-06 01:34:17 +0000849
John McCall777d6e52011-08-11 02:22:43 +0000850 return lpad;
John McCallf1549f62010-07-06 01:34:17 +0000851}
852
John McCall8e3f8612010-07-13 22:12:14 +0000853namespace {
854 /// A cleanup to call __cxa_end_catch. In many cases, the caught
855 /// exception type lets us state definitively that the thrown exception
856 /// type does not have a destructor. In particular:
857 /// - Catch-alls tell us nothing, so we have to conservatively
858 /// assume that the thrown exception might have a destructor.
859 /// - Catches by reference behave according to their base types.
860 /// - Catches of non-record types will only trigger for exceptions
861 /// of non-record types, which never have destructors.
862 /// - Catches of record types can trigger for arbitrary subclasses
863 /// of the caught type, so we have to assume the actual thrown
864 /// exception type might have a throwing destructor, even if the
865 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +0000866 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +0000867 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
868 bool MightThrow;
869
John McCallad346f42011-07-12 20:27:29 +0000870 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8e3f8612010-07-13 22:12:14 +0000871 if (!MightThrow) {
872 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
873 return;
874 }
875
Jay Foad4c7d9f12011-07-15 08:37:34 +0000876 CGF.EmitCallOrInvoke(getEndCatchFn(CGF));
John McCall8e3f8612010-07-13 22:12:14 +0000877 }
878 };
879}
880
John McCallf1549f62010-07-06 01:34:17 +0000881/// Emits a call to __cxa_begin_catch and enters a cleanup to call
882/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +0000883///
884/// \param EndMightThrow - true if __cxa_end_catch might throw
885static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
886 llvm::Value *Exn,
887 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +0000888 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
889 Call->setDoesNotThrow();
890
John McCall1f0fca52010-07-21 07:22:38 +0000891 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +0000892
893 return Call;
894}
895
896/// A "special initializer" callback for initializing a catch
897/// parameter during catch initialization.
898static void InitCatchParam(CodeGenFunction &CGF,
899 const VarDecl &CatchParam,
900 llvm::Value *ParamAddr) {
901 // Load the exception from where the landing pad saved it.
Bill Wendlingae270592011-09-15 18:57:19 +0000902 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCallf1549f62010-07-06 01:34:17 +0000903
904 CanQualType CatchType =
905 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
Chris Lattner2acc6e32011-07-18 04:24:23 +0000906 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
John McCallf1549f62010-07-06 01:34:17 +0000907
908 // If we're catching by reference, we can just cast the object
909 // pointer to the appropriate pointer.
910 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +0000911 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
912 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +0000913
John McCallf1549f62010-07-06 01:34:17 +0000914 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +0000915 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +0000916
917 // We have no way to tell the personality function that we're
918 // catching by reference, so if we're catching a pointer,
919 // __cxa_begin_catch will actually return that pointer by value.
920 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
921 QualType PointeeType = PT->getPointeeType();
922
923 // When catching by reference, generally we should just ignore
924 // this by-value pointer and use the exception object instead.
925 if (!PointeeType->isRecordType()) {
926
927 // Exn points to the struct _Unwind_Exception header, which
928 // we have to skip past in order to reach the exception data.
929 unsigned HeaderSize =
930 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
931 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
932
933 // However, if we're catching a pointer-to-record type that won't
934 // work, because the personality function might have adjusted
935 // the pointer. There's actually no way for us to fully satisfy
936 // the language/ABI contract here: we can't use Exn because it
937 // might have the wrong adjustment, but we can't use the by-value
938 // pointer because it's off by a level of abstraction.
939 //
940 // The current solution is to dump the adjusted pointer into an
941 // alloca, which breaks language semantics (because changing the
942 // pointer doesn't change the exception) but at least works.
943 // The better solution would be to filter out non-exact matches
944 // and rethrow them, but this is tricky because the rethrow
945 // really needs to be catchable by other sites at this landing
946 // pad. The best solution is to fix the personality function.
947 } else {
948 // Pull the pointer for the reference type off.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000949 llvm::Type *PtrTy =
John McCall204b0752010-07-20 22:17:55 +0000950 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
951
952 // Create the temporary and write the adjusted pointer into it.
953 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
954 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
955 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
956
957 // Bind the reference to the temporary.
958 AdjustedExn = ExnPtrTmp;
959 }
960 }
961
John McCallf1549f62010-07-06 01:34:17 +0000962 llvm::Value *ExnCast =
963 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
964 CGF.Builder.CreateStore(ExnCast, ParamAddr);
965 return;
966 }
967
968 // Non-aggregates (plus complexes).
969 bool IsComplex = false;
970 if (!CGF.hasAggregateLLVMType(CatchType) ||
971 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +0000972 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +0000973
974 // If the catch type is a pointer type, __cxa_begin_catch returns
975 // the pointer by value.
976 if (CatchType->hasPointerRepresentation()) {
977 llvm::Value *CastExn =
978 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
979 CGF.Builder.CreateStore(CastExn, ParamAddr);
980 return;
981 }
982
983 // Otherwise, it returns a pointer into the exception object.
984
Chris Lattner2acc6e32011-07-18 04:24:23 +0000985 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallf1549f62010-07-06 01:34:17 +0000986 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
987
988 if (IsComplex) {
989 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
990 ParamAddr, /*volatile*/ false);
991 } else {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000992 unsigned Alignment =
993 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallf1549f62010-07-06 01:34:17 +0000994 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000995 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
996 CatchType);
John McCallf1549f62010-07-06 01:34:17 +0000997 }
998 return;
999 }
1000
John McCallacff6962011-02-16 08:39:19 +00001001 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallf1549f62010-07-06 01:34:17 +00001002
Chris Lattner2acc6e32011-07-18 04:24:23 +00001003 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallf1549f62010-07-06 01:34:17 +00001004
John McCallacff6962011-02-16 08:39:19 +00001005 // Check for a copy expression. If we don't have a copy expression,
1006 // that means a trivial copy is okay.
John McCalle996ffd2011-02-16 08:02:54 +00001007 const Expr *copyExpr = CatchParam.getInit();
1008 if (!copyExpr) {
John McCallacff6962011-02-16 08:39:19 +00001009 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1010 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1011 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001012 return;
1013 }
1014
1015 // We have to call __cxa_get_exception_ptr to get the adjusted
1016 // pointer before copying.
John McCalle996ffd2011-02-16 08:02:54 +00001017 llvm::CallInst *rawAdjustedExn =
John McCallf1549f62010-07-06 01:34:17 +00001018 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
John McCalle996ffd2011-02-16 08:02:54 +00001019 rawAdjustedExn->setDoesNotThrow();
John McCallf1549f62010-07-06 01:34:17 +00001020
John McCalle996ffd2011-02-16 08:02:54 +00001021 // Cast that to the appropriate type.
1022 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallf1549f62010-07-06 01:34:17 +00001023
John McCalle996ffd2011-02-16 08:02:54 +00001024 // The copy expression is defined in terms of an OpaqueValueExpr.
1025 // Find it and map it to the adjusted expression.
1026 CodeGenFunction::OpaqueValueMapping
John McCall56ca35d2011-02-17 10:25:35 +00001027 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1028 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallf1549f62010-07-06 01:34:17 +00001029
1030 // Call the copy ctor in a terminate scope.
1031 CGF.EHStack.pushTerminate();
John McCalle996ffd2011-02-16 08:02:54 +00001032
1033 // Perform the copy construction.
John McCall7c2349b2011-08-25 20:40:09 +00001034 CGF.EmitAggExpr(copyExpr, AggValueSlot::forAddr(ParamAddr, Qualifiers(),
1035 AggValueSlot::IsNotDestructed,
John McCall13668622011-08-26 00:46:38 +00001036 AggValueSlot::DoesNotNeedGCBarriers,
1037 AggValueSlot::IsNotAliased));
John McCalle996ffd2011-02-16 08:02:54 +00001038
1039 // Leave the terminate scope.
John McCallf1549f62010-07-06 01:34:17 +00001040 CGF.EHStack.popTerminate();
1041
John McCalle996ffd2011-02-16 08:02:54 +00001042 // Undo the opaque value mapping.
1043 opaque.pop();
1044
John McCallf1549f62010-07-06 01:34:17 +00001045 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001046 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001047}
1048
1049/// Begins a catch statement by initializing the catch variable and
1050/// calling __cxa_begin_catch.
John McCalle996ffd2011-02-16 08:02:54 +00001051static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallf1549f62010-07-06 01:34:17 +00001052 // We have to be very careful with the ordering of cleanups here:
1053 // C++ [except.throw]p4:
1054 // The destruction [of the exception temporary] occurs
1055 // immediately after the destruction of the object declared in
1056 // the exception-declaration in the handler.
1057 //
1058 // So the precise ordering is:
1059 // 1. Construct catch variable.
1060 // 2. __cxa_begin_catch
1061 // 3. Enter __cxa_end_catch cleanup
1062 // 4. Enter dtor cleanup
1063 //
John McCall34695852011-02-22 06:44:22 +00001064 // We do this by using a slightly abnormal initialization process.
1065 // Delegation sequence:
John McCallf1549f62010-07-06 01:34:17 +00001066 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCall34695852011-02-22 06:44:22 +00001067 // - EmitAutoVarAlloca creates the variable and debug info
John McCallf1549f62010-07-06 01:34:17 +00001068 // - InitCatchParam initializes the variable from the exception
John McCall34695852011-02-22 06:44:22 +00001069 // - CallBeginCatch calls __cxa_begin_catch
1070 // - CallBeginCatch enters the __cxa_end_catch cleanup
1071 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallf1549f62010-07-06 01:34:17 +00001072 // - EmitCXXTryStmt emits the code for the catch body
1073 // - EmitCXXTryStmt close the RunCleanupsScope
1074
1075 VarDecl *CatchParam = S->getExceptionDecl();
1076 if (!CatchParam) {
Bill Wendlingae270592011-09-15 18:57:19 +00001077 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCall8e3f8612010-07-13 22:12:14 +00001078 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001079 return;
1080 }
1081
1082 // Emit the local.
John McCall34695852011-02-22 06:44:22 +00001083 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1084 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
1085 CGF.EmitAutoVarCleanups(var);
John McCall9fc6a772010-02-19 09:25:03 +00001086}
1087
John McCallfcd5c0c2010-07-13 22:24:23 +00001088namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001089 struct CallRethrow : EHScopeStack::Cleanup {
John McCallad346f42011-07-12 20:27:29 +00001090 void Emit(CodeGenFunction &CGF, Flags flags) {
Jay Foad4c7d9f12011-07-15 08:37:34 +00001091 CGF.EmitCallOrInvoke(getReThrowFn(CGF));
John McCallfcd5c0c2010-07-13 22:24:23 +00001092 }
1093 };
1094}
1095
John McCall777d6e52011-08-11 02:22:43 +00001096/// Emit the structure of the dispatch block for the given catch scope.
1097/// It is an invariant that the dispatch block already exists.
1098static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1099 EHCatchScope &catchScope) {
1100 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1101 assert(dispatchBlock);
1102
1103 // If there's only a single catch-all, getEHDispatchBlock returned
1104 // that catch-all as the dispatch block.
1105 if (catchScope.getNumHandlers() == 1 &&
1106 catchScope.getHandler(0).isCatchAll()) {
1107 assert(dispatchBlock == catchScope.getHandler(0).Block);
1108 return;
1109 }
1110
1111 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1112 CGF.EmitBlockAfterUses(dispatchBlock);
1113
1114 // Select the right handler.
1115 llvm::Value *llvm_eh_typeid_for =
1116 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1117
1118 // Load the selector value.
Bill Wendlingae270592011-09-15 18:57:19 +00001119 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall777d6e52011-08-11 02:22:43 +00001120
1121 // Test against each of the exception types we claim to catch.
1122 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1123 assert(i < e && "ran off end of handlers!");
1124 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1125
1126 llvm::Value *typeValue = handler.Type;
1127 assert(typeValue && "fell into catch-all case!");
1128 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1129
1130 // Figure out the next block.
1131 bool nextIsEnd;
1132 llvm::BasicBlock *nextBlock;
1133
1134 // If this is the last handler, we're at the end, and the next
1135 // block is the block for the enclosing EH scope.
1136 if (i + 1 == e) {
1137 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1138 nextIsEnd = true;
1139
1140 // If the next handler is a catch-all, we're at the end, and the
1141 // next block is that handler.
1142 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1143 nextBlock = catchScope.getHandler(i+1).Block;
1144 nextIsEnd = true;
1145
1146 // Otherwise, we're not at the end and we need a new block.
1147 } else {
1148 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1149 nextIsEnd = false;
1150 }
1151
1152 // Figure out the catch type's index in the LSDA's type table.
1153 llvm::CallInst *typeIndex =
1154 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1155 typeIndex->setDoesNotThrow();
1156
1157 llvm::Value *matchesTypeIndex =
1158 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1159 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1160
1161 // If the next handler is a catch-all, we're completely done.
1162 if (nextIsEnd) {
1163 CGF.Builder.restoreIP(savedIP);
1164 return;
1165
1166 // Otherwise we need to emit and continue at that block.
1167 } else {
1168 CGF.EmitBlock(nextBlock);
1169 }
1170 }
1171
1172 llvm_unreachable("fell out of loop!");
1173}
1174
1175void CodeGenFunction::popCatchScope() {
1176 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1177 if (catchScope.hasEHBranches())
1178 emitCatchDispatchBlock(*this, catchScope);
1179 EHStack.popCatch();
1180}
1181
John McCall59a70002010-07-07 06:56:46 +00001182void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001183 unsigned NumHandlers = S.getNumHandlers();
1184 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1185 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001186
John McCall777d6e52011-08-11 02:22:43 +00001187 // If the catch was not required, bail out now.
1188 if (!CatchScope.hasEHBranches()) {
1189 EHStack.popCatch();
1190 return;
1191 }
1192
1193 // Emit the structure of the EH dispatch for this catch.
1194 emitCatchDispatchBlock(*this, CatchScope);
1195
John McCallf1549f62010-07-06 01:34:17 +00001196 // Copy the handler blocks off before we pop the EH stack. Emitting
1197 // the handlers might scribble on this memory.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001198 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallf1549f62010-07-06 01:34:17 +00001199 memcpy(Handlers.data(), CatchScope.begin(),
1200 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall777d6e52011-08-11 02:22:43 +00001201
John McCallf1549f62010-07-06 01:34:17 +00001202 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001203
John McCallf1549f62010-07-06 01:34:17 +00001204 // The fall-through block.
1205 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001206
John McCallf1549f62010-07-06 01:34:17 +00001207 // We just emitted the body of the try; jump to the continue block.
1208 if (HaveInsertPoint())
1209 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001210
John McCall59a70002010-07-07 06:56:46 +00001211 // Determine if we need an implicit rethrow for all these catch handlers.
1212 bool ImplicitRethrow = false;
1213 if (IsFnTryBlock)
1214 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1215 isa<CXXConstructorDecl>(CurCodeDecl);
1216
John McCall777d6e52011-08-11 02:22:43 +00001217 // Perversely, we emit the handlers backwards precisely because we
1218 // want them to appear in source order. In all of these cases, the
1219 // catch block will have exactly one predecessor, which will be a
1220 // particular block in the catch dispatch. However, in the case of
1221 // a catch-all, one of the dispatch blocks will branch to two
1222 // different handlers, and EmitBlockAfterUses will cause the second
1223 // handler to be moved before the first.
1224 for (unsigned I = NumHandlers; I != 0; --I) {
1225 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1226 EmitBlockAfterUses(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001227
John McCallf1549f62010-07-06 01:34:17 +00001228 // Catch the exception if this isn't a catch-all.
John McCall777d6e52011-08-11 02:22:43 +00001229 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump2bf701e2009-11-20 23:44:51 +00001230
John McCallf1549f62010-07-06 01:34:17 +00001231 // Enter a cleanup scope, including the catch variable and the
1232 // end-catch.
1233 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001234
John McCallf1549f62010-07-06 01:34:17 +00001235 // Initialize the catch variable and set up the cleanups.
1236 BeginCatch(*this, C);
1237
John McCall59a70002010-07-07 06:56:46 +00001238 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001239 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1240 // called, and so it is pushed after BeginCatch.
1241 if (ImplicitRethrow)
John McCall1f0fca52010-07-21 07:22:38 +00001242 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001243
John McCallf1549f62010-07-06 01:34:17 +00001244 // Perform the body of the catch.
1245 EmitStmt(C->getHandlerBlock());
1246
1247 // Fall out through the catch cleanups.
1248 CatchScope.ForceCleanup();
1249
1250 // Branch out of the try.
1251 if (HaveInsertPoint())
1252 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001253 }
1254
John McCallf1549f62010-07-06 01:34:17 +00001255 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001256}
Mike Stumpd88ea562009-12-09 03:35:49 +00001257
John McCall55b20fc2010-07-21 00:52:03 +00001258namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001259 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001260 llvm::Value *ForEHVar;
1261 llvm::Value *EndCatchFn;
1262 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1263 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1264
John McCallad346f42011-07-12 20:27:29 +00001265 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall55b20fc2010-07-21 00:52:03 +00001266 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1267 llvm::BasicBlock *CleanupContBB =
1268 CGF.createBasicBlock("finally.cleanup.cont");
1269
1270 llvm::Value *ShouldEndCatch =
1271 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1272 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1273 CGF.EmitBlock(EndCatchBB);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001274 CGF.EmitCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall55b20fc2010-07-21 00:52:03 +00001275 CGF.EmitBlock(CleanupContBB);
1276 }
1277 };
John McCall77199712010-07-21 05:47:49 +00001278
John McCall1f0fca52010-07-21 07:22:38 +00001279 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001280 const Stmt *Body;
1281 llvm::Value *ForEHVar;
1282 llvm::Value *EndCatchFn;
1283 llvm::Value *RethrowFn;
1284 llvm::Value *SavedExnVar;
1285
1286 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1287 llvm::Value *EndCatchFn,
1288 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1289 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1290 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1291
John McCallad346f42011-07-12 20:27:29 +00001292 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall77199712010-07-21 05:47:49 +00001293 // Enter a cleanup to call the end-catch function if one was provided.
1294 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001295 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1296 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001297
John McCalld96a8e72010-08-11 00:16:14 +00001298 // Save the current cleanup destination in case there are
1299 // cleanups in the finally block.
1300 llvm::Value *SavedCleanupDest =
1301 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1302 "cleanup.dest.saved");
1303
John McCall77199712010-07-21 05:47:49 +00001304 // Emit the finally block.
1305 CGF.EmitStmt(Body);
1306
1307 // If the end of the finally is reachable, check whether this was
1308 // for EH. If so, rethrow.
1309 if (CGF.HaveInsertPoint()) {
1310 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1311 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1312
1313 llvm::Value *ShouldRethrow =
1314 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1315 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1316
1317 CGF.EmitBlock(RethrowBB);
1318 if (SavedExnVar) {
Jay Foad4c7d9f12011-07-15 08:37:34 +00001319 CGF.EmitCallOrInvoke(RethrowFn, CGF.Builder.CreateLoad(SavedExnVar));
John McCall77199712010-07-21 05:47:49 +00001320 } else {
Jay Foad4c7d9f12011-07-15 08:37:34 +00001321 CGF.EmitCallOrInvoke(RethrowFn);
John McCall77199712010-07-21 05:47:49 +00001322 }
1323 CGF.Builder.CreateUnreachable();
1324
1325 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001326
1327 // Restore the cleanup destination.
1328 CGF.Builder.CreateStore(SavedCleanupDest,
1329 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001330 }
1331
1332 // Leave the end-catch cleanup. As an optimization, pretend that
1333 // the fallthrough path was inaccessible; we've dynamically proven
1334 // that we're not in the EH case along that path.
1335 if (EndCatchFn) {
1336 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1337 CGF.PopCleanupBlock();
1338 CGF.Builder.restoreIP(SavedIP);
1339 }
1340
1341 // Now make sure we actually have an insertion point or the
1342 // cleanup gods will hate us.
1343 CGF.EnsureInsertPoint();
1344 }
1345 };
John McCall55b20fc2010-07-21 00:52:03 +00001346}
1347
John McCallf1549f62010-07-06 01:34:17 +00001348/// Enters a finally block for an implementation using zero-cost
1349/// exceptions. This is mostly general, but hard-codes some
1350/// language/ABI-specific behavior in the catch-all sections.
John McCalld768e9d2011-06-22 02:32:12 +00001351void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1352 const Stmt *body,
1353 llvm::Constant *beginCatchFn,
1354 llvm::Constant *endCatchFn,
1355 llvm::Constant *rethrowFn) {
1356 assert((beginCatchFn != 0) == (endCatchFn != 0) &&
John McCallf1549f62010-07-06 01:34:17 +00001357 "begin/end catch functions not paired");
John McCalld768e9d2011-06-22 02:32:12 +00001358 assert(rethrowFn && "rethrow function is required");
1359
1360 BeginCatchFn = beginCatchFn;
Mike Stumpd88ea562009-12-09 03:35:49 +00001361
John McCallf1549f62010-07-06 01:34:17 +00001362 // The rethrow function has one of the following two types:
1363 // void (*)()
1364 // void (*)(void*)
1365 // In the latter case we need to pass it the exception object.
1366 // But we can't use the exception slot because the @finally might
1367 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2acc6e32011-07-18 04:24:23 +00001368 llvm::FunctionType *rethrowFnTy =
John McCallf1549f62010-07-06 01:34:17 +00001369 cast<llvm::FunctionType>(
John McCalld768e9d2011-06-22 02:32:12 +00001370 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1371 SavedExnVar = 0;
1372 if (rethrowFnTy->getNumParams())
1373 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001374
John McCallf1549f62010-07-06 01:34:17 +00001375 // A finally block is a statement which must be executed on any edge
1376 // out of a given scope. Unlike a cleanup, the finally block may
1377 // contain arbitrary control flow leading out of itself. In
1378 // addition, finally blocks should always be executed, even if there
1379 // are no catch handlers higher on the stack. Therefore, we
1380 // surround the protected scope with a combination of a normal
1381 // cleanup (to catch attempts to break out of the block via normal
1382 // control flow) and an EH catch-all (semantically "outside" any try
1383 // statement to which the finally block might have been attached).
1384 // The finally block itself is generated in the context of a cleanup
1385 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001386
John McCallf1549f62010-07-06 01:34:17 +00001387 // Jump destination for performing the finally block on an exception
1388 // edge. We'll never actually reach this block, so unreachable is
1389 // fine.
John McCalld768e9d2011-06-22 02:32:12 +00001390 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001391
John McCallf1549f62010-07-06 01:34:17 +00001392 // Whether the finally block is being executed for EH purposes.
John McCalld768e9d2011-06-22 02:32:12 +00001393 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1394 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpd88ea562009-12-09 03:35:49 +00001395
John McCallf1549f62010-07-06 01:34:17 +00001396 // Enter a normal cleanup which will perform the @finally block.
John McCalld768e9d2011-06-22 02:32:12 +00001397 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1398 ForEHVar, endCatchFn,
1399 rethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001400
1401 // Enter a catch-all scope.
John McCalld768e9d2011-06-22 02:32:12 +00001402 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1403 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1404 catchScope->setCatchAllHandler(0, catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001405}
1406
John McCalld768e9d2011-06-22 02:32:12 +00001407void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +00001408 // Leave the finally catch-all.
John McCalld768e9d2011-06-22 02:32:12 +00001409 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1410 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall777d6e52011-08-11 02:22:43 +00001411
1412 CGF.popCatchScope();
John McCallf1549f62010-07-06 01:34:17 +00001413
John McCalld768e9d2011-06-22 02:32:12 +00001414 // If there are any references to the catch-all block, emit it.
1415 if (catchBB->use_empty()) {
1416 delete catchBB;
1417 } else {
1418 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1419 CGF.EmitBlock(catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001420
John McCalld768e9d2011-06-22 02:32:12 +00001421 llvm::Value *exn = 0;
John McCallf1549f62010-07-06 01:34:17 +00001422
John McCalld768e9d2011-06-22 02:32:12 +00001423 // If there's a begin-catch function, call it.
1424 if (BeginCatchFn) {
Bill Wendlingae270592011-09-15 18:57:19 +00001425 exn = CGF.getExceptionFromSlot();
John McCalld768e9d2011-06-22 02:32:12 +00001426 CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
1427 }
1428
1429 // If we need to remember the exception pointer to rethrow later, do so.
1430 if (SavedExnVar) {
Bill Wendlingae270592011-09-15 18:57:19 +00001431 if (!exn) exn = CGF.getExceptionFromSlot();
John McCalld768e9d2011-06-22 02:32:12 +00001432 CGF.Builder.CreateStore(exn, SavedExnVar);
1433 }
1434
1435 // Tell the cleanups in the finally block that we're do this for EH.
1436 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1437
1438 // Thread a jump through the finally cleanup.
1439 CGF.EmitBranchThroughCleanup(RethrowDest);
1440
1441 CGF.Builder.restoreIP(savedIP);
1442 }
1443
1444 // Finally, leave the @finally cleanup.
1445 CGF.PopCleanupBlock();
John McCallf1549f62010-07-06 01:34:17 +00001446}
1447
1448llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1449 if (TerminateLandingPad)
1450 return TerminateLandingPad;
1451
1452 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1453
1454 // This will get inserted at the end of the function.
1455 TerminateLandingPad = createBasicBlock("terminate.lpad");
1456 Builder.SetInsertPoint(TerminateLandingPad);
1457
1458 // Tell the backend that this is a landing pad.
John McCall8262b6a2010-07-17 00:43:08 +00001459 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
Bill Wendling285cfd82011-09-19 20:31:14 +00001460 llvm::LandingPadInst *LPadInst =
1461 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
1462 getOpaquePersonalityFn(CGM, Personality), 0);
1463 LPadInst->addClause(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +00001464
1465 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1466 TerminateCall->setDoesNotReturn();
1467 TerminateCall->setDoesNotThrow();
John McCalld16c2cf2011-02-08 08:22:06 +00001468 Builder.CreateUnreachable();
Mike Stumpd88ea562009-12-09 03:35:49 +00001469
John McCallf1549f62010-07-06 01:34:17 +00001470 // Restore the saved insertion state.
1471 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001472
John McCallf1549f62010-07-06 01:34:17 +00001473 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001474}
Mike Stump9b39c512009-12-09 22:59:31 +00001475
1476llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001477 if (TerminateHandler)
1478 return TerminateHandler;
1479
John McCallf1549f62010-07-06 01:34:17 +00001480 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001481
John McCallf1549f62010-07-06 01:34:17 +00001482 // Set up the terminate handler. This block is inserted at the very
1483 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001484 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001485 Builder.SetInsertPoint(TerminateHandler);
1486 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001487 TerminateCall->setDoesNotReturn();
1488 TerminateCall->setDoesNotThrow();
1489 Builder.CreateUnreachable();
1490
John McCall3d3ec1c2010-04-21 10:05:39 +00001491 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001492 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001493
Mike Stump9b39c512009-12-09 22:59:31 +00001494 return TerminateHandler;
1495}
John McCallf1549f62010-07-06 01:34:17 +00001496
John McCall777d6e52011-08-11 02:22:43 +00001497llvm::BasicBlock *CodeGenFunction::getEHResumeBlock() {
1498 if (EHResumeBlock) return EHResumeBlock;
John McCallff8e1152010-07-23 21:56:41 +00001499
1500 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1501
1502 // We emit a jump to a notional label at the outermost unwind state.
John McCall777d6e52011-08-11 02:22:43 +00001503 EHResumeBlock = createBasicBlock("eh.resume");
1504 Builder.SetInsertPoint(EHResumeBlock);
John McCallff8e1152010-07-23 21:56:41 +00001505
1506 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1507
1508 // This can always be a call because we necessarily didn't find
1509 // anything on the EH stack which needs our help.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001510 StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCall93c332a2011-05-28 21:13:02 +00001511 if (!RethrowName.empty()) {
1512 Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
Bill Wendlingae270592011-09-15 18:57:19 +00001513 getExceptionFromSlot())
John McCall93c332a2011-05-28 21:13:02 +00001514 ->setDoesNotReturn();
1515 } else {
Bill Wendlingae270592011-09-15 18:57:19 +00001516 llvm::Value *Exn = getExceptionFromSlot();
John McCallff8e1152010-07-23 21:56:41 +00001517
John McCall93c332a2011-05-28 21:13:02 +00001518 switch (CleanupHackLevel) {
1519 case CHL_MandatoryCatchall:
1520 // In mandatory-catchall mode, we need to use
1521 // _Unwind_Resume_or_Rethrow, or whatever the personality's
1522 // equivalent is.
1523 Builder.CreateCall(getUnwindResumeOrRethrowFn(), Exn)
1524 ->setDoesNotReturn();
1525 break;
1526 case CHL_MandatoryCleanup: {
Bill Wendling285cfd82011-09-19 20:31:14 +00001527 // In mandatory-cleanup mode, we should use 'resume'.
1528
1529 // Recreate the landingpad's return value for the 'resume' instruction.
1530 llvm::Value *Exn = getExceptionFromSlot();
1531 llvm::Value *Sel = getSelectorFromSlot();
1532
1533 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1534 Sel->getType(), NULL);
1535 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1536 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1537 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1538
1539 Builder.CreateResume(LPadVal);
1540 Builder.restoreIP(SavedIP);
1541 return EHResumeBlock;
John McCall93c332a2011-05-28 21:13:02 +00001542 }
1543 case CHL_Ideal:
1544 // In an idealized mode where we don't have to worry about the
1545 // optimizer combining landing pads, we should just use
1546 // _Unwind_Resume (or the personality's equivalent).
1547 Builder.CreateCall(getUnwindResumeFn(), Exn)
1548 ->setDoesNotReturn();
1549 break;
1550 }
1551 }
1552
John McCallff8e1152010-07-23 21:56:41 +00001553 Builder.CreateUnreachable();
1554
1555 Builder.restoreIP(SavedIP);
1556
John McCall777d6e52011-08-11 02:22:43 +00001557 return EHResumeBlock;
John McCallff8e1152010-07-23 21:56:41 +00001558}