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