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