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