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