CGException.cpp revision 9cbe4f0ba01ec304e1e3d071c071f7bca33631c0
1//===--- 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
14#include "clang/AST/StmtCXX.h"
15
16#include "llvm/Intrinsics.h"
17#include "llvm/IntrinsicInst.h"
18#include "llvm/Support/CallSite.h"
19
20#include "CGObjCRuntime.h"
21#include "CodeGenFunction.h"
22#include "CGException.h"
23#include "CGCleanup.h"
24#include "TargetInfo.h"
25
26using namespace clang;
27using namespace CodeGen;
28
29static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
30  // void *__cxa_allocate_exception(size_t thrown_size);
31
32  llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
33  llvm::Type *ArgTys[] = { SizeTy };
34  const llvm::FunctionType *FTy =
35    llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
36                            ArgTys, /*IsVarArgs=*/false);
37
38  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
39}
40
41static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
42  // void __cxa_free_exception(void *thrown_exception);
43
44  llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
45  llvm::Type *ArgTys[] = { Int8PtrTy };
46  const llvm::FunctionType *FTy =
47    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
48                            ArgTys, /*IsVarArgs=*/false);
49
50  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
51}
52
53static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
54  // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
55  //                  void (*dest) (void *));
56
57  llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
58  llvm::Type *Args[3] = { Int8PtrTy, Int8PtrTy, Int8PtrTy };
59  const llvm::FunctionType *FTy =
60    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
61                            Args, /*IsVarArgs=*/false);
62
63  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
64}
65
66static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
67  // void __cxa_rethrow();
68
69  const llvm::FunctionType *FTy =
70    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
71                            /*IsVarArgs=*/false);
72
73  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
74}
75
76static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
77  // void *__cxa_get_exception_ptr(void*);
78
79  llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
80  llvm::Type *ArgTys[] = { Int8PtrTy };
81  const llvm::FunctionType *FTy =
82    llvm::FunctionType::get(Int8PtrTy, ArgTys, /*IsVarArgs=*/false);
83
84  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
85}
86
87static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
88  // void *__cxa_begin_catch(void*);
89
90  llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
91  llvm::Type *ArgTys[] = { Int8PtrTy };
92  const llvm::FunctionType *FTy =
93    llvm::FunctionType::get(Int8PtrTy, ArgTys, /*IsVarArgs=*/false);
94
95  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
96}
97
98static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
99  // void __cxa_end_catch();
100
101  const llvm::FunctionType *FTy =
102    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
103                            /*IsVarArgs=*/false);
104
105  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
106}
107
108static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
109  // void __cxa_call_unexepcted(void *thrown_exception);
110
111  llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
112  llvm::Type *ArgTys[] = { Int8PtrTy };
113  const llvm::FunctionType *FTy =
114    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
115                            ArgTys, /*IsVarArgs=*/false);
116
117  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
118}
119
120llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
121  llvm::Type *ArgTys[] = { Int8PtrTy };
122  const llvm::FunctionType *FTy =
123    llvm::FunctionType::get(VoidTy, ArgTys, /*IsVarArgs=*/false);
124
125  if (CGM.getLangOptions().SjLjExceptions)
126    return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
127  return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
128}
129
130llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
131  llvm::Type *ArgTys[] = { Int8PtrTy };
132  const llvm::FunctionType *FTy =
133    llvm::FunctionType::get(VoidTy, ArgTys, /*IsVarArgs=*/false);
134
135  if (CGM.getLangOptions().SjLjExceptions)
136    return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
137  return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
138}
139
140static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
141  // void __terminate();
142
143  const llvm::FunctionType *FTy =
144    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
145                            /*IsVarArgs=*/false);
146
147  llvm::StringRef name;
148
149  // In C++, use std::terminate().
150  if (CGF.getLangOptions().CPlusPlus)
151    name = "_ZSt9terminatev"; // FIXME: mangling!
152  else if (CGF.getLangOptions().ObjC1 &&
153           CGF.CGM.getCodeGenOpts().ObjCRuntimeHasTerminate)
154    name = "objc_terminate";
155  else
156    name = "abort";
157  return CGF.CGM.CreateRuntimeFunction(FTy, name);
158}
159
160static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
161                                            llvm::StringRef Name) {
162  llvm::Type *Int8PtrTy =
163    llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
164  const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
165  llvm::Type *ArgTys[] = { Int8PtrTy };
166  const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, ArgTys,
167                                                          /*IsVarArgs=*/false);
168
169  return CGF.CGM.CreateRuntimeFunction(FTy, Name);
170}
171
172const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
173const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
174const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
175const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
176const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
177const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
178                                            "objc_exception_throw");
179const EHPersonality EHPersonality::GNU_ObjCXX("__gnustep_objcxx_personality_v0");
180
181static const EHPersonality &getCPersonality(const LangOptions &L) {
182  if (L.SjLjExceptions)
183    return EHPersonality::GNU_C_SJLJ;
184  return EHPersonality::GNU_C;
185}
186
187static const EHPersonality &getObjCPersonality(const LangOptions &L) {
188  if (L.NeXTRuntime) {
189    if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
190    else return getCPersonality(L);
191  } else {
192    return EHPersonality::GNU_ObjC;
193  }
194}
195
196static const EHPersonality &getCXXPersonality(const LangOptions &L) {
197  if (L.SjLjExceptions)
198    return EHPersonality::GNU_CPlusPlus_SJLJ;
199  else
200    return EHPersonality::GNU_CPlusPlus;
201}
202
203/// Determines the personality function to use when both C++
204/// and Objective-C exceptions are being caught.
205static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
206  // The ObjC personality defers to the C++ personality for non-ObjC
207  // handlers.  Unlike the C++ case, we use the same personality
208  // function on targets using (backend-driven) SJLJ EH.
209  if (L.NeXTRuntime) {
210    if (L.ObjCNonFragileABI)
211      return EHPersonality::NeXT_ObjC;
212
213    // In the fragile ABI, just use C++ exception handling and hope
214    // they're not doing crazy exception mixing.
215    else
216      return getCXXPersonality(L);
217  }
218
219  // The GNU runtime's personality function inherently doesn't support
220  // mixed EH.  Use the C++ personality just to avoid returning null.
221  return EHPersonality::GNU_ObjCXX;
222}
223
224const EHPersonality &EHPersonality::get(const LangOptions &L) {
225  if (L.CPlusPlus && L.ObjC1)
226    return getObjCXXPersonality(L);
227  else if (L.CPlusPlus)
228    return getCXXPersonality(L);
229  else if (L.ObjC1)
230    return getObjCPersonality(L);
231  else
232    return getCPersonality(L);
233}
234
235static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
236                                        const EHPersonality &Personality) {
237  llvm::Constant *Fn =
238    CGM.CreateRuntimeFunction(llvm::FunctionType::get(
239                                llvm::Type::getInt32Ty(CGM.getLLVMContext()),
240                                true),
241                              Personality.getPersonalityFnName());
242  return Fn;
243}
244
245static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
246                                        const EHPersonality &Personality) {
247  llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
248  return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
249}
250
251/// Check whether a personality function could reasonably be swapped
252/// for a C++ personality function.
253static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
254  for (llvm::Constant::use_iterator
255         I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
256    llvm::User *User = *I;
257
258    // Conditionally white-list bitcasts.
259    if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
260      if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
261      if (!PersonalityHasOnlyCXXUses(CE))
262        return false;
263      continue;
264    }
265
266    // Otherwise, it has to be a selector call.
267    if (!isa<llvm::EHSelectorInst>(User)) return false;
268
269    llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
270    for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
271      // Look for something that would've been returned by the ObjC
272      // runtime's GetEHType() method.
273      llvm::GlobalVariable *GV
274        = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
275      if (!GV) continue;
276
277      // ObjC EH selector entries are always global variables with
278      // names starting like this.
279      if (GV->getName().startswith("OBJC_EHTYPE"))
280        return false;
281    }
282  }
283
284  return true;
285}
286
287/// Try to use the C++ personality function in ObjC++.  Not doing this
288/// can cause some incompatibilities with gcc, which is more
289/// aggressive about only using the ObjC++ personality in a function
290/// when it really needs it.
291void CodeGenModule::SimplifyPersonality() {
292  // For now, this is really a Darwin-specific operation.
293  if (!Context.Target.getTriple().isOSDarwin())
294    return;
295
296  // If we're not in ObjC++ -fexceptions, there's nothing to do.
297  if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
298    return;
299
300  const EHPersonality &ObjCXX = EHPersonality::get(Features);
301  const EHPersonality &CXX = getCXXPersonality(Features);
302  if (&ObjCXX == &CXX ||
303      ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
304    return;
305
306  llvm::Function *Fn =
307    getModule().getFunction(ObjCXX.getPersonalityFnName());
308
309  // Nothing to do if it's unused.
310  if (!Fn || Fn->use_empty()) return;
311
312  // Can't do the optimization if it has non-C++ uses.
313  if (!PersonalityHasOnlyCXXUses(Fn)) return;
314
315  // Create the C++ personality function and kill off the old
316  // function.
317  llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
318
319  // This can happen if the user is screwing with us.
320  if (Fn->getType() != CXXFn->getType()) return;
321
322  Fn->replaceAllUsesWith(CXXFn);
323  Fn->eraseFromParent();
324}
325
326/// Returns the value to inject into a selector to indicate the
327/// presence of a catch-all.
328static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
329  // Possibly we should use @llvm.eh.catch.all.value here.
330  return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
331}
332
333/// Returns the value to inject into a selector to indicate the
334/// presence of a cleanup.
335static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
336  return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
337}
338
339namespace {
340  /// A cleanup to free the exception object if its initialization
341  /// throws.
342  struct FreeException {
343    static void Emit(CodeGenFunction &CGF, bool forEH,
344                     llvm::Value *exn) {
345      CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
346        ->setDoesNotThrow();
347    }
348  };
349}
350
351// Emits an exception expression into the given location.  This
352// differs from EmitAnyExprToMem only in that, if a final copy-ctor
353// call is required, an exception within that copy ctor causes
354// std::terminate to be invoked.
355static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
356                             llvm::Value *addr) {
357  // Make sure the exception object is cleaned up if there's an
358  // exception during initialization.
359  CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
360  EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
361
362  // __cxa_allocate_exception returns a void*;  we need to cast this
363  // to the appropriate type for the object.
364  const llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
365  llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
366
367  // FIXME: this isn't quite right!  If there's a final unelided call
368  // to a copy constructor, then according to [except.terminate]p1 we
369  // must call std::terminate() if that constructor throws, because
370  // technically that copy occurs after the exception expression is
371  // evaluated but before the exception is caught.  But the best way
372  // to handle that is to teach EmitAggExpr to do the final copy
373  // differently if it can't be elided.
374  CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
375                       /*IsInit*/ true);
376
377  // Deactivate the cleanup block.
378  CGF.DeactivateCleanupBlock(cleanup);
379}
380
381llvm::Value *CodeGenFunction::getExceptionSlot() {
382  if (!ExceptionSlot)
383    ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
384  return ExceptionSlot;
385}
386
387llvm::Value *CodeGenFunction::getEHSelectorSlot() {
388  if (!EHSelectorSlot)
389    EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
390  return EHSelectorSlot;
391}
392
393void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
394  if (!E->getSubExpr()) {
395    if (getInvokeDest()) {
396      Builder.CreateInvoke(getReThrowFn(*this),
397                           getUnreachableBlock(),
398                           getInvokeDest())
399        ->setDoesNotReturn();
400    } else {
401      Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
402      Builder.CreateUnreachable();
403    }
404
405    // throw is an expression, and the expression emitters expect us
406    // to leave ourselves at a valid insertion point.
407    EmitBlock(createBasicBlock("throw.cont"));
408
409    return;
410  }
411
412  QualType ThrowType = E->getSubExpr()->getType();
413
414  // Now allocate the exception object.
415  const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
416  uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
417
418  llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
419  llvm::CallInst *ExceptionPtr =
420    Builder.CreateCall(AllocExceptionFn,
421                       llvm::ConstantInt::get(SizeTy, TypeSize),
422                       "exception");
423  ExceptionPtr->setDoesNotThrow();
424
425  EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
426
427  // Now throw the exception.
428  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
429  llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
430                                                         /*ForEH=*/true);
431
432  // The address of the destructor.  If the exception type has a
433  // trivial destructor (or isn't a record), we just pass null.
434  llvm::Constant *Dtor = 0;
435  if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
436    CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
437    if (!Record->hasTrivialDestructor()) {
438      CXXDestructorDecl *DtorD = Record->getDestructor();
439      Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
440      Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
441    }
442  }
443  if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
444
445  if (getInvokeDest()) {
446    llvm::InvokeInst *ThrowCall =
447      Builder.CreateInvoke3(getThrowFn(*this),
448                            getUnreachableBlock(), getInvokeDest(),
449                            ExceptionPtr, TypeInfo, Dtor);
450    ThrowCall->setDoesNotReturn();
451  } else {
452    llvm::CallInst *ThrowCall =
453      Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
454    ThrowCall->setDoesNotReturn();
455    Builder.CreateUnreachable();
456  }
457
458  // throw is an expression, and the expression emitters expect us
459  // to leave ourselves at a valid insertion point.
460  EmitBlock(createBasicBlock("throw.cont"));
461}
462
463void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
464  if (!CGM.getLangOptions().CXXExceptions)
465    return;
466
467  const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
468  if (FD == 0)
469    return;
470  const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
471  if (Proto == 0)
472    return;
473
474  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
475  if (isNoexceptExceptionSpec(EST)) {
476    if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
477      // noexcept functions are simple terminate scopes.
478      EHStack.pushTerminate();
479    }
480  } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
481    unsigned NumExceptions = Proto->getNumExceptions();
482    EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
483
484    for (unsigned I = 0; I != NumExceptions; ++I) {
485      QualType Ty = Proto->getExceptionType(I);
486      QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
487      llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
488                                                        /*ForEH=*/true);
489      Filter->setFilter(I, EHType);
490    }
491  }
492}
493
494void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
495  if (!CGM.getLangOptions().CXXExceptions)
496    return;
497
498  const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
499  if (FD == 0)
500    return;
501  const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
502  if (Proto == 0)
503    return;
504
505  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
506  if (isNoexceptExceptionSpec(EST)) {
507    if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
508      EHStack.popTerminate();
509    }
510  } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
511    EHStack.popFilter();
512  }
513}
514
515void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
516  EnterCXXTryStmt(S);
517  EmitStmt(S.getTryBlock());
518  ExitCXXTryStmt(S);
519}
520
521void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
522  unsigned NumHandlers = S.getNumHandlers();
523  EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
524
525  for (unsigned I = 0; I != NumHandlers; ++I) {
526    const CXXCatchStmt *C = S.getHandler(I);
527
528    llvm::BasicBlock *Handler = createBasicBlock("catch");
529    if (C->getExceptionDecl()) {
530      // FIXME: Dropping the reference type on the type into makes it
531      // impossible to correctly implement catch-by-reference
532      // semantics for pointers.  Unfortunately, this is what all
533      // existing compilers do, and it's not clear that the standard
534      // personality routine is capable of doing this right.  See C++ DR 388:
535      //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
536      QualType CaughtType = C->getCaughtType();
537      CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
538
539      llvm::Value *TypeInfo = 0;
540      if (CaughtType->isObjCObjectPointerType())
541        TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
542      else
543        TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
544      CatchScope->setHandler(I, TypeInfo, Handler);
545    } else {
546      // No exception decl indicates '...', a catch-all.
547      CatchScope->setCatchAllHandler(I, Handler);
548    }
549  }
550}
551
552/// Check whether this is a non-EH scope, i.e. a scope which doesn't
553/// affect exception handling.  Currently, the only non-EH scopes are
554/// normal-only cleanup scopes.
555static bool isNonEHScope(const EHScope &S) {
556  switch (S.getKind()) {
557  case EHScope::Cleanup:
558    return !cast<EHCleanupScope>(S).isEHCleanup();
559  case EHScope::Filter:
560  case EHScope::Catch:
561  case EHScope::Terminate:
562    return false;
563  }
564
565  // Suppress warning.
566  return false;
567}
568
569llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
570  assert(EHStack.requiresLandingPad());
571  assert(!EHStack.empty());
572
573  if (!CGM.getLangOptions().Exceptions)
574    return 0;
575
576  // Check the innermost scope for a cached landing pad.  If this is
577  // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
578  llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
579  if (LP) return LP;
580
581  // Build the landing pad for this scope.
582  LP = EmitLandingPad();
583  assert(LP);
584
585  // Cache the landing pad on the innermost scope.  If this is a
586  // non-EH scope, cache the landing pad on the enclosing scope, too.
587  for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
588    ir->setCachedLandingPad(LP);
589    if (!isNonEHScope(*ir)) break;
590  }
591
592  return LP;
593}
594
595// This code contains a hack to work around a design flaw in
596// LLVM's EH IR which breaks semantics after inlining.  This same
597// hack is implemented in llvm-gcc.
598//
599// The LLVM EH abstraction is basically a thin veneer over the
600// traditional GCC zero-cost design: for each range of instructions
601// in the function, there is (at most) one "landing pad" with an
602// associated chain of EH actions.  A language-specific personality
603// function interprets this chain of actions and (1) decides whether
604// or not to resume execution at the landing pad and (2) if so,
605// provides an integer indicating why it's stopping.  In LLVM IR,
606// the association of a landing pad with a range of instructions is
607// achieved via an invoke instruction, the chain of actions becomes
608// the arguments to the @llvm.eh.selector call, and the selector
609// call returns the integer indicator.  Other than the required
610// presence of two intrinsic function calls in the landing pad,
611// the IR exactly describes the layout of the output code.
612//
613// A principal advantage of this design is that it is completely
614// language-agnostic; in theory, the LLVM optimizers can treat
615// landing pads neutrally, and targets need only know how to lower
616// the intrinsics to have a functioning exceptions system (assuming
617// that platform exceptions follow something approximately like the
618// GCC design).  Unfortunately, landing pads cannot be combined in a
619// language-agnostic way: given selectors A and B, there is no way
620// to make a single landing pad which faithfully represents the
621// semantics of propagating an exception first through A, then
622// through B, without knowing how the personality will interpret the
623// (lowered form of the) selectors.  This means that inlining has no
624// choice but to crudely chain invokes (i.e., to ignore invokes in
625// the inlined function, but to turn all unwindable calls into
626// invokes), which is only semantically valid if every unwind stops
627// at every landing pad.
628//
629// Therefore, the invoke-inline hack is to guarantee that every
630// landing pad has a catch-all.
631enum CleanupHackLevel_t {
632  /// A level of hack that requires that all landing pads have
633  /// catch-alls.
634  CHL_MandatoryCatchall,
635
636  /// A level of hack that requires that all landing pads handle
637  /// cleanups.
638  CHL_MandatoryCleanup,
639
640  /// No hacks at all;  ideal IR generation.
641  CHL_Ideal
642};
643const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
644
645llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
646  assert(EHStack.requiresLandingPad());
647
648  for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
649    assert(ir != EHStack.end() &&
650           "stack requiring landing pad is nothing but non-EH scopes?");
651
652    // If this is a terminate scope, just use the singleton terminate
653    // landing pad.
654    if (isa<EHTerminateScope>(*ir))
655      return getTerminateLandingPad();
656
657    // If this isn't an EH scope, iterate; otherwise break out.
658    if (!isNonEHScope(*ir)) break;
659    ++ir;
660
661    // We haven't checked this scope for a cached landing pad yet.
662    if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
663      return LP;
664  }
665
666  // Save the current IR generation state.
667  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
668
669  const EHPersonality &Personality = EHPersonality::get(getLangOptions());
670
671  // Create and configure the landing pad.
672  llvm::BasicBlock *LP = createBasicBlock("lpad");
673  EmitBlock(LP);
674
675  // Save the exception pointer.  It's safe to use a single exception
676  // pointer per function because EH cleanups can never have nested
677  // try/catches.
678  llvm::CallInst *Exn =
679    Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
680  Exn->setDoesNotThrow();
681  Builder.CreateStore(Exn, getExceptionSlot());
682
683  // Build the selector arguments.
684  llvm::SmallVector<llvm::Value*, 8> EHSelector;
685  EHSelector.push_back(Exn);
686  EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
687
688  // Accumulate all the handlers in scope.
689  llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
690  UnwindDest CatchAll;
691  bool HasEHCleanup = false;
692  bool HasEHFilter = false;
693  llvm::SmallVector<llvm::Value*, 8> EHFilters;
694  for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
695         I != E; ++I) {
696
697    switch (I->getKind()) {
698    case EHScope::Cleanup:
699      if (!HasEHCleanup)
700        HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
701      // We otherwise don't care about cleanups.
702      continue;
703
704    case EHScope::Filter: {
705      assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
706      assert(!CatchAll.isValid() && "EH filter reached after catch-all");
707
708      // Filter scopes get added to the selector in weird ways.
709      EHFilterScope &Filter = cast<EHFilterScope>(*I);
710      HasEHFilter = true;
711
712      // Add all the filter values which we aren't already explicitly
713      // catching.
714      for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
715        llvm::Value *FV = Filter.getFilter(I);
716        if (!EHHandlers.count(FV))
717          EHFilters.push_back(FV);
718      }
719      goto done;
720    }
721
722    case EHScope::Terminate:
723      // Terminate scopes are basically catch-alls.
724      assert(!CatchAll.isValid());
725      CatchAll = UnwindDest(getTerminateHandler(),
726                            EHStack.getEnclosingEHCleanup(I),
727                            cast<EHTerminateScope>(*I).getDestIndex());
728      goto done;
729
730    case EHScope::Catch:
731      break;
732    }
733
734    EHCatchScope &Catch = cast<EHCatchScope>(*I);
735    for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
736      EHCatchScope::Handler Handler = Catch.getHandler(HI);
737
738      // Catch-all.  We should only have one of these per catch.
739      if (!Handler.Type) {
740        assert(!CatchAll.isValid());
741        CatchAll = UnwindDest(Handler.Block,
742                              EHStack.getEnclosingEHCleanup(I),
743                              Handler.Index);
744        continue;
745      }
746
747      // Check whether we already have a handler for this type.
748      UnwindDest &Dest = EHHandlers[Handler.Type];
749      if (Dest.isValid()) continue;
750
751      EHSelector.push_back(Handler.Type);
752      Dest = UnwindDest(Handler.Block,
753                        EHStack.getEnclosingEHCleanup(I),
754                        Handler.Index);
755    }
756
757    // Stop if we found a catch-all.
758    if (CatchAll.isValid()) break;
759  }
760
761 done:
762  unsigned LastToEmitInLoop = EHSelector.size();
763
764  // If we have a catch-all, add null to the selector.
765  if (CatchAll.isValid()) {
766    EHSelector.push_back(getCatchAllValue(*this));
767
768  // If we have an EH filter, we need to add those handlers in the
769  // right place in the selector, which is to say, at the end.
770  } else if (HasEHFilter) {
771    // Create a filter expression: an integer constant saying how many
772    // filters there are (+1 to avoid ambiguity with 0 for cleanup),
773    // followed by the filter types.  The personality routine only
774    // lands here if the filter doesn't match.
775    EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
776                                                EHFilters.size() + 1));
777    EHSelector.append(EHFilters.begin(), EHFilters.end());
778
779    // Also check whether we need a cleanup.
780    if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup)
781      EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
782                           ? getCatchAllValue(*this)
783                           : getCleanupValue(*this));
784
785  // Otherwise, signal that we at least have cleanups.
786  } else if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup) {
787    EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
788                         ? getCatchAllValue(*this)
789                         : getCleanupValue(*this));
790
791  // At the MandatoryCleanup hack level, we don't need to actually
792  // spuriously tell the unwinder that we have cleanups, but we do
793  // need to always be prepared to handle cleanups.
794  } else if (CleanupHackLevel == CHL_MandatoryCleanup) {
795    // Just don't decrement LastToEmitInLoop.
796
797  } else {
798    assert(LastToEmitInLoop > 2);
799    LastToEmitInLoop--;
800  }
801
802  assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
803
804  // Tell the backend how to generate the landing pad.
805  llvm::CallInst *Selection =
806    Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
807                       EHSelector.begin(), EHSelector.end(), "eh.selector");
808  Selection->setDoesNotThrow();
809
810  // Save the selector value in mandatory-cleanup mode.
811  if (CleanupHackLevel == CHL_MandatoryCleanup)
812    Builder.CreateStore(Selection, getEHSelectorSlot());
813
814  // Select the right handler.
815  llvm::Value *llvm_eh_typeid_for =
816    CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
817
818  // The results of llvm_eh_typeid_for aren't reliable --- at least
819  // not locally --- so we basically have to do this as an 'if' chain.
820  // We walk through the first N-1 catch clauses, testing and chaining,
821  // and then fall into the final clause (which is either a cleanup, a
822  // filter (possibly with a cleanup), a catch-all, or another catch).
823  for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
824    llvm::Value *Type = EHSelector[I];
825    UnwindDest Dest = EHHandlers[Type];
826    assert(Dest.isValid() && "no handler entry for value in selector?");
827
828    // Figure out where to branch on a match.  As a debug code-size
829    // optimization, if the scope depth matches the innermost cleanup,
830    // we branch directly to the catch handler.
831    llvm::BasicBlock *Match = Dest.getBlock();
832    bool MatchNeedsCleanup =
833      Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
834    if (MatchNeedsCleanup)
835      Match = createBasicBlock("eh.match");
836
837    llvm::BasicBlock *Next = createBasicBlock("eh.next");
838
839    // Check whether the exception matches.
840    llvm::CallInst *Id
841      = Builder.CreateCall(llvm_eh_typeid_for,
842                           Builder.CreateBitCast(Type, Int8PtrTy));
843    Id->setDoesNotThrow();
844    Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
845                         Match, Next);
846
847    // Emit match code if necessary.
848    if (MatchNeedsCleanup) {
849      EmitBlock(Match);
850      EmitBranchThroughEHCleanup(Dest);
851    }
852
853    // Continue to the next match.
854    EmitBlock(Next);
855  }
856
857  // Emit the final case in the selector.
858  // This might be a catch-all....
859  if (CatchAll.isValid()) {
860    assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
861    EmitBranchThroughEHCleanup(CatchAll);
862
863  // ...or an EH filter...
864  } else if (HasEHFilter) {
865    llvm::Value *SavedSelection = Selection;
866
867    // First, unwind out to the outermost scope if necessary.
868    if (EHStack.hasEHCleanups()) {
869      // The end here might not dominate the beginning, so we might need to
870      // save the selector if we need it.
871      llvm::AllocaInst *SelectorVar = 0;
872      if (HasEHCleanup) {
873        SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
874        Builder.CreateStore(Selection, SelectorVar);
875      }
876
877      llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
878      EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
879                                            EHStack.getNextEHDestIndex()));
880      EmitBlock(CleanupContBB);
881
882      if (HasEHCleanup)
883        SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
884    }
885
886    // If there was a cleanup, we'll need to actually check whether we
887    // landed here because the filter triggered.
888    if (CleanupHackLevel != CHL_Ideal || HasEHCleanup) {
889      llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
890
891      llvm::Constant *Zero = llvm::ConstantInt::get(Int32Ty, 0);
892      llvm::Value *FailsFilter =
893        Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
894      Builder.CreateCondBr(FailsFilter, UnexpectedBB, getRethrowDest().getBlock());
895
896      EmitBlock(UnexpectedBB);
897    }
898
899    // Call __cxa_call_unexpected.  This doesn't need to be an invoke
900    // because __cxa_call_unexpected magically filters exceptions
901    // according to the last landing pad the exception was thrown
902    // into.  Seriously.
903    Builder.CreateCall(getUnexpectedFn(*this),
904                       Builder.CreateLoad(getExceptionSlot()))
905      ->setDoesNotReturn();
906    Builder.CreateUnreachable();
907
908  // ...or a normal catch handler...
909  } else if (CleanupHackLevel == CHL_Ideal && !HasEHCleanup) {
910    llvm::Value *Type = EHSelector.back();
911    EmitBranchThroughEHCleanup(EHHandlers[Type]);
912
913  // ...or a cleanup.
914  } else {
915    EmitBranchThroughEHCleanup(getRethrowDest());
916  }
917
918  // Restore the old IR generation state.
919  Builder.restoreIP(SavedIP);
920
921  return LP;
922}
923
924namespace {
925  /// A cleanup to call __cxa_end_catch.  In many cases, the caught
926  /// exception type lets us state definitively that the thrown exception
927  /// type does not have a destructor.  In particular:
928  ///   - Catch-alls tell us nothing, so we have to conservatively
929  ///     assume that the thrown exception might have a destructor.
930  ///   - Catches by reference behave according to their base types.
931  ///   - Catches of non-record types will only trigger for exceptions
932  ///     of non-record types, which never have destructors.
933  ///   - Catches of record types can trigger for arbitrary subclasses
934  ///     of the caught type, so we have to assume the actual thrown
935  ///     exception type might have a throwing destructor, even if the
936  ///     caught type's destructor is trivial or nothrow.
937  struct CallEndCatch : EHScopeStack::Cleanup {
938    CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
939    bool MightThrow;
940
941    void Emit(CodeGenFunction &CGF, bool IsForEH) {
942      if (!MightThrow) {
943        CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
944        return;
945      }
946
947      CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
948    }
949  };
950}
951
952/// Emits a call to __cxa_begin_catch and enters a cleanup to call
953/// __cxa_end_catch.
954///
955/// \param EndMightThrow - true if __cxa_end_catch might throw
956static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
957                                   llvm::Value *Exn,
958                                   bool EndMightThrow) {
959  llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
960  Call->setDoesNotThrow();
961
962  CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
963
964  return Call;
965}
966
967/// A "special initializer" callback for initializing a catch
968/// parameter during catch initialization.
969static void InitCatchParam(CodeGenFunction &CGF,
970                           const VarDecl &CatchParam,
971                           llvm::Value *ParamAddr) {
972  // Load the exception from where the landing pad saved it.
973  llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
974
975  CanQualType CatchType =
976    CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
977  const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
978
979  // If we're catching by reference, we can just cast the object
980  // pointer to the appropriate pointer.
981  if (isa<ReferenceType>(CatchType)) {
982    QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
983    bool EndCatchMightThrow = CaughtType->isRecordType();
984
985    // __cxa_begin_catch returns the adjusted object pointer.
986    llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
987
988    // We have no way to tell the personality function that we're
989    // catching by reference, so if we're catching a pointer,
990    // __cxa_begin_catch will actually return that pointer by value.
991    if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
992      QualType PointeeType = PT->getPointeeType();
993
994      // When catching by reference, generally we should just ignore
995      // this by-value pointer and use the exception object instead.
996      if (!PointeeType->isRecordType()) {
997
998        // Exn points to the struct _Unwind_Exception header, which
999        // we have to skip past in order to reach the exception data.
1000        unsigned HeaderSize =
1001          CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
1002        AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
1003
1004      // However, if we're catching a pointer-to-record type that won't
1005      // work, because the personality function might have adjusted
1006      // the pointer.  There's actually no way for us to fully satisfy
1007      // the language/ABI contract here:  we can't use Exn because it
1008      // might have the wrong adjustment, but we can't use the by-value
1009      // pointer because it's off by a level of abstraction.
1010      //
1011      // The current solution is to dump the adjusted pointer into an
1012      // alloca, which breaks language semantics (because changing the
1013      // pointer doesn't change the exception) but at least works.
1014      // The better solution would be to filter out non-exact matches
1015      // and rethrow them, but this is tricky because the rethrow
1016      // really needs to be catchable by other sites at this landing
1017      // pad.  The best solution is to fix the personality function.
1018      } else {
1019        // Pull the pointer for the reference type off.
1020        const llvm::Type *PtrTy =
1021          cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1022
1023        // Create the temporary and write the adjusted pointer into it.
1024        llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1025        llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1026        CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1027
1028        // Bind the reference to the temporary.
1029        AdjustedExn = ExnPtrTmp;
1030      }
1031    }
1032
1033    llvm::Value *ExnCast =
1034      CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1035    CGF.Builder.CreateStore(ExnCast, ParamAddr);
1036    return;
1037  }
1038
1039  // Non-aggregates (plus complexes).
1040  bool IsComplex = false;
1041  if (!CGF.hasAggregateLLVMType(CatchType) ||
1042      (IsComplex = CatchType->isAnyComplexType())) {
1043    llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
1044
1045    // If the catch type is a pointer type, __cxa_begin_catch returns
1046    // the pointer by value.
1047    if (CatchType->hasPointerRepresentation()) {
1048      llvm::Value *CastExn =
1049        CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1050      CGF.Builder.CreateStore(CastExn, ParamAddr);
1051      return;
1052    }
1053
1054    // Otherwise, it returns a pointer into the exception object.
1055
1056    const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1057    llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1058
1059    if (IsComplex) {
1060      CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1061                             ParamAddr, /*volatile*/ false);
1062    } else {
1063      unsigned Alignment =
1064        CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
1065      llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
1066      CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1067                            CatchType);
1068    }
1069    return;
1070  }
1071
1072  assert(isa<RecordType>(CatchType) && "unexpected catch type!");
1073
1074  const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1075
1076  // Check for a copy expression.  If we don't have a copy expression,
1077  // that means a trivial copy is okay.
1078  const Expr *copyExpr = CatchParam.getInit();
1079  if (!copyExpr) {
1080    llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1081    llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1082    CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
1083    return;
1084  }
1085
1086  // We have to call __cxa_get_exception_ptr to get the adjusted
1087  // pointer before copying.
1088  llvm::CallInst *rawAdjustedExn =
1089    CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1090  rawAdjustedExn->setDoesNotThrow();
1091
1092  // Cast that to the appropriate type.
1093  llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1094
1095  // The copy expression is defined in terms of an OpaqueValueExpr.
1096  // Find it and map it to the adjusted expression.
1097  CodeGenFunction::OpaqueValueMapping
1098    opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1099           CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
1100
1101  // Call the copy ctor in a terminate scope.
1102  CGF.EHStack.pushTerminate();
1103
1104  // Perform the copy construction.
1105  CGF.EmitAggExpr(copyExpr, AggValueSlot::forAddr(ParamAddr, Qualifiers(),
1106                                                  false));
1107
1108  // Leave the terminate scope.
1109  CGF.EHStack.popTerminate();
1110
1111  // Undo the opaque value mapping.
1112  opaque.pop();
1113
1114  // Finally we can call __cxa_begin_catch.
1115  CallBeginCatch(CGF, Exn, true);
1116}
1117
1118/// Begins a catch statement by initializing the catch variable and
1119/// calling __cxa_begin_catch.
1120static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
1121  // We have to be very careful with the ordering of cleanups here:
1122  //   C++ [except.throw]p4:
1123  //     The destruction [of the exception temporary] occurs
1124  //     immediately after the destruction of the object declared in
1125  //     the exception-declaration in the handler.
1126  //
1127  // So the precise ordering is:
1128  //   1.  Construct catch variable.
1129  //   2.  __cxa_begin_catch
1130  //   3.  Enter __cxa_end_catch cleanup
1131  //   4.  Enter dtor cleanup
1132  //
1133  // We do this by using a slightly abnormal initialization process.
1134  // Delegation sequence:
1135  //   - ExitCXXTryStmt opens a RunCleanupsScope
1136  //     - EmitAutoVarAlloca creates the variable and debug info
1137  //       - InitCatchParam initializes the variable from the exception
1138  //       - CallBeginCatch calls __cxa_begin_catch
1139  //       - CallBeginCatch enters the __cxa_end_catch cleanup
1140  //     - EmitAutoVarCleanups enters the variable destructor cleanup
1141  //   - EmitCXXTryStmt emits the code for the catch body
1142  //   - EmitCXXTryStmt close the RunCleanupsScope
1143
1144  VarDecl *CatchParam = S->getExceptionDecl();
1145  if (!CatchParam) {
1146    llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
1147    CallBeginCatch(CGF, Exn, true);
1148    return;
1149  }
1150
1151  // Emit the local.
1152  CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1153  InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
1154  CGF.EmitAutoVarCleanups(var);
1155}
1156
1157namespace {
1158  struct CallRethrow : EHScopeStack::Cleanup {
1159    void Emit(CodeGenFunction &CGF, bool IsForEH) {
1160      CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1161    }
1162  };
1163}
1164
1165void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1166  unsigned NumHandlers = S.getNumHandlers();
1167  EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1168  assert(CatchScope.getNumHandlers() == NumHandlers);
1169
1170  // Copy the handler blocks off before we pop the EH stack.  Emitting
1171  // the handlers might scribble on this memory.
1172  llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1173  memcpy(Handlers.data(), CatchScope.begin(),
1174         NumHandlers * sizeof(EHCatchScope::Handler));
1175  EHStack.popCatch();
1176
1177  // The fall-through block.
1178  llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1179
1180  // We just emitted the body of the try; jump to the continue block.
1181  if (HaveInsertPoint())
1182    Builder.CreateBr(ContBB);
1183
1184  // Determine if we need an implicit rethrow for all these catch handlers.
1185  bool ImplicitRethrow = false;
1186  if (IsFnTryBlock)
1187    ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1188                      isa<CXXConstructorDecl>(CurCodeDecl);
1189
1190  for (unsigned I = 0; I != NumHandlers; ++I) {
1191    llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1192    EmitBlock(CatchBlock);
1193
1194    // Catch the exception if this isn't a catch-all.
1195    const CXXCatchStmt *C = S.getHandler(I);
1196
1197    // Enter a cleanup scope, including the catch variable and the
1198    // end-catch.
1199    RunCleanupsScope CatchScope(*this);
1200
1201    // Initialize the catch variable and set up the cleanups.
1202    BeginCatch(*this, C);
1203
1204    // If there's an implicit rethrow, push a normal "cleanup" to call
1205    // _cxa_rethrow.  This needs to happen before __cxa_end_catch is
1206    // called, and so it is pushed after BeginCatch.
1207    if (ImplicitRethrow)
1208      EHStack.pushCleanup<CallRethrow>(NormalCleanup);
1209
1210    // Perform the body of the catch.
1211    EmitStmt(C->getHandlerBlock());
1212
1213    // Fall out through the catch cleanups.
1214    CatchScope.ForceCleanup();
1215
1216    // Branch out of the try.
1217    if (HaveInsertPoint())
1218      Builder.CreateBr(ContBB);
1219  }
1220
1221  EmitBlock(ContBB);
1222}
1223
1224namespace {
1225  struct CallEndCatchForFinally : EHScopeStack::Cleanup {
1226    llvm::Value *ForEHVar;
1227    llvm::Value *EndCatchFn;
1228    CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1229      : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1230
1231    void Emit(CodeGenFunction &CGF, bool IsForEH) {
1232      llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1233      llvm::BasicBlock *CleanupContBB =
1234        CGF.createBasicBlock("finally.cleanup.cont");
1235
1236      llvm::Value *ShouldEndCatch =
1237        CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1238      CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1239      CGF.EmitBlock(EndCatchBB);
1240      CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1241      CGF.EmitBlock(CleanupContBB);
1242    }
1243  };
1244
1245  struct PerformFinally : EHScopeStack::Cleanup {
1246    const Stmt *Body;
1247    llvm::Value *ForEHVar;
1248    llvm::Value *EndCatchFn;
1249    llvm::Value *RethrowFn;
1250    llvm::Value *SavedExnVar;
1251
1252    PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1253                   llvm::Value *EndCatchFn,
1254                   llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1255      : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1256        RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1257
1258    void Emit(CodeGenFunction &CGF, bool IsForEH) {
1259      // Enter a cleanup to call the end-catch function if one was provided.
1260      if (EndCatchFn)
1261        CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1262                                                        ForEHVar, EndCatchFn);
1263
1264      // Save the current cleanup destination in case there are
1265      // cleanups in the finally block.
1266      llvm::Value *SavedCleanupDest =
1267        CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1268                               "cleanup.dest.saved");
1269
1270      // Emit the finally block.
1271      CGF.EmitStmt(Body);
1272
1273      // If the end of the finally is reachable, check whether this was
1274      // for EH.  If so, rethrow.
1275      if (CGF.HaveInsertPoint()) {
1276        llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1277        llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1278
1279        llvm::Value *ShouldRethrow =
1280          CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1281        CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1282
1283        CGF.EmitBlock(RethrowBB);
1284        if (SavedExnVar) {
1285          llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1286          CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1287        } else {
1288          CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1289        }
1290        CGF.Builder.CreateUnreachable();
1291
1292        CGF.EmitBlock(ContBB);
1293
1294        // Restore the cleanup destination.
1295        CGF.Builder.CreateStore(SavedCleanupDest,
1296                                CGF.getNormalCleanupDestSlot());
1297      }
1298
1299      // Leave the end-catch cleanup.  As an optimization, pretend that
1300      // the fallthrough path was inaccessible; we've dynamically proven
1301      // that we're not in the EH case along that path.
1302      if (EndCatchFn) {
1303        CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1304        CGF.PopCleanupBlock();
1305        CGF.Builder.restoreIP(SavedIP);
1306      }
1307
1308      // Now make sure we actually have an insertion point or the
1309      // cleanup gods will hate us.
1310      CGF.EnsureInsertPoint();
1311    }
1312  };
1313}
1314
1315/// Enters a finally block for an implementation using zero-cost
1316/// exceptions.  This is mostly general, but hard-codes some
1317/// language/ABI-specific behavior in the catch-all sections.
1318void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1319                                         const Stmt *body,
1320                                         llvm::Constant *beginCatchFn,
1321                                         llvm::Constant *endCatchFn,
1322                                         llvm::Constant *rethrowFn) {
1323  assert((beginCatchFn != 0) == (endCatchFn != 0) &&
1324         "begin/end catch functions not paired");
1325  assert(rethrowFn && "rethrow function is required");
1326
1327  BeginCatchFn = beginCatchFn;
1328
1329  // The rethrow function has one of the following two types:
1330  //   void (*)()
1331  //   void (*)(void*)
1332  // In the latter case we need to pass it the exception object.
1333  // But we can't use the exception slot because the @finally might
1334  // have a landing pad (which would overwrite the exception slot).
1335  const llvm::FunctionType *rethrowFnTy =
1336    cast<llvm::FunctionType>(
1337      cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1338  SavedExnVar = 0;
1339  if (rethrowFnTy->getNumParams())
1340    SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1341
1342  // A finally block is a statement which must be executed on any edge
1343  // out of a given scope.  Unlike a cleanup, the finally block may
1344  // contain arbitrary control flow leading out of itself.  In
1345  // addition, finally blocks should always be executed, even if there
1346  // are no catch handlers higher on the stack.  Therefore, we
1347  // surround the protected scope with a combination of a normal
1348  // cleanup (to catch attempts to break out of the block via normal
1349  // control flow) and an EH catch-all (semantically "outside" any try
1350  // statement to which the finally block might have been attached).
1351  // The finally block itself is generated in the context of a cleanup
1352  // which conditionally leaves the catch-all.
1353
1354  // Jump destination for performing the finally block on an exception
1355  // edge.  We'll never actually reach this block, so unreachable is
1356  // fine.
1357  RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1358
1359  // Whether the finally block is being executed for EH purposes.
1360  ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1361  CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
1362
1363  // Enter a normal cleanup which will perform the @finally block.
1364  CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1365                                          ForEHVar, endCatchFn,
1366                                          rethrowFn, SavedExnVar);
1367
1368  // Enter a catch-all scope.
1369  llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1370  EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1371  catchScope->setCatchAllHandler(0, catchBB);
1372}
1373
1374void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1375  // Leave the finally catch-all.
1376  EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1377  llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1378  CGF.EHStack.popCatch();
1379
1380  // If there are any references to the catch-all block, emit it.
1381  if (catchBB->use_empty()) {
1382    delete catchBB;
1383  } else {
1384    CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1385    CGF.EmitBlock(catchBB);
1386
1387    llvm::Value *exn = 0;
1388
1389    // If there's a begin-catch function, call it.
1390    if (BeginCatchFn) {
1391      exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
1392      CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
1393    }
1394
1395    // If we need to remember the exception pointer to rethrow later, do so.
1396    if (SavedExnVar) {
1397      if (!exn) exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
1398      CGF.Builder.CreateStore(exn, SavedExnVar);
1399    }
1400
1401    // Tell the cleanups in the finally block that we're do this for EH.
1402    CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1403
1404    // Thread a jump through the finally cleanup.
1405    CGF.EmitBranchThroughCleanup(RethrowDest);
1406
1407    CGF.Builder.restoreIP(savedIP);
1408  }
1409
1410  // Finally, leave the @finally cleanup.
1411  CGF.PopCleanupBlock();
1412}
1413
1414llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1415  if (TerminateLandingPad)
1416    return TerminateLandingPad;
1417
1418  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1419
1420  // This will get inserted at the end of the function.
1421  TerminateLandingPad = createBasicBlock("terminate.lpad");
1422  Builder.SetInsertPoint(TerminateLandingPad);
1423
1424  // Tell the backend that this is a landing pad.
1425  llvm::CallInst *Exn =
1426    Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1427  Exn->setDoesNotThrow();
1428
1429  const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1430
1431  // Tell the backend what the exception table should be:
1432  // nothing but a catch-all.
1433  llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
1434                           getCatchAllValue(*this) };
1435  Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1436                     Args, Args+3, "eh.selector")
1437    ->setDoesNotThrow();
1438
1439  llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1440  TerminateCall->setDoesNotReturn();
1441  TerminateCall->setDoesNotThrow();
1442  Builder.CreateUnreachable();
1443
1444  // Restore the saved insertion state.
1445  Builder.restoreIP(SavedIP);
1446
1447  return TerminateLandingPad;
1448}
1449
1450llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1451  if (TerminateHandler)
1452    return TerminateHandler;
1453
1454  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1455
1456  // Set up the terminate handler.  This block is inserted at the very
1457  // end of the function by FinishFunction.
1458  TerminateHandler = createBasicBlock("terminate.handler");
1459  Builder.SetInsertPoint(TerminateHandler);
1460  llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1461  TerminateCall->setDoesNotReturn();
1462  TerminateCall->setDoesNotThrow();
1463  Builder.CreateUnreachable();
1464
1465  // Restore the saved insertion state.
1466  Builder.restoreIP(SavedIP);
1467
1468  return TerminateHandler;
1469}
1470
1471CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1472  if (RethrowBlock.isValid()) return RethrowBlock;
1473
1474  CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1475
1476  // We emit a jump to a notional label at the outermost unwind state.
1477  llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1478  Builder.SetInsertPoint(Unwind);
1479
1480  const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1481
1482  // This can always be a call because we necessarily didn't find
1483  // anything on the EH stack which needs our help.
1484  llvm::StringRef RethrowName = Personality.getCatchallRethrowFnName();
1485  if (!RethrowName.empty()) {
1486    Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
1487                       Builder.CreateLoad(getExceptionSlot()))
1488      ->setDoesNotReturn();
1489  } else {
1490    llvm::Value *Exn = Builder.CreateLoad(getExceptionSlot());
1491
1492    switch (CleanupHackLevel) {
1493    case CHL_MandatoryCatchall:
1494      // In mandatory-catchall mode, we need to use
1495      // _Unwind_Resume_or_Rethrow, or whatever the personality's
1496      // equivalent is.
1497      Builder.CreateCall(getUnwindResumeOrRethrowFn(), Exn)
1498        ->setDoesNotReturn();
1499      break;
1500    case CHL_MandatoryCleanup: {
1501      // In mandatory-cleanup mode, we should use llvm.eh.resume.
1502      llvm::Value *Selector = Builder.CreateLoad(getEHSelectorSlot());
1503      Builder.CreateCall2(CGM.getIntrinsic(llvm::Intrinsic::eh_resume),
1504                          Exn, Selector)
1505        ->setDoesNotReturn();
1506      break;
1507    }
1508    case CHL_Ideal:
1509      // In an idealized mode where we don't have to worry about the
1510      // optimizer combining landing pads, we should just use
1511      // _Unwind_Resume (or the personality's equivalent).
1512      Builder.CreateCall(getUnwindResumeFn(), Exn)
1513        ->setDoesNotReturn();
1514      break;
1515    }
1516  }
1517
1518  Builder.CreateUnreachable();
1519
1520  Builder.restoreIP(SavedIP);
1521
1522  RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1523  return RethrowBlock;
1524}
1525
1526