blob: 38b9cebb618658474d8d86b0a1f303b97e6ac1e0 [file] [log] [blame]
Sebastian Redl4915e632009-10-11 09:03:14 +00001//===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sebastian Redl4915e632009-10-11 09:03:14 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ exception specification testing.
10//
11//===----------------------------------------------------------------------===//
12
John McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Richard Smith564417a2014-03-20 21:47:22 +000014#include "clang/AST/ASTMutationListener.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"
Richard Smithfbf60b72019-12-13 14:10:13 -080018#include "clang/AST/StmtObjC.h"
Douglas Gregord6bc5e62010-03-24 07:14:45 +000019#include "clang/AST/TypeLoc.h"
Douglas Gregorf40863c2010-02-12 07:32:17 +000020#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/SourceManager.h"
Sebastian Redl4915e632009-10-11 09:03:14 +000022#include "llvm/ADT/SmallPtrSet.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000023#include "llvm/ADT/SmallString.h"
Sebastian Redl4915e632009-10-11 09:03:14 +000024
25namespace clang {
26
27static const FunctionProtoType *GetUnderlyingFunction(QualType T)
28{
29 if (const PointerType *PtrTy = T->getAs<PointerType>())
30 T = PtrTy->getPointeeType();
31 else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
32 T = RefTy->getPointeeType();
Sebastian Redl075b21d2009-10-14 14:38:54 +000033 else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
34 T = MPTy->getPointeeType();
Sebastian Redl4915e632009-10-11 09:03:14 +000035 return T->getAs<FunctionProtoType>();
36}
37
Richard Smith6403e932014-11-14 00:37:55 +000038/// HACK: libstdc++ has a bug where it shadows std::swap with a member
39/// swap function then tries to call std::swap unqualified from the exception
40/// specification of that function. This function detects whether we're in
41/// such a case and turns off delay-parsing of exception specifications.
42bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {
43 auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
44
45 // All the problem cases are member functions named "swap" within class
Richard Smith62895462016-10-19 23:47:37 +000046 // templates declared directly within namespace std or std::__debug or
47 // std::__profile.
48 if (!RD || !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
Richard Smith6403e932014-11-14 00:37:55 +000049 !D.getIdentifier() || !D.getIdentifier()->isStr("swap"))
50 return false;
51
Richard Smith62895462016-10-19 23:47:37 +000052 auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext());
53 if (!ND)
54 return false;
55
56 bool IsInStd = ND->isStdNamespace();
57 if (!IsInStd) {
58 // This isn't a direct member of namespace std, but it might still be
59 // libstdc++'s std::__debug::array or std::__profile::array.
60 IdentifierInfo *II = ND->getIdentifier();
61 if (!II || !(II->isStr("__debug") || II->isStr("__profile")) ||
62 !ND->isInStdNamespace())
63 return false;
64 }
65
Richard Smith6403e932014-11-14 00:37:55 +000066 // Only apply this hack within a system header.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000067 if (!Context.getSourceManager().isInSystemHeader(D.getBeginLoc()))
Richard Smith6403e932014-11-14 00:37:55 +000068 return false;
69
70 return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
71 .Case("array", true)
Richard Smith62895462016-10-19 23:47:37 +000072 .Case("pair", IsInStd)
73 .Case("priority_queue", IsInStd)
74 .Case("stack", IsInStd)
75 .Case("queue", IsInStd)
Richard Smith6403e932014-11-14 00:37:55 +000076 .Default(false);
77}
78
Richard Smitheaf11ad2018-05-03 03:58:32 +000079ExprResult Sema::ActOnNoexceptSpec(SourceLocation NoexceptLoc,
80 Expr *NoexceptExpr,
81 ExceptionSpecificationType &EST) {
82 // FIXME: This is bogus, a noexcept expression is not a condition.
83 ExprResult Converted = CheckBooleanCondition(NoexceptLoc, NoexceptExpr);
84 if (Converted.isInvalid())
85 return Converted;
86
87 if (Converted.get()->isValueDependent()) {
88 EST = EST_DependentNoexcept;
89 return Converted;
90 }
91
92 llvm::APSInt Result;
93 Converted = VerifyIntegerConstantExpression(
94 Converted.get(), &Result,
95 diag::err_noexcept_needs_constant_expression,
96 /*AllowFold*/ false);
97 if (!Converted.isInvalid())
98 EST = !Result ? EST_NoexceptFalse : EST_NoexceptTrue;
99 return Converted;
100}
101
Sebastian Redl4915e632009-10-11 09:03:14 +0000102/// CheckSpecifiedExceptionType - Check if the given type is valid in an
103/// exception specification. Incomplete types, or pointers to incomplete types
104/// other than void are not allowed.
Richard Smith8606d752012-11-28 22:33:28 +0000105///
106/// \param[in,out] T The exception type. This will be decayed to a pointer type
107/// when the input is an array or a function type.
Craig Toppere335f252015-10-04 04:53:55 +0000108bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {
Richard Smitha118c6a2012-11-28 22:52:42 +0000109 // C++11 [except.spec]p2:
110 // A type cv T, "array of T", or "function returning T" denoted
Richard Smith8606d752012-11-28 22:33:28 +0000111 // in an exception-specification is adjusted to type T, "pointer to T", or
112 // "pointer to function returning T", respectively.
Richard Smitha118c6a2012-11-28 22:52:42 +0000113 //
114 // We also apply this rule in C++98.
Richard Smith8606d752012-11-28 22:33:28 +0000115 if (T->isArrayType())
116 T = Context.getArrayDecayedType(T);
117 else if (T->isFunctionType())
118 T = Context.getPointerType(T);
Sebastian Redl4915e632009-10-11 09:03:14 +0000119
Richard Smitha118c6a2012-11-28 22:52:42 +0000120 int Kind = 0;
Richard Smith8606d752012-11-28 22:33:28 +0000121 QualType PointeeT = T;
Richard Smitha118c6a2012-11-28 22:52:42 +0000122 if (const PointerType *PT = T->getAs<PointerType>()) {
123 PointeeT = PT->getPointeeType();
124 Kind = 1;
Sebastian Redl4915e632009-10-11 09:03:14 +0000125
Richard Smitha118c6a2012-11-28 22:52:42 +0000126 // cv void* is explicitly permitted, despite being a pointer to an
127 // incomplete type.
128 if (PointeeT->isVoidType())
129 return false;
130 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
131 PointeeT = RT->getPointeeType();
132 Kind = 2;
Richard Smith8606d752012-11-28 22:33:28 +0000133
Richard Smitha118c6a2012-11-28 22:52:42 +0000134 if (RT->isRValueReferenceType()) {
135 // C++11 [except.spec]p2:
136 // A type denoted in an exception-specification shall not denote [...]
137 // an rvalue reference type.
138 Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
139 << T << Range;
140 return true;
141 }
142 }
143
144 // C++11 [except.spec]p2:
145 // A type denoted in an exception-specification shall not denote an
146 // incomplete type other than a class currently being defined [...].
147 // A type denoted in an exception-specification shall not denote a
148 // pointer or reference to an incomplete type, other than (cv) void* or a
149 // pointer or reference to a class currently being defined.
David Majnemerb2b0da42016-06-10 18:24:41 +0000150 // In Microsoft mode, downgrade this to a warning.
151 unsigned DiagID = diag::err_incomplete_in_exception_spec;
David Majnemer5d321e62016-06-11 01:25:04 +0000152 bool ReturnValueOnError = true;
Reid Kleckner39aa8952019-08-27 17:52:03 +0000153 if (getLangOpts().MSVCCompat) {
David Majnemerb2b0da42016-06-10 18:24:41 +0000154 DiagID = diag::ext_incomplete_in_exception_spec;
David Majnemer5d321e62016-06-11 01:25:04 +0000155 ReturnValueOnError = false;
156 }
Richard Smitha118c6a2012-11-28 22:52:42 +0000157 if (!(PointeeT->isRecordType() &&
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000158 PointeeT->castAs<RecordType>()->isBeingDefined()) &&
David Majnemerb2b0da42016-06-10 18:24:41 +0000159 RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range))
David Majnemer5d321e62016-06-11 01:25:04 +0000160 return ReturnValueOnError;
Sebastian Redl4915e632009-10-11 09:03:14 +0000161
162 return false;
163}
164
165/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
166/// to member to a function with an exception specification. This means that
167/// it is invalid to add another level of indirection.
168bool Sema::CheckDistantExceptionSpec(QualType T) {
Richard Smith3c4f8d22016-10-16 17:54:23 +0000169 // C++17 removes this rule in favor of putting exception specifications into
170 // the type system.
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000171 if (getLangOpts().CPlusPlus17)
Richard Smith3c4f8d22016-10-16 17:54:23 +0000172 return false;
173
Sebastian Redl4915e632009-10-11 09:03:14 +0000174 if (const PointerType *PT = T->getAs<PointerType>())
175 T = PT->getPointeeType();
176 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
177 T = PT->getPointeeType();
178 else
179 return false;
180
181 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
182 if (!FnT)
183 return false;
184
185 return FnT->hasExceptionSpec();
186}
187
Richard Smithf623c962012-04-17 00:58:00 +0000188const FunctionProtoType *
189Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
Richard Smith0b3a4622014-11-13 20:01:57 +0000190 if (FPT->getExceptionSpecType() == EST_Unparsed) {
191 Diag(Loc, diag::err_exception_spec_not_parsed);
192 return nullptr;
193 }
194
Richard Smithd3b5c9082012-07-27 04:22:15 +0000195 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000196 return FPT;
197
198 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
199 const FunctionProtoType *SourceFPT =
200 SourceDecl->getType()->castAs<FunctionProtoType>();
201
Richard Smithd3b5c9082012-07-27 04:22:15 +0000202 // If the exception specification has already been resolved, just return it.
203 if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000204 return SourceFPT;
205
Richard Smithd3b5c9082012-07-27 04:22:15 +0000206 // Compute or instantiate the exception specification now.
Richard Smith3901dfe2013-03-27 00:22:47 +0000207 if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smithd3b5c9082012-07-27 04:22:15 +0000208 EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
209 else
210 InstantiateExceptionSpec(Loc, SourceDecl);
Richard Smithf623c962012-04-17 00:58:00 +0000211
Davide Italiano922b7022015-07-25 01:19:32 +0000212 const FunctionProtoType *Proto =
213 SourceDecl->getType()->castAs<FunctionProtoType>();
214 if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
215 Diag(Loc, diag::err_exception_spec_not_parsed);
216 Proto = nullptr;
217 }
218 return Proto;
Richard Smithf623c962012-04-17 00:58:00 +0000219}
220
Richard Smith8acb4282014-07-31 21:57:55 +0000221void
222Sema::UpdateExceptionSpec(FunctionDecl *FD,
223 const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith564417a2014-03-20 21:47:22 +0000224 // If we've fully resolved the exception specification, notify listeners.
Richard Smith8acb4282014-07-31 21:57:55 +0000225 if (!isUnresolvedExceptionSpec(ESI.Type))
Richard Smith564417a2014-03-20 21:47:22 +0000226 if (auto *Listener = getASTMutationListener())
227 Listener->ResolvedExceptionSpec(FD);
Richard Smith9e2341d2015-03-23 03:25:59 +0000228
George Burgess IV00f70bd2018-03-01 05:43:23 +0000229 for (FunctionDecl *Redecl : FD->redecls())
230 Context.adjustExceptionSpec(Redecl, ESI);
Richard Smith564417a2014-03-20 21:47:22 +0000231}
232
Richard Smith5159bbad2018-09-05 22:30:37 +0000233static bool exceptionSpecNotKnownYet(const FunctionDecl *FD) {
234 auto *MD = dyn_cast<CXXMethodDecl>(FD);
235 if (!MD)
236 return false;
237
238 auto EST = MD->getType()->castAs<FunctionProtoType>()->getExceptionSpecType();
239 return EST == EST_Unparsed ||
240 (EST == EST_Unevaluated && MD->getParent()->isBeingDefined());
Simon Pilgrim58310ec2018-09-06 15:16:17 +0000241}
Richard Smith5159bbad2018-09-05 22:30:37 +0000242
Richard Smith13b40bc2016-11-30 00:13:55 +0000243static bool CheckEquivalentExceptionSpecImpl(
244 Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
245 const FunctionProtoType *Old, SourceLocation OldLoc,
246 const FunctionProtoType *New, SourceLocation NewLoc,
247 bool *MissingExceptionSpecification = nullptr,
248 bool *MissingEmptyExceptionSpecification = nullptr,
249 bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false);
250
Richard Smith66f3ac92012-10-20 08:26:51 +0000251/// Determine whether a function has an implicitly-generated exception
Richard Smith1ee63522012-10-16 23:30:16 +0000252/// specification.
Richard Smith66f3ac92012-10-20 08:26:51 +0000253static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
254 if (!isa<CXXDestructorDecl>(Decl) &&
255 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
256 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
257 return false;
Richard Smith1ee63522012-10-16 23:30:16 +0000258
Richard Smithc7fb2252014-02-07 22:51:16 +0000259 // For a function that the user didn't declare:
260 // - if this is a destructor, its exception specification is implicit.
261 // - if this is 'operator delete' or 'operator delete[]', the exception
262 // specification is as-if an explicit exception specification was given
263 // (per [basic.stc.dynamic]p2).
Richard Smith66f3ac92012-10-20 08:26:51 +0000264 if (!Decl->getTypeSourceInfo())
Richard Smithc7fb2252014-02-07 22:51:16 +0000265 return isa<CXXDestructorDecl>(Decl);
Richard Smith66f3ac92012-10-20 08:26:51 +0000266
Simon Pilgrimafb163f2019-10-21 18:28:31 +0000267 auto *Ty = Decl->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Richard Smith66f3ac92012-10-20 08:26:51 +0000268 return !Ty->hasExceptionSpec();
Richard Smith1ee63522012-10-16 23:30:16 +0000269}
270
Douglas Gregorf40863c2010-02-12 07:32:17 +0000271bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000272 // Just completely ignore this under -fno-exceptions prior to C++17.
273 // In C++17 onwards, the exception specification is part of the type and
Richard Smith13b40bc2016-11-30 00:13:55 +0000274 // we will diagnose mismatches anyway, so it's better to check for them here.
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000275 if (!getLangOpts().CXXExceptions && !getLangOpts().CPlusPlus17)
Richard Smith13b40bc2016-11-30 00:13:55 +0000276 return false;
277
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000278 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
279 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000280 bool MissingExceptionSpecification = false;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000281 bool MissingEmptyExceptionSpecification = false;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000282
Francois Pichet13b4e682011-03-19 23:05:18 +0000283 unsigned DiagID = diag::err_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000284 bool ReturnValueOnError = true;
Reid Kleckner39aa8952019-08-27 17:52:03 +0000285 if (getLangOpts().MSVCCompat) {
Richard Smith1b98ccc2014-07-19 01:39:17 +0000286 DiagID = diag::ext_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000287 ReturnValueOnError = false;
288 }
Richard Smithf623c962012-04-17 00:58:00 +0000289
Richard Smith5159bbad2018-09-05 22:30:37 +0000290 // If we're befriending a member function of a class that's currently being
291 // defined, we might not be able to work out its exception specification yet.
292 // If not, defer the check until later.
293 if (exceptionSpecNotKnownYet(Old) || exceptionSpecNotKnownYet(New)) {
294 DelayedEquivalentExceptionSpecChecks.push_back({New, Old});
295 return false;
296 }
297
Richard Smith1ee63522012-10-16 23:30:16 +0000298 // Check the types as written: they must match before any exception
299 // specification adjustment is applied.
Richard Smith13b40bc2016-11-30 00:13:55 +0000300 if (!CheckEquivalentExceptionSpecImpl(
301 *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
Richard Smith66f3ac92012-10-20 08:26:51 +0000302 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
303 New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
Richard Smith1ee63522012-10-16 23:30:16 +0000304 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
Richard Smith66f3ac92012-10-20 08:26:51 +0000305 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
306 // C++11 [except.spec]p4 [DR1492]:
307 // If a declaration of a function has an implicit
308 // exception-specification, other declarations of the function shall
309 // not specify an exception-specification.
Richard Smithe3ea0012016-08-31 20:38:32 +0000310 if (getLangOpts().CPlusPlus11 && getLangOpts().CXXExceptions &&
Richard Smith66f3ac92012-10-20 08:26:51 +0000311 hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
312 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
313 << hasImplicitExceptionSpec(Old);
Yaron Keren8b563662015-10-03 10:46:20 +0000314 if (Old->getLocation().isValid())
Richard Smith66f3ac92012-10-20 08:26:51 +0000315 Diag(Old->getLocation(), diag::note_previous_declaration);
316 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000317 return false;
Richard Smith66f3ac92012-10-20 08:26:51 +0000318 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000319
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000320 // The failure was something other than an missing exception
Hans Wennborg39a509a2014-02-05 02:37:58 +0000321 // specification; return an error, except in MS mode where this is a warning.
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000322 if (!MissingExceptionSpecification)
Hans Wennborg39a509a2014-02-05 02:37:58 +0000323 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000324
Richard Smith66f3ac92012-10-20 08:26:51 +0000325 const FunctionProtoType *NewProto =
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000326 New->getType()->castAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +0000327
Douglas Gregorf40863c2010-02-12 07:32:17 +0000328 // The new function declaration is only missing an empty exception
329 // specification "throw()". If the throw() specification came from a
330 // function in a system header that has C linkage, just add an empty
Richard Smith836de6b2016-12-19 23:59:34 +0000331 // exception specification to the "new" declaration. Note that C library
332 // implementations are permitted to add these nothrow exception
333 // specifications.
334 //
335 // Likewise if the old function is a builtin.
John McCalldb40c7f2010-12-14 08:05:40 +0000336 if (MissingEmptyExceptionSpecification && NewProto &&
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000337 (Old->getLocation().isInvalid() ||
Richard Smith836de6b2016-12-19 23:59:34 +0000338 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
339 Old->getBuiltinID()) &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000340 Old->isExternC()) {
Richard Smith8acb4282014-07-31 21:57:55 +0000341 New->setType(Context.getFunctionType(
342 NewProto->getReturnType(), NewProto->getParamTypes(),
343 NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
Douglas Gregorf40863c2010-02-12 07:32:17 +0000344 return false;
345 }
346
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000347 const FunctionProtoType *OldProto =
348 Old->getType()->castAs<FunctionProtoType>();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000349
Richard Smith8acb4282014-07-31 21:57:55 +0000350 FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
351 if (ESI.Type == EST_Dynamic) {
Richard Smitheaf11ad2018-05-03 03:58:32 +0000352 // FIXME: What if the exceptions are described in terms of the old
353 // prototype's parameters?
Richard Smith8acb4282014-07-31 21:57:55 +0000354 ESI.Exceptions = OldProto->exceptions();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000355 }
356
Richard Smitheaf11ad2018-05-03 03:58:32 +0000357 if (ESI.Type == EST_NoexceptFalse)
358 ESI.Type = EST_None;
359 if (ESI.Type == EST_NoexceptTrue)
360 ESI.Type = EST_BasicNoexcept;
361
362 // For dependent noexcept, we can't just take the expression from the old
363 // prototype. It likely contains references to the old prototype's parameters.
364 if (ESI.Type == EST_DependentNoexcept) {
Richard Smitha91de372015-09-30 00:48:50 +0000365 New->setInvalidDecl();
366 } else {
367 // Update the type of the function with the appropriate exception
368 // specification.
369 New->setType(Context.getFunctionType(
370 NewProto->getReturnType(), NewProto->getParamTypes(),
371 NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
372 }
373
Reid Kleckner39aa8952019-08-27 17:52:03 +0000374 if (getLangOpts().MSVCCompat && ESI.Type != EST_DependentNoexcept) {
David Majnemer06ce8a42015-10-20 20:49:21 +0000375 // Allow missing exception specifications in redeclarations as an extension.
376 DiagID = diag::ext_ms_missing_exception_specification;
377 ReturnValueOnError = false;
378 } else if (New->isReplaceableGlobalAllocationFunction() &&
Richard Smitheaf11ad2018-05-03 03:58:32 +0000379 ESI.Type != EST_DependentNoexcept) {
David Majnemer06ce8a42015-10-20 20:49:21 +0000380 // Allow missing exception specifications in redeclarations as an extension,
381 // when declaring a replaceable global allocation function.
Richard Smitha91de372015-09-30 00:48:50 +0000382 DiagID = diag::ext_missing_exception_specification;
383 ReturnValueOnError = false;
Erich Keane54182eb2019-05-31 14:26:19 +0000384 } else if (ESI.Type == EST_NoThrow) {
385 // Allow missing attribute 'nothrow' in redeclarations, since this is a very
386 // common omission.
387 DiagID = diag::ext_missing_exception_specification;
388 ReturnValueOnError = false;
Richard Smitha91de372015-09-30 00:48:50 +0000389 } else {
390 DiagID = diag::err_missing_exception_specification;
391 ReturnValueOnError = true;
392 }
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000393
394 // Warn about the lack of exception specification.
395 SmallString<128> ExceptionSpecString;
396 llvm::raw_svector_ostream OS(ExceptionSpecString);
397 switch (OldProto->getExceptionSpecType()) {
398 case EST_DynamicNone:
399 OS << "throw()";
400 break;
401
402 case EST_Dynamic: {
403 OS << "throw(";
404 bool OnFirstException = true;
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000405 for (const auto &E : OldProto->exceptions()) {
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000406 if (OnFirstException)
407 OnFirstException = false;
408 else
409 OS << ", ";
Fangrui Song6907ce22018-07-30 19:24:48 +0000410
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000411 OS << E.getAsString(getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000412 }
413 OS << ")";
414 break;
415 }
416
417 case EST_BasicNoexcept:
418 OS << "noexcept";
419 break;
420
Richard Smitheaf11ad2018-05-03 03:58:32 +0000421 case EST_DependentNoexcept:
422 case EST_NoexceptFalse:
423 case EST_NoexceptTrue:
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000424 OS << "noexcept(";
Richard Trieuddd01ce2014-06-09 22:53:25 +0000425 assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
Craig Topperc3ec1492014-05-26 06:22:03 +0000426 OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000427 OS << ")";
428 break;
Erich Keane54182eb2019-05-31 14:26:19 +0000429 case EST_NoThrow:
430 OS <<"__attribute__((nothrow))";
431 break;
Erich Keane68fa6dd2019-05-31 17:00:48 +0000432 case EST_None:
433 case EST_MSAny:
434 case EST_Unevaluated:
435 case EST_Uninstantiated:
436 case EST_Unparsed:
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000437 llvm_unreachable("This spec type is compatible with none.");
438 }
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000439
440 SourceLocation FixItLoc;
441 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
442 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Richard Smitha91de372015-09-30 00:48:50 +0000443 // FIXME: Preserve enough information so that we can produce a correct fixit
444 // location when there is a trailing return type.
445 if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
446 if (!FTLoc.getTypePtr()->hasTrailingReturn())
447 FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000448 }
449
450 if (FixItLoc.isInvalid())
Richard Smitha91de372015-09-30 00:48:50 +0000451 Diag(New->getLocation(), DiagID)
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000452 << New << OS.str();
453 else {
Richard Smitha91de372015-09-30 00:48:50 +0000454 Diag(New->getLocation(), DiagID)
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000455 << New << OS.str()
456 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
457 }
458
Yaron Keren8b563662015-10-03 10:46:20 +0000459 if (Old->getLocation().isValid())
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000460 Diag(Old->getLocation(), diag::note_previous_declaration);
461
Richard Smitha91de372015-09-30 00:48:50 +0000462 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000463}
464
Sebastian Redl4915e632009-10-11 09:03:14 +0000465/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
466/// exception specifications. Exception specifications are equivalent if
467/// they allow exactly the same set of exception types. It does not matter how
468/// that is achieved. See C++ [except.spec]p2.
469bool Sema::CheckEquivalentExceptionSpec(
470 const FunctionProtoType *Old, SourceLocation OldLoc,
471 const FunctionProtoType *New, SourceLocation NewLoc) {
Richard Smith13b40bc2016-11-30 00:13:55 +0000472 if (!getLangOpts().CXXExceptions)
473 return false;
474
Francois Pichet13b4e682011-03-19 23:05:18 +0000475 unsigned DiagID = diag::err_mismatched_exception_spec;
Reid Kleckner39aa8952019-08-27 17:52:03 +0000476 if (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +0000477 DiagID = diag::ext_mismatched_exception_spec;
Richard Smith13b40bc2016-11-30 00:13:55 +0000478 bool Result = CheckEquivalentExceptionSpecImpl(
479 *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
480 Old, OldLoc, New, NewLoc);
Hans Wennborg39a509a2014-02-05 02:37:58 +0000481
482 // In Microsoft mode, mismatching exception specifications just cause a warning.
Reid Kleckner39aa8952019-08-27 17:52:03 +0000483 if (getLangOpts().MSVCCompat)
Hans Wennborg39a509a2014-02-05 02:37:58 +0000484 return false;
485 return Result;
Sebastian Redl4915e632009-10-11 09:03:14 +0000486}
487
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000488/// CheckEquivalentExceptionSpec - Check if the two types have compatible
489/// exception specifications. See C++ [except.spec]p3.
Richard Smith66f3ac92012-10-20 08:26:51 +0000490///
491/// \return \c false if the exception specifications match, \c true if there is
492/// a problem. If \c true is returned, either a diagnostic has already been
493/// produced or \c *MissingExceptionSpecification is set to \c true.
Richard Smith13b40bc2016-11-30 00:13:55 +0000494static bool CheckEquivalentExceptionSpecImpl(
495 Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
496 const FunctionProtoType *Old, SourceLocation OldLoc,
497 const FunctionProtoType *New, SourceLocation NewLoc,
498 bool *MissingExceptionSpecification,
499 bool *MissingEmptyExceptionSpecification,
500 bool AllowNoexceptAllMatchWithNoSpec, bool IsOperatorNew) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000501 if (MissingExceptionSpecification)
502 *MissingExceptionSpecification = false;
503
Douglas Gregorf40863c2010-02-12 07:32:17 +0000504 if (MissingEmptyExceptionSpecification)
505 *MissingEmptyExceptionSpecification = false;
506
Richard Smith13b40bc2016-11-30 00:13:55 +0000507 Old = S.ResolveExceptionSpec(NewLoc, Old);
Richard Smithf623c962012-04-17 00:58:00 +0000508 if (!Old)
509 return false;
Richard Smith13b40bc2016-11-30 00:13:55 +0000510 New = S.ResolveExceptionSpec(NewLoc, New);
Richard Smithf623c962012-04-17 00:58:00 +0000511 if (!New)
512 return false;
513
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000514 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
515 // - both are non-throwing, regardless of their form,
516 // - both have the form noexcept(constant-expression) and the constant-
517 // expressions are equivalent,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000518 // - both are dynamic-exception-specifications that have the same set of
519 // adjusted types.
520 //
Eric Christophere6b7cf42015-07-10 18:25:52 +0000521 // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000522 // of the form throw(), noexcept, or noexcept(constant-expression) where the
523 // constant-expression yields true.
524 //
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000525 // C++0x [except.spec]p4: If any declaration of a function has an exception-
526 // specifier that is not a noexcept-specification allowing all exceptions,
527 // all declarations [...] of that function shall have a compatible
528 // exception-specification.
529 //
530 // That last point basically means that noexcept(false) matches no spec.
531 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
532
533 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
534 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
535
Richard Smithd3b5c9082012-07-27 04:22:15 +0000536 assert(!isUnresolvedExceptionSpec(OldEST) &&
537 !isUnresolvedExceptionSpec(NewEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000538 "Shouldn't see unknown exception specifications here");
539
Richard Smitheaf11ad2018-05-03 03:58:32 +0000540 CanThrowResult OldCanThrow = Old->canThrow();
541 CanThrowResult NewCanThrow = New->canThrow();
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000542
543 // Any non-throwing specifications are compatible.
Richard Smitheaf11ad2018-05-03 03:58:32 +0000544 if (OldCanThrow == CT_Cannot && NewCanThrow == CT_Cannot)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000545 return false;
546
Richard Smitheaf11ad2018-05-03 03:58:32 +0000547 // Any throws-anything specifications are usually compatible.
548 if (OldCanThrow == CT_Can && OldEST != EST_Dynamic &&
549 NewCanThrow == CT_Can && NewEST != EST_Dynamic) {
550 // The exception is that the absence of an exception specification only
551 // matches noexcept(false) for functions, as described above.
552 if (!AllowNoexceptAllMatchWithNoSpec &&
553 ((OldEST == EST_None && NewEST == EST_NoexceptFalse) ||
554 (OldEST == EST_NoexceptFalse && NewEST == EST_None))) {
555 // This is the disallowed case.
556 } else {
557 return false;
558 }
559 }
560
Richard Smithb64764a2018-07-12 21:11:25 +0000561 // C++14 [except.spec]p3:
562 // Two exception-specifications are compatible if [...] both have the form
563 // noexcept(constant-expression) and the constant-expressions are equivalent
564 if (OldEST == EST_DependentNoexcept && NewEST == EST_DependentNoexcept) {
565 llvm::FoldingSetNodeID OldFSN, NewFSN;
566 Old->getNoexceptExpr()->Profile(OldFSN, S.Context, true);
567 New->getNoexceptExpr()->Profile(NewFSN, S.Context, true);
568 if (OldFSN == NewFSN)
569 return false;
570 }
Richard Smitheaf11ad2018-05-03 03:58:32 +0000571
572 // Dynamic exception specifications with the same set of adjusted types
573 // are compatible.
574 if (OldEST == EST_Dynamic && NewEST == EST_Dynamic) {
575 bool Success = true;
576 // Both have a dynamic exception spec. Collect the first set, then compare
577 // to the second.
578 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
579 for (const auto &I : Old->exceptions())
580 OldTypes.insert(S.Context.getCanonicalType(I).getUnqualifiedType());
581
582 for (const auto &I : New->exceptions()) {
583 CanQualType TypePtr = S.Context.getCanonicalType(I).getUnqualifiedType();
584 if (OldTypes.count(TypePtr))
585 NewTypes.insert(TypePtr);
586 else {
587 Success = false;
588 break;
589 }
590 }
591
592 if (Success && OldTypes.size() == NewTypes.size())
593 return false;
594 }
595
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000596 // As a special compatibility feature, under C++0x we accept no spec and
597 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
598 // This is because the implicit declaration changed, but old code would break.
Richard Smith13b40bc2016-11-30 00:13:55 +0000599 if (S.getLangOpts().CPlusPlus11 && IsOperatorNew) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000600 const FunctionProtoType *WithExceptions = nullptr;
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000601 if (OldEST == EST_None && NewEST == EST_Dynamic)
602 WithExceptions = New;
603 else if (OldEST == EST_Dynamic && NewEST == EST_None)
604 WithExceptions = Old;
605 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
606 // One has no spec, the other throw(something). If that something is
607 // std::bad_alloc, all conditions are met.
608 QualType Exception = *WithExceptions->exception_begin();
609 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
610 IdentifierInfo* Name = ExRecord->getIdentifier();
611 if (Name && Name->getName() == "bad_alloc") {
612 // It's called bad_alloc, but is it in std?
Richard Trieuc771d5d2014-05-28 02:16:01 +0000613 if (ExRecord->isInStdNamespace()) {
614 return false;
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000615 }
616 }
617 }
618 }
619 }
620
Richard Smitheaf11ad2018-05-03 03:58:32 +0000621 // If the caller wants to handle the case that the new function is
622 // incompatible due to a missing exception specification, let it.
623 if (MissingExceptionSpecification && OldEST != EST_None &&
624 NewEST == EST_None) {
625 // The old type has an exception specification of some sort, but
626 // the new type does not.
627 *MissingExceptionSpecification = true;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000628
Richard Smitheaf11ad2018-05-03 03:58:32 +0000629 if (MissingEmptyExceptionSpecification && OldCanThrow == CT_Cannot) {
630 // The old type has a throw() or noexcept(true) exception specification
631 // and the new type has no exception specification, and the caller asked
632 // to handle this itself.
633 *MissingEmptyExceptionSpecification = true;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000634 }
635
Sebastian Redl4915e632009-10-11 09:03:14 +0000636 return true;
637 }
638
Richard Smith13b40bc2016-11-30 00:13:55 +0000639 S.Diag(NewLoc, DiagID);
David Majnemer7da23022015-02-19 07:28:55 +0000640 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Richard Smith13b40bc2016-11-30 00:13:55 +0000641 S.Diag(OldLoc, NoteID);
Sebastian Redl4915e632009-10-11 09:03:14 +0000642 return true;
643}
644
Richard Smith13b40bc2016-11-30 00:13:55 +0000645bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
646 const PartialDiagnostic &NoteID,
647 const FunctionProtoType *Old,
648 SourceLocation OldLoc,
649 const FunctionProtoType *New,
650 SourceLocation NewLoc) {
651 if (!getLangOpts().CXXExceptions)
652 return false;
653 return CheckEquivalentExceptionSpecImpl(*this, DiagID, NoteID, Old, OldLoc,
654 New, NewLoc);
655}
656
Richard Smith56ae0a62018-01-13 05:05:45 +0000657bool Sema::handlerCanCatch(QualType HandlerType, QualType ExceptionType) {
658 // [except.handle]p3:
659 // A handler is a match for an exception object of type E if:
660
661 // HandlerType must be ExceptionType or derived from it, or pointer or
662 // reference to such types.
663 const ReferenceType *RefTy = HandlerType->getAs<ReferenceType>();
664 if (RefTy)
665 HandlerType = RefTy->getPointeeType();
666
667 // -- the handler is of type cv T or cv T& and E and T are the same type
668 if (Context.hasSameUnqualifiedType(ExceptionType, HandlerType))
669 return true;
670
671 // FIXME: ObjC pointer types?
672 if (HandlerType->isPointerType() || HandlerType->isMemberPointerType()) {
673 if (RefTy && (!HandlerType.isConstQualified() ||
674 HandlerType.isVolatileQualified()))
675 return false;
676
677 // -- the handler is of type cv T or const T& where T is a pointer or
678 // pointer to member type and E is std::nullptr_t
679 if (ExceptionType->isNullPtrType())
680 return true;
681
682 // -- the handler is of type cv T or const T& where T is a pointer or
683 // pointer to member type and E is a pointer or pointer to member type
684 // that can be converted to T by one or more of
685 // -- a qualification conversion
686 // -- a function pointer conversion
687 bool LifetimeConv;
688 QualType Result;
689 // FIXME: Should we treat the exception as catchable if a lifetime
690 // conversion is required?
691 if (IsQualificationConversion(ExceptionType, HandlerType, false,
692 LifetimeConv) ||
693 IsFunctionConversion(ExceptionType, HandlerType, Result))
694 return true;
695
696 // -- a standard pointer conversion [...]
697 if (!ExceptionType->isPointerType() || !HandlerType->isPointerType())
698 return false;
699
700 // Handle the "qualification conversion" portion.
701 Qualifiers EQuals, HQuals;
702 ExceptionType = Context.getUnqualifiedArrayType(
703 ExceptionType->getPointeeType(), EQuals);
704 HandlerType = Context.getUnqualifiedArrayType(
705 HandlerType->getPointeeType(), HQuals);
706 if (!HQuals.compatiblyIncludes(EQuals))
707 return false;
708
709 if (HandlerType->isVoidType() && ExceptionType->isObjectType())
710 return true;
711
712 // The only remaining case is a derived-to-base conversion.
713 }
714
715 // -- the handler is of type cg T or cv T& and T is an unambiguous public
716 // base class of E
717 if (!ExceptionType->isRecordType() || !HandlerType->isRecordType())
718 return false;
719 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
720 /*DetectVirtual=*/false);
721 if (!IsDerivedFrom(SourceLocation(), ExceptionType, HandlerType, Paths) ||
722 Paths.isAmbiguous(Context.getCanonicalType(HandlerType)))
723 return false;
724
725 // Do this check from a context without privileges.
726 switch (CheckBaseClassAccess(SourceLocation(), HandlerType, ExceptionType,
727 Paths.front(),
728 /*Diagnostic*/ 0,
729 /*ForceCheck*/ true,
730 /*ForceUnprivileged*/ true)) {
731 case AR_accessible: return true;
732 case AR_inaccessible: return false;
733 case AR_dependent:
734 llvm_unreachable("access check dependent for unprivileged context");
735 case AR_delayed:
736 llvm_unreachable("access check delayed in non-declaration");
737 }
738 llvm_unreachable("unexpected access check result");
739}
740
Sebastian Redl4915e632009-10-11 09:03:14 +0000741/// CheckExceptionSpecSubset - Check whether the second function type's
742/// exception specification is a subset (or equivalent) of the first function
743/// type. This is used by override and pointer assignment checks.
Richard Smith1be59c52016-10-22 01:32:19 +0000744bool Sema::CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
745 const PartialDiagnostic &NestedDiagID,
746 const PartialDiagnostic &NoteID,
Erich Keane81ef6252019-06-03 18:36:26 +0000747 const PartialDiagnostic &NoThrowDiagID,
Richard Smith1be59c52016-10-22 01:32:19 +0000748 const FunctionProtoType *Superset,
749 SourceLocation SuperLoc,
750 const FunctionProtoType *Subset,
751 SourceLocation SubLoc) {
John McCallf9c94092010-05-28 08:37:35 +0000752
753 // Just auto-succeed under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000754 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000755 return false;
756
Sebastian Redl4915e632009-10-11 09:03:14 +0000757 // FIXME: As usual, we could be more specific in our error messages, but
758 // that better waits until we've got types with source locations.
759
760 if (!SubLoc.isValid())
761 SubLoc = SuperLoc;
762
Richard Smithf623c962012-04-17 00:58:00 +0000763 // Resolve the exception specifications, if needed.
764 Superset = ResolveExceptionSpec(SuperLoc, Superset);
765 if (!Superset)
766 return false;
767 Subset = ResolveExceptionSpec(SubLoc, Subset);
768 if (!Subset)
769 return false;
770
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000771 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
Richard Smitheaf11ad2018-05-03 03:58:32 +0000772 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
773 assert(!isUnresolvedExceptionSpec(SuperEST) &&
774 !isUnresolvedExceptionSpec(SubEST) &&
775 "Shouldn't see unknown exception specifications here");
Sebastian Redl4915e632009-10-11 09:03:14 +0000776
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000777 // If there are dependent noexcept specs, assume everything is fine. Unlike
778 // with the equivalency check, this is safe in this case, because we don't
779 // want to merge declarations. Checks after instantiation will catch any
780 // omissions we make here.
Richard Smitheaf11ad2018-05-03 03:58:32 +0000781 if (SuperEST == EST_DependentNoexcept || SubEST == EST_DependentNoexcept)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000782 return false;
783
Richard Smitheaf11ad2018-05-03 03:58:32 +0000784 CanThrowResult SuperCanThrow = Superset->canThrow();
785 CanThrowResult SubCanThrow = Subset->canThrow();
786
787 // If the superset contains everything or the subset contains nothing, we're
788 // done.
789 if ((SuperCanThrow == CT_Can && SuperEST != EST_Dynamic) ||
790 SubCanThrow == CT_Cannot)
Richard Smith1be59c52016-10-22 01:32:19 +0000791 return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
792 Subset, SubLoc);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000793
Erich Keane81ef6252019-06-03 18:36:26 +0000794 // Allow __declspec(nothrow) to be missing on redeclaration as an extension in
795 // some cases.
796 if (NoThrowDiagID.getDiagID() != 0 && SubCanThrow == CT_Can &&
797 SuperCanThrow == CT_Cannot && SuperEST == EST_NoThrow) {
798 Diag(SubLoc, NoThrowDiagID);
799 if (NoteID.getDiagID() != 0)
800 Diag(SuperLoc, NoteID);
801 return true;
802 }
803
Richard Smitheaf11ad2018-05-03 03:58:32 +0000804 // If the subset contains everything or the superset contains nothing, we've
805 // failed.
806 if ((SubCanThrow == CT_Can && SubEST != EST_Dynamic) ||
807 SuperCanThrow == CT_Cannot) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000808 Diag(SubLoc, DiagID);
809 if (NoteID.getDiagID() != 0)
810 Diag(SuperLoc, NoteID);
811 return true;
812 }
813
814 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
815 "Exception spec subset: non-dynamic case slipped through.");
816
817 // Neither contains everything or nothing. Do a proper comparison.
Richard Smith56ae0a62018-01-13 05:05:45 +0000818 for (QualType SubI : Subset->exceptions()) {
819 if (const ReferenceType *RefTy = SubI->getAs<ReferenceType>())
820 SubI = RefTy->getPointeeType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000821
Sebastian Redl4915e632009-10-11 09:03:14 +0000822 // Make sure it's in the superset.
Richard Smith56ae0a62018-01-13 05:05:45 +0000823 bool Contained = false;
824 for (QualType SuperI : Superset->exceptions()) {
825 // [except.spec]p5:
826 // the target entity shall allow at least the exceptions allowed by the
827 // source
828 //
829 // We interpret this as meaning that a handler for some target type would
830 // catch an exception of each source type.
831 if (handlerCanCatch(SuperI, SubI)) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000832 Contained = true;
833 break;
834 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000835 }
836 if (!Contained) {
837 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000838 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000839 Diag(SuperLoc, NoteID);
840 return true;
841 }
842 }
843 // We've run half the gauntlet.
Richard Smith1be59c52016-10-22 01:32:19 +0000844 return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
845 Subset, SubLoc);
Sebastian Redl4915e632009-10-11 09:03:14 +0000846}
847
Richard Smith1be59c52016-10-22 01:32:19 +0000848static bool
849CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID,
850 const PartialDiagnostic &NoteID, QualType Target,
851 SourceLocation TargetLoc, QualType Source,
852 SourceLocation SourceLoc) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000853 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
854 if (!TFunc)
855 return false;
856 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
857 if (!SFunc)
858 return false;
859
860 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
861 SFunc, SourceLoc);
862}
863
864/// CheckParamExceptionSpec - Check if the parameter and return types of the
865/// two functions have equivalent exception specs. This is part of the
866/// assignment and override compatibility check. We do not check the parameters
867/// of parameter function pointers recursively, as no sane programmer would
868/// even be able to write such a function type.
Richard Smith1be59c52016-10-22 01:32:19 +0000869bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &DiagID,
870 const PartialDiagnostic &NoteID,
Richard Smith2e321552014-11-12 02:00:47 +0000871 const FunctionProtoType *Target,
872 SourceLocation TargetLoc,
873 const FunctionProtoType *Source,
874 SourceLocation SourceLoc) {
Richard Smith1be59c52016-10-22 01:32:19 +0000875 auto RetDiag = DiagID;
876 RetDiag << 0;
Alp Toker314cc812014-01-25 16:55:45 +0000877 if (CheckSpecForTypesEquivalent(
Richard Smith1be59c52016-10-22 01:32:19 +0000878 *this, RetDiag, PDiag(),
Alp Toker314cc812014-01-25 16:55:45 +0000879 Target->getReturnType(), TargetLoc, Source->getReturnType(),
880 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000881 return true;
882
Sebastian Redla44822f2009-10-14 16:09:29 +0000883 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redl4915e632009-10-11 09:03:14 +0000884 // compatible.
Alp Toker9cacbab2014-01-20 20:26:09 +0000885 assert(Target->getNumParams() == Source->getNumParams() &&
Sebastian Redl4915e632009-10-11 09:03:14 +0000886 "Functions have different argument counts.");
Alp Toker9cacbab2014-01-20 20:26:09 +0000887 for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
Richard Smith1be59c52016-10-22 01:32:19 +0000888 auto ParamDiag = DiagID;
889 ParamDiag << 1;
Alp Toker9cacbab2014-01-20 20:26:09 +0000890 if (CheckSpecForTypesEquivalent(
Richard Smith1be59c52016-10-22 01:32:19 +0000891 *this, ParamDiag, PDiag(),
Alp Toker9cacbab2014-01-20 20:26:09 +0000892 Target->getParamType(i), TargetLoc, Source->getParamType(i),
893 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000894 return true;
895 }
896 return false;
897}
898
Richard Smith2e321552014-11-12 02:00:47 +0000899bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000900 // First we check for applicability.
901 // Target type must be a function, function pointer or function reference.
902 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
Richard Smith2e321552014-11-12 02:00:47 +0000903 if (!ToFunc || ToFunc->hasDependentExceptionSpec())
Sebastian Redl4915e632009-10-11 09:03:14 +0000904 return false;
905
906 // SourceType must be a function or function pointer.
907 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
Richard Smith2e321552014-11-12 02:00:47 +0000908 if (!FromFunc || FromFunc->hasDependentExceptionSpec())
Sebastian Redl4915e632009-10-11 09:03:14 +0000909 return false;
910
Richard Smith1be59c52016-10-22 01:32:19 +0000911 unsigned DiagID = diag::err_incompatible_exception_specs;
912 unsigned NestedDiagID = diag::err_deep_exception_specs_differ;
913 // This is not an error in C++17 onwards, unless the noexceptness doesn't
914 // match, but in that case we have a full-on type mismatch, not just a
915 // type sugar mismatch.
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000916 if (getLangOpts().CPlusPlus17) {
Richard Smith1be59c52016-10-22 01:32:19 +0000917 DiagID = diag::warn_incompatible_exception_specs;
918 NestedDiagID = diag::warn_deep_exception_specs_differ;
919 }
920
Sebastian Redl4915e632009-10-11 09:03:14 +0000921 // Now we've got the correct types on both sides, check their compatibility.
922 // This means that the source of the conversion can only throw a subset of
923 // the exceptions of the target, and any exception specs on arguments or
924 // return types must be equivalent.
Richard Smith2e321552014-11-12 02:00:47 +0000925 //
926 // FIXME: If there is a nested dependent exception specification, we should
927 // not be checking it here. This is fine:
928 // template<typename T> void f() {
929 // void (*p)(void (*) throw(T));
930 // void (*q)(void (*) throw(int)) = p;
931 // }
932 // ... because it might be instantiated with T=int.
Erich Keane81ef6252019-06-03 18:36:26 +0000933 return CheckExceptionSpecSubset(
934 PDiag(DiagID), PDiag(NestedDiagID), PDiag(), PDiag(), ToFunc,
935 From->getSourceRange().getBegin(), FromFunc, SourceLocation()) &&
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000936 !getLangOpts().CPlusPlus17;
Sebastian Redl4915e632009-10-11 09:03:14 +0000937}
938
939bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
940 const CXXMethodDecl *Old) {
Richard Smith88f45492014-11-22 03:09:05 +0000941 // If the new exception specification hasn't been parsed yet, skip the check.
942 // We'll get called again once it's been parsed.
943 if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
944 EST_Unparsed)
945 return false;
Richard Smith5159bbad2018-09-05 22:30:37 +0000946
947 // Don't check uninstantiated template destructors at all. We can only
948 // synthesize correct specs after the template is instantiated.
949 if (isa<CXXDestructorDecl>(New) && New->getParent()->isDependentType())
950 return false;
951
952 // If the old exception specification hasn't been parsed yet, or the new
953 // exception specification can't be computed yet, remember that we need to
954 // perform this check when we get to the end of the outermost
Richard Smith88f45492014-11-22 03:09:05 +0000955 // lexically-surrounding class.
Richard Smith5159bbad2018-09-05 22:30:37 +0000956 if (exceptionSpecNotKnownYet(Old) || exceptionSpecNotKnownYet(New)) {
957 DelayedOverridingExceptionSpecChecks.push_back({New, Old});
Richard Smith0b3a4622014-11-13 20:01:57 +0000958 return false;
Richard Smith88f45492014-11-22 03:09:05 +0000959 }
Richard Smith5159bbad2018-09-05 22:30:37 +0000960
Francois Picheta8032e92011-05-24 02:11:43 +0000961 unsigned DiagID = diag::err_override_exception_spec;
Reid Kleckner39aa8952019-08-27 17:52:03 +0000962 if (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +0000963 DiagID = diag::ext_override_exception_spec;
Francois Picheta8032e92011-05-24 02:11:43 +0000964 return CheckExceptionSpecSubset(PDiag(DiagID),
Richard Smith1be59c52016-10-22 01:32:19 +0000965 PDiag(diag::err_deep_exception_specs_differ),
Douglas Gregor89336232010-03-29 23:34:08 +0000966 PDiag(diag::note_overridden_virtual_function),
Erich Keane81ef6252019-06-03 18:36:26 +0000967 PDiag(diag::ext_override_exception_spec),
Simon Pilgrimafb163f2019-10-21 18:28:31 +0000968 Old->getType()->castAs<FunctionProtoType>(),
Sebastian Redl4915e632009-10-11 09:03:14 +0000969 Old->getLocation(),
Simon Pilgrimafb163f2019-10-21 18:28:31 +0000970 New->getType()->castAs<FunctionProtoType>(),
Sebastian Redl4915e632009-10-11 09:03:14 +0000971 New->getLocation());
972}
973
Richard Smithfbf60b72019-12-13 14:10:13 -0800974static CanThrowResult canSubStmtsThrow(Sema &Self, const Stmt *S) {
Richard Smithf623c962012-04-17 00:58:00 +0000975 CanThrowResult R = CT_Cannot;
Richard Smithfbf60b72019-12-13 14:10:13 -0800976 for (const Stmt *SubStmt : S->children()) {
977 if (!SubStmt)
978 continue;
979 R = mergeCanThrow(R, Self.canThrow(SubStmt));
Benjamin Kramer642f1732015-07-02 21:03:14 +0000980 if (R == CT_Can)
981 break;
982 }
Richard Smithf623c962012-04-17 00:58:00 +0000983 return R;
984}
985
Richard Smithfbf60b72019-12-13 14:10:13 -0800986/// Determine whether the callee of a particular function call can throw.
987/// E and D are both optional, but at least one of E and Loc must be specified.
988static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
989 SourceLocation Loc = SourceLocation()) {
Richard Smithf623c962012-04-17 00:58:00 +0000990 // As an extension, we assume that __attribute__((nothrow)) functions don't
991 // throw.
Richard Smith3a8f13a2016-12-03 00:29:06 +0000992 if (D && isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
Richard Smithf623c962012-04-17 00:58:00 +0000993 return CT_Cannot;
994
Richard Smith3a8f13a2016-12-03 00:29:06 +0000995 QualType T;
996
997 // In C++1z, just look at the function type of the callee.
Richard Smithfbf60b72019-12-13 14:10:13 -0800998 if (S.getLangOpts().CPlusPlus17 && E && isa<CallExpr>(E)) {
Richard Smith3a8f13a2016-12-03 00:29:06 +0000999 E = cast<CallExpr>(E)->getCallee();
1000 T = E->getType();
1001 if (T->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1002 // Sadly we don't preserve the actual type as part of the "bound member"
1003 // placeholder, so we need to reconstruct it.
1004 E = E->IgnoreParenImpCasts();
1005
1006 // Could be a call to a pointer-to-member or a plain member access.
1007 if (auto *Op = dyn_cast<BinaryOperator>(E)) {
1008 assert(Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI);
1009 T = Op->getRHS()->getType()
1010 ->castAs<MemberPointerType>()->getPointeeType();
1011 } else {
1012 T = cast<MemberExpr>(E)->getMemberDecl()->getType();
1013 }
1014 }
1015 } else if (const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D))
1016 T = VD->getType();
1017 else
1018 // If we have no clue what we're calling, assume the worst.
1019 return CT_Can;
1020
Richard Smithf623c962012-04-17 00:58:00 +00001021 const FunctionProtoType *FT;
1022 if ((FT = T->getAs<FunctionProtoType>())) {
1023 } else if (const PointerType *PT = T->getAs<PointerType>())
1024 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1025 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1026 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1027 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1028 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1029 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1030 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1031
1032 if (!FT)
1033 return CT_Can;
1034
Richard Smithfbf60b72019-12-13 14:10:13 -08001035 FT = S.ResolveExceptionSpec(Loc.isInvalid() ? E->getBeginLoc() : Loc, FT);
Richard Smithf623c962012-04-17 00:58:00 +00001036 if (!FT)
1037 return CT_Can;
1038
Richard Smitheaf11ad2018-05-03 03:58:32 +00001039 return FT->canThrow();
Richard Smithf623c962012-04-17 00:58:00 +00001040}
1041
Richard Smithfbf60b72019-12-13 14:10:13 -08001042static CanThrowResult canVarDeclThrow(Sema &Self, const VarDecl *VD) {
1043 CanThrowResult CT = CT_Cannot;
1044
1045 // Initialization might throw.
1046 if (!VD->isUsableInConstantExpressions(Self.Context))
1047 if (const Expr *Init = VD->getInit())
1048 CT = mergeCanThrow(CT, Self.canThrow(Init));
1049
1050 // Destructor might throw.
1051 if (VD->needsDestruction(Self.Context) == QualType::DK_cxx_destructor) {
1052 if (auto *RD =
1053 VD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
1054 if (auto *Dtor = RD->getDestructor()) {
1055 CT = mergeCanThrow(
1056 CT, canCalleeThrow(Self, nullptr, Dtor, VD->getLocation()));
1057 }
1058 }
1059 }
1060
1061 // If this is a decomposition declaration, bindings might throw.
1062 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
1063 for (auto *B : DD->bindings())
1064 if (auto *HD = B->getHoldingVar())
1065 CT = mergeCanThrow(CT, canVarDeclThrow(Self, HD));
1066
1067 return CT;
1068}
1069
Richard Smithf623c962012-04-17 00:58:00 +00001070static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1071 if (DC->isTypeDependent())
1072 return CT_Dependent;
1073
1074 if (!DC->getTypeAsWritten()->isReferenceType())
1075 return CT_Cannot;
1076
1077 if (DC->getSubExpr()->isTypeDependent())
1078 return CT_Dependent;
1079
1080 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
1081}
1082
1083static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
1084 if (DC->isTypeOperand())
1085 return CT_Cannot;
1086
1087 Expr *Op = DC->getExprOperand();
1088 if (Op->isTypeDependent())
1089 return CT_Dependent;
1090
1091 const RecordType *RT = Op->getType()->getAs<RecordType>();
1092 if (!RT)
1093 return CT_Cannot;
1094
1095 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1096 return CT_Cannot;
1097
1098 if (Op->Classify(S.Context).isPRValue())
1099 return CT_Cannot;
1100
1101 return CT_Can;
1102}
1103
Richard Smithfbf60b72019-12-13 14:10:13 -08001104CanThrowResult Sema::canThrow(const Stmt *S) {
Richard Smithf623c962012-04-17 00:58:00 +00001105 // C++ [expr.unary.noexcept]p3:
1106 // [Can throw] if in a potentially-evaluated context the expression would
1107 // contain:
Richard Smithfbf60b72019-12-13 14:10:13 -08001108 switch (S->getStmtClass()) {
Bill Wendling7c44da22018-10-31 03:48:47 +00001109 case Expr::ConstantExprClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001110 return canThrow(cast<ConstantExpr>(S)->getSubExpr());
Bill Wendling7c44da22018-10-31 03:48:47 +00001111
Richard Smithf623c962012-04-17 00:58:00 +00001112 case Expr::CXXThrowExprClass:
1113 // - a potentially evaluated throw-expression
1114 return CT_Can;
1115
1116 case Expr::CXXDynamicCastExprClass: {
1117 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1118 // where T is a reference type, that requires a run-time check
Richard Smithfbf60b72019-12-13 14:10:13 -08001119 auto *CE = cast<CXXDynamicCastExpr>(S);
1120 // FIXME: Properly determine whether a variably-modified type can throw.
1121 if (CE->getType()->isVariablyModifiedType())
1122 return CT_Can;
1123 CanThrowResult CT = canDynamicCastThrow(CE);
Richard Smithf623c962012-04-17 00:58:00 +00001124 if (CT == CT_Can)
1125 return CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001126 return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
Richard Smithf623c962012-04-17 00:58:00 +00001127 }
1128
1129 case Expr::CXXTypeidExprClass:
1130 // - a potentially evaluated typeid expression applied to a glvalue
1131 // expression whose type is a polymorphic class type
Richard Smithfbf60b72019-12-13 14:10:13 -08001132 return canTypeidThrow(*this, cast<CXXTypeidExpr>(S));
Richard Smithf623c962012-04-17 00:58:00 +00001133
1134 // - a potentially evaluated call to a function, member function, function
1135 // pointer, or member function pointer that does not have a non-throwing
1136 // exception-specification
1137 case Expr::CallExprClass:
1138 case Expr::CXXMemberCallExprClass:
1139 case Expr::CXXOperatorCallExprClass:
1140 case Expr::UserDefinedLiteralClass: {
Richard Smithfbf60b72019-12-13 14:10:13 -08001141 const CallExpr *CE = cast<CallExpr>(S);
Richard Smithf623c962012-04-17 00:58:00 +00001142 CanThrowResult CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001143 if (CE->isTypeDependent())
Richard Smithf623c962012-04-17 00:58:00 +00001144 CT = CT_Dependent;
1145 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
1146 CT = CT_Cannot;
Eli Friedman5a8738f2013-06-25 01:55:41 +00001147 else
Richard Smithfbf60b72019-12-13 14:10:13 -08001148 CT = canCalleeThrow(*this, CE, CE->getCalleeDecl());
Richard Smithf623c962012-04-17 00:58:00 +00001149 if (CT == CT_Can)
1150 return CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001151 return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
Richard Smithf623c962012-04-17 00:58:00 +00001152 }
1153
1154 case Expr::CXXConstructExprClass:
1155 case Expr::CXXTemporaryObjectExprClass: {
Richard Smithfbf60b72019-12-13 14:10:13 -08001156 auto *CE = cast<CXXConstructExpr>(S);
1157 // FIXME: Properly determine whether a variably-modified type can throw.
1158 if (CE->getType()->isVariablyModifiedType())
1159 return CT_Can;
1160 CanThrowResult CT = canCalleeThrow(*this, CE, CE->getConstructor());
Richard Smithf623c962012-04-17 00:58:00 +00001161 if (CT == CT_Can)
1162 return CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001163 return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
Richard Smithf623c962012-04-17 00:58:00 +00001164 }
1165
Richard Smithfbf60b72019-12-13 14:10:13 -08001166 case Expr::CXXInheritedCtorInitExprClass: {
1167 auto *ICIE = cast<CXXInheritedCtorInitExpr>(S);
1168 return canCalleeThrow(*this, ICIE, ICIE->getConstructor());
1169 }
Richard Smith5179eb72016-06-28 19:03:57 +00001170
Richard Smithf623c962012-04-17 00:58:00 +00001171 case Expr::LambdaExprClass: {
Richard Smithfbf60b72019-12-13 14:10:13 -08001172 const LambdaExpr *Lambda = cast<LambdaExpr>(S);
Richard Smithf623c962012-04-17 00:58:00 +00001173 CanThrowResult CT = CT_Cannot;
James Y Knight53c76162015-07-17 18:21:37 +00001174 for (LambdaExpr::const_capture_init_iterator
1175 Cap = Lambda->capture_init_begin(),
1176 CapEnd = Lambda->capture_init_end();
Richard Smithf623c962012-04-17 00:58:00 +00001177 Cap != CapEnd; ++Cap)
1178 CT = mergeCanThrow(CT, canThrow(*Cap));
1179 return CT;
1180 }
1181
1182 case Expr::CXXNewExprClass: {
Richard Smithfbf60b72019-12-13 14:10:13 -08001183 auto *NE = cast<CXXNewExpr>(S);
Richard Smithf623c962012-04-17 00:58:00 +00001184 CanThrowResult CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001185 if (NE->isTypeDependent())
Richard Smithf623c962012-04-17 00:58:00 +00001186 CT = CT_Dependent;
1187 else
Richard Smithfbf60b72019-12-13 14:10:13 -08001188 CT = canCalleeThrow(*this, NE, NE->getOperatorNew());
Richard Smithf623c962012-04-17 00:58:00 +00001189 if (CT == CT_Can)
1190 return CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001191 return mergeCanThrow(CT, canSubStmtsThrow(*this, NE));
Richard Smithf623c962012-04-17 00:58:00 +00001192 }
1193
1194 case Expr::CXXDeleteExprClass: {
Richard Smithfbf60b72019-12-13 14:10:13 -08001195 auto *DE = cast<CXXDeleteExpr>(S);
Richard Smithf623c962012-04-17 00:58:00 +00001196 CanThrowResult CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001197 QualType DTy = DE->getDestroyedType();
Richard Smithf623c962012-04-17 00:58:00 +00001198 if (DTy.isNull() || DTy->isDependentType()) {
1199 CT = CT_Dependent;
1200 } else {
Richard Smithfbf60b72019-12-13 14:10:13 -08001201 CT = canCalleeThrow(*this, DE, DE->getOperatorDelete());
Richard Smithf623c962012-04-17 00:58:00 +00001202 if (const RecordType *RT = DTy->getAs<RecordType>()) {
1203 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedman0423b762013-06-25 01:24:22 +00001204 const CXXDestructorDecl *DD = RD->getDestructor();
1205 if (DD)
Richard Smithfbf60b72019-12-13 14:10:13 -08001206 CT = mergeCanThrow(CT, canCalleeThrow(*this, DE, DD));
Richard Smithf623c962012-04-17 00:58:00 +00001207 }
1208 if (CT == CT_Can)
1209 return CT;
1210 }
Richard Smithfbf60b72019-12-13 14:10:13 -08001211 return mergeCanThrow(CT, canSubStmtsThrow(*this, DE));
Richard Smithf623c962012-04-17 00:58:00 +00001212 }
1213
1214 case Expr::CXXBindTemporaryExprClass: {
Richard Smithfbf60b72019-12-13 14:10:13 -08001215 auto *BTE = cast<CXXBindTemporaryExpr>(S);
Richard Smithf623c962012-04-17 00:58:00 +00001216 // The bound temporary has to be destroyed again, which might throw.
Richard Smithfbf60b72019-12-13 14:10:13 -08001217 CanThrowResult CT =
1218 canCalleeThrow(*this, BTE, BTE->getTemporary()->getDestructor());
Richard Smithf623c962012-04-17 00:58:00 +00001219 if (CT == CT_Can)
1220 return CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001221 return mergeCanThrow(CT, canSubStmtsThrow(*this, BTE));
Richard Smithf623c962012-04-17 00:58:00 +00001222 }
1223
1224 // ObjC message sends are like function calls, but never have exception
1225 // specs.
1226 case Expr::ObjCMessageExprClass:
1227 case Expr::ObjCPropertyRefExprClass:
1228 case Expr::ObjCSubscriptRefExprClass:
1229 return CT_Can;
1230
1231 // All the ObjC literals that are implemented as calls are
1232 // potentially throwing unless we decide to close off that
1233 // possibility.
1234 case Expr::ObjCArrayLiteralClass:
1235 case Expr::ObjCDictionaryLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00001236 case Expr::ObjCBoxedExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001237 return CT_Can;
1238
1239 // Many other things have subexpressions, so we have to test those.
1240 // Some are simple:
Richard Smith9f690bd2015-10-27 06:02:45 +00001241 case Expr::CoawaitExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001242 case Expr::ConditionalOperatorClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00001243 case Expr::CoyieldExprClass:
Richard Smith778dc0f2019-10-19 00:04:38 +00001244 case Expr::CXXRewrittenBinaryOperatorClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00001245 case Expr::CXXStdInitializerListExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001246 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00001247 case Expr::DesignatedInitUpdateExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001248 case Expr::ExprWithCleanupsClass:
1249 case Expr::ExtVectorElementExprClass:
1250 case Expr::InitListExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00001251 case Expr::ArrayInitLoopExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001252 case Expr::MemberExprClass:
1253 case Expr::ObjCIsaExprClass:
1254 case Expr::ObjCIvarRefExprClass:
1255 case Expr::ParenExprClass:
1256 case Expr::ParenListExprClass:
1257 case Expr::ShuffleVectorExprClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001258 case Expr::StmtExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00001259 case Expr::ConvertVectorExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001260 case Expr::VAArgExprClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001261 return canSubStmtsThrow(*this, S);
1262
1263 case Expr::CompoundLiteralExprClass:
1264 case Expr::CXXConstCastExprClass:
1265 case Expr::CXXReinterpretCastExprClass:
1266 case Expr::BuiltinBitCastExprClass:
1267 // FIXME: Properly determine whether a variably-modified type can throw.
1268 if (cast<Expr>(S)->getType()->isVariablyModifiedType())
1269 return CT_Can;
1270 return canSubStmtsThrow(*this, S);
Richard Smithf623c962012-04-17 00:58:00 +00001271
1272 // Some might be dependent for other reasons.
1273 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001274 case Expr::OMPArraySectionExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001275 case Expr::BinaryOperatorClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001276 case Expr::DependentCoawaitExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001277 case Expr::CompoundAssignOperatorClass:
1278 case Expr::CStyleCastExprClass:
1279 case Expr::CXXStaticCastExprClass:
1280 case Expr::CXXFunctionalCastExprClass:
1281 case Expr::ImplicitCastExprClass:
1282 case Expr::MaterializeTemporaryExprClass:
1283 case Expr::UnaryOperatorClass: {
Richard Smithfbf60b72019-12-13 14:10:13 -08001284 // FIXME: Properly determine whether a variably-modified type can throw.
1285 if (auto *CE = dyn_cast<CastExpr>(S))
1286 if (CE->getType()->isVariablyModifiedType())
1287 return CT_Can;
1288 CanThrowResult CT =
1289 cast<Expr>(S)->isTypeDependent() ? CT_Dependent : CT_Cannot;
1290 return mergeCanThrow(CT, canSubStmtsThrow(*this, S));
Richard Smithf623c962012-04-17 00:58:00 +00001291 }
1292
Richard Smith852c9db2013-04-20 22:23:05 +00001293 case Expr::CXXDefaultArgExprClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001294 return canThrow(cast<CXXDefaultArgExpr>(S)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001295
1296 case Expr::CXXDefaultInitExprClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001297 return canThrow(cast<CXXDefaultInitExpr>(S)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001298
Richard Smithfbf60b72019-12-13 14:10:13 -08001299 case Expr::ChooseExprClass: {
1300 auto *CE = cast<ChooseExpr>(S);
1301 if (CE->isTypeDependent() || CE->isValueDependent())
Richard Smithf623c962012-04-17 00:58:00 +00001302 return CT_Dependent;
Richard Smithfbf60b72019-12-13 14:10:13 -08001303 return canThrow(CE->getChosenSubExpr());
1304 }
Richard Smithf623c962012-04-17 00:58:00 +00001305
1306 case Expr::GenericSelectionExprClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001307 if (cast<GenericSelectionExpr>(S)->isResultDependent())
Richard Smithf623c962012-04-17 00:58:00 +00001308 return CT_Dependent;
Richard Smithfbf60b72019-12-13 14:10:13 -08001309 return canThrow(cast<GenericSelectionExpr>(S)->getResultExpr());
Richard Smithf623c962012-04-17 00:58:00 +00001310
1311 // Some expressions are always dependent.
1312 case Expr::CXXDependentScopeMemberExprClass:
1313 case Expr::CXXUnresolvedConstructExprClass:
1314 case Expr::DependentScopeDeclRefExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00001315 case Expr::CXXFoldExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001316 return CT_Dependent;
1317
1318 case Expr::AsTypeExprClass:
1319 case Expr::BinaryConditionalOperatorClass:
1320 case Expr::BlockExprClass:
1321 case Expr::CUDAKernelCallExprClass:
1322 case Expr::DeclRefExprClass:
1323 case Expr::ObjCBridgedCastExprClass:
1324 case Expr::ObjCIndirectCopyRestoreExprClass:
1325 case Expr::ObjCProtocolExprClass:
1326 case Expr::ObjCSelectorExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00001327 case Expr::ObjCAvailabilityCheckExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001328 case Expr::OffsetOfExprClass:
1329 case Expr::PackExpansionExprClass:
1330 case Expr::PseudoObjectExprClass:
1331 case Expr::SubstNonTypeTemplateParmExprClass:
1332 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00001333 case Expr::FunctionParmPackExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001334 case Expr::UnaryExprOrTypeTraitExprClass:
1335 case Expr::UnresolvedLookupExprClass:
1336 case Expr::UnresolvedMemberExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00001337 case Expr::TypoExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001338 // FIXME: Can any of the above throw? If so, when?
1339 return CT_Cannot;
1340
1341 case Expr::AddrLabelExprClass:
1342 case Expr::ArrayTypeTraitExprClass:
1343 case Expr::AtomicExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001344 case Expr::TypeTraitExprClass:
1345 case Expr::CXXBoolLiteralExprClass:
1346 case Expr::CXXNoexceptExprClass:
1347 case Expr::CXXNullPtrLiteralExprClass:
1348 case Expr::CXXPseudoDestructorExprClass:
1349 case Expr::CXXScalarValueInitExprClass:
1350 case Expr::CXXThisExprClass:
1351 case Expr::CXXUuidofExprClass:
1352 case Expr::CharacterLiteralClass:
1353 case Expr::ExpressionTraitExprClass:
1354 case Expr::FloatingLiteralClass:
1355 case Expr::GNUNullExprClass:
1356 case Expr::ImaginaryLiteralClass:
1357 case Expr::ImplicitValueInitExprClass:
1358 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00001359 case Expr::FixedPointLiteralClass:
Richard Smith410306b2016-12-12 02:53:20 +00001360 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00001361 case Expr::NoInitExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001362 case Expr::ObjCEncodeExprClass:
1363 case Expr::ObjCStringLiteralClass:
1364 case Expr::ObjCBoolLiteralExprClass:
1365 case Expr::OpaqueValueExprClass:
1366 case Expr::PredefinedExprClass:
1367 case Expr::SizeOfPackExprClass:
1368 case Expr::StringLiteralClass:
Eric Fiselier708afb52019-05-16 21:04:15 +00001369 case Expr::SourceLocExprClass:
Saar Raz5d98ba62019-10-15 15:24:26 +00001370 case Expr::ConceptSpecializationExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001371 // These expressions can never throw.
1372 return CT_Cannot;
1373
John McCall5e77d762013-04-16 07:28:30 +00001374 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00001375 case Expr::MSPropertySubscriptExprClass:
John McCall5e77d762013-04-16 07:28:30 +00001376 llvm_unreachable("Invalid class for expression");
1377
Richard Smithfbf60b72019-12-13 14:10:13 -08001378 // Most statements can throw if any substatement can throw.
1379 case Stmt::AttributedStmtClass:
1380 case Stmt::BreakStmtClass:
1381 case Stmt::CapturedStmtClass:
1382 case Stmt::CaseStmtClass:
1383 case Stmt::CompoundStmtClass:
1384 case Stmt::ContinueStmtClass:
1385 case Stmt::CoreturnStmtClass:
1386 case Stmt::CoroutineBodyStmtClass:
1387 case Stmt::CXXCatchStmtClass:
1388 case Stmt::CXXForRangeStmtClass:
1389 case Stmt::DefaultStmtClass:
1390 case Stmt::DoStmtClass:
1391 case Stmt::ForStmtClass:
1392 case Stmt::GCCAsmStmtClass:
1393 case Stmt::GotoStmtClass:
1394 case Stmt::IndirectGotoStmtClass:
1395 case Stmt::LabelStmtClass:
1396 case Stmt::MSAsmStmtClass:
1397 case Stmt::MSDependentExistsStmtClass:
1398 case Stmt::NullStmtClass:
1399 case Stmt::ObjCAtCatchStmtClass:
1400 case Stmt::ObjCAtFinallyStmtClass:
1401 case Stmt::ObjCAtSynchronizedStmtClass:
1402 case Stmt::ObjCAutoreleasePoolStmtClass:
1403 case Stmt::ObjCForCollectionStmtClass:
1404 case Stmt::OMPAtomicDirectiveClass:
1405 case Stmt::OMPBarrierDirectiveClass:
1406 case Stmt::OMPCancelDirectiveClass:
1407 case Stmt::OMPCancellationPointDirectiveClass:
1408 case Stmt::OMPCriticalDirectiveClass:
1409 case Stmt::OMPDistributeDirectiveClass:
1410 case Stmt::OMPDistributeParallelForDirectiveClass:
1411 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1412 case Stmt::OMPDistributeSimdDirectiveClass:
1413 case Stmt::OMPFlushDirectiveClass:
1414 case Stmt::OMPForDirectiveClass:
1415 case Stmt::OMPForSimdDirectiveClass:
1416 case Stmt::OMPMasterDirectiveClass:
1417 case Stmt::OMPMasterTaskLoopDirectiveClass:
1418 case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
1419 case Stmt::OMPOrderedDirectiveClass:
1420 case Stmt::OMPParallelDirectiveClass:
1421 case Stmt::OMPParallelForDirectiveClass:
1422 case Stmt::OMPParallelForSimdDirectiveClass:
1423 case Stmt::OMPParallelMasterDirectiveClass:
1424 case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
1425 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
1426 case Stmt::OMPParallelSectionsDirectiveClass:
1427 case Stmt::OMPSectionDirectiveClass:
1428 case Stmt::OMPSectionsDirectiveClass:
1429 case Stmt::OMPSimdDirectiveClass:
1430 case Stmt::OMPSingleDirectiveClass:
1431 case Stmt::OMPTargetDataDirectiveClass:
1432 case Stmt::OMPTargetDirectiveClass:
1433 case Stmt::OMPTargetEnterDataDirectiveClass:
1434 case Stmt::OMPTargetExitDataDirectiveClass:
1435 case Stmt::OMPTargetParallelDirectiveClass:
1436 case Stmt::OMPTargetParallelForDirectiveClass:
1437 case Stmt::OMPTargetParallelForSimdDirectiveClass:
1438 case Stmt::OMPTargetSimdDirectiveClass:
1439 case Stmt::OMPTargetTeamsDirectiveClass:
1440 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1441 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1442 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1443 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1444 case Stmt::OMPTargetUpdateDirectiveClass:
1445 case Stmt::OMPTaskDirectiveClass:
1446 case Stmt::OMPTaskgroupDirectiveClass:
1447 case Stmt::OMPTaskLoopDirectiveClass:
1448 case Stmt::OMPTaskLoopSimdDirectiveClass:
1449 case Stmt::OMPTaskwaitDirectiveClass:
1450 case Stmt::OMPTaskyieldDirectiveClass:
1451 case Stmt::OMPTeamsDirectiveClass:
1452 case Stmt::OMPTeamsDistributeDirectiveClass:
1453 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1454 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1455 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1456 case Stmt::ReturnStmtClass:
1457 case Stmt::SEHExceptStmtClass:
1458 case Stmt::SEHFinallyStmtClass:
1459 case Stmt::SEHLeaveStmtClass:
1460 case Stmt::SEHTryStmtClass:
1461 case Stmt::SwitchStmtClass:
1462 case Stmt::WhileStmtClass:
1463 return canSubStmtsThrow(*this, S);
1464
1465 case Stmt::DeclStmtClass: {
1466 CanThrowResult CT = CT_Cannot;
1467 for (const Decl *D : cast<DeclStmt>(S)->decls()) {
1468 if (auto *VD = dyn_cast<VarDecl>(D))
1469 CT = mergeCanThrow(CT, canVarDeclThrow(*this, VD));
1470
1471 // FIXME: Properly determine whether a variably-modified type can throw.
1472 if (auto *TND = dyn_cast<TypedefNameDecl>(D))
1473 if (TND->getUnderlyingType()->isVariablyModifiedType())
1474 return CT_Can;
1475 if (auto *VD = dyn_cast<ValueDecl>(D))
1476 if (VD->getType()->isVariablyModifiedType())
1477 return CT_Can;
1478 }
1479 return CT;
1480 }
1481
1482 case Stmt::IfStmtClass: {
1483 auto *IS = cast<IfStmt>(S);
1484 CanThrowResult CT = CT_Cannot;
1485 if (const Stmt *Init = IS->getInit())
1486 CT = mergeCanThrow(CT, canThrow(Init));
1487 if (const Stmt *CondDS = IS->getConditionVariableDeclStmt())
1488 CT = mergeCanThrow(CT, canThrow(CondDS));
1489 CT = mergeCanThrow(CT, canThrow(IS->getCond()));
1490
1491 // For 'if constexpr', consider only the non-discarded case.
1492 // FIXME: We should add a DiscardedStmt marker to the AST.
1493 if (Optional<const Stmt *> Case = IS->getNondiscardedCase(Context))
1494 return *Case ? mergeCanThrow(CT, canThrow(*Case)) : CT;
1495
1496 CanThrowResult Then = canThrow(IS->getThen());
1497 CanThrowResult Else = IS->getElse() ? canThrow(IS->getElse()) : CT_Cannot;
1498 if (Then == Else)
1499 return mergeCanThrow(CT, Then);
1500
1501 // For a dependent 'if constexpr', the result is dependent if it depends on
1502 // the value of the condition.
1503 return mergeCanThrow(CT, IS->isConstexpr() ? CT_Dependent
1504 : mergeCanThrow(Then, Else));
1505 }
1506
1507 case Stmt::CXXTryStmtClass: {
1508 auto *TS = cast<CXXTryStmt>(S);
1509 // try /*...*/ catch (...) { H } can throw only if H can throw.
1510 // Any other try-catch can throw if any substatement can throw.
1511 const CXXCatchStmt *FinalHandler = TS->getHandler(TS->getNumHandlers() - 1);
1512 if (!FinalHandler->getExceptionDecl())
1513 return canThrow(FinalHandler->getHandlerBlock());
1514 return canSubStmtsThrow(*this, S);
1515 }
1516
1517 case Stmt::ObjCAtThrowStmtClass:
1518 return CT_Can;
1519
1520 case Stmt::ObjCAtTryStmtClass: {
1521 auto *TS = cast<ObjCAtTryStmt>(S);
1522
1523 // @catch(...) need not be last in Objective-C. Walk backwards until we
1524 // see one or hit the @try.
1525 CanThrowResult CT = CT_Cannot;
1526 if (const Stmt *Finally = TS->getFinallyStmt())
1527 CT = mergeCanThrow(CT, canThrow(Finally));
1528 for (unsigned I = TS->getNumCatchStmts(); I != 0; --I) {
1529 const ObjCAtCatchStmt *Catch = TS->getCatchStmt(I - 1);
1530 CT = mergeCanThrow(CT, canThrow(Catch));
1531 // If we reach a @catch(...), no earlier exceptions can escape.
1532 if (Catch->hasEllipsis())
1533 return CT;
1534 }
1535
1536 // Didn't find an @catch(...). Exceptions from the @try body can escape.
1537 return mergeCanThrow(CT, canThrow(TS->getTryBody()));
1538 }
1539
1540 case Stmt::NoStmtClass:
1541 llvm_unreachable("Invalid class for statement");
Richard Smithf623c962012-04-17 00:58:00 +00001542 }
1543 llvm_unreachable("Bogus StmtClass");
1544}
1545
Sebastian Redl4915e632009-10-11 09:03:14 +00001546} // end namespace clang