1198893Srdivacky//===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===// 2198893Srdivacky// 3198893Srdivacky// The LLVM Compiler Infrastructure 4198893Srdivacky// 5198893Srdivacky// This file is distributed under the University of Illinois Open Source 6198893Srdivacky// License. See LICENSE.TXT for details. 7198893Srdivacky// 8198893Srdivacky//===----------------------------------------------------------------------===// 9198893Srdivacky// 10198893Srdivacky// This contains code dealing with C++ exception related code generation. 11198893Srdivacky// 12198893Srdivacky//===----------------------------------------------------------------------===// 13198893Srdivacky 14234353Sdim#include "CodeGenFunction.h" 15234353Sdim#include "CGCleanup.h" 16234353Sdim#include "CGObjCRuntime.h" 17234353Sdim#include "TargetInfo.h" 18199990Srdivacky#include "clang/AST/StmtCXX.h" 19249423Sdim#include "clang/AST/StmtObjC.h" 20249423Sdim#include "llvm/IR/Intrinsics.h" 21210299Sed#include "llvm/Support/CallSite.h" 22199990Srdivacky 23198893Srdivackyusing namespace clang; 24198893Srdivackyusing namespace CodeGen; 25198893Srdivacky 26249423Sdimstatic llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) { 27198893Srdivacky // void *__cxa_allocate_exception(size_t thrown_size); 28221345Sdim 29226633Sdim llvm::FunctionType *FTy = 30249423Sdim llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false); 31200583Srdivacky 32249423Sdim return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception"); 33198893Srdivacky} 34198893Srdivacky 35249423Sdimstatic llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) { 36200583Srdivacky // void __cxa_free_exception(void *thrown_exception); 37221345Sdim 38226633Sdim llvm::FunctionType *FTy = 39249423Sdim llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 40200583Srdivacky 41249423Sdim return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception"); 42200583Srdivacky} 43200583Srdivacky 44249423Sdimstatic llvm::Constant *getThrowFn(CodeGenModule &CGM) { 45200583Srdivacky // void __cxa_throw(void *thrown_exception, std::type_info *tinfo, 46200583Srdivacky // void (*dest) (void *)); 47198893Srdivacky 48249423Sdim llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy }; 49226633Sdim llvm::FunctionType *FTy = 50249423Sdim llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false); 51200583Srdivacky 52249423Sdim return CGM.CreateRuntimeFunction(FTy, "__cxa_throw"); 53198893Srdivacky} 54198893Srdivacky 55249423Sdimstatic llvm::Constant *getReThrowFn(CodeGenModule &CGM) { 56200583Srdivacky // void __cxa_rethrow(); 57199990Srdivacky 58226633Sdim llvm::FunctionType *FTy = 59249423Sdim llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false); 60200583Srdivacky 61249423Sdim return CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow"); 62199990Srdivacky} 63199990Srdivacky 64249423Sdimstatic llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) { 65210299Sed // void *__cxa_get_exception_ptr(void*); 66221345Sdim 67226633Sdim llvm::FunctionType *FTy = 68249423Sdim llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 69210299Sed 70249423Sdim return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr"); 71210299Sed} 72210299Sed 73249423Sdimstatic llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) { 74210299Sed // void *__cxa_begin_catch(void*); 75199990Srdivacky 76226633Sdim llvm::FunctionType *FTy = 77249423Sdim llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 78200583Srdivacky 79249423Sdim return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch"); 80199990Srdivacky} 81199990Srdivacky 82249423Sdimstatic llvm::Constant *getEndCatchFn(CodeGenModule &CGM) { 83200583Srdivacky // void __cxa_end_catch(); 84199990Srdivacky 85226633Sdim llvm::FunctionType *FTy = 86249423Sdim llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false); 87200583Srdivacky 88249423Sdim return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch"); 89199990Srdivacky} 90199990Srdivacky 91249423Sdimstatic llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) { 92200583Srdivacky // void __cxa_call_unexepcted(void *thrown_exception); 93200583Srdivacky 94226633Sdim llvm::FunctionType *FTy = 95249423Sdim llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 96200583Srdivacky 97249423Sdim return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected"); 98200583Srdivacky} 99200583Srdivacky 100223017Sdimllvm::Constant *CodeGenFunction::getUnwindResumeFn() { 101226633Sdim llvm::FunctionType *FTy = 102226633Sdim llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false); 103223017Sdim 104234353Sdim if (CGM.getLangOpts().SjLjExceptions) 105223017Sdim return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume"); 106223017Sdim return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume"); 107223017Sdim} 108223017Sdim 109208600Srdivackyllvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() { 110226633Sdim llvm::FunctionType *FTy = 111226633Sdim llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false); 112200583Srdivacky 113234353Sdim if (CGM.getLangOpts().SjLjExceptions) 114212904Sdim return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow"); 115208600Srdivacky return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow"); 116199990Srdivacky} 117199990Srdivacky 118249423Sdimstatic llvm::Constant *getTerminateFn(CodeGenModule &CGM) { 119200583Srdivacky // void __terminate(); 120200583Srdivacky 121226633Sdim llvm::FunctionType *FTy = 122249423Sdim llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false); 123200583Srdivacky 124226633Sdim StringRef name; 125224145Sdim 126224145Sdim // In C++, use std::terminate(). 127249423Sdim if (CGM.getLangOpts().CPlusPlus) 128224145Sdim name = "_ZSt9terminatev"; // FIXME: mangling! 129249423Sdim else if (CGM.getLangOpts().ObjC1 && 130249423Sdim CGM.getLangOpts().ObjCRuntime.hasTerminate()) 131224145Sdim name = "objc_terminate"; 132224145Sdim else 133224145Sdim name = "abort"; 134249423Sdim return CGM.CreateRuntimeFunction(FTy, name); 135200583Srdivacky} 136200583Srdivacky 137249423Sdimstatic llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM, 138226633Sdim StringRef Name) { 139226633Sdim llvm::FunctionType *FTy = 140249423Sdim llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 141212904Sdim 142249423Sdim return CGM.CreateRuntimeFunction(FTy, Name); 143210299Sed} 144210299Sed 145234353Sdimnamespace { 146234353Sdim /// The exceptions personality for a function. 147234353Sdim struct EHPersonality { 148234353Sdim const char *PersonalityFn; 149212904Sdim 150234353Sdim // If this is non-null, this personality requires a non-standard 151234353Sdim // function for rethrowing an exception after a catchall cleanup. 152234353Sdim // This function must have prototype void(void*). 153234353Sdim const char *CatchallRethrowFn; 154234353Sdim 155234353Sdim static const EHPersonality &get(const LangOptions &Lang); 156234353Sdim static const EHPersonality GNU_C; 157234353Sdim static const EHPersonality GNU_C_SJLJ; 158234353Sdim static const EHPersonality GNU_ObjC; 159249423Sdim static const EHPersonality GNUstep_ObjC; 160234353Sdim static const EHPersonality GNU_ObjCXX; 161234353Sdim static const EHPersonality NeXT_ObjC; 162234353Sdim static const EHPersonality GNU_CPlusPlus; 163234353Sdim static const EHPersonality GNU_CPlusPlus_SJLJ; 164234353Sdim }; 165234353Sdim} 166234353Sdim 167234353Sdimconst EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", 0 }; 168234353Sdimconst EHPersonality EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", 0 }; 169234353Sdimconst EHPersonality EHPersonality::NeXT_ObjC = { "__objc_personality_v0", 0 }; 170234353Sdimconst EHPersonality EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", 0}; 171234353Sdimconst EHPersonality 172234353SdimEHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", 0 }; 173234353Sdimconst EHPersonality 174234353SdimEHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"}; 175234353Sdimconst EHPersonality 176234353SdimEHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", 0 }; 177249423Sdimconst EHPersonality 178249423SdimEHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", 0 }; 179234353Sdim 180212904Sdimstatic const EHPersonality &getCPersonality(const LangOptions &L) { 181218893Sdim if (L.SjLjExceptions) 182218893Sdim return EHPersonality::GNU_C_SJLJ; 183212904Sdim return EHPersonality::GNU_C; 184212904Sdim} 185212904Sdim 186212904Sdimstatic const EHPersonality &getObjCPersonality(const LangOptions &L) { 187239462Sdim switch (L.ObjCRuntime.getKind()) { 188239462Sdim case ObjCRuntime::FragileMacOSX: 189239462Sdim return getCPersonality(L); 190239462Sdim case ObjCRuntime::MacOSX: 191239462Sdim case ObjCRuntime::iOS: 192239462Sdim return EHPersonality::NeXT_ObjC; 193239462Sdim case ObjCRuntime::GNUstep: 194249423Sdim if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7)) 195249423Sdim return EHPersonality::GNUstep_ObjC; 196249423Sdim // fallthrough 197239462Sdim case ObjCRuntime::GCC: 198239462Sdim case ObjCRuntime::ObjFW: 199212904Sdim return EHPersonality::GNU_ObjC; 200208600Srdivacky } 201239462Sdim llvm_unreachable("bad runtime kind"); 202210299Sed} 203208600Srdivacky 204212904Sdimstatic const EHPersonality &getCXXPersonality(const LangOptions &L) { 205212904Sdim if (L.SjLjExceptions) 206212904Sdim return EHPersonality::GNU_CPlusPlus_SJLJ; 207210299Sed else 208212904Sdim return EHPersonality::GNU_CPlusPlus; 209210299Sed} 210210299Sed 211210299Sed/// Determines the personality function to use when both C++ 212210299Sed/// and Objective-C exceptions are being caught. 213212904Sdimstatic const EHPersonality &getObjCXXPersonality(const LangOptions &L) { 214239462Sdim switch (L.ObjCRuntime.getKind()) { 215210299Sed // The ObjC personality defers to the C++ personality for non-ObjC 216210299Sed // handlers. Unlike the C++ case, we use the same personality 217210299Sed // function on targets using (backend-driven) SJLJ EH. 218239462Sdim case ObjCRuntime::MacOSX: 219239462Sdim case ObjCRuntime::iOS: 220239462Sdim return EHPersonality::NeXT_ObjC; 221210299Sed 222239462Sdim // In the fragile ABI, just use C++ exception handling and hope 223239462Sdim // they're not doing crazy exception mixing. 224239462Sdim case ObjCRuntime::FragileMacOSX: 225239462Sdim return getCXXPersonality(L); 226210299Sed 227239462Sdim // The GCC runtime's personality function inherently doesn't support 228212904Sdim // mixed EH. Use the C++ personality just to avoid returning null. 229239462Sdim case ObjCRuntime::GCC: 230239462Sdim case ObjCRuntime::ObjFW: // XXX: this will change soon 231239462Sdim return EHPersonality::GNU_ObjC; 232239462Sdim case ObjCRuntime::GNUstep: 233239462Sdim return EHPersonality::GNU_ObjCXX; 234239462Sdim } 235239462Sdim llvm_unreachable("bad runtime kind"); 236210299Sed} 237210299Sed 238212904Sdimconst EHPersonality &EHPersonality::get(const LangOptions &L) { 239212904Sdim if (L.CPlusPlus && L.ObjC1) 240212904Sdim return getObjCXXPersonality(L); 241212904Sdim else if (L.CPlusPlus) 242212904Sdim return getCXXPersonality(L); 243212904Sdim else if (L.ObjC1) 244212904Sdim return getObjCPersonality(L); 245210299Sed else 246212904Sdim return getCPersonality(L); 247212904Sdim} 248210299Sed 249218893Sdimstatic llvm::Constant *getPersonalityFn(CodeGenModule &CGM, 250212904Sdim const EHPersonality &Personality) { 251212904Sdim llvm::Constant *Fn = 252234353Sdim CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true), 253234353Sdim Personality.PersonalityFn); 254218893Sdim return Fn; 255208600Srdivacky} 256208600Srdivacky 257218893Sdimstatic llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM, 258218893Sdim const EHPersonality &Personality) { 259218893Sdim llvm::Constant *Fn = getPersonalityFn(CGM, Personality); 260218893Sdim return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy); 261218893Sdim} 262218893Sdim 263218893Sdim/// Check whether a personality function could reasonably be swapped 264218893Sdim/// for a C++ personality function. 265218893Sdimstatic bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) { 266218893Sdim for (llvm::Constant::use_iterator 267218893Sdim I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) { 268218893Sdim llvm::User *User = *I; 269218893Sdim 270218893Sdim // Conditionally white-list bitcasts. 271218893Sdim if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) { 272218893Sdim if (CE->getOpcode() != llvm::Instruction::BitCast) return false; 273218893Sdim if (!PersonalityHasOnlyCXXUses(CE)) 274218893Sdim return false; 275218893Sdim continue; 276218893Sdim } 277218893Sdim 278226633Sdim // Otherwise, it has to be a landingpad instruction. 279226633Sdim llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(User); 280226633Sdim if (!LPI) return false; 281218893Sdim 282226633Sdim for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) { 283218893Sdim // Look for something that would've been returned by the ObjC 284218893Sdim // runtime's GetEHType() method. 285226633Sdim llvm::Value *Val = LPI->getClause(I)->stripPointerCasts(); 286226633Sdim if (LPI->isCatch(I)) { 287226633Sdim // Check if the catch value has the ObjC prefix. 288226633Sdim if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val)) 289226633Sdim // ObjC EH selector entries are always global variables with 290226633Sdim // names starting like this. 291226633Sdim if (GV->getName().startswith("OBJC_EHTYPE")) 292226633Sdim return false; 293226633Sdim } else { 294226633Sdim // Check if any of the filter values have the ObjC prefix. 295226633Sdim llvm::Constant *CVal = cast<llvm::Constant>(Val); 296226633Sdim for (llvm::User::op_iterator 297226633Sdim II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) { 298226633Sdim if (llvm::GlobalVariable *GV = 299226633Sdim cast<llvm::GlobalVariable>((*II)->stripPointerCasts())) 300226633Sdim // ObjC EH selector entries are always global variables with 301226633Sdim // names starting like this. 302226633Sdim if (GV->getName().startswith("OBJC_EHTYPE")) 303226633Sdim return false; 304226633Sdim } 305226633Sdim } 306218893Sdim } 307218893Sdim } 308218893Sdim 309218893Sdim return true; 310218893Sdim} 311218893Sdim 312218893Sdim/// Try to use the C++ personality function in ObjC++. Not doing this 313218893Sdim/// can cause some incompatibilities with gcc, which is more 314218893Sdim/// aggressive about only using the ObjC++ personality in a function 315218893Sdim/// when it really needs it. 316218893Sdimvoid CodeGenModule::SimplifyPersonality() { 317218893Sdim // If we're not in ObjC++ -fexceptions, there's nothing to do. 318234353Sdim if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions) 319218893Sdim return; 320218893Sdim 321243830Sdim // Both the problem this endeavors to fix and the way the logic 322243830Sdim // above works is specific to the NeXT runtime. 323243830Sdim if (!LangOpts.ObjCRuntime.isNeXTFamily()) 324243830Sdim return; 325243830Sdim 326234353Sdim const EHPersonality &ObjCXX = EHPersonality::get(LangOpts); 327234353Sdim const EHPersonality &CXX = getCXXPersonality(LangOpts); 328234353Sdim if (&ObjCXX == &CXX) 329218893Sdim return; 330218893Sdim 331234353Sdim assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 && 332234353Sdim "Different EHPersonalities using the same personality function."); 333218893Sdim 334234353Sdim llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn); 335234353Sdim 336218893Sdim // Nothing to do if it's unused. 337218893Sdim if (!Fn || Fn->use_empty()) return; 338218893Sdim 339218893Sdim // Can't do the optimization if it has non-C++ uses. 340218893Sdim if (!PersonalityHasOnlyCXXUses(Fn)) return; 341218893Sdim 342218893Sdim // Create the C++ personality function and kill off the old 343218893Sdim // function. 344218893Sdim llvm::Constant *CXXFn = getPersonalityFn(*this, CXX); 345218893Sdim 346218893Sdim // This can happen if the user is screwing with us. 347218893Sdim if (Fn->getType() != CXXFn->getType()) return; 348218893Sdim 349218893Sdim Fn->replaceAllUsesWith(CXXFn); 350218893Sdim Fn->eraseFromParent(); 351218893Sdim} 352218893Sdim 353210299Sed/// Returns the value to inject into a selector to indicate the 354210299Sed/// presence of a catch-all. 355210299Sedstatic llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) { 356210299Sed // Possibly we should use @llvm.eh.catch.all.value here. 357218893Sdim return llvm::ConstantPointerNull::get(CGF.Int8PtrTy); 358210299Sed} 359210299Sed 360210299Sednamespace { 361210299Sed /// A cleanup to free the exception object if its initialization 362210299Sed /// throws. 363224145Sdim struct FreeException : EHScopeStack::Cleanup { 364224145Sdim llvm::Value *exn; 365224145Sdim FreeException(llvm::Value *exn) : exn(exn) {} 366224145Sdim void Emit(CodeGenFunction &CGF, Flags flags) { 367249423Sdim CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn); 368210299Sed } 369210299Sed }; 370210299Sed} 371210299Sed 372207619Srdivacky// Emits an exception expression into the given location. This 373207619Srdivacky// differs from EmitAnyExprToMem only in that, if a final copy-ctor 374207619Srdivacky// call is required, an exception within that copy ctor causes 375207619Srdivacky// std::terminate to be invoked. 376218893Sdimstatic void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e, 377218893Sdim llvm::Value *addr) { 378210299Sed // Make sure the exception object is cleaned up if there's an 379210299Sed // exception during initialization. 380218893Sdim CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr); 381218893Sdim EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin(); 382201361Srdivacky 383207619Srdivacky // __cxa_allocate_exception returns a void*; we need to cast this 384207619Srdivacky // to the appropriate type for the object. 385226633Sdim llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo(); 386218893Sdim llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty); 387200583Srdivacky 388207619Srdivacky // FIXME: this isn't quite right! If there's a final unelided call 389207619Srdivacky // to a copy constructor, then according to [except.terminate]p1 we 390207619Srdivacky // must call std::terminate() if that constructor throws, because 391207619Srdivacky // technically that copy occurs after the exception expression is 392207619Srdivacky // evaluated but before the exception is caught. But the best way 393207619Srdivacky // to handle that is to teach EmitAggExpr to do the final copy 394207619Srdivacky // differently if it can't be elided. 395224145Sdim CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(), 396224145Sdim /*IsInit*/ true); 397201361Srdivacky 398218893Sdim // Deactivate the cleanup block. 399234353Sdim CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr)); 400199990Srdivacky} 401199990Srdivacky 402210299Sedllvm::Value *CodeGenFunction::getExceptionSlot() { 403223017Sdim if (!ExceptionSlot) 404223017Sdim ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot"); 405210299Sed return ExceptionSlot; 406199990Srdivacky} 407199990Srdivacky 408223017Sdimllvm::Value *CodeGenFunction::getEHSelectorSlot() { 409223017Sdim if (!EHSelectorSlot) 410223017Sdim EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot"); 411223017Sdim return EHSelectorSlot; 412223017Sdim} 413223017Sdim 414226633Sdimllvm::Value *CodeGenFunction::getExceptionFromSlot() { 415226633Sdim return Builder.CreateLoad(getExceptionSlot(), "exn"); 416226633Sdim} 417226633Sdim 418226633Sdimllvm::Value *CodeGenFunction::getSelectorFromSlot() { 419226633Sdim return Builder.CreateLoad(getEHSelectorSlot(), "sel"); 420226633Sdim} 421226633Sdim 422251662Sdimvoid CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E, 423251662Sdim bool KeepInsertionPoint) { 424198893Srdivacky if (!E->getSubExpr()) { 425249423Sdim EmitNoreturnRuntimeCallOrInvoke(getReThrowFn(CGM), 426249423Sdim ArrayRef<llvm::Value*>()); 427199990Srdivacky 428218893Sdim // throw is an expression, and the expression emitters expect us 429218893Sdim // to leave ourselves at a valid insertion point. 430251662Sdim if (KeepInsertionPoint) 431251662Sdim EmitBlock(createBasicBlock("throw.cont")); 432218893Sdim 433198893Srdivacky return; 434198893Srdivacky } 435200583Srdivacky 436198893Srdivacky QualType ThrowType = E->getSubExpr()->getType(); 437200583Srdivacky 438249423Sdim if (ThrowType->isObjCObjectPointerType()) { 439249423Sdim const Stmt *ThrowStmt = E->getSubExpr(); 440249423Sdim const ObjCAtThrowStmt S(E->getExprLoc(), 441249423Sdim const_cast<Stmt *>(ThrowStmt)); 442249423Sdim CGM.getObjCRuntime().EmitThrowStmt(*this, S, false); 443249423Sdim // This will clear insertion point which was not cleared in 444249423Sdim // call to EmitThrowStmt. 445251662Sdim if (KeepInsertionPoint) 446251662Sdim EmitBlock(createBasicBlock("throw.cont")); 447249423Sdim return; 448249423Sdim } 449249423Sdim 450198893Srdivacky // Now allocate the exception object. 451226633Sdim llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 452207619Srdivacky uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity(); 453200583Srdivacky 454249423Sdim llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM); 455210299Sed llvm::CallInst *ExceptionPtr = 456249423Sdim EmitNounwindRuntimeCall(AllocExceptionFn, 457249423Sdim llvm::ConstantInt::get(SizeTy, TypeSize), 458249423Sdim "exception"); 459200583Srdivacky 460207619Srdivacky EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr); 461198893Srdivacky 462198893Srdivacky // Now throw the exception. 463218893Sdim llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, 464218893Sdim /*ForEH=*/true); 465200583Srdivacky 466207619Srdivacky // The address of the destructor. If the exception type has a 467207619Srdivacky // trivial destructor (or isn't a record), we just pass null. 468207619Srdivacky llvm::Constant *Dtor = 0; 469207619Srdivacky if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) { 470207619Srdivacky CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl()); 471207619Srdivacky if (!Record->hasTrivialDestructor()) { 472210299Sed CXXDestructorDecl *DtorD = Record->getDestructor(); 473207619Srdivacky Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete); 474207619Srdivacky Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy); 475207619Srdivacky } 476207619Srdivacky } 477207619Srdivacky if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy); 478207619Srdivacky 479249423Sdim llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor }; 480249423Sdim EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args); 481200583Srdivacky 482218893Sdim // throw is an expression, and the expression emitters expect us 483218893Sdim // to leave ourselves at a valid insertion point. 484251662Sdim if (KeepInsertionPoint) 485251662Sdim EmitBlock(createBasicBlock("throw.cont")); 486198893Srdivacky} 487199990Srdivacky 488200583Srdivackyvoid CodeGenFunction::EmitStartEHSpec(const Decl *D) { 489234353Sdim if (!CGM.getLangOpts().CXXExceptions) 490203955Srdivacky return; 491203955Srdivacky 492200583Srdivacky const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D); 493200583Srdivacky if (FD == 0) 494200583Srdivacky return; 495200583Srdivacky const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>(); 496200583Srdivacky if (Proto == 0) 497200583Srdivacky return; 498200583Srdivacky 499221345Sdim ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 500221345Sdim if (isNoexceptExceptionSpec(EST)) { 501221345Sdim if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) { 502221345Sdim // noexcept functions are simple terminate scopes. 503221345Sdim EHStack.pushTerminate(); 504221345Sdim } 505221345Sdim } else if (EST == EST_Dynamic || EST == EST_DynamicNone) { 506221345Sdim unsigned NumExceptions = Proto->getNumExceptions(); 507221345Sdim EHFilterScope *Filter = EHStack.pushFilter(NumExceptions); 508200583Srdivacky 509221345Sdim for (unsigned I = 0; I != NumExceptions; ++I) { 510221345Sdim QualType Ty = Proto->getExceptionType(I); 511221345Sdim QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType(); 512221345Sdim llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType, 513221345Sdim /*ForEH=*/true); 514221345Sdim Filter->setFilter(I, EHType); 515221345Sdim } 516200583Srdivacky } 517200583Srdivacky} 518200583Srdivacky 519226633Sdim/// Emit the dispatch block for a filter scope if necessary. 520226633Sdimstatic void emitFilterDispatchBlock(CodeGenFunction &CGF, 521226633Sdim EHFilterScope &filterScope) { 522226633Sdim llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock(); 523226633Sdim if (!dispatchBlock) return; 524226633Sdim if (dispatchBlock->use_empty()) { 525226633Sdim delete dispatchBlock; 526226633Sdim return; 527226633Sdim } 528226633Sdim 529226633Sdim CGF.EmitBlockAfterUses(dispatchBlock); 530226633Sdim 531226633Sdim // If this isn't a catch-all filter, we need to check whether we got 532226633Sdim // here because the filter triggered. 533226633Sdim if (filterScope.getNumFilters()) { 534226633Sdim // Load the selector value. 535226633Sdim llvm::Value *selector = CGF.getSelectorFromSlot(); 536226633Sdim llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected"); 537226633Sdim 538226633Sdim llvm::Value *zero = CGF.Builder.getInt32(0); 539226633Sdim llvm::Value *failsFilter = 540226633Sdim CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails"); 541243830Sdim CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock(false)); 542226633Sdim 543226633Sdim CGF.EmitBlock(unexpectedBB); 544226633Sdim } 545226633Sdim 546226633Sdim // Call __cxa_call_unexpected. This doesn't need to be an invoke 547226633Sdim // because __cxa_call_unexpected magically filters exceptions 548226633Sdim // according to the last landing pad the exception was thrown 549226633Sdim // into. Seriously. 550226633Sdim llvm::Value *exn = CGF.getExceptionFromSlot(); 551249423Sdim CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn) 552226633Sdim ->setDoesNotReturn(); 553226633Sdim CGF.Builder.CreateUnreachable(); 554226633Sdim} 555226633Sdim 556200583Srdivackyvoid CodeGenFunction::EmitEndEHSpec(const Decl *D) { 557234353Sdim if (!CGM.getLangOpts().CXXExceptions) 558203955Srdivacky return; 559203955Srdivacky 560200583Srdivacky const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D); 561200583Srdivacky if (FD == 0) 562200583Srdivacky return; 563200583Srdivacky const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>(); 564200583Srdivacky if (Proto == 0) 565200583Srdivacky return; 566200583Srdivacky 567221345Sdim ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 568221345Sdim if (isNoexceptExceptionSpec(EST)) { 569221345Sdim if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) { 570221345Sdim EHStack.popTerminate(); 571221345Sdim } 572221345Sdim } else if (EST == EST_Dynamic || EST == EST_DynamicNone) { 573226633Sdim EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin()); 574226633Sdim emitFilterDispatchBlock(*this, filterScope); 575221345Sdim EHStack.popFilter(); 576221345Sdim } 577200583Srdivacky} 578200583Srdivacky 579199990Srdivackyvoid CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) { 580210299Sed EnterCXXTryStmt(S); 581204643Srdivacky EmitStmt(S.getTryBlock()); 582210299Sed ExitCXXTryStmt(S); 583204643Srdivacky} 584204643Srdivacky 585210299Sedvoid CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) { 586210299Sed unsigned NumHandlers = S.getNumHandlers(); 587210299Sed EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers); 588204643Srdivacky 589210299Sed for (unsigned I = 0; I != NumHandlers; ++I) { 590210299Sed const CXXCatchStmt *C = S.getHandler(I); 591204643Srdivacky 592210299Sed llvm::BasicBlock *Handler = createBasicBlock("catch"); 593210299Sed if (C->getExceptionDecl()) { 594210299Sed // FIXME: Dropping the reference type on the type into makes it 595210299Sed // impossible to correctly implement catch-by-reference 596210299Sed // semantics for pointers. Unfortunately, this is what all 597210299Sed // existing compilers do, and it's not clear that the standard 598210299Sed // personality routine is capable of doing this right. See C++ DR 388: 599210299Sed // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388 600210299Sed QualType CaughtType = C->getCaughtType(); 601210299Sed CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType(); 602212904Sdim 603212904Sdim llvm::Value *TypeInfo = 0; 604212904Sdim if (CaughtType->isObjCObjectPointerType()) 605212904Sdim TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType); 606212904Sdim else 607218893Sdim TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true); 608210299Sed CatchScope->setHandler(I, TypeInfo, Handler); 609210299Sed } else { 610210299Sed // No exception decl indicates '...', a catch-all. 611210299Sed CatchScope->setCatchAllHandler(I, Handler); 612210299Sed } 613210299Sed } 614204643Srdivacky} 615204643Srdivacky 616226633Sdimllvm::BasicBlock * 617226633SdimCodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) { 618226633Sdim // The dispatch block for the end of the scope chain is a block that 619226633Sdim // just resumes unwinding. 620226633Sdim if (si == EHStack.stable_end()) 621243830Sdim return getEHResumeBlock(true); 622226633Sdim 623226633Sdim // Otherwise, we should look at the actual scope. 624226633Sdim EHScope &scope = *EHStack.find(si); 625226633Sdim 626226633Sdim llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock(); 627226633Sdim if (!dispatchBlock) { 628226633Sdim switch (scope.getKind()) { 629226633Sdim case EHScope::Catch: { 630226633Sdim // Apply a special case to a single catch-all. 631226633Sdim EHCatchScope &catchScope = cast<EHCatchScope>(scope); 632226633Sdim if (catchScope.getNumHandlers() == 1 && 633226633Sdim catchScope.getHandler(0).isCatchAll()) { 634226633Sdim dispatchBlock = catchScope.getHandler(0).Block; 635226633Sdim 636226633Sdim // Otherwise, make a dispatch block. 637226633Sdim } else { 638226633Sdim dispatchBlock = createBasicBlock("catch.dispatch"); 639226633Sdim } 640226633Sdim break; 641226633Sdim } 642226633Sdim 643226633Sdim case EHScope::Cleanup: 644226633Sdim dispatchBlock = createBasicBlock("ehcleanup"); 645226633Sdim break; 646226633Sdim 647226633Sdim case EHScope::Filter: 648226633Sdim dispatchBlock = createBasicBlock("filter.dispatch"); 649226633Sdim break; 650226633Sdim 651226633Sdim case EHScope::Terminate: 652226633Sdim dispatchBlock = getTerminateHandler(); 653226633Sdim break; 654226633Sdim } 655226633Sdim scope.setCachedEHDispatchBlock(dispatchBlock); 656226633Sdim } 657226633Sdim return dispatchBlock; 658226633Sdim} 659226633Sdim 660210299Sed/// Check whether this is a non-EH scope, i.e. a scope which doesn't 661210299Sed/// affect exception handling. Currently, the only non-EH scopes are 662210299Sed/// normal-only cleanup scopes. 663210299Sedstatic bool isNonEHScope(const EHScope &S) { 664210299Sed switch (S.getKind()) { 665210299Sed case EHScope::Cleanup: 666210299Sed return !cast<EHCleanupScope>(S).isEHCleanup(); 667210299Sed case EHScope::Filter: 668210299Sed case EHScope::Catch: 669210299Sed case EHScope::Terminate: 670210299Sed return false; 671210299Sed } 672199990Srdivacky 673234353Sdim llvm_unreachable("Invalid EHScope Kind!"); 674210299Sed} 675199990Srdivacky 676210299Sedllvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() { 677210299Sed assert(EHStack.requiresLandingPad()); 678210299Sed assert(!EHStack.empty()); 679199990Srdivacky 680234353Sdim if (!CGM.getLangOpts().Exceptions) 681210299Sed return 0; 682200583Srdivacky 683210299Sed // Check the innermost scope for a cached landing pad. If this is 684210299Sed // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad. 685210299Sed llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad(); 686210299Sed if (LP) return LP; 687200583Srdivacky 688210299Sed // Build the landing pad for this scope. 689210299Sed LP = EmitLandingPad(); 690210299Sed assert(LP); 691199990Srdivacky 692210299Sed // Cache the landing pad on the innermost scope. If this is a 693210299Sed // non-EH scope, cache the landing pad on the enclosing scope, too. 694210299Sed for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) { 695210299Sed ir->setCachedLandingPad(LP); 696210299Sed if (!isNonEHScope(*ir)) break; 697210299Sed } 698199990Srdivacky 699210299Sed return LP; 700210299Sed} 701210299Sed 702223017Sdim// This code contains a hack to work around a design flaw in 703223017Sdim// LLVM's EH IR which breaks semantics after inlining. This same 704223017Sdim// hack is implemented in llvm-gcc. 705223017Sdim// 706223017Sdim// The LLVM EH abstraction is basically a thin veneer over the 707223017Sdim// traditional GCC zero-cost design: for each range of instructions 708223017Sdim// in the function, there is (at most) one "landing pad" with an 709223017Sdim// associated chain of EH actions. A language-specific personality 710223017Sdim// function interprets this chain of actions and (1) decides whether 711223017Sdim// or not to resume execution at the landing pad and (2) if so, 712223017Sdim// provides an integer indicating why it's stopping. In LLVM IR, 713223017Sdim// the association of a landing pad with a range of instructions is 714223017Sdim// achieved via an invoke instruction, the chain of actions becomes 715223017Sdim// the arguments to the @llvm.eh.selector call, and the selector 716223017Sdim// call returns the integer indicator. Other than the required 717223017Sdim// presence of two intrinsic function calls in the landing pad, 718223017Sdim// the IR exactly describes the layout of the output code. 719223017Sdim// 720223017Sdim// A principal advantage of this design is that it is completely 721223017Sdim// language-agnostic; in theory, the LLVM optimizers can treat 722223017Sdim// landing pads neutrally, and targets need only know how to lower 723223017Sdim// the intrinsics to have a functioning exceptions system (assuming 724223017Sdim// that platform exceptions follow something approximately like the 725223017Sdim// GCC design). Unfortunately, landing pads cannot be combined in a 726223017Sdim// language-agnostic way: given selectors A and B, there is no way 727223017Sdim// to make a single landing pad which faithfully represents the 728223017Sdim// semantics of propagating an exception first through A, then 729223017Sdim// through B, without knowing how the personality will interpret the 730223017Sdim// (lowered form of the) selectors. This means that inlining has no 731223017Sdim// choice but to crudely chain invokes (i.e., to ignore invokes in 732223017Sdim// the inlined function, but to turn all unwindable calls into 733223017Sdim// invokes), which is only semantically valid if every unwind stops 734223017Sdim// at every landing pad. 735223017Sdim// 736223017Sdim// Therefore, the invoke-inline hack is to guarantee that every 737223017Sdim// landing pad has a catch-all. 738223017Sdimenum CleanupHackLevel_t { 739223017Sdim /// A level of hack that requires that all landing pads have 740223017Sdim /// catch-alls. 741223017Sdim CHL_MandatoryCatchall, 742223017Sdim 743223017Sdim /// A level of hack that requires that all landing pads handle 744223017Sdim /// cleanups. 745223017Sdim CHL_MandatoryCleanup, 746223017Sdim 747223017Sdim /// No hacks at all; ideal IR generation. 748223017Sdim CHL_Ideal 749223017Sdim}; 750223017Sdimconst CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup; 751223017Sdim 752210299Sedllvm::BasicBlock *CodeGenFunction::EmitLandingPad() { 753210299Sed assert(EHStack.requiresLandingPad()); 754210299Sed 755226633Sdim EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope()); 756226633Sdim switch (innermostEHScope.getKind()) { 757226633Sdim case EHScope::Terminate: 758226633Sdim return getTerminateLandingPad(); 759210299Sed 760226633Sdim case EHScope::Catch: 761226633Sdim case EHScope::Cleanup: 762226633Sdim case EHScope::Filter: 763226633Sdim if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad()) 764226633Sdim return lpad; 765210299Sed } 766210299Sed 767210299Sed // Save the current IR generation state. 768226633Sdim CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP(); 769210299Sed 770234353Sdim const EHPersonality &personality = EHPersonality::get(getLangOpts()); 771212904Sdim 772210299Sed // Create and configure the landing pad. 773226633Sdim llvm::BasicBlock *lpad = createBasicBlock("lpad"); 774226633Sdim EmitBlock(lpad); 775210299Sed 776226633Sdim llvm::LandingPadInst *LPadInst = 777226633Sdim Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL), 778226633Sdim getOpaquePersonalityFn(CGM, personality), 0); 779226633Sdim 780226633Sdim llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0); 781226633Sdim Builder.CreateStore(LPadExn, getExceptionSlot()); 782226633Sdim llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1); 783226633Sdim Builder.CreateStore(LPadSel, getEHSelectorSlot()); 784226633Sdim 785210299Sed // Save the exception pointer. It's safe to use a single exception 786210299Sed // pointer per function because EH cleanups can never have nested 787210299Sed // try/catches. 788226633Sdim // Build the landingpad instruction. 789210299Sed 790210299Sed // Accumulate all the handlers in scope. 791226633Sdim bool hasCatchAll = false; 792226633Sdim bool hasCleanup = false; 793226633Sdim bool hasFilter = false; 794226633Sdim SmallVector<llvm::Value*, 4> filterTypes; 795226633Sdim llvm::SmallPtrSet<llvm::Value*, 4> catchTypes; 796210299Sed for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); 797210299Sed I != E; ++I) { 798210299Sed 799210299Sed switch (I->getKind()) { 800210299Sed case EHScope::Cleanup: 801226633Sdim // If we have a cleanup, remember that. 802226633Sdim hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup()); 803210299Sed continue; 804210299Sed 805210299Sed case EHScope::Filter: { 806210299Sed assert(I.next() == EHStack.end() && "EH filter is not end of EH stack"); 807226633Sdim assert(!hasCatchAll && "EH filter reached after catch-all"); 808210299Sed 809226633Sdim // Filter scopes get added to the landingpad in weird ways. 810226633Sdim EHFilterScope &filter = cast<EHFilterScope>(*I); 811226633Sdim hasFilter = true; 812210299Sed 813226633Sdim // Add all the filter values. 814226633Sdim for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i) 815226633Sdim filterTypes.push_back(filter.getFilter(i)); 816210299Sed goto done; 817199990Srdivacky } 818210299Sed 819210299Sed case EHScope::Terminate: 820210299Sed // Terminate scopes are basically catch-alls. 821226633Sdim assert(!hasCatchAll); 822226633Sdim hasCatchAll = true; 823210299Sed goto done; 824210299Sed 825210299Sed case EHScope::Catch: 826210299Sed break; 827210299Sed } 828210299Sed 829226633Sdim EHCatchScope &catchScope = cast<EHCatchScope>(*I); 830226633Sdim for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) { 831226633Sdim EHCatchScope::Handler handler = catchScope.getHandler(hi); 832210299Sed 833226633Sdim // If this is a catch-all, register that and abort. 834226633Sdim if (!handler.Type) { 835226633Sdim assert(!hasCatchAll); 836226633Sdim hasCatchAll = true; 837226633Sdim goto done; 838210299Sed } 839210299Sed 840210299Sed // Check whether we already have a handler for this type. 841226633Sdim if (catchTypes.insert(handler.Type)) 842226633Sdim // If not, add it directly to the landingpad. 843226633Sdim LPadInst->addClause(handler.Type); 844210299Sed } 845199990Srdivacky } 846199990Srdivacky 847210299Sed done: 848226633Sdim // If we have a catch-all, add null to the landingpad. 849226633Sdim assert(!(hasCatchAll && hasFilter)); 850226633Sdim if (hasCatchAll) { 851226633Sdim LPadInst->addClause(getCatchAllValue(*this)); 852210299Sed 853210299Sed // If we have an EH filter, we need to add those handlers in the 854226633Sdim // right place in the landingpad, which is to say, at the end. 855226633Sdim } else if (hasFilter) { 856226633Sdim // Create a filter expression: a constant array indicating which filter 857226633Sdim // types there are. The personality routine only lands here if the filter 858226633Sdim // doesn't match. 859249423Sdim SmallVector<llvm::Constant*, 8> Filters; 860226633Sdim llvm::ArrayType *AType = 861226633Sdim llvm::ArrayType::get(!filterTypes.empty() ? 862226633Sdim filterTypes[0]->getType() : Int8PtrTy, 863226633Sdim filterTypes.size()); 864210299Sed 865226633Sdim for (unsigned i = 0, e = filterTypes.size(); i != e; ++i) 866226633Sdim Filters.push_back(cast<llvm::Constant>(filterTypes[i])); 867226633Sdim llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters); 868226633Sdim LPadInst->addClause(FilterArray); 869226633Sdim 870210299Sed // Also check whether we need a cleanup. 871226633Sdim if (hasCleanup) 872226633Sdim LPadInst->setCleanup(true); 873210299Sed 874210299Sed // Otherwise, signal that we at least have cleanups. 875226633Sdim } else if (CleanupHackLevel == CHL_MandatoryCatchall || hasCleanup) { 876226633Sdim if (CleanupHackLevel == CHL_MandatoryCatchall) 877226633Sdim LPadInst->addClause(getCatchAllValue(*this)); 878226633Sdim else 879226633Sdim LPadInst->setCleanup(true); 880199990Srdivacky } 881199990Srdivacky 882226633Sdim assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) && 883226633Sdim "landingpad instruction has no clauses!"); 884199990Srdivacky 885210299Sed // Tell the backend how to generate the landing pad. 886226633Sdim Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope())); 887223017Sdim 888210299Sed // Restore the old IR generation state. 889226633Sdim Builder.restoreIP(savedIP); 890210299Sed 891226633Sdim return lpad; 892210299Sed} 893210299Sed 894210299Sednamespace { 895210299Sed /// A cleanup to call __cxa_end_catch. In many cases, the caught 896210299Sed /// exception type lets us state definitively that the thrown exception 897210299Sed /// type does not have a destructor. In particular: 898210299Sed /// - Catch-alls tell us nothing, so we have to conservatively 899210299Sed /// assume that the thrown exception might have a destructor. 900210299Sed /// - Catches by reference behave according to their base types. 901210299Sed /// - Catches of non-record types will only trigger for exceptions 902210299Sed /// of non-record types, which never have destructors. 903210299Sed /// - Catches of record types can trigger for arbitrary subclasses 904210299Sed /// of the caught type, so we have to assume the actual thrown 905210299Sed /// exception type might have a throwing destructor, even if the 906210299Sed /// caught type's destructor is trivial or nothrow. 907212904Sdim struct CallEndCatch : EHScopeStack::Cleanup { 908210299Sed CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {} 909210299Sed bool MightThrow; 910210299Sed 911224145Sdim void Emit(CodeGenFunction &CGF, Flags flags) { 912210299Sed if (!MightThrow) { 913249423Sdim CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM)); 914210299Sed return; 915210299Sed } 916210299Sed 917249423Sdim CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM)); 918210299Sed } 919210299Sed }; 920210299Sed} 921210299Sed 922210299Sed/// Emits a call to __cxa_begin_catch and enters a cleanup to call 923210299Sed/// __cxa_end_catch. 924210299Sed/// 925210299Sed/// \param EndMightThrow - true if __cxa_end_catch might throw 926210299Sedstatic llvm::Value *CallBeginCatch(CodeGenFunction &CGF, 927210299Sed llvm::Value *Exn, 928210299Sed bool EndMightThrow) { 929249423Sdim llvm::CallInst *call = 930249423Sdim CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn); 931210299Sed 932212904Sdim CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow); 933210299Sed 934249423Sdim return call; 935210299Sed} 936210299Sed 937210299Sed/// A "special initializer" callback for initializing a catch 938210299Sed/// parameter during catch initialization. 939210299Sedstatic void InitCatchParam(CodeGenFunction &CGF, 940210299Sed const VarDecl &CatchParam, 941210299Sed llvm::Value *ParamAddr) { 942210299Sed // Load the exception from where the landing pad saved it. 943226633Sdim llvm::Value *Exn = CGF.getExceptionFromSlot(); 944210299Sed 945210299Sed CanQualType CatchType = 946210299Sed CGF.CGM.getContext().getCanonicalType(CatchParam.getType()); 947226633Sdim llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType); 948210299Sed 949210299Sed // If we're catching by reference, we can just cast the object 950210299Sed // pointer to the appropriate pointer. 951210299Sed if (isa<ReferenceType>(CatchType)) { 952212904Sdim QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType(); 953212904Sdim bool EndCatchMightThrow = CaughtType->isRecordType(); 954210299Sed 955210299Sed // __cxa_begin_catch returns the adjusted object pointer. 956210299Sed llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow); 957212904Sdim 958212904Sdim // We have no way to tell the personality function that we're 959212904Sdim // catching by reference, so if we're catching a pointer, 960212904Sdim // __cxa_begin_catch will actually return that pointer by value. 961212904Sdim if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) { 962212904Sdim QualType PointeeType = PT->getPointeeType(); 963212904Sdim 964212904Sdim // When catching by reference, generally we should just ignore 965212904Sdim // this by-value pointer and use the exception object instead. 966212904Sdim if (!PointeeType->isRecordType()) { 967212904Sdim 968212904Sdim // Exn points to the struct _Unwind_Exception header, which 969212904Sdim // we have to skip past in order to reach the exception data. 970212904Sdim unsigned HeaderSize = 971212904Sdim CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException(); 972212904Sdim AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize); 973212904Sdim 974212904Sdim // However, if we're catching a pointer-to-record type that won't 975212904Sdim // work, because the personality function might have adjusted 976212904Sdim // the pointer. There's actually no way for us to fully satisfy 977212904Sdim // the language/ABI contract here: we can't use Exn because it 978212904Sdim // might have the wrong adjustment, but we can't use the by-value 979212904Sdim // pointer because it's off by a level of abstraction. 980212904Sdim // 981212904Sdim // The current solution is to dump the adjusted pointer into an 982212904Sdim // alloca, which breaks language semantics (because changing the 983212904Sdim // pointer doesn't change the exception) but at least works. 984212904Sdim // The better solution would be to filter out non-exact matches 985212904Sdim // and rethrow them, but this is tricky because the rethrow 986212904Sdim // really needs to be catchable by other sites at this landing 987212904Sdim // pad. The best solution is to fix the personality function. 988212904Sdim } else { 989212904Sdim // Pull the pointer for the reference type off. 990226633Sdim llvm::Type *PtrTy = 991212904Sdim cast<llvm::PointerType>(LLVMCatchTy)->getElementType(); 992212904Sdim 993212904Sdim // Create the temporary and write the adjusted pointer into it. 994212904Sdim llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp"); 995212904Sdim llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy); 996212904Sdim CGF.Builder.CreateStore(Casted, ExnPtrTmp); 997212904Sdim 998212904Sdim // Bind the reference to the temporary. 999212904Sdim AdjustedExn = ExnPtrTmp; 1000212904Sdim } 1001212904Sdim } 1002212904Sdim 1003210299Sed llvm::Value *ExnCast = 1004210299Sed CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref"); 1005210299Sed CGF.Builder.CreateStore(ExnCast, ParamAddr); 1006210299Sed return; 1007200583Srdivacky } 1008199990Srdivacky 1009249423Sdim // Scalars and complexes. 1010249423Sdim TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType); 1011249423Sdim if (TEK != TEK_Aggregate) { 1012210299Sed llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false); 1013210299Sed 1014210299Sed // If the catch type is a pointer type, __cxa_begin_catch returns 1015210299Sed // the pointer by value. 1016210299Sed if (CatchType->hasPointerRepresentation()) { 1017210299Sed llvm::Value *CastExn = 1018210299Sed CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted"); 1019234353Sdim 1020234353Sdim switch (CatchType.getQualifiers().getObjCLifetime()) { 1021234353Sdim case Qualifiers::OCL_Strong: 1022234353Sdim CastExn = CGF.EmitARCRetainNonBlock(CastExn); 1023234353Sdim // fallthrough 1024234353Sdim 1025234353Sdim case Qualifiers::OCL_None: 1026234353Sdim case Qualifiers::OCL_ExplicitNone: 1027234353Sdim case Qualifiers::OCL_Autoreleasing: 1028234353Sdim CGF.Builder.CreateStore(CastExn, ParamAddr); 1029234353Sdim return; 1030234353Sdim 1031234353Sdim case Qualifiers::OCL_Weak: 1032234353Sdim CGF.EmitARCInitWeak(ParamAddr, CastExn); 1033234353Sdim return; 1034234353Sdim } 1035234353Sdim llvm_unreachable("bad ownership qualifier!"); 1036210299Sed } 1037199990Srdivacky 1038210299Sed // Otherwise, it returns a pointer into the exception object. 1039199990Srdivacky 1040226633Sdim llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok 1041210299Sed llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy); 1042199990Srdivacky 1043249423Sdim LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType); 1044249423Sdim LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType, 1045249423Sdim CGF.getContext().getDeclAlign(&CatchParam)); 1046249423Sdim switch (TEK) { 1047249423Sdim case TEK_Complex: 1048249423Sdim CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV), destLV, 1049249423Sdim /*init*/ true); 1050249423Sdim return; 1051249423Sdim case TEK_Scalar: { 1052249423Sdim llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV); 1053249423Sdim CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true); 1054249423Sdim return; 1055210299Sed } 1056249423Sdim case TEK_Aggregate: 1057249423Sdim llvm_unreachable("evaluation kind filtered out!"); 1058249423Sdim } 1059249423Sdim llvm_unreachable("bad evaluation kind"); 1060210299Sed } 1061199990Srdivacky 1062218893Sdim assert(isa<RecordType>(CatchType) && "unexpected catch type!"); 1063199990Srdivacky 1064226633Sdim llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok 1065199990Srdivacky 1066218893Sdim // Check for a copy expression. If we don't have a copy expression, 1067218893Sdim // that means a trivial copy is okay. 1068218893Sdim const Expr *copyExpr = CatchParam.getInit(); 1069218893Sdim if (!copyExpr) { 1070218893Sdim llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true); 1071218893Sdim llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy); 1072218893Sdim CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType); 1073210299Sed return; 1074210299Sed } 1075210299Sed 1076210299Sed // We have to call __cxa_get_exception_ptr to get the adjusted 1077210299Sed // pointer before copying. 1078218893Sdim llvm::CallInst *rawAdjustedExn = 1079249423Sdim CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn); 1080210299Sed 1081218893Sdim // Cast that to the appropriate type. 1082218893Sdim llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy); 1083210299Sed 1084218893Sdim // The copy expression is defined in terms of an OpaqueValueExpr. 1085218893Sdim // Find it and map it to the adjusted expression. 1086218893Sdim CodeGenFunction::OpaqueValueMapping 1087218893Sdim opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr), 1088218893Sdim CGF.MakeAddrLValue(adjustedExn, CatchParam.getType())); 1089210299Sed 1090210299Sed // Call the copy ctor in a terminate scope. 1091210299Sed CGF.EHStack.pushTerminate(); 1092218893Sdim 1093218893Sdim // Perform the copy construction. 1094234353Sdim CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam); 1095234353Sdim CGF.EmitAggExpr(copyExpr, 1096234353Sdim AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(), 1097234353Sdim AggValueSlot::IsNotDestructed, 1098234353Sdim AggValueSlot::DoesNotNeedGCBarriers, 1099234353Sdim AggValueSlot::IsNotAliased)); 1100218893Sdim 1101218893Sdim // Leave the terminate scope. 1102210299Sed CGF.EHStack.popTerminate(); 1103210299Sed 1104218893Sdim // Undo the opaque value mapping. 1105218893Sdim opaque.pop(); 1106218893Sdim 1107210299Sed // Finally we can call __cxa_begin_catch. 1108210299Sed CallBeginCatch(CGF, Exn, true); 1109199990Srdivacky} 1110200583Srdivacky 1111210299Sed/// Begins a catch statement by initializing the catch variable and 1112210299Sed/// calling __cxa_begin_catch. 1113218893Sdimstatic void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) { 1114210299Sed // We have to be very careful with the ordering of cleanups here: 1115210299Sed // C++ [except.throw]p4: 1116210299Sed // The destruction [of the exception temporary] occurs 1117210299Sed // immediately after the destruction of the object declared in 1118210299Sed // the exception-declaration in the handler. 1119210299Sed // 1120210299Sed // So the precise ordering is: 1121210299Sed // 1. Construct catch variable. 1122210299Sed // 2. __cxa_begin_catch 1123210299Sed // 3. Enter __cxa_end_catch cleanup 1124210299Sed // 4. Enter dtor cleanup 1125210299Sed // 1126219077Sdim // We do this by using a slightly abnormal initialization process. 1127219077Sdim // Delegation sequence: 1128210299Sed // - ExitCXXTryStmt opens a RunCleanupsScope 1129219077Sdim // - EmitAutoVarAlloca creates the variable and debug info 1130210299Sed // - InitCatchParam initializes the variable from the exception 1131219077Sdim // - CallBeginCatch calls __cxa_begin_catch 1132219077Sdim // - CallBeginCatch enters the __cxa_end_catch cleanup 1133219077Sdim // - EmitAutoVarCleanups enters the variable destructor cleanup 1134210299Sed // - EmitCXXTryStmt emits the code for the catch body 1135210299Sed // - EmitCXXTryStmt close the RunCleanupsScope 1136200583Srdivacky 1137210299Sed VarDecl *CatchParam = S->getExceptionDecl(); 1138210299Sed if (!CatchParam) { 1139226633Sdim llvm::Value *Exn = CGF.getExceptionFromSlot(); 1140210299Sed CallBeginCatch(CGF, Exn, true); 1141210299Sed return; 1142210299Sed } 1143200583Srdivacky 1144210299Sed // Emit the local. 1145219077Sdim CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam); 1146219077Sdim InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF)); 1147219077Sdim CGF.EmitAutoVarCleanups(var); 1148210299Sed} 1149207619Srdivacky 1150226633Sdim/// Emit the structure of the dispatch block for the given catch scope. 1151226633Sdim/// It is an invariant that the dispatch block already exists. 1152226633Sdimstatic void emitCatchDispatchBlock(CodeGenFunction &CGF, 1153226633Sdim EHCatchScope &catchScope) { 1154226633Sdim llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock(); 1155226633Sdim assert(dispatchBlock); 1156226633Sdim 1157226633Sdim // If there's only a single catch-all, getEHDispatchBlock returned 1158226633Sdim // that catch-all as the dispatch block. 1159226633Sdim if (catchScope.getNumHandlers() == 1 && 1160226633Sdim catchScope.getHandler(0).isCatchAll()) { 1161226633Sdim assert(dispatchBlock == catchScope.getHandler(0).Block); 1162226633Sdim return; 1163226633Sdim } 1164226633Sdim 1165226633Sdim CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP(); 1166226633Sdim CGF.EmitBlockAfterUses(dispatchBlock); 1167226633Sdim 1168226633Sdim // Select the right handler. 1169226633Sdim llvm::Value *llvm_eh_typeid_for = 1170226633Sdim CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for); 1171226633Sdim 1172226633Sdim // Load the selector value. 1173226633Sdim llvm::Value *selector = CGF.getSelectorFromSlot(); 1174226633Sdim 1175226633Sdim // Test against each of the exception types we claim to catch. 1176226633Sdim for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) { 1177226633Sdim assert(i < e && "ran off end of handlers!"); 1178226633Sdim const EHCatchScope::Handler &handler = catchScope.getHandler(i); 1179226633Sdim 1180226633Sdim llvm::Value *typeValue = handler.Type; 1181226633Sdim assert(typeValue && "fell into catch-all case!"); 1182226633Sdim typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy); 1183226633Sdim 1184226633Sdim // Figure out the next block. 1185226633Sdim bool nextIsEnd; 1186226633Sdim llvm::BasicBlock *nextBlock; 1187226633Sdim 1188226633Sdim // If this is the last handler, we're at the end, and the next 1189226633Sdim // block is the block for the enclosing EH scope. 1190226633Sdim if (i + 1 == e) { 1191226633Sdim nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope()); 1192226633Sdim nextIsEnd = true; 1193226633Sdim 1194226633Sdim // If the next handler is a catch-all, we're at the end, and the 1195226633Sdim // next block is that handler. 1196226633Sdim } else if (catchScope.getHandler(i+1).isCatchAll()) { 1197226633Sdim nextBlock = catchScope.getHandler(i+1).Block; 1198226633Sdim nextIsEnd = true; 1199226633Sdim 1200226633Sdim // Otherwise, we're not at the end and we need a new block. 1201226633Sdim } else { 1202226633Sdim nextBlock = CGF.createBasicBlock("catch.fallthrough"); 1203226633Sdim nextIsEnd = false; 1204226633Sdim } 1205226633Sdim 1206226633Sdim // Figure out the catch type's index in the LSDA's type table. 1207226633Sdim llvm::CallInst *typeIndex = 1208226633Sdim CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue); 1209226633Sdim typeIndex->setDoesNotThrow(); 1210226633Sdim 1211226633Sdim llvm::Value *matchesTypeIndex = 1212226633Sdim CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches"); 1213226633Sdim CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock); 1214226633Sdim 1215226633Sdim // If the next handler is a catch-all, we're completely done. 1216226633Sdim if (nextIsEnd) { 1217226633Sdim CGF.Builder.restoreIP(savedIP); 1218226633Sdim return; 1219234353Sdim } 1220226633Sdim // Otherwise we need to emit and continue at that block. 1221234353Sdim CGF.EmitBlock(nextBlock); 1222226633Sdim } 1223226633Sdim} 1224226633Sdim 1225226633Sdimvoid CodeGenFunction::popCatchScope() { 1226226633Sdim EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin()); 1227226633Sdim if (catchScope.hasEHBranches()) 1228226633Sdim emitCatchDispatchBlock(*this, catchScope); 1229226633Sdim EHStack.popCatch(); 1230226633Sdim} 1231226633Sdim 1232210299Sedvoid CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) { 1233210299Sed unsigned NumHandlers = S.getNumHandlers(); 1234210299Sed EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin()); 1235210299Sed assert(CatchScope.getNumHandlers() == NumHandlers); 1236207619Srdivacky 1237226633Sdim // If the catch was not required, bail out now. 1238226633Sdim if (!CatchScope.hasEHBranches()) { 1239226633Sdim EHStack.popCatch(); 1240226633Sdim return; 1241226633Sdim } 1242226633Sdim 1243226633Sdim // Emit the structure of the EH dispatch for this catch. 1244226633Sdim emitCatchDispatchBlock(*this, CatchScope); 1245226633Sdim 1246210299Sed // Copy the handler blocks off before we pop the EH stack. Emitting 1247210299Sed // the handlers might scribble on this memory. 1248226633Sdim SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers); 1249210299Sed memcpy(Handlers.data(), CatchScope.begin(), 1250210299Sed NumHandlers * sizeof(EHCatchScope::Handler)); 1251226633Sdim 1252210299Sed EHStack.popCatch(); 1253200583Srdivacky 1254210299Sed // The fall-through block. 1255210299Sed llvm::BasicBlock *ContBB = createBasicBlock("try.cont"); 1256200583Srdivacky 1257210299Sed // We just emitted the body of the try; jump to the continue block. 1258210299Sed if (HaveInsertPoint()) 1259210299Sed Builder.CreateBr(ContBB); 1260210299Sed 1261239462Sdim // Determine if we need an implicit rethrow for all these catch handlers; 1262239462Sdim // see the comment below. 1263239462Sdim bool doImplicitRethrow = false; 1264210299Sed if (IsFnTryBlock) 1265239462Sdim doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) || 1266239462Sdim isa<CXXConstructorDecl>(CurCodeDecl); 1267210299Sed 1268226633Sdim // Perversely, we emit the handlers backwards precisely because we 1269226633Sdim // want them to appear in source order. In all of these cases, the 1270226633Sdim // catch block will have exactly one predecessor, which will be a 1271226633Sdim // particular block in the catch dispatch. However, in the case of 1272226633Sdim // a catch-all, one of the dispatch blocks will branch to two 1273226633Sdim // different handlers, and EmitBlockAfterUses will cause the second 1274226633Sdim // handler to be moved before the first. 1275226633Sdim for (unsigned I = NumHandlers; I != 0; --I) { 1276226633Sdim llvm::BasicBlock *CatchBlock = Handlers[I-1].Block; 1277226633Sdim EmitBlockAfterUses(CatchBlock); 1278210299Sed 1279210299Sed // Catch the exception if this isn't a catch-all. 1280226633Sdim const CXXCatchStmt *C = S.getHandler(I-1); 1281210299Sed 1282210299Sed // Enter a cleanup scope, including the catch variable and the 1283210299Sed // end-catch. 1284210299Sed RunCleanupsScope CatchScope(*this); 1285210299Sed 1286210299Sed // Initialize the catch variable and set up the cleanups. 1287210299Sed BeginCatch(*this, C); 1288210299Sed 1289210299Sed // Perform the body of the catch. 1290210299Sed EmitStmt(C->getHandlerBlock()); 1291210299Sed 1292239462Sdim // [except.handle]p11: 1293239462Sdim // The currently handled exception is rethrown if control 1294239462Sdim // reaches the end of a handler of the function-try-block of a 1295239462Sdim // constructor or destructor. 1296239462Sdim 1297239462Sdim // It is important that we only do this on fallthrough and not on 1298239462Sdim // return. Note that it's illegal to put a return in a 1299239462Sdim // constructor function-try-block's catch handler (p14), so this 1300239462Sdim // really only applies to destructors. 1301239462Sdim if (doImplicitRethrow && HaveInsertPoint()) { 1302249423Sdim EmitRuntimeCallOrInvoke(getReThrowFn(CGM)); 1303239462Sdim Builder.CreateUnreachable(); 1304239462Sdim Builder.ClearInsertionPoint(); 1305239462Sdim } 1306239462Sdim 1307210299Sed // Fall out through the catch cleanups. 1308210299Sed CatchScope.ForceCleanup(); 1309210299Sed 1310210299Sed // Branch out of the try. 1311210299Sed if (HaveInsertPoint()) 1312210299Sed Builder.CreateBr(ContBB); 1313210299Sed } 1314210299Sed 1315210299Sed EmitBlock(ContBB); 1316210299Sed} 1317210299Sed 1318212904Sdimnamespace { 1319212904Sdim struct CallEndCatchForFinally : EHScopeStack::Cleanup { 1320212904Sdim llvm::Value *ForEHVar; 1321212904Sdim llvm::Value *EndCatchFn; 1322212904Sdim CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn) 1323212904Sdim : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {} 1324212904Sdim 1325224145Sdim void Emit(CodeGenFunction &CGF, Flags flags) { 1326212904Sdim llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch"); 1327212904Sdim llvm::BasicBlock *CleanupContBB = 1328212904Sdim CGF.createBasicBlock("finally.cleanup.cont"); 1329212904Sdim 1330212904Sdim llvm::Value *ShouldEndCatch = 1331212904Sdim CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch"); 1332212904Sdim CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB); 1333212904Sdim CGF.EmitBlock(EndCatchBB); 1334249423Sdim CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw 1335212904Sdim CGF.EmitBlock(CleanupContBB); 1336212904Sdim } 1337212904Sdim }; 1338212904Sdim 1339212904Sdim struct PerformFinally : EHScopeStack::Cleanup { 1340212904Sdim const Stmt *Body; 1341212904Sdim llvm::Value *ForEHVar; 1342212904Sdim llvm::Value *EndCatchFn; 1343212904Sdim llvm::Value *RethrowFn; 1344212904Sdim llvm::Value *SavedExnVar; 1345212904Sdim 1346212904Sdim PerformFinally(const Stmt *Body, llvm::Value *ForEHVar, 1347212904Sdim llvm::Value *EndCatchFn, 1348212904Sdim llvm::Value *RethrowFn, llvm::Value *SavedExnVar) 1349212904Sdim : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn), 1350212904Sdim RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {} 1351212904Sdim 1352224145Sdim void Emit(CodeGenFunction &CGF, Flags flags) { 1353212904Sdim // Enter a cleanup to call the end-catch function if one was provided. 1354212904Sdim if (EndCatchFn) 1355212904Sdim CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup, 1356212904Sdim ForEHVar, EndCatchFn); 1357212904Sdim 1358212904Sdim // Save the current cleanup destination in case there are 1359212904Sdim // cleanups in the finally block. 1360212904Sdim llvm::Value *SavedCleanupDest = 1361212904Sdim CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(), 1362212904Sdim "cleanup.dest.saved"); 1363212904Sdim 1364212904Sdim // Emit the finally block. 1365212904Sdim CGF.EmitStmt(Body); 1366212904Sdim 1367212904Sdim // If the end of the finally is reachable, check whether this was 1368212904Sdim // for EH. If so, rethrow. 1369212904Sdim if (CGF.HaveInsertPoint()) { 1370212904Sdim llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow"); 1371212904Sdim llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont"); 1372212904Sdim 1373212904Sdim llvm::Value *ShouldRethrow = 1374212904Sdim CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow"); 1375212904Sdim CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB); 1376212904Sdim 1377212904Sdim CGF.EmitBlock(RethrowBB); 1378212904Sdim if (SavedExnVar) { 1379249423Sdim CGF.EmitRuntimeCallOrInvoke(RethrowFn, 1380249423Sdim CGF.Builder.CreateLoad(SavedExnVar)); 1381212904Sdim } else { 1382249423Sdim CGF.EmitRuntimeCallOrInvoke(RethrowFn); 1383212904Sdim } 1384212904Sdim CGF.Builder.CreateUnreachable(); 1385212904Sdim 1386212904Sdim CGF.EmitBlock(ContBB); 1387212904Sdim 1388212904Sdim // Restore the cleanup destination. 1389212904Sdim CGF.Builder.CreateStore(SavedCleanupDest, 1390212904Sdim CGF.getNormalCleanupDestSlot()); 1391212904Sdim } 1392212904Sdim 1393212904Sdim // Leave the end-catch cleanup. As an optimization, pretend that 1394212904Sdim // the fallthrough path was inaccessible; we've dynamically proven 1395212904Sdim // that we're not in the EH case along that path. 1396212904Sdim if (EndCatchFn) { 1397212904Sdim CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP(); 1398212904Sdim CGF.PopCleanupBlock(); 1399212904Sdim CGF.Builder.restoreIP(SavedIP); 1400212904Sdim } 1401212904Sdim 1402212904Sdim // Now make sure we actually have an insertion point or the 1403212904Sdim // cleanup gods will hate us. 1404212904Sdim CGF.EnsureInsertPoint(); 1405212904Sdim } 1406212904Sdim }; 1407212904Sdim} 1408212904Sdim 1409210299Sed/// Enters a finally block for an implementation using zero-cost 1410210299Sed/// exceptions. This is mostly general, but hard-codes some 1411210299Sed/// language/ABI-specific behavior in the catch-all sections. 1412224145Sdimvoid CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF, 1413224145Sdim const Stmt *body, 1414224145Sdim llvm::Constant *beginCatchFn, 1415224145Sdim llvm::Constant *endCatchFn, 1416224145Sdim llvm::Constant *rethrowFn) { 1417224145Sdim assert((beginCatchFn != 0) == (endCatchFn != 0) && 1418210299Sed "begin/end catch functions not paired"); 1419224145Sdim assert(rethrowFn && "rethrow function is required"); 1420210299Sed 1421224145Sdim BeginCatchFn = beginCatchFn; 1422224145Sdim 1423210299Sed // The rethrow function has one of the following two types: 1424210299Sed // void (*)() 1425210299Sed // void (*)(void*) 1426210299Sed // In the latter case we need to pass it the exception object. 1427210299Sed // But we can't use the exception slot because the @finally might 1428210299Sed // have a landing pad (which would overwrite the exception slot). 1429226633Sdim llvm::FunctionType *rethrowFnTy = 1430210299Sed cast<llvm::FunctionType>( 1431224145Sdim cast<llvm::PointerType>(rethrowFn->getType())->getElementType()); 1432224145Sdim SavedExnVar = 0; 1433224145Sdim if (rethrowFnTy->getNumParams()) 1434224145Sdim SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn"); 1435210299Sed 1436210299Sed // A finally block is a statement which must be executed on any edge 1437210299Sed // out of a given scope. Unlike a cleanup, the finally block may 1438210299Sed // contain arbitrary control flow leading out of itself. In 1439210299Sed // addition, finally blocks should always be executed, even if there 1440210299Sed // are no catch handlers higher on the stack. Therefore, we 1441210299Sed // surround the protected scope with a combination of a normal 1442210299Sed // cleanup (to catch attempts to break out of the block via normal 1443210299Sed // control flow) and an EH catch-all (semantically "outside" any try 1444210299Sed // statement to which the finally block might have been attached). 1445210299Sed // The finally block itself is generated in the context of a cleanup 1446210299Sed // which conditionally leaves the catch-all. 1447210299Sed 1448210299Sed // Jump destination for performing the finally block on an exception 1449210299Sed // edge. We'll never actually reach this block, so unreachable is 1450210299Sed // fine. 1451224145Sdim RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock()); 1452210299Sed 1453210299Sed // Whether the finally block is being executed for EH purposes. 1454224145Sdim ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh"); 1455224145Sdim CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar); 1456210299Sed 1457210299Sed // Enter a normal cleanup which will perform the @finally block. 1458224145Sdim CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body, 1459224145Sdim ForEHVar, endCatchFn, 1460224145Sdim rethrowFn, SavedExnVar); 1461210299Sed 1462210299Sed // Enter a catch-all scope. 1463224145Sdim llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall"); 1464224145Sdim EHCatchScope *catchScope = CGF.EHStack.pushCatch(1); 1465224145Sdim catchScope->setCatchAllHandler(0, catchBB); 1466224145Sdim} 1467210299Sed 1468224145Sdimvoid CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) { 1469224145Sdim // Leave the finally catch-all. 1470224145Sdim EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin()); 1471224145Sdim llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block; 1472210299Sed 1473226633Sdim CGF.popCatchScope(); 1474226633Sdim 1475224145Sdim // If there are any references to the catch-all block, emit it. 1476224145Sdim if (catchBB->use_empty()) { 1477224145Sdim delete catchBB; 1478224145Sdim } else { 1479224145Sdim CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP(); 1480224145Sdim CGF.EmitBlock(catchBB); 1481210299Sed 1482224145Sdim llvm::Value *exn = 0; 1483210299Sed 1484224145Sdim // If there's a begin-catch function, call it. 1485224145Sdim if (BeginCatchFn) { 1486226633Sdim exn = CGF.getExceptionFromSlot(); 1487249423Sdim CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn); 1488224145Sdim } 1489210299Sed 1490224145Sdim // If we need to remember the exception pointer to rethrow later, do so. 1491224145Sdim if (SavedExnVar) { 1492226633Sdim if (!exn) exn = CGF.getExceptionFromSlot(); 1493224145Sdim CGF.Builder.CreateStore(exn, SavedExnVar); 1494224145Sdim } 1495210299Sed 1496224145Sdim // Tell the cleanups in the finally block that we're do this for EH. 1497224145Sdim CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar); 1498210299Sed 1499224145Sdim // Thread a jump through the finally cleanup. 1500224145Sdim CGF.EmitBranchThroughCleanup(RethrowDest); 1501210299Sed 1502224145Sdim CGF.Builder.restoreIP(savedIP); 1503224145Sdim } 1504210299Sed 1505224145Sdim // Finally, leave the @finally cleanup. 1506224145Sdim CGF.PopCleanupBlock(); 1507210299Sed} 1508210299Sed 1509249423Sdim/// In a terminate landing pad, should we use __clang__call_terminate 1510249423Sdim/// or just a naked call to std::terminate? 1511249423Sdim/// 1512249423Sdim/// __clang_call_terminate calls __cxa_begin_catch, which then allows 1513249423Sdim/// std::terminate to usefully report something about the 1514249423Sdim/// violating exception. 1515249423Sdimstatic bool useClangCallTerminate(CodeGenModule &CGM) { 1516249423Sdim // Only do this for Itanium-family ABIs in C++ mode. 1517249423Sdim return (CGM.getLangOpts().CPlusPlus && 1518249423Sdim CGM.getTarget().getCXXABI().isItaniumFamily()); 1519249423Sdim} 1520249423Sdim 1521249423Sdim/// Get or define the following function: 1522249423Sdim/// void @__clang_call_terminate(i8* %exn) nounwind noreturn 1523249423Sdim/// This code is used only in C++. 1524249423Sdimstatic llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) { 1525249423Sdim llvm::FunctionType *fnTy = 1526249423Sdim llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 1527249423Sdim llvm::Constant *fnRef = 1528249423Sdim CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate"); 1529249423Sdim 1530249423Sdim llvm::Function *fn = dyn_cast<llvm::Function>(fnRef); 1531249423Sdim if (fn && fn->empty()) { 1532249423Sdim fn->setDoesNotThrow(); 1533249423Sdim fn->setDoesNotReturn(); 1534249423Sdim 1535249423Sdim // What we really want is to massively penalize inlining without 1536249423Sdim // forbidding it completely. The difference between that and 1537249423Sdim // 'noinline' is negligible. 1538249423Sdim fn->addFnAttr(llvm::Attribute::NoInline); 1539249423Sdim 1540249423Sdim // Allow this function to be shared across translation units, but 1541249423Sdim // we don't want it to turn into an exported symbol. 1542249423Sdim fn->setLinkage(llvm::Function::LinkOnceODRLinkage); 1543249423Sdim fn->setVisibility(llvm::Function::HiddenVisibility); 1544249423Sdim 1545249423Sdim // Set up the function. 1546249423Sdim llvm::BasicBlock *entry = 1547249423Sdim llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn); 1548249423Sdim CGBuilderTy builder(entry); 1549249423Sdim 1550249423Sdim // Pull the exception pointer out of the parameter list. 1551249423Sdim llvm::Value *exn = &*fn->arg_begin(); 1552249423Sdim 1553249423Sdim // Call __cxa_begin_catch(exn). 1554249423Sdim llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn); 1555249423Sdim catchCall->setDoesNotThrow(); 1556249423Sdim catchCall->setCallingConv(CGM.getRuntimeCC()); 1557249423Sdim 1558249423Sdim // Call std::terminate(). 1559249423Sdim llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM)); 1560249423Sdim termCall->setDoesNotThrow(); 1561249423Sdim termCall->setDoesNotReturn(); 1562249423Sdim termCall->setCallingConv(CGM.getRuntimeCC()); 1563249423Sdim 1564249423Sdim // std::terminate cannot return. 1565249423Sdim builder.CreateUnreachable(); 1566249423Sdim } 1567249423Sdim 1568249423Sdim return fnRef; 1569249423Sdim} 1570249423Sdim 1571210299Sedllvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() { 1572210299Sed if (TerminateLandingPad) 1573210299Sed return TerminateLandingPad; 1574210299Sed 1575210299Sed CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP(); 1576210299Sed 1577210299Sed // This will get inserted at the end of the function. 1578210299Sed TerminateLandingPad = createBasicBlock("terminate.lpad"); 1579210299Sed Builder.SetInsertPoint(TerminateLandingPad); 1580210299Sed 1581210299Sed // Tell the backend that this is a landing pad. 1582234353Sdim const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts()); 1583226633Sdim llvm::LandingPadInst *LPadInst = 1584226633Sdim Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL), 1585226633Sdim getOpaquePersonalityFn(CGM, Personality), 0); 1586226633Sdim LPadInst->addClause(getCatchAllValue(*this)); 1587210299Sed 1588249423Sdim llvm::CallInst *terminateCall; 1589249423Sdim if (useClangCallTerminate(CGM)) { 1590249423Sdim // Extract out the exception pointer. 1591249423Sdim llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0); 1592249423Sdim terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn); 1593249423Sdim } else { 1594249423Sdim terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM)); 1595249423Sdim } 1596249423Sdim terminateCall->setDoesNotReturn(); 1597218893Sdim Builder.CreateUnreachable(); 1598200583Srdivacky 1599210299Sed // Restore the saved insertion state. 1600210299Sed Builder.restoreIP(SavedIP); 1601207619Srdivacky 1602210299Sed return TerminateLandingPad; 1603200583Srdivacky} 1604200583Srdivacky 1605200583Srdivackyllvm::BasicBlock *CodeGenFunction::getTerminateHandler() { 1606200583Srdivacky if (TerminateHandler) 1607200583Srdivacky return TerminateHandler; 1608200583Srdivacky 1609210299Sed CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP(); 1610200583Srdivacky 1611210299Sed // Set up the terminate handler. This block is inserted at the very 1612210299Sed // end of the function by FinishFunction. 1613200583Srdivacky TerminateHandler = createBasicBlock("terminate.handler"); 1614210299Sed Builder.SetInsertPoint(TerminateHandler); 1615249423Sdim llvm::CallInst *TerminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM)); 1616200583Srdivacky TerminateCall->setDoesNotReturn(); 1617200583Srdivacky Builder.CreateUnreachable(); 1618200583Srdivacky 1619207619Srdivacky // Restore the saved insertion state. 1620210299Sed Builder.restoreIP(SavedIP); 1621200583Srdivacky 1622200583Srdivacky return TerminateHandler; 1623200583Srdivacky} 1624210299Sed 1625243830Sdimllvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) { 1626226633Sdim if (EHResumeBlock) return EHResumeBlock; 1627210299Sed 1628212904Sdim CGBuilderTy::InsertPoint SavedIP = Builder.saveIP(); 1629210299Sed 1630212904Sdim // We emit a jump to a notional label at the outermost unwind state. 1631226633Sdim EHResumeBlock = createBasicBlock("eh.resume"); 1632226633Sdim Builder.SetInsertPoint(EHResumeBlock); 1633210299Sed 1634234353Sdim const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts()); 1635210299Sed 1636212904Sdim // This can always be a call because we necessarily didn't find 1637212904Sdim // anything on the EH stack which needs our help. 1638234353Sdim const char *RethrowName = Personality.CatchallRethrowFn; 1639243830Sdim if (RethrowName != 0 && !isCleanup) { 1640249423Sdim EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName), 1641249423Sdim getExceptionFromSlot()) 1642223017Sdim ->setDoesNotReturn(); 1643223017Sdim } else { 1644223017Sdim switch (CleanupHackLevel) { 1645223017Sdim case CHL_MandatoryCatchall: 1646223017Sdim // In mandatory-catchall mode, we need to use 1647223017Sdim // _Unwind_Resume_or_Rethrow, or whatever the personality's 1648223017Sdim // equivalent is. 1649249423Sdim EmitRuntimeCall(getUnwindResumeOrRethrowFn(), 1650249423Sdim getExceptionFromSlot()) 1651223017Sdim ->setDoesNotReturn(); 1652223017Sdim break; 1653223017Sdim case CHL_MandatoryCleanup: { 1654226633Sdim // In mandatory-cleanup mode, we should use 'resume'. 1655226633Sdim 1656226633Sdim // Recreate the landingpad's return value for the 'resume' instruction. 1657226633Sdim llvm::Value *Exn = getExceptionFromSlot(); 1658226633Sdim llvm::Value *Sel = getSelectorFromSlot(); 1659226633Sdim 1660226633Sdim llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), 1661226633Sdim Sel->getType(), NULL); 1662226633Sdim llvm::Value *LPadVal = llvm::UndefValue::get(LPadType); 1663226633Sdim LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val"); 1664226633Sdim LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val"); 1665226633Sdim 1666226633Sdim Builder.CreateResume(LPadVal); 1667226633Sdim Builder.restoreIP(SavedIP); 1668226633Sdim return EHResumeBlock; 1669223017Sdim } 1670223017Sdim case CHL_Ideal: 1671223017Sdim // In an idealized mode where we don't have to worry about the 1672223017Sdim // optimizer combining landing pads, we should just use 1673223017Sdim // _Unwind_Resume (or the personality's equivalent). 1674249423Sdim EmitRuntimeCall(getUnwindResumeFn(), getExceptionFromSlot()) 1675223017Sdim ->setDoesNotReturn(); 1676223017Sdim break; 1677223017Sdim } 1678223017Sdim } 1679223017Sdim 1680212904Sdim Builder.CreateUnreachable(); 1681210299Sed 1682212904Sdim Builder.restoreIP(SavedIP); 1683210299Sed 1684226633Sdim return EHResumeBlock; 1685210299Sed} 1686