SemaExceptionSpec.cpp 60 KB

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