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