blob: a81ef5179549163651367e2ae01b0500abc8918c [file] [log] [blame]
Sebastian Redl4915e632009-10-11 09:03:14 +00001//===--- 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
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Richard Smith564417a2014-03-20 21:47:22 +000015#include "clang/AST/ASTMutationListener.h"
Sebastian Redl4915e632009-10-11 09:03:14 +000016#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
Douglas Gregord6bc5e62010-03-24 07:14:45 +000019#include "clang/AST/TypeLoc.h"
Douglas Gregorf40863c2010-02-12 07:32:17 +000020#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/SourceManager.h"
Sebastian Redl4915e632009-10-11 09:03:14 +000022#include "llvm/ADT/SmallPtrSet.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000023#include "llvm/ADT/SmallString.h"
Sebastian Redl4915e632009-10-11 09:03:14 +000024
25namespace clang {
26
27static const FunctionProtoType *GetUnderlyingFunction(QualType T)
28{
29 if (const PointerType *PtrTy = T->getAs<PointerType>())
30 T = PtrTy->getPointeeType();
31 else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
32 T = RefTy->getPointeeType();
Sebastian Redl075b21d2009-10-14 14:38:54 +000033 else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
34 T = MPTy->getPointeeType();
Sebastian Redl4915e632009-10-11 09:03:14 +000035 return T->getAs<FunctionProtoType>();
36}
37
Richard Smith6403e932014-11-14 00:37:55 +000038/// HACK: libstdc++ has a bug where it shadows std::swap with a member
39/// swap function then tries to call std::swap unqualified from the exception
40/// specification of that function. This function detects whether we're in
41/// such a case and turns off delay-parsing of exception specifications.
42bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {
43 auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
44
45 // All the problem cases are member functions named "swap" within class
46 // templates declared directly within namespace std.
Vassil Vassilev86436392016-08-20 14:50:22 +000047 if (!RD || !getStdNamespace() ||
48 !RD->getEnclosingNamespaceContext()->Equals(getStdNamespace()) ||
Richard Smith6403e932014-11-14 00:37:55 +000049 !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
50 !D.getIdentifier() || !D.getIdentifier()->isStr("swap"))
51 return false;
52
53 // Only apply this hack within a system header.
54 if (!Context.getSourceManager().isInSystemHeader(D.getLocStart()))
55 return false;
56
57 return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
58 .Case("array", true)
59 .Case("pair", true)
60 .Case("priority_queue", true)
61 .Case("stack", true)
62 .Case("queue", true)
63 .Default(false);
64}
65
Sebastian Redl4915e632009-10-11 09:03:14 +000066/// CheckSpecifiedExceptionType - Check if the given type is valid in an
67/// exception specification. Incomplete types, or pointers to incomplete types
68/// other than void are not allowed.
Richard Smith8606d752012-11-28 22:33:28 +000069///
70/// \param[in,out] T The exception type. This will be decayed to a pointer type
71/// when the input is an array or a function type.
Craig Toppere335f252015-10-04 04:53:55 +000072bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {
Richard Smitha118c6a2012-11-28 22:52:42 +000073 // C++11 [except.spec]p2:
74 // A type cv T, "array of T", or "function returning T" denoted
Richard Smith8606d752012-11-28 22:33:28 +000075 // in an exception-specification is adjusted to type T, "pointer to T", or
76 // "pointer to function returning T", respectively.
Richard Smitha118c6a2012-11-28 22:52:42 +000077 //
78 // We also apply this rule in C++98.
Richard Smith8606d752012-11-28 22:33:28 +000079 if (T->isArrayType())
80 T = Context.getArrayDecayedType(T);
81 else if (T->isFunctionType())
82 T = Context.getPointerType(T);
Sebastian Redl4915e632009-10-11 09:03:14 +000083
Richard Smitha118c6a2012-11-28 22:52:42 +000084 int Kind = 0;
Richard Smith8606d752012-11-28 22:33:28 +000085 QualType PointeeT = T;
Richard Smitha118c6a2012-11-28 22:52:42 +000086 if (const PointerType *PT = T->getAs<PointerType>()) {
87 PointeeT = PT->getPointeeType();
88 Kind = 1;
Sebastian Redl4915e632009-10-11 09:03:14 +000089
Richard Smitha118c6a2012-11-28 22:52:42 +000090 // cv void* is explicitly permitted, despite being a pointer to an
91 // incomplete type.
92 if (PointeeT->isVoidType())
93 return false;
94 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
95 PointeeT = RT->getPointeeType();
96 Kind = 2;
Richard Smith8606d752012-11-28 22:33:28 +000097
Richard Smitha118c6a2012-11-28 22:52:42 +000098 if (RT->isRValueReferenceType()) {
99 // C++11 [except.spec]p2:
100 // A type denoted in an exception-specification shall not denote [...]
101 // an rvalue reference type.
102 Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
103 << T << Range;
104 return true;
105 }
106 }
107
108 // C++11 [except.spec]p2:
109 // A type denoted in an exception-specification shall not denote an
110 // incomplete type other than a class currently being defined [...].
111 // A type denoted in an exception-specification shall not denote a
112 // pointer or reference to an incomplete type, other than (cv) void* or a
113 // pointer or reference to a class currently being defined.
David Majnemerb2b0da42016-06-10 18:24:41 +0000114 // In Microsoft mode, downgrade this to a warning.
115 unsigned DiagID = diag::err_incomplete_in_exception_spec;
David Majnemer5d321e62016-06-11 01:25:04 +0000116 bool ReturnValueOnError = true;
117 if (getLangOpts().MicrosoftExt) {
David Majnemerb2b0da42016-06-10 18:24:41 +0000118 DiagID = diag::ext_incomplete_in_exception_spec;
David Majnemer5d321e62016-06-11 01:25:04 +0000119 ReturnValueOnError = false;
120 }
Richard Smitha118c6a2012-11-28 22:52:42 +0000121 if (!(PointeeT->isRecordType() &&
122 PointeeT->getAs<RecordType>()->isBeingDefined()) &&
David Majnemerb2b0da42016-06-10 18:24:41 +0000123 RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range))
David Majnemer5d321e62016-06-11 01:25:04 +0000124 return ReturnValueOnError;
Sebastian Redl4915e632009-10-11 09:03:14 +0000125
126 return false;
127}
128
129/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
130/// to member to a function with an exception specification. This means that
131/// it is invalid to add another level of indirection.
132bool Sema::CheckDistantExceptionSpec(QualType T) {
Richard Smith3c4f8d22016-10-16 17:54:23 +0000133 // C++17 removes this rule in favor of putting exception specifications into
134 // the type system.
135 if (getLangOpts().CPlusPlus1z)
136 return false;
137
Sebastian Redl4915e632009-10-11 09:03:14 +0000138 if (const PointerType *PT = T->getAs<PointerType>())
139 T = PT->getPointeeType();
140 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
141 T = PT->getPointeeType();
142 else
143 return false;
144
145 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
146 if (!FnT)
147 return false;
148
149 return FnT->hasExceptionSpec();
150}
151
Richard Smithf623c962012-04-17 00:58:00 +0000152const FunctionProtoType *
153Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
Richard Smith0b3a4622014-11-13 20:01:57 +0000154 if (FPT->getExceptionSpecType() == EST_Unparsed) {
155 Diag(Loc, diag::err_exception_spec_not_parsed);
156 return nullptr;
157 }
158
Richard Smithd3b5c9082012-07-27 04:22:15 +0000159 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000160 return FPT;
161
162 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
163 const FunctionProtoType *SourceFPT =
164 SourceDecl->getType()->castAs<FunctionProtoType>();
165
Richard Smithd3b5c9082012-07-27 04:22:15 +0000166 // If the exception specification has already been resolved, just return it.
167 if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000168 return SourceFPT;
169
Richard Smithd3b5c9082012-07-27 04:22:15 +0000170 // Compute or instantiate the exception specification now.
Richard Smith3901dfe2013-03-27 00:22:47 +0000171 if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smithd3b5c9082012-07-27 04:22:15 +0000172 EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
173 else
174 InstantiateExceptionSpec(Loc, SourceDecl);
Richard Smithf623c962012-04-17 00:58:00 +0000175
Davide Italiano922b7022015-07-25 01:19:32 +0000176 const FunctionProtoType *Proto =
177 SourceDecl->getType()->castAs<FunctionProtoType>();
178 if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
179 Diag(Loc, diag::err_exception_spec_not_parsed);
180 Proto = nullptr;
181 }
182 return Proto;
Richard Smithf623c962012-04-17 00:58:00 +0000183}
184
Richard Smith8acb4282014-07-31 21:57:55 +0000185void
186Sema::UpdateExceptionSpec(FunctionDecl *FD,
187 const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith564417a2014-03-20 21:47:22 +0000188 // If we've fully resolved the exception specification, notify listeners.
Richard Smith8acb4282014-07-31 21:57:55 +0000189 if (!isUnresolvedExceptionSpec(ESI.Type))
Richard Smith564417a2014-03-20 21:47:22 +0000190 if (auto *Listener = getASTMutationListener())
191 Listener->ResolvedExceptionSpec(FD);
Richard Smith9e2341d2015-03-23 03:25:59 +0000192
193 for (auto *Redecl : FD->redecls())
194 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith564417a2014-03-20 21:47:22 +0000195}
196
Richard Smith66f3ac92012-10-20 08:26:51 +0000197/// Determine whether a function has an implicitly-generated exception
Richard Smith1ee63522012-10-16 23:30:16 +0000198/// specification.
Richard Smith66f3ac92012-10-20 08:26:51 +0000199static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
200 if (!isa<CXXDestructorDecl>(Decl) &&
201 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
202 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
203 return false;
Richard Smith1ee63522012-10-16 23:30:16 +0000204
Richard Smithc7fb2252014-02-07 22:51:16 +0000205 // For a function that the user didn't declare:
206 // - if this is a destructor, its exception specification is implicit.
207 // - if this is 'operator delete' or 'operator delete[]', the exception
208 // specification is as-if an explicit exception specification was given
209 // (per [basic.stc.dynamic]p2).
Richard Smith66f3ac92012-10-20 08:26:51 +0000210 if (!Decl->getTypeSourceInfo())
Richard Smithc7fb2252014-02-07 22:51:16 +0000211 return isa<CXXDestructorDecl>(Decl);
Richard Smith66f3ac92012-10-20 08:26:51 +0000212
213 const FunctionProtoType *Ty =
214 Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
215 return !Ty->hasExceptionSpec();
Richard Smith1ee63522012-10-16 23:30:16 +0000216}
217
Douglas Gregorf40863c2010-02-12 07:32:17 +0000218bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000219 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
220 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000221 bool MissingExceptionSpecification = false;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000222 bool MissingEmptyExceptionSpecification = false;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000223
Francois Pichet13b4e682011-03-19 23:05:18 +0000224 unsigned DiagID = diag::err_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000225 bool ReturnValueOnError = true;
226 if (getLangOpts().MicrosoftExt) {
Richard Smith1b98ccc2014-07-19 01:39:17 +0000227 DiagID = diag::ext_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000228 ReturnValueOnError = false;
229 }
Richard Smithf623c962012-04-17 00:58:00 +0000230
Richard Smith1ee63522012-10-16 23:30:16 +0000231 // Check the types as written: they must match before any exception
232 // specification adjustment is applied.
233 if (!CheckEquivalentExceptionSpec(
234 PDiag(DiagID), PDiag(diag::note_previous_declaration),
Richard Smith66f3ac92012-10-20 08:26:51 +0000235 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
236 New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
Richard Smith1ee63522012-10-16 23:30:16 +0000237 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
Richard Smith66f3ac92012-10-20 08:26:51 +0000238 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
239 // C++11 [except.spec]p4 [DR1492]:
240 // If a declaration of a function has an implicit
241 // exception-specification, other declarations of the function shall
242 // not specify an exception-specification.
Richard Smithe3ea0012016-08-31 20:38:32 +0000243 if (getLangOpts().CPlusPlus11 && getLangOpts().CXXExceptions &&
Richard Smith66f3ac92012-10-20 08:26:51 +0000244 hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
245 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
246 << hasImplicitExceptionSpec(Old);
Yaron Keren8b563662015-10-03 10:46:20 +0000247 if (Old->getLocation().isValid())
Richard Smith66f3ac92012-10-20 08:26:51 +0000248 Diag(Old->getLocation(), diag::note_previous_declaration);
249 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000250 return false;
Richard Smith66f3ac92012-10-20 08:26:51 +0000251 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000252
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000253 // The failure was something other than an missing exception
Hans Wennborg39a509a2014-02-05 02:37:58 +0000254 // specification; return an error, except in MS mode where this is a warning.
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000255 if (!MissingExceptionSpecification)
Hans Wennborg39a509a2014-02-05 02:37:58 +0000256 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000257
Richard Smith66f3ac92012-10-20 08:26:51 +0000258 const FunctionProtoType *NewProto =
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000259 New->getType()->castAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +0000260
Douglas Gregorf40863c2010-02-12 07:32:17 +0000261 // The new function declaration is only missing an empty exception
262 // specification "throw()". If the throw() specification came from a
263 // function in a system header that has C linkage, just add an empty
264 // exception specification to the "new" declaration. This is an
265 // egregious workaround for glibc, which adds throw() specifications
266 // to many libc functions as an optimization. Unfortunately, that
267 // optimization isn't permitted by the C++ standard, so we're forced
268 // to work around it here.
John McCalldb40c7f2010-12-14 08:05:40 +0000269 if (MissingEmptyExceptionSpecification && NewProto &&
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000270 (Old->getLocation().isInvalid() ||
271 Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000272 Old->isExternC()) {
Richard Smith8acb4282014-07-31 21:57:55 +0000273 New->setType(Context.getFunctionType(
274 NewProto->getReturnType(), NewProto->getParamTypes(),
275 NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
Douglas Gregorf40863c2010-02-12 07:32:17 +0000276 return false;
277 }
278
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000279 const FunctionProtoType *OldProto =
280 Old->getType()->castAs<FunctionProtoType>();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000281
Richard Smith8acb4282014-07-31 21:57:55 +0000282 FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
283 if (ESI.Type == EST_Dynamic) {
284 ESI.Exceptions = OldProto->exceptions();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000285 }
286
Richard Smitha91de372015-09-30 00:48:50 +0000287 if (ESI.Type == EST_ComputedNoexcept) {
288 // For computed noexcept, we can't just take the expression from the old
289 // prototype. It likely contains references to the old prototype's
290 // parameters.
291 New->setInvalidDecl();
292 } else {
293 // Update the type of the function with the appropriate exception
294 // specification.
295 New->setType(Context.getFunctionType(
296 NewProto->getReturnType(), NewProto->getParamTypes(),
297 NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
298 }
299
David Majnemer06ce8a42015-10-20 20:49:21 +0000300 if (getLangOpts().MicrosoftExt && ESI.Type != EST_ComputedNoexcept) {
301 // Allow missing exception specifications in redeclarations as an extension.
302 DiagID = diag::ext_ms_missing_exception_specification;
303 ReturnValueOnError = false;
304 } else if (New->isReplaceableGlobalAllocationFunction() &&
305 ESI.Type != EST_ComputedNoexcept) {
306 // Allow missing exception specifications in redeclarations as an extension,
307 // when declaring a replaceable global allocation function.
Richard Smitha91de372015-09-30 00:48:50 +0000308 DiagID = diag::ext_missing_exception_specification;
309 ReturnValueOnError = false;
310 } else {
311 DiagID = diag::err_missing_exception_specification;
312 ReturnValueOnError = true;
313 }
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000314
315 // Warn about the lack of exception specification.
316 SmallString<128> ExceptionSpecString;
317 llvm::raw_svector_ostream OS(ExceptionSpecString);
318 switch (OldProto->getExceptionSpecType()) {
319 case EST_DynamicNone:
320 OS << "throw()";
321 break;
322
323 case EST_Dynamic: {
324 OS << "throw(";
325 bool OnFirstException = true;
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000326 for (const auto &E : OldProto->exceptions()) {
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000327 if (OnFirstException)
328 OnFirstException = false;
329 else
330 OS << ", ";
331
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000332 OS << E.getAsString(getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000333 }
334 OS << ")";
335 break;
336 }
337
338 case EST_BasicNoexcept:
339 OS << "noexcept";
340 break;
341
342 case EST_ComputedNoexcept:
343 OS << "noexcept(";
Richard Trieuddd01ce2014-06-09 22:53:25 +0000344 assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
Craig Topperc3ec1492014-05-26 06:22:03 +0000345 OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000346 OS << ")";
347 break;
348
349 default:
350 llvm_unreachable("This spec type is compatible with none.");
351 }
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000352
353 SourceLocation FixItLoc;
354 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
355 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Richard Smitha91de372015-09-30 00:48:50 +0000356 // FIXME: Preserve enough information so that we can produce a correct fixit
357 // location when there is a trailing return type.
358 if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
359 if (!FTLoc.getTypePtr()->hasTrailingReturn())
360 FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000361 }
362
363 if (FixItLoc.isInvalid())
Richard Smitha91de372015-09-30 00:48:50 +0000364 Diag(New->getLocation(), DiagID)
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000365 << New << OS.str();
366 else {
Richard Smitha91de372015-09-30 00:48:50 +0000367 Diag(New->getLocation(), DiagID)
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000368 << New << OS.str()
369 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
370 }
371
Yaron Keren8b563662015-10-03 10:46:20 +0000372 if (Old->getLocation().isValid())
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000373 Diag(Old->getLocation(), diag::note_previous_declaration);
374
Richard Smitha91de372015-09-30 00:48:50 +0000375 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000376}
377
Sebastian Redl4915e632009-10-11 09:03:14 +0000378/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
379/// exception specifications. Exception specifications are equivalent if
380/// they allow exactly the same set of exception types. It does not matter how
381/// that is achieved. See C++ [except.spec]p2.
382bool Sema::CheckEquivalentExceptionSpec(
383 const FunctionProtoType *Old, SourceLocation OldLoc,
384 const FunctionProtoType *New, SourceLocation NewLoc) {
Francois Pichet13b4e682011-03-19 23:05:18 +0000385 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000386 if (getLangOpts().MicrosoftExt)
Richard Smith1b98ccc2014-07-19 01:39:17 +0000387 DiagID = diag::ext_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000388 bool Result = CheckEquivalentExceptionSpec(PDiag(DiagID),
389 PDiag(diag::note_previous_declaration), Old, OldLoc, New, NewLoc);
390
391 // In Microsoft mode, mismatching exception specifications just cause a warning.
392 if (getLangOpts().MicrosoftExt)
393 return false;
394 return Result;
Sebastian Redl4915e632009-10-11 09:03:14 +0000395}
396
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000397/// CheckEquivalentExceptionSpec - Check if the two types have compatible
398/// exception specifications. See C++ [except.spec]p3.
Richard Smith66f3ac92012-10-20 08:26:51 +0000399///
400/// \return \c false if the exception specifications match, \c true if there is
401/// a problem. If \c true is returned, either a diagnostic has already been
402/// produced or \c *MissingExceptionSpecification is set to \c true.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000403bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000404 const PartialDiagnostic & NoteID,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000405 const FunctionProtoType *Old,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000406 SourceLocation OldLoc,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000407 const FunctionProtoType *New,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000408 SourceLocation NewLoc,
409 bool *MissingExceptionSpecification,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000410 bool*MissingEmptyExceptionSpecification,
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000411 bool AllowNoexceptAllMatchWithNoSpec,
412 bool IsOperatorNew) {
John McCallf9c94092010-05-28 08:37:35 +0000413 // Just completely ignore this under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000414 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000415 return false;
416
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000417 if (MissingExceptionSpecification)
418 *MissingExceptionSpecification = false;
419
Douglas Gregorf40863c2010-02-12 07:32:17 +0000420 if (MissingEmptyExceptionSpecification)
421 *MissingEmptyExceptionSpecification = false;
422
Richard Smithf623c962012-04-17 00:58:00 +0000423 Old = ResolveExceptionSpec(NewLoc, Old);
424 if (!Old)
425 return false;
426 New = ResolveExceptionSpec(NewLoc, New);
427 if (!New)
428 return false;
429
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000430 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
431 // - both are non-throwing, regardless of their form,
432 // - both have the form noexcept(constant-expression) and the constant-
433 // expressions are equivalent,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000434 // - both are dynamic-exception-specifications that have the same set of
435 // adjusted types.
436 //
Eric Christophere6b7cf42015-07-10 18:25:52 +0000437 // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000438 // of the form throw(), noexcept, or noexcept(constant-expression) where the
439 // constant-expression yields true.
440 //
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000441 // C++0x [except.spec]p4: If any declaration of a function has an exception-
442 // specifier that is not a noexcept-specification allowing all exceptions,
443 // all declarations [...] of that function shall have a compatible
444 // exception-specification.
445 //
446 // That last point basically means that noexcept(false) matches no spec.
447 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
448
449 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
450 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
451
Richard Smithd3b5c9082012-07-27 04:22:15 +0000452 assert(!isUnresolvedExceptionSpec(OldEST) &&
453 !isUnresolvedExceptionSpec(NewEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000454 "Shouldn't see unknown exception specifications here");
455
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000456 // Shortcut the case where both have no spec.
457 if (OldEST == EST_None && NewEST == EST_None)
458 return false;
459
Sebastian Redl31ad7542011-03-13 17:09:40 +0000460 FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
461 FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000462 if (OldNR == FunctionProtoType::NR_BadNoexcept ||
463 NewNR == FunctionProtoType::NR_BadNoexcept)
464 return false;
465
466 // Dependent noexcept specifiers are compatible with each other, but nothing
467 // else.
468 // One noexcept is compatible with another if the argument is the same
469 if (OldNR == NewNR &&
470 OldNR != FunctionProtoType::NR_NoNoexcept &&
471 NewNR != FunctionProtoType::NR_NoNoexcept)
472 return false;
473 if (OldNR != NewNR &&
474 OldNR != FunctionProtoType::NR_NoNoexcept &&
475 NewNR != FunctionProtoType::NR_NoNoexcept) {
476 Diag(NewLoc, DiagID);
David Majnemer7da23022015-02-19 07:28:55 +0000477 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000478 Diag(OldLoc, NoteID);
479 return true;
Douglas Gregorf62c5292010-08-30 15:04:51 +0000480 }
481
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000482 // The MS extension throw(...) is compatible with itself.
483 if (OldEST == EST_MSAny && NewEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000484 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000485
486 // It's also compatible with no spec.
487 if ((OldEST == EST_None && NewEST == EST_MSAny) ||
488 (OldEST == EST_MSAny && NewEST == EST_None))
489 return false;
490
491 // It's also compatible with noexcept(false).
492 if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
493 return false;
494 if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
495 return false;
496
497 // As described above, noexcept(false) matches no spec only for functions.
498 if (AllowNoexceptAllMatchWithNoSpec) {
499 if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
500 return false;
501 if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
502 return false;
503 }
504
505 // Any non-throwing specifications are compatible.
506 bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
507 OldEST == EST_DynamicNone;
508 bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
509 NewEST == EST_DynamicNone;
510 if (OldNonThrowing && NewNonThrowing)
511 return false;
512
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000513 // As a special compatibility feature, under C++0x we accept no spec and
514 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
515 // This is because the implicit declaration changed, but old code would break.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000516 if (getLangOpts().CPlusPlus11 && IsOperatorNew) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000517 const FunctionProtoType *WithExceptions = nullptr;
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000518 if (OldEST == EST_None && NewEST == EST_Dynamic)
519 WithExceptions = New;
520 else if (OldEST == EST_Dynamic && NewEST == EST_None)
521 WithExceptions = Old;
522 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
523 // One has no spec, the other throw(something). If that something is
524 // std::bad_alloc, all conditions are met.
525 QualType Exception = *WithExceptions->exception_begin();
526 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
527 IdentifierInfo* Name = ExRecord->getIdentifier();
528 if (Name && Name->getName() == "bad_alloc") {
529 // It's called bad_alloc, but is it in std?
Richard Trieuc771d5d2014-05-28 02:16:01 +0000530 if (ExRecord->isInStdNamespace()) {
531 return false;
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000532 }
533 }
534 }
535 }
536 }
537
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000538 // At this point, the only remaining valid case is two matching dynamic
539 // specifications. We return here unless both specifications are dynamic.
540 if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000541 if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000542 !New->hasExceptionSpec()) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000543 // The old type has an exception specification of some sort, but
544 // the new type does not.
545 *MissingExceptionSpecification = true;
546
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000547 if (MissingEmptyExceptionSpecification && OldNonThrowing) {
548 // The old type has a throw() or noexcept(true) exception specification
549 // and the new type has no exception specification, and the caller asked
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000550 // to handle this itself.
551 *MissingEmptyExceptionSpecification = true;
552 }
553
Douglas Gregorf40863c2010-02-12 07:32:17 +0000554 return true;
555 }
556
Sebastian Redl4915e632009-10-11 09:03:14 +0000557 Diag(NewLoc, DiagID);
David Majnemer7da23022015-02-19 07:28:55 +0000558 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Sebastian Redl4915e632009-10-11 09:03:14 +0000559 Diag(OldLoc, NoteID);
560 return true;
561 }
562
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000563 assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
564 "Exception compatibility logic error: non-dynamic spec slipped through.");
565
Sebastian Redl4915e632009-10-11 09:03:14 +0000566 bool Success = true;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000567 // Both have a dynamic exception spec. Collect the first set, then compare
Sebastian Redl4915e632009-10-11 09:03:14 +0000568 // to the second.
Sebastian Redl184edca2009-10-14 15:06:25 +0000569 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000570 for (const auto &I : Old->exceptions())
571 OldTypes.insert(Context.getCanonicalType(I).getUnqualifiedType());
Sebastian Redl4915e632009-10-11 09:03:14 +0000572
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000573 for (const auto &I : New->exceptions()) {
574 CanQualType TypePtr = Context.getCanonicalType(I).getUnqualifiedType();
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000575 if(OldTypes.count(TypePtr))
576 NewTypes.insert(TypePtr);
577 else
578 Success = false;
579 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000580
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000581 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redl4915e632009-10-11 09:03:14 +0000582
583 if (Success) {
584 return false;
585 }
586 Diag(NewLoc, DiagID);
David Majnemer7da23022015-02-19 07:28:55 +0000587 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Sebastian Redl4915e632009-10-11 09:03:14 +0000588 Diag(OldLoc, NoteID);
589 return true;
590}
591
592/// CheckExceptionSpecSubset - Check whether the second function type's
593/// exception specification is a subset (or equivalent) of the first function
594/// type. This is used by override and pointer assignment checks.
Sebastian Redla44822f2009-10-14 16:09:29 +0000595bool Sema::CheckExceptionSpecSubset(
596 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000597 const FunctionProtoType *Superset, SourceLocation SuperLoc,
598 const FunctionProtoType *Subset, SourceLocation SubLoc) {
John McCallf9c94092010-05-28 08:37:35 +0000599
600 // Just auto-succeed under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000601 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000602 return false;
603
Sebastian Redl4915e632009-10-11 09:03:14 +0000604 // FIXME: As usual, we could be more specific in our error messages, but
605 // that better waits until we've got types with source locations.
606
607 if (!SubLoc.isValid())
608 SubLoc = SuperLoc;
609
Richard Smithf623c962012-04-17 00:58:00 +0000610 // Resolve the exception specifications, if needed.
611 Superset = ResolveExceptionSpec(SuperLoc, Superset);
612 if (!Superset)
613 return false;
614 Subset = ResolveExceptionSpec(SubLoc, Subset);
615 if (!Subset)
616 return false;
617
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000618 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
619
Sebastian Redl4915e632009-10-11 09:03:14 +0000620 // If superset contains everything, we're done.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000621 if (SuperEST == EST_None || SuperEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000622 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
623
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000624 // If there are dependent noexcept specs, assume everything is fine. Unlike
625 // with the equivalency check, this is safe in this case, because we don't
626 // want to merge declarations. Checks after instantiation will catch any
627 // omissions we make here.
628 // We also shortcut checking if a noexcept expression was bad.
629
Sebastian Redl31ad7542011-03-13 17:09:40 +0000630 FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000631 if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
632 SuperNR == FunctionProtoType::NR_Dependent)
633 return false;
634
635 // Another case of the superset containing everything.
636 if (SuperNR == FunctionProtoType::NR_Throw)
637 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
638
639 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
640
Richard Smithd3b5c9082012-07-27 04:22:15 +0000641 assert(!isUnresolvedExceptionSpec(SuperEST) &&
642 !isUnresolvedExceptionSpec(SubEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000643 "Shouldn't see unknown exception specifications here");
644
Sebastian Redl4915e632009-10-11 09:03:14 +0000645 // It does not. If the subset contains everything, we've failed.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000646 if (SubEST == EST_None || SubEST == EST_MSAny) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000647 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000648 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000649 Diag(SuperLoc, NoteID);
650 return true;
651 }
652
Sebastian Redl31ad7542011-03-13 17:09:40 +0000653 FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000654 if (SubNR == FunctionProtoType::NR_BadNoexcept ||
655 SubNR == FunctionProtoType::NR_Dependent)
656 return false;
657
658 // Another case of the subset containing everything.
659 if (SubNR == FunctionProtoType::NR_Throw) {
660 Diag(SubLoc, DiagID);
661 if (NoteID.getDiagID() != 0)
662 Diag(SuperLoc, NoteID);
663 return true;
664 }
665
666 // If the subset contains nothing, we're done.
667 if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
668 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
669
670 // Otherwise, if the superset contains nothing, we've failed.
671 if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
672 Diag(SubLoc, DiagID);
673 if (NoteID.getDiagID() != 0)
674 Diag(SuperLoc, NoteID);
675 return true;
676 }
677
678 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
679 "Exception spec subset: non-dynamic case slipped through.");
680
681 // Neither contains everything or nothing. Do a proper comparison.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000682 for (const auto &SubI : Subset->exceptions()) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000683 // Take one type from the subset.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000684 QualType CanonicalSubT = Context.getCanonicalType(SubI);
Sebastian Redl075b21d2009-10-14 14:38:54 +0000685 // Unwrap pointers and references so that we can do checks within a class
686 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
687 // conversions on the pointee.
Sebastian Redl4915e632009-10-11 09:03:14 +0000688 bool SubIsPointer = false;
689 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
690 CanonicalSubT = RefTy->getPointeeType();
691 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
692 CanonicalSubT = PtrTy->getPointeeType();
693 SubIsPointer = true;
694 }
695 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000696 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000697
698 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
699 /*DetectVirtual=*/false);
700
701 bool Contained = false;
702 // Make sure it's in the superset.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000703 for (const auto &SuperI : Superset->exceptions()) {
704 QualType CanonicalSuperT = Context.getCanonicalType(SuperI);
Sebastian Redl4915e632009-10-11 09:03:14 +0000705 // SubT must be SuperT or derived from it, or pointer or reference to
706 // such types.
707 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
708 CanonicalSuperT = RefTy->getPointeeType();
709 if (SubIsPointer) {
710 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
711 CanonicalSuperT = PtrTy->getPointeeType();
712 else {
713 continue;
714 }
715 }
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000716 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000717 // If the types are the same, move on to the next type in the subset.
718 if (CanonicalSubT == CanonicalSuperT) {
719 Contained = true;
720 break;
721 }
722
723 // Otherwise we need to check the inheritance.
724 if (!SubIsClass || !CanonicalSuperT->isRecordType())
725 continue;
726
727 Paths.clear();
Richard Smith0f59cb32015-12-18 21:45:41 +0000728 if (!IsDerivedFrom(SubLoc, CanonicalSubT, CanonicalSuperT, Paths))
Sebastian Redl4915e632009-10-11 09:03:14 +0000729 continue;
730
Douglas Gregor27ac4292010-05-21 20:29:55 +0000731 if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
Sebastian Redl4915e632009-10-11 09:03:14 +0000732 continue;
733
John McCall5b0829a2010-02-10 09:31:12 +0000734 // Do this check from a context without privileges.
John McCall1064d7e2010-03-16 05:22:47 +0000735 switch (CheckBaseClassAccess(SourceLocation(),
John McCall5b0829a2010-02-10 09:31:12 +0000736 CanonicalSuperT, CanonicalSubT,
737 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +0000738 /*Diagnostic*/ 0,
John McCall5b0829a2010-02-10 09:31:12 +0000739 /*ForceCheck*/ true,
John McCall1064d7e2010-03-16 05:22:47 +0000740 /*ForceUnprivileged*/ true)) {
John McCall5b0829a2010-02-10 09:31:12 +0000741 case AR_accessible: break;
742 case AR_inaccessible: continue;
743 case AR_dependent:
744 llvm_unreachable("access check dependent for unprivileged context");
John McCall5b0829a2010-02-10 09:31:12 +0000745 case AR_delayed:
746 llvm_unreachable("access check delayed in non-declaration");
John McCall5b0829a2010-02-10 09:31:12 +0000747 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000748
749 Contained = true;
750 break;
751 }
752 if (!Contained) {
753 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000754 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000755 Diag(SuperLoc, NoteID);
756 return true;
757 }
758 }
759 // We've run half the gauntlet.
760 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
761}
762
763static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redla44822f2009-10-14 16:09:29 +0000764 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000765 QualType Target, SourceLocation TargetLoc,
766 QualType Source, SourceLocation SourceLoc)
767{
768 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
769 if (!TFunc)
770 return false;
771 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
772 if (!SFunc)
773 return false;
774
775 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
776 SFunc, SourceLoc);
777}
778
779/// CheckParamExceptionSpec - Check if the parameter and return types of the
780/// two functions have equivalent exception specs. This is part of the
781/// assignment and override compatibility check. We do not check the parameters
782/// of parameter function pointers recursively, as no sane programmer would
783/// even be able to write such a function type.
Richard Smith2e321552014-11-12 02:00:47 +0000784bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &NoteID,
785 const FunctionProtoType *Target,
786 SourceLocation TargetLoc,
787 const FunctionProtoType *Source,
788 SourceLocation SourceLoc) {
Alp Toker314cc812014-01-25 16:55:45 +0000789 if (CheckSpecForTypesEquivalent(
790 *this, PDiag(diag::err_deep_exception_specs_differ) << 0, PDiag(),
791 Target->getReturnType(), TargetLoc, Source->getReturnType(),
792 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000793 return true;
794
Sebastian Redla44822f2009-10-14 16:09:29 +0000795 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redl4915e632009-10-11 09:03:14 +0000796 // compatible.
Alp Toker9cacbab2014-01-20 20:26:09 +0000797 assert(Target->getNumParams() == Source->getNumParams() &&
Sebastian Redl4915e632009-10-11 09:03:14 +0000798 "Functions have different argument counts.");
Alp Toker9cacbab2014-01-20 20:26:09 +0000799 for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
800 if (CheckSpecForTypesEquivalent(
801 *this, PDiag(diag::err_deep_exception_specs_differ) << 1, PDiag(),
802 Target->getParamType(i), TargetLoc, Source->getParamType(i),
803 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000804 return true;
805 }
806 return false;
807}
808
Richard Smith2e321552014-11-12 02:00:47 +0000809bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000810 // First we check for applicability.
811 // Target type must be a function, function pointer or function reference.
812 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
Richard Smith2e321552014-11-12 02:00:47 +0000813 if (!ToFunc || ToFunc->hasDependentExceptionSpec())
Sebastian Redl4915e632009-10-11 09:03:14 +0000814 return false;
815
816 // SourceType must be a function or function pointer.
817 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
Richard Smith2e321552014-11-12 02:00:47 +0000818 if (!FromFunc || FromFunc->hasDependentExceptionSpec())
Sebastian Redl4915e632009-10-11 09:03:14 +0000819 return false;
820
821 // Now we've got the correct types on both sides, check their compatibility.
822 // This means that the source of the conversion can only throw a subset of
823 // the exceptions of the target, and any exception specs on arguments or
824 // return types must be equivalent.
Richard Smith2e321552014-11-12 02:00:47 +0000825 //
826 // FIXME: If there is a nested dependent exception specification, we should
827 // not be checking it here. This is fine:
828 // template<typename T> void f() {
829 // void (*p)(void (*) throw(T));
830 // void (*q)(void (*) throw(int)) = p;
831 // }
832 // ... because it might be instantiated with T=int.
Douglas Gregor89336232010-03-29 23:34:08 +0000833 return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
834 PDiag(), ToFunc,
835 From->getSourceRange().getBegin(),
Sebastian Redl4915e632009-10-11 09:03:14 +0000836 FromFunc, SourceLocation());
837}
838
839bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
840 const CXXMethodDecl *Old) {
Richard Smith88f45492014-11-22 03:09:05 +0000841 // If the new exception specification hasn't been parsed yet, skip the check.
842 // We'll get called again once it's been parsed.
843 if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
844 EST_Unparsed)
845 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000846 if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
Sebastian Redl645d9582011-05-20 05:57:18 +0000847 // Don't check uninstantiated template destructors at all. We can only
848 // synthesize correct specs after the template is instantiated.
849 if (New->getParent()->isDependentType())
850 return false;
851 if (New->getParent()->isBeingDefined()) {
852 // The destructor might be updated once the definition is finished. So
853 // remember it and check later.
Richard Smith88f45492014-11-22 03:09:05 +0000854 DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
Sebastian Redl645d9582011-05-20 05:57:18 +0000855 return false;
856 }
Sebastian Redl623ea822011-05-19 05:13:44 +0000857 }
Richard Smith88f45492014-11-22 03:09:05 +0000858 // If the old exception specification hasn't been parsed yet, remember that
859 // we need to perform this check when we get to the end of the outermost
860 // lexically-surrounding class.
861 if (Old->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
862 EST_Unparsed) {
863 DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
Richard Smith0b3a4622014-11-13 20:01:57 +0000864 return false;
Richard Smith88f45492014-11-22 03:09:05 +0000865 }
Francois Picheta8032e92011-05-24 02:11:43 +0000866 unsigned DiagID = diag::err_override_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000867 if (getLangOpts().MicrosoftExt)
Richard Smith1b98ccc2014-07-19 01:39:17 +0000868 DiagID = diag::ext_override_exception_spec;
Francois Picheta8032e92011-05-24 02:11:43 +0000869 return CheckExceptionSpecSubset(PDiag(DiagID),
Douglas Gregor89336232010-03-29 23:34:08 +0000870 PDiag(diag::note_overridden_virtual_function),
Sebastian Redl4915e632009-10-11 09:03:14 +0000871 Old->getType()->getAs<FunctionProtoType>(),
872 Old->getLocation(),
873 New->getType()->getAs<FunctionProtoType>(),
874 New->getLocation());
875}
876
Benjamin Kramer642f1732015-07-02 21:03:14 +0000877static CanThrowResult canSubExprsThrow(Sema &S, const Expr *E) {
Richard Smithf623c962012-04-17 00:58:00 +0000878 CanThrowResult R = CT_Cannot;
Benjamin Kramer642f1732015-07-02 21:03:14 +0000879 for (const Stmt *SubStmt : E->children()) {
880 R = mergeCanThrow(R, S.canThrow(cast<Expr>(SubStmt)));
881 if (R == CT_Can)
882 break;
883 }
Richard Smithf623c962012-04-17 00:58:00 +0000884 return R;
885}
886
Eli Friedman0423b762013-06-25 01:24:22 +0000887static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
888 assert(D && "Expected decl");
Richard Smithf623c962012-04-17 00:58:00 +0000889
890 // See if we can get a function type from the decl somehow.
891 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
892 if (!VD) // If we have no clue what we're calling, assume the worst.
893 return CT_Can;
894
895 // As an extension, we assume that __attribute__((nothrow)) functions don't
896 // throw.
897 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
898 return CT_Cannot;
899
900 QualType T = VD->getType();
901 const FunctionProtoType *FT;
902 if ((FT = T->getAs<FunctionProtoType>())) {
903 } else if (const PointerType *PT = T->getAs<PointerType>())
904 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
905 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
906 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
907 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
908 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
909 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
910 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
911
912 if (!FT)
913 return CT_Can;
914
915 FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
916 if (!FT)
917 return CT_Can;
918
Richard Smithf623c962012-04-17 00:58:00 +0000919 return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
920}
921
922static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
923 if (DC->isTypeDependent())
924 return CT_Dependent;
925
926 if (!DC->getTypeAsWritten()->isReferenceType())
927 return CT_Cannot;
928
929 if (DC->getSubExpr()->isTypeDependent())
930 return CT_Dependent;
931
932 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
933}
934
935static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
936 if (DC->isTypeOperand())
937 return CT_Cannot;
938
939 Expr *Op = DC->getExprOperand();
940 if (Op->isTypeDependent())
941 return CT_Dependent;
942
943 const RecordType *RT = Op->getType()->getAs<RecordType>();
944 if (!RT)
945 return CT_Cannot;
946
947 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
948 return CT_Cannot;
949
950 if (Op->Classify(S.Context).isPRValue())
951 return CT_Cannot;
952
953 return CT_Can;
954}
955
956CanThrowResult Sema::canThrow(const Expr *E) {
957 // C++ [expr.unary.noexcept]p3:
958 // [Can throw] if in a potentially-evaluated context the expression would
959 // contain:
960 switch (E->getStmtClass()) {
961 case Expr::CXXThrowExprClass:
962 // - a potentially evaluated throw-expression
963 return CT_Can;
964
965 case Expr::CXXDynamicCastExprClass: {
966 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
967 // where T is a reference type, that requires a run-time check
968 CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
969 if (CT == CT_Can)
970 return CT;
971 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
972 }
973
974 case Expr::CXXTypeidExprClass:
975 // - a potentially evaluated typeid expression applied to a glvalue
976 // expression whose type is a polymorphic class type
977 return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
978
979 // - a potentially evaluated call to a function, member function, function
980 // pointer, or member function pointer that does not have a non-throwing
981 // exception-specification
982 case Expr::CallExprClass:
983 case Expr::CXXMemberCallExprClass:
984 case Expr::CXXOperatorCallExprClass:
985 case Expr::UserDefinedLiteralClass: {
986 const CallExpr *CE = cast<CallExpr>(E);
987 CanThrowResult CT;
988 if (E->isTypeDependent())
989 CT = CT_Dependent;
990 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
991 CT = CT_Cannot;
Eli Friedman5a8738f2013-06-25 01:55:41 +0000992 else if (CE->getCalleeDecl())
Richard Smithf623c962012-04-17 00:58:00 +0000993 CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
Eli Friedman5a8738f2013-06-25 01:55:41 +0000994 else
995 CT = CT_Can;
Richard Smithf623c962012-04-17 00:58:00 +0000996 if (CT == CT_Can)
997 return CT;
998 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
999 }
1000
1001 case Expr::CXXConstructExprClass:
1002 case Expr::CXXTemporaryObjectExprClass: {
1003 CanThrowResult CT = canCalleeThrow(*this, E,
1004 cast<CXXConstructExpr>(E)->getConstructor());
1005 if (CT == CT_Can)
1006 return CT;
1007 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1008 }
1009
Richard Smith5179eb72016-06-28 19:03:57 +00001010 case Expr::CXXInheritedCtorInitExprClass:
1011 return canCalleeThrow(*this, E,
1012 cast<CXXInheritedCtorInitExpr>(E)->getConstructor());
1013
Richard Smithf623c962012-04-17 00:58:00 +00001014 case Expr::LambdaExprClass: {
1015 const LambdaExpr *Lambda = cast<LambdaExpr>(E);
1016 CanThrowResult CT = CT_Cannot;
James Y Knight53c76162015-07-17 18:21:37 +00001017 for (LambdaExpr::const_capture_init_iterator
1018 Cap = Lambda->capture_init_begin(),
1019 CapEnd = Lambda->capture_init_end();
Richard Smithf623c962012-04-17 00:58:00 +00001020 Cap != CapEnd; ++Cap)
1021 CT = mergeCanThrow(CT, canThrow(*Cap));
1022 return CT;
1023 }
1024
1025 case Expr::CXXNewExprClass: {
1026 CanThrowResult CT;
1027 if (E->isTypeDependent())
1028 CT = CT_Dependent;
1029 else
1030 CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
1031 if (CT == CT_Can)
1032 return CT;
1033 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1034 }
1035
1036 case Expr::CXXDeleteExprClass: {
1037 CanThrowResult CT;
1038 QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
1039 if (DTy.isNull() || DTy->isDependentType()) {
1040 CT = CT_Dependent;
1041 } else {
1042 CT = canCalleeThrow(*this, E,
1043 cast<CXXDeleteExpr>(E)->getOperatorDelete());
1044 if (const RecordType *RT = DTy->getAs<RecordType>()) {
1045 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedman0423b762013-06-25 01:24:22 +00001046 const CXXDestructorDecl *DD = RD->getDestructor();
1047 if (DD)
1048 CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
Richard Smithf623c962012-04-17 00:58:00 +00001049 }
1050 if (CT == CT_Can)
1051 return CT;
1052 }
1053 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1054 }
1055
1056 case Expr::CXXBindTemporaryExprClass: {
1057 // The bound temporary has to be destroyed again, which might throw.
1058 CanThrowResult CT = canCalleeThrow(*this, E,
1059 cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
1060 if (CT == CT_Can)
1061 return CT;
1062 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1063 }
1064
1065 // ObjC message sends are like function calls, but never have exception
1066 // specs.
1067 case Expr::ObjCMessageExprClass:
1068 case Expr::ObjCPropertyRefExprClass:
1069 case Expr::ObjCSubscriptRefExprClass:
1070 return CT_Can;
1071
1072 // All the ObjC literals that are implemented as calls are
1073 // potentially throwing unless we decide to close off that
1074 // possibility.
1075 case Expr::ObjCArrayLiteralClass:
1076 case Expr::ObjCDictionaryLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00001077 case Expr::ObjCBoxedExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001078 return CT_Can;
1079
1080 // Many other things have subexpressions, so we have to test those.
1081 // Some are simple:
Richard Smith9f690bd2015-10-27 06:02:45 +00001082 case Expr::CoawaitExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001083 case Expr::ConditionalOperatorClass:
1084 case Expr::CompoundLiteralExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00001085 case Expr::CoyieldExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001086 case Expr::CXXConstCastExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001087 case Expr::CXXReinterpretCastExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00001088 case Expr::CXXStdInitializerListExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001089 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00001090 case Expr::DesignatedInitUpdateExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001091 case Expr::ExprWithCleanupsClass:
1092 case Expr::ExtVectorElementExprClass:
1093 case Expr::InitListExprClass:
1094 case Expr::MemberExprClass:
1095 case Expr::ObjCIsaExprClass:
1096 case Expr::ObjCIvarRefExprClass:
1097 case Expr::ParenExprClass:
1098 case Expr::ParenListExprClass:
1099 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00001100 case Expr::ConvertVectorExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001101 case Expr::VAArgExprClass:
1102 return canSubExprsThrow(*this, E);
1103
1104 // Some might be dependent for other reasons.
1105 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001106 case Expr::OMPArraySectionExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001107 case Expr::BinaryOperatorClass:
1108 case Expr::CompoundAssignOperatorClass:
1109 case Expr::CStyleCastExprClass:
1110 case Expr::CXXStaticCastExprClass:
1111 case Expr::CXXFunctionalCastExprClass:
1112 case Expr::ImplicitCastExprClass:
1113 case Expr::MaterializeTemporaryExprClass:
1114 case Expr::UnaryOperatorClass: {
1115 CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1116 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1117 }
1118
1119 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1120 case Expr::StmtExprClass:
1121 return CT_Can;
1122
Richard Smith852c9db2013-04-20 22:23:05 +00001123 case Expr::CXXDefaultArgExprClass:
1124 return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1125
1126 case Expr::CXXDefaultInitExprClass:
1127 return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1128
Richard Smithf623c962012-04-17 00:58:00 +00001129 case Expr::ChooseExprClass:
1130 if (E->isTypeDependent() || E->isValueDependent())
1131 return CT_Dependent;
Eli Friedman75807f22013-07-20 00:40:58 +00001132 return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
Richard Smithf623c962012-04-17 00:58:00 +00001133
1134 case Expr::GenericSelectionExprClass:
1135 if (cast<GenericSelectionExpr>(E)->isResultDependent())
1136 return CT_Dependent;
1137 return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1138
1139 // Some expressions are always dependent.
1140 case Expr::CXXDependentScopeMemberExprClass:
1141 case Expr::CXXUnresolvedConstructExprClass:
1142 case Expr::DependentScopeDeclRefExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00001143 case Expr::CXXFoldExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001144 return CT_Dependent;
1145
1146 case Expr::AsTypeExprClass:
1147 case Expr::BinaryConditionalOperatorClass:
1148 case Expr::BlockExprClass:
1149 case Expr::CUDAKernelCallExprClass:
1150 case Expr::DeclRefExprClass:
1151 case Expr::ObjCBridgedCastExprClass:
1152 case Expr::ObjCIndirectCopyRestoreExprClass:
1153 case Expr::ObjCProtocolExprClass:
1154 case Expr::ObjCSelectorExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00001155 case Expr::ObjCAvailabilityCheckExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001156 case Expr::OffsetOfExprClass:
1157 case Expr::PackExpansionExprClass:
1158 case Expr::PseudoObjectExprClass:
1159 case Expr::SubstNonTypeTemplateParmExprClass:
1160 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00001161 case Expr::FunctionParmPackExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001162 case Expr::UnaryExprOrTypeTraitExprClass:
1163 case Expr::UnresolvedLookupExprClass:
1164 case Expr::UnresolvedMemberExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00001165 case Expr::TypoExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001166 // FIXME: Can any of the above throw? If so, when?
1167 return CT_Cannot;
1168
1169 case Expr::AddrLabelExprClass:
1170 case Expr::ArrayTypeTraitExprClass:
1171 case Expr::AtomicExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001172 case Expr::TypeTraitExprClass:
1173 case Expr::CXXBoolLiteralExprClass:
1174 case Expr::CXXNoexceptExprClass:
1175 case Expr::CXXNullPtrLiteralExprClass:
1176 case Expr::CXXPseudoDestructorExprClass:
1177 case Expr::CXXScalarValueInitExprClass:
1178 case Expr::CXXThisExprClass:
1179 case Expr::CXXUuidofExprClass:
1180 case Expr::CharacterLiteralClass:
1181 case Expr::ExpressionTraitExprClass:
1182 case Expr::FloatingLiteralClass:
1183 case Expr::GNUNullExprClass:
1184 case Expr::ImaginaryLiteralClass:
1185 case Expr::ImplicitValueInitExprClass:
1186 case Expr::IntegerLiteralClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00001187 case Expr::NoInitExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001188 case Expr::ObjCEncodeExprClass:
1189 case Expr::ObjCStringLiteralClass:
1190 case Expr::ObjCBoolLiteralExprClass:
1191 case Expr::OpaqueValueExprClass:
1192 case Expr::PredefinedExprClass:
1193 case Expr::SizeOfPackExprClass:
1194 case Expr::StringLiteralClass:
Richard Smithf623c962012-04-17 00:58:00 +00001195 // These expressions can never throw.
1196 return CT_Cannot;
1197
John McCall5e77d762013-04-16 07:28:30 +00001198 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00001199 case Expr::MSPropertySubscriptExprClass:
John McCall5e77d762013-04-16 07:28:30 +00001200 llvm_unreachable("Invalid class for expression");
1201
Richard Smithf623c962012-04-17 00:58:00 +00001202#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1203#define STMT_RANGE(Base, First, Last)
1204#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1205#define EXPR(CLASS, PARENT)
1206#define ABSTRACT_STMT(STMT)
1207#include "clang/AST/StmtNodes.inc"
1208 case Expr::NoStmtClass:
1209 llvm_unreachable("Invalid class for expression");
1210 }
1211 llvm_unreachable("Bogus StmtClass");
1212}
1213
Sebastian Redl4915e632009-10-11 09:03:14 +00001214} // end namespace clang