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