blob: 919d106e24b200dac972a2fb1ba7282dc9d9dc7f [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"
Sebastian Redl4915e632009-10-11 09:03:14 +000015#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
Douglas Gregord6bc5e62010-03-24 07:14:45 +000018#include "clang/AST/TypeLoc.h"
Douglas Gregorf40863c2010-02-12 07:32:17 +000019#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/Preprocessor.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
38/// CheckSpecifiedExceptionType - Check if the given type is valid in an
39/// exception specification. Incomplete types, or pointers to incomplete types
40/// other than void are not allowed.
Richard Smith8606d752012-11-28 22:33:28 +000041///
42/// \param[in,out] T The exception type. This will be decayed to a pointer type
43/// when the input is an array or a function type.
44bool Sema::CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range) {
Richard Smitha118c6a2012-11-28 22:52:42 +000045 // C++11 [except.spec]p2:
46 // A type cv T, "array of T", or "function returning T" denoted
Richard Smith8606d752012-11-28 22:33:28 +000047 // in an exception-specification is adjusted to type T, "pointer to T", or
48 // "pointer to function returning T", respectively.
Richard Smitha118c6a2012-11-28 22:52:42 +000049 //
50 // We also apply this rule in C++98.
Richard Smith8606d752012-11-28 22:33:28 +000051 if (T->isArrayType())
52 T = Context.getArrayDecayedType(T);
53 else if (T->isFunctionType())
54 T = Context.getPointerType(T);
Sebastian Redl4915e632009-10-11 09:03:14 +000055
Richard Smitha118c6a2012-11-28 22:52:42 +000056 int Kind = 0;
Richard Smith8606d752012-11-28 22:33:28 +000057 QualType PointeeT = T;
Richard Smitha118c6a2012-11-28 22:52:42 +000058 if (const PointerType *PT = T->getAs<PointerType>()) {
59 PointeeT = PT->getPointeeType();
60 Kind = 1;
Sebastian Redl4915e632009-10-11 09:03:14 +000061
Richard Smitha118c6a2012-11-28 22:52:42 +000062 // cv void* is explicitly permitted, despite being a pointer to an
63 // incomplete type.
64 if (PointeeT->isVoidType())
65 return false;
66 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
67 PointeeT = RT->getPointeeType();
68 Kind = 2;
Richard Smith8606d752012-11-28 22:33:28 +000069
Richard Smitha118c6a2012-11-28 22:52:42 +000070 if (RT->isRValueReferenceType()) {
71 // C++11 [except.spec]p2:
72 // A type denoted in an exception-specification shall not denote [...]
73 // an rvalue reference type.
74 Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
75 << T << Range;
76 return true;
77 }
78 }
79
80 // C++11 [except.spec]p2:
81 // A type denoted in an exception-specification shall not denote an
82 // incomplete type other than a class currently being defined [...].
83 // A type denoted in an exception-specification shall not denote a
84 // pointer or reference to an incomplete type, other than (cv) void* or a
85 // pointer or reference to a class currently being defined.
86 if (!(PointeeT->isRecordType() &&
87 PointeeT->getAs<RecordType>()->isBeingDefined()) &&
Richard Smith8606d752012-11-28 22:33:28 +000088 RequireCompleteType(Range.getBegin(), PointeeT,
Richard Smitha118c6a2012-11-28 22:52:42 +000089 diag::err_incomplete_in_exception_spec, Kind, Range))
Sebastian Redl7eb5d372009-10-14 14:59:48 +000090 return true;
Sebastian Redl4915e632009-10-11 09:03:14 +000091
92 return false;
93}
94
95/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
96/// to member to a function with an exception specification. This means that
97/// it is invalid to add another level of indirection.
98bool Sema::CheckDistantExceptionSpec(QualType T) {
99 if (const PointerType *PT = T->getAs<PointerType>())
100 T = PT->getPointeeType();
101 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
102 T = PT->getPointeeType();
103 else
104 return false;
105
106 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
107 if (!FnT)
108 return false;
109
110 return FnT->hasExceptionSpec();
111}
112
Richard Smithf623c962012-04-17 00:58:00 +0000113const FunctionProtoType *
114Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000115 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000116 return FPT;
117
118 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
119 const FunctionProtoType *SourceFPT =
120 SourceDecl->getType()->castAs<FunctionProtoType>();
121
Richard Smithd3b5c9082012-07-27 04:22:15 +0000122 // If the exception specification has already been resolved, just return it.
123 if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000124 return SourceFPT;
125
Richard Smithd3b5c9082012-07-27 04:22:15 +0000126 // Compute or instantiate the exception specification now.
Richard Smith3901dfe2013-03-27 00:22:47 +0000127 if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smithd3b5c9082012-07-27 04:22:15 +0000128 EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
129 else
130 InstantiateExceptionSpec(Loc, SourceDecl);
Richard Smithf623c962012-04-17 00:58:00 +0000131
132 return SourceDecl->getType()->castAs<FunctionProtoType>();
133}
134
Richard Smith66f3ac92012-10-20 08:26:51 +0000135/// Determine whether a function has an implicitly-generated exception
Richard Smith1ee63522012-10-16 23:30:16 +0000136/// specification.
Richard Smith66f3ac92012-10-20 08:26:51 +0000137static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
138 if (!isa<CXXDestructorDecl>(Decl) &&
139 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
140 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
141 return false;
Richard Smith1ee63522012-10-16 23:30:16 +0000142
Richard Smith66f3ac92012-10-20 08:26:51 +0000143 // If the user didn't declare the function, its exception specification must
144 // be implicit.
145 if (!Decl->getTypeSourceInfo())
146 return true;
147
148 const FunctionProtoType *Ty =
149 Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
150 return !Ty->hasExceptionSpec();
Richard Smith1ee63522012-10-16 23:30:16 +0000151}
152
Douglas Gregorf40863c2010-02-12 07:32:17 +0000153bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000154 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
155 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000156 bool MissingExceptionSpecification = false;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000157 bool MissingEmptyExceptionSpecification = false;
Francois Pichet13b4e682011-03-19 23:05:18 +0000158 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000159 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000160 DiagID = diag::warn_mismatched_exception_spec;
Richard Smithf623c962012-04-17 00:58:00 +0000161
Richard Smith1ee63522012-10-16 23:30:16 +0000162 // Check the types as written: they must match before any exception
163 // specification adjustment is applied.
164 if (!CheckEquivalentExceptionSpec(
165 PDiag(DiagID), PDiag(diag::note_previous_declaration),
Richard Smith66f3ac92012-10-20 08:26:51 +0000166 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
167 New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
Richard Smith1ee63522012-10-16 23:30:16 +0000168 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
Richard Smith66f3ac92012-10-20 08:26:51 +0000169 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
170 // C++11 [except.spec]p4 [DR1492]:
171 // If a declaration of a function has an implicit
172 // exception-specification, other declarations of the function shall
173 // not specify an exception-specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000174 if (getLangOpts().CPlusPlus11 &&
Richard Smith66f3ac92012-10-20 08:26:51 +0000175 hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
176 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
177 << hasImplicitExceptionSpec(Old);
178 if (!Old->getLocation().isInvalid())
179 Diag(Old->getLocation(), diag::note_previous_declaration);
180 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000181 return false;
Richard Smith66f3ac92012-10-20 08:26:51 +0000182 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000183
184 // The failure was something other than an empty exception
185 // specification; return an error.
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000186 if (!MissingExceptionSpecification && !MissingEmptyExceptionSpecification)
Douglas Gregorf40863c2010-02-12 07:32:17 +0000187 return true;
188
Richard Smith66f3ac92012-10-20 08:26:51 +0000189 const FunctionProtoType *NewProto =
190 New->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +0000191
Douglas Gregorf40863c2010-02-12 07:32:17 +0000192 // The new function declaration is only missing an empty exception
193 // specification "throw()". If the throw() specification came from a
194 // function in a system header that has C linkage, just add an empty
195 // exception specification to the "new" declaration. This is an
196 // egregious workaround for glibc, which adds throw() specifications
197 // to many libc functions as an optimization. Unfortunately, that
198 // optimization isn't permitted by the C++ standard, so we're forced
199 // to work around it here.
John McCalldb40c7f2010-12-14 08:05:40 +0000200 if (MissingEmptyExceptionSpecification && NewProto &&
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000201 (Old->getLocation().isInvalid() ||
202 Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000203 Old->isExternC()) {
John McCalldb40c7f2010-12-14 08:05:40 +0000204 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000205 EPI.ExceptionSpecType = EST_DynamicNone;
Reid Kleckner896b32f2013-06-10 20:51:09 +0000206 QualType NewType = Context.getFunctionType(NewProto->getResultType(),
207 NewProto->getArgTypes(), EPI);
Douglas Gregorf40863c2010-02-12 07:32:17 +0000208 New->setType(NewType);
209 return false;
210 }
211
John McCalldb40c7f2010-12-14 08:05:40 +0000212 if (MissingExceptionSpecification && NewProto) {
Richard Smith66f3ac92012-10-20 08:26:51 +0000213 const FunctionProtoType *OldProto =
214 Old->getType()->getAs<FunctionProtoType>();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000215
John McCalldb40c7f2010-12-14 08:05:40 +0000216 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000217 EPI.ExceptionSpecType = OldProto->getExceptionSpecType();
218 if (EPI.ExceptionSpecType == EST_Dynamic) {
219 EPI.NumExceptions = OldProto->getNumExceptions();
220 EPI.Exceptions = OldProto->exception_begin();
221 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
222 // FIXME: We can't just take the expression from the old prototype. It
223 // likely contains references to the old prototype's parameters.
224 }
John McCalldb40c7f2010-12-14 08:05:40 +0000225
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000226 // Update the type of the function with the appropriate exception
227 // specification.
Reid Kleckner896b32f2013-06-10 20:51:09 +0000228 QualType NewType = Context.getFunctionType(NewProto->getResultType(),
229 NewProto->getArgTypes(), EPI);
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000230 New->setType(NewType);
231
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000232 // Warn about the lack of exception specification.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000233 SmallString<128> ExceptionSpecString;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000234 llvm::raw_svector_ostream OS(ExceptionSpecString);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000235 switch (OldProto->getExceptionSpecType()) {
236 case EST_DynamicNone:
237 OS << "throw()";
238 break;
239
240 case EST_Dynamic: {
241 OS << "throw(";
242 bool OnFirstException = true;
243 for (FunctionProtoType::exception_iterator E = OldProto->exception_begin(),
244 EEnd = OldProto->exception_end();
245 E != EEnd;
246 ++E) {
247 if (OnFirstException)
248 OnFirstException = false;
249 else
250 OS << ", ";
251
Douglas Gregor75acd922011-09-27 23:30:47 +0000252 OS << E->getAsString(getPrintingPolicy());
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000253 }
254 OS << ")";
255 break;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000256 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000257
258 case EST_BasicNoexcept:
259 OS << "noexcept";
260 break;
261
262 case EST_ComputedNoexcept:
263 OS << "noexcept(";
Richard Smith235341b2012-08-16 03:56:14 +0000264 OldProto->getNoexceptExpr()->printPretty(OS, 0, getPrintingPolicy());
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000265 OS << ")";
266 break;
267
268 default:
David Blaikie83d382b2011-09-23 05:06:16 +0000269 llvm_unreachable("This spec type is compatible with none.");
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000270 }
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000271 OS.flush();
272
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +0000273 SourceLocation FixItLoc;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000274 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
Abramo Bagnara6d810632010-12-14 22:11:44 +0000275 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +0000276 if (FunctionTypeLoc FTLoc = TL.getAs<FunctionTypeLoc>())
277 FixItLoc = PP.getLocForEndOfToken(FTLoc.getLocalRangeEnd());
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000278 }
279
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +0000280 if (FixItLoc.isInvalid())
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000281 Diag(New->getLocation(), diag::warn_missing_exception_specification)
282 << New << OS.str();
283 else {
284 // FIXME: This will get more complicated with C++0x
285 // late-specified return types.
286 Diag(New->getLocation(), diag::warn_missing_exception_specification)
287 << New << OS.str()
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +0000288 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000289 }
290
291 if (!Old->getLocation().isInvalid())
292 Diag(Old->getLocation(), diag::note_previous_declaration);
293
294 return false;
295 }
296
Francois Pichet13b4e682011-03-19 23:05:18 +0000297 Diag(New->getLocation(), DiagID);
Douglas Gregorf40863c2010-02-12 07:32:17 +0000298 Diag(Old->getLocation(), diag::note_previous_declaration);
299 return true;
300}
301
Sebastian Redl4915e632009-10-11 09:03:14 +0000302/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
303/// exception specifications. Exception specifications are equivalent if
304/// they allow exactly the same set of exception types. It does not matter how
305/// that is achieved. See C++ [except.spec]p2.
306bool Sema::CheckEquivalentExceptionSpec(
307 const FunctionProtoType *Old, SourceLocation OldLoc,
308 const FunctionProtoType *New, SourceLocation NewLoc) {
Francois Pichet13b4e682011-03-19 23:05:18 +0000309 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000310 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000311 DiagID = diag::warn_mismatched_exception_spec;
Richard Smith1ee63522012-10-16 23:30:16 +0000312 return CheckEquivalentExceptionSpec(PDiag(DiagID),
Douglas Gregor89336232010-03-29 23:34:08 +0000313 PDiag(diag::note_previous_declaration),
Sebastian Redl4915e632009-10-11 09:03:14 +0000314 Old, OldLoc, New, NewLoc);
315}
316
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000317/// CheckEquivalentExceptionSpec - Check if the two types have compatible
318/// exception specifications. See C++ [except.spec]p3.
Richard Smith66f3ac92012-10-20 08:26:51 +0000319///
320/// \return \c false if the exception specifications match, \c true if there is
321/// a problem. If \c true is returned, either a diagnostic has already been
322/// produced or \c *MissingExceptionSpecification is set to \c true.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000323bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000324 const PartialDiagnostic & NoteID,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000325 const FunctionProtoType *Old,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000326 SourceLocation OldLoc,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000327 const FunctionProtoType *New,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000328 SourceLocation NewLoc,
329 bool *MissingExceptionSpecification,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000330 bool*MissingEmptyExceptionSpecification,
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000331 bool AllowNoexceptAllMatchWithNoSpec,
332 bool IsOperatorNew) {
John McCallf9c94092010-05-28 08:37:35 +0000333 // Just completely ignore this under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000334 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000335 return false;
336
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000337 if (MissingExceptionSpecification)
338 *MissingExceptionSpecification = false;
339
Douglas Gregorf40863c2010-02-12 07:32:17 +0000340 if (MissingEmptyExceptionSpecification)
341 *MissingEmptyExceptionSpecification = false;
342
Richard Smithf623c962012-04-17 00:58:00 +0000343 Old = ResolveExceptionSpec(NewLoc, Old);
344 if (!Old)
345 return false;
346 New = ResolveExceptionSpec(NewLoc, New);
347 if (!New)
348 return false;
349
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000350 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
351 // - both are non-throwing, regardless of their form,
352 // - both have the form noexcept(constant-expression) and the constant-
353 // expressions are equivalent,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000354 // - both are dynamic-exception-specifications that have the same set of
355 // adjusted types.
356 //
357 // C++0x [except.spec]p12: An exception-specifcation is non-throwing if it is
358 // of the form throw(), noexcept, or noexcept(constant-expression) where the
359 // constant-expression yields true.
360 //
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000361 // C++0x [except.spec]p4: If any declaration of a function has an exception-
362 // specifier that is not a noexcept-specification allowing all exceptions,
363 // all declarations [...] of that function shall have a compatible
364 // exception-specification.
365 //
366 // That last point basically means that noexcept(false) matches no spec.
367 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
368
369 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
370 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
371
Richard Smithd3b5c9082012-07-27 04:22:15 +0000372 assert(!isUnresolvedExceptionSpec(OldEST) &&
373 !isUnresolvedExceptionSpec(NewEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000374 "Shouldn't see unknown exception specifications here");
375
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000376 // Shortcut the case where both have no spec.
377 if (OldEST == EST_None && NewEST == EST_None)
378 return false;
379
Sebastian Redl31ad7542011-03-13 17:09:40 +0000380 FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
381 FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000382 if (OldNR == FunctionProtoType::NR_BadNoexcept ||
383 NewNR == FunctionProtoType::NR_BadNoexcept)
384 return false;
385
386 // Dependent noexcept specifiers are compatible with each other, but nothing
387 // else.
388 // One noexcept is compatible with another if the argument is the same
389 if (OldNR == NewNR &&
390 OldNR != FunctionProtoType::NR_NoNoexcept &&
391 NewNR != FunctionProtoType::NR_NoNoexcept)
392 return false;
393 if (OldNR != NewNR &&
394 OldNR != FunctionProtoType::NR_NoNoexcept &&
395 NewNR != FunctionProtoType::NR_NoNoexcept) {
396 Diag(NewLoc, DiagID);
397 if (NoteID.getDiagID() != 0)
398 Diag(OldLoc, NoteID);
399 return true;
Douglas Gregorf62c5292010-08-30 15:04:51 +0000400 }
401
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000402 // The MS extension throw(...) is compatible with itself.
403 if (OldEST == EST_MSAny && NewEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000404 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000405
406 // It's also compatible with no spec.
407 if ((OldEST == EST_None && NewEST == EST_MSAny) ||
408 (OldEST == EST_MSAny && NewEST == EST_None))
409 return false;
410
411 // It's also compatible with noexcept(false).
412 if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
413 return false;
414 if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
415 return false;
416
417 // As described above, noexcept(false) matches no spec only for functions.
418 if (AllowNoexceptAllMatchWithNoSpec) {
419 if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
420 return false;
421 if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
422 return false;
423 }
424
425 // Any non-throwing specifications are compatible.
426 bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
427 OldEST == EST_DynamicNone;
428 bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
429 NewEST == EST_DynamicNone;
430 if (OldNonThrowing && NewNonThrowing)
431 return false;
432
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000433 // As a special compatibility feature, under C++0x we accept no spec and
434 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
435 // This is because the implicit declaration changed, but old code would break.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000436 if (getLangOpts().CPlusPlus11 && IsOperatorNew) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000437 const FunctionProtoType *WithExceptions = 0;
438 if (OldEST == EST_None && NewEST == EST_Dynamic)
439 WithExceptions = New;
440 else if (OldEST == EST_Dynamic && NewEST == EST_None)
441 WithExceptions = Old;
442 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
443 // One has no spec, the other throw(something). If that something is
444 // std::bad_alloc, all conditions are met.
445 QualType Exception = *WithExceptions->exception_begin();
446 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
447 IdentifierInfo* Name = ExRecord->getIdentifier();
448 if (Name && Name->getName() == "bad_alloc") {
449 // It's called bad_alloc, but is it in std?
450 DeclContext* DC = ExRecord->getDeclContext();
Sebastian Redlc34c29f2011-03-15 20:41:09 +0000451 DC = DC->getEnclosingNamespaceContext();
452 if (NamespaceDecl* NS = dyn_cast<NamespaceDecl>(DC)) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000453 IdentifierInfo* NSName = NS->getIdentifier();
Sebastian Redlc34c29f2011-03-15 20:41:09 +0000454 DC = DC->getParent();
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000455 if (NSName && NSName->getName() == "std" &&
Sebastian Redlc34c29f2011-03-15 20:41:09 +0000456 DC->getEnclosingNamespaceContext()->isTranslationUnit()) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000457 return false;
Sebastian Redlc34c29f2011-03-15 20:41:09 +0000458 }
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000459 }
460 }
461 }
462 }
463 }
464
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000465 // At this point, the only remaining valid case is two matching dynamic
466 // specifications. We return here unless both specifications are dynamic.
467 if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000468 if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000469 !New->hasExceptionSpec()) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000470 // The old type has an exception specification of some sort, but
471 // the new type does not.
472 *MissingExceptionSpecification = true;
473
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000474 if (MissingEmptyExceptionSpecification && OldNonThrowing) {
475 // The old type has a throw() or noexcept(true) exception specification
476 // and the new type has no exception specification, and the caller asked
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000477 // to handle this itself.
478 *MissingEmptyExceptionSpecification = true;
479 }
480
Douglas Gregorf40863c2010-02-12 07:32:17 +0000481 return true;
482 }
483
Sebastian Redl4915e632009-10-11 09:03:14 +0000484 Diag(NewLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000485 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000486 Diag(OldLoc, NoteID);
487 return true;
488 }
489
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000490 assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
491 "Exception compatibility logic error: non-dynamic spec slipped through.");
492
Sebastian Redl4915e632009-10-11 09:03:14 +0000493 bool Success = true;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000494 // Both have a dynamic exception spec. Collect the first set, then compare
Sebastian Redl4915e632009-10-11 09:03:14 +0000495 // to the second.
Sebastian Redl184edca2009-10-14 15:06:25 +0000496 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
Sebastian Redl4915e632009-10-11 09:03:14 +0000497 for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
498 E = Old->exception_end(); I != E; ++I)
Sebastian Redl184edca2009-10-14 15:06:25 +0000499 OldTypes.insert(Context.getCanonicalType(*I).getUnqualifiedType());
Sebastian Redl4915e632009-10-11 09:03:14 +0000500
501 for (FunctionProtoType::exception_iterator I = New->exception_begin(),
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000502 E = New->exception_end(); I != E && Success; ++I) {
Sebastian Redl184edca2009-10-14 15:06:25 +0000503 CanQualType TypePtr = Context.getCanonicalType(*I).getUnqualifiedType();
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000504 if(OldTypes.count(TypePtr))
505 NewTypes.insert(TypePtr);
506 else
507 Success = false;
508 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000509
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000510 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redl4915e632009-10-11 09:03:14 +0000511
512 if (Success) {
513 return false;
514 }
515 Diag(NewLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000516 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000517 Diag(OldLoc, NoteID);
518 return true;
519}
520
521/// CheckExceptionSpecSubset - Check whether the second function type's
522/// exception specification is a subset (or equivalent) of the first function
523/// type. This is used by override and pointer assignment checks.
Sebastian Redla44822f2009-10-14 16:09:29 +0000524bool Sema::CheckExceptionSpecSubset(
525 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000526 const FunctionProtoType *Superset, SourceLocation SuperLoc,
527 const FunctionProtoType *Subset, SourceLocation SubLoc) {
John McCallf9c94092010-05-28 08:37:35 +0000528
529 // Just auto-succeed under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000530 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000531 return false;
532
Sebastian Redl4915e632009-10-11 09:03:14 +0000533 // FIXME: As usual, we could be more specific in our error messages, but
534 // that better waits until we've got types with source locations.
535
536 if (!SubLoc.isValid())
537 SubLoc = SuperLoc;
538
Richard Smithf623c962012-04-17 00:58:00 +0000539 // Resolve the exception specifications, if needed.
540 Superset = ResolveExceptionSpec(SuperLoc, Superset);
541 if (!Superset)
542 return false;
543 Subset = ResolveExceptionSpec(SubLoc, Subset);
544 if (!Subset)
545 return false;
546
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000547 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
548
Sebastian Redl4915e632009-10-11 09:03:14 +0000549 // If superset contains everything, we're done.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000550 if (SuperEST == EST_None || SuperEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000551 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
552
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000553 // If there are dependent noexcept specs, assume everything is fine. Unlike
554 // with the equivalency check, this is safe in this case, because we don't
555 // want to merge declarations. Checks after instantiation will catch any
556 // omissions we make here.
557 // We also shortcut checking if a noexcept expression was bad.
558
Sebastian Redl31ad7542011-03-13 17:09:40 +0000559 FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000560 if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
561 SuperNR == FunctionProtoType::NR_Dependent)
562 return false;
563
564 // Another case of the superset containing everything.
565 if (SuperNR == FunctionProtoType::NR_Throw)
566 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
567
568 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
569
Richard Smithd3b5c9082012-07-27 04:22:15 +0000570 assert(!isUnresolvedExceptionSpec(SuperEST) &&
571 !isUnresolvedExceptionSpec(SubEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000572 "Shouldn't see unknown exception specifications here");
573
Sebastian Redl4915e632009-10-11 09:03:14 +0000574 // It does not. If the subset contains everything, we've failed.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000575 if (SubEST == EST_None || SubEST == EST_MSAny) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000576 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000577 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000578 Diag(SuperLoc, NoteID);
579 return true;
580 }
581
Sebastian Redl31ad7542011-03-13 17:09:40 +0000582 FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000583 if (SubNR == FunctionProtoType::NR_BadNoexcept ||
584 SubNR == FunctionProtoType::NR_Dependent)
585 return false;
586
587 // Another case of the subset containing everything.
588 if (SubNR == FunctionProtoType::NR_Throw) {
589 Diag(SubLoc, DiagID);
590 if (NoteID.getDiagID() != 0)
591 Diag(SuperLoc, NoteID);
592 return true;
593 }
594
595 // If the subset contains nothing, we're done.
596 if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
597 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
598
599 // Otherwise, if the superset contains nothing, we've failed.
600 if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
601 Diag(SubLoc, DiagID);
602 if (NoteID.getDiagID() != 0)
603 Diag(SuperLoc, NoteID);
604 return true;
605 }
606
607 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
608 "Exception spec subset: non-dynamic case slipped through.");
609
610 // Neither contains everything or nothing. Do a proper comparison.
Sebastian Redl4915e632009-10-11 09:03:14 +0000611 for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
612 SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
613 // Take one type from the subset.
614 QualType CanonicalSubT = Context.getCanonicalType(*SubI);
Sebastian Redl075b21d2009-10-14 14:38:54 +0000615 // Unwrap pointers and references so that we can do checks within a class
616 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
617 // conversions on the pointee.
Sebastian Redl4915e632009-10-11 09:03:14 +0000618 bool SubIsPointer = false;
619 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
620 CanonicalSubT = RefTy->getPointeeType();
621 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
622 CanonicalSubT = PtrTy->getPointeeType();
623 SubIsPointer = true;
624 }
625 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000626 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000627
628 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
629 /*DetectVirtual=*/false);
630
631 bool Contained = false;
632 // Make sure it's in the superset.
633 for (FunctionProtoType::exception_iterator SuperI =
634 Superset->exception_begin(), SuperE = Superset->exception_end();
635 SuperI != SuperE; ++SuperI) {
636 QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
637 // SubT must be SuperT or derived from it, or pointer or reference to
638 // such types.
639 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
640 CanonicalSuperT = RefTy->getPointeeType();
641 if (SubIsPointer) {
642 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
643 CanonicalSuperT = PtrTy->getPointeeType();
644 else {
645 continue;
646 }
647 }
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000648 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000649 // If the types are the same, move on to the next type in the subset.
650 if (CanonicalSubT == CanonicalSuperT) {
651 Contained = true;
652 break;
653 }
654
655 // Otherwise we need to check the inheritance.
656 if (!SubIsClass || !CanonicalSuperT->isRecordType())
657 continue;
658
659 Paths.clear();
660 if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
661 continue;
662
Douglas Gregor27ac4292010-05-21 20:29:55 +0000663 if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
Sebastian Redl4915e632009-10-11 09:03:14 +0000664 continue;
665
John McCall5b0829a2010-02-10 09:31:12 +0000666 // Do this check from a context without privileges.
John McCall1064d7e2010-03-16 05:22:47 +0000667 switch (CheckBaseClassAccess(SourceLocation(),
John McCall5b0829a2010-02-10 09:31:12 +0000668 CanonicalSuperT, CanonicalSubT,
669 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +0000670 /*Diagnostic*/ 0,
John McCall5b0829a2010-02-10 09:31:12 +0000671 /*ForceCheck*/ true,
John McCall1064d7e2010-03-16 05:22:47 +0000672 /*ForceUnprivileged*/ true)) {
John McCall5b0829a2010-02-10 09:31:12 +0000673 case AR_accessible: break;
674 case AR_inaccessible: continue;
675 case AR_dependent:
676 llvm_unreachable("access check dependent for unprivileged context");
John McCall5b0829a2010-02-10 09:31:12 +0000677 case AR_delayed:
678 llvm_unreachable("access check delayed in non-declaration");
John McCall5b0829a2010-02-10 09:31:12 +0000679 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000680
681 Contained = true;
682 break;
683 }
684 if (!Contained) {
685 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000686 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000687 Diag(SuperLoc, NoteID);
688 return true;
689 }
690 }
691 // We've run half the gauntlet.
692 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
693}
694
695static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redla44822f2009-10-14 16:09:29 +0000696 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000697 QualType Target, SourceLocation TargetLoc,
698 QualType Source, SourceLocation SourceLoc)
699{
700 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
701 if (!TFunc)
702 return false;
703 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
704 if (!SFunc)
705 return false;
706
707 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
708 SFunc, SourceLoc);
709}
710
711/// CheckParamExceptionSpec - Check if the parameter and return types of the
712/// two functions have equivalent exception specs. This is part of the
713/// assignment and override compatibility check. We do not check the parameters
714/// of parameter function pointers recursively, as no sane programmer would
715/// even be able to write such a function type.
Sebastian Redla44822f2009-10-14 16:09:29 +0000716bool Sema::CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000717 const FunctionProtoType *Target, SourceLocation TargetLoc,
718 const FunctionProtoType *Source, SourceLocation SourceLoc)
719{
Sebastian Redla44822f2009-10-14 16:09:29 +0000720 if (CheckSpecForTypesEquivalent(*this,
Douglas Gregor89336232010-03-29 23:34:08 +0000721 PDiag(diag::err_deep_exception_specs_differ) << 0,
722 PDiag(),
Sebastian Redl4915e632009-10-11 09:03:14 +0000723 Target->getResultType(), TargetLoc,
724 Source->getResultType(), SourceLoc))
725 return true;
726
Sebastian Redla44822f2009-10-14 16:09:29 +0000727 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redl4915e632009-10-11 09:03:14 +0000728 // compatible.
729 assert(Target->getNumArgs() == Source->getNumArgs() &&
730 "Functions have different argument counts.");
731 for (unsigned i = 0, E = Target->getNumArgs(); i != E; ++i) {
Sebastian Redla44822f2009-10-14 16:09:29 +0000732 if (CheckSpecForTypesEquivalent(*this,
Douglas Gregor89336232010-03-29 23:34:08 +0000733 PDiag(diag::err_deep_exception_specs_differ) << 1,
734 PDiag(),
Sebastian Redl4915e632009-10-11 09:03:14 +0000735 Target->getArgType(i), TargetLoc,
736 Source->getArgType(i), SourceLoc))
737 return true;
738 }
739 return false;
740}
741
742bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
743{
744 // First we check for applicability.
745 // Target type must be a function, function pointer or function reference.
746 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
747 if (!ToFunc)
748 return false;
749
750 // SourceType must be a function or function pointer.
751 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
752 if (!FromFunc)
753 return false;
754
755 // Now we've got the correct types on both sides, check their compatibility.
756 // This means that the source of the conversion can only throw a subset of
757 // the exceptions of the target, and any exception specs on arguments or
758 // return types must be equivalent.
Douglas Gregor89336232010-03-29 23:34:08 +0000759 return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
760 PDiag(), ToFunc,
761 From->getSourceRange().getBegin(),
Sebastian Redl4915e632009-10-11 09:03:14 +0000762 FromFunc, SourceLocation());
763}
764
765bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
766 const CXXMethodDecl *Old) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000767 if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
Sebastian Redl645d9582011-05-20 05:57:18 +0000768 // Don't check uninstantiated template destructors at all. We can only
769 // synthesize correct specs after the template is instantiated.
770 if (New->getParent()->isDependentType())
771 return false;
772 if (New->getParent()->isBeingDefined()) {
773 // The destructor might be updated once the definition is finished. So
774 // remember it and check later.
775 DelayedDestructorExceptionSpecChecks.push_back(std::make_pair(
776 cast<CXXDestructorDecl>(New), cast<CXXDestructorDecl>(Old)));
777 return false;
778 }
Sebastian Redl623ea822011-05-19 05:13:44 +0000779 }
Francois Picheta8032e92011-05-24 02:11:43 +0000780 unsigned DiagID = diag::err_override_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000781 if (getLangOpts().MicrosoftExt)
Francois Picheta8032e92011-05-24 02:11:43 +0000782 DiagID = diag::warn_override_exception_spec;
783 return CheckExceptionSpecSubset(PDiag(DiagID),
Douglas Gregor89336232010-03-29 23:34:08 +0000784 PDiag(diag::note_overridden_virtual_function),
Sebastian Redl4915e632009-10-11 09:03:14 +0000785 Old->getType()->getAs<FunctionProtoType>(),
786 Old->getLocation(),
787 New->getType()->getAs<FunctionProtoType>(),
788 New->getLocation());
789}
790
Richard Smithf623c962012-04-17 00:58:00 +0000791static CanThrowResult canSubExprsThrow(Sema &S, const Expr *CE) {
792 Expr *E = const_cast<Expr*>(CE);
793 CanThrowResult R = CT_Cannot;
794 for (Expr::child_range I = E->children(); I && R != CT_Can; ++I)
795 R = mergeCanThrow(R, S.canThrow(cast<Expr>(*I)));
796 return R;
797}
798
799static CanThrowResult canCalleeThrow(Sema &S, const Expr *E,
800 const Decl *D,
801 bool NullThrows = true) {
802 if (!D)
803 return NullThrows ? CT_Can : CT_Cannot;
804
805 // See if we can get a function type from the decl somehow.
806 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
807 if (!VD) // If we have no clue what we're calling, assume the worst.
808 return CT_Can;
809
810 // As an extension, we assume that __attribute__((nothrow)) functions don't
811 // throw.
812 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
813 return CT_Cannot;
814
815 QualType T = VD->getType();
816 const FunctionProtoType *FT;
817 if ((FT = T->getAs<FunctionProtoType>())) {
818 } else if (const PointerType *PT = T->getAs<PointerType>())
819 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
820 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
821 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
822 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
823 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
824 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
825 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
826
827 if (!FT)
828 return CT_Can;
829
830 FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
831 if (!FT)
832 return CT_Can;
833
Richard Smithf623c962012-04-17 00:58:00 +0000834 return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
835}
836
837static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
838 if (DC->isTypeDependent())
839 return CT_Dependent;
840
841 if (!DC->getTypeAsWritten()->isReferenceType())
842 return CT_Cannot;
843
844 if (DC->getSubExpr()->isTypeDependent())
845 return CT_Dependent;
846
847 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
848}
849
850static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
851 if (DC->isTypeOperand())
852 return CT_Cannot;
853
854 Expr *Op = DC->getExprOperand();
855 if (Op->isTypeDependent())
856 return CT_Dependent;
857
858 const RecordType *RT = Op->getType()->getAs<RecordType>();
859 if (!RT)
860 return CT_Cannot;
861
862 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
863 return CT_Cannot;
864
865 if (Op->Classify(S.Context).isPRValue())
866 return CT_Cannot;
867
868 return CT_Can;
869}
870
871CanThrowResult Sema::canThrow(const Expr *E) {
872 // C++ [expr.unary.noexcept]p3:
873 // [Can throw] if in a potentially-evaluated context the expression would
874 // contain:
875 switch (E->getStmtClass()) {
876 case Expr::CXXThrowExprClass:
877 // - a potentially evaluated throw-expression
878 return CT_Can;
879
880 case Expr::CXXDynamicCastExprClass: {
881 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
882 // where T is a reference type, that requires a run-time check
883 CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
884 if (CT == CT_Can)
885 return CT;
886 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
887 }
888
889 case Expr::CXXTypeidExprClass:
890 // - a potentially evaluated typeid expression applied to a glvalue
891 // expression whose type is a polymorphic class type
892 return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
893
894 // - a potentially evaluated call to a function, member function, function
895 // pointer, or member function pointer that does not have a non-throwing
896 // exception-specification
897 case Expr::CallExprClass:
898 case Expr::CXXMemberCallExprClass:
899 case Expr::CXXOperatorCallExprClass:
900 case Expr::UserDefinedLiteralClass: {
901 const CallExpr *CE = cast<CallExpr>(E);
902 CanThrowResult CT;
903 if (E->isTypeDependent())
904 CT = CT_Dependent;
905 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
906 CT = CT_Cannot;
907 else
908 CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
909 if (CT == CT_Can)
910 return CT;
911 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
912 }
913
914 case Expr::CXXConstructExprClass:
915 case Expr::CXXTemporaryObjectExprClass: {
916 CanThrowResult CT = canCalleeThrow(*this, E,
917 cast<CXXConstructExpr>(E)->getConstructor());
918 if (CT == CT_Can)
919 return CT;
920 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
921 }
922
923 case Expr::LambdaExprClass: {
924 const LambdaExpr *Lambda = cast<LambdaExpr>(E);
925 CanThrowResult CT = CT_Cannot;
926 for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
927 CapEnd = Lambda->capture_init_end();
928 Cap != CapEnd; ++Cap)
929 CT = mergeCanThrow(CT, canThrow(*Cap));
930 return CT;
931 }
932
933 case Expr::CXXNewExprClass: {
934 CanThrowResult CT;
935 if (E->isTypeDependent())
936 CT = CT_Dependent;
937 else
938 CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
939 if (CT == CT_Can)
940 return CT;
941 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
942 }
943
944 case Expr::CXXDeleteExprClass: {
945 CanThrowResult CT;
946 QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
947 if (DTy.isNull() || DTy->isDependentType()) {
948 CT = CT_Dependent;
949 } else {
950 CT = canCalleeThrow(*this, E,
951 cast<CXXDeleteExpr>(E)->getOperatorDelete());
952 if (const RecordType *RT = DTy->getAs<RecordType>()) {
953 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
954 CT = mergeCanThrow(CT, canCalleeThrow(*this, E, RD->getDestructor()));
955 }
956 if (CT == CT_Can)
957 return CT;
958 }
959 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
960 }
961
962 case Expr::CXXBindTemporaryExprClass: {
963 // The bound temporary has to be destroyed again, which might throw.
964 CanThrowResult CT = canCalleeThrow(*this, E,
965 cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
966 if (CT == CT_Can)
967 return CT;
968 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
969 }
970
971 // ObjC message sends are like function calls, but never have exception
972 // specs.
973 case Expr::ObjCMessageExprClass:
974 case Expr::ObjCPropertyRefExprClass:
975 case Expr::ObjCSubscriptRefExprClass:
976 return CT_Can;
977
978 // All the ObjC literals that are implemented as calls are
979 // potentially throwing unless we decide to close off that
980 // possibility.
981 case Expr::ObjCArrayLiteralClass:
982 case Expr::ObjCDictionaryLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +0000983 case Expr::ObjCBoxedExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000984 return CT_Can;
985
986 // Many other things have subexpressions, so we have to test those.
987 // Some are simple:
988 case Expr::ConditionalOperatorClass:
989 case Expr::CompoundLiteralExprClass:
990 case Expr::CXXConstCastExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000991 case Expr::CXXReinterpretCastExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +0000992 case Expr::CXXStdInitializerListExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000993 case Expr::DesignatedInitExprClass:
994 case Expr::ExprWithCleanupsClass:
995 case Expr::ExtVectorElementExprClass:
996 case Expr::InitListExprClass:
997 case Expr::MemberExprClass:
998 case Expr::ObjCIsaExprClass:
999 case Expr::ObjCIvarRefExprClass:
1000 case Expr::ParenExprClass:
1001 case Expr::ParenListExprClass:
1002 case Expr::ShuffleVectorExprClass:
1003 case Expr::VAArgExprClass:
1004 return canSubExprsThrow(*this, E);
1005
1006 // Some might be dependent for other reasons.
1007 case Expr::ArraySubscriptExprClass:
1008 case Expr::BinaryOperatorClass:
1009 case Expr::CompoundAssignOperatorClass:
1010 case Expr::CStyleCastExprClass:
1011 case Expr::CXXStaticCastExprClass:
1012 case Expr::CXXFunctionalCastExprClass:
1013 case Expr::ImplicitCastExprClass:
1014 case Expr::MaterializeTemporaryExprClass:
1015 case Expr::UnaryOperatorClass: {
1016 CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1017 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1018 }
1019
1020 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1021 case Expr::StmtExprClass:
1022 return CT_Can;
1023
Richard Smith852c9db2013-04-20 22:23:05 +00001024 case Expr::CXXDefaultArgExprClass:
1025 return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1026
1027 case Expr::CXXDefaultInitExprClass:
1028 return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1029
Richard Smithf623c962012-04-17 00:58:00 +00001030 case Expr::ChooseExprClass:
1031 if (E->isTypeDependent() || E->isValueDependent())
1032 return CT_Dependent;
1033 return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr(Context));
1034
1035 case Expr::GenericSelectionExprClass:
1036 if (cast<GenericSelectionExpr>(E)->isResultDependent())
1037 return CT_Dependent;
1038 return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1039
1040 // Some expressions are always dependent.
1041 case Expr::CXXDependentScopeMemberExprClass:
1042 case Expr::CXXUnresolvedConstructExprClass:
1043 case Expr::DependentScopeDeclRefExprClass:
1044 return CT_Dependent;
1045
1046 case Expr::AsTypeExprClass:
1047 case Expr::BinaryConditionalOperatorClass:
1048 case Expr::BlockExprClass:
1049 case Expr::CUDAKernelCallExprClass:
1050 case Expr::DeclRefExprClass:
1051 case Expr::ObjCBridgedCastExprClass:
1052 case Expr::ObjCIndirectCopyRestoreExprClass:
1053 case Expr::ObjCProtocolExprClass:
1054 case Expr::ObjCSelectorExprClass:
1055 case Expr::OffsetOfExprClass:
1056 case Expr::PackExpansionExprClass:
1057 case Expr::PseudoObjectExprClass:
1058 case Expr::SubstNonTypeTemplateParmExprClass:
1059 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00001060 case Expr::FunctionParmPackExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001061 case Expr::UnaryExprOrTypeTraitExprClass:
1062 case Expr::UnresolvedLookupExprClass:
1063 case Expr::UnresolvedMemberExprClass:
1064 // FIXME: Can any of the above throw? If so, when?
1065 return CT_Cannot;
1066
1067 case Expr::AddrLabelExprClass:
1068 case Expr::ArrayTypeTraitExprClass:
1069 case Expr::AtomicExprClass:
1070 case Expr::BinaryTypeTraitExprClass:
1071 case Expr::TypeTraitExprClass:
1072 case Expr::CXXBoolLiteralExprClass:
1073 case Expr::CXXNoexceptExprClass:
1074 case Expr::CXXNullPtrLiteralExprClass:
1075 case Expr::CXXPseudoDestructorExprClass:
1076 case Expr::CXXScalarValueInitExprClass:
1077 case Expr::CXXThisExprClass:
1078 case Expr::CXXUuidofExprClass:
1079 case Expr::CharacterLiteralClass:
1080 case Expr::ExpressionTraitExprClass:
1081 case Expr::FloatingLiteralClass:
1082 case Expr::GNUNullExprClass:
1083 case Expr::ImaginaryLiteralClass:
1084 case Expr::ImplicitValueInitExprClass:
1085 case Expr::IntegerLiteralClass:
1086 case Expr::ObjCEncodeExprClass:
1087 case Expr::ObjCStringLiteralClass:
1088 case Expr::ObjCBoolLiteralExprClass:
1089 case Expr::OpaqueValueExprClass:
1090 case Expr::PredefinedExprClass:
1091 case Expr::SizeOfPackExprClass:
1092 case Expr::StringLiteralClass:
1093 case Expr::UnaryTypeTraitExprClass:
1094 // These expressions can never throw.
1095 return CT_Cannot;
1096
John McCall5e77d762013-04-16 07:28:30 +00001097 case Expr::MSPropertyRefExprClass:
1098 llvm_unreachable("Invalid class for expression");
1099
Richard Smithf623c962012-04-17 00:58:00 +00001100#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1101#define STMT_RANGE(Base, First, Last)
1102#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1103#define EXPR(CLASS, PARENT)
1104#define ABSTRACT_STMT(STMT)
1105#include "clang/AST/StmtNodes.inc"
1106 case Expr::NoStmtClass:
1107 llvm_unreachable("Invalid class for expression");
1108 }
1109 llvm_unreachable("Bogus StmtClass");
1110}
1111
Sebastian Redl4915e632009-10-11 09:03:14 +00001112} // end namespace clang