SemaExceptionSpec.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336
  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-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file provides Sema routines for C++ exception specification testing.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Sema/SemaInternal.h"
  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/TypeLoc.h"
  18. #include "clang/Basic/Diagnostic.h"
  19. #include "clang/Basic/SourceManager.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallString.h"
  22. namespace clang {
  23. static const FunctionProtoType *GetUnderlyingFunction(QualType T)
  24. {
  25. if (const PointerType *PtrTy = T->getAs<PointerType>())
  26. T = PtrTy->getPointeeType();
  27. else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
  28. T = RefTy->getPointeeType();
  29. else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
  30. T = MPTy->getPointeeType();
  31. return T->getAs<FunctionProtoType>();
  32. }
  33. /// HACK: libstdc++ has a bug where it shadows std::swap with a member
  34. /// swap function then tries to call std::swap unqualified from the exception
  35. /// specification of that function. This function detects whether we're in
  36. /// such a case and turns off delay-parsing of exception specifications.
  37. bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {
  38. auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
  39. // All the problem cases are member functions named "swap" within class
  40. // templates declared directly within namespace std or std::__debug or
  41. // std::__profile.
  42. if (!RD || !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
  43. !D.getIdentifier() || !D.getIdentifier()->isStr("swap"))
  44. return false;
  45. auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext());
  46. if (!ND)
  47. return false;
  48. bool IsInStd = ND->isStdNamespace();
  49. if (!IsInStd) {
  50. // This isn't a direct member of namespace std, but it might still be
  51. // libstdc++'s std::__debug::array or std::__profile::array.
  52. IdentifierInfo *II = ND->getIdentifier();
  53. if (!II || !(II->isStr("__debug") || II->isStr("__profile")) ||
  54. !ND->isInStdNamespace())
  55. return false;
  56. }
  57. // Only apply this hack within a system header.
  58. if (!Context.getSourceManager().isInSystemHeader(D.getBeginLoc()))
  59. return false;
  60. return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
  61. .Case("array", true)
  62. .Case("pair", IsInStd)
  63. .Case("priority_queue", IsInStd)
  64. .Case("stack", IsInStd)
  65. .Case("queue", IsInStd)
  66. .Default(false);
  67. }
  68. ExprResult Sema::ActOnNoexceptSpec(SourceLocation NoexceptLoc,
  69. Expr *NoexceptExpr,
  70. ExceptionSpecificationType &EST) {
  71. // FIXME: This is bogus, a noexcept expression is not a condition.
  72. ExprResult Converted = CheckBooleanCondition(NoexceptLoc, NoexceptExpr);
  73. if (Converted.isInvalid())
  74. return Converted;
  75. if (Converted.get()->isValueDependent()) {
  76. EST = EST_DependentNoexcept;
  77. return Converted;
  78. }
  79. llvm::APSInt Result;
  80. Converted = VerifyIntegerConstantExpression(
  81. Converted.get(), &Result,
  82. diag::err_noexcept_needs_constant_expression,
  83. /*AllowFold*/ false);
  84. if (!Converted.isInvalid())
  85. EST = !Result ? EST_NoexceptFalse : EST_NoexceptTrue;
  86. return Converted;
  87. }
  88. /// CheckSpecifiedExceptionType - Check if the given type is valid in an
  89. /// exception specification. Incomplete types, or pointers to incomplete types
  90. /// other than void are not allowed.
  91. ///
  92. /// \param[in,out] T The exception type. This will be decayed to a pointer type
  93. /// when the input is an array or a function type.
  94. bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {
  95. // C++11 [except.spec]p2:
  96. // A type cv T, "array of T", or "function returning T" denoted
  97. // in an exception-specification is adjusted to type T, "pointer to T", or
  98. // "pointer to function returning T", respectively.
  99. //
  100. // We also apply this rule in C++98.
  101. if (T->isArrayType())
  102. T = Context.getArrayDecayedType(T);
  103. else if (T->isFunctionType())
  104. T = Context.getPointerType(T);
  105. int Kind = 0;
  106. QualType PointeeT = T;
  107. if (const PointerType *PT = T->getAs<PointerType>()) {
  108. PointeeT = PT->getPointeeType();
  109. Kind = 1;
  110. // cv void* is explicitly permitted, despite being a pointer to an
  111. // incomplete type.
  112. if (PointeeT->isVoidType())
  113. return false;
  114. } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
  115. PointeeT = RT->getPointeeType();
  116. Kind = 2;
  117. if (RT->isRValueReferenceType()) {
  118. // C++11 [except.spec]p2:
  119. // A type denoted in an exception-specification shall not denote [...]
  120. // an rvalue reference type.
  121. Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
  122. << T << Range;
  123. return true;
  124. }
  125. }
  126. // C++11 [except.spec]p2:
  127. // A type denoted in an exception-specification shall not denote an
  128. // incomplete type other than a class currently being defined [...].
  129. // A type denoted in an exception-specification shall not denote a
  130. // pointer or reference to an incomplete type, other than (cv) void* or a
  131. // pointer or reference to a class currently being defined.
  132. // In Microsoft mode, downgrade this to a warning.
  133. unsigned DiagID = diag::err_incomplete_in_exception_spec;
  134. bool ReturnValueOnError = true;
  135. if (getLangOpts().MSVCCompat) {
  136. DiagID = diag::ext_incomplete_in_exception_spec;
  137. ReturnValueOnError = false;
  138. }
  139. if (!(PointeeT->isRecordType() &&
  140. PointeeT->castAs<RecordType>()->isBeingDefined()) &&
  141. RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range))
  142. return ReturnValueOnError;
  143. return false;
  144. }
  145. /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
  146. /// to member to a function with an exception specification. This means that
  147. /// it is invalid to add another level of indirection.
  148. bool Sema::CheckDistantExceptionSpec(QualType T) {
  149. // C++17 removes this rule in favor of putting exception specifications into
  150. // the type system.
  151. if (getLangOpts().CPlusPlus17)
  152. return false;
  153. if (const PointerType *PT = T->getAs<PointerType>())
  154. T = PT->getPointeeType();
  155. else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
  156. T = PT->getPointeeType();
  157. else
  158. return false;
  159. const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
  160. if (!FnT)
  161. return false;
  162. return FnT->hasExceptionSpec();
  163. }
  164. const FunctionProtoType *
  165. Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
  166. if (FPT->getExceptionSpecType() == EST_Unparsed) {
  167. Diag(Loc, diag::err_exception_spec_not_parsed);
  168. return nullptr;
  169. }
  170. if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  171. return FPT;
  172. FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
  173. const FunctionProtoType *SourceFPT =
  174. SourceDecl->getType()->castAs<FunctionProtoType>();
  175. // If the exception specification has already been resolved, just return it.
  176. if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
  177. return SourceFPT;
  178. // Compute or instantiate the exception specification now.
  179. if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
  180. EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
  181. else
  182. InstantiateExceptionSpec(Loc, SourceDecl);
  183. const FunctionProtoType *Proto =
  184. SourceDecl->getType()->castAs<FunctionProtoType>();
  185. if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
  186. Diag(Loc, diag::err_exception_spec_not_parsed);
  187. Proto = nullptr;
  188. }
  189. return Proto;
  190. }
  191. void
  192. Sema::UpdateExceptionSpec(FunctionDecl *FD,
  193. const FunctionProtoType::ExceptionSpecInfo &ESI) {
  194. // If we've fully resolved the exception specification, notify listeners.
  195. if (!isUnresolvedExceptionSpec(ESI.Type))
  196. if (auto *Listener = getASTMutationListener())
  197. Listener->ResolvedExceptionSpec(FD);
  198. for (FunctionDecl *Redecl : FD->redecls())
  199. Context.adjustExceptionSpec(Redecl, ESI);
  200. }
  201. static bool exceptionSpecNotKnownYet(const FunctionDecl *FD) {
  202. auto *MD = dyn_cast<CXXMethodDecl>(FD);
  203. if (!MD)
  204. return false;
  205. auto EST = MD->getType()->castAs<FunctionProtoType>()->getExceptionSpecType();
  206. return EST == EST_Unparsed ||
  207. (EST == EST_Unevaluated && MD->getParent()->isBeingDefined());
  208. }
  209. static bool CheckEquivalentExceptionSpecImpl(
  210. Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
  211. const FunctionProtoType *Old, SourceLocation OldLoc,
  212. const FunctionProtoType *New, SourceLocation NewLoc,
  213. bool *MissingExceptionSpecification = nullptr,
  214. bool *MissingEmptyExceptionSpecification = nullptr,
  215. bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false);
  216. /// Determine whether a function has an implicitly-generated exception
  217. /// specification.
  218. static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
  219. if (!isa<CXXDestructorDecl>(Decl) &&
  220. Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
  221. Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
  222. return false;
  223. // For a function that the user didn't declare:
  224. // - if this is a destructor, its exception specification is implicit.
  225. // - if this is 'operator delete' or 'operator delete[]', the exception
  226. // specification is as-if an explicit exception specification was given
  227. // (per [basic.stc.dynamic]p2).
  228. if (!Decl->getTypeSourceInfo())
  229. return isa<CXXDestructorDecl>(Decl);
  230. const FunctionProtoType *Ty =
  231. Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
  232. return !Ty->hasExceptionSpec();
  233. }
  234. bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
  235. // Just completely ignore this under -fno-exceptions prior to C++17.
  236. // In C++17 onwards, the exception specification is part of the type and
  237. // we will diagnose mismatches anyway, so it's better to check for them here.
  238. if (!getLangOpts().CXXExceptions && !getLangOpts().CPlusPlus17)
  239. return false;
  240. OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
  241. bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
  242. bool MissingExceptionSpecification = false;
  243. bool MissingEmptyExceptionSpecification = false;
  244. unsigned DiagID = diag::err_mismatched_exception_spec;
  245. bool ReturnValueOnError = true;
  246. if (getLangOpts().MSVCCompat) {
  247. DiagID = diag::ext_mismatched_exception_spec;
  248. ReturnValueOnError = false;
  249. }
  250. // If we're befriending a member function of a class that's currently being
  251. // defined, we might not be able to work out its exception specification yet.
  252. // If not, defer the check until later.
  253. if (exceptionSpecNotKnownYet(Old) || exceptionSpecNotKnownYet(New)) {
  254. DelayedEquivalentExceptionSpecChecks.push_back({New, Old});
  255. return false;
  256. }
  257. // Check the types as written: they must match before any exception
  258. // specification adjustment is applied.
  259. if (!CheckEquivalentExceptionSpecImpl(
  260. *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
  261. Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
  262. New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
  263. &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
  264. /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
  265. // C++11 [except.spec]p4 [DR1492]:
  266. // If a declaration of a function has an implicit
  267. // exception-specification, other declarations of the function shall
  268. // not specify an exception-specification.
  269. if (getLangOpts().CPlusPlus11 && getLangOpts().CXXExceptions &&
  270. hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
  271. Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
  272. << hasImplicitExceptionSpec(Old);
  273. if (Old->getLocation().isValid())
  274. Diag(Old->getLocation(), diag::note_previous_declaration);
  275. }
  276. return false;
  277. }
  278. // The failure was something other than an missing exception
  279. // specification; return an error, except in MS mode where this is a warning.
  280. if (!MissingExceptionSpecification)
  281. return ReturnValueOnError;
  282. const FunctionProtoType *NewProto =
  283. New->getType()->castAs<FunctionProtoType>();
  284. // The new function declaration is only missing an empty exception
  285. // specification "throw()". If the throw() specification came from a
  286. // function in a system header that has C linkage, just add an empty
  287. // exception specification to the "new" declaration. Note that C library
  288. // implementations are permitted to add these nothrow exception
  289. // specifications.
  290. //
  291. // Likewise if the old function is a builtin.
  292. if (MissingEmptyExceptionSpecification && NewProto &&
  293. (Old->getLocation().isInvalid() ||
  294. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  295. Old->getBuiltinID()) &&
  296. Old->isExternC()) {
  297. New->setType(Context.getFunctionType(
  298. NewProto->getReturnType(), NewProto->getParamTypes(),
  299. NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
  300. return false;
  301. }
  302. const FunctionProtoType *OldProto =
  303. Old->getType()->castAs<FunctionProtoType>();
  304. FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
  305. if (ESI.Type == EST_Dynamic) {
  306. // FIXME: What if the exceptions are described in terms of the old
  307. // prototype's parameters?
  308. ESI.Exceptions = OldProto->exceptions();
  309. }
  310. if (ESI.Type == EST_NoexceptFalse)
  311. ESI.Type = EST_None;
  312. if (ESI.Type == EST_NoexceptTrue)
  313. ESI.Type = EST_BasicNoexcept;
  314. // For dependent noexcept, we can't just take the expression from the old
  315. // prototype. It likely contains references to the old prototype's parameters.
  316. if (ESI.Type == EST_DependentNoexcept) {
  317. New->setInvalidDecl();
  318. } else {
  319. // Update the type of the function with the appropriate exception
  320. // specification.
  321. New->setType(Context.getFunctionType(
  322. NewProto->getReturnType(), NewProto->getParamTypes(),
  323. NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
  324. }
  325. if (getLangOpts().MSVCCompat && ESI.Type != EST_DependentNoexcept) {
  326. // Allow missing exception specifications in redeclarations as an extension.
  327. DiagID = diag::ext_ms_missing_exception_specification;
  328. ReturnValueOnError = false;
  329. } else if (New->isReplaceableGlobalAllocationFunction() &&
  330. ESI.Type != EST_DependentNoexcept) {
  331. // Allow missing exception specifications in redeclarations as an extension,
  332. // when declaring a replaceable global allocation function.
  333. DiagID = diag::ext_missing_exception_specification;
  334. ReturnValueOnError = false;
  335. } else if (ESI.Type == EST_NoThrow) {
  336. // Allow missing attribute 'nothrow' in redeclarations, since this is a very
  337. // common omission.
  338. DiagID = diag::ext_missing_exception_specification;
  339. ReturnValueOnError = false;
  340. } else {
  341. DiagID = diag::err_missing_exception_specification;
  342. ReturnValueOnError = true;
  343. }
  344. // Warn about the lack of exception specification.
  345. SmallString<128> ExceptionSpecString;
  346. llvm::raw_svector_ostream OS(ExceptionSpecString);
  347. switch (OldProto->getExceptionSpecType()) {
  348. case EST_DynamicNone:
  349. OS << "throw()";
  350. break;
  351. case EST_Dynamic: {
  352. OS << "throw(";
  353. bool OnFirstException = true;
  354. for (const auto &E : OldProto->exceptions()) {
  355. if (OnFirstException)
  356. OnFirstException = false;
  357. else
  358. OS << ", ";
  359. OS << E.getAsString(getPrintingPolicy());
  360. }
  361. OS << ")";
  362. break;
  363. }
  364. case EST_BasicNoexcept:
  365. OS << "noexcept";
  366. break;
  367. case EST_DependentNoexcept:
  368. case EST_NoexceptFalse:
  369. case EST_NoexceptTrue:
  370. OS << "noexcept(";
  371. assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
  372. OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
  373. OS << ")";
  374. break;
  375. case EST_NoThrow:
  376. OS <<"__attribute__((nothrow))";
  377. break;
  378. case EST_None:
  379. case EST_MSAny:
  380. case EST_Unevaluated:
  381. case EST_Uninstantiated:
  382. case EST_Unparsed:
  383. llvm_unreachable("This spec type is compatible with none.");
  384. }
  385. SourceLocation FixItLoc;
  386. if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
  387. TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
  388. // FIXME: Preserve enough information so that we can produce a correct fixit
  389. // location when there is a trailing return type.
  390. if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
  391. if (!FTLoc.getTypePtr()->hasTrailingReturn())
  392. FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
  393. }
  394. if (FixItLoc.isInvalid())
  395. Diag(New->getLocation(), DiagID)
  396. << New << OS.str();
  397. else {
  398. Diag(New->getLocation(), DiagID)
  399. << New << OS.str()
  400. << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
  401. }
  402. if (Old->getLocation().isValid())
  403. Diag(Old->getLocation(), diag::note_previous_declaration);
  404. return ReturnValueOnError;
  405. }
  406. /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
  407. /// exception specifications. Exception specifications are equivalent if
  408. /// they allow exactly the same set of exception types. It does not matter how
  409. /// that is achieved. See C++ [except.spec]p2.
  410. bool Sema::CheckEquivalentExceptionSpec(
  411. const FunctionProtoType *Old, SourceLocation OldLoc,
  412. const FunctionProtoType *New, SourceLocation NewLoc) {
  413. if (!getLangOpts().CXXExceptions)
  414. return false;
  415. unsigned DiagID = diag::err_mismatched_exception_spec;
  416. if (getLangOpts().MSVCCompat)
  417. DiagID = diag::ext_mismatched_exception_spec;
  418. bool Result = CheckEquivalentExceptionSpecImpl(
  419. *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
  420. Old, OldLoc, New, NewLoc);
  421. // In Microsoft mode, mismatching exception specifications just cause a warning.
  422. if (getLangOpts().MSVCCompat)
  423. return false;
  424. return Result;
  425. }
  426. /// CheckEquivalentExceptionSpec - Check if the two types have compatible
  427. /// exception specifications. See C++ [except.spec]p3.
  428. ///
  429. /// \return \c false if the exception specifications match, \c true if there is
  430. /// a problem. If \c true is returned, either a diagnostic has already been
  431. /// produced or \c *MissingExceptionSpecification is set to \c true.
  432. static bool CheckEquivalentExceptionSpecImpl(
  433. Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
  434. const FunctionProtoType *Old, SourceLocation OldLoc,
  435. const FunctionProtoType *New, SourceLocation NewLoc,
  436. bool *MissingExceptionSpecification,
  437. bool *MissingEmptyExceptionSpecification,
  438. bool AllowNoexceptAllMatchWithNoSpec, bool IsOperatorNew) {
  439. if (MissingExceptionSpecification)
  440. *MissingExceptionSpecification = false;
  441. if (MissingEmptyExceptionSpecification)
  442. *MissingEmptyExceptionSpecification = false;
  443. Old = S.ResolveExceptionSpec(NewLoc, Old);
  444. if (!Old)
  445. return false;
  446. New = S.ResolveExceptionSpec(NewLoc, New);
  447. if (!New)
  448. return false;
  449. // C++0x [except.spec]p3: Two exception-specifications are compatible if:
  450. // - both are non-throwing, regardless of their form,
  451. // - both have the form noexcept(constant-expression) and the constant-
  452. // expressions are equivalent,
  453. // - both are dynamic-exception-specifications that have the same set of
  454. // adjusted types.
  455. //
  456. // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
  457. // of the form throw(), noexcept, or noexcept(constant-expression) where the
  458. // constant-expression yields true.
  459. //
  460. // C++0x [except.spec]p4: If any declaration of a function has an exception-
  461. // specifier that is not a noexcept-specification allowing all exceptions,
  462. // all declarations [...] of that function shall have a compatible
  463. // exception-specification.
  464. //
  465. // That last point basically means that noexcept(false) matches no spec.
  466. // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
  467. ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
  468. ExceptionSpecificationType NewEST = New->getExceptionSpecType();
  469. assert(!isUnresolvedExceptionSpec(OldEST) &&
  470. !isUnresolvedExceptionSpec(NewEST) &&
  471. "Shouldn't see unknown exception specifications here");
  472. CanThrowResult OldCanThrow = Old->canThrow();
  473. CanThrowResult NewCanThrow = New->canThrow();
  474. // Any non-throwing specifications are compatible.
  475. if (OldCanThrow == CT_Cannot && NewCanThrow == CT_Cannot)
  476. return false;
  477. // Any throws-anything specifications are usually compatible.
  478. if (OldCanThrow == CT_Can && OldEST != EST_Dynamic &&
  479. NewCanThrow == CT_Can && NewEST != EST_Dynamic) {
  480. // The exception is that the absence of an exception specification only
  481. // matches noexcept(false) for functions, as described above.
  482. if (!AllowNoexceptAllMatchWithNoSpec &&
  483. ((OldEST == EST_None && NewEST == EST_NoexceptFalse) ||
  484. (OldEST == EST_NoexceptFalse && NewEST == EST_None))) {
  485. // This is the disallowed case.
  486. } else {
  487. return false;
  488. }
  489. }
  490. // C++14 [except.spec]p3:
  491. // Two exception-specifications are compatible if [...] both have the form
  492. // noexcept(constant-expression) and the constant-expressions are equivalent
  493. if (OldEST == EST_DependentNoexcept && NewEST == EST_DependentNoexcept) {
  494. llvm::FoldingSetNodeID OldFSN, NewFSN;
  495. Old->getNoexceptExpr()->Profile(OldFSN, S.Context, true);
  496. New->getNoexceptExpr()->Profile(NewFSN, S.Context, true);
  497. if (OldFSN == NewFSN)
  498. return false;
  499. }
  500. // Dynamic exception specifications with the same set of adjusted types
  501. // are compatible.
  502. if (OldEST == EST_Dynamic && NewEST == EST_Dynamic) {
  503. bool Success = true;
  504. // Both have a dynamic exception spec. Collect the first set, then compare
  505. // to the second.
  506. llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
  507. for (const auto &I : Old->exceptions())
  508. OldTypes.insert(S.Context.getCanonicalType(I).getUnqualifiedType());
  509. for (const auto &I : New->exceptions()) {
  510. CanQualType TypePtr = S.Context.getCanonicalType(I).getUnqualifiedType();
  511. if (OldTypes.count(TypePtr))
  512. NewTypes.insert(TypePtr);
  513. else {
  514. Success = false;
  515. break;
  516. }
  517. }
  518. if (Success && OldTypes.size() == NewTypes.size())
  519. return false;
  520. }
  521. // As a special compatibility feature, under C++0x we accept no spec and
  522. // throw(std::bad_alloc) as equivalent for operator new and operator new[].
  523. // This is because the implicit declaration changed, but old code would break.
  524. if (S.getLangOpts().CPlusPlus11 && IsOperatorNew) {
  525. const FunctionProtoType *WithExceptions = nullptr;
  526. if (OldEST == EST_None && NewEST == EST_Dynamic)
  527. WithExceptions = New;
  528. else if (OldEST == EST_Dynamic && NewEST == EST_None)
  529. WithExceptions = Old;
  530. if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
  531. // One has no spec, the other throw(something). If that something is
  532. // std::bad_alloc, all conditions are met.
  533. QualType Exception = *WithExceptions->exception_begin();
  534. if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
  535. IdentifierInfo* Name = ExRecord->getIdentifier();
  536. if (Name && Name->getName() == "bad_alloc") {
  537. // It's called bad_alloc, but is it in std?
  538. if (ExRecord->isInStdNamespace()) {
  539. return false;
  540. }
  541. }
  542. }
  543. }
  544. }
  545. // If the caller wants to handle the case that the new function is
  546. // incompatible due to a missing exception specification, let it.
  547. if (MissingExceptionSpecification && OldEST != EST_None &&
  548. NewEST == EST_None) {
  549. // The old type has an exception specification of some sort, but
  550. // the new type does not.
  551. *MissingExceptionSpecification = true;
  552. if (MissingEmptyExceptionSpecification && OldCanThrow == CT_Cannot) {
  553. // The old type has a throw() or noexcept(true) exception specification
  554. // and the new type has no exception specification, and the caller asked
  555. // to handle this itself.
  556. *MissingEmptyExceptionSpecification = true;
  557. }
  558. return true;
  559. }
  560. S.Diag(NewLoc, DiagID);
  561. if (NoteID.getDiagID() != 0 && OldLoc.isValid())
  562. S.Diag(OldLoc, NoteID);
  563. return true;
  564. }
  565. bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
  566. const PartialDiagnostic &NoteID,
  567. const FunctionProtoType *Old,
  568. SourceLocation OldLoc,
  569. const FunctionProtoType *New,
  570. SourceLocation NewLoc) {
  571. if (!getLangOpts().CXXExceptions)
  572. return false;
  573. return CheckEquivalentExceptionSpecImpl(*this, DiagID, NoteID, Old, OldLoc,
  574. New, NewLoc);
  575. }
  576. bool Sema::handlerCanCatch(QualType HandlerType, QualType ExceptionType) {
  577. // [except.handle]p3:
  578. // A handler is a match for an exception object of type E if:
  579. // HandlerType must be ExceptionType or derived from it, or pointer or
  580. // reference to such types.
  581. const ReferenceType *RefTy = HandlerType->getAs<ReferenceType>();
  582. if (RefTy)
  583. HandlerType = RefTy->getPointeeType();
  584. // -- the handler is of type cv T or cv T& and E and T are the same type
  585. if (Context.hasSameUnqualifiedType(ExceptionType, HandlerType))
  586. return true;
  587. // FIXME: ObjC pointer types?
  588. if (HandlerType->isPointerType() || HandlerType->isMemberPointerType()) {
  589. if (RefTy && (!HandlerType.isConstQualified() ||
  590. HandlerType.isVolatileQualified()))
  591. return false;
  592. // -- the handler is of type cv T or const T& where T is a pointer or
  593. // pointer to member type and E is std::nullptr_t
  594. if (ExceptionType->isNullPtrType())
  595. return true;
  596. // -- the handler is of type cv T or const T& where T is a pointer or
  597. // pointer to member type and E is a pointer or pointer to member type
  598. // that can be converted to T by one or more of
  599. // -- a qualification conversion
  600. // -- a function pointer conversion
  601. bool LifetimeConv;
  602. QualType Result;
  603. // FIXME: Should we treat the exception as catchable if a lifetime
  604. // conversion is required?
  605. if (IsQualificationConversion(ExceptionType, HandlerType, false,
  606. LifetimeConv) ||
  607. IsFunctionConversion(ExceptionType, HandlerType, Result))
  608. return true;
  609. // -- a standard pointer conversion [...]
  610. if (!ExceptionType->isPointerType() || !HandlerType->isPointerType())
  611. return false;
  612. // Handle the "qualification conversion" portion.
  613. Qualifiers EQuals, HQuals;
  614. ExceptionType = Context.getUnqualifiedArrayType(
  615. ExceptionType->getPointeeType(), EQuals);
  616. HandlerType = Context.getUnqualifiedArrayType(
  617. HandlerType->getPointeeType(), HQuals);
  618. if (!HQuals.compatiblyIncludes(EQuals))
  619. return false;
  620. if (HandlerType->isVoidType() && ExceptionType->isObjectType())
  621. return true;
  622. // The only remaining case is a derived-to-base conversion.
  623. }
  624. // -- the handler is of type cg T or cv T& and T is an unambiguous public
  625. // base class of E
  626. if (!ExceptionType->isRecordType() || !HandlerType->isRecordType())
  627. return false;
  628. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  629. /*DetectVirtual=*/false);
  630. if (!IsDerivedFrom(SourceLocation(), ExceptionType, HandlerType, Paths) ||
  631. Paths.isAmbiguous(Context.getCanonicalType(HandlerType)))
  632. return false;
  633. // Do this check from a context without privileges.
  634. switch (CheckBaseClassAccess(SourceLocation(), HandlerType, ExceptionType,
  635. Paths.front(),
  636. /*Diagnostic*/ 0,
  637. /*ForceCheck*/ true,
  638. /*ForceUnprivileged*/ true)) {
  639. case AR_accessible: return true;
  640. case AR_inaccessible: return false;
  641. case AR_dependent:
  642. llvm_unreachable("access check dependent for unprivileged context");
  643. case AR_delayed:
  644. llvm_unreachable("access check delayed in non-declaration");
  645. }
  646. llvm_unreachable("unexpected access check result");
  647. }
  648. /// CheckExceptionSpecSubset - Check whether the second function type's
  649. /// exception specification is a subset (or equivalent) of the first function
  650. /// type. This is used by override and pointer assignment checks.
  651. bool Sema::CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
  652. const PartialDiagnostic &NestedDiagID,
  653. const PartialDiagnostic &NoteID,
  654. const PartialDiagnostic &NoThrowDiagID,
  655. const FunctionProtoType *Superset,
  656. SourceLocation SuperLoc,
  657. const FunctionProtoType *Subset,
  658. SourceLocation SubLoc) {
  659. // Just auto-succeed under -fno-exceptions.
  660. if (!getLangOpts().CXXExceptions)
  661. return false;
  662. // FIXME: As usual, we could be more specific in our error messages, but
  663. // that better waits until we've got types with source locations.
  664. if (!SubLoc.isValid())
  665. SubLoc = SuperLoc;
  666. // Resolve the exception specifications, if needed.
  667. Superset = ResolveExceptionSpec(SuperLoc, Superset);
  668. if (!Superset)
  669. return false;
  670. Subset = ResolveExceptionSpec(SubLoc, Subset);
  671. if (!Subset)
  672. return false;
  673. ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
  674. ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
  675. assert(!isUnresolvedExceptionSpec(SuperEST) &&
  676. !isUnresolvedExceptionSpec(SubEST) &&
  677. "Shouldn't see unknown exception specifications here");
  678. // If there are dependent noexcept specs, assume everything is fine. Unlike
  679. // with the equivalency check, this is safe in this case, because we don't
  680. // want to merge declarations. Checks after instantiation will catch any
  681. // omissions we make here.
  682. if (SuperEST == EST_DependentNoexcept || SubEST == EST_DependentNoexcept)
  683. return false;
  684. CanThrowResult SuperCanThrow = Superset->canThrow();
  685. CanThrowResult SubCanThrow = Subset->canThrow();
  686. // If the superset contains everything or the subset contains nothing, we're
  687. // done.
  688. if ((SuperCanThrow == CT_Can && SuperEST != EST_Dynamic) ||
  689. SubCanThrow == CT_Cannot)
  690. return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
  691. Subset, SubLoc);
  692. // Allow __declspec(nothrow) to be missing on redeclaration as an extension in
  693. // some cases.
  694. if (NoThrowDiagID.getDiagID() != 0 && SubCanThrow == CT_Can &&
  695. SuperCanThrow == CT_Cannot && SuperEST == EST_NoThrow) {
  696. Diag(SubLoc, NoThrowDiagID);
  697. if (NoteID.getDiagID() != 0)
  698. Diag(SuperLoc, NoteID);
  699. return true;
  700. }
  701. // If the subset contains everything or the superset contains nothing, we've
  702. // failed.
  703. if ((SubCanThrow == CT_Can && SubEST != EST_Dynamic) ||
  704. SuperCanThrow == CT_Cannot) {
  705. Diag(SubLoc, DiagID);
  706. if (NoteID.getDiagID() != 0)
  707. Diag(SuperLoc, NoteID);
  708. return true;
  709. }
  710. assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
  711. "Exception spec subset: non-dynamic case slipped through.");
  712. // Neither contains everything or nothing. Do a proper comparison.
  713. for (QualType SubI : Subset->exceptions()) {
  714. if (const ReferenceType *RefTy = SubI->getAs<ReferenceType>())
  715. SubI = RefTy->getPointeeType();
  716. // Make sure it's in the superset.
  717. bool Contained = false;
  718. for (QualType SuperI : Superset->exceptions()) {
  719. // [except.spec]p5:
  720. // the target entity shall allow at least the exceptions allowed by the
  721. // source
  722. //
  723. // We interpret this as meaning that a handler for some target type would
  724. // catch an exception of each source type.
  725. if (handlerCanCatch(SuperI, SubI)) {
  726. Contained = true;
  727. break;
  728. }
  729. }
  730. if (!Contained) {
  731. Diag(SubLoc, DiagID);
  732. if (NoteID.getDiagID() != 0)
  733. Diag(SuperLoc, NoteID);
  734. return true;
  735. }
  736. }
  737. // We've run half the gauntlet.
  738. return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
  739. Subset, SubLoc);
  740. }
  741. static bool
  742. CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID,
  743. const PartialDiagnostic &NoteID, QualType Target,
  744. SourceLocation TargetLoc, QualType Source,
  745. SourceLocation SourceLoc) {
  746. const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
  747. if (!TFunc)
  748. return false;
  749. const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
  750. if (!SFunc)
  751. return false;
  752. return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
  753. SFunc, SourceLoc);
  754. }
  755. /// CheckParamExceptionSpec - Check if the parameter and return types of the
  756. /// two functions have equivalent exception specs. This is part of the
  757. /// assignment and override compatibility check. We do not check the parameters
  758. /// of parameter function pointers recursively, as no sane programmer would
  759. /// even be able to write such a function type.
  760. bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &DiagID,
  761. const PartialDiagnostic &NoteID,
  762. const FunctionProtoType *Target,
  763. SourceLocation TargetLoc,
  764. const FunctionProtoType *Source,
  765. SourceLocation SourceLoc) {
  766. auto RetDiag = DiagID;
  767. RetDiag << 0;
  768. if (CheckSpecForTypesEquivalent(
  769. *this, RetDiag, PDiag(),
  770. Target->getReturnType(), TargetLoc, Source->getReturnType(),
  771. SourceLoc))
  772. return true;
  773. // We shouldn't even be testing this unless the arguments are otherwise
  774. // compatible.
  775. assert(Target->getNumParams() == Source->getNumParams() &&
  776. "Functions have different argument counts.");
  777. for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
  778. auto ParamDiag = DiagID;
  779. ParamDiag << 1;
  780. if (CheckSpecForTypesEquivalent(
  781. *this, ParamDiag, PDiag(),
  782. Target->getParamType(i), TargetLoc, Source->getParamType(i),
  783. SourceLoc))
  784. return true;
  785. }
  786. return false;
  787. }
  788. bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
  789. // First we check for applicability.
  790. // Target type must be a function, function pointer or function reference.
  791. const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
  792. if (!ToFunc || ToFunc->hasDependentExceptionSpec())
  793. return false;
  794. // SourceType must be a function or function pointer.
  795. const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
  796. if (!FromFunc || FromFunc->hasDependentExceptionSpec())
  797. return false;
  798. unsigned DiagID = diag::err_incompatible_exception_specs;
  799. unsigned NestedDiagID = diag::err_deep_exception_specs_differ;
  800. // This is not an error in C++17 onwards, unless the noexceptness doesn't
  801. // match, but in that case we have a full-on type mismatch, not just a
  802. // type sugar mismatch.
  803. if (getLangOpts().CPlusPlus17) {
  804. DiagID = diag::warn_incompatible_exception_specs;
  805. NestedDiagID = diag::warn_deep_exception_specs_differ;
  806. }
  807. // Now we've got the correct types on both sides, check their compatibility.
  808. // This means that the source of the conversion can only throw a subset of
  809. // the exceptions of the target, and any exception specs on arguments or
  810. // return types must be equivalent.
  811. //
  812. // FIXME: If there is a nested dependent exception specification, we should
  813. // not be checking it here. This is fine:
  814. // template<typename T> void f() {
  815. // void (*p)(void (*) throw(T));
  816. // void (*q)(void (*) throw(int)) = p;
  817. // }
  818. // ... because it might be instantiated with T=int.
  819. return CheckExceptionSpecSubset(
  820. PDiag(DiagID), PDiag(NestedDiagID), PDiag(), PDiag(), ToFunc,
  821. From->getSourceRange().getBegin(), FromFunc, SourceLocation()) &&
  822. !getLangOpts().CPlusPlus17;
  823. }
  824. bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
  825. const CXXMethodDecl *Old) {
  826. // If the new exception specification hasn't been parsed yet, skip the check.
  827. // We'll get called again once it's been parsed.
  828. if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
  829. EST_Unparsed)
  830. return false;
  831. // Don't check uninstantiated template destructors at all. We can only
  832. // synthesize correct specs after the template is instantiated.
  833. if (isa<CXXDestructorDecl>(New) && New->getParent()->isDependentType())
  834. return false;
  835. // If the old exception specification hasn't been parsed yet, or the new
  836. // exception specification can't be computed yet, remember that we need to
  837. // perform this check when we get to the end of the outermost
  838. // lexically-surrounding class.
  839. if (exceptionSpecNotKnownYet(Old) || exceptionSpecNotKnownYet(New)) {
  840. DelayedOverridingExceptionSpecChecks.push_back({New, Old});
  841. return false;
  842. }
  843. unsigned DiagID = diag::err_override_exception_spec;
  844. if (getLangOpts().MSVCCompat)
  845. DiagID = diag::ext_override_exception_spec;
  846. return CheckExceptionSpecSubset(PDiag(DiagID),
  847. PDiag(diag::err_deep_exception_specs_differ),
  848. PDiag(diag::note_overridden_virtual_function),
  849. PDiag(diag::ext_override_exception_spec),
  850. Old->getType()->getAs<FunctionProtoType>(),
  851. Old->getLocation(),
  852. New->getType()->getAs<FunctionProtoType>(),
  853. New->getLocation());
  854. }
  855. static CanThrowResult canSubExprsThrow(Sema &S, const Expr *E) {
  856. CanThrowResult R = CT_Cannot;
  857. for (const Stmt *SubStmt : E->children()) {
  858. R = mergeCanThrow(R, S.canThrow(cast<Expr>(SubStmt)));
  859. if (R == CT_Can)
  860. break;
  861. }
  862. return R;
  863. }
  864. static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
  865. // As an extension, we assume that __attribute__((nothrow)) functions don't
  866. // throw.
  867. if (D && isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
  868. return CT_Cannot;
  869. QualType T;
  870. // In C++1z, just look at the function type of the callee.
  871. if (S.getLangOpts().CPlusPlus17 && isa<CallExpr>(E)) {
  872. E = cast<CallExpr>(E)->getCallee();
  873. T = E->getType();
  874. if (T->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
  875. // Sadly we don't preserve the actual type as part of the "bound member"
  876. // placeholder, so we need to reconstruct it.
  877. E = E->IgnoreParenImpCasts();
  878. // Could be a call to a pointer-to-member or a plain member access.
  879. if (auto *Op = dyn_cast<BinaryOperator>(E)) {
  880. assert(Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI);
  881. T = Op->getRHS()->getType()
  882. ->castAs<MemberPointerType>()->getPointeeType();
  883. } else {
  884. T = cast<MemberExpr>(E)->getMemberDecl()->getType();
  885. }
  886. }
  887. } else if (const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D))
  888. T = VD->getType();
  889. else
  890. // If we have no clue what we're calling, assume the worst.
  891. return CT_Can;
  892. const FunctionProtoType *FT;
  893. if ((FT = T->getAs<FunctionProtoType>())) {
  894. } else if (const PointerType *PT = T->getAs<PointerType>())
  895. FT = PT->getPointeeType()->getAs<FunctionProtoType>();
  896. else if (const ReferenceType *RT = T->getAs<ReferenceType>())
  897. FT = RT->getPointeeType()->getAs<FunctionProtoType>();
  898. else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
  899. FT = MT->getPointeeType()->getAs<FunctionProtoType>();
  900. else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
  901. FT = BT->getPointeeType()->getAs<FunctionProtoType>();
  902. if (!FT)
  903. return CT_Can;
  904. FT = S.ResolveExceptionSpec(E->getBeginLoc(), FT);
  905. if (!FT)
  906. return CT_Can;
  907. return FT->canThrow();
  908. }
  909. static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
  910. if (DC->isTypeDependent())
  911. return CT_Dependent;
  912. if (!DC->getTypeAsWritten()->isReferenceType())
  913. return CT_Cannot;
  914. if (DC->getSubExpr()->isTypeDependent())
  915. return CT_Dependent;
  916. return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
  917. }
  918. static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
  919. if (DC->isTypeOperand())
  920. return CT_Cannot;
  921. Expr *Op = DC->getExprOperand();
  922. if (Op->isTypeDependent())
  923. return CT_Dependent;
  924. const RecordType *RT = Op->getType()->getAs<RecordType>();
  925. if (!RT)
  926. return CT_Cannot;
  927. if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
  928. return CT_Cannot;
  929. if (Op->Classify(S.Context).isPRValue())
  930. return CT_Cannot;
  931. return CT_Can;
  932. }
  933. CanThrowResult Sema::canThrow(const Expr *E) {
  934. // C++ [expr.unary.noexcept]p3:
  935. // [Can throw] if in a potentially-evaluated context the expression would
  936. // contain:
  937. switch (E->getStmtClass()) {
  938. case Expr::ConstantExprClass:
  939. return canThrow(cast<ConstantExpr>(E)->getSubExpr());
  940. case Expr::CXXThrowExprClass:
  941. // - a potentially evaluated throw-expression
  942. return CT_Can;
  943. case Expr::CXXDynamicCastExprClass: {
  944. // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
  945. // where T is a reference type, that requires a run-time check
  946. CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
  947. if (CT == CT_Can)
  948. return CT;
  949. return mergeCanThrow(CT, canSubExprsThrow(*this, E));
  950. }
  951. case Expr::CXXTypeidExprClass:
  952. // - a potentially evaluated typeid expression applied to a glvalue
  953. // expression whose type is a polymorphic class type
  954. return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
  955. // - a potentially evaluated call to a function, member function, function
  956. // pointer, or member function pointer that does not have a non-throwing
  957. // exception-specification
  958. case Expr::CallExprClass:
  959. case Expr::CXXMemberCallExprClass:
  960. case Expr::CXXOperatorCallExprClass:
  961. case Expr::UserDefinedLiteralClass: {
  962. const CallExpr *CE = cast<CallExpr>(E);
  963. CanThrowResult CT;
  964. if (E->isTypeDependent())
  965. CT = CT_Dependent;
  966. else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
  967. CT = CT_Cannot;
  968. else
  969. CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
  970. if (CT == CT_Can)
  971. return CT;
  972. return mergeCanThrow(CT, canSubExprsThrow(*this, E));
  973. }
  974. case Expr::CXXConstructExprClass:
  975. case Expr::CXXTemporaryObjectExprClass: {
  976. CanThrowResult CT = canCalleeThrow(*this, E,
  977. cast<CXXConstructExpr>(E)->getConstructor());
  978. if (CT == CT_Can)
  979. return CT;
  980. return mergeCanThrow(CT, canSubExprsThrow(*this, E));
  981. }
  982. case Expr::CXXInheritedCtorInitExprClass:
  983. return canCalleeThrow(*this, E,
  984. cast<CXXInheritedCtorInitExpr>(E)->getConstructor());
  985. case Expr::LambdaExprClass: {
  986. const LambdaExpr *Lambda = cast<LambdaExpr>(E);
  987. CanThrowResult CT = CT_Cannot;
  988. for (LambdaExpr::const_capture_init_iterator
  989. Cap = Lambda->capture_init_begin(),
  990. CapEnd = Lambda->capture_init_end();
  991. Cap != CapEnd; ++Cap)
  992. CT = mergeCanThrow(CT, canThrow(*Cap));
  993. return CT;
  994. }
  995. case Expr::CXXNewExprClass: {
  996. CanThrowResult CT;
  997. if (E->isTypeDependent())
  998. CT = CT_Dependent;
  999. else
  1000. CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
  1001. if (CT == CT_Can)
  1002. return CT;
  1003. return mergeCanThrow(CT, canSubExprsThrow(*this, E));
  1004. }
  1005. case Expr::CXXDeleteExprClass: {
  1006. CanThrowResult CT;
  1007. QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
  1008. if (DTy.isNull() || DTy->isDependentType()) {
  1009. CT = CT_Dependent;
  1010. } else {
  1011. CT = canCalleeThrow(*this, E,
  1012. cast<CXXDeleteExpr>(E)->getOperatorDelete());
  1013. if (const RecordType *RT = DTy->getAs<RecordType>()) {
  1014. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  1015. const CXXDestructorDecl *DD = RD->getDestructor();
  1016. if (DD)
  1017. CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
  1018. }
  1019. if (CT == CT_Can)
  1020. return CT;
  1021. }
  1022. return mergeCanThrow(CT, canSubExprsThrow(*this, E));
  1023. }
  1024. case Expr::CXXBindTemporaryExprClass: {
  1025. // The bound temporary has to be destroyed again, which might throw.
  1026. CanThrowResult CT = canCalleeThrow(*this, E,
  1027. cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
  1028. if (CT == CT_Can)
  1029. return CT;
  1030. return mergeCanThrow(CT, canSubExprsThrow(*this, E));
  1031. }
  1032. // ObjC message sends are like function calls, but never have exception
  1033. // specs.
  1034. case Expr::ObjCMessageExprClass:
  1035. case Expr::ObjCPropertyRefExprClass:
  1036. case Expr::ObjCSubscriptRefExprClass:
  1037. return CT_Can;
  1038. // All the ObjC literals that are implemented as calls are
  1039. // potentially throwing unless we decide to close off that
  1040. // possibility.
  1041. case Expr::ObjCArrayLiteralClass:
  1042. case Expr::ObjCDictionaryLiteralClass:
  1043. case Expr::ObjCBoxedExprClass:
  1044. return CT_Can;
  1045. // Many other things have subexpressions, so we have to test those.
  1046. // Some are simple:
  1047. case Expr::CoawaitExprClass:
  1048. case Expr::ConditionalOperatorClass:
  1049. case Expr::CompoundLiteralExprClass:
  1050. case Expr::CoyieldExprClass:
  1051. case Expr::CXXConstCastExprClass:
  1052. case Expr::CXXReinterpretCastExprClass:
  1053. case Expr::BuiltinBitCastExprClass:
  1054. case Expr::CXXStdInitializerListExprClass:
  1055. case Expr::DesignatedInitExprClass:
  1056. case Expr::DesignatedInitUpdateExprClass:
  1057. case Expr::ExprWithCleanupsClass:
  1058. case Expr::ExtVectorElementExprClass:
  1059. case Expr::InitListExprClass:
  1060. case Expr::ArrayInitLoopExprClass:
  1061. case Expr::MemberExprClass:
  1062. case Expr::ObjCIsaExprClass:
  1063. case Expr::ObjCIvarRefExprClass:
  1064. case Expr::ParenExprClass:
  1065. case Expr::ParenListExprClass:
  1066. case Expr::ShuffleVectorExprClass:
  1067. case Expr::ConvertVectorExprClass:
  1068. case Expr::VAArgExprClass:
  1069. return canSubExprsThrow(*this, E);
  1070. // Some might be dependent for other reasons.
  1071. case Expr::ArraySubscriptExprClass:
  1072. case Expr::OMPArraySectionExprClass:
  1073. case Expr::BinaryOperatorClass:
  1074. case Expr::DependentCoawaitExprClass:
  1075. case Expr::CompoundAssignOperatorClass:
  1076. case Expr::CStyleCastExprClass:
  1077. case Expr::CXXStaticCastExprClass:
  1078. case Expr::CXXFunctionalCastExprClass:
  1079. case Expr::ImplicitCastExprClass:
  1080. case Expr::MaterializeTemporaryExprClass:
  1081. case Expr::UnaryOperatorClass: {
  1082. CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
  1083. return mergeCanThrow(CT, canSubExprsThrow(*this, E));
  1084. }
  1085. // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
  1086. case Expr::StmtExprClass:
  1087. return CT_Can;
  1088. case Expr::CXXDefaultArgExprClass:
  1089. return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
  1090. case Expr::CXXDefaultInitExprClass:
  1091. return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
  1092. case Expr::ChooseExprClass:
  1093. if (E->isTypeDependent() || E->isValueDependent())
  1094. return CT_Dependent;
  1095. return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
  1096. case Expr::GenericSelectionExprClass:
  1097. if (cast<GenericSelectionExpr>(E)->isResultDependent())
  1098. return CT_Dependent;
  1099. return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
  1100. // Some expressions are always dependent.
  1101. case Expr::CXXDependentScopeMemberExprClass:
  1102. case Expr::CXXUnresolvedConstructExprClass:
  1103. case Expr::DependentScopeDeclRefExprClass:
  1104. case Expr::CXXFoldExprClass:
  1105. return CT_Dependent;
  1106. case Expr::AsTypeExprClass:
  1107. case Expr::BinaryConditionalOperatorClass:
  1108. case Expr::BlockExprClass:
  1109. case Expr::CUDAKernelCallExprClass:
  1110. case Expr::DeclRefExprClass:
  1111. case Expr::ObjCBridgedCastExprClass:
  1112. case Expr::ObjCIndirectCopyRestoreExprClass:
  1113. case Expr::ObjCProtocolExprClass:
  1114. case Expr::ObjCSelectorExprClass:
  1115. case Expr::ObjCAvailabilityCheckExprClass:
  1116. case Expr::OffsetOfExprClass:
  1117. case Expr::PackExpansionExprClass:
  1118. case Expr::PseudoObjectExprClass:
  1119. case Expr::SubstNonTypeTemplateParmExprClass:
  1120. case Expr::SubstNonTypeTemplateParmPackExprClass:
  1121. case Expr::FunctionParmPackExprClass:
  1122. case Expr::UnaryExprOrTypeTraitExprClass:
  1123. case Expr::UnresolvedLookupExprClass:
  1124. case Expr::UnresolvedMemberExprClass:
  1125. case Expr::TypoExprClass:
  1126. // FIXME: Can any of the above throw? If so, when?
  1127. return CT_Cannot;
  1128. case Expr::AddrLabelExprClass:
  1129. case Expr::ArrayTypeTraitExprClass:
  1130. case Expr::AtomicExprClass:
  1131. case Expr::TypeTraitExprClass:
  1132. case Expr::CXXBoolLiteralExprClass:
  1133. case Expr::CXXNoexceptExprClass:
  1134. case Expr::CXXNullPtrLiteralExprClass:
  1135. case Expr::CXXPseudoDestructorExprClass:
  1136. case Expr::CXXScalarValueInitExprClass:
  1137. case Expr::CXXThisExprClass:
  1138. case Expr::CXXUuidofExprClass:
  1139. case Expr::CharacterLiteralClass:
  1140. case Expr::ExpressionTraitExprClass:
  1141. case Expr::FloatingLiteralClass:
  1142. case Expr::GNUNullExprClass:
  1143. case Expr::ImaginaryLiteralClass:
  1144. case Expr::ImplicitValueInitExprClass:
  1145. case Expr::IntegerLiteralClass:
  1146. case Expr::FixedPointLiteralClass:
  1147. case Expr::ArrayInitIndexExprClass:
  1148. case Expr::NoInitExprClass:
  1149. case Expr::ObjCEncodeExprClass:
  1150. case Expr::ObjCStringLiteralClass:
  1151. case Expr::ObjCBoolLiteralExprClass:
  1152. case Expr::OpaqueValueExprClass:
  1153. case Expr::PredefinedExprClass:
  1154. case Expr::SizeOfPackExprClass:
  1155. case Expr::StringLiteralClass:
  1156. case Expr::SourceLocExprClass:
  1157. // These expressions can never throw.
  1158. return CT_Cannot;
  1159. case Expr::MSPropertyRefExprClass:
  1160. case Expr::MSPropertySubscriptExprClass:
  1161. llvm_unreachable("Invalid class for expression");
  1162. #define STMT(CLASS, PARENT) case Expr::CLASS##Class:
  1163. #define STMT_RANGE(Base, First, Last)
  1164. #define LAST_STMT_RANGE(BASE, FIRST, LAST)
  1165. #define EXPR(CLASS, PARENT)
  1166. #define ABSTRACT_STMT(STMT)
  1167. #include "clang/AST/StmtNodes.inc"
  1168. case Expr::NoStmtClass:
  1169. llvm_unreachable("Invalid class for expression");
  1170. }
  1171. llvm_unreachable("Bogus StmtClass");
  1172. }
  1173. } // end namespace clang