1 //===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code dealing with C++ exception related code generation.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGCXXABI.h"
14 #include "CGCleanup.h"
15 #include "CGObjCRuntime.h"
16 #include "CodeGenFunction.h"
17 #include "ConstantEmitter.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 "clang/AST/StmtVisitor.h"
23 #include "clang/Basic/DiagnosticSema.h"
24 #include "clang/Basic/TargetBuiltins.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/IntrinsicsWebAssembly.h"
28 #include "llvm/Support/SaveAndRestore.h"
29 
30 using namespace clang;
31 using namespace CodeGen;
32 
33 static llvm::FunctionCallee getFreeExceptionFn(CodeGenModule &CGM) {
34   // void __cxa_free_exception(void *thrown_exception);
35 
36   llvm::FunctionType *FTy =
37     llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
38 
39   return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
40 }
41 
42 static llvm::FunctionCallee getUnexpectedFn(CodeGenModule &CGM) {
43   // void __cxa_call_unexpected(void *thrown_exception);
44 
45   llvm::FunctionType *FTy =
46     llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
47 
48   return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
49 }
50 
51 llvm::FunctionCallee CodeGenModule::getTerminateFn() {
52   // void __terminate();
53 
54   llvm::FunctionType *FTy =
55     llvm::FunctionType::get(VoidTy, /*isVarArg=*/false);
56 
57   StringRef name;
58 
59   // In C++, use std::terminate().
60   if (getLangOpts().CPlusPlus &&
61       getTarget().getCXXABI().isItaniumFamily()) {
62     name = "_ZSt9terminatev";
63   } else if (getLangOpts().CPlusPlus &&
64              getTarget().getCXXABI().isMicrosoft()) {
65     if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
66       name = "__std_terminate";
67     else
68       name = "?terminate@@YAXXZ";
69   } else if (getLangOpts().ObjC &&
70              getLangOpts().ObjCRuntime.hasTerminate())
71     name = "objc_terminate";
72   else
73     name = "abort";
74   return CreateRuntimeFunction(FTy, name);
75 }
76 
77 static llvm::FunctionCallee getCatchallRethrowFn(CodeGenModule &CGM,
78                                                  StringRef Name) {
79   llvm::FunctionType *FTy =
80     llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
81 
82   return CGM.CreateRuntimeFunction(FTy, Name);
83 }
84 
85 const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
86 const EHPersonality
87 EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
88 const EHPersonality
89 EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
90 const EHPersonality
91 EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
92 const EHPersonality
93 EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
94 const EHPersonality
95 EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
96 const EHPersonality
97 EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
98 const EHPersonality
99 EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
100 const EHPersonality
101 EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
102 const EHPersonality
103 EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
104 const EHPersonality
105 EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
106 const EHPersonality
107 EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
108 const EHPersonality
109 EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
110 const EHPersonality
111 EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
112 const EHPersonality
113 EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
114 const EHPersonality
115 EHPersonality::GNU_Wasm_CPlusPlus = { "__gxx_wasm_personality_v0", nullptr };
116 
117 static const EHPersonality &getCPersonality(const TargetInfo &Target,
118                                             const LangOptions &L) {
119   const llvm::Triple &T = Target.getTriple();
120   if (T.isWindowsMSVCEnvironment())
121     return EHPersonality::MSVC_CxxFrameHandler3;
122   if (L.SjLjExceptions)
123     return EHPersonality::GNU_C_SJLJ;
124   if (L.DWARFExceptions)
125     return EHPersonality::GNU_C;
126   if (L.SEHExceptions)
127     return EHPersonality::GNU_C_SEH;
128   return EHPersonality::GNU_C;
129 }
130 
131 static const EHPersonality &getObjCPersonality(const TargetInfo &Target,
132                                                const LangOptions &L) {
133   const llvm::Triple &T = Target.getTriple();
134   if (T.isWindowsMSVCEnvironment())
135     return EHPersonality::MSVC_CxxFrameHandler3;
136 
137   switch (L.ObjCRuntime.getKind()) {
138   case ObjCRuntime::FragileMacOSX:
139     return getCPersonality(Target, L);
140   case ObjCRuntime::MacOSX:
141   case ObjCRuntime::iOS:
142   case ObjCRuntime::WatchOS:
143     return EHPersonality::NeXT_ObjC;
144   case ObjCRuntime::GNUstep:
145     if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
146       return EHPersonality::GNUstep_ObjC;
147     LLVM_FALLTHROUGH;
148   case ObjCRuntime::GCC:
149   case ObjCRuntime::ObjFW:
150     if (L.SjLjExceptions)
151       return EHPersonality::GNU_ObjC_SJLJ;
152     if (L.SEHExceptions)
153       return EHPersonality::GNU_ObjC_SEH;
154     return EHPersonality::GNU_ObjC;
155   }
156   llvm_unreachable("bad runtime kind");
157 }
158 
159 static const EHPersonality &getCXXPersonality(const TargetInfo &Target,
160                                               const LangOptions &L) {
161   const llvm::Triple &T = Target.getTriple();
162   if (T.isWindowsMSVCEnvironment())
163     return EHPersonality::MSVC_CxxFrameHandler3;
164   if (L.SjLjExceptions)
165     return EHPersonality::GNU_CPlusPlus_SJLJ;
166   if (L.DWARFExceptions)
167     return EHPersonality::GNU_CPlusPlus;
168   if (L.SEHExceptions)
169     return EHPersonality::GNU_CPlusPlus_SEH;
170   if (L.WasmExceptions)
171     return EHPersonality::GNU_Wasm_CPlusPlus;
172   return EHPersonality::GNU_CPlusPlus;
173 }
174 
175 /// Determines the personality function to use when both C++
176 /// and Objective-C exceptions are being caught.
177 static const EHPersonality &getObjCXXPersonality(const TargetInfo &Target,
178                                                  const LangOptions &L) {
179   if (Target.getTriple().isWindowsMSVCEnvironment())
180     return EHPersonality::MSVC_CxxFrameHandler3;
181 
182   switch (L.ObjCRuntime.getKind()) {
183   // In the fragile ABI, just use C++ exception handling and hope
184   // they're not doing crazy exception mixing.
185   case ObjCRuntime::FragileMacOSX:
186     return getCXXPersonality(Target, L);
187 
188   // The ObjC personality defers to the C++ personality for non-ObjC
189   // handlers.  Unlike the C++ case, we use the same personality
190   // function on targets using (backend-driven) SJLJ EH.
191   case ObjCRuntime::MacOSX:
192   case ObjCRuntime::iOS:
193   case ObjCRuntime::WatchOS:
194     return getObjCPersonality(Target, L);
195 
196   case ObjCRuntime::GNUstep:
197     return EHPersonality::GNU_ObjCXX;
198 
199   // The GCC runtime's personality function inherently doesn't support
200   // mixed EH.  Use the ObjC personality just to avoid returning null.
201   case ObjCRuntime::GCC:
202   case ObjCRuntime::ObjFW:
203     return getObjCPersonality(Target, L);
204   }
205   llvm_unreachable("bad runtime kind");
206 }
207 
208 static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
209   if (T.getArch() == llvm::Triple::x86)
210     return EHPersonality::MSVC_except_handler;
211   return EHPersonality::MSVC_C_specific_handler;
212 }
213 
214 const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
215                                         const FunctionDecl *FD) {
216   const llvm::Triple &T = CGM.getTarget().getTriple();
217   const LangOptions &L = CGM.getLangOpts();
218   const TargetInfo &Target = CGM.getTarget();
219 
220   // Functions using SEH get an SEH personality.
221   if (FD && FD->usesSEHTry())
222     return getSEHPersonalityMSVC(T);
223 
224   if (L.ObjC)
225     return L.CPlusPlus ? getObjCXXPersonality(Target, L)
226                        : getObjCPersonality(Target, L);
227   return L.CPlusPlus ? getCXXPersonality(Target, L)
228                      : getCPersonality(Target, L);
229 }
230 
231 const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
232   const auto *FD = CGF.CurCodeDecl;
233   // For outlined finallys and filters, use the SEH personality in case they
234   // contain more SEH. This mostly only affects finallys. Filters could
235   // hypothetically use gnu statement expressions to sneak in nested SEH.
236   FD = FD ? FD : CGF.CurSEHParent;
237   return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(FD));
238 }
239 
240 static llvm::FunctionCallee getPersonalityFn(CodeGenModule &CGM,
241                                              const EHPersonality &Personality) {
242   return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
243                                    Personality.PersonalityFn,
244                                    llvm::AttributeList(), /*Local=*/true);
245 }
246 
247 static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
248                                         const EHPersonality &Personality) {
249   llvm::FunctionCallee Fn = getPersonalityFn(CGM, Personality);
250   llvm::PointerType* Int8PtrTy = llvm::PointerType::get(
251       llvm::Type::getInt8Ty(CGM.getLLVMContext()),
252       CGM.getDataLayout().getProgramAddressSpace());
253 
254   return llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(Fn.getCallee()),
255                                         Int8PtrTy);
256 }
257 
258 /// Check whether a landingpad instruction only uses C++ features.
259 static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
260   for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
261     // Look for something that would've been returned by the ObjC
262     // runtime's GetEHType() method.
263     llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
264     if (LPI->isCatch(I)) {
265       // Check if the catch value has the ObjC prefix.
266       if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
267         // ObjC EH selector entries are always global variables with
268         // names starting like this.
269         if (GV->getName().startswith("OBJC_EHTYPE"))
270           return false;
271     } else {
272       // Check if any of the filter values have the ObjC prefix.
273       llvm::Constant *CVal = cast<llvm::Constant>(Val);
274       for (llvm::User::op_iterator
275               II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
276         if (llvm::GlobalVariable *GV =
277             cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
278           // ObjC EH selector entries are always global variables with
279           // names starting like this.
280           if (GV->getName().startswith("OBJC_EHTYPE"))
281             return false;
282       }
283     }
284   }
285   return true;
286 }
287 
288 /// Check whether a personality function could reasonably be swapped
289 /// for a C++ personality function.
290 static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
291   for (llvm::User *U : Fn->users()) {
292     // Conditionally white-list bitcasts.
293     if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
294       if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
295       if (!PersonalityHasOnlyCXXUses(CE))
296         return false;
297       continue;
298     }
299 
300     // Otherwise it must be a function.
301     llvm::Function *F = dyn_cast<llvm::Function>(U);
302     if (!F) return false;
303 
304     for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
305       if (BB->isLandingPad())
306         if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
307           return false;
308     }
309   }
310 
311   return true;
312 }
313 
314 /// Try to use the C++ personality function in ObjC++.  Not doing this
315 /// can cause some incompatibilities with gcc, which is more
316 /// aggressive about only using the ObjC++ personality in a function
317 /// when it really needs it.
318 void CodeGenModule::SimplifyPersonality() {
319   // If we're not in ObjC++ -fexceptions, there's nothing to do.
320   if (!LangOpts.CPlusPlus || !LangOpts.ObjC || !LangOpts.Exceptions)
321     return;
322 
323   // Both the problem this endeavors to fix and the way the logic
324   // above works is specific to the NeXT runtime.
325   if (!LangOpts.ObjCRuntime.isNeXTFamily())
326     return;
327 
328   const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
329   const EHPersonality &CXX = getCXXPersonality(getTarget(), LangOpts);
330   if (&ObjCXX == &CXX)
331     return;
332 
333   assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
334          "Different EHPersonalities using the same personality function.");
335 
336   llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
337 
338   // Nothing to do if it's unused.
339   if (!Fn || Fn->use_empty()) return;
340 
341   // Can't do the optimization if it has non-C++ uses.
342   if (!PersonalityHasOnlyCXXUses(Fn)) return;
343 
344   // Create the C++ personality function and kill off the old
345   // function.
346   llvm::FunctionCallee CXXFn = getPersonalityFn(*this, CXX);
347 
348   // This can happen if the user is screwing with us.
349   if (Fn->getType() != CXXFn.getCallee()->getType())
350     return;
351 
352   Fn->replaceAllUsesWith(CXXFn.getCallee());
353   Fn->eraseFromParent();
354 }
355 
356 /// Returns the value to inject into a selector to indicate the
357 /// presence of a catch-all.
358 static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
359   // Possibly we should use @llvm.eh.catch.all.value here.
360   return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
361 }
362 
363 namespace {
364   /// A cleanup to free the exception object if its initialization
365   /// throws.
366   struct FreeException final : EHScopeStack::Cleanup {
367     llvm::Value *exn;
368     FreeException(llvm::Value *exn) : exn(exn) {}
369     void Emit(CodeGenFunction &CGF, Flags flags) override {
370       CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
371     }
372   };
373 } // end anonymous namespace
374 
375 // Emits an exception expression into the given location.  This
376 // differs from EmitAnyExprToMem only in that, if a final copy-ctor
377 // call is required, an exception within that copy ctor causes
378 // std::terminate to be invoked.
379 void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
380   // Make sure the exception object is cleaned up if there's an
381   // exception during initialization.
382   pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
383   EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
384 
385   // __cxa_allocate_exception returns a void*;  we need to cast this
386   // to the appropriate type for the object.
387   llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
388   Address typedAddr = Builder.CreateBitCast(addr, ty);
389 
390   // FIXME: this isn't quite right!  If there's a final unelided call
391   // to a copy constructor, then according to [except.terminate]p1 we
392   // must call std::terminate() if that constructor throws, because
393   // technically that copy occurs after the exception expression is
394   // evaluated but before the exception is caught.  But the best way
395   // to handle that is to teach EmitAggExpr to do the final copy
396   // differently if it can't be elided.
397   EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
398                    /*IsInit*/ true);
399 
400   // Deactivate the cleanup block.
401   DeactivateCleanupBlock(cleanup,
402                          cast<llvm::Instruction>(typedAddr.getPointer()));
403 }
404 
405 Address CodeGenFunction::getExceptionSlot() {
406   if (!ExceptionSlot)
407     ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
408   return Address(ExceptionSlot, getPointerAlign());
409 }
410 
411 Address CodeGenFunction::getEHSelectorSlot() {
412   if (!EHSelectorSlot)
413     EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
414   return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
415 }
416 
417 llvm::Value *CodeGenFunction::getExceptionFromSlot() {
418   return Builder.CreateLoad(getExceptionSlot(), "exn");
419 }
420 
421 llvm::Value *CodeGenFunction::getSelectorFromSlot() {
422   return Builder.CreateLoad(getEHSelectorSlot(), "sel");
423 }
424 
425 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
426                                        bool KeepInsertionPoint) {
427   if (const Expr *SubExpr = E->getSubExpr()) {
428     QualType ThrowType = SubExpr->getType();
429     if (ThrowType->isObjCObjectPointerType()) {
430       const Stmt *ThrowStmt = E->getSubExpr();
431       const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
432       CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
433     } else {
434       CGM.getCXXABI().emitThrow(*this, E);
435     }
436   } else {
437     CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
438   }
439 
440   // throw is an expression, and the expression emitters expect us
441   // to leave ourselves at a valid insertion point.
442   if (KeepInsertionPoint)
443     EmitBlock(createBasicBlock("throw.cont"));
444 }
445 
446 void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
447   if (!CGM.getLangOpts().CXXExceptions)
448     return;
449 
450   const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
451   if (!FD) {
452     // Check if CapturedDecl is nothrow and create terminate scope for it.
453     if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
454       if (CD->isNothrow())
455         EHStack.pushTerminate();
456     }
457     return;
458   }
459   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
460   if (!Proto)
461     return;
462 
463   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
464   if (isNoexceptExceptionSpec(EST) && Proto->canThrow() == CT_Cannot) {
465     // noexcept functions are simple terminate scopes.
466     EHStack.pushTerminate();
467   } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
468     // TODO: Revisit exception specifications for the MS ABI.  There is a way to
469     // encode these in an object file but MSVC doesn't do anything with it.
470     if (getTarget().getCXXABI().isMicrosoft())
471       return;
472     // In wasm we currently treat 'throw()' in the same way as 'noexcept'. In
473     // case of throw with types, we ignore it and print a warning for now.
474     // TODO Correctly handle exception specification in wasm
475     if (getTarget().getCXXABI() == TargetCXXABI::WebAssembly) {
476       if (EST == EST_DynamicNone)
477         EHStack.pushTerminate();
478       else
479         CGM.getDiags().Report(D->getLocation(),
480                               diag::warn_wasm_dynamic_exception_spec_ignored)
481             << FD->getExceptionSpecSourceRange();
482       return;
483     }
484     unsigned NumExceptions = Proto->getNumExceptions();
485     EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
486 
487     for (unsigned I = 0; I != NumExceptions; ++I) {
488       QualType Ty = Proto->getExceptionType(I);
489       QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
490       llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
491                                                         /*ForEH=*/true);
492       Filter->setFilter(I, EHType);
493     }
494   }
495 }
496 
497 /// Emit the dispatch block for a filter scope if necessary.
498 static void emitFilterDispatchBlock(CodeGenFunction &CGF,
499                                     EHFilterScope &filterScope) {
500   llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
501   if (!dispatchBlock) return;
502   if (dispatchBlock->use_empty()) {
503     delete dispatchBlock;
504     return;
505   }
506 
507   CGF.EmitBlockAfterUses(dispatchBlock);
508 
509   // If this isn't a catch-all filter, we need to check whether we got
510   // here because the filter triggered.
511   if (filterScope.getNumFilters()) {
512     // Load the selector value.
513     llvm::Value *selector = CGF.getSelectorFromSlot();
514     llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
515 
516     llvm::Value *zero = CGF.Builder.getInt32(0);
517     llvm::Value *failsFilter =
518         CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
519     CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
520                              CGF.getEHResumeBlock(false));
521 
522     CGF.EmitBlock(unexpectedBB);
523   }
524 
525   // Call __cxa_call_unexpected.  This doesn't need to be an invoke
526   // because __cxa_call_unexpected magically filters exceptions
527   // according to the last landing pad the exception was thrown
528   // into.  Seriously.
529   llvm::Value *exn = CGF.getExceptionFromSlot();
530   CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
531     ->setDoesNotReturn();
532   CGF.Builder.CreateUnreachable();
533 }
534 
535 void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
536   if (!CGM.getLangOpts().CXXExceptions)
537     return;
538 
539   const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
540   if (!FD) {
541     // Check if CapturedDecl is nothrow and pop terminate scope for it.
542     if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
543       if (CD->isNothrow())
544         EHStack.popTerminate();
545     }
546     return;
547   }
548   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
549   if (!Proto)
550     return;
551 
552   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
553   if (isNoexceptExceptionSpec(EST) && Proto->canThrow() == CT_Cannot) {
554     EHStack.popTerminate();
555   } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
556     // TODO: Revisit exception specifications for the MS ABI.  There is a way to
557     // encode these in an object file but MSVC doesn't do anything with it.
558     if (getTarget().getCXXABI().isMicrosoft())
559       return;
560     // In wasm we currently treat 'throw()' in the same way as 'noexcept'. In
561     // case of throw with types, we ignore it and print a warning for now.
562     // TODO Correctly handle exception specification in wasm
563     if (getTarget().getCXXABI() == TargetCXXABI::WebAssembly) {
564       if (EST == EST_DynamicNone)
565         EHStack.popTerminate();
566       return;
567     }
568     EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
569     emitFilterDispatchBlock(*this, filterScope);
570     EHStack.popFilter();
571   }
572 }
573 
574 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
575   EnterCXXTryStmt(S);
576   EmitStmt(S.getTryBlock());
577   ExitCXXTryStmt(S);
578 }
579 
580 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
581   unsigned NumHandlers = S.getNumHandlers();
582   EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
583 
584   for (unsigned I = 0; I != NumHandlers; ++I) {
585     const CXXCatchStmt *C = S.getHandler(I);
586 
587     llvm::BasicBlock *Handler = createBasicBlock("catch");
588     if (C->getExceptionDecl()) {
589       // FIXME: Dropping the reference type on the type into makes it
590       // impossible to correctly implement catch-by-reference
591       // semantics for pointers.  Unfortunately, this is what all
592       // existing compilers do, and it's not clear that the standard
593       // personality routine is capable of doing this right.  See C++ DR 388:
594       //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
595       Qualifiers CaughtTypeQuals;
596       QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
597           C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
598 
599       CatchTypeInfo TypeInfo{nullptr, 0};
600       if (CaughtType->isObjCObjectPointerType())
601         TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
602       else
603         TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
604             CaughtType, C->getCaughtType());
605       CatchScope->setHandler(I, TypeInfo, Handler);
606     } else {
607       // No exception decl indicates '...', a catch-all.
608       CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
609     }
610   }
611 }
612 
613 llvm::BasicBlock *
614 CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
615   if (EHPersonality::get(*this).usesFuncletPads())
616     return getFuncletEHDispatchBlock(si);
617 
618   // The dispatch block for the end of the scope chain is a block that
619   // just resumes unwinding.
620   if (si == EHStack.stable_end())
621     return getEHResumeBlock(true);
622 
623   // Otherwise, we should look at the actual scope.
624   EHScope &scope = *EHStack.find(si);
625 
626   llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
627   if (!dispatchBlock) {
628     switch (scope.getKind()) {
629     case EHScope::Catch: {
630       // Apply a special case to a single catch-all.
631       EHCatchScope &catchScope = cast<EHCatchScope>(scope);
632       if (catchScope.getNumHandlers() == 1 &&
633           catchScope.getHandler(0).isCatchAll()) {
634         dispatchBlock = catchScope.getHandler(0).Block;
635 
636       // Otherwise, make a dispatch block.
637       } else {
638         dispatchBlock = createBasicBlock("catch.dispatch");
639       }
640       break;
641     }
642 
643     case EHScope::Cleanup:
644       dispatchBlock = createBasicBlock("ehcleanup");
645       break;
646 
647     case EHScope::Filter:
648       dispatchBlock = createBasicBlock("filter.dispatch");
649       break;
650 
651     case EHScope::Terminate:
652       dispatchBlock = getTerminateHandler();
653       break;
654 
655     case EHScope::PadEnd:
656       llvm_unreachable("PadEnd unnecessary for Itanium!");
657     }
658     scope.setCachedEHDispatchBlock(dispatchBlock);
659   }
660   return dispatchBlock;
661 }
662 
663 llvm::BasicBlock *
664 CodeGenFunction::getFuncletEHDispatchBlock(EHScopeStack::stable_iterator SI) {
665   // Returning nullptr indicates that the previous dispatch block should unwind
666   // to caller.
667   if (SI == EHStack.stable_end())
668     return nullptr;
669 
670   // Otherwise, we should look at the actual scope.
671   EHScope &EHS = *EHStack.find(SI);
672 
673   llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
674   if (DispatchBlock)
675     return DispatchBlock;
676 
677   if (EHS.getKind() == EHScope::Terminate)
678     DispatchBlock = getTerminateFunclet();
679   else
680     DispatchBlock = createBasicBlock();
681   CGBuilderTy Builder(*this, DispatchBlock);
682 
683   switch (EHS.getKind()) {
684   case EHScope::Catch:
685     DispatchBlock->setName("catch.dispatch");
686     break;
687 
688   case EHScope::Cleanup:
689     DispatchBlock->setName("ehcleanup");
690     break;
691 
692   case EHScope::Filter:
693     llvm_unreachable("exception specifications not handled yet!");
694 
695   case EHScope::Terminate:
696     DispatchBlock->setName("terminate");
697     break;
698 
699   case EHScope::PadEnd:
700     llvm_unreachable("PadEnd dispatch block missing!");
701   }
702   EHS.setCachedEHDispatchBlock(DispatchBlock);
703   return DispatchBlock;
704 }
705 
706 /// Check whether this is a non-EH scope, i.e. a scope which doesn't
707 /// affect exception handling.  Currently, the only non-EH scopes are
708 /// normal-only cleanup scopes.
709 static bool isNonEHScope(const EHScope &S) {
710   switch (S.getKind()) {
711   case EHScope::Cleanup:
712     return !cast<EHCleanupScope>(S).isEHCleanup();
713   case EHScope::Filter:
714   case EHScope::Catch:
715   case EHScope::Terminate:
716   case EHScope::PadEnd:
717     return false;
718   }
719 
720   llvm_unreachable("Invalid EHScope Kind!");
721 }
722 
723 llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
724   assert(EHStack.requiresLandingPad());
725   assert(!EHStack.empty());
726 
727   // If exceptions are disabled/ignored and SEH is not in use, then there is no
728   // invoke destination. SEH "works" even if exceptions are off. In practice,
729   // this means that C++ destructors and other EH cleanups don't run, which is
730   // consistent with MSVC's behavior.
731   const LangOptions &LO = CGM.getLangOpts();
732   if (!LO.Exceptions || LO.IgnoreExceptions) {
733     if (!LO.Borland && !LO.MicrosoftExt)
734       return nullptr;
735     if (!currentFunctionUsesSEHTry())
736       return nullptr;
737   }
738 
739   // CUDA device code doesn't have exceptions.
740   if (LO.CUDA && LO.CUDAIsDevice)
741     return nullptr;
742 
743   // Check the innermost scope for a cached landing pad.  If this is
744   // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
745   llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
746   if (LP) return LP;
747 
748   const EHPersonality &Personality = EHPersonality::get(*this);
749 
750   if (!CurFn->hasPersonalityFn())
751     CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
752 
753   if (Personality.usesFuncletPads()) {
754     // We don't need separate landing pads in the funclet model.
755     LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
756   } else {
757     // Build the landing pad for this scope.
758     LP = EmitLandingPad();
759   }
760 
761   assert(LP);
762 
763   // Cache the landing pad on the innermost scope.  If this is a
764   // non-EH scope, cache the landing pad on the enclosing scope, too.
765   for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
766     ir->setCachedLandingPad(LP);
767     if (!isNonEHScope(*ir)) break;
768   }
769 
770   return LP;
771 }
772 
773 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
774   assert(EHStack.requiresLandingPad());
775   assert(!CGM.getLangOpts().IgnoreExceptions &&
776          "LandingPad should not be emitted when -fignore-exceptions are in "
777          "effect.");
778   EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
779   switch (innermostEHScope.getKind()) {
780   case EHScope::Terminate:
781     return getTerminateLandingPad();
782 
783   case EHScope::PadEnd:
784     llvm_unreachable("PadEnd unnecessary for Itanium!");
785 
786   case EHScope::Catch:
787   case EHScope::Cleanup:
788   case EHScope::Filter:
789     if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
790       return lpad;
791   }
792 
793   // Save the current IR generation state.
794   CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
795   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
796 
797   // Create and configure the landing pad.
798   llvm::BasicBlock *lpad = createBasicBlock("lpad");
799   EmitBlock(lpad);
800 
801   llvm::LandingPadInst *LPadInst =
802       Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
803 
804   llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
805   Builder.CreateStore(LPadExn, getExceptionSlot());
806   llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
807   Builder.CreateStore(LPadSel, getEHSelectorSlot());
808 
809   // Save the exception pointer.  It's safe to use a single exception
810   // pointer per function because EH cleanups can never have nested
811   // try/catches.
812   // Build the landingpad instruction.
813 
814   // Accumulate all the handlers in scope.
815   bool hasCatchAll = false;
816   bool hasCleanup = false;
817   bool hasFilter = false;
818   SmallVector<llvm::Value*, 4> filterTypes;
819   llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
820   for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
821        ++I) {
822 
823     switch (I->getKind()) {
824     case EHScope::Cleanup:
825       // If we have a cleanup, remember that.
826       hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
827       continue;
828 
829     case EHScope::Filter: {
830       assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
831       assert(!hasCatchAll && "EH filter reached after catch-all");
832 
833       // Filter scopes get added to the landingpad in weird ways.
834       EHFilterScope &filter = cast<EHFilterScope>(*I);
835       hasFilter = true;
836 
837       // Add all the filter values.
838       for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
839         filterTypes.push_back(filter.getFilter(i));
840       goto done;
841     }
842 
843     case EHScope::Terminate:
844       // Terminate scopes are basically catch-alls.
845       assert(!hasCatchAll);
846       hasCatchAll = true;
847       goto done;
848 
849     case EHScope::Catch:
850       break;
851 
852     case EHScope::PadEnd:
853       llvm_unreachable("PadEnd unnecessary for Itanium!");
854     }
855 
856     EHCatchScope &catchScope = cast<EHCatchScope>(*I);
857     for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
858       EHCatchScope::Handler handler = catchScope.getHandler(hi);
859       assert(handler.Type.Flags == 0 &&
860              "landingpads do not support catch handler flags");
861 
862       // If this is a catch-all, register that and abort.
863       if (!handler.Type.RTTI) {
864         assert(!hasCatchAll);
865         hasCatchAll = true;
866         goto done;
867       }
868 
869       // Check whether we already have a handler for this type.
870       if (catchTypes.insert(handler.Type.RTTI).second)
871         // If not, add it directly to the landingpad.
872         LPadInst->addClause(handler.Type.RTTI);
873     }
874   }
875 
876  done:
877   // If we have a catch-all, add null to the landingpad.
878   assert(!(hasCatchAll && hasFilter));
879   if (hasCatchAll) {
880     LPadInst->addClause(getCatchAllValue(*this));
881 
882   // If we have an EH filter, we need to add those handlers in the
883   // right place in the landingpad, which is to say, at the end.
884   } else if (hasFilter) {
885     // Create a filter expression: a constant array indicating which filter
886     // types there are. The personality routine only lands here if the filter
887     // doesn't match.
888     SmallVector<llvm::Constant*, 8> Filters;
889     llvm::ArrayType *AType =
890       llvm::ArrayType::get(!filterTypes.empty() ?
891                              filterTypes[0]->getType() : Int8PtrTy,
892                            filterTypes.size());
893 
894     for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
895       Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
896     llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
897     LPadInst->addClause(FilterArray);
898 
899     // Also check whether we need a cleanup.
900     if (hasCleanup)
901       LPadInst->setCleanup(true);
902 
903   // Otherwise, signal that we at least have cleanups.
904   } else if (hasCleanup) {
905     LPadInst->setCleanup(true);
906   }
907 
908   assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
909          "landingpad instruction has no clauses!");
910 
911   // Tell the backend how to generate the landing pad.
912   Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
913 
914   // Restore the old IR generation state.
915   Builder.restoreIP(savedIP);
916 
917   return lpad;
918 }
919 
920 static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
921   llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
922   assert(DispatchBlock);
923 
924   CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
925   CGF.EmitBlockAfterUses(DispatchBlock);
926 
927   llvm::Value *ParentPad = CGF.CurrentFuncletPad;
928   if (!ParentPad)
929     ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
930   llvm::BasicBlock *UnwindBB =
931       CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
932 
933   unsigned NumHandlers = CatchScope.getNumHandlers();
934   llvm::CatchSwitchInst *CatchSwitch =
935       CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
936 
937   // Test against each of the exception types we claim to catch.
938   for (unsigned I = 0; I < NumHandlers; ++I) {
939     const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
940 
941     CatchTypeInfo TypeInfo = Handler.Type;
942     if (!TypeInfo.RTTI)
943       TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
944 
945     CGF.Builder.SetInsertPoint(Handler.Block);
946 
947     if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
948       CGF.Builder.CreateCatchPad(
949           CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
950                         llvm::Constant::getNullValue(CGF.VoidPtrTy)});
951     } else {
952       CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
953     }
954 
955     CatchSwitch->addHandler(Handler.Block);
956   }
957   CGF.Builder.restoreIP(SavedIP);
958 }
959 
960 // Wasm uses Windows-style EH instructions, but it merges all catch clauses into
961 // one big catchpad, within which we use Itanium's landingpad-style selector
962 // comparison instructions.
963 static void emitWasmCatchPadBlock(CodeGenFunction &CGF,
964                                   EHCatchScope &CatchScope) {
965   llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
966   assert(DispatchBlock);
967 
968   CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
969   CGF.EmitBlockAfterUses(DispatchBlock);
970 
971   llvm::Value *ParentPad = CGF.CurrentFuncletPad;
972   if (!ParentPad)
973     ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
974   llvm::BasicBlock *UnwindBB =
975       CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
976 
977   unsigned NumHandlers = CatchScope.getNumHandlers();
978   llvm::CatchSwitchInst *CatchSwitch =
979       CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
980 
981   // We don't use a landingpad instruction, so generate intrinsic calls to
982   // provide exception and selector values.
983   llvm::BasicBlock *WasmCatchStartBlock = CGF.createBasicBlock("catch.start");
984   CatchSwitch->addHandler(WasmCatchStartBlock);
985   CGF.EmitBlockAfterUses(WasmCatchStartBlock);
986 
987   // Create a catchpad instruction.
988   SmallVector<llvm::Value *, 4> CatchTypes;
989   for (unsigned I = 0, E = NumHandlers; I < E; ++I) {
990     const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
991     CatchTypeInfo TypeInfo = Handler.Type;
992     if (!TypeInfo.RTTI)
993       TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
994     CatchTypes.push_back(TypeInfo.RTTI);
995   }
996   auto *CPI = CGF.Builder.CreateCatchPad(CatchSwitch, CatchTypes);
997 
998   // Create calls to wasm.get.exception and wasm.get.ehselector intrinsics.
999   // Before they are lowered appropriately later, they provide values for the
1000   // exception and selector.
1001   llvm::Function *GetExnFn =
1002       CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
1003   llvm::Function *GetSelectorFn =
1004       CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_ehselector);
1005   llvm::CallInst *Exn = CGF.Builder.CreateCall(GetExnFn, CPI);
1006   CGF.Builder.CreateStore(Exn, CGF.getExceptionSlot());
1007   llvm::CallInst *Selector = CGF.Builder.CreateCall(GetSelectorFn, CPI);
1008 
1009   llvm::Function *TypeIDFn = CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1010 
1011   // If there's only a single catch-all, branch directly to its handler.
1012   if (CatchScope.getNumHandlers() == 1 &&
1013       CatchScope.getHandler(0).isCatchAll()) {
1014     CGF.Builder.CreateBr(CatchScope.getHandler(0).Block);
1015     CGF.Builder.restoreIP(SavedIP);
1016     return;
1017   }
1018 
1019   // Test against each of the exception types we claim to catch.
1020   for (unsigned I = 0, E = NumHandlers;; ++I) {
1021     assert(I < E && "ran off end of handlers!");
1022     const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
1023     CatchTypeInfo TypeInfo = Handler.Type;
1024     if (!TypeInfo.RTTI)
1025       TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
1026 
1027     // Figure out the next block.
1028     llvm::BasicBlock *NextBlock;
1029 
1030     bool EmitNextBlock = false, NextIsEnd = false;
1031 
1032     // If this is the last handler, we're at the end, and the next block is a
1033     // block that contains a call to the rethrow function, so we can unwind to
1034     // the enclosing EH scope. The call itself will be generated later.
1035     if (I + 1 == E) {
1036       NextBlock = CGF.createBasicBlock("rethrow");
1037       EmitNextBlock = true;
1038       NextIsEnd = true;
1039 
1040       // If the next handler is a catch-all, we're at the end, and the
1041       // next block is that handler.
1042     } else if (CatchScope.getHandler(I + 1).isCatchAll()) {
1043       NextBlock = CatchScope.getHandler(I + 1).Block;
1044       NextIsEnd = true;
1045 
1046       // Otherwise, we're not at the end and we need a new block.
1047     } else {
1048       NextBlock = CGF.createBasicBlock("catch.fallthrough");
1049       EmitNextBlock = true;
1050     }
1051 
1052     // Figure out the catch type's index in the LSDA's type table.
1053     llvm::CallInst *TypeIndex = CGF.Builder.CreateCall(TypeIDFn, TypeInfo.RTTI);
1054     TypeIndex->setDoesNotThrow();
1055 
1056     llvm::Value *MatchesTypeIndex =
1057         CGF.Builder.CreateICmpEQ(Selector, TypeIndex, "matches");
1058     CGF.Builder.CreateCondBr(MatchesTypeIndex, Handler.Block, NextBlock);
1059 
1060     if (EmitNextBlock)
1061       CGF.EmitBlock(NextBlock);
1062     if (NextIsEnd)
1063       break;
1064   }
1065 
1066   CGF.Builder.restoreIP(SavedIP);
1067 }
1068 
1069 /// Emit the structure of the dispatch block for the given catch scope.
1070 /// It is an invariant that the dispatch block already exists.
1071 static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1072                                    EHCatchScope &catchScope) {
1073   if (EHPersonality::get(CGF).isWasmPersonality())
1074     return emitWasmCatchPadBlock(CGF, catchScope);
1075   if (EHPersonality::get(CGF).usesFuncletPads())
1076     return emitCatchPadBlock(CGF, catchScope);
1077 
1078   llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1079   assert(dispatchBlock);
1080 
1081   // If there's only a single catch-all, getEHDispatchBlock returned
1082   // that catch-all as the dispatch block.
1083   if (catchScope.getNumHandlers() == 1 &&
1084       catchScope.getHandler(0).isCatchAll()) {
1085     assert(dispatchBlock == catchScope.getHandler(0).Block);
1086     return;
1087   }
1088 
1089   CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1090   CGF.EmitBlockAfterUses(dispatchBlock);
1091 
1092   // Select the right handler.
1093   llvm::Function *llvm_eh_typeid_for =
1094     CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1095 
1096   // Load the selector value.
1097   llvm::Value *selector = CGF.getSelectorFromSlot();
1098 
1099   // Test against each of the exception types we claim to catch.
1100   for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1101     assert(i < e && "ran off end of handlers!");
1102     const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1103 
1104     llvm::Value *typeValue = handler.Type.RTTI;
1105     assert(handler.Type.Flags == 0 &&
1106            "landingpads do not support catch handler flags");
1107     assert(typeValue && "fell into catch-all case!");
1108     typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1109 
1110     // Figure out the next block.
1111     bool nextIsEnd;
1112     llvm::BasicBlock *nextBlock;
1113 
1114     // If this is the last handler, we're at the end, and the next
1115     // block is the block for the enclosing EH scope.
1116     if (i + 1 == e) {
1117       nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1118       nextIsEnd = true;
1119 
1120     // If the next handler is a catch-all, we're at the end, and the
1121     // next block is that handler.
1122     } else if (catchScope.getHandler(i+1).isCatchAll()) {
1123       nextBlock = catchScope.getHandler(i+1).Block;
1124       nextIsEnd = true;
1125 
1126     // Otherwise, we're not at the end and we need a new block.
1127     } else {
1128       nextBlock = CGF.createBasicBlock("catch.fallthrough");
1129       nextIsEnd = false;
1130     }
1131 
1132     // Figure out the catch type's index in the LSDA's type table.
1133     llvm::CallInst *typeIndex =
1134       CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1135     typeIndex->setDoesNotThrow();
1136 
1137     llvm::Value *matchesTypeIndex =
1138       CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1139     CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1140 
1141     // If the next handler is a catch-all, we're completely done.
1142     if (nextIsEnd) {
1143       CGF.Builder.restoreIP(savedIP);
1144       return;
1145     }
1146     // Otherwise we need to emit and continue at that block.
1147     CGF.EmitBlock(nextBlock);
1148   }
1149 }
1150 
1151 void CodeGenFunction::popCatchScope() {
1152   EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1153   if (catchScope.hasEHBranches())
1154     emitCatchDispatchBlock(*this, catchScope);
1155   EHStack.popCatch();
1156 }
1157 
1158 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1159   unsigned NumHandlers = S.getNumHandlers();
1160   EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1161   assert(CatchScope.getNumHandlers() == NumHandlers);
1162   llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
1163 
1164   // If the catch was not required, bail out now.
1165   if (!CatchScope.hasEHBranches()) {
1166     CatchScope.clearHandlerBlocks();
1167     EHStack.popCatch();
1168     return;
1169   }
1170 
1171   // Emit the structure of the EH dispatch for this catch.
1172   emitCatchDispatchBlock(*this, CatchScope);
1173 
1174   // Copy the handler blocks off before we pop the EH stack.  Emitting
1175   // the handlers might scribble on this memory.
1176   SmallVector<EHCatchScope::Handler, 8> Handlers(
1177       CatchScope.begin(), CatchScope.begin() + NumHandlers);
1178 
1179   EHStack.popCatch();
1180 
1181   // The fall-through block.
1182   llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1183 
1184   // We just emitted the body of the try; jump to the continue block.
1185   if (HaveInsertPoint())
1186     Builder.CreateBr(ContBB);
1187 
1188   // Determine if we need an implicit rethrow for all these catch handlers;
1189   // see the comment below.
1190   bool doImplicitRethrow = false;
1191   if (IsFnTryBlock)
1192     doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1193                         isa<CXXConstructorDecl>(CurCodeDecl);
1194 
1195   // Wasm uses Windows-style EH instructions, but merges all catch clauses into
1196   // one big catchpad. So we save the old funclet pad here before we traverse
1197   // each catch handler.
1198   SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1199       CurrentFuncletPad);
1200   llvm::BasicBlock *WasmCatchStartBlock = nullptr;
1201   if (EHPersonality::get(*this).isWasmPersonality()) {
1202     auto *CatchSwitch =
1203         cast<llvm::CatchSwitchInst>(DispatchBlock->getFirstNonPHI());
1204     WasmCatchStartBlock = CatchSwitch->hasUnwindDest()
1205                               ? CatchSwitch->getSuccessor(1)
1206                               : CatchSwitch->getSuccessor(0);
1207     auto *CPI = cast<llvm::CatchPadInst>(WasmCatchStartBlock->getFirstNonPHI());
1208     CurrentFuncletPad = CPI;
1209   }
1210 
1211   // Perversely, we emit the handlers backwards precisely because we
1212   // want them to appear in source order.  In all of these cases, the
1213   // catch block will have exactly one predecessor, which will be a
1214   // particular block in the catch dispatch.  However, in the case of
1215   // a catch-all, one of the dispatch blocks will branch to two
1216   // different handlers, and EmitBlockAfterUses will cause the second
1217   // handler to be moved before the first.
1218   bool HasCatchAll = false;
1219   for (unsigned I = NumHandlers; I != 0; --I) {
1220     HasCatchAll |= Handlers[I - 1].isCatchAll();
1221     llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1222     EmitBlockAfterUses(CatchBlock);
1223 
1224     // Catch the exception if this isn't a catch-all.
1225     const CXXCatchStmt *C = S.getHandler(I-1);
1226 
1227     // Enter a cleanup scope, including the catch variable and the
1228     // end-catch.
1229     RunCleanupsScope CatchScope(*this);
1230 
1231     // Initialize the catch variable and set up the cleanups.
1232     SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1233         CurrentFuncletPad);
1234     CGM.getCXXABI().emitBeginCatch(*this, C);
1235 
1236     // Emit the PGO counter increment.
1237     incrementProfileCounter(C);
1238 
1239     // Perform the body of the catch.
1240     EmitStmt(C->getHandlerBlock());
1241 
1242     // [except.handle]p11:
1243     //   The currently handled exception is rethrown if control
1244     //   reaches the end of a handler of the function-try-block of a
1245     //   constructor or destructor.
1246 
1247     // It is important that we only do this on fallthrough and not on
1248     // return.  Note that it's illegal to put a return in a
1249     // constructor function-try-block's catch handler (p14), so this
1250     // really only applies to destructors.
1251     if (doImplicitRethrow && HaveInsertPoint()) {
1252       CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
1253       Builder.CreateUnreachable();
1254       Builder.ClearInsertionPoint();
1255     }
1256 
1257     // Fall out through the catch cleanups.
1258     CatchScope.ForceCleanup();
1259 
1260     // Branch out of the try.
1261     if (HaveInsertPoint())
1262       Builder.CreateBr(ContBB);
1263   }
1264 
1265   // Because in wasm we merge all catch clauses into one big catchpad, in case
1266   // none of the types in catch handlers matches after we test against each of
1267   // them, we should unwind to the next EH enclosing scope. We generate a call
1268   // to rethrow function here to do that.
1269   if (EHPersonality::get(*this).isWasmPersonality() && !HasCatchAll) {
1270     assert(WasmCatchStartBlock);
1271     // Navigate for the "rethrow" block we created in emitWasmCatchPadBlock().
1272     // Wasm uses landingpad-style conditional branches to compare selectors, so
1273     // we follow the false destination for each of the cond branches to reach
1274     // the rethrow block.
1275     llvm::BasicBlock *RethrowBlock = WasmCatchStartBlock;
1276     while (llvm::Instruction *TI = RethrowBlock->getTerminator()) {
1277       auto *BI = cast<llvm::BranchInst>(TI);
1278       assert(BI->isConditional());
1279       RethrowBlock = BI->getSuccessor(1);
1280     }
1281     assert(RethrowBlock != WasmCatchStartBlock && RethrowBlock->empty());
1282     Builder.SetInsertPoint(RethrowBlock);
1283     llvm::Function *RethrowInCatchFn =
1284         CGM.getIntrinsic(llvm::Intrinsic::wasm_rethrow_in_catch);
1285     EmitNoreturnRuntimeCallOrInvoke(RethrowInCatchFn, {});
1286   }
1287 
1288   EmitBlock(ContBB);
1289   incrementProfileCounter(&S);
1290 }
1291 
1292 namespace {
1293   struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
1294     llvm::Value *ForEHVar;
1295     llvm::FunctionCallee EndCatchFn;
1296     CallEndCatchForFinally(llvm::Value *ForEHVar,
1297                            llvm::FunctionCallee EndCatchFn)
1298         : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1299 
1300     void Emit(CodeGenFunction &CGF, Flags flags) override {
1301       llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1302       llvm::BasicBlock *CleanupContBB =
1303         CGF.createBasicBlock("finally.cleanup.cont");
1304 
1305       llvm::Value *ShouldEndCatch =
1306         CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
1307       CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1308       CGF.EmitBlock(EndCatchBB);
1309       CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
1310       CGF.EmitBlock(CleanupContBB);
1311     }
1312   };
1313 
1314   struct PerformFinally final : EHScopeStack::Cleanup {
1315     const Stmt *Body;
1316     llvm::Value *ForEHVar;
1317     llvm::FunctionCallee EndCatchFn;
1318     llvm::FunctionCallee RethrowFn;
1319     llvm::Value *SavedExnVar;
1320 
1321     PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1322                    llvm::FunctionCallee EndCatchFn,
1323                    llvm::FunctionCallee RethrowFn, llvm::Value *SavedExnVar)
1324         : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1325           RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1326 
1327     void Emit(CodeGenFunction &CGF, Flags flags) override {
1328       // Enter a cleanup to call the end-catch function if one was provided.
1329       if (EndCatchFn)
1330         CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1331                                                         ForEHVar, EndCatchFn);
1332 
1333       // Save the current cleanup destination in case there are
1334       // cleanups in the finally block.
1335       llvm::Value *SavedCleanupDest =
1336         CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1337                                "cleanup.dest.saved");
1338 
1339       // Emit the finally block.
1340       CGF.EmitStmt(Body);
1341 
1342       // If the end of the finally is reachable, check whether this was
1343       // for EH.  If so, rethrow.
1344       if (CGF.HaveInsertPoint()) {
1345         llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1346         llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1347 
1348         llvm::Value *ShouldRethrow =
1349           CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
1350         CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1351 
1352         CGF.EmitBlock(RethrowBB);
1353         if (SavedExnVar) {
1354           CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1355             CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
1356         } else {
1357           CGF.EmitRuntimeCallOrInvoke(RethrowFn);
1358         }
1359         CGF.Builder.CreateUnreachable();
1360 
1361         CGF.EmitBlock(ContBB);
1362 
1363         // Restore the cleanup destination.
1364         CGF.Builder.CreateStore(SavedCleanupDest,
1365                                 CGF.getNormalCleanupDestSlot());
1366       }
1367 
1368       // Leave the end-catch cleanup.  As an optimization, pretend that
1369       // the fallthrough path was inaccessible; we've dynamically proven
1370       // that we're not in the EH case along that path.
1371       if (EndCatchFn) {
1372         CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1373         CGF.PopCleanupBlock();
1374         CGF.Builder.restoreIP(SavedIP);
1375       }
1376 
1377       // Now make sure we actually have an insertion point or the
1378       // cleanup gods will hate us.
1379       CGF.EnsureInsertPoint();
1380     }
1381   };
1382 } // end anonymous namespace
1383 
1384 /// Enters a finally block for an implementation using zero-cost
1385 /// exceptions.  This is mostly general, but hard-codes some
1386 /// language/ABI-specific behavior in the catch-all sections.
1387 void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF, const Stmt *body,
1388                                          llvm::FunctionCallee beginCatchFn,
1389                                          llvm::FunctionCallee endCatchFn,
1390                                          llvm::FunctionCallee rethrowFn) {
1391   assert((!!beginCatchFn) == (!!endCatchFn) &&
1392          "begin/end catch functions not paired");
1393   assert(rethrowFn && "rethrow function is required");
1394 
1395   BeginCatchFn = beginCatchFn;
1396 
1397   // The rethrow function has one of the following two types:
1398   //   void (*)()
1399   //   void (*)(void*)
1400   // In the latter case we need to pass it the exception object.
1401   // But we can't use the exception slot because the @finally might
1402   // have a landing pad (which would overwrite the exception slot).
1403   llvm::FunctionType *rethrowFnTy = rethrowFn.getFunctionType();
1404   SavedExnVar = nullptr;
1405   if (rethrowFnTy->getNumParams())
1406     SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1407 
1408   // A finally block is a statement which must be executed on any edge
1409   // out of a given scope.  Unlike a cleanup, the finally block may
1410   // contain arbitrary control flow leading out of itself.  In
1411   // addition, finally blocks should always be executed, even if there
1412   // are no catch handlers higher on the stack.  Therefore, we
1413   // surround the protected scope with a combination of a normal
1414   // cleanup (to catch attempts to break out of the block via normal
1415   // control flow) and an EH catch-all (semantically "outside" any try
1416   // statement to which the finally block might have been attached).
1417   // The finally block itself is generated in the context of a cleanup
1418   // which conditionally leaves the catch-all.
1419 
1420   // Jump destination for performing the finally block on an exception
1421   // edge.  We'll never actually reach this block, so unreachable is
1422   // fine.
1423   RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1424 
1425   // Whether the finally block is being executed for EH purposes.
1426   ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1427   CGF.Builder.CreateFlagStore(false, ForEHVar);
1428 
1429   // Enter a normal cleanup which will perform the @finally block.
1430   CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1431                                           ForEHVar, endCatchFn,
1432                                           rethrowFn, SavedExnVar);
1433 
1434   // Enter a catch-all scope.
1435   llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1436   EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1437   catchScope->setCatchAllHandler(0, catchBB);
1438 }
1439 
1440 void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1441   // Leave the finally catch-all.
1442   EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1443   llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1444 
1445   CGF.popCatchScope();
1446 
1447   // If there are any references to the catch-all block, emit it.
1448   if (catchBB->use_empty()) {
1449     delete catchBB;
1450   } else {
1451     CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1452     CGF.EmitBlock(catchBB);
1453 
1454     llvm::Value *exn = nullptr;
1455 
1456     // If there's a begin-catch function, call it.
1457     if (BeginCatchFn) {
1458       exn = CGF.getExceptionFromSlot();
1459       CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
1460     }
1461 
1462     // If we need to remember the exception pointer to rethrow later, do so.
1463     if (SavedExnVar) {
1464       if (!exn) exn = CGF.getExceptionFromSlot();
1465       CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
1466     }
1467 
1468     // Tell the cleanups in the finally block that we're do this for EH.
1469     CGF.Builder.CreateFlagStore(true, ForEHVar);
1470 
1471     // Thread a jump through the finally cleanup.
1472     CGF.EmitBranchThroughCleanup(RethrowDest);
1473 
1474     CGF.Builder.restoreIP(savedIP);
1475   }
1476 
1477   // Finally, leave the @finally cleanup.
1478   CGF.PopCleanupBlock();
1479 }
1480 
1481 llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1482   if (TerminateLandingPad)
1483     return TerminateLandingPad;
1484 
1485   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1486 
1487   // This will get inserted at the end of the function.
1488   TerminateLandingPad = createBasicBlock("terminate.lpad");
1489   Builder.SetInsertPoint(TerminateLandingPad);
1490 
1491   // Tell the backend that this is a landing pad.
1492   const EHPersonality &Personality = EHPersonality::get(*this);
1493 
1494   if (!CurFn->hasPersonalityFn())
1495     CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1496 
1497   llvm::LandingPadInst *LPadInst =
1498       Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
1499   LPadInst->addClause(getCatchAllValue(*this));
1500 
1501   llvm::Value *Exn = nullptr;
1502   if (getLangOpts().CPlusPlus)
1503     Exn = Builder.CreateExtractValue(LPadInst, 0);
1504   llvm::CallInst *terminateCall =
1505       CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1506   terminateCall->setDoesNotReturn();
1507   Builder.CreateUnreachable();
1508 
1509   // Restore the saved insertion state.
1510   Builder.restoreIP(SavedIP);
1511 
1512   return TerminateLandingPad;
1513 }
1514 
1515 llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1516   if (TerminateHandler)
1517     return TerminateHandler;
1518 
1519   // Set up the terminate handler.  This block is inserted at the very
1520   // end of the function by FinishFunction.
1521   TerminateHandler = createBasicBlock("terminate.handler");
1522   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1523   Builder.SetInsertPoint(TerminateHandler);
1524 
1525   llvm::Value *Exn = nullptr;
1526   if (getLangOpts().CPlusPlus)
1527     Exn = getExceptionFromSlot();
1528   llvm::CallInst *terminateCall =
1529       CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1530   terminateCall->setDoesNotReturn();
1531   Builder.CreateUnreachable();
1532 
1533   // Restore the saved insertion state.
1534   Builder.restoreIP(SavedIP);
1535 
1536   return TerminateHandler;
1537 }
1538 
1539 llvm::BasicBlock *CodeGenFunction::getTerminateFunclet() {
1540   assert(EHPersonality::get(*this).usesFuncletPads() &&
1541          "use getTerminateLandingPad for non-funclet EH");
1542 
1543   llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
1544   if (TerminateFunclet)
1545     return TerminateFunclet;
1546 
1547   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1548 
1549   // Set up the terminate handler.  This block is inserted at the very
1550   // end of the function by FinishFunction.
1551   TerminateFunclet = createBasicBlock("terminate.handler");
1552   Builder.SetInsertPoint(TerminateFunclet);
1553 
1554   // Create the cleanuppad using the current parent pad as its token. Use 'none'
1555   // if this is a top-level terminate scope, which is the common case.
1556   SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1557       CurrentFuncletPad);
1558   llvm::Value *ParentPad = CurrentFuncletPad;
1559   if (!ParentPad)
1560     ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1561   CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1562 
1563   // Emit the __std_terminate call.
1564   llvm::Value *Exn = nullptr;
1565   // In case of wasm personality, we need to pass the exception value to
1566   // __clang_call_terminate function.
1567   if (getLangOpts().CPlusPlus &&
1568       EHPersonality::get(*this).isWasmPersonality()) {
1569     llvm::Function *GetExnFn =
1570         CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
1571     Exn = Builder.CreateCall(GetExnFn, CurrentFuncletPad);
1572   }
1573   llvm::CallInst *terminateCall =
1574       CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1575   terminateCall->setDoesNotReturn();
1576   Builder.CreateUnreachable();
1577 
1578   // Restore the saved insertion state.
1579   Builder.restoreIP(SavedIP);
1580 
1581   return TerminateFunclet;
1582 }
1583 
1584 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1585   if (EHResumeBlock) return EHResumeBlock;
1586 
1587   CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1588 
1589   // We emit a jump to a notional label at the outermost unwind state.
1590   EHResumeBlock = createBasicBlock("eh.resume");
1591   Builder.SetInsertPoint(EHResumeBlock);
1592 
1593   const EHPersonality &Personality = EHPersonality::get(*this);
1594 
1595   // This can always be a call because we necessarily didn't find
1596   // anything on the EH stack which needs our help.
1597   const char *RethrowName = Personality.CatchallRethrowFn;
1598   if (RethrowName != nullptr && !isCleanup) {
1599     EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1600                     getExceptionFromSlot())->setDoesNotReturn();
1601     Builder.CreateUnreachable();
1602     Builder.restoreIP(SavedIP);
1603     return EHResumeBlock;
1604   }
1605 
1606   // Recreate the landingpad's return value for the 'resume' instruction.
1607   llvm::Value *Exn = getExceptionFromSlot();
1608   llvm::Value *Sel = getSelectorFromSlot();
1609 
1610   llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
1611   llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1612   LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1613   LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1614 
1615   Builder.CreateResume(LPadVal);
1616   Builder.restoreIP(SavedIP);
1617   return EHResumeBlock;
1618 }
1619 
1620 void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1621   EnterSEHTryStmt(S);
1622   {
1623     JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1624 
1625     SEHTryEpilogueStack.push_back(&TryExit);
1626     EmitStmt(S.getTryBlock());
1627     SEHTryEpilogueStack.pop_back();
1628 
1629     if (!TryExit.getBlock()->use_empty())
1630       EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1631     else
1632       delete TryExit.getBlock();
1633   }
1634   ExitSEHTryStmt(S);
1635 }
1636 
1637 namespace {
1638 struct PerformSEHFinally final : EHScopeStack::Cleanup {
1639   llvm::Function *OutlinedFinally;
1640   PerformSEHFinally(llvm::Function *OutlinedFinally)
1641       : OutlinedFinally(OutlinedFinally) {}
1642 
1643   void Emit(CodeGenFunction &CGF, Flags F) override {
1644     ASTContext &Context = CGF.getContext();
1645     CodeGenModule &CGM = CGF.CGM;
1646 
1647     CallArgList Args;
1648 
1649     // Compute the two argument values.
1650     QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
1651     llvm::Value *FP = nullptr;
1652     // If CFG.IsOutlinedSEHHelper is true, then we are within a finally block.
1653     if (CGF.IsOutlinedSEHHelper) {
1654       FP = &CGF.CurFn->arg_begin()[1];
1655     } else {
1656       llvm::Function *LocalAddrFn =
1657           CGM.getIntrinsic(llvm::Intrinsic::localaddress);
1658       FP = CGF.Builder.CreateCall(LocalAddrFn);
1659     }
1660 
1661     llvm::Value *IsForEH =
1662         llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1663 
1664     // Except _leave and fall-through at the end, all other exits in a _try
1665     //   (return/goto/continue/break) are considered as abnormal terminations
1666     //   since _leave/fall-through is always Indexed 0,
1667     //   just use NormalCleanupDestSlot (>= 1 for goto/return/..),
1668     //   as 1st Arg to indicate abnormal termination
1669     if (!F.isForEHCleanup() && F.hasExitSwitch()) {
1670       Address Addr = CGF.getNormalCleanupDestSlot();
1671       llvm::Value *Load = CGF.Builder.CreateLoad(Addr, "cleanup.dest");
1672       llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int32Ty);
1673       IsForEH = CGF.Builder.CreateICmpNE(Load, Zero);
1674     }
1675 
1676     Args.add(RValue::get(IsForEH), ArgTys[0]);
1677     Args.add(RValue::get(FP), ArgTys[1]);
1678 
1679     // Arrange a two-arg function info and type.
1680     const CGFunctionInfo &FnInfo =
1681         CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
1682 
1683     auto Callee = CGCallee::forDirect(OutlinedFinally);
1684     CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
1685   }
1686 };
1687 } // end anonymous namespace
1688 
1689 namespace {
1690 /// Find all local variable captures in the statement.
1691 struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1692   CodeGenFunction &ParentCGF;
1693   const VarDecl *ParentThis;
1694   llvm::SmallSetVector<const VarDecl *, 4> Captures;
1695   Address SEHCodeSlot = Address::invalid();
1696   CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1697       : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1698 
1699   // Return true if we need to do any capturing work.
1700   bool foundCaptures() {
1701     return !Captures.empty() || SEHCodeSlot.isValid();
1702   }
1703 
1704   void Visit(const Stmt *S) {
1705     // See if this is a capture, then recurse.
1706     ConstStmtVisitor<CaptureFinder>::Visit(S);
1707     for (const Stmt *Child : S->children())
1708       if (Child)
1709         Visit(Child);
1710   }
1711 
1712   void VisitDeclRefExpr(const DeclRefExpr *E) {
1713     // If this is already a capture, just make sure we capture 'this'.
1714     if (E->refersToEnclosingVariableOrCapture()) {
1715       Captures.insert(ParentThis);
1716       return;
1717     }
1718 
1719     const auto *D = dyn_cast<VarDecl>(E->getDecl());
1720     if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1721       Captures.insert(D);
1722   }
1723 
1724   void VisitCXXThisExpr(const CXXThisExpr *E) {
1725     Captures.insert(ParentThis);
1726   }
1727 
1728   void VisitCallExpr(const CallExpr *E) {
1729     // We only need to add parent frame allocations for these builtins in x86.
1730     if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1731       return;
1732 
1733     unsigned ID = E->getBuiltinCallee();
1734     switch (ID) {
1735     case Builtin::BI__exception_code:
1736     case Builtin::BI_exception_code:
1737       // This is the simple case where we are the outermost finally. All we
1738       // have to do here is make sure we escape this and recover it in the
1739       // outlined handler.
1740       if (!SEHCodeSlot.isValid())
1741         SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1742       break;
1743     }
1744   }
1745 };
1746 } // end anonymous namespace
1747 
1748 Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
1749                                                    Address ParentVar,
1750                                                    llvm::Value *ParentFP) {
1751   llvm::CallInst *RecoverCall = nullptr;
1752   CGBuilderTy Builder(*this, AllocaInsertPt);
1753   if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
1754     // Mark the variable escaped if nobody else referenced it and compute the
1755     // localescape index.
1756     auto InsertPair = ParentCGF.EscapedLocals.insert(
1757         std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1758     int FrameEscapeIdx = InsertPair.first->second;
1759     // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
1760     llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1761         &CGM.getModule(), llvm::Intrinsic::localrecover);
1762     llvm::Constant *ParentI8Fn =
1763         llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1764     RecoverCall = Builder.CreateCall(
1765         FrameRecoverFn, {ParentI8Fn, ParentFP,
1766                          llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1767 
1768   } else {
1769     // If the parent didn't have an alloca, we're doing some nested outlining.
1770     // Just clone the existing localrecover call, but tweak the FP argument to
1771     // use our FP value. All other arguments are constants.
1772     auto *ParentRecover =
1773         cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
1774     assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1775            "expected alloca or localrecover in parent LocalDeclMap");
1776     RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1777     RecoverCall->setArgOperand(1, ParentFP);
1778     RecoverCall->insertBefore(AllocaInsertPt);
1779   }
1780 
1781   // Bitcast the variable, rename it, and insert it in the local decl map.
1782   llvm::Value *ChildVar =
1783       Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1784   ChildVar->setName(ParentVar.getName());
1785   return Address(ChildVar, ParentVar.getAlignment());
1786 }
1787 
1788 void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
1789                                          const Stmt *OutlinedStmt,
1790                                          bool IsFilter) {
1791   // Find all captures in the Stmt.
1792   CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1793   Finder.Visit(OutlinedStmt);
1794 
1795   // We can exit early on x86_64 when there are no captures. We just have to
1796   // save the exception code in filters so that __exception_code() works.
1797   if (!Finder.foundCaptures() &&
1798       CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1799     if (IsFilter)
1800       EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
1801     return;
1802   }
1803 
1804   llvm::Value *EntryFP = nullptr;
1805   CGBuilderTy Builder(CGM, AllocaInsertPt);
1806   if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1807     // 32-bit SEH filters need to be careful about FP recovery.  The end of the
1808     // EH registration is passed in as the EBP physical register.  We can
1809     // recover that with llvm.frameaddress(1).
1810     EntryFP = Builder.CreateCall(
1811         CGM.getIntrinsic(llvm::Intrinsic::frameaddress, AllocaInt8PtrTy),
1812         {Builder.getInt32(1)});
1813   } else {
1814     // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1815     // second parameter.
1816     auto AI = CurFn->arg_begin();
1817     ++AI;
1818     EntryFP = &*AI;
1819   }
1820 
1821   llvm::Value *ParentFP = EntryFP;
1822   if (IsFilter) {
1823     // Given whatever FP the runtime provided us in EntryFP, recover the true
1824     // frame pointer of the parent function. We only need to do this in filters,
1825     // since finally funclets recover the parent FP for us.
1826     llvm::Function *RecoverFPIntrin =
1827         CGM.getIntrinsic(llvm::Intrinsic::eh_recoverfp);
1828     llvm::Constant *ParentI8Fn =
1829         llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1830     ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
1831   }
1832 
1833   // Create llvm.localrecover calls for all captures.
1834   for (const VarDecl *VD : Finder.Captures) {
1835     if (isa<ImplicitParamDecl>(VD)) {
1836       CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1837       CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1838       continue;
1839     }
1840     if (VD->getType()->isVariablyModifiedType()) {
1841       CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1842       continue;
1843     }
1844     assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1845            "captured non-local variable");
1846 
1847     // If this decl hasn't been declared yet, it will be declared in the
1848     // OutlinedStmt.
1849     auto I = ParentCGF.LocalDeclMap.find(VD);
1850     if (I == ParentCGF.LocalDeclMap.end())
1851       continue;
1852 
1853     Address ParentVar = I->second;
1854     setAddrOfLocalVar(
1855         VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
1856   }
1857 
1858   if (Finder.SEHCodeSlot.isValid()) {
1859     SEHCodeSlotStack.push_back(
1860         recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1861   }
1862 
1863   if (IsFilter)
1864     EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
1865 }
1866 
1867 /// Arrange a function prototype that can be called by Windows exception
1868 /// handling personalities. On Win64, the prototype looks like:
1869 /// RetTy func(void *EHPtrs, void *ParentFP);
1870 void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
1871                                              bool IsFilter,
1872                                              const Stmt *OutlinedStmt) {
1873   SourceLocation StartLoc = OutlinedStmt->getBeginLoc();
1874 
1875   // Get the mangled function name.
1876   SmallString<128> Name;
1877   {
1878     llvm::raw_svector_ostream OS(Name);
1879     const NamedDecl *ParentSEHFn = ParentCGF.CurSEHParent;
1880     assert(ParentSEHFn && "No CurSEHParent!");
1881     MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1882     if (IsFilter)
1883       Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
1884     else
1885       Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
1886   }
1887 
1888   FunctionArgList Args;
1889   if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1890     // All SEH finally functions take two parameters. Win64 filters take two
1891     // parameters. Win32 filters take no parameters.
1892     if (IsFilter) {
1893       Args.push_back(ImplicitParamDecl::Create(
1894           getContext(), /*DC=*/nullptr, StartLoc,
1895           &getContext().Idents.get("exception_pointers"),
1896           getContext().VoidPtrTy, ImplicitParamDecl::Other));
1897     } else {
1898       Args.push_back(ImplicitParamDecl::Create(
1899           getContext(), /*DC=*/nullptr, StartLoc,
1900           &getContext().Idents.get("abnormal_termination"),
1901           getContext().UnsignedCharTy, ImplicitParamDecl::Other));
1902     }
1903     Args.push_back(ImplicitParamDecl::Create(
1904         getContext(), /*DC=*/nullptr, StartLoc,
1905         &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
1906         ImplicitParamDecl::Other));
1907   }
1908 
1909   QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1910 
1911   const CGFunctionInfo &FnInfo =
1912     CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
1913 
1914   llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1915   llvm::Function *Fn = llvm::Function::Create(
1916       FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
1917 
1918   IsOutlinedSEHHelper = true;
1919 
1920   StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1921                 OutlinedStmt->getBeginLoc(), OutlinedStmt->getBeginLoc());
1922   CurSEHParent = ParentCGF.CurSEHParent;
1923 
1924   CGM.SetInternalFunctionAttributes(GlobalDecl(), CurFn, FnInfo);
1925   EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
1926 }
1927 
1928 /// Create a stub filter function that will ultimately hold the code of the
1929 /// filter expression. The EH preparation passes in LLVM will outline the code
1930 /// from the main function body into this stub.
1931 llvm::Function *
1932 CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1933                                            const SEHExceptStmt &Except) {
1934   const Expr *FilterExpr = Except.getFilterExpr();
1935   startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
1936 
1937   // Emit the original filter expression, convert to i32, and return.
1938   llvm::Value *R = EmitScalarExpr(FilterExpr);
1939   R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
1940                             FilterExpr->getType()->isSignedIntegerType());
1941   Builder.CreateStore(R, ReturnValue);
1942 
1943   FinishFunction(FilterExpr->getEndLoc());
1944 
1945   return CurFn;
1946 }
1947 
1948 llvm::Function *
1949 CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1950                                             const SEHFinallyStmt &Finally) {
1951   const Stmt *FinallyBlock = Finally.getBlock();
1952   startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
1953 
1954   // Emit the original filter expression, convert to i32, and return.
1955   EmitStmt(FinallyBlock);
1956 
1957   FinishFunction(FinallyBlock->getEndLoc());
1958 
1959   return CurFn;
1960 }
1961 
1962 void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1963                                                llvm::Value *ParentFP,
1964                                                llvm::Value *EntryFP) {
1965   // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1966   // __exception_info intrinsic.
1967   if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1968     // On Win64, the info is passed as the first parameter to the filter.
1969     SEHInfo = &*CurFn->arg_begin();
1970     SEHCodeSlotStack.push_back(
1971         CreateMemTemp(getContext().IntTy, "__exception_code"));
1972   } else {
1973     // On Win32, the EBP on entry to the filter points to the end of an
1974     // exception registration object. It contains 6 32-bit fields, and the info
1975     // pointer is stored in the second field. So, GEP 20 bytes backwards and
1976     // load the pointer.
1977     SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
1978     SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
1979     SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
1980     SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1981         ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1982   }
1983 
1984   // Save the exception code in the exception slot to unify exception access in
1985   // the filter function and the landing pad.
1986   // struct EXCEPTION_POINTERS {
1987   //   EXCEPTION_RECORD *ExceptionRecord;
1988   //   CONTEXT *ContextRecord;
1989   // };
1990   // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
1991   llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1992   llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
1993   llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
1994   llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
1995   Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
1996   llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
1997   assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1998   Builder.CreateStore(Code, SEHCodeSlotStack.back());
1999 }
2000 
2001 llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
2002   // Sema should diagnose calling this builtin outside of a filter context, but
2003   // don't crash if we screw up.
2004   if (!SEHInfo)
2005     return llvm::UndefValue::get(Int8PtrTy);
2006   assert(SEHInfo->getType() == Int8PtrTy);
2007   return SEHInfo;
2008 }
2009 
2010 llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
2011   assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
2012   return Builder.CreateLoad(SEHCodeSlotStack.back());
2013 }
2014 
2015 llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
2016   // Abnormal termination is just the first parameter to the outlined finally
2017   // helper.
2018   auto AI = CurFn->arg_begin();
2019   return Builder.CreateZExt(&*AI, Int32Ty);
2020 }
2021 
2022 void CodeGenFunction::pushSEHCleanup(CleanupKind Kind,
2023                                      llvm::Function *FinallyFunc) {
2024   EHStack.pushCleanup<PerformSEHFinally>(Kind, FinallyFunc);
2025 }
2026 
2027 void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
2028   CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
2029   if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
2030     // Outline the finally block.
2031     llvm::Function *FinallyFunc =
2032         HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
2033 
2034     // Push a cleanup for __finally blocks.
2035     EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
2036     return;
2037   }
2038 
2039   // Otherwise, we must have an __except block.
2040   const SEHExceptStmt *Except = S.getExceptHandler();
2041   assert(Except);
2042   EHCatchScope *CatchScope = EHStack.pushCatch(1);
2043   SEHCodeSlotStack.push_back(
2044       CreateMemTemp(getContext().IntTy, "__exception_code"));
2045 
2046   // If the filter is known to evaluate to 1, then we can use the clause
2047   // "catch i8* null". We can't do this on x86 because the filter has to save
2048   // the exception code.
2049   llvm::Constant *C =
2050     ConstantEmitter(*this).tryEmitAbstract(Except->getFilterExpr(),
2051                                            getContext().IntTy);
2052   if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
2053       C->isOneValue()) {
2054     CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
2055     return;
2056   }
2057 
2058   // In general, we have to emit an outlined filter function. Use the function
2059   // in place of the RTTI typeinfo global that C++ EH uses.
2060   llvm::Function *FilterFunc =
2061       HelperCGF.GenerateSEHFilterFunction(*this, *Except);
2062   llvm::Constant *OpaqueFunc =
2063       llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
2064   CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
2065 }
2066 
2067 void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
2068   // Just pop the cleanup if it's a __finally block.
2069   if (S.getFinallyHandler()) {
2070     PopCleanupBlock();
2071     return;
2072   }
2073 
2074   // Otherwise, we must have an __except block.
2075   const SEHExceptStmt *Except = S.getExceptHandler();
2076   assert(Except && "__try must have __finally xor __except");
2077   EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
2078 
2079   // Don't emit the __except block if the __try block lacked invokes.
2080   // TODO: Model unwind edges from instructions, either with iload / istore or
2081   // a try body function.
2082   if (!CatchScope.hasEHBranches()) {
2083     CatchScope.clearHandlerBlocks();
2084     EHStack.popCatch();
2085     SEHCodeSlotStack.pop_back();
2086     return;
2087   }
2088 
2089   // The fall-through block.
2090   llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
2091 
2092   // We just emitted the body of the __try; jump to the continue block.
2093   if (HaveInsertPoint())
2094     Builder.CreateBr(ContBB);
2095 
2096   // Check if our filter function returned true.
2097   emitCatchDispatchBlock(*this, CatchScope);
2098 
2099   // Grab the block before we pop the handler.
2100   llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
2101   EHStack.popCatch();
2102 
2103   EmitBlockAfterUses(CatchPadBB);
2104 
2105   // __except blocks don't get outlined into funclets, so immediately do a
2106   // catchret.
2107   llvm::CatchPadInst *CPI =
2108       cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
2109   llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
2110   Builder.CreateCatchRet(CPI, ExceptBB);
2111   EmitBlock(ExceptBB);
2112 
2113   // On Win64, the exception code is returned in EAX. Copy it into the slot.
2114   if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
2115     llvm::Function *SEHCodeIntrin =
2116         CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
2117     llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
2118     Builder.CreateStore(Code, SEHCodeSlotStack.back());
2119   }
2120 
2121   // Emit the __except body.
2122   EmitStmt(Except->getBlock());
2123 
2124   // End the lifetime of the exception code.
2125   SEHCodeSlotStack.pop_back();
2126 
2127   if (HaveInsertPoint())
2128     Builder.CreateBr(ContBB);
2129 
2130   EmitBlock(ContBB);
2131 }
2132 
2133 void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
2134   // If this code is reachable then emit a stop point (if generating
2135   // debug info). We have to do this ourselves because we are on the
2136   // "simple" statement path.
2137   if (HaveInsertPoint())
2138     EmitStopPoint(&S);
2139 
2140   // This must be a __leave from a __finally block, which we warn on and is UB.
2141   // Just emit unreachable.
2142   if (!isSEHTryScope()) {
2143     Builder.CreateUnreachable();
2144     Builder.ClearInsertionPoint();
2145     return;
2146   }
2147 
2148   EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
2149 }
2150