SemaExceptionSpec.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. //===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file provides Sema routines for C++ exception specification testing.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.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/Lex/Preprocessor.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. /// CheckSpecifiedExceptionType - Check if the given type is valid in an
  35. /// exception specification. Incomplete types, or pointers to incomplete types
  36. /// other than void are not allowed.
  37. bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
  38. // This check (and the similar one below) deals with issue 437, that changes
  39. // C++ 9.2p2 this way:
  40. // Within the class member-specification, the class is regarded as complete
  41. // within function bodies, default arguments, exception-specifications, and
  42. // constructor ctor-initializers (including such things in nested classes).
  43. if (T->isRecordType() && T->getAs<RecordType>()->isBeingDefined())
  44. return false;
  45. // C++ 15.4p2: A type denoted in an exception-specification shall not denote
  46. // an incomplete type.
  47. if (RequireCompleteType(Range.getBegin(), T,
  48. PDiag(diag::err_incomplete_in_exception_spec) << /*direct*/0 << Range))
  49. return true;
  50. // C++ 15.4p2: A type denoted in an exception-specification shall not denote
  51. // an incomplete type a pointer or reference to an incomplete type, other
  52. // than (cv) void*.
  53. int kind;
  54. if (const PointerType* IT = T->getAs<PointerType>()) {
  55. T = IT->getPointeeType();
  56. kind = 1;
  57. } else if (const ReferenceType* IT = T->getAs<ReferenceType>()) {
  58. T = IT->getPointeeType();
  59. kind = 2;
  60. } else
  61. return false;
  62. // Again as before
  63. if (T->isRecordType() && T->getAs<RecordType>()->isBeingDefined())
  64. return false;
  65. if (!T->isVoidType() && RequireCompleteType(Range.getBegin(), T,
  66. PDiag(diag::err_incomplete_in_exception_spec) << kind << Range))
  67. return true;
  68. return false;
  69. }
  70. /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
  71. /// to member to a function with an exception specification. This means that
  72. /// it is invalid to add another level of indirection.
  73. bool Sema::CheckDistantExceptionSpec(QualType T) {
  74. if (const PointerType *PT = T->getAs<PointerType>())
  75. T = PT->getPointeeType();
  76. else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
  77. T = PT->getPointeeType();
  78. else
  79. return false;
  80. const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
  81. if (!FnT)
  82. return false;
  83. return FnT->hasExceptionSpec();
  84. }
  85. bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
  86. OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
  87. bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
  88. bool MissingExceptionSpecification = false;
  89. bool MissingEmptyExceptionSpecification = false;
  90. unsigned DiagID = diag::err_mismatched_exception_spec;
  91. if (getLangOptions().MicrosoftExt)
  92. DiagID = diag::warn_mismatched_exception_spec;
  93. if (!CheckEquivalentExceptionSpec(PDiag(DiagID),
  94. PDiag(diag::note_previous_declaration),
  95. Old->getType()->getAs<FunctionProtoType>(),
  96. Old->getLocation(),
  97. New->getType()->getAs<FunctionProtoType>(),
  98. New->getLocation(),
  99. &MissingExceptionSpecification,
  100. &MissingEmptyExceptionSpecification,
  101. /*AllowNoexceptAllMatchWithNoSpec=*/true,
  102. IsOperatorNew))
  103. return false;
  104. // The failure was something other than an empty exception
  105. // specification; return an error.
  106. if (!MissingExceptionSpecification && !MissingEmptyExceptionSpecification)
  107. return true;
  108. const FunctionProtoType *NewProto
  109. = New->getType()->getAs<FunctionProtoType>();
  110. // The new function declaration is only missing an empty exception
  111. // specification "throw()". If the throw() specification came from a
  112. // function in a system header that has C linkage, just add an empty
  113. // exception specification to the "new" declaration. This is an
  114. // egregious workaround for glibc, which adds throw() specifications
  115. // to many libc functions as an optimization. Unfortunately, that
  116. // optimization isn't permitted by the C++ standard, so we're forced
  117. // to work around it here.
  118. if (MissingEmptyExceptionSpecification && NewProto &&
  119. (Old->getLocation().isInvalid() ||
  120. Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
  121. Old->isExternC()) {
  122. FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
  123. EPI.ExceptionSpecType = EST_DynamicNone;
  124. QualType NewType = Context.getFunctionType(NewProto->getResultType(),
  125. NewProto->arg_type_begin(),
  126. NewProto->getNumArgs(),
  127. EPI);
  128. New->setType(NewType);
  129. return false;
  130. }
  131. if (MissingExceptionSpecification && NewProto) {
  132. const FunctionProtoType *OldProto
  133. = Old->getType()->getAs<FunctionProtoType>();
  134. FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
  135. EPI.ExceptionSpecType = OldProto->getExceptionSpecType();
  136. if (EPI.ExceptionSpecType == EST_Dynamic) {
  137. EPI.NumExceptions = OldProto->getNumExceptions();
  138. EPI.Exceptions = OldProto->exception_begin();
  139. } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
  140. // FIXME: We can't just take the expression from the old prototype. It
  141. // likely contains references to the old prototype's parameters.
  142. }
  143. // Update the type of the function with the appropriate exception
  144. // specification.
  145. QualType NewType = Context.getFunctionType(NewProto->getResultType(),
  146. NewProto->arg_type_begin(),
  147. NewProto->getNumArgs(),
  148. EPI);
  149. New->setType(NewType);
  150. // If exceptions are disabled, suppress the warning about missing
  151. // exception specifications for new and delete operators.
  152. if (!getLangOptions().CXXExceptions) {
  153. switch (New->getDeclName().getCXXOverloadedOperator()) {
  154. case OO_New:
  155. case OO_Array_New:
  156. case OO_Delete:
  157. case OO_Array_Delete:
  158. if (New->getDeclContext()->isTranslationUnit())
  159. return false;
  160. break;
  161. default:
  162. break;
  163. }
  164. }
  165. // Warn about the lack of exception specification.
  166. llvm::SmallString<128> ExceptionSpecString;
  167. llvm::raw_svector_ostream OS(ExceptionSpecString);
  168. switch (OldProto->getExceptionSpecType()) {
  169. case EST_DynamicNone:
  170. OS << "throw()";
  171. break;
  172. case EST_Dynamic: {
  173. OS << "throw(";
  174. bool OnFirstException = true;
  175. for (FunctionProtoType::exception_iterator E = OldProto->exception_begin(),
  176. EEnd = OldProto->exception_end();
  177. E != EEnd;
  178. ++E) {
  179. if (OnFirstException)
  180. OnFirstException = false;
  181. else
  182. OS << ", ";
  183. OS << E->getAsString(getPrintingPolicy());
  184. }
  185. OS << ")";
  186. break;
  187. }
  188. case EST_BasicNoexcept:
  189. OS << "noexcept";
  190. break;
  191. case EST_ComputedNoexcept:
  192. OS << "noexcept(";
  193. OldProto->getNoexceptExpr()->printPretty(OS, Context, 0,
  194. getPrintingPolicy());
  195. OS << ")";
  196. break;
  197. default:
  198. llvm_unreachable("This spec type is compatible with none.");
  199. }
  200. OS.flush();
  201. SourceLocation FixItLoc;
  202. if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
  203. TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
  204. if (const FunctionTypeLoc *FTLoc = dyn_cast<FunctionTypeLoc>(&TL))
  205. FixItLoc = PP.getLocForEndOfToken(FTLoc->getLocalRangeEnd());
  206. }
  207. if (FixItLoc.isInvalid())
  208. Diag(New->getLocation(), diag::warn_missing_exception_specification)
  209. << New << OS.str();
  210. else {
  211. // FIXME: This will get more complicated with C++0x
  212. // late-specified return types.
  213. Diag(New->getLocation(), diag::warn_missing_exception_specification)
  214. << New << OS.str()
  215. << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
  216. }
  217. if (!Old->getLocation().isInvalid())
  218. Diag(Old->getLocation(), diag::note_previous_declaration);
  219. return false;
  220. }
  221. Diag(New->getLocation(), DiagID);
  222. Diag(Old->getLocation(), diag::note_previous_declaration);
  223. return true;
  224. }
  225. /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
  226. /// exception specifications. Exception specifications are equivalent if
  227. /// they allow exactly the same set of exception types. It does not matter how
  228. /// that is achieved. See C++ [except.spec]p2.
  229. bool Sema::CheckEquivalentExceptionSpec(
  230. const FunctionProtoType *Old, SourceLocation OldLoc,
  231. const FunctionProtoType *New, SourceLocation NewLoc) {
  232. unsigned DiagID = diag::err_mismatched_exception_spec;
  233. if (getLangOptions().MicrosoftExt)
  234. DiagID = diag::warn_mismatched_exception_spec;
  235. return CheckEquivalentExceptionSpec(
  236. PDiag(DiagID),
  237. PDiag(diag::note_previous_declaration),
  238. Old, OldLoc, New, NewLoc);
  239. }
  240. /// CheckEquivalentExceptionSpec - Check if the two types have compatible
  241. /// exception specifications. See C++ [except.spec]p3.
  242. bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
  243. const PartialDiagnostic & NoteID,
  244. const FunctionProtoType *Old,
  245. SourceLocation OldLoc,
  246. const FunctionProtoType *New,
  247. SourceLocation NewLoc,
  248. bool *MissingExceptionSpecification,
  249. bool*MissingEmptyExceptionSpecification,
  250. bool AllowNoexceptAllMatchWithNoSpec,
  251. bool IsOperatorNew) {
  252. // Just completely ignore this under -fno-exceptions.
  253. if (!getLangOptions().CXXExceptions)
  254. return false;
  255. if (MissingExceptionSpecification)
  256. *MissingExceptionSpecification = false;
  257. if (MissingEmptyExceptionSpecification)
  258. *MissingEmptyExceptionSpecification = false;
  259. // C++0x [except.spec]p3: Two exception-specifications are compatible if:
  260. // - both are non-throwing, regardless of their form,
  261. // - both have the form noexcept(constant-expression) and the constant-
  262. // expressions are equivalent,
  263. // - both are dynamic-exception-specifications that have the same set of
  264. // adjusted types.
  265. //
  266. // C++0x [except.spec]p12: An exception-specifcation is non-throwing if it is
  267. // of the form throw(), noexcept, or noexcept(constant-expression) where the
  268. // constant-expression yields true.
  269. //
  270. // C++0x [except.spec]p4: If any declaration of a function has an exception-
  271. // specifier that is not a noexcept-specification allowing all exceptions,
  272. // all declarations [...] of that function shall have a compatible
  273. // exception-specification.
  274. //
  275. // That last point basically means that noexcept(false) matches no spec.
  276. // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
  277. ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
  278. ExceptionSpecificationType NewEST = New->getExceptionSpecType();
  279. assert(OldEST != EST_Delayed && NewEST != EST_Delayed &&
  280. "Shouldn't see unknown exception specifications here");
  281. // Shortcut the case where both have no spec.
  282. if (OldEST == EST_None && NewEST == EST_None)
  283. return false;
  284. FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
  285. FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
  286. if (OldNR == FunctionProtoType::NR_BadNoexcept ||
  287. NewNR == FunctionProtoType::NR_BadNoexcept)
  288. return false;
  289. // Dependent noexcept specifiers are compatible with each other, but nothing
  290. // else.
  291. // One noexcept is compatible with another if the argument is the same
  292. if (OldNR == NewNR &&
  293. OldNR != FunctionProtoType::NR_NoNoexcept &&
  294. NewNR != FunctionProtoType::NR_NoNoexcept)
  295. return false;
  296. if (OldNR != NewNR &&
  297. OldNR != FunctionProtoType::NR_NoNoexcept &&
  298. NewNR != FunctionProtoType::NR_NoNoexcept) {
  299. Diag(NewLoc, DiagID);
  300. if (NoteID.getDiagID() != 0)
  301. Diag(OldLoc, NoteID);
  302. return true;
  303. }
  304. // The MS extension throw(...) is compatible with itself.
  305. if (OldEST == EST_MSAny && NewEST == EST_MSAny)
  306. return false;
  307. // It's also compatible with no spec.
  308. if ((OldEST == EST_None && NewEST == EST_MSAny) ||
  309. (OldEST == EST_MSAny && NewEST == EST_None))
  310. return false;
  311. // It's also compatible with noexcept(false).
  312. if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
  313. return false;
  314. if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
  315. return false;
  316. // As described above, noexcept(false) matches no spec only for functions.
  317. if (AllowNoexceptAllMatchWithNoSpec) {
  318. if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
  319. return false;
  320. if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
  321. return false;
  322. }
  323. // Any non-throwing specifications are compatible.
  324. bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
  325. OldEST == EST_DynamicNone;
  326. bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
  327. NewEST == EST_DynamicNone;
  328. if (OldNonThrowing && NewNonThrowing)
  329. return false;
  330. // As a special compatibility feature, under C++0x we accept no spec and
  331. // throw(std::bad_alloc) as equivalent for operator new and operator new[].
  332. // This is because the implicit declaration changed, but old code would break.
  333. if (getLangOptions().CPlusPlus0x && IsOperatorNew) {
  334. const FunctionProtoType *WithExceptions = 0;
  335. if (OldEST == EST_None && NewEST == EST_Dynamic)
  336. WithExceptions = New;
  337. else if (OldEST == EST_Dynamic && NewEST == EST_None)
  338. WithExceptions = Old;
  339. if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
  340. // One has no spec, the other throw(something). If that something is
  341. // std::bad_alloc, all conditions are met.
  342. QualType Exception = *WithExceptions->exception_begin();
  343. if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
  344. IdentifierInfo* Name = ExRecord->getIdentifier();
  345. if (Name && Name->getName() == "bad_alloc") {
  346. // It's called bad_alloc, but is it in std?
  347. DeclContext* DC = ExRecord->getDeclContext();
  348. DC = DC->getEnclosingNamespaceContext();
  349. if (NamespaceDecl* NS = dyn_cast<NamespaceDecl>(DC)) {
  350. IdentifierInfo* NSName = NS->getIdentifier();
  351. DC = DC->getParent();
  352. if (NSName && NSName->getName() == "std" &&
  353. DC->getEnclosingNamespaceContext()->isTranslationUnit()) {
  354. return false;
  355. }
  356. }
  357. }
  358. }
  359. }
  360. }
  361. // At this point, the only remaining valid case is two matching dynamic
  362. // specifications. We return here unless both specifications are dynamic.
  363. if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
  364. if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
  365. !New->hasExceptionSpec()) {
  366. // The old type has an exception specification of some sort, but
  367. // the new type does not.
  368. *MissingExceptionSpecification = true;
  369. if (MissingEmptyExceptionSpecification && OldNonThrowing) {
  370. // The old type has a throw() or noexcept(true) exception specification
  371. // and the new type has no exception specification, and the caller asked
  372. // to handle this itself.
  373. *MissingEmptyExceptionSpecification = true;
  374. }
  375. return true;
  376. }
  377. Diag(NewLoc, DiagID);
  378. if (NoteID.getDiagID() != 0)
  379. Diag(OldLoc, NoteID);
  380. return true;
  381. }
  382. assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
  383. "Exception compatibility logic error: non-dynamic spec slipped through.");
  384. bool Success = true;
  385. // Both have a dynamic exception spec. Collect the first set, then compare
  386. // to the second.
  387. llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
  388. for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
  389. E = Old->exception_end(); I != E; ++I)
  390. OldTypes.insert(Context.getCanonicalType(*I).getUnqualifiedType());
  391. for (FunctionProtoType::exception_iterator I = New->exception_begin(),
  392. E = New->exception_end(); I != E && Success; ++I) {
  393. CanQualType TypePtr = Context.getCanonicalType(*I).getUnqualifiedType();
  394. if(OldTypes.count(TypePtr))
  395. NewTypes.insert(TypePtr);
  396. else
  397. Success = false;
  398. }
  399. Success = Success && OldTypes.size() == NewTypes.size();
  400. if (Success) {
  401. return false;
  402. }
  403. Diag(NewLoc, DiagID);
  404. if (NoteID.getDiagID() != 0)
  405. Diag(OldLoc, NoteID);
  406. return true;
  407. }
  408. /// CheckExceptionSpecSubset - Check whether the second function type's
  409. /// exception specification is a subset (or equivalent) of the first function
  410. /// type. This is used by override and pointer assignment checks.
  411. bool Sema::CheckExceptionSpecSubset(
  412. const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
  413. const FunctionProtoType *Superset, SourceLocation SuperLoc,
  414. const FunctionProtoType *Subset, SourceLocation SubLoc) {
  415. // Just auto-succeed under -fno-exceptions.
  416. if (!getLangOptions().CXXExceptions)
  417. return false;
  418. // FIXME: As usual, we could be more specific in our error messages, but
  419. // that better waits until we've got types with source locations.
  420. if (!SubLoc.isValid())
  421. SubLoc = SuperLoc;
  422. ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
  423. // If superset contains everything, we're done.
  424. if (SuperEST == EST_None || SuperEST == EST_MSAny)
  425. return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
  426. // If there are dependent noexcept specs, assume everything is fine. Unlike
  427. // with the equivalency check, this is safe in this case, because we don't
  428. // want to merge declarations. Checks after instantiation will catch any
  429. // omissions we make here.
  430. // We also shortcut checking if a noexcept expression was bad.
  431. FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
  432. if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
  433. SuperNR == FunctionProtoType::NR_Dependent)
  434. return false;
  435. // Another case of the superset containing everything.
  436. if (SuperNR == FunctionProtoType::NR_Throw)
  437. return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
  438. ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
  439. assert(SuperEST != EST_Delayed && SubEST != EST_Delayed &&
  440. "Shouldn't see unknown exception specifications here");
  441. // It does not. If the subset contains everything, we've failed.
  442. if (SubEST == EST_None || SubEST == EST_MSAny) {
  443. Diag(SubLoc, DiagID);
  444. if (NoteID.getDiagID() != 0)
  445. Diag(SuperLoc, NoteID);
  446. return true;
  447. }
  448. FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
  449. if (SubNR == FunctionProtoType::NR_BadNoexcept ||
  450. SubNR == FunctionProtoType::NR_Dependent)
  451. return false;
  452. // Another case of the subset containing everything.
  453. if (SubNR == FunctionProtoType::NR_Throw) {
  454. Diag(SubLoc, DiagID);
  455. if (NoteID.getDiagID() != 0)
  456. Diag(SuperLoc, NoteID);
  457. return true;
  458. }
  459. // If the subset contains nothing, we're done.
  460. if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
  461. return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
  462. // Otherwise, if the superset contains nothing, we've failed.
  463. if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
  464. Diag(SubLoc, DiagID);
  465. if (NoteID.getDiagID() != 0)
  466. Diag(SuperLoc, NoteID);
  467. return true;
  468. }
  469. assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
  470. "Exception spec subset: non-dynamic case slipped through.");
  471. // Neither contains everything or nothing. Do a proper comparison.
  472. for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
  473. SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
  474. // Take one type from the subset.
  475. QualType CanonicalSubT = Context.getCanonicalType(*SubI);
  476. // Unwrap pointers and references so that we can do checks within a class
  477. // hierarchy. Don't unwrap member pointers; they don't have hierarchy
  478. // conversions on the pointee.
  479. bool SubIsPointer = false;
  480. if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
  481. CanonicalSubT = RefTy->getPointeeType();
  482. if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
  483. CanonicalSubT = PtrTy->getPointeeType();
  484. SubIsPointer = true;
  485. }
  486. bool SubIsClass = CanonicalSubT->isRecordType();
  487. CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
  488. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  489. /*DetectVirtual=*/false);
  490. bool Contained = false;
  491. // Make sure it's in the superset.
  492. for (FunctionProtoType::exception_iterator SuperI =
  493. Superset->exception_begin(), SuperE = Superset->exception_end();
  494. SuperI != SuperE; ++SuperI) {
  495. QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
  496. // SubT must be SuperT or derived from it, or pointer or reference to
  497. // such types.
  498. if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
  499. CanonicalSuperT = RefTy->getPointeeType();
  500. if (SubIsPointer) {
  501. if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
  502. CanonicalSuperT = PtrTy->getPointeeType();
  503. else {
  504. continue;
  505. }
  506. }
  507. CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
  508. // If the types are the same, move on to the next type in the subset.
  509. if (CanonicalSubT == CanonicalSuperT) {
  510. Contained = true;
  511. break;
  512. }
  513. // Otherwise we need to check the inheritance.
  514. if (!SubIsClass || !CanonicalSuperT->isRecordType())
  515. continue;
  516. Paths.clear();
  517. if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
  518. continue;
  519. if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
  520. continue;
  521. // Do this check from a context without privileges.
  522. switch (CheckBaseClassAccess(SourceLocation(),
  523. CanonicalSuperT, CanonicalSubT,
  524. Paths.front(),
  525. /*Diagnostic*/ 0,
  526. /*ForceCheck*/ true,
  527. /*ForceUnprivileged*/ true)) {
  528. case AR_accessible: break;
  529. case AR_inaccessible: continue;
  530. case AR_dependent:
  531. llvm_unreachable("access check dependent for unprivileged context");
  532. case AR_delayed:
  533. llvm_unreachable("access check delayed in non-declaration");
  534. }
  535. Contained = true;
  536. break;
  537. }
  538. if (!Contained) {
  539. Diag(SubLoc, DiagID);
  540. if (NoteID.getDiagID() != 0)
  541. Diag(SuperLoc, NoteID);
  542. return true;
  543. }
  544. }
  545. // We've run half the gauntlet.
  546. return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
  547. }
  548. static bool CheckSpecForTypesEquivalent(Sema &S,
  549. const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
  550. QualType Target, SourceLocation TargetLoc,
  551. QualType Source, SourceLocation SourceLoc)
  552. {
  553. const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
  554. if (!TFunc)
  555. return false;
  556. const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
  557. if (!SFunc)
  558. return false;
  559. return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
  560. SFunc, SourceLoc);
  561. }
  562. /// CheckParamExceptionSpec - Check if the parameter and return types of the
  563. /// two functions have equivalent exception specs. This is part of the
  564. /// assignment and override compatibility check. We do not check the parameters
  565. /// of parameter function pointers recursively, as no sane programmer would
  566. /// even be able to write such a function type.
  567. bool Sema::CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
  568. const FunctionProtoType *Target, SourceLocation TargetLoc,
  569. const FunctionProtoType *Source, SourceLocation SourceLoc)
  570. {
  571. if (CheckSpecForTypesEquivalent(*this,
  572. PDiag(diag::err_deep_exception_specs_differ) << 0,
  573. PDiag(),
  574. Target->getResultType(), TargetLoc,
  575. Source->getResultType(), SourceLoc))
  576. return true;
  577. // We shouldn't even be testing this unless the arguments are otherwise
  578. // compatible.
  579. assert(Target->getNumArgs() == Source->getNumArgs() &&
  580. "Functions have different argument counts.");
  581. for (unsigned i = 0, E = Target->getNumArgs(); i != E; ++i) {
  582. if (CheckSpecForTypesEquivalent(*this,
  583. PDiag(diag::err_deep_exception_specs_differ) << 1,
  584. PDiag(),
  585. Target->getArgType(i), TargetLoc,
  586. Source->getArgType(i), SourceLoc))
  587. return true;
  588. }
  589. return false;
  590. }
  591. bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
  592. {
  593. // First we check for applicability.
  594. // Target type must be a function, function pointer or function reference.
  595. const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
  596. if (!ToFunc)
  597. return false;
  598. // SourceType must be a function or function pointer.
  599. const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
  600. if (!FromFunc)
  601. return false;
  602. // Now we've got the correct types on both sides, check their compatibility.
  603. // This means that the source of the conversion can only throw a subset of
  604. // the exceptions of the target, and any exception specs on arguments or
  605. // return types must be equivalent.
  606. return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
  607. PDiag(), ToFunc,
  608. From->getSourceRange().getBegin(),
  609. FromFunc, SourceLocation());
  610. }
  611. bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
  612. const CXXMethodDecl *Old) {
  613. if (getLangOptions().CPlusPlus0x && isa<CXXDestructorDecl>(New)) {
  614. // Don't check uninstantiated template destructors at all. We can only
  615. // synthesize correct specs after the template is instantiated.
  616. if (New->getParent()->isDependentType())
  617. return false;
  618. if (New->getParent()->isBeingDefined()) {
  619. // The destructor might be updated once the definition is finished. So
  620. // remember it and check later.
  621. DelayedDestructorExceptionSpecChecks.push_back(std::make_pair(
  622. cast<CXXDestructorDecl>(New), cast<CXXDestructorDecl>(Old)));
  623. return false;
  624. }
  625. }
  626. unsigned DiagID = diag::err_override_exception_spec;
  627. if (getLangOptions().MicrosoftExt)
  628. DiagID = diag::warn_override_exception_spec;
  629. return CheckExceptionSpecSubset(PDiag(DiagID),
  630. PDiag(diag::note_overridden_virtual_function),
  631. Old->getType()->getAs<FunctionProtoType>(),
  632. Old->getLocation(),
  633. New->getType()->getAs<FunctionProtoType>(),
  634. New->getLocation());
  635. }
  636. } // end namespace clang