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 *getAllocateExceptionFn(CodeGenModule &CGM) {
29   // void *__cxa_allocate_exception(size_t thrown_size);
30 
31   llvm::FunctionType *FTy =
32     llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
33 
34   return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
35 }
36 
37 static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
38   // void __cxa_free_exception(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_free_exception");
44 }
45 
46 static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
47   // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
48   //                  void (*dest) (void *));
49 
50   llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
51   llvm::FunctionType *FTy =
52     llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
53 
54   return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
55 }
56 
57 static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
58   // void *__cxa_get_exception_ptr(void*);
59 
60   llvm::FunctionType *FTy =
61     llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
62 
63   return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
64 }
65 
66 static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
67   if (CGM.getTarget().getCXXABI().isMicrosoft())
68     return CGM.getIntrinsic(llvm::Intrinsic::eh_begincatch);
69 
70   // void *__cxa_begin_catch(void*);
71 
72   llvm::FunctionType *FTy =
73     llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
74 
75   return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
76 }
77 
78 static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
79   if (CGM.getTarget().getCXXABI().isMicrosoft())
80     return CGM.getIntrinsic(llvm::Intrinsic::eh_endcatch);
81 
82   // void __cxa_end_catch();
83 
84   llvm::FunctionType *FTy =
85     llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
86 
87   return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
88 }
89 
90 static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
91   // void __cxa_call_unexpected(void *thrown_exception);
92 
93   llvm::FunctionType *FTy =
94     llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
95 
96   return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
97 }
98 
99 static llvm::Constant *getTerminateFn(CodeGenModule &CGM) {
100   // void __terminate();
101 
102   llvm::FunctionType *FTy =
103     llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
104 
105   StringRef name;
106 
107   // In C++, use std::terminate().
108   if (CGM.getLangOpts().CPlusPlus &&
109       CGM.getTarget().getCXXABI().isItaniumFamily()) {
110     name = "_ZSt9terminatev";
111   } else if (CGM.getLangOpts().CPlusPlus &&
112              CGM.getTarget().getCXXABI().isMicrosoft()) {
113     name = "\01?terminate@@YAXXZ";
114   } else if (CGM.getLangOpts().ObjC1 &&
115              CGM.getLangOpts().ObjCRuntime.hasTerminate())
116     name = "objc_terminate";
117   else
118     name = "abort";
119   return CGM.CreateRuntimeFunction(FTy, name);
120 }
121 
122 static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
123                                             StringRef Name) {
124   llvm::FunctionType *FTy =
125     llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
126 
127   return CGM.CreateRuntimeFunction(FTy, Name);
128 }
129 
130 namespace {
131   /// The exceptions personality for a function.
132   struct EHPersonality {
133     const char *PersonalityFn;
134 
135     // If this is non-null, this personality requires a non-standard
136     // function for rethrowing an exception after a catchall cleanup.
137     // This function must have prototype void(void*).
138     const char *CatchallRethrowFn;
139 
140     static const EHPersonality &get(CodeGenModule &CGM,
141                                     const FunctionDecl *FD);
142     static const EHPersonality &get(CodeGenFunction &CGF) {
143       return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
144     }
145 
146     static const EHPersonality GNU_C;
147     static const EHPersonality GNU_C_SJLJ;
148     static const EHPersonality GNU_C_SEH;
149     static const EHPersonality GNU_ObjC;
150     static const EHPersonality GNUstep_ObjC;
151     static const EHPersonality GNU_ObjCXX;
152     static const EHPersonality NeXT_ObjC;
153     static const EHPersonality GNU_CPlusPlus;
154     static const EHPersonality GNU_CPlusPlus_SJLJ;
155     static const EHPersonality GNU_CPlusPlus_SEH;
156     static const EHPersonality MSVC_except_handler;
157     static const EHPersonality MSVC_C_specific_handler;
158     static const EHPersonality MSVC_CxxFrameHandler3;
159   };
160 }
161 
162 const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
163 const EHPersonality
164 EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
165 const EHPersonality
166 EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
167 const EHPersonality
168 EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
169 const EHPersonality
170 EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
171 const EHPersonality
172 EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
173 const EHPersonality
174 EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
175 const EHPersonality
176 EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
177 const EHPersonality
178 EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
179 const EHPersonality
180 EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
181 const EHPersonality
182 EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
183 const EHPersonality
184 EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
185 const EHPersonality
186 EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
187 
188 /// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
189 /// other platforms, unless the user asked for SjLj exceptions.
190 static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
191   return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
192 }
193 
194 static const EHPersonality &getCPersonality(const llvm::Triple &T,
195                                             const LangOptions &L) {
196   if (L.SjLjExceptions)
197     return EHPersonality::GNU_C_SJLJ;
198   else if (useLibGCCSEHPersonality(T))
199     return EHPersonality::GNU_C_SEH;
200   return EHPersonality::GNU_C;
201 }
202 
203 static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
204                                                const LangOptions &L) {
205   switch (L.ObjCRuntime.getKind()) {
206   case ObjCRuntime::FragileMacOSX:
207     return getCPersonality(T, L);
208   case ObjCRuntime::MacOSX:
209   case ObjCRuntime::iOS:
210     return EHPersonality::NeXT_ObjC;
211   case ObjCRuntime::GNUstep:
212     if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
213       return EHPersonality::GNUstep_ObjC;
214     // fallthrough
215   case ObjCRuntime::GCC:
216   case ObjCRuntime::ObjFW:
217     return EHPersonality::GNU_ObjC;
218   }
219   llvm_unreachable("bad runtime kind");
220 }
221 
222 static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
223                                               const LangOptions &L) {
224   if (L.SjLjExceptions)
225     return EHPersonality::GNU_CPlusPlus_SJLJ;
226   else if (useLibGCCSEHPersonality(T))
227     return EHPersonality::GNU_CPlusPlus_SEH;
228   return EHPersonality::GNU_CPlusPlus;
229 }
230 
231 /// Determines the personality function to use when both C++
232 /// and Objective-C exceptions are being caught.
233 static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
234                                                  const LangOptions &L) {
235   switch (L.ObjCRuntime.getKind()) {
236   // The ObjC personality defers to the C++ personality for non-ObjC
237   // handlers.  Unlike the C++ case, we use the same personality
238   // function on targets using (backend-driven) SJLJ EH.
239   case ObjCRuntime::MacOSX:
240   case ObjCRuntime::iOS:
241     return EHPersonality::NeXT_ObjC;
242 
243   // In the fragile ABI, just use C++ exception handling and hope
244   // they're not doing crazy exception mixing.
245   case ObjCRuntime::FragileMacOSX:
246     return getCXXPersonality(T, L);
247 
248   // The GCC runtime's personality function inherently doesn't support
249   // mixed EH.  Use the C++ personality just to avoid returning null.
250   case ObjCRuntime::GCC:
251   case ObjCRuntime::ObjFW: // XXX: this will change soon
252     return EHPersonality::GNU_ObjC;
253   case ObjCRuntime::GNUstep:
254     return EHPersonality::GNU_ObjCXX;
255   }
256   llvm_unreachable("bad runtime kind");
257 }
258 
259 static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
260   if (T.getArch() == llvm::Triple::x86)
261     return EHPersonality::MSVC_except_handler;
262   return EHPersonality::MSVC_C_specific_handler;
263 }
264 
265 const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
266                                         const FunctionDecl *FD) {
267   const llvm::Triple &T = CGM.getTarget().getTriple();
268   const LangOptions &L = CGM.getLangOpts();
269 
270   // Try to pick a personality function that is compatible with MSVC if we're
271   // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
272   // the GCC-style personality function.
273   if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
274     if (L.SjLjExceptions)
275       return EHPersonality::GNU_CPlusPlus_SJLJ;
276     else if (FD && FD->usesSEHTry())
277       return getSEHPersonalityMSVC(T);
278     else
279       return EHPersonality::MSVC_CxxFrameHandler3;
280   }
281 
282   if (L.CPlusPlus && L.ObjC1)
283     return getObjCXXPersonality(T, L);
284   else if (L.CPlusPlus)
285     return getCXXPersonality(T, L);
286   else if (L.ObjC1)
287     return getObjCPersonality(T, L);
288   else
289     return getCPersonality(T, L);
290 }
291 
292 static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
293                                         const EHPersonality &Personality) {
294   llvm::Constant *Fn =
295     CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
296                               Personality.PersonalityFn);
297   return Fn;
298 }
299 
300 static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
301                                         const EHPersonality &Personality) {
302   llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
303   return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
304 }
305 
306 /// Check whether a personality function could reasonably be swapped
307 /// for a C++ personality function.
308 static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
309   for (llvm::User *U : Fn->users()) {
310     // Conditionally white-list bitcasts.
311     if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
312       if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
313       if (!PersonalityHasOnlyCXXUses(CE))
314         return false;
315       continue;
316     }
317 
318     // Otherwise, it has to be a landingpad instruction.
319     llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
320     if (!LPI) return false;
321 
322     for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
323       // Look for something that would've been returned by the ObjC
324       // runtime's GetEHType() method.
325       llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
326       if (LPI->isCatch(I)) {
327         // Check if the catch value has the ObjC prefix.
328         if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
329           // ObjC EH selector entries are always global variables with
330           // names starting like this.
331           if (GV->getName().startswith("OBJC_EHTYPE"))
332             return false;
333       } else {
334         // Check if any of the filter values have the ObjC prefix.
335         llvm::Constant *CVal = cast<llvm::Constant>(Val);
336         for (llvm::User::op_iterator
337                II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
338           if (llvm::GlobalVariable *GV =
339               cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
340             // ObjC EH selector entries are always global variables with
341             // names starting like this.
342             if (GV->getName().startswith("OBJC_EHTYPE"))
343               return false;
344         }
345       }
346     }
347   }
348 
349   return true;
350 }
351 
352 /// Try to use the C++ personality function in ObjC++.  Not doing this
353 /// can cause some incompatibilities with gcc, which is more
354 /// aggressive about only using the ObjC++ personality in a function
355 /// when it really needs it.
356 void CodeGenModule::SimplifyPersonality() {
357   // If we're not in ObjC++ -fexceptions, there's nothing to do.
358   if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
359     return;
360 
361   // Both the problem this endeavors to fix and the way the logic
362   // above works is specific to the NeXT runtime.
363   if (!LangOpts.ObjCRuntime.isNeXTFamily())
364     return;
365 
366   const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
367   const EHPersonality &CXX =
368       getCXXPersonality(getTarget().getTriple(), LangOpts);
369   if (&ObjCXX == &CXX)
370     return;
371 
372   assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
373          "Different EHPersonalities using the same personality function.");
374 
375   llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
376 
377   // Nothing to do if it's unused.
378   if (!Fn || Fn->use_empty()) return;
379 
380   // Can't do the optimization if it has non-C++ uses.
381   if (!PersonalityHasOnlyCXXUses(Fn)) return;
382 
383   // Create the C++ personality function and kill off the old
384   // function.
385   llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
386 
387   // This can happen if the user is screwing with us.
388   if (Fn->getType() != CXXFn->getType()) return;
389 
390   Fn->replaceAllUsesWith(CXXFn);
391   Fn->eraseFromParent();
392 }
393 
394 /// Returns the value to inject into a selector to indicate the
395 /// presence of a catch-all.
396 static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
397   // Possibly we should use @llvm.eh.catch.all.value here.
398   return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
399 }
400 
401 namespace {
402   /// A cleanup to free the exception object if its initialization
403   /// throws.
404   struct FreeException : EHScopeStack::Cleanup {
405     llvm::Value *exn;
406     FreeException(llvm::Value *exn) : exn(exn) {}
407     void Emit(CodeGenFunction &CGF, Flags flags) override {
408       CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
409     }
410   };
411 }
412 
413 // Emits an exception expression into the given location.  This
414 // differs from EmitAnyExprToMem only in that, if a final copy-ctor
415 // call is required, an exception within that copy ctor causes
416 // std::terminate to be invoked.
417 static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
418                              llvm::Value *addr) {
419   // Make sure the exception object is cleaned up if there's an
420   // exception during initialization.
421   CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
422   EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
423 
424   // __cxa_allocate_exception returns a void*;  we need to cast this
425   // to the appropriate type for the object.
426   llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
427   llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
428 
429   // FIXME: this isn't quite right!  If there's a final unelided call
430   // to a copy constructor, then according to [except.terminate]p1 we
431   // must call std::terminate() if that constructor throws, because
432   // technically that copy occurs after the exception expression is
433   // evaluated but before the exception is caught.  But the best way
434   // to handle that is to teach EmitAggExpr to do the final copy
435   // differently if it can't be elided.
436   CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
437                        /*IsInit*/ true);
438 
439   // Deactivate the cleanup block.
440   CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
441 }
442 
443 llvm::Value *CodeGenFunction::getExceptionSlot() {
444   if (!ExceptionSlot)
445     ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
446   return ExceptionSlot;
447 }
448 
449 llvm::Value *CodeGenFunction::getEHSelectorSlot() {
450   if (!EHSelectorSlot)
451     EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
452   return EHSelectorSlot;
453 }
454 
455 llvm::Value *CodeGenFunction::getExceptionFromSlot() {
456   return Builder.CreateLoad(getExceptionSlot(), "exn");
457 }
458 
459 llvm::Value *CodeGenFunction::getSelectorFromSlot() {
460   return Builder.CreateLoad(getEHSelectorSlot(), "sel");
461 }
462 
463 llvm::Value *CodeGenFunction::getAbnormalTerminationSlot() {
464   if (!AbnormalTerminationSlot)
465     AbnormalTerminationSlot =
466         CreateTempAlloca(Int8Ty, "abnormal.termination.slot");
467   return AbnormalTerminationSlot;
468 }
469 
470 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
471                                        bool KeepInsertionPoint) {
472   if (!E->getSubExpr()) {
473     CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/true);
474 
475     // throw is an expression, and the expression emitters expect us
476     // to leave ourselves at a valid insertion point.
477     if (KeepInsertionPoint)
478       EmitBlock(createBasicBlock("throw.cont"));
479 
480     return;
481   }
482 
483   if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) {
484     // Call std::terminate().
485     llvm::CallInst *TermCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
486     TermCall->setDoesNotReturn();
487 
488     // throw is an expression, and the expression emitters expect us
489     // to leave ourselves at a valid insertion point.
490     if (KeepInsertionPoint)
491       EmitBlock(createBasicBlock("throw.cont"));
492 
493     return;
494   }
495 
496   QualType ThrowType = E->getSubExpr()->getType();
497 
498   if (ThrowType->isObjCObjectPointerType()) {
499     const Stmt *ThrowStmt = E->getSubExpr();
500     const ObjCAtThrowStmt S(E->getExprLoc(),
501                             const_cast<Stmt *>(ThrowStmt));
502     CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
503     // This will clear insertion point which was not cleared in
504     // call to EmitThrowStmt.
505     if (KeepInsertionPoint)
506       EmitBlock(createBasicBlock("throw.cont"));
507     return;
508   }
509 
510   // Now allocate the exception object.
511   llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
512   uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
513 
514   llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
515   llvm::CallInst *ExceptionPtr =
516     EmitNounwindRuntimeCall(AllocExceptionFn,
517                             llvm::ConstantInt::get(SizeTy, TypeSize),
518                             "exception");
519 
520   EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
521 
522   // Now throw the exception.
523   llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
524                                                          /*ForEH=*/true);
525 
526   // The address of the destructor.  If the exception type has a
527   // trivial destructor (or isn't a record), we just pass null.
528   llvm::Constant *Dtor = nullptr;
529   if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
530     CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
531     if (!Record->hasTrivialDestructor()) {
532       CXXDestructorDecl *DtorD = Record->getDestructor();
533       Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
534       Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
535     }
536   }
537   if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
538 
539   llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
540   EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
541 
542   // throw is an expression, and the expression emitters expect us
543   // to leave ourselves at a valid insertion point.
544   if (KeepInsertionPoint)
545     EmitBlock(createBasicBlock("throw.cont"));
546 }
547 
548 void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
549   if (!CGM.getLangOpts().CXXExceptions)
550     return;
551 
552   const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
553   if (!FD) {
554     // Check if CapturedDecl is nothrow and create terminate scope for it.
555     if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
556       if (CD->isNothrow())
557         EHStack.pushTerminate();
558     }
559     return;
560   }
561   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
562   if (!Proto)
563     return;
564 
565   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
566   if (isNoexceptExceptionSpec(EST)) {
567     if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
568       // noexcept functions are simple terminate scopes.
569       EHStack.pushTerminate();
570     }
571   } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
572     unsigned NumExceptions = Proto->getNumExceptions();
573     EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
574 
575     for (unsigned I = 0; I != NumExceptions; ++I) {
576       QualType Ty = Proto->getExceptionType(I);
577       QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
578       llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
579                                                         /*ForEH=*/true);
580       Filter->setFilter(I, EHType);
581     }
582   }
583 }
584 
585 /// Emit the dispatch block for a filter scope if necessary.
586 static void emitFilterDispatchBlock(CodeGenFunction &CGF,
587                                     EHFilterScope &filterScope) {
588   llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
589   if (!dispatchBlock) return;
590   if (dispatchBlock->use_empty()) {
591     delete dispatchBlock;
592     return;
593   }
594 
595   CGF.EmitBlockAfterUses(dispatchBlock);
596 
597   // If this isn't a catch-all filter, we need to check whether we got
598   // here because the filter triggered.
599   if (filterScope.getNumFilters()) {
600     // Load the selector value.
601     llvm::Value *selector = CGF.getSelectorFromSlot();
602     llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
603 
604     llvm::Value *zero = CGF.Builder.getInt32(0);
605     llvm::Value *failsFilter =
606         CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
607     CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
608                              CGF.getEHResumeBlock(false));
609 
610     CGF.EmitBlock(unexpectedBB);
611   }
612 
613   // Call __cxa_call_unexpected.  This doesn't need to be an invoke
614   // because __cxa_call_unexpected magically filters exceptions
615   // according to the last landing pad the exception was thrown
616   // into.  Seriously.
617   llvm::Value *exn = CGF.getExceptionFromSlot();
618   CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
619     ->setDoesNotReturn();
620   CGF.Builder.CreateUnreachable();
621 }
622 
623 void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
624   if (!CGM.getLangOpts().CXXExceptions)
625     return;
626 
627   const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
628   if (!FD) {
629     // Check if CapturedDecl is nothrow and pop terminate scope for it.
630     if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
631       if (CD->isNothrow())
632         EHStack.popTerminate();
633     }
634     return;
635   }
636   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
637   if (!Proto)
638     return;
639 
640   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
641   if (isNoexceptExceptionSpec(EST)) {
642     if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
643       EHStack.popTerminate();
644     }
645   } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
646     EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
647     emitFilterDispatchBlock(*this, filterScope);
648     EHStack.popFilter();
649   }
650 }
651 
652 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
653   EnterCXXTryStmt(S);
654   EmitStmt(S.getTryBlock());
655   ExitCXXTryStmt(S);
656 }
657 
658 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
659   unsigned NumHandlers = S.getNumHandlers();
660   EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
661 
662   for (unsigned I = 0; I != NumHandlers; ++I) {
663     const CXXCatchStmt *C = S.getHandler(I);
664 
665     llvm::BasicBlock *Handler = createBasicBlock("catch");
666     if (C->getExceptionDecl()) {
667       // FIXME: Dropping the reference type on the type into makes it
668       // impossible to correctly implement catch-by-reference
669       // semantics for pointers.  Unfortunately, this is what all
670       // existing compilers do, and it's not clear that the standard
671       // personality routine is capable of doing this right.  See C++ DR 388:
672       //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
673       Qualifiers CaughtTypeQuals;
674       QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
675           C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
676 
677       llvm::Constant *TypeInfo = nullptr;
678       if (CaughtType->isObjCObjectPointerType())
679         TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
680       else
681         TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
682       CatchScope->setHandler(I, TypeInfo, Handler);
683     } else {
684       // No exception decl indicates '...', a catch-all.
685       CatchScope->setCatchAllHandler(I, Handler);
686     }
687   }
688 }
689 
690 llvm::BasicBlock *
691 CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
692   // The dispatch block for the end of the scope chain is a block that
693   // just resumes unwinding.
694   if (si == EHStack.stable_end())
695     return getEHResumeBlock(true);
696 
697   // Otherwise, we should look at the actual scope.
698   EHScope &scope = *EHStack.find(si);
699 
700   llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
701   if (!dispatchBlock) {
702     switch (scope.getKind()) {
703     case EHScope::Catch: {
704       // Apply a special case to a single catch-all.
705       EHCatchScope &catchScope = cast<EHCatchScope>(scope);
706       if (catchScope.getNumHandlers() == 1 &&
707           catchScope.getHandler(0).isCatchAll()) {
708         dispatchBlock = catchScope.getHandler(0).Block;
709 
710       // Otherwise, make a dispatch block.
711       } else {
712         dispatchBlock = createBasicBlock("catch.dispatch");
713       }
714       break;
715     }
716 
717     case EHScope::Cleanup:
718       dispatchBlock = createBasicBlock("ehcleanup");
719       break;
720 
721     case EHScope::Filter:
722       dispatchBlock = createBasicBlock("filter.dispatch");
723       break;
724 
725     case EHScope::Terminate:
726       dispatchBlock = getTerminateHandler();
727       break;
728     }
729     scope.setCachedEHDispatchBlock(dispatchBlock);
730   }
731   return dispatchBlock;
732 }
733 
734 /// Check whether this is a non-EH scope, i.e. a scope which doesn't
735 /// affect exception handling.  Currently, the only non-EH scopes are
736 /// normal-only cleanup scopes.
737 static bool isNonEHScope(const EHScope &S) {
738   switch (S.getKind()) {
739   case EHScope::Cleanup:
740     return !cast<EHCleanupScope>(S).isEHCleanup();
741   case EHScope::Filter:
742   case EHScope::Catch:
743   case EHScope::Terminate:
744     return false;
745   }
746 
747   llvm_unreachable("Invalid EHScope Kind!");
748 }
749 
750 llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
751   assert(EHStack.requiresLandingPad());
752   assert(!EHStack.empty());
753 
754   // If exceptions are disabled, there are usually no landingpads. However, when
755   // SEH is enabled, functions using SEH still get landingpads.
756   const LangOptions &LO = CGM.getLangOpts();
757   if (!LO.Exceptions) {
758     if (!LO.Borland && !LO.MicrosoftExt)
759       return nullptr;
760     if (!currentFunctionUsesSEHTry())
761       return nullptr;
762   }
763 
764   // Check the innermost scope for a cached landing pad.  If this is
765   // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
766   llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
767   if (LP) return LP;
768 
769   // Build the landing pad for this scope.
770   LP = EmitLandingPad();
771   assert(LP);
772 
773   // Cache the landing pad on the innermost scope.  If this is a
774   // non-EH scope, cache the landing pad on the enclosing scope, too.
775   for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
776     ir->setCachedLandingPad(LP);
777     if (!isNonEHScope(*ir)) break;
778   }
779 
780   return LP;
781 }
782 
783 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
784   assert(EHStack.requiresLandingPad());
785 
786   EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
787   switch (innermostEHScope.getKind()) {
788   case EHScope::Terminate:
789     return getTerminateLandingPad();
790 
791   case EHScope::Catch:
792   case EHScope::Cleanup:
793   case EHScope::Filter:
794     if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
795       return lpad;
796   }
797 
798   // Save the current IR generation state.
799   CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
800   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
801 
802   const EHPersonality &personality = EHPersonality::get(*this);
803 
804   // Create and configure the landing pad.
805   llvm::BasicBlock *lpad = createBasicBlock("lpad");
806   EmitBlock(lpad);
807 
808   llvm::LandingPadInst *LPadInst =
809     Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
810                              getOpaquePersonalityFn(CGM, personality), 0);
811 
812   llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
813   Builder.CreateStore(LPadExn, getExceptionSlot());
814   llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
815   Builder.CreateStore(LPadSel, getEHSelectorSlot());
816 
817   // Save the exception pointer.  It's safe to use a single exception
818   // pointer per function because EH cleanups can never have nested
819   // try/catches.
820   // Build the landingpad instruction.
821 
822   // Accumulate all the handlers in scope.
823   bool hasCatchAll = false;
824   bool hasCleanup = false;
825   bool hasFilter = false;
826   SmallVector<llvm::Value*, 4> filterTypes;
827   llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
828   for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
829        ++I) {
830 
831     switch (I->getKind()) {
832     case EHScope::Cleanup:
833       // If we have a cleanup, remember that.
834       hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
835       continue;
836 
837     case EHScope::Filter: {
838       assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
839       assert(!hasCatchAll && "EH filter reached after catch-all");
840 
841       // Filter scopes get added to the landingpad in weird ways.
842       EHFilterScope &filter = cast<EHFilterScope>(*I);
843       hasFilter = true;
844 
845       // Add all the filter values.
846       for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
847         filterTypes.push_back(filter.getFilter(i));
848       goto done;
849     }
850 
851     case EHScope::Terminate:
852       // Terminate scopes are basically catch-alls.
853       assert(!hasCatchAll);
854       hasCatchAll = true;
855       goto done;
856 
857     case EHScope::Catch:
858       break;
859     }
860 
861     EHCatchScope &catchScope = cast<EHCatchScope>(*I);
862     for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
863       EHCatchScope::Handler handler = catchScope.getHandler(hi);
864 
865       // If this is a catch-all, register that and abort.
866       if (!handler.Type) {
867         assert(!hasCatchAll);
868         hasCatchAll = true;
869         goto done;
870       }
871 
872       // Check whether we already have a handler for this type.
873       if (catchTypes.insert(handler.Type).second)
874         // If not, add it directly to the landingpad.
875         LPadInst->addClause(handler.Type);
876     }
877   }
878 
879  done:
880   // If we have a catch-all, add null to the landingpad.
881   assert(!(hasCatchAll && hasFilter));
882   if (hasCatchAll) {
883     LPadInst->addClause(getCatchAllValue(*this));
884 
885   // If we have an EH filter, we need to add those handlers in the
886   // right place in the landingpad, which is to say, at the end.
887   } else if (hasFilter) {
888     // Create a filter expression: a constant array indicating which filter
889     // types there are. The personality routine only lands here if the filter
890     // doesn't match.
891     SmallVector<llvm::Constant*, 8> Filters;
892     llvm::ArrayType *AType =
893       llvm::ArrayType::get(!filterTypes.empty() ?
894                              filterTypes[0]->getType() : Int8PtrTy,
895                            filterTypes.size());
896 
897     for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
898       Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
899     llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
900     LPadInst->addClause(FilterArray);
901 
902     // Also check whether we need a cleanup.
903     if (hasCleanup)
904       LPadInst->setCleanup(true);
905 
906   // Otherwise, signal that we at least have cleanups.
907   } else if (hasCleanup) {
908     LPadInst->setCleanup(true);
909   }
910 
911   assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
912          "landingpad instruction has no clauses!");
913 
914   // Tell the backend how to generate the landing pad.
915   Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
916 
917   // Restore the old IR generation state.
918   Builder.restoreIP(savedIP);
919 
920   return lpad;
921 }
922 
923 namespace {
924   /// A cleanup to call __cxa_end_catch.  In many cases, the caught
925   /// exception type lets us state definitively that the thrown exception
926   /// type does not have a destructor.  In particular:
927   ///   - Catch-alls tell us nothing, so we have to conservatively
928   ///     assume that the thrown exception might have a destructor.
929   ///   - Catches by reference behave according to their base types.
930   ///   - Catches of non-record types will only trigger for exceptions
931   ///     of non-record types, which never have destructors.
932   ///   - Catches of record types can trigger for arbitrary subclasses
933   ///     of the caught type, so we have to assume the actual thrown
934   ///     exception type might have a throwing destructor, even if the
935   ///     caught type's destructor is trivial or nothrow.
936   struct CallEndCatch : EHScopeStack::Cleanup {
937     CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
938     bool MightThrow;
939 
940     void Emit(CodeGenFunction &CGF, Flags flags) override {
941       if (!MightThrow) {
942         CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
943         return;
944       }
945 
946       CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
947     }
948   };
949 }
950 
951 /// Emits a call to __cxa_begin_catch and enters a cleanup to call
952 /// __cxa_end_catch.
953 ///
954 /// \param EndMightThrow - true if __cxa_end_catch might throw
955 static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
956                                    llvm::Value *Exn,
957                                    bool EndMightThrow) {
958   llvm::CallInst *call =
959     CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
960 
961   CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
962 
963   return call;
964 }
965 
966 /// A "special initializer" callback for initializing a catch
967 /// parameter during catch initialization.
968 static void InitCatchParam(CodeGenFunction &CGF,
969                            const VarDecl &CatchParam,
970                            llvm::Value *ParamAddr,
971                            SourceLocation Loc) {
972   // Load the exception from where the landing pad saved it.
973   llvm::Value *Exn = CGF.getExceptionFromSlot();
974 
975   CanQualType CatchType =
976     CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
977   llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
978 
979   // If we're catching by reference, we can just cast the object
980   // pointer to the appropriate pointer.
981   if (isa<ReferenceType>(CatchType)) {
982     QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
983     bool EndCatchMightThrow = CaughtType->isRecordType();
984 
985     // __cxa_begin_catch returns the adjusted object pointer.
986     llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
987 
988     // We have no way to tell the personality function that we're
989     // catching by reference, so if we're catching a pointer,
990     // __cxa_begin_catch will actually return that pointer by value.
991     if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
992       QualType PointeeType = PT->getPointeeType();
993 
994       // When catching by reference, generally we should just ignore
995       // this by-value pointer and use the exception object instead.
996       if (!PointeeType->isRecordType()) {
997 
998         // Exn points to the struct _Unwind_Exception header, which
999         // we have to skip past in order to reach the exception data.
1000         unsigned HeaderSize =
1001           CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
1002         AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
1003 
1004       // However, if we're catching a pointer-to-record type that won't
1005       // work, because the personality function might have adjusted
1006       // the pointer.  There's actually no way for us to fully satisfy
1007       // the language/ABI contract here:  we can't use Exn because it
1008       // might have the wrong adjustment, but we can't use the by-value
1009       // pointer because it's off by a level of abstraction.
1010       //
1011       // The current solution is to dump the adjusted pointer into an
1012       // alloca, which breaks language semantics (because changing the
1013       // pointer doesn't change the exception) but at least works.
1014       // The better solution would be to filter out non-exact matches
1015       // and rethrow them, but this is tricky because the rethrow
1016       // really needs to be catchable by other sites at this landing
1017       // pad.  The best solution is to fix the personality function.
1018       } else {
1019         // Pull the pointer for the reference type off.
1020         llvm::Type *PtrTy =
1021           cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1022 
1023         // Create the temporary and write the adjusted pointer into it.
1024         llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1025         llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1026         CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1027 
1028         // Bind the reference to the temporary.
1029         AdjustedExn = ExnPtrTmp;
1030       }
1031     }
1032 
1033     llvm::Value *ExnCast =
1034       CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1035     CGF.Builder.CreateStore(ExnCast, ParamAddr);
1036     return;
1037   }
1038 
1039   // Scalars and complexes.
1040   TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
1041   if (TEK != TEK_Aggregate) {
1042     llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
1043 
1044     // If the catch type is a pointer type, __cxa_begin_catch returns
1045     // the pointer by value.
1046     if (CatchType->hasPointerRepresentation()) {
1047       llvm::Value *CastExn =
1048         CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1049 
1050       switch (CatchType.getQualifiers().getObjCLifetime()) {
1051       case Qualifiers::OCL_Strong:
1052         CastExn = CGF.EmitARCRetainNonBlock(CastExn);
1053         // fallthrough
1054 
1055       case Qualifiers::OCL_None:
1056       case Qualifiers::OCL_ExplicitNone:
1057       case Qualifiers::OCL_Autoreleasing:
1058         CGF.Builder.CreateStore(CastExn, ParamAddr);
1059         return;
1060 
1061       case Qualifiers::OCL_Weak:
1062         CGF.EmitARCInitWeak(ParamAddr, CastExn);
1063         return;
1064       }
1065       llvm_unreachable("bad ownership qualifier!");
1066     }
1067 
1068     // Otherwise, it returns a pointer into the exception object.
1069 
1070     llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1071     llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1072 
1073     LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
1074     LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
1075                                   CGF.getContext().getDeclAlign(&CatchParam));
1076     switch (TEK) {
1077     case TEK_Complex:
1078       CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
1079                              /*init*/ true);
1080       return;
1081     case TEK_Scalar: {
1082       llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
1083       CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
1084       return;
1085     }
1086     case TEK_Aggregate:
1087       llvm_unreachable("evaluation kind filtered out!");
1088     }
1089     llvm_unreachable("bad evaluation kind");
1090   }
1091 
1092   assert(isa<RecordType>(CatchType) && "unexpected catch type!");
1093 
1094   llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1095 
1096   // Check for a copy expression.  If we don't have a copy expression,
1097   // that means a trivial copy is okay.
1098   const Expr *copyExpr = CatchParam.getInit();
1099   if (!copyExpr) {
1100     llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1101     llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1102     CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
1103     return;
1104   }
1105 
1106   // We have to call __cxa_get_exception_ptr to get the adjusted
1107   // pointer before copying.
1108   llvm::CallInst *rawAdjustedExn =
1109     CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
1110 
1111   // Cast that to the appropriate type.
1112   llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1113 
1114   // The copy expression is defined in terms of an OpaqueValueExpr.
1115   // Find it and map it to the adjusted expression.
1116   CodeGenFunction::OpaqueValueMapping
1117     opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1118            CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
1119 
1120   // Call the copy ctor in a terminate scope.
1121   CGF.EHStack.pushTerminate();
1122 
1123   // Perform the copy construction.
1124   CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
1125   CGF.EmitAggExpr(copyExpr,
1126                   AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1127                                         AggValueSlot::IsNotDestructed,
1128                                         AggValueSlot::DoesNotNeedGCBarriers,
1129                                         AggValueSlot::IsNotAliased));
1130 
1131   // Leave the terminate scope.
1132   CGF.EHStack.popTerminate();
1133 
1134   // Undo the opaque value mapping.
1135   opaque.pop();
1136 
1137   // Finally we can call __cxa_begin_catch.
1138   CallBeginCatch(CGF, Exn, true);
1139 }
1140 
1141 /// Begins a catch statement by initializing the catch variable and
1142 /// calling __cxa_begin_catch.
1143 static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
1144   // We have to be very careful with the ordering of cleanups here:
1145   //   C++ [except.throw]p4:
1146   //     The destruction [of the exception temporary] occurs
1147   //     immediately after the destruction of the object declared in
1148   //     the exception-declaration in the handler.
1149   //
1150   // So the precise ordering is:
1151   //   1.  Construct catch variable.
1152   //   2.  __cxa_begin_catch
1153   //   3.  Enter __cxa_end_catch cleanup
1154   //   4.  Enter dtor cleanup
1155   //
1156   // We do this by using a slightly abnormal initialization process.
1157   // Delegation sequence:
1158   //   - ExitCXXTryStmt opens a RunCleanupsScope
1159   //     - EmitAutoVarAlloca creates the variable and debug info
1160   //       - InitCatchParam initializes the variable from the exception
1161   //       - CallBeginCatch calls __cxa_begin_catch
1162   //       - CallBeginCatch enters the __cxa_end_catch cleanup
1163   //     - EmitAutoVarCleanups enters the variable destructor cleanup
1164   //   - EmitCXXTryStmt emits the code for the catch body
1165   //   - EmitCXXTryStmt close the RunCleanupsScope
1166 
1167   VarDecl *CatchParam = S->getExceptionDecl();
1168   if (!CatchParam) {
1169     llvm::Value *Exn = CGF.getExceptionFromSlot();
1170     CallBeginCatch(CGF, Exn, true);
1171     return;
1172   }
1173 
1174   // Emit the local.
1175   CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1176   InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
1177   CGF.EmitAutoVarCleanups(var);
1178 }
1179 
1180 /// Emit the structure of the dispatch block for the given catch scope.
1181 /// It is an invariant that the dispatch block already exists.
1182 static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1183                                    EHCatchScope &catchScope) {
1184   llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1185   assert(dispatchBlock);
1186 
1187   // If there's only a single catch-all, getEHDispatchBlock returned
1188   // that catch-all as the dispatch block.
1189   if (catchScope.getNumHandlers() == 1 &&
1190       catchScope.getHandler(0).isCatchAll()) {
1191     assert(dispatchBlock == catchScope.getHandler(0).Block);
1192     return;
1193   }
1194 
1195   CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1196   CGF.EmitBlockAfterUses(dispatchBlock);
1197 
1198   // Select the right handler.
1199   llvm::Value *llvm_eh_typeid_for =
1200     CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1201 
1202   // Load the selector value.
1203   llvm::Value *selector = CGF.getSelectorFromSlot();
1204 
1205   // Test against each of the exception types we claim to catch.
1206   for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1207     assert(i < e && "ran off end of handlers!");
1208     const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1209 
1210     llvm::Value *typeValue = handler.Type;
1211     assert(typeValue && "fell into catch-all case!");
1212     typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1213 
1214     // Figure out the next block.
1215     bool nextIsEnd;
1216     llvm::BasicBlock *nextBlock;
1217 
1218     // If this is the last handler, we're at the end, and the next
1219     // block is the block for the enclosing EH scope.
1220     if (i + 1 == e) {
1221       nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1222       nextIsEnd = true;
1223 
1224     // If the next handler is a catch-all, we're at the end, and the
1225     // next block is that handler.
1226     } else if (catchScope.getHandler(i+1).isCatchAll()) {
1227       nextBlock = catchScope.getHandler(i+1).Block;
1228       nextIsEnd = true;
1229 
1230     // Otherwise, we're not at the end and we need a new block.
1231     } else {
1232       nextBlock = CGF.createBasicBlock("catch.fallthrough");
1233       nextIsEnd = false;
1234     }
1235 
1236     // Figure out the catch type's index in the LSDA's type table.
1237     llvm::CallInst *typeIndex =
1238       CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1239     typeIndex->setDoesNotThrow();
1240 
1241     llvm::Value *matchesTypeIndex =
1242       CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1243     CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1244 
1245     // If the next handler is a catch-all, we're completely done.
1246     if (nextIsEnd) {
1247       CGF.Builder.restoreIP(savedIP);
1248       return;
1249     }
1250     // Otherwise we need to emit and continue at that block.
1251     CGF.EmitBlock(nextBlock);
1252   }
1253 }
1254 
1255 void CodeGenFunction::popCatchScope() {
1256   EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1257   if (catchScope.hasEHBranches())
1258     emitCatchDispatchBlock(*this, catchScope);
1259   EHStack.popCatch();
1260 }
1261 
1262 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1263   unsigned NumHandlers = S.getNumHandlers();
1264   EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1265   assert(CatchScope.getNumHandlers() == NumHandlers);
1266 
1267   // If the catch was not required, bail out now.
1268   if (!CatchScope.hasEHBranches()) {
1269     CatchScope.clearHandlerBlocks();
1270     EHStack.popCatch();
1271     return;
1272   }
1273 
1274   // Emit the structure of the EH dispatch for this catch.
1275   emitCatchDispatchBlock(*this, CatchScope);
1276 
1277   // Copy the handler blocks off before we pop the EH stack.  Emitting
1278   // the handlers might scribble on this memory.
1279   SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1280   memcpy(Handlers.data(), CatchScope.begin(),
1281          NumHandlers * sizeof(EHCatchScope::Handler));
1282 
1283   EHStack.popCatch();
1284 
1285   // The fall-through block.
1286   llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1287 
1288   // We just emitted the body of the try; jump to the continue block.
1289   if (HaveInsertPoint())
1290     Builder.CreateBr(ContBB);
1291 
1292   // Determine if we need an implicit rethrow for all these catch handlers;
1293   // see the comment below.
1294   bool doImplicitRethrow = false;
1295   if (IsFnTryBlock)
1296     doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1297                         isa<CXXConstructorDecl>(CurCodeDecl);
1298 
1299   // Perversely, we emit the handlers backwards precisely because we
1300   // want them to appear in source order.  In all of these cases, the
1301   // catch block will have exactly one predecessor, which will be a
1302   // particular block in the catch dispatch.  However, in the case of
1303   // a catch-all, one of the dispatch blocks will branch to two
1304   // different handlers, and EmitBlockAfterUses will cause the second
1305   // handler to be moved before the first.
1306   for (unsigned I = NumHandlers; I != 0; --I) {
1307     llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1308     EmitBlockAfterUses(CatchBlock);
1309 
1310     // Catch the exception if this isn't a catch-all.
1311     const CXXCatchStmt *C = S.getHandler(I-1);
1312 
1313     // Enter a cleanup scope, including the catch variable and the
1314     // end-catch.
1315     RunCleanupsScope CatchScope(*this);
1316 
1317     // Initialize the catch variable and set up the cleanups.
1318     BeginCatch(*this, C);
1319 
1320     // Emit the PGO counter increment.
1321     RegionCounter CatchCnt = getPGORegionCounter(C);
1322     CatchCnt.beginRegion(Builder);
1323 
1324     // Perform the body of the catch.
1325     EmitStmt(C->getHandlerBlock());
1326 
1327     // [except.handle]p11:
1328     //   The currently handled exception is rethrown if control
1329     //   reaches the end of a handler of the function-try-block of a
1330     //   constructor or destructor.
1331 
1332     // It is important that we only do this on fallthrough and not on
1333     // return.  Note that it's illegal to put a return in a
1334     // constructor function-try-block's catch handler (p14), so this
1335     // really only applies to destructors.
1336     if (doImplicitRethrow && HaveInsertPoint()) {
1337       CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
1338       Builder.CreateUnreachable();
1339       Builder.ClearInsertionPoint();
1340     }
1341 
1342     // Fall out through the catch cleanups.
1343     CatchScope.ForceCleanup();
1344 
1345     // Branch out of the try.
1346     if (HaveInsertPoint())
1347       Builder.CreateBr(ContBB);
1348   }
1349 
1350   RegionCounter ContCnt = getPGORegionCounter(&S);
1351   EmitBlock(ContBB);
1352   ContCnt.beginRegion(Builder);
1353 }
1354 
1355 namespace {
1356   struct CallEndCatchForFinally : EHScopeStack::Cleanup {
1357     llvm::Value *ForEHVar;
1358     llvm::Value *EndCatchFn;
1359     CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1360       : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1361 
1362     void Emit(CodeGenFunction &CGF, Flags flags) override {
1363       llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1364       llvm::BasicBlock *CleanupContBB =
1365         CGF.createBasicBlock("finally.cleanup.cont");
1366 
1367       llvm::Value *ShouldEndCatch =
1368         CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1369       CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1370       CGF.EmitBlock(EndCatchBB);
1371       CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
1372       CGF.EmitBlock(CleanupContBB);
1373     }
1374   };
1375 
1376   struct PerformFinally : EHScopeStack::Cleanup {
1377     const Stmt *Body;
1378     llvm::Value *ForEHVar;
1379     llvm::Value *EndCatchFn;
1380     llvm::Value *RethrowFn;
1381     llvm::Value *SavedExnVar;
1382 
1383     PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1384                    llvm::Value *EndCatchFn,
1385                    llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1386       : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1387         RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1388 
1389     void Emit(CodeGenFunction &CGF, Flags flags) override {
1390       // Enter a cleanup to call the end-catch function if one was provided.
1391       if (EndCatchFn)
1392         CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1393                                                         ForEHVar, EndCatchFn);
1394 
1395       // Save the current cleanup destination in case there are
1396       // cleanups in the finally block.
1397       llvm::Value *SavedCleanupDest =
1398         CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1399                                "cleanup.dest.saved");
1400 
1401       // Emit the finally block.
1402       CGF.EmitStmt(Body);
1403 
1404       // If the end of the finally is reachable, check whether this was
1405       // for EH.  If so, rethrow.
1406       if (CGF.HaveInsertPoint()) {
1407         llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1408         llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1409 
1410         llvm::Value *ShouldRethrow =
1411           CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1412         CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1413 
1414         CGF.EmitBlock(RethrowBB);
1415         if (SavedExnVar) {
1416           CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1417                                       CGF.Builder.CreateLoad(SavedExnVar));
1418         } else {
1419           CGF.EmitRuntimeCallOrInvoke(RethrowFn);
1420         }
1421         CGF.Builder.CreateUnreachable();
1422 
1423         CGF.EmitBlock(ContBB);
1424 
1425         // Restore the cleanup destination.
1426         CGF.Builder.CreateStore(SavedCleanupDest,
1427                                 CGF.getNormalCleanupDestSlot());
1428       }
1429 
1430       // Leave the end-catch cleanup.  As an optimization, pretend that
1431       // the fallthrough path was inaccessible; we've dynamically proven
1432       // that we're not in the EH case along that path.
1433       if (EndCatchFn) {
1434         CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1435         CGF.PopCleanupBlock();
1436         CGF.Builder.restoreIP(SavedIP);
1437       }
1438 
1439       // Now make sure we actually have an insertion point or the
1440       // cleanup gods will hate us.
1441       CGF.EnsureInsertPoint();
1442     }
1443   };
1444 }
1445 
1446 /// Enters a finally block for an implementation using zero-cost
1447 /// exceptions.  This is mostly general, but hard-codes some
1448 /// language/ABI-specific behavior in the catch-all sections.
1449 void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1450                                          const Stmt *body,
1451                                          llvm::Constant *beginCatchFn,
1452                                          llvm::Constant *endCatchFn,
1453                                          llvm::Constant *rethrowFn) {
1454   assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
1455          "begin/end catch functions not paired");
1456   assert(rethrowFn && "rethrow function is required");
1457 
1458   BeginCatchFn = beginCatchFn;
1459 
1460   // The rethrow function has one of the following two types:
1461   //   void (*)()
1462   //   void (*)(void*)
1463   // In the latter case we need to pass it the exception object.
1464   // But we can't use the exception slot because the @finally might
1465   // have a landing pad (which would overwrite the exception slot).
1466   llvm::FunctionType *rethrowFnTy =
1467     cast<llvm::FunctionType>(
1468       cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1469   SavedExnVar = nullptr;
1470   if (rethrowFnTy->getNumParams())
1471     SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1472 
1473   // A finally block is a statement which must be executed on any edge
1474   // out of a given scope.  Unlike a cleanup, the finally block may
1475   // contain arbitrary control flow leading out of itself.  In
1476   // addition, finally blocks should always be executed, even if there
1477   // are no catch handlers higher on the stack.  Therefore, we
1478   // surround the protected scope with a combination of a normal
1479   // cleanup (to catch attempts to break out of the block via normal
1480   // control flow) and an EH catch-all (semantically "outside" any try
1481   // statement to which the finally block might have been attached).
1482   // The finally block itself is generated in the context of a cleanup
1483   // which conditionally leaves the catch-all.
1484 
1485   // Jump destination for performing the finally block on an exception
1486   // edge.  We'll never actually reach this block, so unreachable is
1487   // fine.
1488   RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1489 
1490   // Whether the finally block is being executed for EH purposes.
1491   ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1492   CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
1493 
1494   // Enter a normal cleanup which will perform the @finally block.
1495   CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1496                                           ForEHVar, endCatchFn,
1497                                           rethrowFn, SavedExnVar);
1498 
1499   // Enter a catch-all scope.
1500   llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1501   EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1502   catchScope->setCatchAllHandler(0, catchBB);
1503 }
1504 
1505 void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1506   // Leave the finally catch-all.
1507   EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1508   llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1509 
1510   CGF.popCatchScope();
1511 
1512   // If there are any references to the catch-all block, emit it.
1513   if (catchBB->use_empty()) {
1514     delete catchBB;
1515   } else {
1516     CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1517     CGF.EmitBlock(catchBB);
1518 
1519     llvm::Value *exn = nullptr;
1520 
1521     // If there's a begin-catch function, call it.
1522     if (BeginCatchFn) {
1523       exn = CGF.getExceptionFromSlot();
1524       CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
1525     }
1526 
1527     // If we need to remember the exception pointer to rethrow later, do so.
1528     if (SavedExnVar) {
1529       if (!exn) exn = CGF.getExceptionFromSlot();
1530       CGF.Builder.CreateStore(exn, SavedExnVar);
1531     }
1532 
1533     // Tell the cleanups in the finally block that we're do this for EH.
1534     CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1535 
1536     // Thread a jump through the finally cleanup.
1537     CGF.EmitBranchThroughCleanup(RethrowDest);
1538 
1539     CGF.Builder.restoreIP(savedIP);
1540   }
1541 
1542   // Finally, leave the @finally cleanup.
1543   CGF.PopCleanupBlock();
1544 }
1545 
1546 /// In a terminate landing pad, should we use __clang__call_terminate
1547 /// or just a naked call to std::terminate?
1548 ///
1549 /// __clang_call_terminate calls __cxa_begin_catch, which then allows
1550 /// std::terminate to usefully report something about the
1551 /// violating exception.
1552 static bool useClangCallTerminate(CodeGenModule &CGM) {
1553   // Only do this for Itanium-family ABIs in C++ mode.
1554   return (CGM.getLangOpts().CPlusPlus &&
1555           CGM.getTarget().getCXXABI().isItaniumFamily());
1556 }
1557 
1558 /// Get or define the following function:
1559 ///   void @__clang_call_terminate(i8* %exn) nounwind noreturn
1560 /// This code is used only in C++.
1561 static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
1562   llvm::FunctionType *fnTy =
1563     llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
1564   llvm::Constant *fnRef =
1565     CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
1566 
1567   llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
1568   if (fn && fn->empty()) {
1569     fn->setDoesNotThrow();
1570     fn->setDoesNotReturn();
1571 
1572     // What we really want is to massively penalize inlining without
1573     // forbidding it completely.  The difference between that and
1574     // 'noinline' is negligible.
1575     fn->addFnAttr(llvm::Attribute::NoInline);
1576 
1577     // Allow this function to be shared across translation units, but
1578     // we don't want it to turn into an exported symbol.
1579     fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
1580     fn->setVisibility(llvm::Function::HiddenVisibility);
1581     if (CGM.supportsCOMDAT())
1582       fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
1583 
1584     // Set up the function.
1585     llvm::BasicBlock *entry =
1586       llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
1587     CGBuilderTy builder(entry);
1588 
1589     // Pull the exception pointer out of the parameter list.
1590     llvm::Value *exn = &*fn->arg_begin();
1591 
1592     // Call __cxa_begin_catch(exn).
1593     llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
1594     catchCall->setDoesNotThrow();
1595     catchCall->setCallingConv(CGM.getRuntimeCC());
1596 
1597     // Call std::terminate().
1598     llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM));
1599     termCall->setDoesNotThrow();
1600     termCall->setDoesNotReturn();
1601     termCall->setCallingConv(CGM.getRuntimeCC());
1602 
1603     // std::terminate cannot return.
1604     builder.CreateUnreachable();
1605   }
1606 
1607   return fnRef;
1608 }
1609 
1610 llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1611   if (TerminateLandingPad)
1612     return TerminateLandingPad;
1613 
1614   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1615 
1616   // This will get inserted at the end of the function.
1617   TerminateLandingPad = createBasicBlock("terminate.lpad");
1618   Builder.SetInsertPoint(TerminateLandingPad);
1619 
1620   // Tell the backend that this is a landing pad.
1621   const EHPersonality &Personality = EHPersonality::get(*this);
1622   llvm::LandingPadInst *LPadInst =
1623     Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
1624                              getOpaquePersonalityFn(CGM, Personality), 0);
1625   LPadInst->addClause(getCatchAllValue(*this));
1626 
1627   llvm::CallInst *terminateCall;
1628   if (useClangCallTerminate(CGM)) {
1629     // Extract out the exception pointer.
1630     llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0);
1631     terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1632   } else {
1633     terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1634   }
1635   terminateCall->setDoesNotReturn();
1636   Builder.CreateUnreachable();
1637 
1638   // Restore the saved insertion state.
1639   Builder.restoreIP(SavedIP);
1640 
1641   return TerminateLandingPad;
1642 }
1643 
1644 llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1645   if (TerminateHandler)
1646     return TerminateHandler;
1647 
1648   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1649 
1650   // Set up the terminate handler.  This block is inserted at the very
1651   // end of the function by FinishFunction.
1652   TerminateHandler = createBasicBlock("terminate.handler");
1653   Builder.SetInsertPoint(TerminateHandler);
1654   llvm::CallInst *terminateCall;
1655   if (useClangCallTerminate(CGM)) {
1656     // Load the exception pointer.
1657     llvm::Value *exn = getExceptionFromSlot();
1658     terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1659   } else {
1660     terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1661   }
1662   terminateCall->setDoesNotReturn();
1663   Builder.CreateUnreachable();
1664 
1665   // Restore the saved insertion state.
1666   Builder.restoreIP(SavedIP);
1667 
1668   return TerminateHandler;
1669 }
1670 
1671 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1672   if (EHResumeBlock) return EHResumeBlock;
1673 
1674   CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1675 
1676   // We emit a jump to a notional label at the outermost unwind state.
1677   EHResumeBlock = createBasicBlock("eh.resume");
1678   Builder.SetInsertPoint(EHResumeBlock);
1679 
1680   const EHPersonality &Personality = EHPersonality::get(*this);
1681 
1682   // This can always be a call because we necessarily didn't find
1683   // anything on the EH stack which needs our help.
1684   const char *RethrowName = Personality.CatchallRethrowFn;
1685   if (RethrowName != nullptr && !isCleanup) {
1686     EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1687                     getExceptionFromSlot())->setDoesNotReturn();
1688     Builder.CreateUnreachable();
1689     Builder.restoreIP(SavedIP);
1690     return EHResumeBlock;
1691   }
1692 
1693   // Recreate the landingpad's return value for the 'resume' instruction.
1694   llvm::Value *Exn = getExceptionFromSlot();
1695   llvm::Value *Sel = getSelectorFromSlot();
1696 
1697   llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1698                                                Sel->getType(), nullptr);
1699   llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1700   LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1701   LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1702 
1703   Builder.CreateResume(LPadVal);
1704   Builder.restoreIP(SavedIP);
1705   return EHResumeBlock;
1706 }
1707 
1708 void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1709   // FIXME: Implement SEH on other architectures.
1710   const llvm::Triple &T = CGM.getTarget().getTriple();
1711   if (T.getArch() != llvm::Triple::x86_64 ||
1712       !T.isKnownWindowsMSVCEnvironment()) {
1713     ErrorUnsupported(&S, "__try statement");
1714     return;
1715   }
1716 
1717   SEHFinallyInfo FI;
1718   EnterSEHTryStmt(S, FI);
1719   {
1720     JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1721 
1722     SEHTryEpilogueStack.push_back(&TryExit);
1723     EmitStmt(S.getTryBlock());
1724     SEHTryEpilogueStack.pop_back();
1725 
1726     if (!TryExit.getBlock()->use_empty())
1727       EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1728     else
1729       delete TryExit.getBlock();
1730   }
1731   ExitSEHTryStmt(S, FI);
1732 }
1733 
1734 namespace {
1735 struct PerformSEHFinally : EHScopeStack::Cleanup  {
1736   CodeGenFunction::SEHFinallyInfo *FI;
1737   PerformSEHFinally(CodeGenFunction::SEHFinallyInfo *FI) : FI(FI) {}
1738 
1739   void Emit(CodeGenFunction &CGF, Flags F) override {
1740     // Cleanups are emitted at most twice: once for normal control flow and once
1741     // for exception control flow. Branch into the finally block, and remember
1742     // the continuation block so we can branch out later.
1743     if (!FI->FinallyBB) {
1744       FI->FinallyBB = CGF.createBasicBlock("__finally");
1745       FI->FinallyBB->insertInto(CGF.CurFn);
1746       FI->FinallyBB->moveAfter(CGF.Builder.GetInsertBlock());
1747     }
1748 
1749     // Set the termination status and branch in.
1750     CGF.Builder.CreateStore(
1751         llvm::ConstantInt::get(CGF.Int8Ty, F.isForEHCleanup()),
1752         CGF.getAbnormalTerminationSlot());
1753     CGF.Builder.CreateBr(FI->FinallyBB);
1754 
1755     // Create a continuation block for normal or exceptional control.
1756     if (F.isForEHCleanup()) {
1757       assert(!FI->ResumeBB && "double emission for EH");
1758       FI->ResumeBB = CGF.createBasicBlock("__finally.resume");
1759       CGF.EmitBlock(FI->ResumeBB);
1760     } else {
1761       assert(F.isForNormalCleanup() && !FI->ContBB && "double normal emission");
1762       FI->ContBB = CGF.createBasicBlock("__finally.cont");
1763       CGF.EmitBlock(FI->ContBB);
1764       // Try to keep source order.
1765       FI->ContBB->moveAfter(FI->FinallyBB);
1766     }
1767   }
1768 };
1769 }
1770 
1771 /// Create a stub filter function that will ultimately hold the code of the
1772 /// filter expression. The EH preparation passes in LLVM will outline the code
1773 /// from the main function body into this stub.
1774 llvm::Function *
1775 CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1776                                            const SEHExceptStmt &Except) {
1777   const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1778   llvm::Function *ParentFn = ParentCGF.CurFn;
1779 
1780   Expr *FilterExpr = Except.getFilterExpr();
1781 
1782   // Get the mangled function name.
1783   SmallString<128> Name;
1784   {
1785     llvm::raw_svector_ostream OS(Name);
1786     const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1787     assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1788     CGM.getCXXABI().getMangleContext().mangleSEHFilterExpression(Parent, OS);
1789   }
1790 
1791   // Arrange a function with the declaration:
1792   // int filt(EXCEPTION_POINTERS *exception_pointers, void *frame_pointer)
1793   QualType RetTy = getContext().IntTy;
1794   FunctionArgList Args;
1795   SEHPointersDecl = ImplicitParamDecl::Create(
1796       getContext(), nullptr, FilterExpr->getLocStart(),
1797       &getContext().Idents.get("exception_pointers"), getContext().VoidPtrTy);
1798   Args.push_back(SEHPointersDecl);
1799   Args.push_back(ImplicitParamDecl::Create(
1800       getContext(), nullptr, FilterExpr->getLocStart(),
1801       &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1802   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1803       RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
1804   llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1805   llvm::Function *Fn = llvm::Function::Create(FnTy, ParentFn->getLinkage(),
1806                                               Name.str(), &CGM.getModule());
1807   // The filter is either in the same comdat as the function, or it's internal.
1808   if (llvm::Comdat *C = ParentFn->getComdat()) {
1809     Fn->setComdat(C);
1810   } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
1811     // FIXME: Unreachable with Rafael's changes?
1812     llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1813     ParentFn->setComdat(C);
1814     Fn->setComdat(C);
1815   } else {
1816     Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1817   }
1818 
1819   StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1820                 FilterExpr->getLocStart(), FilterExpr->getLocStart());
1821 
1822   EmitSEHExceptionCodeSave();
1823 
1824   // Insert dummy allocas for every local variable in scope. We'll initialize
1825   // them and prune the unused ones after we find out which ones were
1826   // referenced.
1827   for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
1828     const Decl *VD = DeclPtrs.first;
1829     llvm::Value *Ptr = DeclPtrs.second;
1830     auto *ValTy = cast<llvm::PointerType>(Ptr->getType())->getElementType();
1831     LocalDeclMap[VD] = CreateTempAlloca(ValTy, Ptr->getName() + ".filt");
1832   }
1833 
1834   // Emit the original filter expression, convert to i32, and return.
1835   llvm::Value *R = EmitScalarExpr(FilterExpr);
1836   R = Builder.CreateIntCast(R, CGM.IntTy,
1837                             FilterExpr->getType()->isSignedIntegerType());
1838   Builder.CreateStore(R, ReturnValue);
1839 
1840   FinishFunction(FilterExpr->getLocEnd());
1841 
1842   for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
1843     const Decl *VD = DeclPtrs.first;
1844     auto *Alloca = cast<llvm::AllocaInst>(LocalDeclMap[VD]);
1845     if (Alloca->hasNUses(0)) {
1846       Alloca->eraseFromParent();
1847       continue;
1848     }
1849     ErrorUnsupported(FilterExpr,
1850                      "SEH filter expression local variable capture");
1851   }
1852 
1853   return Fn;
1854 }
1855 
1856 void CodeGenFunction::EmitSEHExceptionCodeSave() {
1857   // Save the exception code in the exception slot to unify exception access in
1858   // the filter function and the landing pad.
1859   // struct EXCEPTION_POINTERS {
1860   //   EXCEPTION_RECORD *ExceptionRecord;
1861   //   CONTEXT *ContextRecord;
1862   // };
1863   // void *exn.slot =
1864   //     (void *)(uintptr_t)exception_pointers->ExceptionRecord->ExceptionCode;
1865   llvm::Value *Ptrs = Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1866   llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1867   llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
1868   Ptrs = Builder.CreateBitCast(Ptrs, PtrsTy->getPointerTo());
1869   llvm::Value *Rec = Builder.CreateStructGEP(Ptrs, 0);
1870   Rec = Builder.CreateLoad(Rec);
1871   llvm::Value *Code = Builder.CreateLoad(Rec);
1872   Code = Builder.CreateZExt(Code, CGM.IntPtrTy);
1873   // FIXME: Change landing pads to produce {i32, i32} and make the exception
1874   // slot an i32.
1875   Code = Builder.CreateIntToPtr(Code, CGM.VoidPtrTy);
1876   Builder.CreateStore(Code, getExceptionSlot());
1877 }
1878 
1879 llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1880   // Sema should diagnose calling this builtin outside of a filter context, but
1881   // don't crash if we screw up.
1882   if (!SEHPointersDecl)
1883     return llvm::UndefValue::get(Int8PtrTy);
1884   return Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1885 }
1886 
1887 llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
1888   // If we're in a landing pad or filter function, the exception slot contains
1889   // the code.
1890   assert(ExceptionSlot);
1891   llvm::Value *Code =
1892       Builder.CreatePtrToInt(getExceptionFromSlot(), CGM.IntPtrTy);
1893   return Builder.CreateTrunc(Code, CGM.Int32Ty);
1894 }
1895 
1896 llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
1897   // Load from the abnormal termination slot. It will be uninitialized outside
1898   // of __finally blocks, which we should warn or error on.
1899   llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot());
1900   return Builder.CreateZExt(IsEH, Int32Ty);
1901 }
1902 
1903 void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
1904   if (S.getFinallyHandler()) {
1905     // Push a cleanup for __finally blocks.
1906     EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, &FI);
1907     return;
1908   }
1909 
1910   // Otherwise, we must have an __except block.
1911   SEHExceptStmt *Except = S.getExceptHandler();
1912   assert(Except);
1913   EHCatchScope *CatchScope = EHStack.pushCatch(1);
1914 
1915   // If the filter is known to evaluate to 1, then we can use the clause "catch
1916   // i8* null".
1917   llvm::Constant *C =
1918       CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1919   if (C && C->isOneValue()) {
1920     CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1921     return;
1922   }
1923 
1924   // In general, we have to emit an outlined filter function. Use the function
1925   // in place of the RTTI typeinfo global that C++ EH uses.
1926   CodeGenFunction FilterCGF(CGM, /*suppressNewContext=*/true);
1927   llvm::Function *FilterFunc =
1928       FilterCGF.GenerateSEHFilterFunction(*this, *Except);
1929   llvm::Constant *OpaqueFunc =
1930       llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1931   CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except"));
1932 }
1933 
1934 void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
1935   // Just pop the cleanup if it's a __finally block.
1936   if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
1937     PopCleanupBlock();
1938     assert(FI.ContBB && "did not emit normal cleanup");
1939 
1940     // Emit the code into FinallyBB.
1941     CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1942     Builder.SetInsertPoint(FI.FinallyBB);
1943     EmitStmt(Finally->getBlock());
1944 
1945     if (HaveInsertPoint()) {
1946       if (FI.ResumeBB) {
1947         llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot(),
1948                                                "abnormal.termination");
1949         IsEH = Builder.CreateICmpEQ(IsEH, llvm::ConstantInt::get(Int8Ty, 0));
1950         Builder.CreateCondBr(IsEH, FI.ContBB, FI.ResumeBB);
1951       } else {
1952         // There was nothing exceptional in the try body, so we only have normal
1953         // control flow.
1954         Builder.CreateBr(FI.ContBB);
1955       }
1956     }
1957 
1958     Builder.restoreIP(SavedIP);
1959 
1960     return;
1961   }
1962 
1963   // Otherwise, we must have an __except block.
1964   const SEHExceptStmt *Except = S.getExceptHandler();
1965   assert(Except && "__try must have __finally xor __except");
1966   EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1967 
1968   // Don't emit the __except block if the __try block lacked invokes.
1969   // TODO: Model unwind edges from instructions, either with iload / istore or
1970   // a try body function.
1971   if (!CatchScope.hasEHBranches()) {
1972     CatchScope.clearHandlerBlocks();
1973     EHStack.popCatch();
1974     return;
1975   }
1976 
1977   // The fall-through block.
1978   llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1979 
1980   // We just emitted the body of the __try; jump to the continue block.
1981   if (HaveInsertPoint())
1982     Builder.CreateBr(ContBB);
1983 
1984   // Check if our filter function returned true.
1985   emitCatchDispatchBlock(*this, CatchScope);
1986 
1987   // Grab the block before we pop the handler.
1988   llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1989   EHStack.popCatch();
1990 
1991   EmitBlockAfterUses(ExceptBB);
1992 
1993   // Emit the __except body.
1994   EmitStmt(Except->getBlock());
1995 
1996   if (HaveInsertPoint())
1997     Builder.CreateBr(ContBB);
1998 
1999   EmitBlock(ContBB);
2000 }
2001 
2002 void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
2003   // If this code is reachable then emit a stop point (if generating
2004   // debug info). We have to do this ourselves because we are on the
2005   // "simple" statement path.
2006   if (HaveInsertPoint())
2007     EmitStopPoint(&S);
2008 
2009   assert(!SEHTryEpilogueStack.empty() &&
2010          "sema should have rejected this __leave");
2011   EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
2012 }
2013