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