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