SemaExceptionSpec.cpp 44 KB

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