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