brintos

brintos / llvm-project-archived public Read only

0
0
Text · 60.2 KiB · a0483c3 Raw
1629 lines · cpp
1//===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- 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-exception6//7//===----------------------------------------------------------------------===//8//9// This file provides Sema routines for C++ exception specification testing.10//11//===----------------------------------------------------------------------===//12 13#include "clang/AST/ASTMutationListener.h"14#include "clang/AST/CXXInheritance.h"15#include "clang/AST/Expr.h"16#include "clang/AST/ExprCXX.h"17#include "clang/AST/StmtObjC.h"18#include "clang/AST/TypeLoc.h"19#include "clang/Basic/Diagnostic.h"20#include "clang/Basic/SourceManager.h"21#include "clang/Lex/Preprocessor.h"22#include "clang/Sema/SemaInternal.h"23#include "llvm/ADT/SmallPtrSet.h"24#include <optional>25 26namespace clang {27 28static const FunctionProtoType *GetUnderlyingFunction(QualType T)29{30  if (const PointerType *PtrTy = T->getAs<PointerType>())31    T = PtrTy->getPointeeType();32  else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())33    T = RefTy->getPointeeType();34  else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())35    T = MPTy->getPointeeType();36  return T->getAs<FunctionProtoType>();37}38 39/// HACK: 2014-11-14 libstdc++ had a bug where it shadows std::swap with a40/// member swap function then tries to call std::swap unqualified from the41/// exception specification of that function. This function detects whether42/// we're in such a case and turns off delay-parsing of exception43/// specifications. Libstdc++ 6.1 (released 2016-04-27) appears to have44/// resolved it as side-effect of commit ddb63209a8d (2015-06-05).45bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {46  auto *RD = dyn_cast<CXXRecordDecl>(CurContext);47 48  if (!getPreprocessor().NeedsStdLibCxxWorkaroundBefore(2016'04'27))49    return false;50  // All the problem cases are member functions named "swap" within class51  // templates declared directly within namespace std or std::__debug or52  // std::__profile.53  if (!RD || !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||54      !D.getIdentifier() || !D.getIdentifier()->isStr("swap"))55    return false;56 57  auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext());58  if (!ND)59    return false;60 61  bool IsInStd = ND->isStdNamespace();62  if (!IsInStd) {63    // This isn't a direct member of namespace std, but it might still be64    // libstdc++'s std::__debug::array or std::__profile::array.65    IdentifierInfo *II = ND->getIdentifier();66    if (!II || !(II->isStr("__debug") || II->isStr("__profile")) ||67        !ND->isInStdNamespace())68      return false;69  }70 71  // Only apply this hack within a system header.72  if (!Context.getSourceManager().isInSystemHeader(D.getBeginLoc()))73    return false;74 75  return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())76      .Case("array", true)77      .Case("pair", IsInStd)78      .Case("priority_queue", IsInStd)79      .Case("stack", IsInStd)80      .Case("queue", IsInStd)81      .Default(false);82}83 84ExprResult Sema::ActOnNoexceptSpec(Expr *NoexceptExpr,85                                   ExceptionSpecificationType &EST) {86 87  if (NoexceptExpr->isTypeDependent() ||88      NoexceptExpr->containsUnexpandedParameterPack()) {89    EST = EST_DependentNoexcept;90    return NoexceptExpr;91  }92 93  llvm::APSInt Result;94  ExprResult Converted = CheckConvertedConstantExpression(95      NoexceptExpr, Context.BoolTy, Result, CCEKind::Noexcept);96 97  if (Converted.isInvalid()) {98    EST = EST_NoexceptFalse;99    // Fill in an expression of 'false' as a fixup.100    auto *BoolExpr = new (Context)101        CXXBoolLiteralExpr(false, Context.BoolTy, NoexceptExpr->getBeginLoc());102    llvm::APSInt Value{1};103    Value = 0;104    return ConstantExpr::Create(Context, BoolExpr, APValue{Value});105  }106 107  if (Converted.get()->isValueDependent()) {108    EST = EST_DependentNoexcept;109    return Converted;110  }111 112  if (!Converted.isInvalid())113    EST = !Result ? EST_NoexceptFalse : EST_NoexceptTrue;114  return Converted;115}116 117bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {118  // C++11 [except.spec]p2:119  //   A type cv T, "array of T", or "function returning T" denoted120  //   in an exception-specification is adjusted to type T, "pointer to T", or121  //   "pointer to function returning T", respectively.122  //123  // We also apply this rule in C++98.124  if (T->isArrayType())125    T = Context.getArrayDecayedType(T);126  else if (T->isFunctionType())127    T = Context.getPointerType(T);128 129  int Kind = 0;130  QualType PointeeT = T;131  if (const PointerType *PT = T->getAs<PointerType>()) {132    PointeeT = PT->getPointeeType();133    Kind = 1;134 135    // cv void* is explicitly permitted, despite being a pointer to an136    // incomplete type.137    if (PointeeT->isVoidType())138      return false;139  } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {140    PointeeT = RT->getPointeeType();141    Kind = 2;142 143    if (RT->isRValueReferenceType()) {144      // C++11 [except.spec]p2:145      //   A type denoted in an exception-specification shall not denote [...]146      //   an rvalue reference type.147      Diag(Range.getBegin(), diag::err_rref_in_exception_spec)148        << T << Range;149      return true;150    }151  }152 153  // C++11 [except.spec]p2:154  //   A type denoted in an exception-specification shall not denote an155  //   incomplete type other than a class currently being defined [...].156  //   A type denoted in an exception-specification shall not denote a157  //   pointer or reference to an incomplete type, other than (cv) void* or a158  //   pointer or reference to a class currently being defined.159  // In Microsoft mode, downgrade this to a warning.160  unsigned DiagID = diag::err_incomplete_in_exception_spec;161  bool ReturnValueOnError = true;162  if (getLangOpts().MSVCCompat) {163    DiagID = diag::ext_incomplete_in_exception_spec;164    ReturnValueOnError = false;165  }166  if (auto *RD = PointeeT->getAsRecordDecl();167      !(RD && RD->isBeingDefined()) &&168      RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range))169    return ReturnValueOnError;170 171  // WebAssembly reference types can't be used in exception specifications.172  if (PointeeT.isWebAssemblyReferenceType()) {173    Diag(Range.getBegin(), diag::err_wasm_reftype_exception_spec);174    return true;175  }176 177  // The MSVC compatibility mode doesn't extend to sizeless types,178  // so diagnose them separately.179  if (PointeeT->isSizelessType() && Kind != 1) {180    Diag(Range.getBegin(), diag::err_sizeless_in_exception_spec)181        << (Kind == 2 ? 1 : 0) << PointeeT << Range;182    return true;183  }184 185  return false;186}187 188bool Sema::CheckDistantExceptionSpec(QualType T) {189  // C++17 removes this rule in favor of putting exception specifications into190  // the type system.191  if (getLangOpts().CPlusPlus17)192    return false;193 194  if (const PointerType *PT = T->getAs<PointerType>())195    T = PT->getPointeeType();196  else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())197    T = PT->getPointeeType();198  else199    return false;200 201  const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();202  if (!FnT)203    return false;204 205  return FnT->hasExceptionSpec();206}207 208const FunctionProtoType *209Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {210  if (FPT->getExceptionSpecType() == EST_Unparsed) {211    Diag(Loc, diag::err_exception_spec_not_parsed);212    return nullptr;213  }214 215  if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))216    return FPT;217 218  FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();219  const FunctionProtoType *SourceFPT =220      SourceDecl->getType()->castAs<FunctionProtoType>();221 222  // If the exception specification has already been resolved, just return it.223  if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))224    return SourceFPT;225 226  // Compute or instantiate the exception specification now.227  if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)228    EvaluateImplicitExceptionSpec(Loc, SourceDecl);229  else230    InstantiateExceptionSpec(Loc, SourceDecl);231 232  const FunctionProtoType *Proto =233    SourceDecl->getType()->castAs<FunctionProtoType>();234  if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {235    Diag(Loc, diag::err_exception_spec_not_parsed);236    Proto = nullptr;237  }238  return Proto;239}240 241void242Sema::UpdateExceptionSpec(FunctionDecl *FD,243                          const FunctionProtoType::ExceptionSpecInfo &ESI) {244  // If we've fully resolved the exception specification, notify listeners.245  if (!isUnresolvedExceptionSpec(ESI.Type))246    if (auto *Listener = getASTMutationListener())247      Listener->ResolvedExceptionSpec(FD);248 249  for (FunctionDecl *Redecl : FD->redecls())250    Context.adjustExceptionSpec(Redecl, ESI);251}252 253static bool exceptionSpecNotKnownYet(const FunctionDecl *FD) {254  ExceptionSpecificationType EST =255      FD->getType()->castAs<FunctionProtoType>()->getExceptionSpecType();256  if (EST == EST_Unparsed)257    return true;258  else if (EST != EST_Unevaluated)259    return false;260  const DeclContext *DC = FD->getLexicalDeclContext();261  return DC->isRecord() && cast<RecordDecl>(DC)->isBeingDefined();262}263 264static bool CheckEquivalentExceptionSpecImpl(265    Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,266    const FunctionProtoType *Old, SourceLocation OldLoc,267    const FunctionProtoType *New, SourceLocation NewLoc,268    bool *MissingExceptionSpecification = nullptr,269    bool *MissingEmptyExceptionSpecification = nullptr,270    bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false);271 272/// Determine whether a function has an implicitly-generated exception273/// specification.274static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {275  if (!isa<CXXDestructorDecl>(Decl) &&276      Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&277      Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)278    return false;279 280  // For a function that the user didn't declare:281  //  - if this is a destructor, its exception specification is implicit.282  //  - if this is 'operator delete' or 'operator delete[]', the exception283  //    specification is as-if an explicit exception specification was given284  //    (per [basic.stc.dynamic]p2).285  if (!Decl->getTypeSourceInfo())286    return isa<CXXDestructorDecl>(Decl);287 288  auto *Ty = Decl->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();289  return !Ty->hasExceptionSpec();290}291 292bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {293  // Just completely ignore this under -fno-exceptions prior to C++17.294  // In C++17 onwards, the exception specification is part of the type and295  // we will diagnose mismatches anyway, so it's better to check for them here.296  if (!getLangOpts().CXXExceptions && !getLangOpts().CPlusPlus17)297    return false;298 299  OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();300  bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;301  bool MissingExceptionSpecification = false;302  bool MissingEmptyExceptionSpecification = false;303 304  unsigned DiagID = diag::err_mismatched_exception_spec;305  bool ReturnValueOnError = true;306  if (getLangOpts().MSVCCompat) {307    DiagID = diag::ext_mismatched_exception_spec;308    ReturnValueOnError = false;309  }310 311  // If we're befriending a member function of a class that's currently being312  // defined, we might not be able to work out its exception specification yet.313  // If not, defer the check until later.314  if (exceptionSpecNotKnownYet(Old) || exceptionSpecNotKnownYet(New)) {315    DelayedEquivalentExceptionSpecChecks.push_back({New, Old});316    return false;317  }318 319  // Check the types as written: they must match before any exception320  // specification adjustment is applied.321  if (!CheckEquivalentExceptionSpecImpl(322        *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),323        Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),324        New->getType()->getAs<FunctionProtoType>(), New->getLocation(),325        &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,326        /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {327    // C++11 [except.spec]p4 [DR1492]:328    //   If a declaration of a function has an implicit329    //   exception-specification, other declarations of the function shall330    //   not specify an exception-specification.331    if (getLangOpts().CPlusPlus11 && getLangOpts().CXXExceptions &&332        hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {333      Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)334        << hasImplicitExceptionSpec(Old);335      if (Old->getLocation().isValid())336        Diag(Old->getLocation(), diag::note_previous_declaration);337    }338    return false;339  }340 341  // The failure was something other than an missing exception342  // specification; return an error, except in MS mode where this is a warning.343  if (!MissingExceptionSpecification)344    return ReturnValueOnError;345 346  const auto *NewProto = New->getType()->castAs<FunctionProtoType>();347 348  // The new function declaration is only missing an empty exception349  // specification "throw()". If the throw() specification came from a350  // function in a system header that has C linkage, just add an empty351  // exception specification to the "new" declaration. Note that C library352  // implementations are permitted to add these nothrow exception353  // specifications.354  //355  // Likewise if the old function is a builtin.356  if (MissingEmptyExceptionSpecification &&357      (Old->getLocation().isInvalid() ||358       Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||359       Old->getBuiltinID()) &&360      Old->isExternC()) {361    New->setType(Context.getFunctionType(362        NewProto->getReturnType(), NewProto->getParamTypes(),363        NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));364    return false;365  }366 367  const auto *OldProto = Old->getType()->castAs<FunctionProtoType>();368 369  FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();370  if (ESI.Type == EST_Dynamic) {371    // FIXME: What if the exceptions are described in terms of the old372    // prototype's parameters?373    ESI.Exceptions = OldProto->exceptions();374  }375 376  if (ESI.Type == EST_NoexceptFalse)377    ESI.Type = EST_None;378  if (ESI.Type == EST_NoexceptTrue)379    ESI.Type = EST_BasicNoexcept;380 381  // For dependent noexcept, we can't just take the expression from the old382  // prototype. It likely contains references to the old prototype's parameters.383  if (ESI.Type == EST_DependentNoexcept) {384    New->setInvalidDecl();385  } else {386    // Update the type of the function with the appropriate exception387    // specification.388    New->setType(Context.getFunctionType(389        NewProto->getReturnType(), NewProto->getParamTypes(),390        NewProto->getExtProtoInfo().withExceptionSpec(ESI)));391  }392 393  if (getLangOpts().MSVCCompat && isDynamicExceptionSpec(ESI.Type)) {394    DiagID = diag::ext_missing_exception_specification;395    ReturnValueOnError = false;396  } else if (New->isReplaceableGlobalAllocationFunction() &&397             ESI.Type != EST_DependentNoexcept) {398    // Allow missing exception specifications in redeclarations as an extension,399    // when declaring a replaceable global allocation function.400    DiagID = diag::ext_missing_exception_specification;401    ReturnValueOnError = false;402  } else if (ESI.Type == EST_NoThrow) {403    // Don't emit any warning for missing 'nothrow' in MSVC.404    if (getLangOpts().MSVCCompat) {405      return false;406    }407    // Allow missing attribute 'nothrow' in redeclarations, since this is a very408    // common omission.409    DiagID = diag::ext_missing_exception_specification;410    ReturnValueOnError = false;411  } else {412    DiagID = diag::err_missing_exception_specification;413    ReturnValueOnError = true;414  }415 416  // Warn about the lack of exception specification.417  SmallString<128> ExceptionSpecString;418  llvm::raw_svector_ostream OS(ExceptionSpecString);419  switch (OldProto->getExceptionSpecType()) {420  case EST_DynamicNone:421    OS << "throw()";422    break;423 424  case EST_Dynamic: {425    OS << "throw(";426    bool OnFirstException = true;427    for (const auto &E : OldProto->exceptions()) {428      if (OnFirstException)429        OnFirstException = false;430      else431        OS << ", ";432 433      OS << E.getAsString(getPrintingPolicy());434    }435    OS << ")";436    break;437  }438 439  case EST_BasicNoexcept:440    OS << "noexcept";441    break;442 443  case EST_DependentNoexcept:444  case EST_NoexceptFalse:445  case EST_NoexceptTrue:446    OS << "noexcept(";447    assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");448    OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());449    OS << ")";450    break;451  case EST_NoThrow:452    OS <<"__attribute__((nothrow))";453    break;454  case EST_None:455  case EST_MSAny:456  case EST_Unevaluated:457  case EST_Uninstantiated:458  case EST_Unparsed:459    llvm_unreachable("This spec type is compatible with none.");460  }461 462  SourceLocation FixItLoc;463  if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {464    TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();465    // FIXME: Preserve enough information so that we can produce a correct fixit466    // location when there is a trailing return type.467    if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())468      if (!FTLoc.getTypePtr()->hasTrailingReturn())469        FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());470  }471 472  if (FixItLoc.isInvalid())473    Diag(New->getLocation(), DiagID)474      << New << OS.str();475  else {476    Diag(New->getLocation(), DiagID)477      << New << OS.str()478      << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());479  }480 481  if (Old->getLocation().isValid())482    Diag(Old->getLocation(), diag::note_previous_declaration);483 484  return ReturnValueOnError;485}486 487bool Sema::CheckEquivalentExceptionSpec(488    const FunctionProtoType *Old, SourceLocation OldLoc,489    const FunctionProtoType *New, SourceLocation NewLoc) {490  if (!getLangOpts().CXXExceptions)491    return false;492 493  unsigned DiagID = diag::err_mismatched_exception_spec;494  if (getLangOpts().MSVCCompat)495    DiagID = diag::ext_mismatched_exception_spec;496  bool Result = CheckEquivalentExceptionSpecImpl(497      *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),498      Old, OldLoc, New, NewLoc);499 500  // In Microsoft mode, mismatching exception specifications just cause a warning.501  if (getLangOpts().MSVCCompat)502    return false;503  return Result;504}505 506/// CheckEquivalentExceptionSpec - Check if the two types have compatible507/// exception specifications. See C++ [except.spec]p3.508///509/// \return \c false if the exception specifications match, \c true if there is510/// a problem. If \c true is returned, either a diagnostic has already been511/// produced or \c *MissingExceptionSpecification is set to \c true.512static bool CheckEquivalentExceptionSpecImpl(513    Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,514    const FunctionProtoType *Old, SourceLocation OldLoc,515    const FunctionProtoType *New, SourceLocation NewLoc,516    bool *MissingExceptionSpecification,517    bool *MissingEmptyExceptionSpecification,518    bool AllowNoexceptAllMatchWithNoSpec, bool IsOperatorNew) {519  if (MissingExceptionSpecification)520    *MissingExceptionSpecification = false;521 522  if (MissingEmptyExceptionSpecification)523    *MissingEmptyExceptionSpecification = false;524 525  Old = S.ResolveExceptionSpec(NewLoc, Old);526  if (!Old)527    return false;528  New = S.ResolveExceptionSpec(NewLoc, New);529  if (!New)530    return false;531 532  // C++0x [except.spec]p3: Two exception-specifications are compatible if:533  //   - both are non-throwing, regardless of their form,534  //   - both have the form noexcept(constant-expression) and the constant-535  //     expressions are equivalent,536  //   - both are dynamic-exception-specifications that have the same set of537  //     adjusted types.538  //539  // C++0x [except.spec]p12: An exception-specification is non-throwing if it is540  //   of the form throw(), noexcept, or noexcept(constant-expression) where the541  //   constant-expression yields true.542  //543  // C++0x [except.spec]p4: If any declaration of a function has an exception-544  //   specifier that is not a noexcept-specification allowing all exceptions,545  //   all declarations [...] of that function shall have a compatible546  //   exception-specification.547  //548  // That last point basically means that noexcept(false) matches no spec.549  // It's considered when AllowNoexceptAllMatchWithNoSpec is true.550 551  ExceptionSpecificationType OldEST = Old->getExceptionSpecType();552  ExceptionSpecificationType NewEST = New->getExceptionSpecType();553 554  assert(!isUnresolvedExceptionSpec(OldEST) &&555         !isUnresolvedExceptionSpec(NewEST) &&556         "Shouldn't see unknown exception specifications here");557 558  CanThrowResult OldCanThrow = Old->canThrow();559  CanThrowResult NewCanThrow = New->canThrow();560 561  // Any non-throwing specifications are compatible.562  if (OldCanThrow == CT_Cannot && NewCanThrow == CT_Cannot)563    return false;564 565  // Any throws-anything specifications are usually compatible.566  if (OldCanThrow == CT_Can && OldEST != EST_Dynamic &&567      NewCanThrow == CT_Can && NewEST != EST_Dynamic) {568    // The exception is that the absence of an exception specification only569    // matches noexcept(false) for functions, as described above.570    if (!AllowNoexceptAllMatchWithNoSpec &&571        ((OldEST == EST_None && NewEST == EST_NoexceptFalse) ||572         (OldEST == EST_NoexceptFalse && NewEST == EST_None))) {573      // This is the disallowed case.574    } else {575      return false;576    }577  }578 579  // C++14 [except.spec]p3:580  //   Two exception-specifications are compatible if [...] both have the form581  //   noexcept(constant-expression) and the constant-expressions are equivalent582  if (OldEST == EST_DependentNoexcept && NewEST == EST_DependentNoexcept) {583    llvm::FoldingSetNodeID OldFSN, NewFSN;584    Old->getNoexceptExpr()->Profile(OldFSN, S.Context, true);585    New->getNoexceptExpr()->Profile(NewFSN, S.Context, true);586    if (OldFSN == NewFSN)587      return false;588  }589 590  // Dynamic exception specifications with the same set of adjusted types591  // are compatible.592  if (OldEST == EST_Dynamic && NewEST == EST_Dynamic) {593    bool Success = true;594    // Both have a dynamic exception spec. Collect the first set, then compare595    // to the second.596    llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;597    for (const auto &I : Old->exceptions())598      OldTypes.insert(S.Context.getCanonicalType(I).getUnqualifiedType());599 600    for (const auto &I : New->exceptions()) {601      CanQualType TypePtr = S.Context.getCanonicalType(I).getUnqualifiedType();602      if (OldTypes.count(TypePtr))603        NewTypes.insert(TypePtr);604      else {605        Success = false;606        break;607      }608    }609 610    if (Success && OldTypes.size() == NewTypes.size())611      return false;612  }613 614  // As a special compatibility feature, under C++0x we accept no spec and615  // throw(std::bad_alloc) as equivalent for operator new and operator new[].616  // This is because the implicit declaration changed, but old code would break.617  if (S.getLangOpts().CPlusPlus11 && IsOperatorNew) {618    const FunctionProtoType *WithExceptions = nullptr;619    if (OldEST == EST_None && NewEST == EST_Dynamic)620      WithExceptions = New;621    else if (OldEST == EST_Dynamic && NewEST == EST_None)622      WithExceptions = Old;623    if (WithExceptions && WithExceptions->getNumExceptions() == 1) {624      // One has no spec, the other throw(something). If that something is625      // std::bad_alloc, all conditions are met.626      QualType Exception = *WithExceptions->exception_begin();627      if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {628        IdentifierInfo* Name = ExRecord->getIdentifier();629        if (Name && Name->getName() == "bad_alloc") {630          // It's called bad_alloc, but is it in std?631          if (ExRecord->isInStdNamespace()) {632            return false;633          }634        }635      }636    }637  }638 639  // If the caller wants to handle the case that the new function is640  // incompatible due to a missing exception specification, let it.641  if (MissingExceptionSpecification && OldEST != EST_None &&642      NewEST == EST_None) {643    // The old type has an exception specification of some sort, but644    // the new type does not.645    *MissingExceptionSpecification = true;646 647    if (MissingEmptyExceptionSpecification && OldCanThrow == CT_Cannot) {648      // The old type has a throw() or noexcept(true) exception specification649      // and the new type has no exception specification, and the caller asked650      // to handle this itself.651      *MissingEmptyExceptionSpecification = true;652    }653 654    return true;655  }656 657  S.Diag(NewLoc, DiagID);658  if (NoteID.getDiagID() != 0 && OldLoc.isValid())659    S.Diag(OldLoc, NoteID);660  return true;661}662 663bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,664                                        const PartialDiagnostic &NoteID,665                                        const FunctionProtoType *Old,666                                        SourceLocation OldLoc,667                                        const FunctionProtoType *New,668                                        SourceLocation NewLoc) {669  if (!getLangOpts().CXXExceptions)670    return false;671  return CheckEquivalentExceptionSpecImpl(*this, DiagID, NoteID, Old, OldLoc,672                                          New, NewLoc);673}674 675bool Sema::handlerCanCatch(QualType HandlerType, QualType ExceptionType) {676  // [except.handle]p3:677  //   A handler is a match for an exception object of type E if:678 679  // HandlerType must be ExceptionType or derived from it, or pointer or680  // reference to such types.681  const ReferenceType *RefTy = HandlerType->getAs<ReferenceType>();682  if (RefTy)683    HandlerType = RefTy->getPointeeType();684 685  //   -- the handler is of type cv T or cv T& and E and T are the same type686  if (Context.hasSameUnqualifiedType(ExceptionType, HandlerType))687    return true;688 689  // FIXME: ObjC pointer types?690  if (HandlerType->isPointerType() || HandlerType->isMemberPointerType()) {691    if (RefTy && (!HandlerType.isConstQualified() ||692                  HandlerType.isVolatileQualified()))693      return false;694 695    // -- the handler is of type cv T or const T& where T is a pointer or696    //    pointer to member type and E is std::nullptr_t697    if (ExceptionType->isNullPtrType())698      return true;699 700    // -- the handler is of type cv T or const T& where T is a pointer or701    //    pointer to member type and E is a pointer or pointer to member type702    //    that can be converted to T by one or more of703    //    -- a qualification conversion704    //    -- a function pointer conversion705    bool LifetimeConv;706    // FIXME: Should we treat the exception as catchable if a lifetime707    // conversion is required?708    if (IsQualificationConversion(ExceptionType, HandlerType, false,709                                  LifetimeConv) ||710        IsFunctionConversion(ExceptionType, HandlerType))711      return true;712 713    //    -- a standard pointer conversion [...]714    if (!ExceptionType->isPointerType() || !HandlerType->isPointerType())715      return false;716 717    // Handle the "qualification conversion" portion.718    Qualifiers EQuals, HQuals;719    ExceptionType = Context.getUnqualifiedArrayType(720        ExceptionType->getPointeeType(), EQuals);721    HandlerType =722        Context.getUnqualifiedArrayType(HandlerType->getPointeeType(), HQuals);723    if (!HQuals.compatiblyIncludes(EQuals, getASTContext()))724      return false;725 726    if (HandlerType->isVoidType() && ExceptionType->isObjectType())727      return true;728 729    // The only remaining case is a derived-to-base conversion.730  }731 732  //   -- the handler is of type cg T or cv T& and T is an unambiguous public733  //      base class of E734  if (!ExceptionType->isRecordType() || !HandlerType->isRecordType())735    return false;736  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,737                     /*DetectVirtual=*/false);738  if (!IsDerivedFrom(SourceLocation(), ExceptionType, HandlerType, Paths) ||739      Paths.isAmbiguous(Context.getCanonicalType(HandlerType)))740    return false;741 742  // Do this check from a context without privileges.743  switch (CheckBaseClassAccess(SourceLocation(), HandlerType, ExceptionType,744                               Paths.front(),745                               /*Diagnostic*/ 0,746                               /*ForceCheck*/ true,747                               /*ForceUnprivileged*/ true)) {748  case AR_accessible: return true;749  case AR_inaccessible: return false;750  case AR_dependent:751    llvm_unreachable("access check dependent for unprivileged context");752  case AR_delayed:753    llvm_unreachable("access check delayed in non-declaration");754  }755  llvm_unreachable("unexpected access check result");756}757 758bool Sema::CheckExceptionSpecSubset(759    const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,760    const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,761    const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,762    SourceLocation SuperLoc, const FunctionProtoType *Subset,763    bool SkipSubsetFirstParameter, SourceLocation SubLoc) {764 765  // Just auto-succeed under -fno-exceptions.766  if (!getLangOpts().CXXExceptions)767    return false;768 769  // FIXME: As usual, we could be more specific in our error messages, but770  // that better waits until we've got types with source locations.771 772  if (!SubLoc.isValid())773    SubLoc = SuperLoc;774 775  // Resolve the exception specifications, if needed.776  Superset = ResolveExceptionSpec(SuperLoc, Superset);777  if (!Superset)778    return false;779  Subset = ResolveExceptionSpec(SubLoc, Subset);780  if (!Subset)781    return false;782 783  ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();784  ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();785  assert(!isUnresolvedExceptionSpec(SuperEST) &&786         !isUnresolvedExceptionSpec(SubEST) &&787         "Shouldn't see unknown exception specifications here");788 789  // If there are dependent noexcept specs, assume everything is fine. Unlike790  // with the equivalency check, this is safe in this case, because we don't791  // want to merge declarations. Checks after instantiation will catch any792  // omissions we make here.793  if (SuperEST == EST_DependentNoexcept || SubEST == EST_DependentNoexcept)794    return false;795 796  CanThrowResult SuperCanThrow = Superset->canThrow();797  CanThrowResult SubCanThrow = Subset->canThrow();798 799  // If the superset contains everything or the subset contains nothing, we're800  // done.801  if ((SuperCanThrow == CT_Can && SuperEST != EST_Dynamic) ||802      SubCanThrow == CT_Cannot)803    return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset,804                                   SkipSupersetFirstParameter, SuperLoc, Subset,805                                   SkipSubsetFirstParameter, SubLoc);806 807  // Allow __declspec(nothrow) to be missing on redeclaration as an extension in808  // some cases.809  if (NoThrowDiagID.getDiagID() != 0 && SubCanThrow == CT_Can &&810      SuperCanThrow == CT_Cannot && SuperEST == EST_NoThrow) {811    Diag(SubLoc, NoThrowDiagID);812    if (NoteID.getDiagID() != 0)813      Diag(SuperLoc, NoteID);814    return true;815  }816 817  // If the subset contains everything or the superset contains nothing, we've818  // failed.819  if ((SubCanThrow == CT_Can && SubEST != EST_Dynamic) ||820      SuperCanThrow == CT_Cannot) {821    Diag(SubLoc, DiagID);822    if (NoteID.getDiagID() != 0)823      Diag(SuperLoc, NoteID);824    return true;825  }826 827  assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&828         "Exception spec subset: non-dynamic case slipped through.");829 830  // Neither contains everything or nothing. Do a proper comparison.831  for (QualType SubI : Subset->exceptions()) {832    if (const ReferenceType *RefTy = SubI->getAs<ReferenceType>())833      SubI = RefTy->getPointeeType();834 835    // Make sure it's in the superset.836    bool Contained = false;837    for (QualType SuperI : Superset->exceptions()) {838      // [except.spec]p5:839      //   the target entity shall allow at least the exceptions allowed by the840      //   source841      //842      // We interpret this as meaning that a handler for some target type would843      // catch an exception of each source type.844      if (handlerCanCatch(SuperI, SubI)) {845        Contained = true;846        break;847      }848    }849    if (!Contained) {850      Diag(SubLoc, DiagID);851      if (NoteID.getDiagID() != 0)852        Diag(SuperLoc, NoteID);853      return true;854    }855  }856  // We've run half the gauntlet.857  return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset,858                                 SkipSupersetFirstParameter, SuperLoc, Subset,859                                 SkipSupersetFirstParameter, SubLoc);860}861 862static bool863CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID,864                            const PartialDiagnostic &NoteID, QualType Target,865                            SourceLocation TargetLoc, QualType Source,866                            SourceLocation SourceLoc) {867  const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);868  if (!TFunc)869    return false;870  const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);871  if (!SFunc)872    return false;873 874  return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,875                                        SFunc, SourceLoc);876}877 878bool Sema::CheckParamExceptionSpec(879    const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,880    const FunctionProtoType *Target, bool SkipTargetFirstParameter,881    SourceLocation TargetLoc, const FunctionProtoType *Source,882    bool SkipSourceFirstParameter, SourceLocation SourceLoc) {883  auto RetDiag = DiagID;884  RetDiag << 0;885  if (CheckSpecForTypesEquivalent(886          *this, RetDiag, PDiag(),887          Target->getReturnType(), TargetLoc, Source->getReturnType(),888          SourceLoc))889    return true;890 891  // We shouldn't even be testing this unless the arguments are otherwise892  // compatible.893  assert((Target->getNumParams() - (unsigned)SkipTargetFirstParameter) ==894             (Source->getNumParams() - (unsigned)SkipSourceFirstParameter) &&895         "Functions have different argument counts.");896  for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {897    auto ParamDiag = DiagID;898    ParamDiag << 1;899    if (CheckSpecForTypesEquivalent(900            *this, ParamDiag, PDiag(),901            Target->getParamType(i + (SkipTargetFirstParameter ? 1 : 0)),902            TargetLoc, Source->getParamType(SkipSourceFirstParameter ? 1 : 0),903            SourceLoc))904      return true;905  }906  return false;907}908 909bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {910  // First we check for applicability.911  // Target type must be a function, function pointer or function reference.912  const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);913  if (!ToFunc || ToFunc->hasDependentExceptionSpec())914    return false;915 916  // SourceType must be a function or function pointer.917  const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());918  if (!FromFunc || FromFunc->hasDependentExceptionSpec())919    return false;920 921  unsigned DiagID = diag::err_incompatible_exception_specs;922  unsigned NestedDiagID = diag::err_deep_exception_specs_differ;923  // This is not an error in C++17 onwards, unless the noexceptness doesn't924  // match, but in that case we have a full-on type mismatch, not just a925  // type sugar mismatch.926  if (getLangOpts().CPlusPlus17) {927    DiagID = diag::warn_incompatible_exception_specs;928    NestedDiagID = diag::warn_deep_exception_specs_differ;929  }930 931  // Now we've got the correct types on both sides, check their compatibility.932  // This means that the source of the conversion can only throw a subset of933  // the exceptions of the target, and any exception specs on arguments or934  // return types must be equivalent.935  //936  // FIXME: If there is a nested dependent exception specification, we should937  // not be checking it here. This is fine:938  //   template<typename T> void f() {939  //     void (*p)(void (*) throw(T));940  //     void (*q)(void (*) throw(int)) = p;941  //   }942  // ... because it might be instantiated with T=int.943  return CheckExceptionSpecSubset(PDiag(DiagID), PDiag(NestedDiagID), PDiag(),944                                  PDiag(), ToFunc, 0,945                                  From->getSourceRange().getBegin(), FromFunc,946                                  0, SourceLocation()) &&947         !getLangOpts().CPlusPlus17;948}949 950bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,951                                                const CXXMethodDecl *Old) {952  // If the new exception specification hasn't been parsed yet, skip the check.953  // We'll get called again once it's been parsed.954  if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==955      EST_Unparsed)956    return false;957 958  // Don't check uninstantiated template destructors at all. We can only959  // synthesize correct specs after the template is instantiated.960  if (isa<CXXDestructorDecl>(New) && New->getParent()->isDependentType())961    return false;962 963  // If the old exception specification hasn't been parsed yet, or the new964  // exception specification can't be computed yet, remember that we need to965  // perform this check when we get to the end of the outermost966  // lexically-surrounding class.967  if (exceptionSpecNotKnownYet(Old) || exceptionSpecNotKnownYet(New)) {968    DelayedOverridingExceptionSpecChecks.push_back({New, Old});969    return false;970  }971 972  unsigned DiagID = diag::err_override_exception_spec;973  if (getLangOpts().MSVCCompat)974    DiagID = diag::ext_override_exception_spec;975  return CheckExceptionSpecSubset(976      PDiag(DiagID), PDiag(diag::err_deep_exception_specs_differ),977      PDiag(diag::note_overridden_virtual_function),978      PDiag(diag::ext_override_exception_spec),979      Old->getType()->castAs<FunctionProtoType>(),980      Old->hasCXXExplicitFunctionObjectParameter(), Old->getLocation(),981      New->getType()->castAs<FunctionProtoType>(),982      New->hasCXXExplicitFunctionObjectParameter(), New->getLocation());983}984 985static CanThrowResult canSubStmtsThrow(Sema &Self, const Stmt *S) {986  CanThrowResult R = CT_Cannot;987  for (const Stmt *SubStmt : S->children()) {988    if (!SubStmt)989      continue;990    R = mergeCanThrow(R, Self.canThrow(SubStmt));991    if (R == CT_Can)992      break;993  }994  return R;995}996 997CanThrowResult Sema::canCalleeThrow(Sema &S, const Expr *E, const Decl *D,998                                    SourceLocation Loc) {999  // As an extension, we assume that __attribute__((nothrow)) functions don't1000  // throw.1001  if (isa_and_nonnull<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())1002    return CT_Cannot;1003 1004  QualType T;1005 1006  // In C++1z, just look at the function type of the callee.1007  if (S.getLangOpts().CPlusPlus17 && isa_and_nonnull<CallExpr>(E)) {1008    E = cast<CallExpr>(E)->getCallee();1009    T = E->getType();1010    if (T->isSpecificPlaceholderType(BuiltinType::BoundMember)) {1011      // Sadly we don't preserve the actual type as part of the "bound member"1012      // placeholder, so we need to reconstruct it.1013      E = E->IgnoreParenImpCasts();1014 1015      // Could be a call to a pointer-to-member or a plain member access.1016      if (auto *Op = dyn_cast<BinaryOperator>(E)) {1017        assert(Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI);1018        T = Op->getRHS()->getType()1019              ->castAs<MemberPointerType>()->getPointeeType();1020      } else {1021        T = cast<MemberExpr>(E)->getMemberDecl()->getType();1022      }1023    }1024  } else if (const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D))1025    T = VD->getType();1026  else1027    // If we have no clue what we're calling, assume the worst.1028    return CT_Can;1029 1030  const FunctionProtoType *FT;1031  if ((FT = T->getAs<FunctionProtoType>())) {1032  } else if (const PointerType *PT = T->getAs<PointerType>())1033    FT = PT->getPointeeType()->getAs<FunctionProtoType>();1034  else if (const ReferenceType *RT = T->getAs<ReferenceType>())1035    FT = RT->getPointeeType()->getAs<FunctionProtoType>();1036  else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())1037    FT = MT->getPointeeType()->getAs<FunctionProtoType>();1038  else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())1039    FT = BT->getPointeeType()->getAs<FunctionProtoType>();1040 1041  if (!FT)1042    return CT_Can;1043 1044  if (Loc.isValid() || (Loc.isInvalid() && E))1045    FT = S.ResolveExceptionSpec(Loc.isInvalid() ? E->getBeginLoc() : Loc, FT);1046  if (!FT)1047    return CT_Can;1048 1049  return FT->canThrow();1050}1051 1052static CanThrowResult canVarDeclThrow(Sema &Self, const VarDecl *VD) {1053  CanThrowResult CT = CT_Cannot;1054 1055  // Initialization might throw.1056  if (!VD->isUsableInConstantExpressions(Self.Context))1057    if (const Expr *Init = VD->getInit())1058      CT = mergeCanThrow(CT, Self.canThrow(Init));1059 1060  // Destructor might throw.1061  if (VD->needsDestruction(Self.Context) == QualType::DK_cxx_destructor) {1062    if (auto *RD =1063            VD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {1064      if (auto *Dtor = RD->getDestructor()) {1065        CT = mergeCanThrow(1066            CT, Sema::canCalleeThrow(Self, nullptr, Dtor, VD->getLocation()));1067      }1068    }1069  }1070 1071  // If this is a decomposition declaration, bindings might throw.1072  if (auto *DD = dyn_cast<DecompositionDecl>(VD))1073    for (auto *B : DD->flat_bindings())1074      if (auto *HD = B->getHoldingVar())1075        CT = mergeCanThrow(CT, canVarDeclThrow(Self, HD));1076 1077  return CT;1078}1079 1080static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {1081  if (DC->isTypeDependent())1082    return CT_Dependent;1083 1084  if (!DC->getTypeAsWritten()->isReferenceType())1085    return CT_Cannot;1086 1087  if (DC->getSubExpr()->isTypeDependent())1088    return CT_Dependent;1089 1090  return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;1091}1092 1093static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {1094  // A typeid of a type is a constant and does not throw.1095  if (DC->isTypeOperand())1096    return CT_Cannot;1097 1098  if (DC->isValueDependent())1099    return CT_Dependent;1100 1101  // If this operand is not evaluated it cannot possibly throw.1102  if (!DC->isPotentiallyEvaluated())1103    return CT_Cannot;1104 1105  // Can throw std::bad_typeid if a nullptr is dereferenced.1106  if (DC->hasNullCheck())1107    return CT_Can;1108 1109  return S.canThrow(DC->getExprOperand());1110}1111 1112CanThrowResult Sema::canThrow(const Stmt *S) {1113  // C++ [expr.unary.noexcept]p3:1114  //   [Can throw] if in a potentially-evaluated context the expression would1115  //   contain:1116  switch (S->getStmtClass()) {1117  case Expr::ConstantExprClass:1118    return canThrow(cast<ConstantExpr>(S)->getSubExpr());1119 1120  case Expr::CXXThrowExprClass:1121    //   - a potentially evaluated throw-expression1122    return CT_Can;1123 1124  case Expr::CXXDynamicCastExprClass: {1125    //   - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),1126    //     where T is a reference type, that requires a run-time check1127    auto *CE = cast<CXXDynamicCastExpr>(S);1128    // FIXME: Properly determine whether a variably-modified type can throw.1129    if (CE->getType()->isVariablyModifiedType())1130      return CT_Can;1131    CanThrowResult CT = canDynamicCastThrow(CE);1132    if (CT == CT_Can)1133      return CT;1134    return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));1135  }1136 1137  case Expr::CXXTypeidExprClass:1138    //   - a potentially evaluated typeid expression applied to a (possibly1139    //     parenthesized) built-in unary * operator applied to a pointer to a1140    //     polymorphic class type1141    return canTypeidThrow(*this, cast<CXXTypeidExpr>(S));1142 1143    //   - a potentially evaluated call to a function, member function, function1144    //     pointer, or member function pointer that does not have a non-throwing1145    //     exception-specification1146  case Expr::CallExprClass:1147  case Expr::CXXMemberCallExprClass:1148  case Expr::CXXOperatorCallExprClass:1149  case Expr::UserDefinedLiteralClass: {1150    const CallExpr *CE = cast<CallExpr>(S);1151    CanThrowResult CT;1152    if (CE->isTypeDependent())1153      CT = CT_Dependent;1154    else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))1155      CT = CT_Cannot;1156    else1157      CT = canCalleeThrow(*this, CE, CE->getCalleeDecl());1158    if (CT == CT_Can)1159      return CT;1160    return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));1161  }1162 1163  case Expr::CXXConstructExprClass:1164  case Expr::CXXTemporaryObjectExprClass: {1165    auto *CE = cast<CXXConstructExpr>(S);1166    // FIXME: Properly determine whether a variably-modified type can throw.1167    if (CE->getType()->isVariablyModifiedType())1168      return CT_Can;1169    CanThrowResult CT = canCalleeThrow(*this, CE, CE->getConstructor());1170    if (CT == CT_Can)1171      return CT;1172    return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));1173  }1174 1175  case Expr::CXXInheritedCtorInitExprClass: {1176    auto *ICIE = cast<CXXInheritedCtorInitExpr>(S);1177    return canCalleeThrow(*this, ICIE, ICIE->getConstructor());1178  }1179 1180  case Expr::LambdaExprClass: {1181    const LambdaExpr *Lambda = cast<LambdaExpr>(S);1182    CanThrowResult CT = CT_Cannot;1183    for (LambdaExpr::const_capture_init_iterator1184             Cap = Lambda->capture_init_begin(),1185             CapEnd = Lambda->capture_init_end();1186         Cap != CapEnd; ++Cap)1187      CT = mergeCanThrow(CT, canThrow(*Cap));1188    return CT;1189  }1190 1191  case Expr::CXXNewExprClass: {1192    auto *NE = cast<CXXNewExpr>(S);1193    CanThrowResult CT;1194    if (NE->isTypeDependent())1195      CT = CT_Dependent;1196    else1197      CT = canCalleeThrow(*this, NE, NE->getOperatorNew());1198    if (CT == CT_Can)1199      return CT;1200    return mergeCanThrow(CT, canSubStmtsThrow(*this, NE));1201  }1202 1203  case Expr::CXXDeleteExprClass: {1204    auto *DE = cast<CXXDeleteExpr>(S);1205    CanThrowResult CT = CT_Cannot;1206    QualType DTy = DE->getDestroyedType();1207    if (DTy.isNull() || DTy->isDependentType()) {1208      CT = CT_Dependent;1209    } else {1210      // C++20 [expr.delete]p6: If the value of the operand of the delete-1211      // expression is not a null pointer value and the selected deallocation1212      // function (see below) is not a destroying operator delete, the delete-1213      // expression will invoke the destructor (if any) for the object or the1214      // elements of the array being deleted.1215      const FunctionDecl *OperatorDelete = DE->getOperatorDelete();1216      if (const auto *RD = DTy->getAsCXXRecordDecl()) {1217        if (const CXXDestructorDecl *DD = RD->getDestructor();1218            DD && DD->isCalledByDelete(OperatorDelete))1219          CT = canCalleeThrow(*this, DE, DD);1220      }1221 1222      // We always look at the exception specification of the operator delete.1223      CT = mergeCanThrow(CT, canCalleeThrow(*this, DE, OperatorDelete));1224 1225      // If we know we can throw, we're done.1226      if (CT == CT_Can)1227        return CT;1228    }1229    return mergeCanThrow(CT, canSubStmtsThrow(*this, DE));1230  }1231 1232  case Expr::CXXBindTemporaryExprClass: {1233    auto *BTE = cast<CXXBindTemporaryExpr>(S);1234    // The bound temporary has to be destroyed again, which might throw.1235    CanThrowResult CT =1236        canCalleeThrow(*this, BTE, BTE->getTemporary()->getDestructor());1237    if (CT == CT_Can)1238      return CT;1239    return mergeCanThrow(CT, canSubStmtsThrow(*this, BTE));1240  }1241 1242  case Expr::PseudoObjectExprClass: {1243    auto *POE = cast<PseudoObjectExpr>(S);1244    CanThrowResult CT = CT_Cannot;1245    for (const Expr *E : POE->semantics()) {1246      CT = mergeCanThrow(CT, canThrow(E));1247      if (CT == CT_Can)1248        break;1249    }1250    return CT;1251  }1252 1253    // ObjC message sends are like function calls, but never have exception1254    // specs.1255  case Expr::ObjCMessageExprClass:1256  case Expr::ObjCPropertyRefExprClass:1257  case Expr::ObjCSubscriptRefExprClass:1258    return CT_Can;1259 1260    // All the ObjC literals that are implemented as calls are1261    // potentially throwing unless we decide to close off that1262    // possibility.1263  case Expr::ObjCArrayLiteralClass:1264  case Expr::ObjCDictionaryLiteralClass:1265  case Expr::ObjCBoxedExprClass:1266    return CT_Can;1267 1268    // Many other things have subexpressions, so we have to test those.1269    // Some are simple:1270  case Expr::CoawaitExprClass:1271  case Expr::ConditionalOperatorClass:1272  case Expr::CoyieldExprClass:1273  case Expr::CXXRewrittenBinaryOperatorClass:1274  case Expr::CXXStdInitializerListExprClass:1275  case Expr::DesignatedInitExprClass:1276  case Expr::DesignatedInitUpdateExprClass:1277  case Expr::ExprWithCleanupsClass:1278  case Expr::ExtVectorElementExprClass:1279  case Expr::InitListExprClass:1280  case Expr::ArrayInitLoopExprClass:1281  case Expr::MemberExprClass:1282  case Expr::ObjCIsaExprClass:1283  case Expr::ObjCIvarRefExprClass:1284  case Expr::ParenExprClass:1285  case Expr::ParenListExprClass:1286  case Expr::ShuffleVectorExprClass:1287  case Expr::StmtExprClass:1288  case Expr::ConvertVectorExprClass:1289  case Expr::VAArgExprClass:1290  case Expr::CXXParenListInitExprClass:1291    return canSubStmtsThrow(*this, S);1292 1293  case Expr::CompoundLiteralExprClass:1294  case Expr::CXXConstCastExprClass:1295  case Expr::CXXAddrspaceCastExprClass:1296  case Expr::CXXReinterpretCastExprClass:1297  case Expr::BuiltinBitCastExprClass:1298      // FIXME: Properly determine whether a variably-modified type can throw.1299    if (cast<Expr>(S)->getType()->isVariablyModifiedType())1300      return CT_Can;1301    return canSubStmtsThrow(*this, S);1302 1303    // Some might be dependent for other reasons.1304  case Expr::ArraySubscriptExprClass:1305  case Expr::MatrixSubscriptExprClass:1306  case Expr::ArraySectionExprClass:1307  case Expr::OMPArrayShapingExprClass:1308  case Expr::OMPIteratorExprClass:1309  case Expr::BinaryOperatorClass:1310  case Expr::DependentCoawaitExprClass:1311  case Expr::CompoundAssignOperatorClass:1312  case Expr::CStyleCastExprClass:1313  case Expr::CXXStaticCastExprClass:1314  case Expr::CXXFunctionalCastExprClass:1315  case Expr::ImplicitCastExprClass:1316  case Expr::MaterializeTemporaryExprClass:1317  case Expr::UnaryOperatorClass: {1318    // FIXME: Properly determine whether a variably-modified type can throw.1319    if (auto *CE = dyn_cast<CastExpr>(S))1320      if (CE->getType()->isVariablyModifiedType())1321        return CT_Can;1322    CanThrowResult CT =1323        cast<Expr>(S)->isTypeDependent() ? CT_Dependent : CT_Cannot;1324    return mergeCanThrow(CT, canSubStmtsThrow(*this, S));1325  }1326 1327  case Expr::CXXDefaultArgExprClass:1328    return canThrow(cast<CXXDefaultArgExpr>(S)->getExpr());1329 1330  case Expr::CXXDefaultInitExprClass:1331    return canThrow(cast<CXXDefaultInitExpr>(S)->getExpr());1332 1333  case Expr::ChooseExprClass: {1334    auto *CE = cast<ChooseExpr>(S);1335    if (CE->isTypeDependent() || CE->isValueDependent())1336      return CT_Dependent;1337    return canThrow(CE->getChosenSubExpr());1338  }1339 1340  case Expr::GenericSelectionExprClass:1341    if (cast<GenericSelectionExpr>(S)->isResultDependent())1342      return CT_Dependent;1343    return canThrow(cast<GenericSelectionExpr>(S)->getResultExpr());1344 1345    // Some expressions are always dependent.1346  case Expr::CXXDependentScopeMemberExprClass:1347  case Expr::CXXUnresolvedConstructExprClass:1348  case Expr::DependentScopeDeclRefExprClass:1349  case Expr::CXXFoldExprClass:1350  case Expr::RecoveryExprClass:1351    return CT_Dependent;1352 1353  case Expr::AsTypeExprClass:1354  case Expr::BinaryConditionalOperatorClass:1355  case Expr::BlockExprClass:1356  case Expr::CUDAKernelCallExprClass:1357  case Expr::DeclRefExprClass:1358  case Expr::ObjCBridgedCastExprClass:1359  case Expr::ObjCIndirectCopyRestoreExprClass:1360  case Expr::ObjCProtocolExprClass:1361  case Expr::ObjCSelectorExprClass:1362  case Expr::ObjCAvailabilityCheckExprClass:1363  case Expr::OffsetOfExprClass:1364  case Expr::PackExpansionExprClass:1365  case Expr::SubstNonTypeTemplateParmExprClass:1366  case Expr::SubstNonTypeTemplateParmPackExprClass:1367  case Expr::FunctionParmPackExprClass:1368  case Expr::UnaryExprOrTypeTraitExprClass:1369  case Expr::UnresolvedLookupExprClass:1370  case Expr::UnresolvedMemberExprClass:1371    // FIXME: Many of the above can throw.1372    return CT_Cannot;1373 1374  case Expr::AddrLabelExprClass:1375  case Expr::ArrayTypeTraitExprClass:1376  case Expr::AtomicExprClass:1377  case Expr::TypeTraitExprClass:1378  case Expr::CXXBoolLiteralExprClass:1379  case Expr::CXXNoexceptExprClass:1380  case Expr::CXXNullPtrLiteralExprClass:1381  case Expr::CXXPseudoDestructorExprClass:1382  case Expr::CXXScalarValueInitExprClass:1383  case Expr::CXXThisExprClass:1384  case Expr::CXXUuidofExprClass:1385  case Expr::CharacterLiteralClass:1386  case Expr::ExpressionTraitExprClass:1387  case Expr::FloatingLiteralClass:1388  case Expr::GNUNullExprClass:1389  case Expr::ImaginaryLiteralClass:1390  case Expr::ImplicitValueInitExprClass:1391  case Expr::IntegerLiteralClass:1392  case Expr::FixedPointLiteralClass:1393  case Expr::ArrayInitIndexExprClass:1394  case Expr::NoInitExprClass:1395  case Expr::ObjCEncodeExprClass:1396  case Expr::ObjCStringLiteralClass:1397  case Expr::ObjCBoolLiteralExprClass:1398  case Expr::OpaqueValueExprClass:1399  case Expr::PredefinedExprClass:1400  case Expr::SizeOfPackExprClass:1401  case Expr::PackIndexingExprClass:1402  case Expr::StringLiteralClass:1403  case Expr::SourceLocExprClass:1404  case Expr::EmbedExprClass:1405  case Expr::ConceptSpecializationExprClass:1406  case Expr::RequiresExprClass:1407  case Expr::HLSLOutArgExprClass:1408  case Stmt::OpenACCEnterDataConstructClass:1409  case Stmt::OpenACCExitDataConstructClass:1410  case Stmt::OpenACCWaitConstructClass:1411  case Stmt::OpenACCCacheConstructClass:1412  case Stmt::OpenACCInitConstructClass:1413  case Stmt::OpenACCShutdownConstructClass:1414  case Stmt::OpenACCSetConstructClass:1415  case Stmt::OpenACCUpdateConstructClass:1416    // These expressions can never throw.1417    return CT_Cannot;1418 1419  case Expr::MSPropertyRefExprClass:1420  case Expr::MSPropertySubscriptExprClass:1421    llvm_unreachable("Invalid class for expression");1422 1423    // Most statements can throw if any substatement can throw.1424  case Stmt::OpenACCComputeConstructClass:1425  case Stmt::OpenACCLoopConstructClass:1426  case Stmt::OpenACCCombinedConstructClass:1427  case Stmt::OpenACCDataConstructClass:1428  case Stmt::OpenACCHostDataConstructClass:1429  case Stmt::OpenACCAtomicConstructClass:1430  case Stmt::AttributedStmtClass:1431  case Stmt::BreakStmtClass:1432  case Stmt::CapturedStmtClass:1433  case Stmt::SYCLKernelCallStmtClass:1434  case Stmt::CaseStmtClass:1435  case Stmt::CompoundStmtClass:1436  case Stmt::ContinueStmtClass:1437  case Stmt::CoreturnStmtClass:1438  case Stmt::CoroutineBodyStmtClass:1439  case Stmt::CXXCatchStmtClass:1440  case Stmt::CXXForRangeStmtClass:1441  case Stmt::DefaultStmtClass:1442  case Stmt::DoStmtClass:1443  case Stmt::ForStmtClass:1444  case Stmt::GCCAsmStmtClass:1445  case Stmt::GotoStmtClass:1446  case Stmt::IndirectGotoStmtClass:1447  case Stmt::LabelStmtClass:1448  case Stmt::MSAsmStmtClass:1449  case Stmt::MSDependentExistsStmtClass:1450  case Stmt::NullStmtClass:1451  case Stmt::ObjCAtCatchStmtClass:1452  case Stmt::ObjCAtFinallyStmtClass:1453  case Stmt::ObjCAtSynchronizedStmtClass:1454  case Stmt::ObjCAutoreleasePoolStmtClass:1455  case Stmt::ObjCForCollectionStmtClass:1456  case Stmt::OMPAtomicDirectiveClass:1457  case Stmt::OMPAssumeDirectiveClass:1458  case Stmt::OMPBarrierDirectiveClass:1459  case Stmt::OMPCancelDirectiveClass:1460  case Stmt::OMPCancellationPointDirectiveClass:1461  case Stmt::OMPCriticalDirectiveClass:1462  case Stmt::OMPDistributeDirectiveClass:1463  case Stmt::OMPDistributeParallelForDirectiveClass:1464  case Stmt::OMPDistributeParallelForSimdDirectiveClass:1465  case Stmt::OMPDistributeSimdDirectiveClass:1466  case Stmt::OMPFlushDirectiveClass:1467  case Stmt::OMPDepobjDirectiveClass:1468  case Stmt::OMPScanDirectiveClass:1469  case Stmt::OMPForDirectiveClass:1470  case Stmt::OMPForSimdDirectiveClass:1471  case Stmt::OMPMasterDirectiveClass:1472  case Stmt::OMPMasterTaskLoopDirectiveClass:1473  case Stmt::OMPMaskedTaskLoopDirectiveClass:1474  case Stmt::OMPMasterTaskLoopSimdDirectiveClass:1475  case Stmt::OMPMaskedTaskLoopSimdDirectiveClass:1476  case Stmt::OMPOrderedDirectiveClass:1477  case Stmt::OMPCanonicalLoopClass:1478  case Stmt::OMPParallelDirectiveClass:1479  case Stmt::OMPParallelForDirectiveClass:1480  case Stmt::OMPParallelForSimdDirectiveClass:1481  case Stmt::OMPParallelMasterDirectiveClass:1482  case Stmt::OMPParallelMaskedDirectiveClass:1483  case Stmt::OMPParallelMasterTaskLoopDirectiveClass:1484  case Stmt::OMPParallelMaskedTaskLoopDirectiveClass:1485  case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:1486  case Stmt::OMPParallelMaskedTaskLoopSimdDirectiveClass:1487  case Stmt::OMPParallelSectionsDirectiveClass:1488  case Stmt::OMPSectionDirectiveClass:1489  case Stmt::OMPSectionsDirectiveClass:1490  case Stmt::OMPSimdDirectiveClass:1491  case Stmt::OMPTileDirectiveClass:1492  case Stmt::OMPStripeDirectiveClass:1493  case Stmt::OMPUnrollDirectiveClass:1494  case Stmt::OMPReverseDirectiveClass:1495  case Stmt::OMPInterchangeDirectiveClass:1496  case Stmt::OMPFuseDirectiveClass:1497  case Stmt::OMPSingleDirectiveClass:1498  case Stmt::OMPTargetDataDirectiveClass:1499  case Stmt::OMPTargetDirectiveClass:1500  case Stmt::OMPTargetEnterDataDirectiveClass:1501  case Stmt::OMPTargetExitDataDirectiveClass:1502  case Stmt::OMPTargetParallelDirectiveClass:1503  case Stmt::OMPTargetParallelForDirectiveClass:1504  case Stmt::OMPTargetParallelForSimdDirectiveClass:1505  case Stmt::OMPTargetSimdDirectiveClass:1506  case Stmt::OMPTargetTeamsDirectiveClass:1507  case Stmt::OMPTargetTeamsDistributeDirectiveClass:1508  case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:1509  case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:1510  case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:1511  case Stmt::OMPTargetUpdateDirectiveClass:1512  case Stmt::OMPScopeDirectiveClass:1513  case Stmt::OMPTaskDirectiveClass:1514  case Stmt::OMPTaskgroupDirectiveClass:1515  case Stmt::OMPTaskLoopDirectiveClass:1516  case Stmt::OMPTaskLoopSimdDirectiveClass:1517  case Stmt::OMPTaskwaitDirectiveClass:1518  case Stmt::OMPTaskyieldDirectiveClass:1519  case Stmt::OMPErrorDirectiveClass:1520  case Stmt::OMPTeamsDirectiveClass:1521  case Stmt::OMPTeamsDistributeDirectiveClass:1522  case Stmt::OMPTeamsDistributeParallelForDirectiveClass:1523  case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:1524  case Stmt::OMPTeamsDistributeSimdDirectiveClass:1525  case Stmt::OMPInteropDirectiveClass:1526  case Stmt::OMPDispatchDirectiveClass:1527  case Stmt::OMPMaskedDirectiveClass:1528  case Stmt::OMPMetaDirectiveClass:1529  case Stmt::OMPGenericLoopDirectiveClass:1530  case Stmt::OMPTeamsGenericLoopDirectiveClass:1531  case Stmt::OMPTargetTeamsGenericLoopDirectiveClass:1532  case Stmt::OMPParallelGenericLoopDirectiveClass:1533  case Stmt::OMPTargetParallelGenericLoopDirectiveClass:1534  case Stmt::ReturnStmtClass:1535  case Stmt::SEHExceptStmtClass:1536  case Stmt::SEHFinallyStmtClass:1537  case Stmt::SEHLeaveStmtClass:1538  case Stmt::SEHTryStmtClass:1539  case Stmt::SwitchStmtClass:1540  case Stmt::WhileStmtClass:1541    return canSubStmtsThrow(*this, S);1542 1543  case Stmt::DeclStmtClass: {1544    CanThrowResult CT = CT_Cannot;1545    for (const Decl *D : cast<DeclStmt>(S)->decls()) {1546      if (auto *VD = dyn_cast<VarDecl>(D))1547        CT = mergeCanThrow(CT, canVarDeclThrow(*this, VD));1548 1549      // FIXME: Properly determine whether a variably-modified type can throw.1550      if (auto *TND = dyn_cast<TypedefNameDecl>(D))1551        if (TND->getUnderlyingType()->isVariablyModifiedType())1552          return CT_Can;1553      if (auto *VD = dyn_cast<ValueDecl>(D))1554        if (VD->getType()->isVariablyModifiedType())1555          return CT_Can;1556    }1557    return CT;1558  }1559 1560  case Stmt::IfStmtClass: {1561    auto *IS = cast<IfStmt>(S);1562    CanThrowResult CT = CT_Cannot;1563    if (const Stmt *Init = IS->getInit())1564      CT = mergeCanThrow(CT, canThrow(Init));1565    if (const Stmt *CondDS = IS->getConditionVariableDeclStmt())1566      CT = mergeCanThrow(CT, canThrow(CondDS));1567    CT = mergeCanThrow(CT, canThrow(IS->getCond()));1568 1569    // For 'if constexpr', consider only the non-discarded case.1570    // FIXME: We should add a DiscardedStmt marker to the AST.1571    if (std::optional<const Stmt *> Case = IS->getNondiscardedCase(Context))1572      return *Case ? mergeCanThrow(CT, canThrow(*Case)) : CT;1573 1574    CanThrowResult Then = canThrow(IS->getThen());1575    CanThrowResult Else = IS->getElse() ? canThrow(IS->getElse()) : CT_Cannot;1576    if (Then == Else)1577      return mergeCanThrow(CT, Then);1578 1579    // For a dependent 'if constexpr', the result is dependent if it depends on1580    // the value of the condition.1581    return mergeCanThrow(CT, IS->isConstexpr() ? CT_Dependent1582                                               : mergeCanThrow(Then, Else));1583  }1584 1585  case Stmt::CXXTryStmtClass: {1586    auto *TS = cast<CXXTryStmt>(S);1587    // try /*...*/ catch (...) { H } can throw only if H can throw.1588    // Any other try-catch can throw if any substatement can throw.1589    const CXXCatchStmt *FinalHandler = TS->getHandler(TS->getNumHandlers() - 1);1590    if (!FinalHandler->getExceptionDecl())1591      return canThrow(FinalHandler->getHandlerBlock());1592    return canSubStmtsThrow(*this, S);1593  }1594 1595  case Stmt::ObjCAtThrowStmtClass:1596    return CT_Can;1597 1598  case Stmt::ObjCAtTryStmtClass: {1599    auto *TS = cast<ObjCAtTryStmt>(S);1600 1601    // @catch(...) need not be last in Objective-C. Walk backwards until we1602    // see one or hit the @try.1603    CanThrowResult CT = CT_Cannot;1604    if (const Stmt *Finally = TS->getFinallyStmt())1605      CT = mergeCanThrow(CT, canThrow(Finally));1606    for (unsigned I = TS->getNumCatchStmts(); I != 0; --I) {1607      const ObjCAtCatchStmt *Catch = TS->getCatchStmt(I - 1);1608      CT = mergeCanThrow(CT, canThrow(Catch));1609      // If we reach a @catch(...), no earlier exceptions can escape.1610      if (Catch->hasEllipsis())1611        return CT;1612    }1613 1614    // Didn't find an @catch(...). Exceptions from the @try body can escape.1615    return mergeCanThrow(CT, canThrow(TS->getTryBody()));1616  }1617 1618  case Stmt::SYCLUniqueStableNameExprClass:1619    return CT_Cannot;1620  case Stmt::OpenACCAsteriskSizeExprClass:1621    return CT_Cannot;1622  case Stmt::NoStmtClass:1623    llvm_unreachable("Invalid class for statement");1624  }1625  llvm_unreachable("Bogus StmtClass");1626}1627 1628} // end namespace clang1629