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