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