CGException.cpp revision 8370c58b9295b32bee50443fe3ac43a47a2047e8
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
18#include "CodeGenFunction.h"
19using namespace clang;
20using namespace CodeGen;
21
22static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
23  // void *__cxa_allocate_exception(size_t thrown_size);
24  const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
25  std::vector<const llvm::Type*> Args(1, SizeTy);
26
27  const llvm::FunctionType *FTy =
28  llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
29                          Args, false);
30
31  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
32}
33
34static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
35  // void __cxa_free_exception(void *thrown_exception);
36  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
37  std::vector<const llvm::Type*> Args(1, Int8PtrTy);
38
39  const llvm::FunctionType *FTy =
40  llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
41                          Args, false);
42
43  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
44}
45
46static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
47  // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
48  //                  void (*dest) (void *));
49
50  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
51  std::vector<const llvm::Type*> Args(3, Int8PtrTy);
52
53  const llvm::FunctionType *FTy =
54    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
55                            Args, false);
56
57  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
58}
59
60static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
61  // void __cxa_rethrow();
62
63  const llvm::FunctionType *FTy =
64    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
65
66  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
67}
68
69static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
70  // void* __cxa_begin_catch();
71
72  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
73  std::vector<const llvm::Type*> Args(1, Int8PtrTy);
74
75  const llvm::FunctionType *FTy =
76    llvm::FunctionType::get(Int8PtrTy, Args, false);
77
78  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
79}
80
81static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
82  // void __cxa_end_catch();
83
84  const llvm::FunctionType *FTy =
85    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
86
87  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
88}
89
90static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
91  // void __cxa_call_unexepcted(void *thrown_exception);
92
93  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
94  std::vector<const llvm::Type*> Args(1, Int8PtrTy);
95
96  const llvm::FunctionType *FTy =
97    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
98                            Args, false);
99
100  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
101}
102
103// FIXME: Eventually this will all go into the backend.  Set from the target for
104// now.
105static int using_sjlj_exceptions = 0;
106
107static llvm::Constant *getUnwindResumeOrRethrowFn(CodeGenFunction &CGF) {
108  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
109  std::vector<const llvm::Type*> Args(1, Int8PtrTy);
110
111  const llvm::FunctionType *FTy =
112    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), Args,
113                            false);
114
115  if (using_sjlj_exceptions)
116    return CGF.CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
117  return CGF.CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
118}
119
120static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
121  // void __terminate();
122
123  const llvm::FunctionType *FTy =
124    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
125
126  return CGF.CGM.CreateRuntimeFunction(FTy, "_ZSt9terminatev");
127}
128
129// CopyObject - Utility to copy an object.  Calls copy constructor as necessary.
130// DestPtr is casted to the right type.
131static void CopyObject(CodeGenFunction &CGF, const Expr *E,
132                       llvm::Value *DestPtr, llvm::Value *ExceptionPtrPtr) {
133  QualType ObjectType = E->getType();
134
135  // Store the throw exception in the exception object.
136  if (!CGF.hasAggregateLLVMType(ObjectType)) {
137    llvm::Value *Value = CGF.EmitScalarExpr(E);
138    const llvm::Type *ValuePtrTy = Value->getType()->getPointerTo();
139
140    CGF.Builder.CreateStore(Value,
141                            CGF.Builder.CreateBitCast(DestPtr, ValuePtrTy));
142  } else {
143    const llvm::Type *Ty = CGF.ConvertType(ObjectType)->getPointerTo();
144    const CXXRecordDecl *RD =
145      cast<CXXRecordDecl>(ObjectType->getAs<RecordType>()->getDecl());
146
147    llvm::Value *This = CGF.Builder.CreateBitCast(DestPtr, Ty);
148    if (RD->hasTrivialCopyConstructor()) {
149      CGF.EmitAggExpr(E, This, false);
150    } else if (CXXConstructorDecl *CopyCtor
151               = RD->getCopyConstructor(CGF.getContext(), 0)) {
152      llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
153      if (CGF.Exceptions) {
154        CodeGenFunction::EHCleanupBlock Cleanup(CGF);
155        llvm::Constant *FreeExceptionFn = getFreeExceptionFn(CGF);
156
157        // Load the exception pointer.
158        llvm::Value *ExceptionPtr = CGF.Builder.CreateLoad(ExceptionPtrPtr);
159        CGF.Builder.CreateCall(FreeExceptionFn, ExceptionPtr);
160      }
161
162      llvm::Value *Src = CGF.EmitLValue(E).getAddress();
163      CGF.setInvokeDest(PrevLandingPad);
164
165      llvm::BasicBlock *TerminateHandler = CGF.getTerminateHandler();
166      PrevLandingPad = CGF.getInvokeDest();
167      CGF.setInvokeDest(TerminateHandler);
168
169      // Stolen from EmitClassAggrMemberwiseCopy
170      llvm::Value *Callee = CGF.CGM.GetAddrOfCXXConstructor(CopyCtor,
171                                                            Ctor_Complete);
172      CallArgList CallArgs;
173      CallArgs.push_back(std::make_pair(RValue::get(This),
174                                      CopyCtor->getThisType(CGF.getContext())));
175
176      // Push the Src ptr.
177      CallArgs.push_back(std::make_pair(RValue::get(Src),
178                                        CopyCtor->getParamDecl(0)->getType()));
179      QualType ResultType =
180        CopyCtor->getType()->getAs<FunctionType>()->getResultType();
181      CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
182                   Callee, CallArgs, CopyCtor);
183      CGF.setInvokeDest(PrevLandingPad);
184    } else
185      llvm::llvm_unreachable("uncopyable object");
186  }
187}
188
189// CopyObject - Utility to copy an object.  Calls copy constructor as necessary.
190// N is casted to the right type.
191static void CopyObject(CodeGenFunction &CGF, QualType ObjectType,
192                       bool WasPointer, llvm::Value *E, llvm::Value *N) {
193  // Store the throw exception in the exception object.
194  if (WasPointer || !CGF.hasAggregateLLVMType(ObjectType)) {
195    llvm::Value *Value = E;
196    if (!WasPointer)
197      Value = CGF.Builder.CreateLoad(Value);
198    const llvm::Type *ValuePtrTy = Value->getType()->getPointerTo(0);
199    CGF.Builder.CreateStore(Value, CGF.Builder.CreateBitCast(N, ValuePtrTy));
200  } else {
201    const llvm::Type *Ty = CGF.ConvertType(ObjectType)->getPointerTo(0);
202    const CXXRecordDecl *RD;
203    RD = cast<CXXRecordDecl>(ObjectType->getAs<RecordType>()->getDecl());
204    llvm::Value *This = CGF.Builder.CreateBitCast(N, Ty);
205    if (RD->hasTrivialCopyConstructor()) {
206      CGF.EmitAggregateCopy(This, E, ObjectType);
207    } else if (CXXConstructorDecl *CopyCtor
208               = RD->getCopyConstructor(CGF.getContext(), 0)) {
209      llvm::Value *Src = E;
210
211      // Stolen from EmitClassAggrMemberwiseCopy
212      llvm::Value *Callee = CGF.CGM.GetAddrOfCXXConstructor(CopyCtor,
213                                                            Ctor_Complete);
214      CallArgList CallArgs;
215      CallArgs.push_back(std::make_pair(RValue::get(This),
216                                      CopyCtor->getThisType(CGF.getContext())));
217
218      // Push the Src ptr.
219      CallArgs.push_back(std::make_pair(RValue::get(Src),
220                                        CopyCtor->getParamDecl(0)->getType()));
221      QualType ResultType =
222        CopyCtor->getType()->getAs<FunctionType>()->getResultType();
223      CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
224                   Callee, CallArgs, CopyCtor);
225    } else
226      llvm::llvm_unreachable("uncopyable object");
227  }
228}
229
230void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
231  if (!E->getSubExpr()) {
232    if (getInvokeDest()) {
233      llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
234      Builder.CreateInvoke(getReThrowFn(*this), Cont, getInvokeDest())
235        ->setDoesNotReturn();
236      EmitBlock(Cont);
237    } else
238      Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
239    Builder.CreateUnreachable();
240
241    // Clear the insertion point to indicate we are in unreachable code.
242    Builder.ClearInsertionPoint();
243    return;
244  }
245
246  QualType ThrowType = E->getSubExpr()->getType();
247
248  // Now allocate the exception object.
249  const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
250  uint64_t TypeSize = getContext().getTypeSize(ThrowType) / 8;
251
252  llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
253  llvm::Value *ExceptionPtr =
254    Builder.CreateCall(AllocExceptionFn,
255                       llvm::ConstantInt::get(SizeTy, TypeSize),
256                       "exception");
257
258  llvm::Value *ExceptionPtrPtr =
259    CreateTempAlloca(ExceptionPtr->getType(), "exception.ptr");
260  Builder.CreateStore(ExceptionPtr, ExceptionPtrPtr);
261
262
263  CopyObject(*this, E->getSubExpr(), ExceptionPtr, ExceptionPtrPtr);
264
265  // Now throw the exception.
266  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
267  llvm::Constant *TypeInfo = CGM.GenerateRTTI(ThrowType);
268  llvm::Constant *Dtor = llvm::Constant::getNullValue(Int8PtrTy);
269
270  if (getInvokeDest()) {
271    llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
272    llvm::InvokeInst *ThrowCall =
273      Builder.CreateInvoke3(getThrowFn(*this), Cont, getInvokeDest(),
274                            ExceptionPtr, TypeInfo, Dtor);
275    ThrowCall->setDoesNotReturn();
276    EmitBlock(Cont);
277  } else {
278    llvm::CallInst *ThrowCall =
279      Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
280    ThrowCall->setDoesNotReturn();
281  }
282  Builder.CreateUnreachable();
283
284  // Clear the insertion point to indicate we are in unreachable code.
285  Builder.ClearInsertionPoint();
286
287  // FIXME: For now, emit a dummy basic block because expr emitters in generally
288  // are not ready to handle emitting expressions at unreachable points.
289  EnsureInsertPoint();
290}
291
292void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
293  const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
294  if (FD == 0)
295    return;
296  const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
297  if (Proto == 0)
298    return;
299
300  assert(!Proto->hasAnyExceptionSpec() && "function with parameter pack");
301
302  if (!Proto->hasExceptionSpec())
303    return;
304
305  llvm::Constant *Personality =
306    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getInt32Ty
307                                                      (VMContext),
308                                                      true),
309                              "__gxx_personality_v0");
310  Personality = llvm::ConstantExpr::getBitCast(Personality, PtrToInt8Ty);
311  llvm::Value *llvm_eh_exception =
312    CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
313  llvm::Value *llvm_eh_selector =
314    CGM.getIntrinsic(llvm::Intrinsic::eh_selector);
315  const llvm::IntegerType *Int8Ty;
316  const llvm::PointerType *PtrToInt8Ty;
317  Int8Ty = llvm::Type::getInt8Ty(VMContext);
318  // C string type.  Used in lots of places.
319  PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
320  llvm::Constant *Null = llvm::ConstantPointerNull::get(PtrToInt8Ty);
321  llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
322
323  llvm::BasicBlock *PrevLandingPad = getInvokeDest();
324  llvm::BasicBlock *EHSpecHandler = createBasicBlock("ehspec.handler");
325  llvm::BasicBlock *Match = createBasicBlock("match");
326  llvm::BasicBlock *Unwind = 0;
327
328  assert(PrevLandingPad == 0 && "EHSpec has invoke context");
329
330  llvm::BasicBlock *Cont = createBasicBlock("cont");
331
332  EmitBranchThroughCleanup(Cont);
333
334  // Emit the statements in the try {} block
335  setInvokeDest(EHSpecHandler);
336
337  EmitBlock(EHSpecHandler);
338  // Exception object
339  llvm::Value *Exc = Builder.CreateCall(llvm_eh_exception, "exc");
340  llvm::Value *RethrowPtr = CreateTempAlloca(Exc->getType(), "_rethrow");
341
342  SelectorArgs.push_back(Exc);
343  SelectorArgs.push_back(Personality);
344  SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
345                                                Proto->getNumExceptions()+1));
346
347  for (unsigned i = 0; i < Proto->getNumExceptions(); ++i) {
348    QualType Ty = Proto->getExceptionType(i);
349    llvm::Value *EHType
350      = CGM.GenerateRTTI(Ty.getNonReferenceType());
351    SelectorArgs.push_back(EHType);
352  }
353  if (Proto->getNumExceptions())
354    SelectorArgs.push_back(Null);
355
356  // Find which handler was matched.
357  llvm::Value *Selector
358    = Builder.CreateCall(llvm_eh_selector, SelectorArgs.begin(),
359                         SelectorArgs.end(), "selector");
360  if (Proto->getNumExceptions()) {
361    Unwind = createBasicBlock("Unwind");
362
363    Builder.CreateStore(Exc, RethrowPtr);
364    Builder.CreateCondBr(Builder.CreateICmpSLT(Selector,
365                                               llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
366                                                                      0)),
367                         Match, Unwind);
368
369    EmitBlock(Match);
370  }
371  Builder.CreateCall(getUnexpectedFn(*this), Exc)->setDoesNotReturn();
372  Builder.CreateUnreachable();
373
374  if (Proto->getNumExceptions()) {
375    EmitBlock(Unwind);
376    Builder.CreateCall(getUnwindResumeOrRethrowFn(*this),
377                       Builder.CreateLoad(RethrowPtr));
378    Builder.CreateUnreachable();
379  }
380
381  EmitBlock(Cont);
382}
383
384void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
385  const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
386  if (FD == 0)
387    return;
388  const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
389  if (Proto == 0)
390    return;
391
392  if (!Proto->hasExceptionSpec())
393    return;
394
395  setInvokeDest(0);
396}
397
398void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
399  // Pointer to the personality function
400  llvm::Constant *Personality =
401    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getInt32Ty
402                                                      (VMContext),
403                                                      true),
404                              "__gxx_personality_v0");
405  Personality = llvm::ConstantExpr::getBitCast(Personality, PtrToInt8Ty);
406  llvm::Value *llvm_eh_exception =
407    CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
408  llvm::Value *llvm_eh_selector =
409    CGM.getIntrinsic(llvm::Intrinsic::eh_selector);
410
411  llvm::BasicBlock *PrevLandingPad = getInvokeDest();
412  llvm::BasicBlock *TryHandler = createBasicBlock("try.handler");
413  llvm::BasicBlock *FinallyBlock = createBasicBlock("finally");
414  llvm::BasicBlock *FinallyRethrow = createBasicBlock("finally.throw");
415  llvm::BasicBlock *FinallyEnd = createBasicBlock("finally.end");
416
417  // Push an EH context entry, used for handling rethrows.
418  PushCleanupBlock(FinallyBlock);
419
420  // Emit the statements in the try {} block
421  setInvokeDest(TryHandler);
422
423  // FIXME: We should not have to do this here.  The AST should have the member
424  // initializers under the CXXTryStmt's TryBlock.
425  if (OuterTryBlock == &S) {
426    GlobalDecl GD = CurGD;
427    const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
428
429    if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
430      size_t OldCleanupStackSize = CleanupEntries.size();
431      EmitCtorPrologue(CD, CurGD.getCtorType());
432      EmitStmt(S.getTryBlock());
433
434      // If any of the member initializers are temporaries bound to references
435      // make sure to emit their destructors.
436      EmitCleanupBlocks(OldCleanupStackSize);
437    } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
438      llvm::BasicBlock *DtorEpilogue  = createBasicBlock("dtor.epilogue");
439      PushCleanupBlock(DtorEpilogue);
440
441      EmitStmt(S.getTryBlock());
442
443      CleanupBlockInfo Info = PopCleanupBlock();
444
445      assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
446      EmitBlock(DtorEpilogue);
447      EmitDtorEpilogue(DD, GD.getDtorType());
448
449      if (Info.SwitchBlock)
450        EmitBlock(Info.SwitchBlock);
451      if (Info.EndBlock)
452        EmitBlock(Info.EndBlock);
453    } else
454      EmitStmt(S.getTryBlock());
455  } else
456    EmitStmt(S.getTryBlock());
457
458  // Jump to end if there is no exception
459  EmitBranchThroughCleanup(FinallyEnd);
460
461  llvm::BasicBlock *TerminateHandler = getTerminateHandler();
462
463  // Emit the handlers
464  EmitBlock(TryHandler);
465
466  const llvm::IntegerType *Int8Ty;
467  const llvm::PointerType *PtrToInt8Ty;
468  Int8Ty = llvm::Type::getInt8Ty(VMContext);
469  // C string type.  Used in lots of places.
470  PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
471  llvm::Constant *Null = llvm::ConstantPointerNull::get(PtrToInt8Ty);
472  llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
473  llvm::Value *llvm_eh_typeid_for =
474    CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
475  // Exception object
476  llvm::Value *Exc = Builder.CreateCall(llvm_eh_exception, "exc");
477  llvm::Value *RethrowPtr = CreateTempAlloca(Exc->getType(), "_rethrow");
478
479  llvm::SmallVector<llvm::Value*, 8> Args;
480  Args.clear();
481  SelectorArgs.push_back(Exc);
482  SelectorArgs.push_back(Personality);
483
484  bool HasCatchAll = false;
485  for (unsigned i = 0; i<S.getNumHandlers(); ++i) {
486    const CXXCatchStmt *C = S.getHandler(i);
487    VarDecl *CatchParam = C->getExceptionDecl();
488    if (CatchParam) {
489      llvm::Value *EHType
490        = CGM.GenerateRTTI(C->getCaughtType().getNonReferenceType());
491      SelectorArgs.push_back(EHType);
492    } else {
493      // null indicates catch all
494      SelectorArgs.push_back(Null);
495      HasCatchAll = true;
496    }
497  }
498
499  // We use a cleanup unless there was already a catch all.
500  if (!HasCatchAll) {
501    SelectorArgs.push_back(Null);
502  }
503
504  // Find which handler was matched.
505  llvm::Value *Selector
506    = Builder.CreateCall(llvm_eh_selector, SelectorArgs.begin(),
507                         SelectorArgs.end(), "selector");
508  for (unsigned i = 0; i<S.getNumHandlers(); ++i) {
509    const CXXCatchStmt *C = S.getHandler(i);
510    VarDecl *CatchParam = C->getExceptionDecl();
511    Stmt *CatchBody = C->getHandlerBlock();
512
513    llvm::BasicBlock *Next = 0;
514
515    if (SelectorArgs[i+2] != Null) {
516      llvm::BasicBlock *Match = createBasicBlock("match");
517      Next = createBasicBlock("catch.next");
518      const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
519      llvm::Value *Id
520        = Builder.CreateCall(llvm_eh_typeid_for,
521                             Builder.CreateBitCast(SelectorArgs[i+2],
522                                                   Int8PtrTy));
523      Builder.CreateCondBr(Builder.CreateICmpEQ(Selector, Id),
524                           Match, Next);
525      EmitBlock(Match);
526    }
527
528    llvm::BasicBlock *MatchEnd = createBasicBlock("match.end");
529    llvm::BasicBlock *MatchHandler = createBasicBlock("match.handler");
530
531    PushCleanupBlock(MatchEnd);
532    setInvokeDest(MatchHandler);
533
534    llvm::Value *ExcObject = Builder.CreateCall(getBeginCatchFn(*this), Exc);
535
536    {
537      CleanupScope CatchScope(*this);
538      // Bind the catch parameter if it exists.
539      if (CatchParam) {
540        QualType CatchType = CatchParam->getType().getNonReferenceType();
541        setInvokeDest(TerminateHandler);
542        bool WasPointer = true;
543        if (!CatchType.getTypePtr()->isPointerType()) {
544          if (!isa<ReferenceType>(CatchParam->getType()))
545            WasPointer = false;
546          CatchType = getContext().getPointerType(CatchType);
547        }
548        ExcObject = Builder.CreateBitCast(ExcObject, ConvertType(CatchType));
549        EmitLocalBlockVarDecl(*CatchParam);
550        // FIXME: we need to do this sooner so that the EH region for the
551        // cleanup doesn't start until after the ctor completes, use a decl
552        // init?
553        CopyObject(*this, CatchParam->getType().getNonReferenceType(),
554                   WasPointer, ExcObject, GetAddrOfLocalVar(CatchParam));
555        setInvokeDest(MatchHandler);
556      }
557
558      EmitStmt(CatchBody);
559    }
560
561    EmitBranchThroughCleanup(FinallyEnd);
562
563    EmitBlock(MatchHandler);
564
565    llvm::Value *Exc = Builder.CreateCall(llvm_eh_exception, "exc");
566    // We are required to emit this call to satisfy LLVM, even
567    // though we don't use the result.
568    Args.clear();
569    Args.push_back(Exc);
570    Args.push_back(Personality);
571    Args.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
572                                          0));
573    Builder.CreateCall(llvm_eh_selector, Args.begin(), Args.end());
574    Builder.CreateStore(Exc, RethrowPtr);
575    EmitBranchThroughCleanup(FinallyRethrow);
576
577    CodeGenFunction::CleanupBlockInfo Info = PopCleanupBlock();
578
579    EmitBlock(MatchEnd);
580
581    llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
582    Builder.CreateInvoke(getEndCatchFn(*this),
583                         Cont, TerminateHandler,
584                         Args.begin(), Args.begin());
585    EmitBlock(Cont);
586    if (Info.SwitchBlock)
587      EmitBlock(Info.SwitchBlock);
588    if (Info.EndBlock)
589      EmitBlock(Info.EndBlock);
590
591    Exc = Builder.CreateCall(llvm_eh_exception, "exc");
592    Builder.CreateStore(Exc, RethrowPtr);
593    EmitBranchThroughCleanup(FinallyRethrow);
594
595    if (Next)
596      EmitBlock(Next);
597  }
598  if (!HasCatchAll) {
599    Builder.CreateStore(Exc, RethrowPtr);
600    EmitBranchThroughCleanup(FinallyRethrow);
601  }
602
603  CodeGenFunction::CleanupBlockInfo Info = PopCleanupBlock();
604
605  setInvokeDest(PrevLandingPad);
606
607  EmitBlock(FinallyBlock);
608
609  if (Info.SwitchBlock)
610    EmitBlock(Info.SwitchBlock);
611  if (Info.EndBlock)
612    EmitBlock(Info.EndBlock);
613
614  // Branch around the rethrow code.
615  EmitBranch(FinallyEnd);
616
617  EmitBlock(FinallyRethrow);
618  // FIXME: Eventually we can chain the handlers together and just do a call
619  // here.
620  if (getInvokeDest()) {
621    llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
622    Builder.CreateInvoke(getUnwindResumeOrRethrowFn(*this), Cont,
623                         getInvokeDest(),
624                         Builder.CreateLoad(RethrowPtr));
625    EmitBlock(Cont);
626  } else
627    Builder.CreateCall(getUnwindResumeOrRethrowFn(*this),
628                       Builder.CreateLoad(RethrowPtr));
629
630  Builder.CreateUnreachable();
631
632  EmitBlock(FinallyEnd);
633}
634
635CodeGenFunction::EHCleanupBlock::~EHCleanupBlock() {
636  llvm::BasicBlock *Cont1 = CGF.createBasicBlock("cont");
637  CGF.EmitBranch(Cont1);
638  CGF.setInvokeDest(PreviousInvokeDest);
639
640
641  CGF.EmitBlock(CleanupHandler);
642
643  llvm::Constant *Personality =
644    CGF.CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getInt32Ty
645                                                          (CGF.VMContext),
646                                                          true),
647                                  "__gxx_personality_v0");
648  Personality = llvm::ConstantExpr::getBitCast(Personality, CGF.PtrToInt8Ty);
649  llvm::Value *llvm_eh_exception =
650    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
651  llvm::Value *llvm_eh_selector =
652    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector);
653
654  llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
655  const llvm::IntegerType *Int8Ty;
656  const llvm::PointerType *PtrToInt8Ty;
657  Int8Ty = llvm::Type::getInt8Ty(CGF.VMContext);
658  // C string type.  Used in lots of places.
659  PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
660  llvm::Constant *Null = llvm::ConstantPointerNull::get(PtrToInt8Ty);
661  llvm::SmallVector<llvm::Value*, 8> Args;
662  Args.clear();
663  Args.push_back(Exc);
664  Args.push_back(Personality);
665  Args.push_back(Null);
666  CGF.Builder.CreateCall(llvm_eh_selector, Args.begin(), Args.end());
667
668  CGF.EmitBlock(CleanupEntryBB);
669
670  CGF.EmitBlock(Cont1);
671
672  if (CGF.getInvokeDest()) {
673    llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
674    CGF.Builder.CreateInvoke(getUnwindResumeOrRethrowFn(CGF), Cont,
675                             CGF.getInvokeDest(), Exc);
676    CGF.EmitBlock(Cont);
677  } else
678    CGF.Builder.CreateCall(getUnwindResumeOrRethrowFn(CGF), Exc);
679
680  CGF.Builder.CreateUnreachable();
681
682  CGF.EmitBlock(Cont);
683  if (CGF.Exceptions)
684    CGF.setInvokeDest(CleanupHandler);
685}
686
687llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
688  if (TerminateHandler)
689    return TerminateHandler;
690
691  llvm::BasicBlock *Cont = 0;
692
693  if (HaveInsertPoint()) {
694    Cont = createBasicBlock("cont");
695    EmitBranch(Cont);
696  }
697
698  llvm::Constant *Personality =
699    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getInt32Ty
700                                                      (VMContext),
701                                                      true),
702                              "__gxx_personality_v0");
703  Personality = llvm::ConstantExpr::getBitCast(Personality, PtrToInt8Ty);
704  llvm::Value *llvm_eh_exception =
705    CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
706  llvm::Value *llvm_eh_selector =
707    CGM.getIntrinsic(llvm::Intrinsic::eh_selector);
708
709  // Set up terminate handler
710  TerminateHandler = createBasicBlock("terminate.handler");
711  EmitBlock(TerminateHandler);
712  llvm::Value *Exc = Builder.CreateCall(llvm_eh_exception, "exc");
713  // We are required to emit this call to satisfy LLVM, even
714  // though we don't use the result.
715  llvm::SmallVector<llvm::Value*, 8> Args;
716  Args.push_back(Exc);
717  Args.push_back(Personality);
718  Args.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
719                                        1));
720  Builder.CreateCall(llvm_eh_selector, Args.begin(), Args.end());
721  llvm::CallInst *TerminateCall =
722    Builder.CreateCall(getTerminateFn(*this));
723  TerminateCall->setDoesNotReturn();
724  TerminateCall->setDoesNotThrow();
725  Builder.CreateUnreachable();
726
727  // Clear the insertion point to indicate we are in unreachable code.
728  Builder.ClearInsertionPoint();
729
730  if (Cont)
731    EmitBlock(Cont);
732
733  return TerminateHandler;
734}
735