SemaExceptionSpec.cpp 44 KB

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