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