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