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