SemaExceptionSpec.cpp 50 KB

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