blob: f88ead56f449af575512369f81d7d428f7a2b7fd [file] [log] [blame]
Sebastian Redldced2262009-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Sebastian Redldced2262009-10-11 09:03:14 +000015#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
Douglas Gregor2eef8292010-03-24 07:14:45 +000018#include "clang/AST/TypeLoc.h"
19#include "clang/Lex/Preprocessor.h"
Douglas Gregore13ad832010-02-12 07:32:17 +000020#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/SourceManager.h"
Sebastian Redldced2262009-10-11 09:03:14 +000022#include "llvm/ADT/SmallPtrSet.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000023#include "llvm/ADT/SmallString.h"
Sebastian Redldced2262009-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 Redlc3a3b7b2009-10-14 14:38:54 +000033 else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
34 T = MPTy->getPointeeType();
Sebastian Redldced2262009-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.
41bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
Sebastian Redldced2262009-10-11 09:03:14 +000042
Douglas Gregor0966f352009-12-10 18:13:52 +000043 // This check (and the similar one below) deals with issue 437, that changes
44 // C++ 9.2p2 this way:
45 // Within the class member-specification, the class is regarded as complete
46 // within function bodies, default arguments, exception-specifications, and
47 // constructor ctor-initializers (including such things in nested classes).
48 if (T->isRecordType() && T->getAs<RecordType>()->isBeingDefined())
49 return false;
50
Sebastian Redldced2262009-10-11 09:03:14 +000051 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
52 // an incomplete type.
Sebastian Redl491b84c2009-10-14 14:59:48 +000053 if (RequireCompleteType(Range.getBegin(), T,
Douglas Gregord10099e2012-05-04 16:32:21 +000054 diag::err_incomplete_in_exception_spec,
55 /*direct*/0, Range))
Sebastian Redl491b84c2009-10-14 14:59:48 +000056 return true;
Sebastian Redldced2262009-10-11 09:03:14 +000057
58 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
59 // an incomplete type a pointer or reference to an incomplete type, other
60 // than (cv) void*.
61 int kind;
62 if (const PointerType* IT = T->getAs<PointerType>()) {
63 T = IT->getPointeeType();
64 kind = 1;
65 } else if (const ReferenceType* IT = T->getAs<ReferenceType>()) {
66 T = IT->getPointeeType();
67 kind = 2;
68 } else
69 return false;
70
Douglas Gregor0966f352009-12-10 18:13:52 +000071 // Again as before
72 if (T->isRecordType() && T->getAs<RecordType>()->isBeingDefined())
73 return false;
74
Douglas Gregord10099e2012-05-04 16:32:21 +000075 if (!T->isVoidType() &&
76 RequireCompleteType(Range.getBegin(), T,
77 diag::err_incomplete_in_exception_spec, kind, Range))
Sebastian Redl491b84c2009-10-14 14:59:48 +000078 return true;
Sebastian Redldced2262009-10-11 09:03:14 +000079
80 return false;
81}
82
83/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
84/// to member to a function with an exception specification. This means that
85/// it is invalid to add another level of indirection.
86bool Sema::CheckDistantExceptionSpec(QualType T) {
87 if (const PointerType *PT = T->getAs<PointerType>())
88 T = PT->getPointeeType();
89 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
90 T = PT->getPointeeType();
91 else
92 return false;
93
94 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
95 if (!FnT)
96 return false;
97
98 return FnT->hasExceptionSpec();
99}
100
Richard Smithe6975e92012-04-17 00:58:00 +0000101const FunctionProtoType *
102Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
103 // FIXME: If FD is a special member, we should delay computing its exception
104 // specification until this point.
105 if (FPT->getExceptionSpecType() != EST_Uninstantiated)
106 return FPT;
107
108 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
109 const FunctionProtoType *SourceFPT =
110 SourceDecl->getType()->castAs<FunctionProtoType>();
111
112 if (SourceFPT->getExceptionSpecType() != EST_Uninstantiated)
113 return SourceFPT;
114
115 // Instantiate the exception specification now.
116 InstantiateExceptionSpec(Loc, SourceDecl);
117
118 return SourceDecl->getType()->castAs<FunctionProtoType>();
119}
120
Douglas Gregore13ad832010-02-12 07:32:17 +0000121bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000122 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
123 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000124 bool MissingExceptionSpecification = false;
Douglas Gregore13ad832010-02-12 07:32:17 +0000125 bool MissingEmptyExceptionSpecification = false;
Francois Picheteedd4672011-03-19 23:05:18 +0000126 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikie4e4d0842012-03-11 07:00:24 +0000127 if (getLangOpts().MicrosoftExt)
Francois Pichetcf320c62011-04-22 08:25:24 +0000128 DiagID = diag::warn_mismatched_exception_spec;
Richard Smithe6975e92012-04-17 00:58:00 +0000129
Francois Picheteedd4672011-03-19 23:05:18 +0000130 if (!CheckEquivalentExceptionSpec(PDiag(DiagID),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000131 PDiag(diag::note_previous_declaration),
Douglas Gregore13ad832010-02-12 07:32:17 +0000132 Old->getType()->getAs<FunctionProtoType>(),
133 Old->getLocation(),
134 New->getType()->getAs<FunctionProtoType>(),
135 New->getLocation(),
Douglas Gregor2eef8292010-03-24 07:14:45 +0000136 &MissingExceptionSpecification,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000137 &MissingEmptyExceptionSpecification,
Sebastian Redl99439d42011-03-15 19:52:30 +0000138 /*AllowNoexceptAllMatchWithNoSpec=*/true,
139 IsOperatorNew))
Douglas Gregore13ad832010-02-12 07:32:17 +0000140 return false;
141
142 // The failure was something other than an empty exception
143 // specification; return an error.
Douglas Gregor2eef8292010-03-24 07:14:45 +0000144 if (!MissingExceptionSpecification && !MissingEmptyExceptionSpecification)
Douglas Gregore13ad832010-02-12 07:32:17 +0000145 return true;
146
John McCalle23cf432010-12-14 08:05:40 +0000147 const FunctionProtoType *NewProto
148 = New->getType()->getAs<FunctionProtoType>();
149
Douglas Gregore13ad832010-02-12 07:32:17 +0000150 // The new function declaration is only missing an empty exception
151 // specification "throw()". If the throw() specification came from a
152 // function in a system header that has C linkage, just add an empty
153 // exception specification to the "new" declaration. This is an
154 // egregious workaround for glibc, which adds throw() specifications
155 // to many libc functions as an optimization. Unfortunately, that
156 // optimization isn't permitted by the C++ standard, so we're forced
157 // to work around it here.
John McCalle23cf432010-12-14 08:05:40 +0000158 if (MissingEmptyExceptionSpecification && NewProto &&
Douglas Gregor2eef8292010-03-24 07:14:45 +0000159 (Old->getLocation().isInvalid() ||
160 Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
Douglas Gregore13ad832010-02-12 07:32:17 +0000161 Old->isExternC()) {
John McCalle23cf432010-12-14 08:05:40 +0000162 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +0000163 EPI.ExceptionSpecType = EST_DynamicNone;
Douglas Gregore13ad832010-02-12 07:32:17 +0000164 QualType NewType = Context.getFunctionType(NewProto->getResultType(),
165 NewProto->arg_type_begin(),
166 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +0000167 EPI);
Douglas Gregore13ad832010-02-12 07:32:17 +0000168 New->setType(NewType);
169 return false;
170 }
171
John McCalle23cf432010-12-14 08:05:40 +0000172 if (MissingExceptionSpecification && NewProto) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000173 const FunctionProtoType *OldProto
174 = Old->getType()->getAs<FunctionProtoType>();
175
John McCalle23cf432010-12-14 08:05:40 +0000176 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +0000177 EPI.ExceptionSpecType = OldProto->getExceptionSpecType();
178 if (EPI.ExceptionSpecType == EST_Dynamic) {
179 EPI.NumExceptions = OldProto->getNumExceptions();
180 EPI.Exceptions = OldProto->exception_begin();
181 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
182 // FIXME: We can't just take the expression from the old prototype. It
183 // likely contains references to the old prototype's parameters.
184 }
John McCalle23cf432010-12-14 08:05:40 +0000185
Douglas Gregor2eef8292010-03-24 07:14:45 +0000186 // Update the type of the function with the appropriate exception
187 // specification.
188 QualType NewType = Context.getFunctionType(NewProto->getResultType(),
189 NewProto->arg_type_begin(),
190 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +0000191 EPI);
Douglas Gregor2eef8292010-03-24 07:14:45 +0000192 New->setType(NewType);
193
194 // If exceptions are disabled, suppress the warning about missing
195 // exception specifications for new and delete operators.
David Blaikie4e4d0842012-03-11 07:00:24 +0000196 if (!getLangOpts().CXXExceptions) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000197 switch (New->getDeclName().getCXXOverloadedOperator()) {
198 case OO_New:
199 case OO_Array_New:
200 case OO_Delete:
201 case OO_Array_Delete:
202 if (New->getDeclContext()->isTranslationUnit())
203 return false;
204 break;
205
206 default:
207 break;
208 }
209 }
210
211 // Warn about the lack of exception specification.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000212 SmallString<128> ExceptionSpecString;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000213 llvm::raw_svector_ostream OS(ExceptionSpecString);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000214 switch (OldProto->getExceptionSpecType()) {
215 case EST_DynamicNone:
216 OS << "throw()";
217 break;
218
219 case EST_Dynamic: {
220 OS << "throw(";
221 bool OnFirstException = true;
222 for (FunctionProtoType::exception_iterator E = OldProto->exception_begin(),
223 EEnd = OldProto->exception_end();
224 E != EEnd;
225 ++E) {
226 if (OnFirstException)
227 OnFirstException = false;
228 else
229 OS << ", ";
230
Douglas Gregor8987b232011-09-27 23:30:47 +0000231 OS << E->getAsString(getPrintingPolicy());
Sebastian Redl60618fa2011-03-12 11:50:43 +0000232 }
233 OS << ")";
234 break;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000235 }
Sebastian Redl60618fa2011-03-12 11:50:43 +0000236
237 case EST_BasicNoexcept:
238 OS << "noexcept";
239 break;
240
241 case EST_ComputedNoexcept:
242 OS << "noexcept(";
Douglas Gregor8987b232011-09-27 23:30:47 +0000243 OldProto->getNoexceptExpr()->printPretty(OS, Context, 0,
244 getPrintingPolicy());
Sebastian Redl60618fa2011-03-12 11:50:43 +0000245 OS << ")";
246 break;
247
248 default:
David Blaikieb219cfc2011-09-23 05:06:16 +0000249 llvm_unreachable("This spec type is compatible with none.");
Sebastian Redl60618fa2011-03-12 11:50:43 +0000250 }
Douglas Gregor2eef8292010-03-24 07:14:45 +0000251 OS.flush();
252
Abramo Bagnara796aa442011-03-12 11:17:06 +0000253 SourceLocation FixItLoc;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000254 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
Abramo Bagnara723df242010-12-14 22:11:44 +0000255 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor2eef8292010-03-24 07:14:45 +0000256 if (const FunctionTypeLoc *FTLoc = dyn_cast<FunctionTypeLoc>(&TL))
Abramo Bagnara796aa442011-03-12 11:17:06 +0000257 FixItLoc = PP.getLocForEndOfToken(FTLoc->getLocalRangeEnd());
Douglas Gregor2eef8292010-03-24 07:14:45 +0000258 }
259
Abramo Bagnara796aa442011-03-12 11:17:06 +0000260 if (FixItLoc.isInvalid())
Douglas Gregor2eef8292010-03-24 07:14:45 +0000261 Diag(New->getLocation(), diag::warn_missing_exception_specification)
262 << New << OS.str();
263 else {
264 // FIXME: This will get more complicated with C++0x
265 // late-specified return types.
266 Diag(New->getLocation(), diag::warn_missing_exception_specification)
267 << New << OS.str()
Abramo Bagnara796aa442011-03-12 11:17:06 +0000268 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
Douglas Gregor2eef8292010-03-24 07:14:45 +0000269 }
270
271 if (!Old->getLocation().isInvalid())
272 Diag(Old->getLocation(), diag::note_previous_declaration);
273
274 return false;
275 }
276
Francois Picheteedd4672011-03-19 23:05:18 +0000277 Diag(New->getLocation(), DiagID);
Douglas Gregore13ad832010-02-12 07:32:17 +0000278 Diag(Old->getLocation(), diag::note_previous_declaration);
279 return true;
280}
281
Sebastian Redldced2262009-10-11 09:03:14 +0000282/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
283/// exception specifications. Exception specifications are equivalent if
284/// they allow exactly the same set of exception types. It does not matter how
285/// that is achieved. See C++ [except.spec]p2.
286bool Sema::CheckEquivalentExceptionSpec(
287 const FunctionProtoType *Old, SourceLocation OldLoc,
288 const FunctionProtoType *New, SourceLocation NewLoc) {
Francois Picheteedd4672011-03-19 23:05:18 +0000289 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikie4e4d0842012-03-11 07:00:24 +0000290 if (getLangOpts().MicrosoftExt)
Francois Pichetcf320c62011-04-22 08:25:24 +0000291 DiagID = diag::warn_mismatched_exception_spec;
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000292 return CheckEquivalentExceptionSpec(
Francois Picheteedd4672011-03-19 23:05:18 +0000293 PDiag(DiagID),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000294 PDiag(diag::note_previous_declaration),
Sebastian Redldced2262009-10-11 09:03:14 +0000295 Old, OldLoc, New, NewLoc);
296}
297
Sebastian Redl60618fa2011-03-12 11:50:43 +0000298/// CheckEquivalentExceptionSpec - Check if the two types have compatible
299/// exception specifications. See C++ [except.spec]p3.
300bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000301 const PartialDiagnostic & NoteID,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000302 const FunctionProtoType *Old,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000303 SourceLocation OldLoc,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000304 const FunctionProtoType *New,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000305 SourceLocation NewLoc,
306 bool *MissingExceptionSpecification,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000307 bool*MissingEmptyExceptionSpecification,
Sebastian Redl99439d42011-03-15 19:52:30 +0000308 bool AllowNoexceptAllMatchWithNoSpec,
309 bool IsOperatorNew) {
John McCall811d0be2010-05-28 08:37:35 +0000310 // Just completely ignore this under -fno-exceptions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000311 if (!getLangOpts().CXXExceptions)
John McCall811d0be2010-05-28 08:37:35 +0000312 return false;
313
Douglas Gregor2eef8292010-03-24 07:14:45 +0000314 if (MissingExceptionSpecification)
315 *MissingExceptionSpecification = false;
316
Douglas Gregore13ad832010-02-12 07:32:17 +0000317 if (MissingEmptyExceptionSpecification)
318 *MissingEmptyExceptionSpecification = false;
319
Richard Smithe6975e92012-04-17 00:58:00 +0000320 Old = ResolveExceptionSpec(NewLoc, Old);
321 if (!Old)
322 return false;
323 New = ResolveExceptionSpec(NewLoc, New);
324 if (!New)
325 return false;
326
Sebastian Redl60618fa2011-03-12 11:50:43 +0000327 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
328 // - both are non-throwing, regardless of their form,
329 // - both have the form noexcept(constant-expression) and the constant-
330 // expressions are equivalent,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000331 // - both are dynamic-exception-specifications that have the same set of
332 // adjusted types.
333 //
334 // C++0x [except.spec]p12: An exception-specifcation is non-throwing if it is
335 // of the form throw(), noexcept, or noexcept(constant-expression) where the
336 // constant-expression yields true.
337 //
Sebastian Redl60618fa2011-03-12 11:50:43 +0000338 // C++0x [except.spec]p4: If any declaration of a function has an exception-
339 // specifier that is not a noexcept-specification allowing all exceptions,
340 // all declarations [...] of that function shall have a compatible
341 // exception-specification.
342 //
343 // That last point basically means that noexcept(false) matches no spec.
344 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
345
346 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
347 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
348
Richard Smith7a614d82011-06-11 17:19:42 +0000349 assert(OldEST != EST_Delayed && NewEST != EST_Delayed &&
Richard Smithe6975e92012-04-17 00:58:00 +0000350 OldEST != EST_Uninstantiated && NewEST != EST_Uninstantiated &&
Richard Smith7a614d82011-06-11 17:19:42 +0000351 "Shouldn't see unknown exception specifications here");
352
Sebastian Redl60618fa2011-03-12 11:50:43 +0000353 // Shortcut the case where both have no spec.
354 if (OldEST == EST_None && NewEST == EST_None)
355 return false;
356
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000357 FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
358 FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000359 if (OldNR == FunctionProtoType::NR_BadNoexcept ||
360 NewNR == FunctionProtoType::NR_BadNoexcept)
361 return false;
362
363 // Dependent noexcept specifiers are compatible with each other, but nothing
364 // else.
365 // One noexcept is compatible with another if the argument is the same
366 if (OldNR == NewNR &&
367 OldNR != FunctionProtoType::NR_NoNoexcept &&
368 NewNR != FunctionProtoType::NR_NoNoexcept)
369 return false;
370 if (OldNR != NewNR &&
371 OldNR != FunctionProtoType::NR_NoNoexcept &&
372 NewNR != FunctionProtoType::NR_NoNoexcept) {
373 Diag(NewLoc, DiagID);
374 if (NoteID.getDiagID() != 0)
375 Diag(OldLoc, NoteID);
376 return true;
Douglas Gregor5b6f7692010-08-30 15:04:51 +0000377 }
378
Sebastian Redl60618fa2011-03-12 11:50:43 +0000379 // The MS extension throw(...) is compatible with itself.
380 if (OldEST == EST_MSAny && NewEST == EST_MSAny)
Sebastian Redldced2262009-10-11 09:03:14 +0000381 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +0000382
383 // It's also compatible with no spec.
384 if ((OldEST == EST_None && NewEST == EST_MSAny) ||
385 (OldEST == EST_MSAny && NewEST == EST_None))
386 return false;
387
388 // It's also compatible with noexcept(false).
389 if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
390 return false;
391 if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
392 return false;
393
394 // As described above, noexcept(false) matches no spec only for functions.
395 if (AllowNoexceptAllMatchWithNoSpec) {
396 if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
397 return false;
398 if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
399 return false;
400 }
401
402 // Any non-throwing specifications are compatible.
403 bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
404 OldEST == EST_DynamicNone;
405 bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
406 NewEST == EST_DynamicNone;
407 if (OldNonThrowing && NewNonThrowing)
408 return false;
409
Sebastian Redl99439d42011-03-15 19:52:30 +0000410 // As a special compatibility feature, under C++0x we accept no spec and
411 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
412 // This is because the implicit declaration changed, but old code would break.
David Blaikie4e4d0842012-03-11 07:00:24 +0000413 if (getLangOpts().CPlusPlus0x && IsOperatorNew) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000414 const FunctionProtoType *WithExceptions = 0;
415 if (OldEST == EST_None && NewEST == EST_Dynamic)
416 WithExceptions = New;
417 else if (OldEST == EST_Dynamic && NewEST == EST_None)
418 WithExceptions = Old;
419 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
420 // One has no spec, the other throw(something). If that something is
421 // std::bad_alloc, all conditions are met.
422 QualType Exception = *WithExceptions->exception_begin();
423 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
424 IdentifierInfo* Name = ExRecord->getIdentifier();
425 if (Name && Name->getName() == "bad_alloc") {
426 // It's called bad_alloc, but is it in std?
427 DeclContext* DC = ExRecord->getDeclContext();
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000428 DC = DC->getEnclosingNamespaceContext();
429 if (NamespaceDecl* NS = dyn_cast<NamespaceDecl>(DC)) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000430 IdentifierInfo* NSName = NS->getIdentifier();
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000431 DC = DC->getParent();
Sebastian Redl99439d42011-03-15 19:52:30 +0000432 if (NSName && NSName->getName() == "std" &&
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000433 DC->getEnclosingNamespaceContext()->isTranslationUnit()) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000434 return false;
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000435 }
Sebastian Redl99439d42011-03-15 19:52:30 +0000436 }
437 }
438 }
439 }
440 }
441
Sebastian Redl60618fa2011-03-12 11:50:43 +0000442 // At this point, the only remaining valid case is two matching dynamic
443 // specifications. We return here unless both specifications are dynamic.
444 if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000445 if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
Douglas Gregore13ad832010-02-12 07:32:17 +0000446 !New->hasExceptionSpec()) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000447 // The old type has an exception specification of some sort, but
448 // the new type does not.
449 *MissingExceptionSpecification = true;
450
Sebastian Redl60618fa2011-03-12 11:50:43 +0000451 if (MissingEmptyExceptionSpecification && OldNonThrowing) {
452 // The old type has a throw() or noexcept(true) exception specification
453 // and the new type has no exception specification, and the caller asked
Douglas Gregor2eef8292010-03-24 07:14:45 +0000454 // to handle this itself.
455 *MissingEmptyExceptionSpecification = true;
456 }
457
Douglas Gregore13ad832010-02-12 07:32:17 +0000458 return true;
459 }
460
Sebastian Redldced2262009-10-11 09:03:14 +0000461 Diag(NewLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000462 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000463 Diag(OldLoc, NoteID);
464 return true;
465 }
466
Sebastian Redl60618fa2011-03-12 11:50:43 +0000467 assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
468 "Exception compatibility logic error: non-dynamic spec slipped through.");
469
Sebastian Redldced2262009-10-11 09:03:14 +0000470 bool Success = true;
Sebastian Redl60618fa2011-03-12 11:50:43 +0000471 // Both have a dynamic exception spec. Collect the first set, then compare
Sebastian Redldced2262009-10-11 09:03:14 +0000472 // to the second.
Sebastian Redl1219d152009-10-14 15:06:25 +0000473 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
Sebastian Redldced2262009-10-11 09:03:14 +0000474 for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
475 E = Old->exception_end(); I != E; ++I)
Sebastian Redl1219d152009-10-14 15:06:25 +0000476 OldTypes.insert(Context.getCanonicalType(*I).getUnqualifiedType());
Sebastian Redldced2262009-10-11 09:03:14 +0000477
478 for (FunctionProtoType::exception_iterator I = New->exception_begin(),
Sebastian Redl5db4d902009-10-11 09:11:23 +0000479 E = New->exception_end(); I != E && Success; ++I) {
Sebastian Redl1219d152009-10-14 15:06:25 +0000480 CanQualType TypePtr = Context.getCanonicalType(*I).getUnqualifiedType();
Sebastian Redl5db4d902009-10-11 09:11:23 +0000481 if(OldTypes.count(TypePtr))
482 NewTypes.insert(TypePtr);
483 else
484 Success = false;
485 }
Sebastian Redldced2262009-10-11 09:03:14 +0000486
Sebastian Redl5db4d902009-10-11 09:11:23 +0000487 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redldced2262009-10-11 09:03:14 +0000488
489 if (Success) {
490 return false;
491 }
492 Diag(NewLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000493 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000494 Diag(OldLoc, NoteID);
495 return true;
496}
497
498/// CheckExceptionSpecSubset - Check whether the second function type's
499/// exception specification is a subset (or equivalent) of the first function
500/// type. This is used by override and pointer assignment checks.
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000501bool Sema::CheckExceptionSpecSubset(
502 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000503 const FunctionProtoType *Superset, SourceLocation SuperLoc,
504 const FunctionProtoType *Subset, SourceLocation SubLoc) {
John McCall811d0be2010-05-28 08:37:35 +0000505
506 // Just auto-succeed under -fno-exceptions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000507 if (!getLangOpts().CXXExceptions)
John McCall811d0be2010-05-28 08:37:35 +0000508 return false;
509
Sebastian Redldced2262009-10-11 09:03:14 +0000510 // FIXME: As usual, we could be more specific in our error messages, but
511 // that better waits until we've got types with source locations.
512
513 if (!SubLoc.isValid())
514 SubLoc = SuperLoc;
515
Richard Smithe6975e92012-04-17 00:58:00 +0000516 // Resolve the exception specifications, if needed.
517 Superset = ResolveExceptionSpec(SuperLoc, Superset);
518 if (!Superset)
519 return false;
520 Subset = ResolveExceptionSpec(SubLoc, Subset);
521 if (!Subset)
522 return false;
523
Sebastian Redl60618fa2011-03-12 11:50:43 +0000524 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
525
Sebastian Redldced2262009-10-11 09:03:14 +0000526 // If superset contains everything, we're done.
Sebastian Redl60618fa2011-03-12 11:50:43 +0000527 if (SuperEST == EST_None || SuperEST == EST_MSAny)
Sebastian Redldced2262009-10-11 09:03:14 +0000528 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
529
Sebastian Redl60618fa2011-03-12 11:50:43 +0000530 // If there are dependent noexcept specs, assume everything is fine. Unlike
531 // with the equivalency check, this is safe in this case, because we don't
532 // want to merge declarations. Checks after instantiation will catch any
533 // omissions we make here.
534 // We also shortcut checking if a noexcept expression was bad.
535
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000536 FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000537 if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
538 SuperNR == FunctionProtoType::NR_Dependent)
539 return false;
540
541 // Another case of the superset containing everything.
542 if (SuperNR == FunctionProtoType::NR_Throw)
543 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
544
545 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
546
Richard Smith7a614d82011-06-11 17:19:42 +0000547 assert(SuperEST != EST_Delayed && SubEST != EST_Delayed &&
Richard Smithe6975e92012-04-17 00:58:00 +0000548 SuperEST != EST_Uninstantiated && SubEST != EST_Uninstantiated &&
Richard Smith7a614d82011-06-11 17:19:42 +0000549 "Shouldn't see unknown exception specifications here");
550
Sebastian Redldced2262009-10-11 09:03:14 +0000551 // It does not. If the subset contains everything, we've failed.
Sebastian Redl60618fa2011-03-12 11:50:43 +0000552 if (SubEST == EST_None || SubEST == EST_MSAny) {
Sebastian Redldced2262009-10-11 09:03:14 +0000553 Diag(SubLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000554 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000555 Diag(SuperLoc, NoteID);
556 return true;
557 }
558
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000559 FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000560 if (SubNR == FunctionProtoType::NR_BadNoexcept ||
561 SubNR == FunctionProtoType::NR_Dependent)
562 return false;
563
564 // Another case of the subset containing everything.
565 if (SubNR == FunctionProtoType::NR_Throw) {
566 Diag(SubLoc, DiagID);
567 if (NoteID.getDiagID() != 0)
568 Diag(SuperLoc, NoteID);
569 return true;
570 }
571
572 // If the subset contains nothing, we're done.
573 if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
574 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
575
576 // Otherwise, if the superset contains nothing, we've failed.
577 if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
578 Diag(SubLoc, DiagID);
579 if (NoteID.getDiagID() != 0)
580 Diag(SuperLoc, NoteID);
581 return true;
582 }
583
584 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
585 "Exception spec subset: non-dynamic case slipped through.");
586
587 // Neither contains everything or nothing. Do a proper comparison.
Sebastian Redldced2262009-10-11 09:03:14 +0000588 for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
589 SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
590 // Take one type from the subset.
591 QualType CanonicalSubT = Context.getCanonicalType(*SubI);
Sebastian Redlc3a3b7b2009-10-14 14:38:54 +0000592 // Unwrap pointers and references so that we can do checks within a class
593 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
594 // conversions on the pointee.
Sebastian Redldced2262009-10-11 09:03:14 +0000595 bool SubIsPointer = false;
596 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
597 CanonicalSubT = RefTy->getPointeeType();
598 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
599 CanonicalSubT = PtrTy->getPointeeType();
600 SubIsPointer = true;
601 }
602 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregora4923eb2009-11-16 21:35:15 +0000603 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redldced2262009-10-11 09:03:14 +0000604
605 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
606 /*DetectVirtual=*/false);
607
608 bool Contained = false;
609 // Make sure it's in the superset.
610 for (FunctionProtoType::exception_iterator SuperI =
611 Superset->exception_begin(), SuperE = Superset->exception_end();
612 SuperI != SuperE; ++SuperI) {
613 QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
614 // SubT must be SuperT or derived from it, or pointer or reference to
615 // such types.
616 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
617 CanonicalSuperT = RefTy->getPointeeType();
618 if (SubIsPointer) {
619 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
620 CanonicalSuperT = PtrTy->getPointeeType();
621 else {
622 continue;
623 }
624 }
Douglas Gregora4923eb2009-11-16 21:35:15 +0000625 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redldced2262009-10-11 09:03:14 +0000626 // If the types are the same, move on to the next type in the subset.
627 if (CanonicalSubT == CanonicalSuperT) {
628 Contained = true;
629 break;
630 }
631
632 // Otherwise we need to check the inheritance.
633 if (!SubIsClass || !CanonicalSuperT->isRecordType())
634 continue;
635
636 Paths.clear();
637 if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
638 continue;
639
Douglas Gregore0d5fe22010-05-21 20:29:55 +0000640 if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
Sebastian Redldced2262009-10-11 09:03:14 +0000641 continue;
642
John McCall6b2accb2010-02-10 09:31:12 +0000643 // Do this check from a context without privileges.
John McCall58e6f342010-03-16 05:22:47 +0000644 switch (CheckBaseClassAccess(SourceLocation(),
John McCall6b2accb2010-02-10 09:31:12 +0000645 CanonicalSuperT, CanonicalSubT,
646 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +0000647 /*Diagnostic*/ 0,
John McCall6b2accb2010-02-10 09:31:12 +0000648 /*ForceCheck*/ true,
John McCall58e6f342010-03-16 05:22:47 +0000649 /*ForceUnprivileged*/ true)) {
John McCall6b2accb2010-02-10 09:31:12 +0000650 case AR_accessible: break;
651 case AR_inaccessible: continue;
652 case AR_dependent:
653 llvm_unreachable("access check dependent for unprivileged context");
John McCall6b2accb2010-02-10 09:31:12 +0000654 case AR_delayed:
655 llvm_unreachable("access check delayed in non-declaration");
John McCall6b2accb2010-02-10 09:31:12 +0000656 }
Sebastian Redldced2262009-10-11 09:03:14 +0000657
658 Contained = true;
659 break;
660 }
661 if (!Contained) {
662 Diag(SubLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000663 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000664 Diag(SuperLoc, NoteID);
665 return true;
666 }
667 }
668 // We've run half the gauntlet.
669 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
670}
671
672static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000673 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000674 QualType Target, SourceLocation TargetLoc,
675 QualType Source, SourceLocation SourceLoc)
676{
677 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
678 if (!TFunc)
679 return false;
680 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
681 if (!SFunc)
682 return false;
683
684 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
685 SFunc, SourceLoc);
686}
687
688/// CheckParamExceptionSpec - Check if the parameter and return types of the
689/// two functions have equivalent exception specs. This is part of the
690/// assignment and override compatibility check. We do not check the parameters
691/// of parameter function pointers recursively, as no sane programmer would
692/// even be able to write such a function type.
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000693bool Sema::CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000694 const FunctionProtoType *Target, SourceLocation TargetLoc,
695 const FunctionProtoType *Source, SourceLocation SourceLoc)
696{
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000697 if (CheckSpecForTypesEquivalent(*this,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000698 PDiag(diag::err_deep_exception_specs_differ) << 0,
699 PDiag(),
Sebastian Redldced2262009-10-11 09:03:14 +0000700 Target->getResultType(), TargetLoc,
701 Source->getResultType(), SourceLoc))
702 return true;
703
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000704 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redldced2262009-10-11 09:03:14 +0000705 // compatible.
706 assert(Target->getNumArgs() == Source->getNumArgs() &&
707 "Functions have different argument counts.");
708 for (unsigned i = 0, E = Target->getNumArgs(); i != E; ++i) {
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000709 if (CheckSpecForTypesEquivalent(*this,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000710 PDiag(diag::err_deep_exception_specs_differ) << 1,
711 PDiag(),
Sebastian Redldced2262009-10-11 09:03:14 +0000712 Target->getArgType(i), TargetLoc,
713 Source->getArgType(i), SourceLoc))
714 return true;
715 }
716 return false;
717}
718
719bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
720{
721 // First we check for applicability.
722 // Target type must be a function, function pointer or function reference.
723 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
724 if (!ToFunc)
725 return false;
726
727 // SourceType must be a function or function pointer.
728 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
729 if (!FromFunc)
730 return false;
731
732 // Now we've got the correct types on both sides, check their compatibility.
733 // This means that the source of the conversion can only throw a subset of
734 // the exceptions of the target, and any exception specs on arguments or
735 // return types must be equivalent.
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000736 return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
737 PDiag(), ToFunc,
738 From->getSourceRange().getBegin(),
Sebastian Redldced2262009-10-11 09:03:14 +0000739 FromFunc, SourceLocation());
740}
741
742bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
743 const CXXMethodDecl *Old) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000744 if (getLangOpts().CPlusPlus0x && isa<CXXDestructorDecl>(New)) {
Sebastian Redla0448262011-05-20 05:57:18 +0000745 // Don't check uninstantiated template destructors at all. We can only
746 // synthesize correct specs after the template is instantiated.
747 if (New->getParent()->isDependentType())
748 return false;
749 if (New->getParent()->isBeingDefined()) {
750 // The destructor might be updated once the definition is finished. So
751 // remember it and check later.
752 DelayedDestructorExceptionSpecChecks.push_back(std::make_pair(
753 cast<CXXDestructorDecl>(New), cast<CXXDestructorDecl>(Old)));
754 return false;
755 }
Sebastian Redl0ee33912011-05-19 05:13:44 +0000756 }
Francois Pichet0f161592011-05-24 02:11:43 +0000757 unsigned DiagID = diag::err_override_exception_spec;
David Blaikie4e4d0842012-03-11 07:00:24 +0000758 if (getLangOpts().MicrosoftExt)
Francois Pichet0f161592011-05-24 02:11:43 +0000759 DiagID = diag::warn_override_exception_spec;
760 return CheckExceptionSpecSubset(PDiag(DiagID),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000761 PDiag(diag::note_overridden_virtual_function),
Sebastian Redldced2262009-10-11 09:03:14 +0000762 Old->getType()->getAs<FunctionProtoType>(),
763 Old->getLocation(),
764 New->getType()->getAs<FunctionProtoType>(),
765 New->getLocation());
766}
767
Richard Smithe6975e92012-04-17 00:58:00 +0000768static CanThrowResult canSubExprsThrow(Sema &S, const Expr *CE) {
769 Expr *E = const_cast<Expr*>(CE);
770 CanThrowResult R = CT_Cannot;
771 for (Expr::child_range I = E->children(); I && R != CT_Can; ++I)
772 R = mergeCanThrow(R, S.canThrow(cast<Expr>(*I)));
773 return R;
774}
775
776static CanThrowResult canCalleeThrow(Sema &S, const Expr *E,
777 const Decl *D,
778 bool NullThrows = true) {
779 if (!D)
780 return NullThrows ? CT_Can : CT_Cannot;
781
782 // See if we can get a function type from the decl somehow.
783 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
784 if (!VD) // If we have no clue what we're calling, assume the worst.
785 return CT_Can;
786
787 // As an extension, we assume that __attribute__((nothrow)) functions don't
788 // throw.
789 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
790 return CT_Cannot;
791
792 QualType T = VD->getType();
793 const FunctionProtoType *FT;
794 if ((FT = T->getAs<FunctionProtoType>())) {
795 } else if (const PointerType *PT = T->getAs<PointerType>())
796 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
797 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
798 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
799 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
800 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
801 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
802 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
803
804 if (!FT)
805 return CT_Can;
806
807 FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
808 if (!FT)
809 return CT_Can;
810
811 if (FT->getExceptionSpecType() == EST_Delayed) {
812 // FIXME: Try to resolve a delayed exception spec in ResolveExceptionSpec.
813 assert(isa<CXXConstructorDecl>(D) &&
814 "only constructor exception specs can be unknown");
815 S.Diag(E->getLocStart(), diag::err_exception_spec_unknown)
816 << E->getSourceRange();
817 return CT_Can;
818 }
819
820 return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
821}
822
823static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
824 if (DC->isTypeDependent())
825 return CT_Dependent;
826
827 if (!DC->getTypeAsWritten()->isReferenceType())
828 return CT_Cannot;
829
830 if (DC->getSubExpr()->isTypeDependent())
831 return CT_Dependent;
832
833 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
834}
835
836static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
837 if (DC->isTypeOperand())
838 return CT_Cannot;
839
840 Expr *Op = DC->getExprOperand();
841 if (Op->isTypeDependent())
842 return CT_Dependent;
843
844 const RecordType *RT = Op->getType()->getAs<RecordType>();
845 if (!RT)
846 return CT_Cannot;
847
848 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
849 return CT_Cannot;
850
851 if (Op->Classify(S.Context).isPRValue())
852 return CT_Cannot;
853
854 return CT_Can;
855}
856
857CanThrowResult Sema::canThrow(const Expr *E) {
858 // C++ [expr.unary.noexcept]p3:
859 // [Can throw] if in a potentially-evaluated context the expression would
860 // contain:
861 switch (E->getStmtClass()) {
862 case Expr::CXXThrowExprClass:
863 // - a potentially evaluated throw-expression
864 return CT_Can;
865
866 case Expr::CXXDynamicCastExprClass: {
867 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
868 // where T is a reference type, that requires a run-time check
869 CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
870 if (CT == CT_Can)
871 return CT;
872 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
873 }
874
875 case Expr::CXXTypeidExprClass:
876 // - a potentially evaluated typeid expression applied to a glvalue
877 // expression whose type is a polymorphic class type
878 return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
879
880 // - a potentially evaluated call to a function, member function, function
881 // pointer, or member function pointer that does not have a non-throwing
882 // exception-specification
883 case Expr::CallExprClass:
884 case Expr::CXXMemberCallExprClass:
885 case Expr::CXXOperatorCallExprClass:
886 case Expr::UserDefinedLiteralClass: {
887 const CallExpr *CE = cast<CallExpr>(E);
888 CanThrowResult CT;
889 if (E->isTypeDependent())
890 CT = CT_Dependent;
891 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
892 CT = CT_Cannot;
893 else
894 CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
895 if (CT == CT_Can)
896 return CT;
897 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
898 }
899
900 case Expr::CXXConstructExprClass:
901 case Expr::CXXTemporaryObjectExprClass: {
902 CanThrowResult CT = canCalleeThrow(*this, E,
903 cast<CXXConstructExpr>(E)->getConstructor());
904 if (CT == CT_Can)
905 return CT;
906 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
907 }
908
909 case Expr::LambdaExprClass: {
910 const LambdaExpr *Lambda = cast<LambdaExpr>(E);
911 CanThrowResult CT = CT_Cannot;
912 for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
913 CapEnd = Lambda->capture_init_end();
914 Cap != CapEnd; ++Cap)
915 CT = mergeCanThrow(CT, canThrow(*Cap));
916 return CT;
917 }
918
919 case Expr::CXXNewExprClass: {
920 CanThrowResult CT;
921 if (E->isTypeDependent())
922 CT = CT_Dependent;
923 else
924 CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
925 if (CT == CT_Can)
926 return CT;
927 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
928 }
929
930 case Expr::CXXDeleteExprClass: {
931 CanThrowResult CT;
932 QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
933 if (DTy.isNull() || DTy->isDependentType()) {
934 CT = CT_Dependent;
935 } else {
936 CT = canCalleeThrow(*this, E,
937 cast<CXXDeleteExpr>(E)->getOperatorDelete());
938 if (const RecordType *RT = DTy->getAs<RecordType>()) {
939 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
940 CT = mergeCanThrow(CT, canCalleeThrow(*this, E, RD->getDestructor()));
941 }
942 if (CT == CT_Can)
943 return CT;
944 }
945 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
946 }
947
948 case Expr::CXXBindTemporaryExprClass: {
949 // The bound temporary has to be destroyed again, which might throw.
950 CanThrowResult CT = canCalleeThrow(*this, E,
951 cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
952 if (CT == CT_Can)
953 return CT;
954 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
955 }
956
957 // ObjC message sends are like function calls, but never have exception
958 // specs.
959 case Expr::ObjCMessageExprClass:
960 case Expr::ObjCPropertyRefExprClass:
961 case Expr::ObjCSubscriptRefExprClass:
962 return CT_Can;
963
964 // All the ObjC literals that are implemented as calls are
965 // potentially throwing unless we decide to close off that
966 // possibility.
967 case Expr::ObjCArrayLiteralClass:
968 case Expr::ObjCDictionaryLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +0000969 case Expr::ObjCBoxedExprClass:
Richard Smithe6975e92012-04-17 00:58:00 +0000970 return CT_Can;
971
972 // Many other things have subexpressions, so we have to test those.
973 // Some are simple:
974 case Expr::ConditionalOperatorClass:
975 case Expr::CompoundLiteralExprClass:
976 case Expr::CXXConstCastExprClass:
977 case Expr::CXXDefaultArgExprClass:
978 case Expr::CXXReinterpretCastExprClass:
979 case Expr::DesignatedInitExprClass:
980 case Expr::ExprWithCleanupsClass:
981 case Expr::ExtVectorElementExprClass:
982 case Expr::InitListExprClass:
983 case Expr::MemberExprClass:
984 case Expr::ObjCIsaExprClass:
985 case Expr::ObjCIvarRefExprClass:
986 case Expr::ParenExprClass:
987 case Expr::ParenListExprClass:
988 case Expr::ShuffleVectorExprClass:
989 case Expr::VAArgExprClass:
990 return canSubExprsThrow(*this, E);
991
992 // Some might be dependent for other reasons.
993 case Expr::ArraySubscriptExprClass:
994 case Expr::BinaryOperatorClass:
995 case Expr::CompoundAssignOperatorClass:
996 case Expr::CStyleCastExprClass:
997 case Expr::CXXStaticCastExprClass:
998 case Expr::CXXFunctionalCastExprClass:
999 case Expr::ImplicitCastExprClass:
1000 case Expr::MaterializeTemporaryExprClass:
1001 case Expr::UnaryOperatorClass: {
1002 CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1003 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1004 }
1005
1006 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1007 case Expr::StmtExprClass:
1008 return CT_Can;
1009
1010 case Expr::ChooseExprClass:
1011 if (E->isTypeDependent() || E->isValueDependent())
1012 return CT_Dependent;
1013 return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr(Context));
1014
1015 case Expr::GenericSelectionExprClass:
1016 if (cast<GenericSelectionExpr>(E)->isResultDependent())
1017 return CT_Dependent;
1018 return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1019
1020 // Some expressions are always dependent.
1021 case Expr::CXXDependentScopeMemberExprClass:
1022 case Expr::CXXUnresolvedConstructExprClass:
1023 case Expr::DependentScopeDeclRefExprClass:
1024 return CT_Dependent;
1025
1026 case Expr::AsTypeExprClass:
1027 case Expr::BinaryConditionalOperatorClass:
1028 case Expr::BlockExprClass:
1029 case Expr::CUDAKernelCallExprClass:
1030 case Expr::DeclRefExprClass:
1031 case Expr::ObjCBridgedCastExprClass:
1032 case Expr::ObjCIndirectCopyRestoreExprClass:
1033 case Expr::ObjCProtocolExprClass:
1034 case Expr::ObjCSelectorExprClass:
1035 case Expr::OffsetOfExprClass:
1036 case Expr::PackExpansionExprClass:
1037 case Expr::PseudoObjectExprClass:
1038 case Expr::SubstNonTypeTemplateParmExprClass:
1039 case Expr::SubstNonTypeTemplateParmPackExprClass:
1040 case Expr::UnaryExprOrTypeTraitExprClass:
1041 case Expr::UnresolvedLookupExprClass:
1042 case Expr::UnresolvedMemberExprClass:
1043 // FIXME: Can any of the above throw? If so, when?
1044 return CT_Cannot;
1045
1046 case Expr::AddrLabelExprClass:
1047 case Expr::ArrayTypeTraitExprClass:
1048 case Expr::AtomicExprClass:
1049 case Expr::BinaryTypeTraitExprClass:
1050 case Expr::TypeTraitExprClass:
1051 case Expr::CXXBoolLiteralExprClass:
1052 case Expr::CXXNoexceptExprClass:
1053 case Expr::CXXNullPtrLiteralExprClass:
1054 case Expr::CXXPseudoDestructorExprClass:
1055 case Expr::CXXScalarValueInitExprClass:
1056 case Expr::CXXThisExprClass:
1057 case Expr::CXXUuidofExprClass:
1058 case Expr::CharacterLiteralClass:
1059 case Expr::ExpressionTraitExprClass:
1060 case Expr::FloatingLiteralClass:
1061 case Expr::GNUNullExprClass:
1062 case Expr::ImaginaryLiteralClass:
1063 case Expr::ImplicitValueInitExprClass:
1064 case Expr::IntegerLiteralClass:
1065 case Expr::ObjCEncodeExprClass:
1066 case Expr::ObjCStringLiteralClass:
1067 case Expr::ObjCBoolLiteralExprClass:
1068 case Expr::OpaqueValueExprClass:
1069 case Expr::PredefinedExprClass:
1070 case Expr::SizeOfPackExprClass:
1071 case Expr::StringLiteralClass:
1072 case Expr::UnaryTypeTraitExprClass:
1073 // These expressions can never throw.
1074 return CT_Cannot;
1075
1076#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1077#define STMT_RANGE(Base, First, Last)
1078#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1079#define EXPR(CLASS, PARENT)
1080#define ABSTRACT_STMT(STMT)
1081#include "clang/AST/StmtNodes.inc"
1082 case Expr::NoStmtClass:
1083 llvm_unreachable("Invalid class for expression");
1084 }
1085 llvm_unreachable("Bogus StmtClass");
1086}
1087
Sebastian Redldced2262009-10-11 09:03:14 +00001088} // end namespace clang