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