1 //===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code dealing with C++ exception related code generation. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CGCXXABI.h" 16 #include "CGCleanup.h" 17 #include "CGObjCRuntime.h" 18 #include "TargetInfo.h" 19 #include "clang/AST/Mangle.h" 20 #include "clang/AST/StmtCXX.h" 21 #include "clang/AST/StmtObjC.h" 22 #include "clang/AST/StmtVisitor.h" 23 #include "llvm/IR/CallSite.h" 24 #include "llvm/IR/Intrinsics.h" 25 #include "llvm/IR/IntrinsicInst.h" 26 #include "llvm/Support/SaveAndRestore.h" 27 28 using namespace clang; 29 using namespace CodeGen; 30 31 static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) { 32 // void __cxa_free_exception(void *thrown_exception); 33 34 llvm::FunctionType *FTy = 35 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 36 37 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception"); 38 } 39 40 static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) { 41 // void __cxa_call_unexpected(void *thrown_exception); 42 43 llvm::FunctionType *FTy = 44 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 45 46 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected"); 47 } 48 49 llvm::Constant *CodeGenModule::getTerminateFn() { 50 // void __terminate(); 51 52 llvm::FunctionType *FTy = 53 llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false); 54 55 StringRef name; 56 57 // In C++, use std::terminate(). 58 if (getLangOpts().CPlusPlus && 59 getTarget().getCXXABI().isItaniumFamily()) { 60 name = "_ZSt9terminatev"; 61 } else if (getLangOpts().CPlusPlus && 62 getTarget().getCXXABI().isMicrosoft()) { 63 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 64 name = "__std_terminate"; 65 else 66 name = "\01?terminate@@YAXXZ"; 67 } else if (getLangOpts().ObjC1 && 68 getLangOpts().ObjCRuntime.hasTerminate()) 69 name = "objc_terminate"; 70 else 71 name = "abort"; 72 return CreateRuntimeFunction(FTy, name); 73 } 74 75 static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM, 76 StringRef Name) { 77 llvm::FunctionType *FTy = 78 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 79 80 return CGM.CreateRuntimeFunction(FTy, Name); 81 } 82 83 namespace { 84 /// The exceptions personality for a function. 85 struct EHPersonality { 86 const char *PersonalityFn; 87 88 // If this is non-null, this personality requires a non-standard 89 // function for rethrowing an exception after a catchall cleanup. 90 // This function must have prototype void(void*). 91 const char *CatchallRethrowFn; 92 93 static const EHPersonality &get(CodeGenModule &CGM, 94 const FunctionDecl *FD); 95 static const EHPersonality &get(CodeGenFunction &CGF) { 96 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl)); 97 } 98 99 static const EHPersonality GNU_C; 100 static const EHPersonality GNU_C_SJLJ; 101 static const EHPersonality GNU_C_SEH; 102 static const EHPersonality GNU_ObjC; 103 static const EHPersonality GNUstep_ObjC; 104 static const EHPersonality GNU_ObjCXX; 105 static const EHPersonality NeXT_ObjC; 106 static const EHPersonality GNU_CPlusPlus; 107 static const EHPersonality GNU_CPlusPlus_SJLJ; 108 static const EHPersonality GNU_CPlusPlus_SEH; 109 static const EHPersonality MSVC_except_handler; 110 static const EHPersonality MSVC_C_specific_handler; 111 static const EHPersonality MSVC_CxxFrameHandler3; 112 }; 113 } 114 115 const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr }; 116 const EHPersonality 117 EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr }; 118 const EHPersonality 119 EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr }; 120 const EHPersonality 121 EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr }; 122 const EHPersonality 123 EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr }; 124 const EHPersonality 125 EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr }; 126 const EHPersonality 127 EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr }; 128 const EHPersonality 129 EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"}; 130 const EHPersonality 131 EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr }; 132 const EHPersonality 133 EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr }; 134 const EHPersonality 135 EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr }; 136 const EHPersonality 137 EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr }; 138 const EHPersonality 139 EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr }; 140 141 /// On Win64, use libgcc's SEH personality function. We fall back to dwarf on 142 /// other platforms, unless the user asked for SjLj exceptions. 143 static bool useLibGCCSEHPersonality(const llvm::Triple &T) { 144 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64; 145 } 146 147 static const EHPersonality &getCPersonality(const llvm::Triple &T, 148 const LangOptions &L) { 149 if (L.SjLjExceptions) 150 return EHPersonality::GNU_C_SJLJ; 151 else if (useLibGCCSEHPersonality(T)) 152 return EHPersonality::GNU_C_SEH; 153 return EHPersonality::GNU_C; 154 } 155 156 static const EHPersonality &getObjCPersonality(const llvm::Triple &T, 157 const LangOptions &L) { 158 switch (L.ObjCRuntime.getKind()) { 159 case ObjCRuntime::FragileMacOSX: 160 return getCPersonality(T, L); 161 case ObjCRuntime::MacOSX: 162 case ObjCRuntime::iOS: 163 return EHPersonality::NeXT_ObjC; 164 case ObjCRuntime::GNUstep: 165 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7)) 166 return EHPersonality::GNUstep_ObjC; 167 // fallthrough 168 case ObjCRuntime::GCC: 169 case ObjCRuntime::ObjFW: 170 return EHPersonality::GNU_ObjC; 171 } 172 llvm_unreachable("bad runtime kind"); 173 } 174 175 static const EHPersonality &getCXXPersonality(const llvm::Triple &T, 176 const LangOptions &L) { 177 if (L.SjLjExceptions) 178 return EHPersonality::GNU_CPlusPlus_SJLJ; 179 else if (useLibGCCSEHPersonality(T)) 180 return EHPersonality::GNU_CPlusPlus_SEH; 181 return EHPersonality::GNU_CPlusPlus; 182 } 183 184 /// Determines the personality function to use when both C++ 185 /// and Objective-C exceptions are being caught. 186 static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T, 187 const LangOptions &L) { 188 switch (L.ObjCRuntime.getKind()) { 189 // The ObjC personality defers to the C++ personality for non-ObjC 190 // handlers. Unlike the C++ case, we use the same personality 191 // function on targets using (backend-driven) SJLJ EH. 192 case ObjCRuntime::MacOSX: 193 case ObjCRuntime::iOS: 194 return EHPersonality::NeXT_ObjC; 195 196 // In the fragile ABI, just use C++ exception handling and hope 197 // they're not doing crazy exception mixing. 198 case ObjCRuntime::FragileMacOSX: 199 return getCXXPersonality(T, L); 200 201 // The GCC runtime's personality function inherently doesn't support 202 // mixed EH. Use the C++ personality just to avoid returning null. 203 case ObjCRuntime::GCC: 204 case ObjCRuntime::ObjFW: // XXX: this will change soon 205 return EHPersonality::GNU_ObjC; 206 case ObjCRuntime::GNUstep: 207 return EHPersonality::GNU_ObjCXX; 208 } 209 llvm_unreachable("bad runtime kind"); 210 } 211 212 static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) { 213 if (T.getArch() == llvm::Triple::x86) 214 return EHPersonality::MSVC_except_handler; 215 return EHPersonality::MSVC_C_specific_handler; 216 } 217 218 const EHPersonality &EHPersonality::get(CodeGenModule &CGM, 219 const FunctionDecl *FD) { 220 const llvm::Triple &T = CGM.getTarget().getTriple(); 221 const LangOptions &L = CGM.getLangOpts(); 222 223 // Try to pick a personality function that is compatible with MSVC if we're 224 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports 225 // the GCC-style personality function. 226 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) { 227 if (L.SjLjExceptions) 228 return EHPersonality::GNU_CPlusPlus_SJLJ; 229 else if (FD && FD->usesSEHTry()) 230 return getSEHPersonalityMSVC(T); 231 else 232 return EHPersonality::MSVC_CxxFrameHandler3; 233 } 234 235 if (L.CPlusPlus && L.ObjC1) 236 return getObjCXXPersonality(T, L); 237 else if (L.CPlusPlus) 238 return getCXXPersonality(T, L); 239 else if (L.ObjC1) 240 return getObjCPersonality(T, L); 241 else 242 return getCPersonality(T, L); 243 } 244 245 static llvm::Constant *getPersonalityFn(CodeGenModule &CGM, 246 const EHPersonality &Personality) { 247 llvm::Constant *Fn = 248 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true), 249 Personality.PersonalityFn); 250 return Fn; 251 } 252 253 static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM, 254 const EHPersonality &Personality) { 255 llvm::Constant *Fn = getPersonalityFn(CGM, Personality); 256 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy); 257 } 258 259 /// Check whether a personality function could reasonably be swapped 260 /// for a C++ personality function. 261 static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) { 262 for (llvm::User *U : Fn->users()) { 263 // Conditionally white-list bitcasts. 264 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) { 265 if (CE->getOpcode() != llvm::Instruction::BitCast) return false; 266 if (!PersonalityHasOnlyCXXUses(CE)) 267 return false; 268 continue; 269 } 270 271 // Otherwise, it has to be a landingpad instruction. 272 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U); 273 if (!LPI) return false; 274 275 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) { 276 // Look for something that would've been returned by the ObjC 277 // runtime's GetEHType() method. 278 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts(); 279 if (LPI->isCatch(I)) { 280 // Check if the catch value has the ObjC prefix. 281 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val)) 282 // ObjC EH selector entries are always global variables with 283 // names starting like this. 284 if (GV->getName().startswith("OBJC_EHTYPE")) 285 return false; 286 } else { 287 // Check if any of the filter values have the ObjC prefix. 288 llvm::Constant *CVal = cast<llvm::Constant>(Val); 289 for (llvm::User::op_iterator 290 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) { 291 if (llvm::GlobalVariable *GV = 292 cast<llvm::GlobalVariable>((*II)->stripPointerCasts())) 293 // ObjC EH selector entries are always global variables with 294 // names starting like this. 295 if (GV->getName().startswith("OBJC_EHTYPE")) 296 return false; 297 } 298 } 299 } 300 } 301 302 return true; 303 } 304 305 /// Try to use the C++ personality function in ObjC++. Not doing this 306 /// can cause some incompatibilities with gcc, which is more 307 /// aggressive about only using the ObjC++ personality in a function 308 /// when it really needs it. 309 void CodeGenModule::SimplifyPersonality() { 310 // If we're not in ObjC++ -fexceptions, there's nothing to do. 311 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions) 312 return; 313 314 // Both the problem this endeavors to fix and the way the logic 315 // above works is specific to the NeXT runtime. 316 if (!LangOpts.ObjCRuntime.isNeXTFamily()) 317 return; 318 319 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr); 320 const EHPersonality &CXX = 321 getCXXPersonality(getTarget().getTriple(), LangOpts); 322 if (&ObjCXX == &CXX) 323 return; 324 325 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 && 326 "Different EHPersonalities using the same personality function."); 327 328 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn); 329 330 // Nothing to do if it's unused. 331 if (!Fn || Fn->use_empty()) return; 332 333 // Can't do the optimization if it has non-C++ uses. 334 if (!PersonalityHasOnlyCXXUses(Fn)) return; 335 336 // Create the C++ personality function and kill off the old 337 // function. 338 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX); 339 340 // This can happen if the user is screwing with us. 341 if (Fn->getType() != CXXFn->getType()) return; 342 343 Fn->replaceAllUsesWith(CXXFn); 344 Fn->eraseFromParent(); 345 } 346 347 /// Returns the value to inject into a selector to indicate the 348 /// presence of a catch-all. 349 static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) { 350 // Possibly we should use @llvm.eh.catch.all.value here. 351 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy); 352 } 353 354 namespace { 355 /// A cleanup to free the exception object if its initialization 356 /// throws. 357 struct FreeException : EHScopeStack::Cleanup { 358 llvm::Value *exn; 359 FreeException(llvm::Value *exn) : exn(exn) {} 360 void Emit(CodeGenFunction &CGF, Flags flags) override { 361 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn); 362 } 363 }; 364 } 365 366 // Emits an exception expression into the given location. This 367 // differs from EmitAnyExprToMem only in that, if a final copy-ctor 368 // call is required, an exception within that copy ctor causes 369 // std::terminate to be invoked. 370 void CodeGenFunction::EmitAnyExprToExn(const Expr *e, llvm::Value *addr) { 371 // Make sure the exception object is cleaned up if there's an 372 // exception during initialization. 373 pushFullExprCleanup<FreeException>(EHCleanup, addr); 374 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin(); 375 376 // __cxa_allocate_exception returns a void*; we need to cast this 377 // to the appropriate type for the object. 378 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo(); 379 llvm::Value *typedAddr = Builder.CreateBitCast(addr, ty); 380 381 // FIXME: this isn't quite right! If there's a final unelided call 382 // to a copy constructor, then according to [except.terminate]p1 we 383 // must call std::terminate() if that constructor throws, because 384 // technically that copy occurs after the exception expression is 385 // evaluated but before the exception is caught. But the best way 386 // to handle that is to teach EmitAggExpr to do the final copy 387 // differently if it can't be elided. 388 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(), 389 /*IsInit*/ true); 390 391 // Deactivate the cleanup block. 392 DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr)); 393 } 394 395 llvm::Value *CodeGenFunction::getExceptionSlot() { 396 if (!ExceptionSlot) 397 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot"); 398 return ExceptionSlot; 399 } 400 401 llvm::Value *CodeGenFunction::getEHSelectorSlot() { 402 if (!EHSelectorSlot) 403 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot"); 404 return EHSelectorSlot; 405 } 406 407 llvm::Value *CodeGenFunction::getExceptionFromSlot() { 408 return Builder.CreateLoad(getExceptionSlot(), "exn"); 409 } 410 411 llvm::Value *CodeGenFunction::getSelectorFromSlot() { 412 return Builder.CreateLoad(getEHSelectorSlot(), "sel"); 413 } 414 415 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E, 416 bool KeepInsertionPoint) { 417 if (const Expr *SubExpr = E->getSubExpr()) { 418 QualType ThrowType = SubExpr->getType(); 419 if (ThrowType->isObjCObjectPointerType()) { 420 const Stmt *ThrowStmt = E->getSubExpr(); 421 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt)); 422 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false); 423 } else { 424 CGM.getCXXABI().emitThrow(*this, E); 425 } 426 } else { 427 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true); 428 } 429 430 // throw is an expression, and the expression emitters expect us 431 // to leave ourselves at a valid insertion point. 432 if (KeepInsertionPoint) 433 EmitBlock(createBasicBlock("throw.cont")); 434 } 435 436 void CodeGenFunction::EmitStartEHSpec(const Decl *D) { 437 if (!CGM.getLangOpts().CXXExceptions) 438 return; 439 440 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D); 441 if (!FD) { 442 // Check if CapturedDecl is nothrow and create terminate scope for it. 443 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) { 444 if (CD->isNothrow()) 445 EHStack.pushTerminate(); 446 } 447 return; 448 } 449 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>(); 450 if (!Proto) 451 return; 452 453 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 454 if (isNoexceptExceptionSpec(EST)) { 455 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) { 456 // noexcept functions are simple terminate scopes. 457 EHStack.pushTerminate(); 458 } 459 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) { 460 // TODO: Revisit exception specifications for the MS ABI. There is a way to 461 // encode these in an object file but MSVC doesn't do anything with it. 462 if (getTarget().getCXXABI().isMicrosoft()) 463 return; 464 unsigned NumExceptions = Proto->getNumExceptions(); 465 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions); 466 467 for (unsigned I = 0; I != NumExceptions; ++I) { 468 QualType Ty = Proto->getExceptionType(I); 469 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType(); 470 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType, 471 /*ForEH=*/true); 472 Filter->setFilter(I, EHType); 473 } 474 } 475 } 476 477 /// Emit the dispatch block for a filter scope if necessary. 478 static void emitFilterDispatchBlock(CodeGenFunction &CGF, 479 EHFilterScope &filterScope) { 480 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock(); 481 if (!dispatchBlock) return; 482 if (dispatchBlock->use_empty()) { 483 delete dispatchBlock; 484 return; 485 } 486 487 CGF.EmitBlockAfterUses(dispatchBlock); 488 489 // If this isn't a catch-all filter, we need to check whether we got 490 // here because the filter triggered. 491 if (filterScope.getNumFilters()) { 492 // Load the selector value. 493 llvm::Value *selector = CGF.getSelectorFromSlot(); 494 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected"); 495 496 llvm::Value *zero = CGF.Builder.getInt32(0); 497 llvm::Value *failsFilter = 498 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails"); 499 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, 500 CGF.getEHResumeBlock(false)); 501 502 CGF.EmitBlock(unexpectedBB); 503 } 504 505 // Call __cxa_call_unexpected. This doesn't need to be an invoke 506 // because __cxa_call_unexpected magically filters exceptions 507 // according to the last landing pad the exception was thrown 508 // into. Seriously. 509 llvm::Value *exn = CGF.getExceptionFromSlot(); 510 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn) 511 ->setDoesNotReturn(); 512 CGF.Builder.CreateUnreachable(); 513 } 514 515 void CodeGenFunction::EmitEndEHSpec(const Decl *D) { 516 if (!CGM.getLangOpts().CXXExceptions) 517 return; 518 519 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D); 520 if (!FD) { 521 // Check if CapturedDecl is nothrow and pop terminate scope for it. 522 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) { 523 if (CD->isNothrow()) 524 EHStack.popTerminate(); 525 } 526 return; 527 } 528 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>(); 529 if (!Proto) 530 return; 531 532 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 533 if (isNoexceptExceptionSpec(EST)) { 534 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) { 535 EHStack.popTerminate(); 536 } 537 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) { 538 // TODO: Revisit exception specifications for the MS ABI. There is a way to 539 // encode these in an object file but MSVC doesn't do anything with it. 540 if (getTarget().getCXXABI().isMicrosoft()) 541 return; 542 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin()); 543 emitFilterDispatchBlock(*this, filterScope); 544 EHStack.popFilter(); 545 } 546 } 547 548 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) { 549 EnterCXXTryStmt(S); 550 EmitStmt(S.getTryBlock()); 551 ExitCXXTryStmt(S); 552 } 553 554 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) { 555 unsigned NumHandlers = S.getNumHandlers(); 556 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers); 557 558 for (unsigned I = 0; I != NumHandlers; ++I) { 559 const CXXCatchStmt *C = S.getHandler(I); 560 561 llvm::BasicBlock *Handler = createBasicBlock("catch"); 562 if (C->getExceptionDecl()) { 563 // FIXME: Dropping the reference type on the type into makes it 564 // impossible to correctly implement catch-by-reference 565 // semantics for pointers. Unfortunately, this is what all 566 // existing compilers do, and it's not clear that the standard 567 // personality routine is capable of doing this right. See C++ DR 388: 568 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388 569 Qualifiers CaughtTypeQuals; 570 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType( 571 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals); 572 573 llvm::Constant *TypeInfo = nullptr; 574 if (CaughtType->isObjCObjectPointerType()) 575 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType); 576 else 577 TypeInfo = 578 CGM.getAddrOfCXXCatchHandlerType(CaughtType, C->getCaughtType()); 579 CatchScope->setHandler(I, TypeInfo, Handler); 580 } else { 581 // No exception decl indicates '...', a catch-all. 582 CatchScope->setCatchAllHandler(I, Handler); 583 } 584 } 585 } 586 587 llvm::BasicBlock * 588 CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) { 589 // The dispatch block for the end of the scope chain is a block that 590 // just resumes unwinding. 591 if (si == EHStack.stable_end()) 592 return getEHResumeBlock(true); 593 594 // Otherwise, we should look at the actual scope. 595 EHScope &scope = *EHStack.find(si); 596 597 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock(); 598 if (!dispatchBlock) { 599 switch (scope.getKind()) { 600 case EHScope::Catch: { 601 // Apply a special case to a single catch-all. 602 EHCatchScope &catchScope = cast<EHCatchScope>(scope); 603 if (catchScope.getNumHandlers() == 1 && 604 catchScope.getHandler(0).isCatchAll()) { 605 dispatchBlock = catchScope.getHandler(0).Block; 606 607 // Otherwise, make a dispatch block. 608 } else { 609 dispatchBlock = createBasicBlock("catch.dispatch"); 610 } 611 break; 612 } 613 614 case EHScope::Cleanup: 615 dispatchBlock = createBasicBlock("ehcleanup"); 616 break; 617 618 case EHScope::Filter: 619 dispatchBlock = createBasicBlock("filter.dispatch"); 620 break; 621 622 case EHScope::Terminate: 623 dispatchBlock = getTerminateHandler(); 624 break; 625 } 626 scope.setCachedEHDispatchBlock(dispatchBlock); 627 } 628 return dispatchBlock; 629 } 630 631 /// Check whether this is a non-EH scope, i.e. a scope which doesn't 632 /// affect exception handling. Currently, the only non-EH scopes are 633 /// normal-only cleanup scopes. 634 static bool isNonEHScope(const EHScope &S) { 635 switch (S.getKind()) { 636 case EHScope::Cleanup: 637 return !cast<EHCleanupScope>(S).isEHCleanup(); 638 case EHScope::Filter: 639 case EHScope::Catch: 640 case EHScope::Terminate: 641 return false; 642 } 643 644 llvm_unreachable("Invalid EHScope Kind!"); 645 } 646 647 llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() { 648 assert(EHStack.requiresLandingPad()); 649 assert(!EHStack.empty()); 650 651 // If exceptions are disabled, there are usually no landingpads. However, when 652 // SEH is enabled, functions using SEH still get landingpads. 653 const LangOptions &LO = CGM.getLangOpts(); 654 if (!LO.Exceptions) { 655 if (!LO.Borland && !LO.MicrosoftExt) 656 return nullptr; 657 if (!currentFunctionUsesSEHTry()) 658 return nullptr; 659 } 660 661 // Check the innermost scope for a cached landing pad. If this is 662 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad. 663 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad(); 664 if (LP) return LP; 665 666 // Build the landing pad for this scope. 667 LP = EmitLandingPad(); 668 assert(LP); 669 670 // Cache the landing pad on the innermost scope. If this is a 671 // non-EH scope, cache the landing pad on the enclosing scope, too. 672 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) { 673 ir->setCachedLandingPad(LP); 674 if (!isNonEHScope(*ir)) break; 675 } 676 677 return LP; 678 } 679 680 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() { 681 assert(EHStack.requiresLandingPad()); 682 683 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope()); 684 switch (innermostEHScope.getKind()) { 685 case EHScope::Terminate: 686 return getTerminateLandingPad(); 687 688 case EHScope::Catch: 689 case EHScope::Cleanup: 690 case EHScope::Filter: 691 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad()) 692 return lpad; 693 } 694 695 // Save the current IR generation state. 696 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP(); 697 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation); 698 699 const EHPersonality &personality = EHPersonality::get(*this); 700 701 // Create and configure the landing pad. 702 llvm::BasicBlock *lpad = createBasicBlock("lpad"); 703 EmitBlock(lpad); 704 705 llvm::LandingPadInst *LPadInst = 706 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 707 getOpaquePersonalityFn(CGM, personality), 0); 708 709 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0); 710 Builder.CreateStore(LPadExn, getExceptionSlot()); 711 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1); 712 Builder.CreateStore(LPadSel, getEHSelectorSlot()); 713 714 // Save the exception pointer. It's safe to use a single exception 715 // pointer per function because EH cleanups can never have nested 716 // try/catches. 717 // Build the landingpad instruction. 718 719 // Accumulate all the handlers in scope. 720 bool hasCatchAll = false; 721 bool hasCleanup = false; 722 bool hasFilter = false; 723 SmallVector<llvm::Value*, 4> filterTypes; 724 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes; 725 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E; 726 ++I) { 727 728 switch (I->getKind()) { 729 case EHScope::Cleanup: 730 // If we have a cleanup, remember that. 731 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup()); 732 continue; 733 734 case EHScope::Filter: { 735 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack"); 736 assert(!hasCatchAll && "EH filter reached after catch-all"); 737 738 // Filter scopes get added to the landingpad in weird ways. 739 EHFilterScope &filter = cast<EHFilterScope>(*I); 740 hasFilter = true; 741 742 // Add all the filter values. 743 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i) 744 filterTypes.push_back(filter.getFilter(i)); 745 goto done; 746 } 747 748 case EHScope::Terminate: 749 // Terminate scopes are basically catch-alls. 750 assert(!hasCatchAll); 751 hasCatchAll = true; 752 goto done; 753 754 case EHScope::Catch: 755 break; 756 } 757 758 EHCatchScope &catchScope = cast<EHCatchScope>(*I); 759 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) { 760 EHCatchScope::Handler handler = catchScope.getHandler(hi); 761 762 // If this is a catch-all, register that and abort. 763 if (!handler.Type) { 764 assert(!hasCatchAll); 765 hasCatchAll = true; 766 goto done; 767 } 768 769 // Check whether we already have a handler for this type. 770 if (catchTypes.insert(handler.Type).second) 771 // If not, add it directly to the landingpad. 772 LPadInst->addClause(handler.Type); 773 } 774 } 775 776 done: 777 // If we have a catch-all, add null to the landingpad. 778 assert(!(hasCatchAll && hasFilter)); 779 if (hasCatchAll) { 780 LPadInst->addClause(getCatchAllValue(*this)); 781 782 // If we have an EH filter, we need to add those handlers in the 783 // right place in the landingpad, which is to say, at the end. 784 } else if (hasFilter) { 785 // Create a filter expression: a constant array indicating which filter 786 // types there are. The personality routine only lands here if the filter 787 // doesn't match. 788 SmallVector<llvm::Constant*, 8> Filters; 789 llvm::ArrayType *AType = 790 llvm::ArrayType::get(!filterTypes.empty() ? 791 filterTypes[0]->getType() : Int8PtrTy, 792 filterTypes.size()); 793 794 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i) 795 Filters.push_back(cast<llvm::Constant>(filterTypes[i])); 796 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters); 797 LPadInst->addClause(FilterArray); 798 799 // Also check whether we need a cleanup. 800 if (hasCleanup) 801 LPadInst->setCleanup(true); 802 803 // Otherwise, signal that we at least have cleanups. 804 } else if (hasCleanup) { 805 LPadInst->setCleanup(true); 806 } 807 808 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) && 809 "landingpad instruction has no clauses!"); 810 811 // Tell the backend how to generate the landing pad. 812 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope())); 813 814 // Restore the old IR generation state. 815 Builder.restoreIP(savedIP); 816 817 return lpad; 818 } 819 820 /// Emit the structure of the dispatch block for the given catch scope. 821 /// It is an invariant that the dispatch block already exists. 822 static void emitCatchDispatchBlock(CodeGenFunction &CGF, 823 EHCatchScope &catchScope) { 824 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock(); 825 assert(dispatchBlock); 826 827 // If there's only a single catch-all, getEHDispatchBlock returned 828 // that catch-all as the dispatch block. 829 if (catchScope.getNumHandlers() == 1 && 830 catchScope.getHandler(0).isCatchAll()) { 831 assert(dispatchBlock == catchScope.getHandler(0).Block); 832 return; 833 } 834 835 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP(); 836 CGF.EmitBlockAfterUses(dispatchBlock); 837 838 // Select the right handler. 839 llvm::Value *llvm_eh_typeid_for = 840 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for); 841 842 // Load the selector value. 843 llvm::Value *selector = CGF.getSelectorFromSlot(); 844 845 // Test against each of the exception types we claim to catch. 846 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) { 847 assert(i < e && "ran off end of handlers!"); 848 const EHCatchScope::Handler &handler = catchScope.getHandler(i); 849 850 llvm::Value *typeValue = handler.Type; 851 assert(typeValue && "fell into catch-all case!"); 852 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy); 853 854 // Figure out the next block. 855 bool nextIsEnd; 856 llvm::BasicBlock *nextBlock; 857 858 // If this is the last handler, we're at the end, and the next 859 // block is the block for the enclosing EH scope. 860 if (i + 1 == e) { 861 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope()); 862 nextIsEnd = true; 863 864 // If the next handler is a catch-all, we're at the end, and the 865 // next block is that handler. 866 } else if (catchScope.getHandler(i+1).isCatchAll()) { 867 nextBlock = catchScope.getHandler(i+1).Block; 868 nextIsEnd = true; 869 870 // Otherwise, we're not at the end and we need a new block. 871 } else { 872 nextBlock = CGF.createBasicBlock("catch.fallthrough"); 873 nextIsEnd = false; 874 } 875 876 // Figure out the catch type's index in the LSDA's type table. 877 llvm::CallInst *typeIndex = 878 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue); 879 typeIndex->setDoesNotThrow(); 880 881 llvm::Value *matchesTypeIndex = 882 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches"); 883 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock); 884 885 // If the next handler is a catch-all, we're completely done. 886 if (nextIsEnd) { 887 CGF.Builder.restoreIP(savedIP); 888 return; 889 } 890 // Otherwise we need to emit and continue at that block. 891 CGF.EmitBlock(nextBlock); 892 } 893 } 894 895 void CodeGenFunction::popCatchScope() { 896 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin()); 897 if (catchScope.hasEHBranches()) 898 emitCatchDispatchBlock(*this, catchScope); 899 EHStack.popCatch(); 900 } 901 902 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) { 903 unsigned NumHandlers = S.getNumHandlers(); 904 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin()); 905 assert(CatchScope.getNumHandlers() == NumHandlers); 906 907 // If the catch was not required, bail out now. 908 if (!CatchScope.hasEHBranches()) { 909 CatchScope.clearHandlerBlocks(); 910 EHStack.popCatch(); 911 return; 912 } 913 914 // Emit the structure of the EH dispatch for this catch. 915 emitCatchDispatchBlock(*this, CatchScope); 916 917 // Copy the handler blocks off before we pop the EH stack. Emitting 918 // the handlers might scribble on this memory. 919 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers); 920 memcpy(Handlers.data(), CatchScope.begin(), 921 NumHandlers * sizeof(EHCatchScope::Handler)); 922 923 EHStack.popCatch(); 924 925 // The fall-through block. 926 llvm::BasicBlock *ContBB = createBasicBlock("try.cont"); 927 928 // We just emitted the body of the try; jump to the continue block. 929 if (HaveInsertPoint()) 930 Builder.CreateBr(ContBB); 931 932 // Determine if we need an implicit rethrow for all these catch handlers; 933 // see the comment below. 934 bool doImplicitRethrow = false; 935 if (IsFnTryBlock) 936 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) || 937 isa<CXXConstructorDecl>(CurCodeDecl); 938 939 // Perversely, we emit the handlers backwards precisely because we 940 // want them to appear in source order. In all of these cases, the 941 // catch block will have exactly one predecessor, which will be a 942 // particular block in the catch dispatch. However, in the case of 943 // a catch-all, one of the dispatch blocks will branch to two 944 // different handlers, and EmitBlockAfterUses will cause the second 945 // handler to be moved before the first. 946 for (unsigned I = NumHandlers; I != 0; --I) { 947 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block; 948 EmitBlockAfterUses(CatchBlock); 949 950 // Catch the exception if this isn't a catch-all. 951 const CXXCatchStmt *C = S.getHandler(I-1); 952 953 // Enter a cleanup scope, including the catch variable and the 954 // end-catch. 955 RunCleanupsScope CatchScope(*this); 956 957 // Initialize the catch variable and set up the cleanups. 958 CGM.getCXXABI().emitBeginCatch(*this, C); 959 960 // Emit the PGO counter increment. 961 incrementProfileCounter(C); 962 963 // Perform the body of the catch. 964 EmitStmt(C->getHandlerBlock()); 965 966 // [except.handle]p11: 967 // The currently handled exception is rethrown if control 968 // reaches the end of a handler of the function-try-block of a 969 // constructor or destructor. 970 971 // It is important that we only do this on fallthrough and not on 972 // return. Note that it's illegal to put a return in a 973 // constructor function-try-block's catch handler (p14), so this 974 // really only applies to destructors. 975 if (doImplicitRethrow && HaveInsertPoint()) { 976 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false); 977 Builder.CreateUnreachable(); 978 Builder.ClearInsertionPoint(); 979 } 980 981 // Fall out through the catch cleanups. 982 CatchScope.ForceCleanup(); 983 984 // Branch out of the try. 985 if (HaveInsertPoint()) 986 Builder.CreateBr(ContBB); 987 } 988 989 EmitBlock(ContBB); 990 incrementProfileCounter(&S); 991 } 992 993 namespace { 994 struct CallEndCatchForFinally : EHScopeStack::Cleanup { 995 llvm::Value *ForEHVar; 996 llvm::Value *EndCatchFn; 997 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn) 998 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {} 999 1000 void Emit(CodeGenFunction &CGF, Flags flags) override { 1001 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch"); 1002 llvm::BasicBlock *CleanupContBB = 1003 CGF.createBasicBlock("finally.cleanup.cont"); 1004 1005 llvm::Value *ShouldEndCatch = 1006 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch"); 1007 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB); 1008 CGF.EmitBlock(EndCatchBB); 1009 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw 1010 CGF.EmitBlock(CleanupContBB); 1011 } 1012 }; 1013 1014 struct PerformFinally : EHScopeStack::Cleanup { 1015 const Stmt *Body; 1016 llvm::Value *ForEHVar; 1017 llvm::Value *EndCatchFn; 1018 llvm::Value *RethrowFn; 1019 llvm::Value *SavedExnVar; 1020 1021 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar, 1022 llvm::Value *EndCatchFn, 1023 llvm::Value *RethrowFn, llvm::Value *SavedExnVar) 1024 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn), 1025 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {} 1026 1027 void Emit(CodeGenFunction &CGF, Flags flags) override { 1028 // Enter a cleanup to call the end-catch function if one was provided. 1029 if (EndCatchFn) 1030 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup, 1031 ForEHVar, EndCatchFn); 1032 1033 // Save the current cleanup destination in case there are 1034 // cleanups in the finally block. 1035 llvm::Value *SavedCleanupDest = 1036 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(), 1037 "cleanup.dest.saved"); 1038 1039 // Emit the finally block. 1040 CGF.EmitStmt(Body); 1041 1042 // If the end of the finally is reachable, check whether this was 1043 // for EH. If so, rethrow. 1044 if (CGF.HaveInsertPoint()) { 1045 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow"); 1046 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont"); 1047 1048 llvm::Value *ShouldRethrow = 1049 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow"); 1050 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB); 1051 1052 CGF.EmitBlock(RethrowBB); 1053 if (SavedExnVar) { 1054 CGF.EmitRuntimeCallOrInvoke(RethrowFn, 1055 CGF.Builder.CreateLoad(SavedExnVar)); 1056 } else { 1057 CGF.EmitRuntimeCallOrInvoke(RethrowFn); 1058 } 1059 CGF.Builder.CreateUnreachable(); 1060 1061 CGF.EmitBlock(ContBB); 1062 1063 // Restore the cleanup destination. 1064 CGF.Builder.CreateStore(SavedCleanupDest, 1065 CGF.getNormalCleanupDestSlot()); 1066 } 1067 1068 // Leave the end-catch cleanup. As an optimization, pretend that 1069 // the fallthrough path was inaccessible; we've dynamically proven 1070 // that we're not in the EH case along that path. 1071 if (EndCatchFn) { 1072 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP(); 1073 CGF.PopCleanupBlock(); 1074 CGF.Builder.restoreIP(SavedIP); 1075 } 1076 1077 // Now make sure we actually have an insertion point or the 1078 // cleanup gods will hate us. 1079 CGF.EnsureInsertPoint(); 1080 } 1081 }; 1082 } 1083 1084 /// Enters a finally block for an implementation using zero-cost 1085 /// exceptions. This is mostly general, but hard-codes some 1086 /// language/ABI-specific behavior in the catch-all sections. 1087 void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF, 1088 const Stmt *body, 1089 llvm::Constant *beginCatchFn, 1090 llvm::Constant *endCatchFn, 1091 llvm::Constant *rethrowFn) { 1092 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) && 1093 "begin/end catch functions not paired"); 1094 assert(rethrowFn && "rethrow function is required"); 1095 1096 BeginCatchFn = beginCatchFn; 1097 1098 // The rethrow function has one of the following two types: 1099 // void (*)() 1100 // void (*)(void*) 1101 // In the latter case we need to pass it the exception object. 1102 // But we can't use the exception slot because the @finally might 1103 // have a landing pad (which would overwrite the exception slot). 1104 llvm::FunctionType *rethrowFnTy = 1105 cast<llvm::FunctionType>( 1106 cast<llvm::PointerType>(rethrowFn->getType())->getElementType()); 1107 SavedExnVar = nullptr; 1108 if (rethrowFnTy->getNumParams()) 1109 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn"); 1110 1111 // A finally block is a statement which must be executed on any edge 1112 // out of a given scope. Unlike a cleanup, the finally block may 1113 // contain arbitrary control flow leading out of itself. In 1114 // addition, finally blocks should always be executed, even if there 1115 // are no catch handlers higher on the stack. Therefore, we 1116 // surround the protected scope with a combination of a normal 1117 // cleanup (to catch attempts to break out of the block via normal 1118 // control flow) and an EH catch-all (semantically "outside" any try 1119 // statement to which the finally block might have been attached). 1120 // The finally block itself is generated in the context of a cleanup 1121 // which conditionally leaves the catch-all. 1122 1123 // Jump destination for performing the finally block on an exception 1124 // edge. We'll never actually reach this block, so unreachable is 1125 // fine. 1126 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock()); 1127 1128 // Whether the finally block is being executed for EH purposes. 1129 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh"); 1130 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar); 1131 1132 // Enter a normal cleanup which will perform the @finally block. 1133 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body, 1134 ForEHVar, endCatchFn, 1135 rethrowFn, SavedExnVar); 1136 1137 // Enter a catch-all scope. 1138 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall"); 1139 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1); 1140 catchScope->setCatchAllHandler(0, catchBB); 1141 } 1142 1143 void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) { 1144 // Leave the finally catch-all. 1145 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin()); 1146 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block; 1147 1148 CGF.popCatchScope(); 1149 1150 // If there are any references to the catch-all block, emit it. 1151 if (catchBB->use_empty()) { 1152 delete catchBB; 1153 } else { 1154 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP(); 1155 CGF.EmitBlock(catchBB); 1156 1157 llvm::Value *exn = nullptr; 1158 1159 // If there's a begin-catch function, call it. 1160 if (BeginCatchFn) { 1161 exn = CGF.getExceptionFromSlot(); 1162 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn); 1163 } 1164 1165 // If we need to remember the exception pointer to rethrow later, do so. 1166 if (SavedExnVar) { 1167 if (!exn) exn = CGF.getExceptionFromSlot(); 1168 CGF.Builder.CreateStore(exn, SavedExnVar); 1169 } 1170 1171 // Tell the cleanups in the finally block that we're do this for EH. 1172 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar); 1173 1174 // Thread a jump through the finally cleanup. 1175 CGF.EmitBranchThroughCleanup(RethrowDest); 1176 1177 CGF.Builder.restoreIP(savedIP); 1178 } 1179 1180 // Finally, leave the @finally cleanup. 1181 CGF.PopCleanupBlock(); 1182 } 1183 1184 llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() { 1185 if (TerminateLandingPad) 1186 return TerminateLandingPad; 1187 1188 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP(); 1189 1190 // This will get inserted at the end of the function. 1191 TerminateLandingPad = createBasicBlock("terminate.lpad"); 1192 Builder.SetInsertPoint(TerminateLandingPad); 1193 1194 // Tell the backend that this is a landing pad. 1195 const EHPersonality &Personality = EHPersonality::get(*this); 1196 llvm::LandingPadInst *LPadInst = 1197 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 1198 getOpaquePersonalityFn(CGM, Personality), 0); 1199 LPadInst->addClause(getCatchAllValue(*this)); 1200 1201 llvm::Value *Exn = 0; 1202 if (getLangOpts().CPlusPlus) 1203 Exn = Builder.CreateExtractValue(LPadInst, 0); 1204 llvm::CallInst *terminateCall = 1205 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn); 1206 terminateCall->setDoesNotReturn(); 1207 Builder.CreateUnreachable(); 1208 1209 // Restore the saved insertion state. 1210 Builder.restoreIP(SavedIP); 1211 1212 return TerminateLandingPad; 1213 } 1214 1215 llvm::BasicBlock *CodeGenFunction::getTerminateHandler() { 1216 if (TerminateHandler) 1217 return TerminateHandler; 1218 1219 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP(); 1220 1221 // Set up the terminate handler. This block is inserted at the very 1222 // end of the function by FinishFunction. 1223 TerminateHandler = createBasicBlock("terminate.handler"); 1224 Builder.SetInsertPoint(TerminateHandler); 1225 llvm::Value *Exn = 0; 1226 if (getLangOpts().CPlusPlus) 1227 Exn = getExceptionFromSlot(); 1228 llvm::CallInst *terminateCall = 1229 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn); 1230 terminateCall->setDoesNotReturn(); 1231 Builder.CreateUnreachable(); 1232 1233 // Restore the saved insertion state. 1234 Builder.restoreIP(SavedIP); 1235 1236 return TerminateHandler; 1237 } 1238 1239 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) { 1240 if (EHResumeBlock) return EHResumeBlock; 1241 1242 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP(); 1243 1244 // We emit a jump to a notional label at the outermost unwind state. 1245 EHResumeBlock = createBasicBlock("eh.resume"); 1246 Builder.SetInsertPoint(EHResumeBlock); 1247 1248 const EHPersonality &Personality = EHPersonality::get(*this); 1249 1250 // This can always be a call because we necessarily didn't find 1251 // anything on the EH stack which needs our help. 1252 const char *RethrowName = Personality.CatchallRethrowFn; 1253 if (RethrowName != nullptr && !isCleanup) { 1254 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName), 1255 getExceptionFromSlot())->setDoesNotReturn(); 1256 Builder.CreateUnreachable(); 1257 Builder.restoreIP(SavedIP); 1258 return EHResumeBlock; 1259 } 1260 1261 // Recreate the landingpad's return value for the 'resume' instruction. 1262 llvm::Value *Exn = getExceptionFromSlot(); 1263 llvm::Value *Sel = getSelectorFromSlot(); 1264 1265 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), 1266 Sel->getType(), nullptr); 1267 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType); 1268 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val"); 1269 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val"); 1270 1271 Builder.CreateResume(LPadVal); 1272 Builder.restoreIP(SavedIP); 1273 return EHResumeBlock; 1274 } 1275 1276 void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) { 1277 // FIXME: Implement SEH on other architectures. 1278 const llvm::Triple &T = CGM.getTarget().getTriple(); 1279 if (T.getArch() != llvm::Triple::x86_64 || 1280 !T.isKnownWindowsMSVCEnvironment()) { 1281 ErrorUnsupported(&S, "__try statement"); 1282 return; 1283 } 1284 1285 EnterSEHTryStmt(S); 1286 { 1287 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave"); 1288 1289 SEHTryEpilogueStack.push_back(&TryExit); 1290 EmitStmt(S.getTryBlock()); 1291 SEHTryEpilogueStack.pop_back(); 1292 1293 if (!TryExit.getBlock()->use_empty()) 1294 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true); 1295 else 1296 delete TryExit.getBlock(); 1297 } 1298 ExitSEHTryStmt(S); 1299 } 1300 1301 namespace { 1302 struct PerformSEHFinally : EHScopeStack::Cleanup { 1303 llvm::Function *OutlinedFinally; 1304 PerformSEHFinally(llvm::Function *OutlinedFinally) 1305 : OutlinedFinally(OutlinedFinally) {} 1306 1307 void Emit(CodeGenFunction &CGF, Flags F) override { 1308 ASTContext &Context = CGF.getContext(); 1309 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy}; 1310 FunctionProtoType::ExtProtoInfo EPI; 1311 const auto *FTP = cast<FunctionType>( 1312 Context.getFunctionType(Context.VoidTy, ArgTys, EPI)); 1313 1314 CallArgList Args; 1315 llvm::Value *IsForEH = 1316 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup()); 1317 Args.add(RValue::get(IsForEH), ArgTys[0]); 1318 1319 CodeGenModule &CGM = CGF.CGM; 1320 llvm::Value *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0); 1321 llvm::Value *FrameAddr = CGM.getIntrinsic(llvm::Intrinsic::frameaddress); 1322 llvm::Value *FP = CGF.Builder.CreateCall(FrameAddr, Zero); 1323 Args.add(RValue::get(FP), ArgTys[1]); 1324 1325 const CGFunctionInfo &FnInfo = 1326 CGM.getTypes().arrangeFreeFunctionCall(Args, FTP, /*chainCall=*/false); 1327 CGF.EmitCall(FnInfo, OutlinedFinally, ReturnValueSlot(), Args); 1328 } 1329 }; 1330 } 1331 1332 namespace { 1333 /// Find all local variable captures in the statement. 1334 struct CaptureFinder : ConstStmtVisitor<CaptureFinder> { 1335 CodeGenFunction &ParentCGF; 1336 const VarDecl *ParentThis; 1337 SmallVector<const VarDecl *, 4> Captures; 1338 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis) 1339 : ParentCGF(ParentCGF), ParentThis(ParentThis) {} 1340 1341 void Visit(const Stmt *S) { 1342 // See if this is a capture, then recurse. 1343 ConstStmtVisitor<CaptureFinder>::Visit(S); 1344 for (const Stmt *Child : S->children()) 1345 if (Child) 1346 Visit(Child); 1347 } 1348 1349 void VisitDeclRefExpr(const DeclRefExpr *E) { 1350 // If this is already a capture, just make sure we capture 'this'. 1351 if (E->refersToEnclosingVariableOrCapture()) { 1352 Captures.push_back(ParentThis); 1353 return; 1354 } 1355 1356 const auto *D = dyn_cast<VarDecl>(E->getDecl()); 1357 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage()) 1358 Captures.push_back(D); 1359 } 1360 1361 void VisitCXXThisExpr(const CXXThisExpr *E) { 1362 Captures.push_back(ParentThis); 1363 } 1364 }; 1365 } 1366 1367 void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF, 1368 const Stmt *OutlinedStmt, 1369 llvm::Value *ParentFP) { 1370 // Find all captures in the Stmt. 1371 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl); 1372 Finder.Visit(OutlinedStmt); 1373 1374 // Typically there are no captures and we can exit early. 1375 if (Finder.Captures.empty()) 1376 return; 1377 1378 // Prepare the first two arguments to llvm.framerecover. 1379 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration( 1380 &CGM.getModule(), llvm::Intrinsic::framerecover); 1381 llvm::Constant *ParentI8Fn = 1382 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy); 1383 1384 // Create llvm.framerecover calls for all captures. 1385 for (const VarDecl *VD : Finder.Captures) { 1386 if (isa<ImplicitParamDecl>(VD)) { 1387 CGM.ErrorUnsupported(VD, "'this' captured by SEH"); 1388 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType())); 1389 continue; 1390 } 1391 if (VD->getType()->isVariablyModifiedType()) { 1392 CGM.ErrorUnsupported(VD, "VLA captured by SEH"); 1393 continue; 1394 } 1395 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) && 1396 "captured non-local variable"); 1397 1398 // If this decl hasn't been declared yet, it will be declared in the 1399 // OutlinedStmt. 1400 auto I = ParentCGF.LocalDeclMap.find(VD); 1401 if (I == ParentCGF.LocalDeclMap.end()) 1402 continue; 1403 llvm::Value *ParentVar = I->second; 1404 1405 llvm::CallInst *RecoverCall = nullptr; 1406 CGBuilderTy Builder(AllocaInsertPt); 1407 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar)) { 1408 // Mark the variable escaped if nobody else referenced it and compute the 1409 // frameescape index. 1410 auto InsertPair = 1411 ParentCGF.EscapedLocals.insert(std::make_pair(ParentAlloca, -1)); 1412 if (InsertPair.second) 1413 InsertPair.first->second = ParentCGF.EscapedLocals.size() - 1; 1414 int FrameEscapeIdx = InsertPair.first->second; 1415 // call i8* @llvm.framerecover(i8* bitcast(@parentFn), i8* %fp, i32 N) 1416 RecoverCall = Builder.CreateCall( 1417 FrameRecoverFn, {ParentI8Fn, ParentFP, 1418 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)}); 1419 1420 } else { 1421 // If the parent didn't have an alloca, we're doing some nested outlining. 1422 // Just clone the existing framerecover call, but tweak the FP argument to 1423 // use our FP value. All other arguments are constants. 1424 auto *ParentRecover = 1425 cast<llvm::IntrinsicInst>(ParentVar->stripPointerCasts()); 1426 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::framerecover && 1427 "expected alloca or framerecover in parent LocalDeclMap"); 1428 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone()); 1429 RecoverCall->setArgOperand(1, ParentFP); 1430 RecoverCall->insertBefore(AllocaInsertPt); 1431 } 1432 1433 // Bitcast the variable, rename it, and insert it in the local decl map. 1434 llvm::Value *ChildVar = 1435 Builder.CreateBitCast(RecoverCall, ParentVar->getType()); 1436 ChildVar->setName(ParentVar->getName()); 1437 LocalDeclMap[VD] = ChildVar; 1438 } 1439 } 1440 1441 /// Arrange a function prototype that can be called by Windows exception 1442 /// handling personalities. On Win64, the prototype looks like: 1443 /// RetTy func(void *EHPtrs, void *ParentFP); 1444 void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF, 1445 StringRef Name, QualType RetTy, 1446 FunctionArgList &Args, 1447 const Stmt *OutlinedStmt) { 1448 llvm::Function *ParentFn = ParentCGF.CurFn; 1449 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration( 1450 RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false); 1451 1452 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); 1453 llvm::Function *Fn = llvm::Function::Create( 1454 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule()); 1455 // The filter is either in the same comdat as the function, or it's internal. 1456 if (llvm::Comdat *C = ParentFn->getComdat()) { 1457 Fn->setComdat(C); 1458 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) { 1459 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName()); 1460 ParentFn->setComdat(C); 1461 Fn->setComdat(C); 1462 } else { 1463 Fn->setLinkage(llvm::GlobalValue::InternalLinkage); 1464 } 1465 1466 IsOutlinedSEHHelper = true; 1467 1468 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args, 1469 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart()); 1470 1471 CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn); 1472 1473 auto AI = Fn->arg_begin(); 1474 ++AI; 1475 EmitCapturedLocals(ParentCGF, OutlinedStmt, &*AI); 1476 } 1477 1478 /// Create a stub filter function that will ultimately hold the code of the 1479 /// filter expression. The EH preparation passes in LLVM will outline the code 1480 /// from the main function body into this stub. 1481 llvm::Function * 1482 CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF, 1483 const SEHExceptStmt &Except) { 1484 const Expr *FilterExpr = Except.getFilterExpr(); 1485 SourceLocation StartLoc = FilterExpr->getLocStart(); 1486 1487 SEHPointersDecl = ImplicitParamDecl::Create( 1488 getContext(), nullptr, StartLoc, 1489 &getContext().Idents.get("exception_pointers"), getContext().VoidPtrTy); 1490 FunctionArgList Args; 1491 Args.push_back(SEHPointersDecl); 1492 Args.push_back(ImplicitParamDecl::Create( 1493 getContext(), nullptr, StartLoc, 1494 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy)); 1495 1496 // Get the mangled function name. 1497 SmallString<128> Name; 1498 { 1499 llvm::raw_svector_ostream OS(Name); 1500 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl; 1501 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl); 1502 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH"); 1503 CGM.getCXXABI().getMangleContext().mangleSEHFilterExpression(Parent, OS); 1504 } 1505 1506 startOutlinedSEHHelper(ParentCGF, Name, getContext().LongTy, Args, 1507 FilterExpr); 1508 1509 // Mark finally block calls as nounwind and noinline to make LLVM's job a 1510 // little easier. 1511 // FIXME: Remove these restrictions in the future. 1512 CurFn->addFnAttr(llvm::Attribute::NoUnwind); 1513 CurFn->addFnAttr(llvm::Attribute::NoInline); 1514 1515 EmitSEHExceptionCodeSave(); 1516 1517 // Emit the original filter expression, convert to i32, and return. 1518 llvm::Value *R = EmitScalarExpr(FilterExpr); 1519 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy), 1520 FilterExpr->getType()->isSignedIntegerType()); 1521 Builder.CreateStore(R, ReturnValue); 1522 1523 FinishFunction(FilterExpr->getLocEnd()); 1524 1525 return CurFn; 1526 } 1527 1528 llvm::Function * 1529 CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF, 1530 const SEHFinallyStmt &Finally) { 1531 const Stmt *FinallyBlock = Finally.getBlock(); 1532 SourceLocation StartLoc = FinallyBlock->getLocStart(); 1533 1534 FunctionArgList Args; 1535 Args.push_back(ImplicitParamDecl::Create( 1536 getContext(), nullptr, StartLoc, 1537 &getContext().Idents.get("abnormal_termination"), 1538 getContext().UnsignedCharTy)); 1539 Args.push_back(ImplicitParamDecl::Create( 1540 getContext(), nullptr, StartLoc, 1541 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy)); 1542 1543 // Get the mangled function name. 1544 SmallString<128> Name; 1545 { 1546 llvm::raw_svector_ostream OS(Name); 1547 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl; 1548 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl); 1549 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH"); 1550 CGM.getCXXABI().getMangleContext().mangleSEHFinallyBlock(Parent, OS); 1551 } 1552 1553 startOutlinedSEHHelper(ParentCGF, Name, getContext().VoidTy, Args, 1554 FinallyBlock); 1555 1556 // Emit the original filter expression, convert to i32, and return. 1557 EmitStmt(FinallyBlock); 1558 1559 FinishFunction(FinallyBlock->getLocEnd()); 1560 1561 return CurFn; 1562 } 1563 1564 void CodeGenFunction::EmitSEHExceptionCodeSave() { 1565 // Save the exception code in the exception slot to unify exception access in 1566 // the filter function and the landing pad. 1567 // struct EXCEPTION_POINTERS { 1568 // EXCEPTION_RECORD *ExceptionRecord; 1569 // CONTEXT *ContextRecord; 1570 // }; 1571 // void *exn.slot = 1572 // (void *)(uintptr_t)exception_pointers->ExceptionRecord->ExceptionCode; 1573 llvm::Value *Ptrs = Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl)); 1574 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo(); 1575 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr); 1576 Ptrs = Builder.CreateBitCast(Ptrs, PtrsTy->getPointerTo()); 1577 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0); 1578 Rec = Builder.CreateLoad(Rec); 1579 llvm::Value *Code = Builder.CreateLoad(Rec); 1580 Code = Builder.CreateZExt(Code, CGM.IntPtrTy); 1581 // FIXME: Change landing pads to produce {i32, i32} and make the exception 1582 // slot an i32. 1583 Code = Builder.CreateIntToPtr(Code, CGM.VoidPtrTy); 1584 Builder.CreateStore(Code, getExceptionSlot()); 1585 } 1586 1587 llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() { 1588 // Sema should diagnose calling this builtin outside of a filter context, but 1589 // don't crash if we screw up. 1590 if (!SEHPointersDecl) 1591 return llvm::UndefValue::get(Int8PtrTy); 1592 return Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl)); 1593 } 1594 1595 llvm::Value *CodeGenFunction::EmitSEHExceptionCode() { 1596 // If we're in a landing pad or filter function, the exception slot contains 1597 // the code. 1598 assert(ExceptionSlot); 1599 llvm::Value *Code = 1600 Builder.CreatePtrToInt(getExceptionFromSlot(), CGM.IntPtrTy); 1601 return Builder.CreateTrunc(Code, CGM.Int32Ty); 1602 } 1603 1604 llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() { 1605 // Abnormal termination is just the first parameter to the outlined finally 1606 // helper. 1607 auto AI = CurFn->arg_begin(); 1608 return Builder.CreateZExt(&*AI, Int32Ty); 1609 } 1610 1611 void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) { 1612 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true); 1613 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) { 1614 // Push a cleanup for __finally blocks. 1615 llvm::Function *FinallyFunc = 1616 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally); 1617 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc); 1618 return; 1619 } 1620 1621 // Otherwise, we must have an __except block. 1622 const SEHExceptStmt *Except = S.getExceptHandler(); 1623 assert(Except); 1624 EHCatchScope *CatchScope = EHStack.pushCatch(1); 1625 1626 // If the filter is known to evaluate to 1, then we can use the clause "catch 1627 // i8* null". 1628 llvm::Constant *C = 1629 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this); 1630 if (C && C->isOneValue()) { 1631 CatchScope->setCatchAllHandler(0, createBasicBlock("__except")); 1632 return; 1633 } 1634 1635 // In general, we have to emit an outlined filter function. Use the function 1636 // in place of the RTTI typeinfo global that C++ EH uses. 1637 llvm::Function *FilterFunc = 1638 HelperCGF.GenerateSEHFilterFunction(*this, *Except); 1639 llvm::Constant *OpaqueFunc = 1640 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy); 1641 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except")); 1642 } 1643 1644 void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) { 1645 // Just pop the cleanup if it's a __finally block. 1646 if (S.getFinallyHandler()) { 1647 PopCleanupBlock(); 1648 return; 1649 } 1650 1651 // Otherwise, we must have an __except block. 1652 const SEHExceptStmt *Except = S.getExceptHandler(); 1653 assert(Except && "__try must have __finally xor __except"); 1654 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin()); 1655 1656 // Don't emit the __except block if the __try block lacked invokes. 1657 // TODO: Model unwind edges from instructions, either with iload / istore or 1658 // a try body function. 1659 if (!CatchScope.hasEHBranches()) { 1660 CatchScope.clearHandlerBlocks(); 1661 EHStack.popCatch(); 1662 return; 1663 } 1664 1665 // The fall-through block. 1666 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont"); 1667 1668 // We just emitted the body of the __try; jump to the continue block. 1669 if (HaveInsertPoint()) 1670 Builder.CreateBr(ContBB); 1671 1672 // Check if our filter function returned true. 1673 emitCatchDispatchBlock(*this, CatchScope); 1674 1675 // Grab the block before we pop the handler. 1676 llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block; 1677 EHStack.popCatch(); 1678 1679 EmitBlockAfterUses(ExceptBB); 1680 1681 // Emit the __except body. 1682 EmitStmt(Except->getBlock()); 1683 1684 if (HaveInsertPoint()) 1685 Builder.CreateBr(ContBB); 1686 1687 EmitBlock(ContBB); 1688 } 1689 1690 void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) { 1691 // If this code is reachable then emit a stop point (if generating 1692 // debug info). We have to do this ourselves because we are on the 1693 // "simple" statement path. 1694 if (HaveInsertPoint()) 1695 EmitStopPoint(&S); 1696 1697 // This must be a __leave from a __finally block, which we warn on and is UB. 1698 // Just emit unreachable. 1699 if (!isSEHTryScope()) { 1700 Builder.CreateUnreachable(); 1701 Builder.ClearInsertionPoint(); 1702 return; 1703 } 1704 1705 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back()); 1706 } 1707