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