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