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