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