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