blob: ac5fc221f414bfde89ca7f78ff12e1c61710c39e [file] [log] [blame]
Anders Carlsson756b5c42009-10-30 01:42:31 +00001//===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ exception related code generation.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stump2bf701e2009-11-20 23:44:51 +000014#include "clang/AST/StmtCXX.h"
15
16#include "llvm/Intrinsics.h"
John McCallb2593832010-09-16 06:16:50 +000017#include "llvm/IntrinsicInst.h"
John McCallf1549f62010-07-06 01:34:17 +000018#include "llvm/Support/CallSite.h"
Mike Stump2bf701e2009-11-20 23:44:51 +000019
John McCall5a180392010-07-24 00:37:23 +000020#include "CGObjCRuntime.h"
Anders Carlsson756b5c42009-10-30 01:42:31 +000021#include "CodeGenFunction.h"
John McCallf1549f62010-07-06 01:34:17 +000022#include "CGException.h"
John McCall36f893c2011-01-28 11:13:47 +000023#include "CGCleanup.h"
John McCall204b0752010-07-20 22:17:55 +000024#include "TargetInfo.h"
John McCallf1549f62010-07-06 01:34:17 +000025
Anders Carlsson756b5c42009-10-30 01:42:31 +000026using namespace clang;
27using namespace CodeGen;
28
Anders Carlssond3379292009-10-30 02:27:02 +000029static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
30 // void *__cxa_allocate_exception(size_t thrown_size);
Mike Stump8755ec32009-12-10 00:06:18 +000031
Anders Carlsson2839d6b2011-04-18 14:24:10 +000032 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
Mike Stump8755ec32009-12-10 00:06:18 +000033 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000034 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
35 SizeTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000036
Anders Carlssond3379292009-10-30 02:27:02 +000037 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
38}
39
Mike Stump99533832009-12-02 07:41:41 +000040static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
41 // void __cxa_free_exception(void *thrown_exception);
Mike Stump8755ec32009-12-10 00:06:18 +000042
Anders Carlsson2839d6b2011-04-18 14:24:10 +000043 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Mike Stump8755ec32009-12-10 00:06:18 +000044 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000045 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
46 Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000047
Mike Stump99533832009-12-02 07:41:41 +000048 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
49}
50
Anders Carlssond3379292009-10-30 02:27:02 +000051static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +000052 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +000053 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +000054
55 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Anders Carlsson2839d6b2011-04-18 14:24:10 +000056 const llvm::Type *Args[3] = { Int8PtrTy, Int8PtrTy, Int8PtrTy };
Mike Stump8755ec32009-12-10 00:06:18 +000057 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +000058 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
Anders Carlsson2839d6b2011-04-18 14:24:10 +000059 Args, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000060
Anders Carlssond3379292009-10-30 02:27:02 +000061 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
62}
63
Mike Stumpb4eea692009-11-20 00:56:31 +000064static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +000065 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +000066
Mike Stump8755ec32009-12-10 00:06:18 +000067 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000068 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
69 /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000070
Mike Stumpb4eea692009-11-20 00:56:31 +000071 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
72}
73
John McCallf1549f62010-07-06 01:34:17 +000074static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
75 // void *__cxa_get_exception_ptr(void*);
John McCallf1549f62010-07-06 01:34:17 +000076
Anders Carlsson2839d6b2011-04-18 14:24:10 +000077 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
John McCallf1549f62010-07-06 01:34:17 +000078 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000079 llvm::FunctionType::get(Int8PtrTy, Int8PtrTy, /*IsVarArgs=*/false);
John McCallf1549f62010-07-06 01:34:17 +000080
81 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
82}
83
Mike Stump2bf701e2009-11-20 23:44:51 +000084static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +000085 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +000086
87 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Mike Stump8755ec32009-12-10 00:06:18 +000088 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000089 llvm::FunctionType::get(Int8PtrTy, Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000090
Mike Stump2bf701e2009-11-20 23:44:51 +000091 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
92}
93
94static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +000095 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +000096
Mike Stump8755ec32009-12-10 00:06:18 +000097 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000098 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
99 /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000100
Mike Stump2bf701e2009-11-20 23:44:51 +0000101 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
102}
103
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000104static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
105 // void __cxa_call_unexepcted(void *thrown_exception);
106
107 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Mike Stump8755ec32009-12-10 00:06:18 +0000108 const llvm::FunctionType *FTy =
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000109 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
Anders Carlsson2839d6b2011-04-18 14:24:10 +0000110 Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000111
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000112 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
113}
114
Douglas Gregor86a3a032010-05-16 01:24:12 +0000115llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
116 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Mike Stump8755ec32009-12-10 00:06:18 +0000117 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +0000118 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), Int8PtrTy,
119 /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000120
Douglas Gregor86a3a032010-05-16 01:24:12 +0000121 if (CGM.getLangOptions().SjLjExceptions)
John McCalla5f2de22010-08-11 20:59:53 +0000122 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor86a3a032010-05-16 01:24:12 +0000123 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000124}
125
Mike Stump99533832009-12-02 07:41:41 +0000126static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
127 // void __terminate();
128
Mike Stump8755ec32009-12-10 00:06:18 +0000129 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +0000130 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
131 /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000132
David Chisnall79a9ad82010-05-17 13:49:20 +0000133 return CGF.CGM.CreateRuntimeFunction(FTy,
134 CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
135}
136
John McCall8262b6a2010-07-17 00:43:08 +0000137static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
John McCallb2593832010-09-16 06:16:50 +0000138 llvm::StringRef Name) {
John McCall8262b6a2010-07-17 00:43:08 +0000139 const llvm::Type *Int8PtrTy =
140 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
John McCall8262b6a2010-07-17 00:43:08 +0000141 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
Anders Carlsson2839d6b2011-04-18 14:24:10 +0000142 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, Int8PtrTy,
143 /*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.
269 if (Context.Target.getTriple().getOS() != llvm::Triple::Darwin)
270 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
309/// Returns the value to inject into a selector to indicate the
310/// presence of a cleanup.
311static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
312 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000313}
314
John McCall09faeab2010-07-13 21:17:51 +0000315namespace {
316 /// A cleanup to free the exception object if its initialization
317 /// throws.
John McCall3ad32c82011-01-28 08:37:24 +0000318 struct FreeException {
319 static void Emit(CodeGenFunction &CGF, bool forEH,
320 llvm::Value *exn) {
321 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
John McCall09faeab2010-07-13 21:17:51 +0000322 ->setDoesNotThrow();
John McCall09faeab2010-07-13 21:17:51 +0000323 }
324 };
325}
326
John McCallac418162010-04-22 01:10:34 +0000327// Emits an exception expression into the given location. This
328// differs from EmitAnyExprToMem only in that, if a final copy-ctor
329// call is required, an exception within that copy ctor causes
330// std::terminate to be invoked.
John McCall3ad32c82011-01-28 08:37:24 +0000331static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
332 llvm::Value *addr) {
John McCallf1549f62010-07-06 01:34:17 +0000333 // Make sure the exception object is cleaned up if there's an
334 // exception during initialization.
John McCall3ad32c82011-01-28 08:37:24 +0000335 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
336 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000337
338 // __cxa_allocate_exception returns a void*; we need to cast this
339 // to the appropriate type for the object.
John McCall3ad32c82011-01-28 08:37:24 +0000340 const llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
341 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCallac418162010-04-22 01:10:34 +0000342
343 // FIXME: this isn't quite right! If there's a final unelided call
344 // to a copy constructor, then according to [except.terminate]p1 we
345 // must call std::terminate() if that constructor throws, because
346 // technically that copy occurs after the exception expression is
347 // evaluated but before the exception is caught. But the best way
348 // to handle that is to teach EmitAggExpr to do the final copy
349 // differently if it can't be elided.
John McCall3ad32c82011-01-28 08:37:24 +0000350 CGF.EmitAnyExprToMem(e, typedAddr, /*Volatile*/ false, /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000351
John McCall3ad32c82011-01-28 08:37:24 +0000352 // Deactivate the cleanup block.
353 CGF.DeactivateCleanupBlock(cleanup);
Mike Stump0f590be2009-12-01 03:41:18 +0000354}
355
John McCallf1549f62010-07-06 01:34:17 +0000356llvm::Value *CodeGenFunction::getExceptionSlot() {
357 if (!ExceptionSlot) {
358 const llvm::Type *i8p = llvm::Type::getInt8PtrTy(getLLVMContext());
359 ExceptionSlot = CreateTempAlloca(i8p, "exn.slot");
Mike Stump0f590be2009-12-01 03:41:18 +0000360 }
John McCallf1549f62010-07-06 01:34:17 +0000361 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000362}
363
Anders Carlsson756b5c42009-10-30 01:42:31 +0000364void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000365 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000366 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000367 Builder.CreateInvoke(getReThrowFn(*this),
368 getUnreachableBlock(),
369 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000370 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000371 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000372 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000373 Builder.CreateUnreachable();
374 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000375
John McCallcd5b22e2011-01-12 03:41:02 +0000376 // throw is an expression, and the expression emitters expect us
377 // to leave ourselves at a valid insertion point.
378 EmitBlock(createBasicBlock("throw.cont"));
379
Anders Carlssond3379292009-10-30 02:27:02 +0000380 return;
381 }
Mike Stump8755ec32009-12-10 00:06:18 +0000382
Anders Carlssond3379292009-10-30 02:27:02 +0000383 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000384
Anders Carlssond3379292009-10-30 02:27:02 +0000385 // Now allocate the exception object.
386 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000387 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000388
Anders Carlssond3379292009-10-30 02:27:02 +0000389 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000390 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000391 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000392 llvm::ConstantInt::get(SizeTy, TypeSize),
393 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000394 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000395
John McCallac418162010-04-22 01:10:34 +0000396 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000397
Anders Carlssond3379292009-10-30 02:27:02 +0000398 // Now throw the exception.
399 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Anders Carlsson82a113a2011-01-24 01:59:49 +0000400 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
401 /*ForEH=*/true);
John McCallac418162010-04-22 01:10:34 +0000402
403 // The address of the destructor. If the exception type has a
404 // trivial destructor (or isn't a record), we just pass null.
405 llvm::Constant *Dtor = 0;
406 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
407 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
408 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000409 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000410 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
411 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
412 }
413 }
414 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000415
Mike Stump0a3816e2009-12-04 01:51:45 +0000416 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000417 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000418 Builder.CreateInvoke3(getThrowFn(*this),
419 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000420 ExceptionPtr, TypeInfo, Dtor);
421 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000422 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000423 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000424 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
425 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000426 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000427 }
Mike Stump8755ec32009-12-10 00:06:18 +0000428
John McCallcd5b22e2011-01-12 03:41:02 +0000429 // throw is an expression, and the expression emitters expect us
430 // to leave ourselves at a valid insertion point.
431 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000432}
Mike Stump2bf701e2009-11-20 23:44:51 +0000433
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000434void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlsson15348ae2011-02-28 02:27:16 +0000435 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000436 return;
437
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000438 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
439 if (FD == 0)
440 return;
441 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
442 if (Proto == 0)
443 return;
444
Sebastian Redla968e972011-03-15 18:42:48 +0000445 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
446 if (isNoexceptExceptionSpec(EST)) {
447 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
448 // noexcept functions are simple terminate scopes.
449 EHStack.pushTerminate();
450 }
451 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
452 unsigned NumExceptions = Proto->getNumExceptions();
453 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000454
Sebastian Redla968e972011-03-15 18:42:48 +0000455 for (unsigned I = 0; I != NumExceptions; ++I) {
456 QualType Ty = Proto->getExceptionType(I);
457 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
458 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
459 /*ForEH=*/true);
460 Filter->setFilter(I, EHType);
461 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000462 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000463}
464
465void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlsson15348ae2011-02-28 02:27:16 +0000466 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000467 return;
468
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000469 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
470 if (FD == 0)
471 return;
472 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
473 if (Proto == 0)
474 return;
475
Sebastian Redla968e972011-03-15 18:42:48 +0000476 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
477 if (isNoexceptExceptionSpec(EST)) {
478 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
479 EHStack.popTerminate();
480 }
481 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
482 EHStack.popFilter();
483 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000484}
485
Mike Stump2bf701e2009-11-20 23:44:51 +0000486void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000487 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000488 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000489 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000490}
491
John McCall59a70002010-07-07 06:56:46 +0000492void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000493 unsigned NumHandlers = S.getNumHandlers();
494 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000495
John McCallf1549f62010-07-06 01:34:17 +0000496 for (unsigned I = 0; I != NumHandlers; ++I) {
497 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000498
John McCallf1549f62010-07-06 01:34:17 +0000499 llvm::BasicBlock *Handler = createBasicBlock("catch");
500 if (C->getExceptionDecl()) {
501 // FIXME: Dropping the reference type on the type into makes it
502 // impossible to correctly implement catch-by-reference
503 // semantics for pointers. Unfortunately, this is what all
504 // existing compilers do, and it's not clear that the standard
505 // personality routine is capable of doing this right. See C++ DR 388:
506 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
507 QualType CaughtType = C->getCaughtType();
508 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall5a180392010-07-24 00:37:23 +0000509
510 llvm::Value *TypeInfo = 0;
511 if (CaughtType->isObjCObjectPointerType())
512 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
513 else
Anders Carlsson82a113a2011-01-24 01:59:49 +0000514 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallf1549f62010-07-06 01:34:17 +0000515 CatchScope->setHandler(I, TypeInfo, Handler);
516 } else {
517 // No exception decl indicates '...', a catch-all.
518 CatchScope->setCatchAllHandler(I, Handler);
519 }
520 }
John McCallf1549f62010-07-06 01:34:17 +0000521}
522
523/// Check whether this is a non-EH scope, i.e. a scope which doesn't
524/// affect exception handling. Currently, the only non-EH scopes are
525/// normal-only cleanup scopes.
526static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000527 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000528 case EHScope::Cleanup:
529 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000530 case EHScope::Filter:
531 case EHScope::Catch:
532 case EHScope::Terminate:
533 return false;
534 }
535
536 // Suppress warning.
537 return false;
John McCallf1549f62010-07-06 01:34:17 +0000538}
539
540llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
541 assert(EHStack.requiresLandingPad());
542 assert(!EHStack.empty());
543
Anders Carlsson7a178512011-02-28 00:33:03 +0000544 if (!CGM.getLangOptions().Exceptions)
John McCallda65ea82010-07-13 20:32:21 +0000545 return 0;
546
John McCallf1549f62010-07-06 01:34:17 +0000547 // Check the innermost scope for a cached landing pad. If this is
548 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
549 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
550 if (LP) return LP;
551
552 // Build the landing pad for this scope.
553 LP = EmitLandingPad();
554 assert(LP);
555
556 // Cache the landing pad on the innermost scope. If this is a
557 // non-EH scope, cache the landing pad on the enclosing scope, too.
558 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
559 ir->setCachedLandingPad(LP);
560 if (!isNonEHScope(*ir)) break;
561 }
562
563 return LP;
564}
565
566llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
567 assert(EHStack.requiresLandingPad());
568
569 // This function contains a hack to work around a design flaw in
570 // LLVM's EH IR which breaks semantics after inlining. This same
571 // hack is implemented in llvm-gcc.
572 //
573 // The LLVM EH abstraction is basically a thin veneer over the
574 // traditional GCC zero-cost design: for each range of instructions
575 // in the function, there is (at most) one "landing pad" with an
576 // associated chain of EH actions. A language-specific personality
577 // function interprets this chain of actions and (1) decides whether
578 // or not to resume execution at the landing pad and (2) if so,
579 // provides an integer indicating why it's stopping. In LLVM IR,
580 // the association of a landing pad with a range of instructions is
581 // achieved via an invoke instruction, the chain of actions becomes
582 // the arguments to the @llvm.eh.selector call, and the selector
583 // call returns the integer indicator. Other than the required
584 // presence of two intrinsic function calls in the landing pad,
585 // the IR exactly describes the layout of the output code.
586 //
587 // A principal advantage of this design is that it is completely
588 // language-agnostic; in theory, the LLVM optimizers can treat
589 // landing pads neutrally, and targets need only know how to lower
590 // the intrinsics to have a functioning exceptions system (assuming
591 // that platform exceptions follow something approximately like the
592 // GCC design). Unfortunately, landing pads cannot be combined in a
593 // language-agnostic way: given selectors A and B, there is no way
594 // to make a single landing pad which faithfully represents the
595 // semantics of propagating an exception first through A, then
596 // through B, without knowing how the personality will interpret the
597 // (lowered form of the) selectors. This means that inlining has no
598 // choice but to crudely chain invokes (i.e., to ignore invokes in
599 // the inlined function, but to turn all unwindable calls into
600 // invokes), which is only semantically valid if every unwind stops
601 // at every landing pad.
602 //
603 // Therefore, the invoke-inline hack is to guarantee that every
604 // landing pad has a catch-all.
605 const bool UseInvokeInlineHack = true;
606
607 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
608 assert(ir != EHStack.end() &&
609 "stack requiring landing pad is nothing but non-EH scopes?");
610
611 // If this is a terminate scope, just use the singleton terminate
612 // landing pad.
613 if (isa<EHTerminateScope>(*ir))
614 return getTerminateLandingPad();
615
616 // If this isn't an EH scope, iterate; otherwise break out.
617 if (!isNonEHScope(*ir)) break;
618 ++ir;
619
620 // We haven't checked this scope for a cached landing pad yet.
621 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
622 return LP;
623 }
624
625 // Save the current IR generation state.
626 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
627
John McCalld16c2cf2011-02-08 08:22:06 +0000628 const EHPersonality &Personality = EHPersonality::get(getLangOptions());
John McCall8262b6a2010-07-17 00:43:08 +0000629
John McCallf1549f62010-07-06 01:34:17 +0000630 // Create and configure the landing pad.
631 llvm::BasicBlock *LP = createBasicBlock("lpad");
632 EmitBlock(LP);
633
634 // Save the exception pointer. It's safe to use a single exception
635 // pointer per function because EH cleanups can never have nested
636 // try/catches.
637 llvm::CallInst *Exn =
638 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
639 Exn->setDoesNotThrow();
640 Builder.CreateStore(Exn, getExceptionSlot());
641
642 // Build the selector arguments.
643 llvm::SmallVector<llvm::Value*, 8> EHSelector;
644 EHSelector.push_back(Exn);
John McCallb2593832010-09-16 06:16:50 +0000645 EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
John McCallf1549f62010-07-06 01:34:17 +0000646
647 // Accumulate all the handlers in scope.
John McCallff8e1152010-07-23 21:56:41 +0000648 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
649 UnwindDest CatchAll;
John McCallf1549f62010-07-06 01:34:17 +0000650 bool HasEHCleanup = false;
651 bool HasEHFilter = false;
652 llvm::SmallVector<llvm::Value*, 8> EHFilters;
653 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
654 I != E; ++I) {
655
656 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000657 case EHScope::Cleanup:
John McCallda65ea82010-07-13 20:32:21 +0000658 if (!HasEHCleanup)
John McCall1f0fca52010-07-21 07:22:38 +0000659 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000660 // We otherwise don't care about cleanups.
661 continue;
662
John McCallf1549f62010-07-06 01:34:17 +0000663 case EHScope::Filter: {
664 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallff8e1152010-07-23 21:56:41 +0000665 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000666
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000667 // Filter scopes get added to the selector in weird ways.
John McCallf1549f62010-07-06 01:34:17 +0000668 EHFilterScope &Filter = cast<EHFilterScope>(*I);
669 HasEHFilter = true;
670
671 // Add all the filter values which we aren't already explicitly
672 // catching.
673 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
674 llvm::Value *FV = Filter.getFilter(I);
675 if (!EHHandlers.count(FV))
676 EHFilters.push_back(FV);
677 }
678 goto done;
679 }
680
681 case EHScope::Terminate:
682 // Terminate scopes are basically catch-alls.
John McCallff8e1152010-07-23 21:56:41 +0000683 assert(!CatchAll.isValid());
684 CatchAll = UnwindDest(getTerminateHandler(),
685 EHStack.getEnclosingEHCleanup(I),
686 cast<EHTerminateScope>(*I).getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000687 goto done;
688
689 case EHScope::Catch:
690 break;
691 }
692
693 EHCatchScope &Catch = cast<EHCatchScope>(*I);
694 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
695 EHCatchScope::Handler Handler = Catch.getHandler(HI);
696
697 // Catch-all. We should only have one of these per catch.
698 if (!Handler.Type) {
John McCallff8e1152010-07-23 21:56:41 +0000699 assert(!CatchAll.isValid());
700 CatchAll = UnwindDest(Handler.Block,
701 EHStack.getEnclosingEHCleanup(I),
702 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000703 continue;
704 }
705
706 // Check whether we already have a handler for this type.
John McCallff8e1152010-07-23 21:56:41 +0000707 UnwindDest &Dest = EHHandlers[Handler.Type];
708 if (Dest.isValid()) continue;
John McCallf1549f62010-07-06 01:34:17 +0000709
710 EHSelector.push_back(Handler.Type);
John McCallff8e1152010-07-23 21:56:41 +0000711 Dest = UnwindDest(Handler.Block,
712 EHStack.getEnclosingEHCleanup(I),
713 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000714 }
715
716 // Stop if we found a catch-all.
John McCallff8e1152010-07-23 21:56:41 +0000717 if (CatchAll.isValid()) break;
John McCallf1549f62010-07-06 01:34:17 +0000718 }
719
720 done:
721 unsigned LastToEmitInLoop = EHSelector.size();
722
723 // If we have a catch-all, add null to the selector.
John McCallff8e1152010-07-23 21:56:41 +0000724 if (CatchAll.isValid()) {
John McCalld16c2cf2011-02-08 08:22:06 +0000725 EHSelector.push_back(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000726
727 // If we have an EH filter, we need to add those handlers in the
728 // right place in the selector, which is to say, at the end.
729 } else if (HasEHFilter) {
730 // Create a filter expression: an integer constant saying how many
731 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
732 // followed by the filter types. The personality routine only
733 // lands here if the filter doesn't match.
734 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
735 EHFilters.size() + 1));
736 EHSelector.append(EHFilters.begin(), EHFilters.end());
737
738 // Also check whether we need a cleanup.
739 if (UseInvokeInlineHack || HasEHCleanup)
740 EHSelector.push_back(UseInvokeInlineHack
John McCalld16c2cf2011-02-08 08:22:06 +0000741 ? getCatchAllValue(*this)
742 : getCleanupValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000743
744 // Otherwise, signal that we at least have cleanups.
745 } else if (UseInvokeInlineHack || HasEHCleanup) {
746 EHSelector.push_back(UseInvokeInlineHack
John McCalld16c2cf2011-02-08 08:22:06 +0000747 ? getCatchAllValue(*this)
748 : getCleanupValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000749 } else {
750 assert(LastToEmitInLoop > 2);
751 LastToEmitInLoop--;
752 }
753
754 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
755
756 // Tell the backend how to generate the landing pad.
757 llvm::CallInst *Selection =
758 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
759 EHSelector.begin(), EHSelector.end(), "eh.selector");
760 Selection->setDoesNotThrow();
761
762 // Select the right handler.
763 llvm::Value *llvm_eh_typeid_for =
764 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
765
766 // The results of llvm_eh_typeid_for aren't reliable --- at least
767 // not locally --- so we basically have to do this as an 'if' chain.
768 // We walk through the first N-1 catch clauses, testing and chaining,
769 // and then fall into the final clause (which is either a cleanup, a
770 // filter (possibly with a cleanup), a catch-all, or another catch).
771 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
772 llvm::Value *Type = EHSelector[I];
John McCallff8e1152010-07-23 21:56:41 +0000773 UnwindDest Dest = EHHandlers[Type];
774 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallf1549f62010-07-06 01:34:17 +0000775
776 // Figure out where to branch on a match. As a debug code-size
777 // optimization, if the scope depth matches the innermost cleanup,
778 // we branch directly to the catch handler.
John McCallff8e1152010-07-23 21:56:41 +0000779 llvm::BasicBlock *Match = Dest.getBlock();
780 bool MatchNeedsCleanup =
781 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +0000782 if (MatchNeedsCleanup)
783 Match = createBasicBlock("eh.match");
784
785 llvm::BasicBlock *Next = createBasicBlock("eh.next");
786
787 // Check whether the exception matches.
788 llvm::CallInst *Id
789 = Builder.CreateCall(llvm_eh_typeid_for,
John McCalld16c2cf2011-02-08 08:22:06 +0000790 Builder.CreateBitCast(Type, Int8PtrTy));
John McCallf1549f62010-07-06 01:34:17 +0000791 Id->setDoesNotThrow();
792 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
793 Match, Next);
794
795 // Emit match code if necessary.
796 if (MatchNeedsCleanup) {
797 EmitBlock(Match);
798 EmitBranchThroughEHCleanup(Dest);
799 }
800
801 // Continue to the next match.
802 EmitBlock(Next);
803 }
804
805 // Emit the final case in the selector.
806 // This might be a catch-all....
John McCallff8e1152010-07-23 21:56:41 +0000807 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000808 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
809 EmitBranchThroughEHCleanup(CatchAll);
810
811 // ...or an EH filter...
812 } else if (HasEHFilter) {
813 llvm::Value *SavedSelection = Selection;
814
815 // First, unwind out to the outermost scope if necessary.
816 if (EHStack.hasEHCleanups()) {
817 // The end here might not dominate the beginning, so we might need to
818 // save the selector if we need it.
819 llvm::AllocaInst *SelectorVar = 0;
820 if (HasEHCleanup) {
821 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
822 Builder.CreateStore(Selection, SelectorVar);
823 }
824
825 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallff8e1152010-07-23 21:56:41 +0000826 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
827 EHStack.getNextEHDestIndex()));
John McCallf1549f62010-07-06 01:34:17 +0000828 EmitBlock(CleanupContBB);
829
830 if (HasEHCleanup)
831 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
832 }
833
834 // If there was a cleanup, we'll need to actually check whether we
835 // landed here because the filter triggered.
836 if (UseInvokeInlineHack || HasEHCleanup) {
837 llvm::BasicBlock *RethrowBB = createBasicBlock("cleanup");
838 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
839
840 llvm::Constant *Zero = llvm::ConstantInt::get(Builder.getInt32Ty(), 0);
841 llvm::Value *FailsFilter =
842 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
843 Builder.CreateCondBr(FailsFilter, UnexpectedBB, RethrowBB);
844
845 // The rethrow block is where we land if this was a cleanup.
846 // TODO: can this be _Unwind_Resume if the InvokeInlineHack is off?
847 EmitBlock(RethrowBB);
848 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
849 Builder.CreateLoad(getExceptionSlot()))
850 ->setDoesNotReturn();
851 Builder.CreateUnreachable();
852
853 EmitBlock(UnexpectedBB);
854 }
855
856 // Call __cxa_call_unexpected. This doesn't need to be an invoke
857 // because __cxa_call_unexpected magically filters exceptions
858 // according to the last landing pad the exception was thrown
859 // into. Seriously.
860 Builder.CreateCall(getUnexpectedFn(*this),
861 Builder.CreateLoad(getExceptionSlot()))
862 ->setDoesNotReturn();
863 Builder.CreateUnreachable();
864
865 // ...or a normal catch handler...
866 } else if (!UseInvokeInlineHack && !HasEHCleanup) {
867 llvm::Value *Type = EHSelector.back();
868 EmitBranchThroughEHCleanup(EHHandlers[Type]);
869
870 // ...or a cleanup.
871 } else {
John McCallff8e1152010-07-23 21:56:41 +0000872 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallf1549f62010-07-06 01:34:17 +0000873 }
874
875 // Restore the old IR generation state.
876 Builder.restoreIP(SavedIP);
877
878 return LP;
879}
880
John McCall8e3f8612010-07-13 22:12:14 +0000881namespace {
882 /// A cleanup to call __cxa_end_catch. In many cases, the caught
883 /// exception type lets us state definitively that the thrown exception
884 /// type does not have a destructor. In particular:
885 /// - Catch-alls tell us nothing, so we have to conservatively
886 /// assume that the thrown exception might have a destructor.
887 /// - Catches by reference behave according to their base types.
888 /// - Catches of non-record types will only trigger for exceptions
889 /// of non-record types, which never have destructors.
890 /// - Catches of record types can trigger for arbitrary subclasses
891 /// of the caught type, so we have to assume the actual thrown
892 /// exception type might have a throwing destructor, even if the
893 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +0000894 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +0000895 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
896 bool MightThrow;
897
898 void Emit(CodeGenFunction &CGF, bool IsForEH) {
899 if (!MightThrow) {
900 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
901 return;
902 }
903
904 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
905 }
906 };
907}
908
John McCallf1549f62010-07-06 01:34:17 +0000909/// Emits a call to __cxa_begin_catch and enters a cleanup to call
910/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +0000911///
912/// \param EndMightThrow - true if __cxa_end_catch might throw
913static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
914 llvm::Value *Exn,
915 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +0000916 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
917 Call->setDoesNotThrow();
918
John McCall1f0fca52010-07-21 07:22:38 +0000919 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +0000920
921 return Call;
922}
923
924/// A "special initializer" callback for initializing a catch
925/// parameter during catch initialization.
926static void InitCatchParam(CodeGenFunction &CGF,
927 const VarDecl &CatchParam,
928 llvm::Value *ParamAddr) {
929 // Load the exception from where the landing pad saved it.
930 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
931
932 CanQualType CatchType =
933 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
934 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
935
936 // If we're catching by reference, we can just cast the object
937 // pointer to the appropriate pointer.
938 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +0000939 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
940 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +0000941
John McCallf1549f62010-07-06 01:34:17 +0000942 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +0000943 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +0000944
945 // We have no way to tell the personality function that we're
946 // catching by reference, so if we're catching a pointer,
947 // __cxa_begin_catch will actually return that pointer by value.
948 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
949 QualType PointeeType = PT->getPointeeType();
950
951 // When catching by reference, generally we should just ignore
952 // this by-value pointer and use the exception object instead.
953 if (!PointeeType->isRecordType()) {
954
955 // Exn points to the struct _Unwind_Exception header, which
956 // we have to skip past in order to reach the exception data.
957 unsigned HeaderSize =
958 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
959 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
960
961 // However, if we're catching a pointer-to-record type that won't
962 // work, because the personality function might have adjusted
963 // the pointer. There's actually no way for us to fully satisfy
964 // the language/ABI contract here: we can't use Exn because it
965 // might have the wrong adjustment, but we can't use the by-value
966 // pointer because it's off by a level of abstraction.
967 //
968 // The current solution is to dump the adjusted pointer into an
969 // alloca, which breaks language semantics (because changing the
970 // pointer doesn't change the exception) but at least works.
971 // The better solution would be to filter out non-exact matches
972 // and rethrow them, but this is tricky because the rethrow
973 // really needs to be catchable by other sites at this landing
974 // pad. The best solution is to fix the personality function.
975 } else {
976 // Pull the pointer for the reference type off.
977 const llvm::Type *PtrTy =
978 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
979
980 // Create the temporary and write the adjusted pointer into it.
981 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
982 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
983 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
984
985 // Bind the reference to the temporary.
986 AdjustedExn = ExnPtrTmp;
987 }
988 }
989
John McCallf1549f62010-07-06 01:34:17 +0000990 llvm::Value *ExnCast =
991 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
992 CGF.Builder.CreateStore(ExnCast, ParamAddr);
993 return;
994 }
995
996 // Non-aggregates (plus complexes).
997 bool IsComplex = false;
998 if (!CGF.hasAggregateLLVMType(CatchType) ||
999 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +00001000 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001001
1002 // If the catch type is a pointer type, __cxa_begin_catch returns
1003 // the pointer by value.
1004 if (CatchType->hasPointerRepresentation()) {
1005 llvm::Value *CastExn =
1006 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1007 CGF.Builder.CreateStore(CastExn, ParamAddr);
1008 return;
1009 }
1010
1011 // Otherwise, it returns a pointer into the exception object.
1012
1013 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1014 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1015
1016 if (IsComplex) {
1017 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1018 ParamAddr, /*volatile*/ false);
1019 } else {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001020 unsigned Alignment =
1021 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallf1549f62010-07-06 01:34:17 +00001022 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001023 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1024 CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001025 }
1026 return;
1027 }
1028
John McCallacff6962011-02-16 08:39:19 +00001029 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallf1549f62010-07-06 01:34:17 +00001030
1031 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1032
John McCallacff6962011-02-16 08:39:19 +00001033 // Check for a copy expression. If we don't have a copy expression,
1034 // that means a trivial copy is okay.
John McCalle996ffd2011-02-16 08:02:54 +00001035 const Expr *copyExpr = CatchParam.getInit();
1036 if (!copyExpr) {
John McCallacff6962011-02-16 08:39:19 +00001037 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1038 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1039 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001040 return;
1041 }
1042
1043 // We have to call __cxa_get_exception_ptr to get the adjusted
1044 // pointer before copying.
John McCalle996ffd2011-02-16 08:02:54 +00001045 llvm::CallInst *rawAdjustedExn =
John McCallf1549f62010-07-06 01:34:17 +00001046 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
John McCalle996ffd2011-02-16 08:02:54 +00001047 rawAdjustedExn->setDoesNotThrow();
John McCallf1549f62010-07-06 01:34:17 +00001048
John McCalle996ffd2011-02-16 08:02:54 +00001049 // Cast that to the appropriate type.
1050 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallf1549f62010-07-06 01:34:17 +00001051
John McCalle996ffd2011-02-16 08:02:54 +00001052 // The copy expression is defined in terms of an OpaqueValueExpr.
1053 // Find it and map it to the adjusted expression.
1054 CodeGenFunction::OpaqueValueMapping
John McCall56ca35d2011-02-17 10:25:35 +00001055 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1056 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallf1549f62010-07-06 01:34:17 +00001057
1058 // Call the copy ctor in a terminate scope.
1059 CGF.EHStack.pushTerminate();
John McCalle996ffd2011-02-16 08:02:54 +00001060
1061 // Perform the copy construction.
1062 CGF.EmitAggExpr(copyExpr, AggValueSlot::forAddr(ParamAddr, false, false));
1063
1064 // Leave the terminate scope.
John McCallf1549f62010-07-06 01:34:17 +00001065 CGF.EHStack.popTerminate();
1066
John McCalle996ffd2011-02-16 08:02:54 +00001067 // Undo the opaque value mapping.
1068 opaque.pop();
1069
John McCallf1549f62010-07-06 01:34:17 +00001070 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001071 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001072}
1073
1074/// Begins a catch statement by initializing the catch variable and
1075/// calling __cxa_begin_catch.
John McCalle996ffd2011-02-16 08:02:54 +00001076static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallf1549f62010-07-06 01:34:17 +00001077 // We have to be very careful with the ordering of cleanups here:
1078 // C++ [except.throw]p4:
1079 // The destruction [of the exception temporary] occurs
1080 // immediately after the destruction of the object declared in
1081 // the exception-declaration in the handler.
1082 //
1083 // So the precise ordering is:
1084 // 1. Construct catch variable.
1085 // 2. __cxa_begin_catch
1086 // 3. Enter __cxa_end_catch cleanup
1087 // 4. Enter dtor cleanup
1088 //
John McCall34695852011-02-22 06:44:22 +00001089 // We do this by using a slightly abnormal initialization process.
1090 // Delegation sequence:
John McCallf1549f62010-07-06 01:34:17 +00001091 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCall34695852011-02-22 06:44:22 +00001092 // - EmitAutoVarAlloca creates the variable and debug info
John McCallf1549f62010-07-06 01:34:17 +00001093 // - InitCatchParam initializes the variable from the exception
John McCall34695852011-02-22 06:44:22 +00001094 // - CallBeginCatch calls __cxa_begin_catch
1095 // - CallBeginCatch enters the __cxa_end_catch cleanup
1096 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallf1549f62010-07-06 01:34:17 +00001097 // - EmitCXXTryStmt emits the code for the catch body
1098 // - EmitCXXTryStmt close the RunCleanupsScope
1099
1100 VarDecl *CatchParam = S->getExceptionDecl();
1101 if (!CatchParam) {
1102 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall8e3f8612010-07-13 22:12:14 +00001103 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001104 return;
1105 }
1106
1107 // Emit the local.
John McCall34695852011-02-22 06:44:22 +00001108 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1109 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
1110 CGF.EmitAutoVarCleanups(var);
John McCall9fc6a772010-02-19 09:25:03 +00001111}
1112
John McCallfcd5c0c2010-07-13 22:24:23 +00001113namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001114 struct CallRethrow : EHScopeStack::Cleanup {
John McCallfcd5c0c2010-07-13 22:24:23 +00001115 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1116 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1117 }
1118 };
1119}
1120
John McCall59a70002010-07-07 06:56:46 +00001121void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001122 unsigned NumHandlers = S.getNumHandlers();
1123 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1124 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001125
John McCallf1549f62010-07-06 01:34:17 +00001126 // Copy the handler blocks off before we pop the EH stack. Emitting
1127 // the handlers might scribble on this memory.
1128 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1129 memcpy(Handlers.data(), CatchScope.begin(),
1130 NumHandlers * sizeof(EHCatchScope::Handler));
1131 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001132
John McCallf1549f62010-07-06 01:34:17 +00001133 // The fall-through block.
1134 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001135
John McCallf1549f62010-07-06 01:34:17 +00001136 // We just emitted the body of the try; jump to the continue block.
1137 if (HaveInsertPoint())
1138 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001139
John McCall59a70002010-07-07 06:56:46 +00001140 // Determine if we need an implicit rethrow for all these catch handlers.
1141 bool ImplicitRethrow = false;
1142 if (IsFnTryBlock)
1143 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1144 isa<CXXConstructorDecl>(CurCodeDecl);
1145
John McCallf1549f62010-07-06 01:34:17 +00001146 for (unsigned I = 0; I != NumHandlers; ++I) {
1147 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1148 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001149
John McCallf1549f62010-07-06 01:34:17 +00001150 // Catch the exception if this isn't a catch-all.
1151 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001152
John McCallf1549f62010-07-06 01:34:17 +00001153 // Enter a cleanup scope, including the catch variable and the
1154 // end-catch.
1155 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001156
John McCallf1549f62010-07-06 01:34:17 +00001157 // Initialize the catch variable and set up the cleanups.
1158 BeginCatch(*this, C);
1159
John McCall59a70002010-07-07 06:56:46 +00001160 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001161 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1162 // called, and so it is pushed after BeginCatch.
1163 if (ImplicitRethrow)
John McCall1f0fca52010-07-21 07:22:38 +00001164 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001165
John McCallf1549f62010-07-06 01:34:17 +00001166 // Perform the body of the catch.
1167 EmitStmt(C->getHandlerBlock());
1168
1169 // Fall out through the catch cleanups.
1170 CatchScope.ForceCleanup();
1171
1172 // Branch out of the try.
1173 if (HaveInsertPoint())
1174 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001175 }
1176
John McCallf1549f62010-07-06 01:34:17 +00001177 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001178}
Mike Stumpd88ea562009-12-09 03:35:49 +00001179
John McCall55b20fc2010-07-21 00:52:03 +00001180namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001181 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001182 llvm::Value *ForEHVar;
1183 llvm::Value *EndCatchFn;
1184 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1185 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1186
1187 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1188 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1189 llvm::BasicBlock *CleanupContBB =
1190 CGF.createBasicBlock("finally.cleanup.cont");
1191
1192 llvm::Value *ShouldEndCatch =
1193 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1194 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1195 CGF.EmitBlock(EndCatchBB);
1196 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1197 CGF.EmitBlock(CleanupContBB);
1198 }
1199 };
John McCall77199712010-07-21 05:47:49 +00001200
John McCall1f0fca52010-07-21 07:22:38 +00001201 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001202 const Stmt *Body;
1203 llvm::Value *ForEHVar;
1204 llvm::Value *EndCatchFn;
1205 llvm::Value *RethrowFn;
1206 llvm::Value *SavedExnVar;
1207
1208 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1209 llvm::Value *EndCatchFn,
1210 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1211 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1212 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1213
1214 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1215 // Enter a cleanup to call the end-catch function if one was provided.
1216 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001217 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1218 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001219
John McCalld96a8e72010-08-11 00:16:14 +00001220 // Save the current cleanup destination in case there are
1221 // cleanups in the finally block.
1222 llvm::Value *SavedCleanupDest =
1223 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1224 "cleanup.dest.saved");
1225
John McCall77199712010-07-21 05:47:49 +00001226 // Emit the finally block.
1227 CGF.EmitStmt(Body);
1228
1229 // If the end of the finally is reachable, check whether this was
1230 // for EH. If so, rethrow.
1231 if (CGF.HaveInsertPoint()) {
1232 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1233 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1234
1235 llvm::Value *ShouldRethrow =
1236 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1237 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1238
1239 CGF.EmitBlock(RethrowBB);
1240 if (SavedExnVar) {
1241 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1242 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1243 } else {
1244 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1245 }
1246 CGF.Builder.CreateUnreachable();
1247
1248 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001249
1250 // Restore the cleanup destination.
1251 CGF.Builder.CreateStore(SavedCleanupDest,
1252 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001253 }
1254
1255 // Leave the end-catch cleanup. As an optimization, pretend that
1256 // the fallthrough path was inaccessible; we've dynamically proven
1257 // that we're not in the EH case along that path.
1258 if (EndCatchFn) {
1259 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1260 CGF.PopCleanupBlock();
1261 CGF.Builder.restoreIP(SavedIP);
1262 }
1263
1264 // Now make sure we actually have an insertion point or the
1265 // cleanup gods will hate us.
1266 CGF.EnsureInsertPoint();
1267 }
1268 };
John McCall55b20fc2010-07-21 00:52:03 +00001269}
1270
John McCallf1549f62010-07-06 01:34:17 +00001271/// Enters a finally block for an implementation using zero-cost
1272/// exceptions. This is mostly general, but hard-codes some
1273/// language/ABI-specific behavior in the catch-all sections.
1274CodeGenFunction::FinallyInfo
1275CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1276 llvm::Constant *BeginCatchFn,
1277 llvm::Constant *EndCatchFn,
1278 llvm::Constant *RethrowFn) {
1279 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1280 "begin/end catch functions not paired");
1281 assert(RethrowFn && "rethrow function is required");
Mike Stumpd88ea562009-12-09 03:35:49 +00001282
John McCallf1549f62010-07-06 01:34:17 +00001283 // The rethrow function has one of the following two types:
1284 // void (*)()
1285 // void (*)(void*)
1286 // In the latter case we need to pass it the exception object.
1287 // But we can't use the exception slot because the @finally might
1288 // have a landing pad (which would overwrite the exception slot).
1289 const llvm::FunctionType *RethrowFnTy =
1290 cast<llvm::FunctionType>(
1291 cast<llvm::PointerType>(RethrowFn->getType())
1292 ->getElementType());
1293 llvm::Value *SavedExnVar = 0;
1294 if (RethrowFnTy->getNumParams())
1295 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001296
John McCallf1549f62010-07-06 01:34:17 +00001297 // A finally block is a statement which must be executed on any edge
1298 // out of a given scope. Unlike a cleanup, the finally block may
1299 // contain arbitrary control flow leading out of itself. In
1300 // addition, finally blocks should always be executed, even if there
1301 // are no catch handlers higher on the stack. Therefore, we
1302 // surround the protected scope with a combination of a normal
1303 // cleanup (to catch attempts to break out of the block via normal
1304 // control flow) and an EH catch-all (semantically "outside" any try
1305 // statement to which the finally block might have been attached).
1306 // The finally block itself is generated in the context of a cleanup
1307 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001308
John McCallf1549f62010-07-06 01:34:17 +00001309 FinallyInfo Info;
John McCall3d3ec1c2010-04-21 10:05:39 +00001310
John McCallf1549f62010-07-06 01:34:17 +00001311 // Jump destination for performing the finally block on an exception
1312 // edge. We'll never actually reach this block, so unreachable is
1313 // fine.
1314 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001315
John McCallf1549f62010-07-06 01:34:17 +00001316 // Whether the finally block is being executed for EH purposes.
John McCalld16c2cf2011-02-08 08:22:06 +00001317 llvm::AllocaInst *ForEHVar = CreateTempAlloca(Builder.getInt1Ty(),
John McCallf1549f62010-07-06 01:34:17 +00001318 "finally.for-eh");
1319 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpd88ea562009-12-09 03:35:49 +00001320
John McCallf1549f62010-07-06 01:34:17 +00001321 // Enter a normal cleanup which will perform the @finally block.
John McCall1f0fca52010-07-21 07:22:38 +00001322 EHStack.pushCleanup<PerformFinally>(NormalCleanup, Body,
1323 ForEHVar, EndCatchFn,
1324 RethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001325
1326 // Enter a catch-all scope.
1327 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1328 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1329 Builder.SetInsertPoint(CatchAllBB);
1330
1331 // If there's a begin-catch function, call it.
1332 if (BeginCatchFn) {
1333 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1334 ->setDoesNotThrow();
1335 }
1336
1337 // If we need to remember the exception pointer to rethrow later, do so.
1338 if (SavedExnVar) {
1339 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1340 Builder.CreateStore(SavedExn, SavedExnVar);
1341 }
1342
1343 // Tell the finally block that we're in EH.
1344 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1345
1346 // Thread a jump through the finally cleanup.
1347 EmitBranchThroughCleanup(RethrowDest);
1348
1349 Builder.restoreIP(SavedIP);
1350
1351 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1352 CatchScope->setCatchAllHandler(0, CatchAllBB);
1353
1354 return Info;
1355}
1356
1357void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1358 // Leave the finally catch-all.
1359 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1360 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1361 EHStack.popCatch();
1362
1363 // And leave the normal cleanup.
1364 PopCleanupBlock();
1365
1366 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1367 EmitBlock(CatchAllBB, true);
1368
1369 Builder.restoreIP(SavedIP);
1370}
1371
1372llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1373 if (TerminateLandingPad)
1374 return TerminateLandingPad;
1375
1376 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1377
1378 // This will get inserted at the end of the function.
1379 TerminateLandingPad = createBasicBlock("terminate.lpad");
1380 Builder.SetInsertPoint(TerminateLandingPad);
1381
1382 // Tell the backend that this is a landing pad.
1383 llvm::CallInst *Exn =
1384 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1385 Exn->setDoesNotThrow();
John McCall8262b6a2010-07-17 00:43:08 +00001386
1387 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallf1549f62010-07-06 01:34:17 +00001388
1389 // Tell the backend what the exception table should be:
1390 // nothing but a catch-all.
John McCallb2593832010-09-16 06:16:50 +00001391 llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
John McCallf1549f62010-07-06 01:34:17 +00001392 getCatchAllValue(*this) };
1393 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1394 Args, Args+3, "eh.selector")
1395 ->setDoesNotThrow();
1396
1397 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1398 TerminateCall->setDoesNotReturn();
1399 TerminateCall->setDoesNotThrow();
John McCalld16c2cf2011-02-08 08:22:06 +00001400 Builder.CreateUnreachable();
Mike Stumpd88ea562009-12-09 03:35:49 +00001401
John McCallf1549f62010-07-06 01:34:17 +00001402 // Restore the saved insertion state.
1403 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001404
John McCallf1549f62010-07-06 01:34:17 +00001405 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001406}
Mike Stump9b39c512009-12-09 22:59:31 +00001407
1408llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001409 if (TerminateHandler)
1410 return TerminateHandler;
1411
John McCallf1549f62010-07-06 01:34:17 +00001412 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001413
John McCallf1549f62010-07-06 01:34:17 +00001414 // Set up the terminate handler. This block is inserted at the very
1415 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001416 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001417 Builder.SetInsertPoint(TerminateHandler);
1418 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001419 TerminateCall->setDoesNotReturn();
1420 TerminateCall->setDoesNotThrow();
1421 Builder.CreateUnreachable();
1422
John McCall3d3ec1c2010-04-21 10:05:39 +00001423 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001424 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001425
Mike Stump9b39c512009-12-09 22:59:31 +00001426 return TerminateHandler;
1427}
John McCallf1549f62010-07-06 01:34:17 +00001428
John McCallff8e1152010-07-23 21:56:41 +00001429CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1430 if (RethrowBlock.isValid()) return RethrowBlock;
1431
1432 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1433
1434 // We emit a jump to a notional label at the outermost unwind state.
1435 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1436 Builder.SetInsertPoint(Unwind);
1437
1438 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1439
1440 // This can always be a call because we necessarily didn't find
1441 // anything on the EH stack which needs our help.
John McCallb2593832010-09-16 06:16:50 +00001442 llvm::StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCallff8e1152010-07-23 21:56:41 +00001443 llvm::Constant *RethrowFn;
John McCallb2593832010-09-16 06:16:50 +00001444 if (!RethrowName.empty())
John McCallff8e1152010-07-23 21:56:41 +00001445 RethrowFn = getCatchallRethrowFn(*this, RethrowName);
1446 else
1447 RethrowFn = getUnwindResumeOrRethrowFn();
1448
1449 Builder.CreateCall(RethrowFn, Builder.CreateLoad(getExceptionSlot()))
1450 ->setDoesNotReturn();
1451 Builder.CreateUnreachable();
1452
1453 Builder.restoreIP(SavedIP);
1454
1455 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1456 return RethrowBlock;
1457}
1458