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