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