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