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