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