SemaExceptionSpec.cpp 59 KB

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