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