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