blob: aaa2bb22565e44bad4b242059f5266548018a422 [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
Richard Smith564417a2014-03-20 21:47:22 +000013#include "clang/AST/ASTMutationListener.h"
Sebastian Redl4915e632009-10-11 09:03:14 +000014#include "clang/AST/CXXInheritance.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
Richard Smithfbf60b72019-12-13 14:10:13 -080017#include "clang/AST/StmtObjC.h"
Douglas Gregord6bc5e62010-03-24 07:14:45 +000018#include "clang/AST/TypeLoc.h"
Douglas Gregorf40863c2010-02-12 07:32:17 +000019#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/SourceManager.h"
Kazu Hirata46d750b2024-11-16 07:37:33 -080021#include "clang/Sema/SemaInternal.h"
Sebastian Redl4915e632009-10-11 09:03:14 +000022#include "llvm/ADT/SmallPtrSet.h"
Kazu Hirataa1580d72023-01-14 11:07:21 -080023#include <optional>
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
Nathan Sidwell0ff41c22021-04-28 04:03:11 -070038/// HACK: 2014-11-14 libstdc++ had a bug where it shadows std::swap with a
39/// member swap function then tries to call std::swap unqualified from the
40/// exception specification of that function. This function detects whether
41/// we're in such a case and turns off delay-parsing of exception
42/// specifications. Libstdc++ 6.1 (released 2016-04-27) appears to have
43/// resolved it as side-effect of commit ddb63209a8d (2015-06-05).
Richard Smith6403e932014-11-14 00:37:55 +000044bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {
45 auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
46
47 // All the problem cases are member functions named "swap" within class
Richard Smith62895462016-10-19 23:47:37 +000048 // templates declared directly within namespace std or std::__debug or
49 // std::__profile.
50 if (!RD || !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
Richard Smith6403e932014-11-14 00:37:55 +000051 !D.getIdentifier() || !D.getIdentifier()->isStr("swap"))
52 return false;
53
Richard Smith62895462016-10-19 23:47:37 +000054 auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext());
55 if (!ND)
56 return false;
57
58 bool IsInStd = ND->isStdNamespace();
59 if (!IsInStd) {
60 // This isn't a direct member of namespace std, but it might still be
61 // libstdc++'s std::__debug::array or std::__profile::array.
62 IdentifierInfo *II = ND->getIdentifier();
63 if (!II || !(II->isStr("__debug") || II->isStr("__profile")) ||
64 !ND->isInStdNamespace())
65 return false;
66 }
67
Richard Smith6403e932014-11-14 00:37:55 +000068 // Only apply this hack within a system header.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000069 if (!Context.getSourceManager().isInSystemHeader(D.getBeginLoc()))
Richard Smith6403e932014-11-14 00:37:55 +000070 return false;
71
72 return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
73 .Case("array", true)
Richard Smith62895462016-10-19 23:47:37 +000074 .Case("pair", IsInStd)
75 .Case("priority_queue", IsInStd)
76 .Case("stack", IsInStd)
77 .Case("queue", IsInStd)
Richard Smith6403e932014-11-14 00:37:55 +000078 .Default(false);
79}
80
Corentin Jabot3c8e94b2021-08-06 10:26:39 -040081ExprResult Sema::ActOnNoexceptSpec(Expr *NoexceptExpr,
Richard Smitheaf11ad2018-05-03 03:58:32 +000082 ExceptionSpecificationType &EST) {
Corentin Jabot3c8e94b2021-08-06 10:26:39 -040083
84 if (NoexceptExpr->isTypeDependent() ||
85 NoexceptExpr->containsUnexpandedParameterPack()) {
86 EST = EST_DependentNoexcept;
87 return NoexceptExpr;
88 }
89
90 llvm::APSInt Result;
91 ExprResult Converted = CheckConvertedConstantExpression(
Vlad Serebrennikovcf2f13a2025-05-02 14:01:15 +030092 NoexceptExpr, Context.BoolTy, Result, CCEKind::Noexcept);
Corentin Jabot3c8e94b2021-08-06 10:26:39 -040093
Erich Keanef0719bf2020-01-13 07:45:17 -080094 if (Converted.isInvalid()) {
95 EST = EST_NoexceptFalse;
Erich Keanef0719bf2020-01-13 07:45:17 -080096 // Fill in an expression of 'false' as a fixup.
97 auto *BoolExpr = new (Context)
98 CXXBoolLiteralExpr(false, Context.BoolTy, NoexceptExpr->getBeginLoc());
99 llvm::APSInt Value{1};
100 Value = 0;
101 return ConstantExpr::Create(Context, BoolExpr, APValue{Value});
102 }
Richard Smitheaf11ad2018-05-03 03:58:32 +0000103
104 if (Converted.get()->isValueDependent()) {
105 EST = EST_DependentNoexcept;
106 return Converted;
107 }
108
Richard Smitheaf11ad2018-05-03 03:58:32 +0000109 if (!Converted.isInvalid())
110 EST = !Result ? EST_NoexceptFalse : EST_NoexceptTrue;
111 return Converted;
112}
113
Craig Toppere335f252015-10-04 04:53:55 +0000114bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {
Richard Smitha118c6a2012-11-28 22:52:42 +0000115 // C++11 [except.spec]p2:
116 // A type cv T, "array of T", or "function returning T" denoted
Richard Smith8606d752012-11-28 22:33:28 +0000117 // in an exception-specification is adjusted to type T, "pointer to T", or
118 // "pointer to function returning T", respectively.
Richard Smitha118c6a2012-11-28 22:52:42 +0000119 //
120 // We also apply this rule in C++98.
Richard Smith8606d752012-11-28 22:33:28 +0000121 if (T->isArrayType())
122 T = Context.getArrayDecayedType(T);
123 else if (T->isFunctionType())
124 T = Context.getPointerType(T);
Sebastian Redl4915e632009-10-11 09:03:14 +0000125
Richard Smitha118c6a2012-11-28 22:52:42 +0000126 int Kind = 0;
Richard Smith8606d752012-11-28 22:33:28 +0000127 QualType PointeeT = T;
Richard Smitha118c6a2012-11-28 22:52:42 +0000128 if (const PointerType *PT = T->getAs<PointerType>()) {
129 PointeeT = PT->getPointeeType();
130 Kind = 1;
Sebastian Redl4915e632009-10-11 09:03:14 +0000131
Richard Smitha118c6a2012-11-28 22:52:42 +0000132 // cv void* is explicitly permitted, despite being a pointer to an
133 // incomplete type.
134 if (PointeeT->isVoidType())
135 return false;
136 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
137 PointeeT = RT->getPointeeType();
138 Kind = 2;
Richard Smith8606d752012-11-28 22:33:28 +0000139
Richard Smitha118c6a2012-11-28 22:52:42 +0000140 if (RT->isRValueReferenceType()) {
141 // C++11 [except.spec]p2:
142 // A type denoted in an exception-specification shall not denote [...]
143 // an rvalue reference type.
144 Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
145 << T << Range;
146 return true;
147 }
148 }
149
150 // C++11 [except.spec]p2:
151 // A type denoted in an exception-specification shall not denote an
152 // incomplete type other than a class currently being defined [...].
153 // A type denoted in an exception-specification shall not denote a
154 // pointer or reference to an incomplete type, other than (cv) void* or a
155 // pointer or reference to a class currently being defined.
David Majnemerb2b0da42016-06-10 18:24:41 +0000156 // In Microsoft mode, downgrade this to a warning.
157 unsigned DiagID = diag::err_incomplete_in_exception_spec;
David Majnemer5d321e62016-06-11 01:25:04 +0000158 bool ReturnValueOnError = true;
Reid Kleckner39aa8952019-08-27 17:52:03 +0000159 if (getLangOpts().MSVCCompat) {
David Majnemerb2b0da42016-06-10 18:24:41 +0000160 DiagID = diag::ext_incomplete_in_exception_spec;
David Majnemer5d321e62016-06-11 01:25:04 +0000161 ReturnValueOnError = false;
162 }
Richard Smitha118c6a2012-11-28 22:52:42 +0000163 if (!(PointeeT->isRecordType() &&
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000164 PointeeT->castAs<RecordType>()->isBeingDefined()) &&
David Majnemerb2b0da42016-06-10 18:24:41 +0000165 RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range))
David Majnemer5d321e62016-06-11 01:25:04 +0000166 return ReturnValueOnError;
Sebastian Redl4915e632009-10-11 09:03:14 +0000167
Paulo Matos55aeb232023-06-10 15:51:05 +0200168 // WebAssembly reference types can't be used in exception specifications.
169 if (PointeeT.isWebAssemblyReferenceType()) {
170 Diag(Range.getBegin(), diag::err_wasm_reftype_exception_spec);
171 return true;
172 }
173
Richard Sandiford09472962020-03-03 10:39:57 +0000174 // The MSVC compatibility mode doesn't extend to sizeless types,
175 // so diagnose them separately.
176 if (PointeeT->isSizelessType() && Kind != 1) {
177 Diag(Range.getBegin(), diag::err_sizeless_in_exception_spec)
178 << (Kind == 2 ? 1 : 0) << PointeeT << Range;
179 return true;
180 }
181
Sebastian Redl4915e632009-10-11 09:03:14 +0000182 return false;
183}
184
Sebastian Redl4915e632009-10-11 09:03:14 +0000185bool Sema::CheckDistantExceptionSpec(QualType T) {
Richard Smith3c4f8d22016-10-16 17:54:23 +0000186 // C++17 removes this rule in favor of putting exception specifications into
187 // the type system.
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000188 if (getLangOpts().CPlusPlus17)
Richard Smith3c4f8d22016-10-16 17:54:23 +0000189 return false;
190
Sebastian Redl4915e632009-10-11 09:03:14 +0000191 if (const PointerType *PT = T->getAs<PointerType>())
192 T = PT->getPointeeType();
193 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
194 T = PT->getPointeeType();
195 else
196 return false;
197
198 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
199 if (!FnT)
200 return false;
201
202 return FnT->hasExceptionSpec();
203}
204
Richard Smithf623c962012-04-17 00:58:00 +0000205const FunctionProtoType *
206Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
Richard Smith0b3a4622014-11-13 20:01:57 +0000207 if (FPT->getExceptionSpecType() == EST_Unparsed) {
208 Diag(Loc, diag::err_exception_spec_not_parsed);
209 return nullptr;
210 }
211
Richard Smithd3b5c9082012-07-27 04:22:15 +0000212 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000213 return FPT;
214
215 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
216 const FunctionProtoType *SourceFPT =
217 SourceDecl->getType()->castAs<FunctionProtoType>();
218
Richard Smithd3b5c9082012-07-27 04:22:15 +0000219 // If the exception specification has already been resolved, just return it.
220 if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000221 return SourceFPT;
222
Richard Smithd3b5c9082012-07-27 04:22:15 +0000223 // Compute or instantiate the exception specification now.
Richard Smith3901dfe2013-03-27 00:22:47 +0000224 if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith4a4e90a2019-12-13 14:11:04 -0800225 EvaluateImplicitExceptionSpec(Loc, SourceDecl);
Richard Smithd3b5c9082012-07-27 04:22:15 +0000226 else
227 InstantiateExceptionSpec(Loc, SourceDecl);
Richard Smithf623c962012-04-17 00:58:00 +0000228
Davide Italiano922b7022015-07-25 01:19:32 +0000229 const FunctionProtoType *Proto =
230 SourceDecl->getType()->castAs<FunctionProtoType>();
231 if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
232 Diag(Loc, diag::err_exception_spec_not_parsed);
233 Proto = nullptr;
234 }
235 return Proto;
Richard Smithf623c962012-04-17 00:58:00 +0000236}
237
Richard Smith8acb4282014-07-31 21:57:55 +0000238void
239Sema::UpdateExceptionSpec(FunctionDecl *FD,
240 const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith564417a2014-03-20 21:47:22 +0000241 // If we've fully resolved the exception specification, notify listeners.
Richard Smith8acb4282014-07-31 21:57:55 +0000242 if (!isUnresolvedExceptionSpec(ESI.Type))
Richard Smith564417a2014-03-20 21:47:22 +0000243 if (auto *Listener = getASTMutationListener())
244 Listener->ResolvedExceptionSpec(FD);
Richard Smith9e2341d2015-03-23 03:25:59 +0000245
George Burgess IV00f70bd2018-03-01 05:43:23 +0000246 for (FunctionDecl *Redecl : FD->redecls())
247 Context.adjustExceptionSpec(Redecl, ESI);
Richard Smith564417a2014-03-20 21:47:22 +0000248}
249
Richard Smith5159bbad2018-09-05 22:30:37 +0000250static bool exceptionSpecNotKnownYet(const FunctionDecl *FD) {
Krystian Stasiowskif061a392024-04-30 14:23:02 -0400251 ExceptionSpecificationType EST =
252 FD->getType()->castAs<FunctionProtoType>()->getExceptionSpecType();
253 if (EST == EST_Unparsed)
254 return true;
255 else if (EST != EST_Unevaluated)
Richard Smith5159bbad2018-09-05 22:30:37 +0000256 return false;
Krystian Stasiowskif061a392024-04-30 14:23:02 -0400257 const DeclContext *DC = FD->getLexicalDeclContext();
258 return DC->isRecord() && cast<RecordDecl>(DC)->isBeingDefined();
Simon Pilgrim58310ec2018-09-06 15:16:17 +0000259}
Richard Smith5159bbad2018-09-05 22:30:37 +0000260
Richard Smith13b40bc2016-11-30 00:13:55 +0000261static bool CheckEquivalentExceptionSpecImpl(
262 Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
263 const FunctionProtoType *Old, SourceLocation OldLoc,
264 const FunctionProtoType *New, SourceLocation NewLoc,
265 bool *MissingExceptionSpecification = nullptr,
266 bool *MissingEmptyExceptionSpecification = nullptr,
267 bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false);
268
Richard Smith66f3ac92012-10-20 08:26:51 +0000269/// Determine whether a function has an implicitly-generated exception
Richard Smith1ee63522012-10-16 23:30:16 +0000270/// specification.
Richard Smith66f3ac92012-10-20 08:26:51 +0000271static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
272 if (!isa<CXXDestructorDecl>(Decl) &&
273 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
274 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
275 return false;
Richard Smith1ee63522012-10-16 23:30:16 +0000276
Richard Smithc7fb2252014-02-07 22:51:16 +0000277 // For a function that the user didn't declare:
278 // - if this is a destructor, its exception specification is implicit.
279 // - if this is 'operator delete' or 'operator delete[]', the exception
280 // specification is as-if an explicit exception specification was given
281 // (per [basic.stc.dynamic]p2).
Richard Smith66f3ac92012-10-20 08:26:51 +0000282 if (!Decl->getTypeSourceInfo())
Richard Smithc7fb2252014-02-07 22:51:16 +0000283 return isa<CXXDestructorDecl>(Decl);
Richard Smith66f3ac92012-10-20 08:26:51 +0000284
Simon Pilgrimafb163f2019-10-21 18:28:31 +0000285 auto *Ty = Decl->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Richard Smith66f3ac92012-10-20 08:26:51 +0000286 return !Ty->hasExceptionSpec();
Richard Smith1ee63522012-10-16 23:30:16 +0000287}
288
Douglas Gregorf40863c2010-02-12 07:32:17 +0000289bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000290 // Just completely ignore this under -fno-exceptions prior to C++17.
291 // In C++17 onwards, the exception specification is part of the type and
Richard Smith13b40bc2016-11-30 00:13:55 +0000292 // we will diagnose mismatches anyway, so it's better to check for them here.
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000293 if (!getLangOpts().CXXExceptions && !getLangOpts().CPlusPlus17)
Richard Smith13b40bc2016-11-30 00:13:55 +0000294 return false;
295
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000296 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
297 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000298 bool MissingExceptionSpecification = false;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000299 bool MissingEmptyExceptionSpecification = false;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000300
Francois Pichet13b4e682011-03-19 23:05:18 +0000301 unsigned DiagID = diag::err_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000302 bool ReturnValueOnError = true;
Reid Kleckner39aa8952019-08-27 17:52:03 +0000303 if (getLangOpts().MSVCCompat) {
Richard Smith1b98ccc2014-07-19 01:39:17 +0000304 DiagID = diag::ext_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000305 ReturnValueOnError = false;
306 }
Richard Smithf623c962012-04-17 00:58:00 +0000307
Richard Smith5159bbad2018-09-05 22:30:37 +0000308 // If we're befriending a member function of a class that's currently being
309 // defined, we might not be able to work out its exception specification yet.
310 // If not, defer the check until later.
311 if (exceptionSpecNotKnownYet(Old) || exceptionSpecNotKnownYet(New)) {
312 DelayedEquivalentExceptionSpecChecks.push_back({New, Old});
313 return false;
314 }
315
Richard Smith1ee63522012-10-16 23:30:16 +0000316 // Check the types as written: they must match before any exception
317 // specification adjustment is applied.
Richard Smith13b40bc2016-11-30 00:13:55 +0000318 if (!CheckEquivalentExceptionSpecImpl(
319 *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
Richard Smith66f3ac92012-10-20 08:26:51 +0000320 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
321 New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
Richard Smith1ee63522012-10-16 23:30:16 +0000322 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
Richard Smith66f3ac92012-10-20 08:26:51 +0000323 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
324 // C++11 [except.spec]p4 [DR1492]:
325 // If a declaration of a function has an implicit
326 // exception-specification, other declarations of the function shall
327 // not specify an exception-specification.
Richard Smithe3ea0012016-08-31 20:38:32 +0000328 if (getLangOpts().CPlusPlus11 && getLangOpts().CXXExceptions &&
Richard Smith66f3ac92012-10-20 08:26:51 +0000329 hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
330 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
331 << hasImplicitExceptionSpec(Old);
Yaron Keren8b563662015-10-03 10:46:20 +0000332 if (Old->getLocation().isValid())
Richard Smith66f3ac92012-10-20 08:26:51 +0000333 Diag(Old->getLocation(), diag::note_previous_declaration);
334 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000335 return false;
Richard Smith66f3ac92012-10-20 08:26:51 +0000336 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000337
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000338 // The failure was something other than an missing exception
Hans Wennborg39a509a2014-02-05 02:37:58 +0000339 // specification; return an error, except in MS mode where this is a warning.
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000340 if (!MissingExceptionSpecification)
Hans Wennborg39a509a2014-02-05 02:37:58 +0000341 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000342
Simon Pilgrim5fe64d22022-02-17 16:59:41 +0000343 const auto *NewProto = New->getType()->castAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +0000344
Douglas Gregorf40863c2010-02-12 07:32:17 +0000345 // The new function declaration is only missing an empty exception
346 // specification "throw()". If the throw() specification came from a
347 // function in a system header that has C linkage, just add an empty
Richard Smith836de6b2016-12-19 23:59:34 +0000348 // exception specification to the "new" declaration. Note that C library
349 // implementations are permitted to add these nothrow exception
350 // specifications.
351 //
352 // Likewise if the old function is a builtin.
Simon Pilgrim5fe64d22022-02-17 16:59:41 +0000353 if (MissingEmptyExceptionSpecification &&
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000354 (Old->getLocation().isInvalid() ||
Richard Smith836de6b2016-12-19 23:59:34 +0000355 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
356 Old->getBuiltinID()) &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000357 Old->isExternC()) {
Richard Smith8acb4282014-07-31 21:57:55 +0000358 New->setType(Context.getFunctionType(
359 NewProto->getReturnType(), NewProto->getParamTypes(),
360 NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
Douglas Gregorf40863c2010-02-12 07:32:17 +0000361 return false;
362 }
363
Simon Pilgrim5fe64d22022-02-17 16:59:41 +0000364 const auto *OldProto = Old->getType()->castAs<FunctionProtoType>();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000365
Richard Smith8acb4282014-07-31 21:57:55 +0000366 FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
367 if (ESI.Type == EST_Dynamic) {
Richard Smitheaf11ad2018-05-03 03:58:32 +0000368 // FIXME: What if the exceptions are described in terms of the old
369 // prototype's parameters?
Richard Smith8acb4282014-07-31 21:57:55 +0000370 ESI.Exceptions = OldProto->exceptions();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000371 }
372
Richard Smitheaf11ad2018-05-03 03:58:32 +0000373 if (ESI.Type == EST_NoexceptFalse)
374 ESI.Type = EST_None;
375 if (ESI.Type == EST_NoexceptTrue)
376 ESI.Type = EST_BasicNoexcept;
377
378 // For dependent noexcept, we can't just take the expression from the old
379 // prototype. It likely contains references to the old prototype's parameters.
380 if (ESI.Type == EST_DependentNoexcept) {
Richard Smitha91de372015-09-30 00:48:50 +0000381 New->setInvalidDecl();
382 } else {
383 // Update the type of the function with the appropriate exception
384 // specification.
385 New->setType(Context.getFunctionType(
386 NewProto->getReturnType(), NewProto->getParamTypes(),
387 NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
388 }
389
Amy Huang28d29772021-12-23 15:09:30 -0800390 if (getLangOpts().MSVCCompat && isDynamicExceptionSpec(ESI.Type)) {
391 DiagID = diag::ext_missing_exception_specification;
David Majnemer06ce8a42015-10-20 20:49:21 +0000392 ReturnValueOnError = false;
393 } else if (New->isReplaceableGlobalAllocationFunction() &&
Richard Smitheaf11ad2018-05-03 03:58:32 +0000394 ESI.Type != EST_DependentNoexcept) {
David Majnemer06ce8a42015-10-20 20:49:21 +0000395 // Allow missing exception specifications in redeclarations as an extension,
396 // when declaring a replaceable global allocation function.
Richard Smitha91de372015-09-30 00:48:50 +0000397 DiagID = diag::ext_missing_exception_specification;
398 ReturnValueOnError = false;
Erich Keane54182eb2019-05-31 14:26:19 +0000399 } else if (ESI.Type == EST_NoThrow) {
Amy Huang28d29772021-12-23 15:09:30 -0800400 // Don't emit any warning for missing 'nothrow' in MSVC.
401 if (getLangOpts().MSVCCompat) {
402 return false;
403 }
Erich Keane54182eb2019-05-31 14:26:19 +0000404 // Allow missing attribute 'nothrow' in redeclarations, since this is a very
405 // common omission.
406 DiagID = diag::ext_missing_exception_specification;
407 ReturnValueOnError = false;
Richard Smitha91de372015-09-30 00:48:50 +0000408 } else {
409 DiagID = diag::err_missing_exception_specification;
410 ReturnValueOnError = true;
411 }
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000412
413 // Warn about the lack of exception specification.
414 SmallString<128> ExceptionSpecString;
415 llvm::raw_svector_ostream OS(ExceptionSpecString);
416 switch (OldProto->getExceptionSpecType()) {
417 case EST_DynamicNone:
418 OS << "throw()";
419 break;
420
421 case EST_Dynamic: {
422 OS << "throw(";
423 bool OnFirstException = true;
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000424 for (const auto &E : OldProto->exceptions()) {
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000425 if (OnFirstException)
426 OnFirstException = false;
427 else
428 OS << ", ";
Fangrui Song6907ce22018-07-30 19:24:48 +0000429
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000430 OS << E.getAsString(getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000431 }
432 OS << ")";
433 break;
434 }
435
436 case EST_BasicNoexcept:
437 OS << "noexcept";
438 break;
439
Richard Smitheaf11ad2018-05-03 03:58:32 +0000440 case EST_DependentNoexcept:
441 case EST_NoexceptFalse:
442 case EST_NoexceptTrue:
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000443 OS << "noexcept(";
Richard Trieuddd01ce2014-06-09 22:53:25 +0000444 assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
Craig Topperc3ec1492014-05-26 06:22:03 +0000445 OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000446 OS << ")";
447 break;
Erich Keane54182eb2019-05-31 14:26:19 +0000448 case EST_NoThrow:
449 OS <<"__attribute__((nothrow))";
450 break;
Erich Keane68fa6dd2019-05-31 17:00:48 +0000451 case EST_None:
452 case EST_MSAny:
453 case EST_Unevaluated:
454 case EST_Uninstantiated:
455 case EST_Unparsed:
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000456 llvm_unreachable("This spec type is compatible with none.");
457 }
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000458
459 SourceLocation FixItLoc;
460 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
461 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Richard Smitha91de372015-09-30 00:48:50 +0000462 // FIXME: Preserve enough information so that we can produce a correct fixit
463 // location when there is a trailing return type.
464 if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
465 if (!FTLoc.getTypePtr()->hasTrailingReturn())
466 FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000467 }
468
469 if (FixItLoc.isInvalid())
Richard Smitha91de372015-09-30 00:48:50 +0000470 Diag(New->getLocation(), DiagID)
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000471 << New << OS.str();
472 else {
Richard Smitha91de372015-09-30 00:48:50 +0000473 Diag(New->getLocation(), DiagID)
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000474 << New << OS.str()
475 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
476 }
477
Yaron Keren8b563662015-10-03 10:46:20 +0000478 if (Old->getLocation().isValid())
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000479 Diag(Old->getLocation(), diag::note_previous_declaration);
480
Richard Smitha91de372015-09-30 00:48:50 +0000481 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000482}
483
Sebastian Redl4915e632009-10-11 09:03:14 +0000484bool Sema::CheckEquivalentExceptionSpec(
485 const FunctionProtoType *Old, SourceLocation OldLoc,
486 const FunctionProtoType *New, SourceLocation NewLoc) {
Richard Smith13b40bc2016-11-30 00:13:55 +0000487 if (!getLangOpts().CXXExceptions)
488 return false;
489
Francois Pichet13b4e682011-03-19 23:05:18 +0000490 unsigned DiagID = diag::err_mismatched_exception_spec;
Reid Kleckner39aa8952019-08-27 17:52:03 +0000491 if (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +0000492 DiagID = diag::ext_mismatched_exception_spec;
Richard Smith13b40bc2016-11-30 00:13:55 +0000493 bool Result = CheckEquivalentExceptionSpecImpl(
494 *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
495 Old, OldLoc, New, NewLoc);
Hans Wennborg39a509a2014-02-05 02:37:58 +0000496
497 // In Microsoft mode, mismatching exception specifications just cause a warning.
Reid Kleckner39aa8952019-08-27 17:52:03 +0000498 if (getLangOpts().MSVCCompat)
Hans Wennborg39a509a2014-02-05 02:37:58 +0000499 return false;
500 return Result;
Sebastian Redl4915e632009-10-11 09:03:14 +0000501}
502
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000503/// CheckEquivalentExceptionSpec - Check if the two types have compatible
504/// exception specifications. See C++ [except.spec]p3.
Richard Smith66f3ac92012-10-20 08:26:51 +0000505///
506/// \return \c false if the exception specifications match, \c true if there is
507/// a problem. If \c true is returned, either a diagnostic has already been
508/// produced or \c *MissingExceptionSpecification is set to \c true.
Richard Smith13b40bc2016-11-30 00:13:55 +0000509static bool CheckEquivalentExceptionSpecImpl(
510 Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
511 const FunctionProtoType *Old, SourceLocation OldLoc,
512 const FunctionProtoType *New, SourceLocation NewLoc,
513 bool *MissingExceptionSpecification,
514 bool *MissingEmptyExceptionSpecification,
515 bool AllowNoexceptAllMatchWithNoSpec, bool IsOperatorNew) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000516 if (MissingExceptionSpecification)
517 *MissingExceptionSpecification = false;
518
Douglas Gregorf40863c2010-02-12 07:32:17 +0000519 if (MissingEmptyExceptionSpecification)
520 *MissingEmptyExceptionSpecification = false;
521
Richard Smith13b40bc2016-11-30 00:13:55 +0000522 Old = S.ResolveExceptionSpec(NewLoc, Old);
Richard Smithf623c962012-04-17 00:58:00 +0000523 if (!Old)
524 return false;
Richard Smith13b40bc2016-11-30 00:13:55 +0000525 New = S.ResolveExceptionSpec(NewLoc, New);
Richard Smithf623c962012-04-17 00:58:00 +0000526 if (!New)
527 return false;
528
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000529 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
530 // - both are non-throwing, regardless of their form,
531 // - both have the form noexcept(constant-expression) and the constant-
532 // expressions are equivalent,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000533 // - both are dynamic-exception-specifications that have the same set of
534 // adjusted types.
535 //
Eric Christophere6b7cf42015-07-10 18:25:52 +0000536 // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000537 // of the form throw(), noexcept, or noexcept(constant-expression) where the
538 // constant-expression yields true.
539 //
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000540 // C++0x [except.spec]p4: If any declaration of a function has an exception-
541 // specifier that is not a noexcept-specification allowing all exceptions,
542 // all declarations [...] of that function shall have a compatible
543 // exception-specification.
544 //
545 // That last point basically means that noexcept(false) matches no spec.
546 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
547
548 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
549 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
550
Richard Smithd3b5c9082012-07-27 04:22:15 +0000551 assert(!isUnresolvedExceptionSpec(OldEST) &&
552 !isUnresolvedExceptionSpec(NewEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000553 "Shouldn't see unknown exception specifications here");
554
Richard Smitheaf11ad2018-05-03 03:58:32 +0000555 CanThrowResult OldCanThrow = Old->canThrow();
556 CanThrowResult NewCanThrow = New->canThrow();
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000557
558 // Any non-throwing specifications are compatible.
Richard Smitheaf11ad2018-05-03 03:58:32 +0000559 if (OldCanThrow == CT_Cannot && NewCanThrow == CT_Cannot)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000560 return false;
561
Richard Smitheaf11ad2018-05-03 03:58:32 +0000562 // Any throws-anything specifications are usually compatible.
563 if (OldCanThrow == CT_Can && OldEST != EST_Dynamic &&
564 NewCanThrow == CT_Can && NewEST != EST_Dynamic) {
565 // The exception is that the absence of an exception specification only
566 // matches noexcept(false) for functions, as described above.
567 if (!AllowNoexceptAllMatchWithNoSpec &&
568 ((OldEST == EST_None && NewEST == EST_NoexceptFalse) ||
569 (OldEST == EST_NoexceptFalse && NewEST == EST_None))) {
570 // This is the disallowed case.
571 } else {
572 return false;
573 }
574 }
575
Richard Smithb64764a2018-07-12 21:11:25 +0000576 // C++14 [except.spec]p3:
577 // Two exception-specifications are compatible if [...] both have the form
578 // noexcept(constant-expression) and the constant-expressions are equivalent
579 if (OldEST == EST_DependentNoexcept && NewEST == EST_DependentNoexcept) {
580 llvm::FoldingSetNodeID OldFSN, NewFSN;
581 Old->getNoexceptExpr()->Profile(OldFSN, S.Context, true);
582 New->getNoexceptExpr()->Profile(NewFSN, S.Context, true);
583 if (OldFSN == NewFSN)
584 return false;
585 }
Richard Smitheaf11ad2018-05-03 03:58:32 +0000586
587 // Dynamic exception specifications with the same set of adjusted types
588 // are compatible.
589 if (OldEST == EST_Dynamic && NewEST == EST_Dynamic) {
590 bool Success = true;
591 // Both have a dynamic exception spec. Collect the first set, then compare
592 // to the second.
593 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
594 for (const auto &I : Old->exceptions())
595 OldTypes.insert(S.Context.getCanonicalType(I).getUnqualifiedType());
596
597 for (const auto &I : New->exceptions()) {
598 CanQualType TypePtr = S.Context.getCanonicalType(I).getUnqualifiedType();
599 if (OldTypes.count(TypePtr))
600 NewTypes.insert(TypePtr);
601 else {
602 Success = false;
603 break;
604 }
605 }
606
607 if (Success && OldTypes.size() == NewTypes.size())
608 return false;
609 }
610
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000611 // As a special compatibility feature, under C++0x we accept no spec and
612 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
613 // This is because the implicit declaration changed, but old code would break.
Richard Smith13b40bc2016-11-30 00:13:55 +0000614 if (S.getLangOpts().CPlusPlus11 && IsOperatorNew) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000615 const FunctionProtoType *WithExceptions = nullptr;
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000616 if (OldEST == EST_None && NewEST == EST_Dynamic)
617 WithExceptions = New;
618 else if (OldEST == EST_Dynamic && NewEST == EST_None)
619 WithExceptions = Old;
620 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
621 // One has no spec, the other throw(something). If that something is
622 // std::bad_alloc, all conditions are met.
623 QualType Exception = *WithExceptions->exception_begin();
624 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
625 IdentifierInfo* Name = ExRecord->getIdentifier();
626 if (Name && Name->getName() == "bad_alloc") {
627 // It's called bad_alloc, but is it in std?
Richard Trieuc771d5d2014-05-28 02:16:01 +0000628 if (ExRecord->isInStdNamespace()) {
629 return false;
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000630 }
631 }
632 }
633 }
634 }
635
Richard Smitheaf11ad2018-05-03 03:58:32 +0000636 // If the caller wants to handle the case that the new function is
637 // incompatible due to a missing exception specification, let it.
638 if (MissingExceptionSpecification && OldEST != EST_None &&
639 NewEST == EST_None) {
640 // The old type has an exception specification of some sort, but
641 // the new type does not.
642 *MissingExceptionSpecification = true;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000643
Richard Smitheaf11ad2018-05-03 03:58:32 +0000644 if (MissingEmptyExceptionSpecification && OldCanThrow == CT_Cannot) {
645 // The old type has a throw() or noexcept(true) exception specification
646 // and the new type has no exception specification, and the caller asked
647 // to handle this itself.
648 *MissingEmptyExceptionSpecification = true;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000649 }
650
Sebastian Redl4915e632009-10-11 09:03:14 +0000651 return true;
652 }
653
Richard Smith13b40bc2016-11-30 00:13:55 +0000654 S.Diag(NewLoc, DiagID);
David Majnemer7da23022015-02-19 07:28:55 +0000655 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Richard Smith13b40bc2016-11-30 00:13:55 +0000656 S.Diag(OldLoc, NoteID);
Sebastian Redl4915e632009-10-11 09:03:14 +0000657 return true;
658}
659
Richard Smith13b40bc2016-11-30 00:13:55 +0000660bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
661 const PartialDiagnostic &NoteID,
662 const FunctionProtoType *Old,
663 SourceLocation OldLoc,
664 const FunctionProtoType *New,
665 SourceLocation NewLoc) {
666 if (!getLangOpts().CXXExceptions)
667 return false;
668 return CheckEquivalentExceptionSpecImpl(*this, DiagID, NoteID, Old, OldLoc,
669 New, NewLoc);
670}
671
Richard Smith56ae0a62018-01-13 05:05:45 +0000672bool Sema::handlerCanCatch(QualType HandlerType, QualType ExceptionType) {
673 // [except.handle]p3:
674 // A handler is a match for an exception object of type E if:
675
676 // HandlerType must be ExceptionType or derived from it, or pointer or
677 // reference to such types.
678 const ReferenceType *RefTy = HandlerType->getAs<ReferenceType>();
679 if (RefTy)
680 HandlerType = RefTy->getPointeeType();
681
682 // -- the handler is of type cv T or cv T& and E and T are the same type
683 if (Context.hasSameUnqualifiedType(ExceptionType, HandlerType))
684 return true;
685
686 // FIXME: ObjC pointer types?
687 if (HandlerType->isPointerType() || HandlerType->isMemberPointerType()) {
688 if (RefTy && (!HandlerType.isConstQualified() ||
689 HandlerType.isVolatileQualified()))
690 return false;
691
692 // -- the handler is of type cv T or const T& where T is a pointer or
693 // pointer to member type and E is std::nullptr_t
694 if (ExceptionType->isNullPtrType())
695 return true;
696
697 // -- the handler is of type cv T or const T& where T is a pointer or
698 // pointer to member type and E is a pointer or pointer to member type
699 // that can be converted to T by one or more of
700 // -- a qualification conversion
701 // -- a function pointer conversion
702 bool LifetimeConv;
703 QualType Result;
704 // FIXME: Should we treat the exception as catchable if a lifetime
705 // conversion is required?
706 if (IsQualificationConversion(ExceptionType, HandlerType, false,
707 LifetimeConv) ||
708 IsFunctionConversion(ExceptionType, HandlerType, Result))
709 return true;
710
711 // -- a standard pointer conversion [...]
712 if (!ExceptionType->isPointerType() || !HandlerType->isPointerType())
713 return false;
714
715 // Handle the "qualification conversion" portion.
716 Qualifiers EQuals, HQuals;
717 ExceptionType = Context.getUnqualifiedArrayType(
718 ExceptionType->getPointeeType(), EQuals);
Joseph Huberb9d678d2024-11-15 06:58:36 -0600719 HandlerType =
720 Context.getUnqualifiedArrayType(HandlerType->getPointeeType(), HQuals);
721 if (!HQuals.compatiblyIncludes(EQuals, getASTContext()))
Richard Smith56ae0a62018-01-13 05:05:45 +0000722 return false;
723
724 if (HandlerType->isVoidType() && ExceptionType->isObjectType())
725 return true;
726
727 // The only remaining case is a derived-to-base conversion.
728 }
729
730 // -- the handler is of type cg T or cv T& and T is an unambiguous public
731 // base class of E
732 if (!ExceptionType->isRecordType() || !HandlerType->isRecordType())
733 return false;
734 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
735 /*DetectVirtual=*/false);
736 if (!IsDerivedFrom(SourceLocation(), ExceptionType, HandlerType, Paths) ||
737 Paths.isAmbiguous(Context.getCanonicalType(HandlerType)))
738 return false;
739
740 // Do this check from a context without privileges.
741 switch (CheckBaseClassAccess(SourceLocation(), HandlerType, ExceptionType,
742 Paths.front(),
743 /*Diagnostic*/ 0,
744 /*ForceCheck*/ true,
745 /*ForceUnprivileged*/ true)) {
746 case AR_accessible: return true;
747 case AR_inaccessible: return false;
748 case AR_dependent:
749 llvm_unreachable("access check dependent for unprivileged context");
750 case AR_delayed:
751 llvm_unreachable("access check delayed in non-declaration");
752 }
753 llvm_unreachable("unexpected access check result");
754}
755
Corentin Jabotaf475172022-01-27 13:55:08 +0100756bool Sema::CheckExceptionSpecSubset(
757 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
758 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
759 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
760 SourceLocation SuperLoc, const FunctionProtoType *Subset,
761 bool SkipSubsetFirstParameter, SourceLocation SubLoc) {
John McCallf9c94092010-05-28 08:37:35 +0000762
763 // Just auto-succeed under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000764 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000765 return false;
766
Sebastian Redl4915e632009-10-11 09:03:14 +0000767 // FIXME: As usual, we could be more specific in our error messages, but
768 // that better waits until we've got types with source locations.
769
770 if (!SubLoc.isValid())
771 SubLoc = SuperLoc;
772
Richard Smithf623c962012-04-17 00:58:00 +0000773 // Resolve the exception specifications, if needed.
774 Superset = ResolveExceptionSpec(SuperLoc, Superset);
775 if (!Superset)
776 return false;
777 Subset = ResolveExceptionSpec(SubLoc, Subset);
778 if (!Subset)
779 return false;
780
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000781 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
Richard Smitheaf11ad2018-05-03 03:58:32 +0000782 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
783 assert(!isUnresolvedExceptionSpec(SuperEST) &&
784 !isUnresolvedExceptionSpec(SubEST) &&
785 "Shouldn't see unknown exception specifications here");
Sebastian Redl4915e632009-10-11 09:03:14 +0000786
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000787 // If there are dependent noexcept specs, assume everything is fine. Unlike
788 // with the equivalency check, this is safe in this case, because we don't
789 // want to merge declarations. Checks after instantiation will catch any
790 // omissions we make here.
Richard Smitheaf11ad2018-05-03 03:58:32 +0000791 if (SuperEST == EST_DependentNoexcept || SubEST == EST_DependentNoexcept)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000792 return false;
793
Richard Smitheaf11ad2018-05-03 03:58:32 +0000794 CanThrowResult SuperCanThrow = Superset->canThrow();
795 CanThrowResult SubCanThrow = Subset->canThrow();
796
797 // If the superset contains everything or the subset contains nothing, we're
798 // done.
799 if ((SuperCanThrow == CT_Can && SuperEST != EST_Dynamic) ||
800 SubCanThrow == CT_Cannot)
Corentin Jabotaf475172022-01-27 13:55:08 +0100801 return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset,
802 SkipSupersetFirstParameter, SuperLoc, Subset,
803 SkipSubsetFirstParameter, SubLoc);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000804
Erich Keane81ef6252019-06-03 18:36:26 +0000805 // Allow __declspec(nothrow) to be missing on redeclaration as an extension in
806 // some cases.
807 if (NoThrowDiagID.getDiagID() != 0 && SubCanThrow == CT_Can &&
808 SuperCanThrow == CT_Cannot && SuperEST == EST_NoThrow) {
809 Diag(SubLoc, NoThrowDiagID);
810 if (NoteID.getDiagID() != 0)
811 Diag(SuperLoc, NoteID);
812 return true;
813 }
814
Richard Smitheaf11ad2018-05-03 03:58:32 +0000815 // If the subset contains everything or the superset contains nothing, we've
816 // failed.
817 if ((SubCanThrow == CT_Can && SubEST != EST_Dynamic) ||
818 SuperCanThrow == CT_Cannot) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000819 Diag(SubLoc, DiagID);
820 if (NoteID.getDiagID() != 0)
821 Diag(SuperLoc, NoteID);
822 return true;
823 }
824
825 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
826 "Exception spec subset: non-dynamic case slipped through.");
827
828 // Neither contains everything or nothing. Do a proper comparison.
Richard Smith56ae0a62018-01-13 05:05:45 +0000829 for (QualType SubI : Subset->exceptions()) {
830 if (const ReferenceType *RefTy = SubI->getAs<ReferenceType>())
831 SubI = RefTy->getPointeeType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000832
Sebastian Redl4915e632009-10-11 09:03:14 +0000833 // Make sure it's in the superset.
Richard Smith56ae0a62018-01-13 05:05:45 +0000834 bool Contained = false;
835 for (QualType SuperI : Superset->exceptions()) {
836 // [except.spec]p5:
837 // the target entity shall allow at least the exceptions allowed by the
838 // source
839 //
840 // We interpret this as meaning that a handler for some target type would
841 // catch an exception of each source type.
842 if (handlerCanCatch(SuperI, SubI)) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000843 Contained = true;
844 break;
845 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000846 }
847 if (!Contained) {
848 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000849 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000850 Diag(SuperLoc, NoteID);
851 return true;
852 }
853 }
854 // We've run half the gauntlet.
Corentin Jabotaf475172022-01-27 13:55:08 +0100855 return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset,
856 SkipSupersetFirstParameter, SuperLoc, Subset,
857 SkipSupersetFirstParameter, SubLoc);
Sebastian Redl4915e632009-10-11 09:03:14 +0000858}
859
Richard Smith1be59c52016-10-22 01:32:19 +0000860static bool
861CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID,
862 const PartialDiagnostic &NoteID, QualType Target,
863 SourceLocation TargetLoc, QualType Source,
864 SourceLocation SourceLoc) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000865 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
866 if (!TFunc)
867 return false;
868 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
869 if (!SFunc)
870 return false;
871
872 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
873 SFunc, SourceLoc);
874}
875
Corentin Jabotaf475172022-01-27 13:55:08 +0100876bool Sema::CheckParamExceptionSpec(
877 const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
878 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
879 SourceLocation TargetLoc, const FunctionProtoType *Source,
880 bool SkipSourceFirstParameter, SourceLocation SourceLoc) {
Richard Smith1be59c52016-10-22 01:32:19 +0000881 auto RetDiag = DiagID;
882 RetDiag << 0;
Alp Toker314cc812014-01-25 16:55:45 +0000883 if (CheckSpecForTypesEquivalent(
Richard Smith1be59c52016-10-22 01:32:19 +0000884 *this, RetDiag, PDiag(),
Alp Toker314cc812014-01-25 16:55:45 +0000885 Target->getReturnType(), TargetLoc, Source->getReturnType(),
886 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000887 return true;
888
Sebastian Redla44822f2009-10-14 16:09:29 +0000889 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redl4915e632009-10-11 09:03:14 +0000890 // compatible.
Corentin Jabotaf475172022-01-27 13:55:08 +0100891 assert((Target->getNumParams() - (unsigned)SkipTargetFirstParameter) ==
892 (Source->getNumParams() - (unsigned)SkipSourceFirstParameter) &&
Sebastian Redl4915e632009-10-11 09:03:14 +0000893 "Functions have different argument counts.");
Alp Toker9cacbab2014-01-20 20:26:09 +0000894 for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
Richard Smith1be59c52016-10-22 01:32:19 +0000895 auto ParamDiag = DiagID;
896 ParamDiag << 1;
Alp Toker9cacbab2014-01-20 20:26:09 +0000897 if (CheckSpecForTypesEquivalent(
Richard Smith1be59c52016-10-22 01:32:19 +0000898 *this, ParamDiag, PDiag(),
Corentin Jabotaf475172022-01-27 13:55:08 +0100899 Target->getParamType(i + (SkipTargetFirstParameter ? 1 : 0)),
900 TargetLoc, Source->getParamType(SkipSourceFirstParameter ? 1 : 0),
Alp Toker9cacbab2014-01-20 20:26:09 +0000901 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000902 return true;
903 }
904 return false;
905}
906
Richard Smith2e321552014-11-12 02:00:47 +0000907bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000908 // First we check for applicability.
909 // Target type must be a function, function pointer or function reference.
910 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
Richard Smith2e321552014-11-12 02:00:47 +0000911 if (!ToFunc || ToFunc->hasDependentExceptionSpec())
Sebastian Redl4915e632009-10-11 09:03:14 +0000912 return false;
913
914 // SourceType must be a function or function pointer.
915 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
Richard Smith2e321552014-11-12 02:00:47 +0000916 if (!FromFunc || FromFunc->hasDependentExceptionSpec())
Sebastian Redl4915e632009-10-11 09:03:14 +0000917 return false;
918
Richard Smith1be59c52016-10-22 01:32:19 +0000919 unsigned DiagID = diag::err_incompatible_exception_specs;
920 unsigned NestedDiagID = diag::err_deep_exception_specs_differ;
921 // This is not an error in C++17 onwards, unless the noexceptness doesn't
922 // match, but in that case we have a full-on type mismatch, not just a
923 // type sugar mismatch.
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000924 if (getLangOpts().CPlusPlus17) {
Richard Smith1be59c52016-10-22 01:32:19 +0000925 DiagID = diag::warn_incompatible_exception_specs;
926 NestedDiagID = diag::warn_deep_exception_specs_differ;
927 }
928
Sebastian Redl4915e632009-10-11 09:03:14 +0000929 // Now we've got the correct types on both sides, check their compatibility.
930 // This means that the source of the conversion can only throw a subset of
931 // the exceptions of the target, and any exception specs on arguments or
932 // return types must be equivalent.
Richard Smith2e321552014-11-12 02:00:47 +0000933 //
934 // FIXME: If there is a nested dependent exception specification, we should
935 // not be checking it here. This is fine:
936 // template<typename T> void f() {
937 // void (*p)(void (*) throw(T));
938 // void (*q)(void (*) throw(int)) = p;
939 // }
940 // ... because it might be instantiated with T=int.
Corentin Jabotaf475172022-01-27 13:55:08 +0100941 return CheckExceptionSpecSubset(PDiag(DiagID), PDiag(NestedDiagID), PDiag(),
942 PDiag(), ToFunc, 0,
943 From->getSourceRange().getBegin(), FromFunc,
944 0, SourceLocation()) &&
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000945 !getLangOpts().CPlusPlus17;
Sebastian Redl4915e632009-10-11 09:03:14 +0000946}
947
948bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
949 const CXXMethodDecl *Old) {
Richard Smith88f45492014-11-22 03:09:05 +0000950 // If the new exception specification hasn't been parsed yet, skip the check.
951 // We'll get called again once it's been parsed.
952 if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
953 EST_Unparsed)
954 return false;
Richard Smith5159bbad2018-09-05 22:30:37 +0000955
956 // Don't check uninstantiated template destructors at all. We can only
957 // synthesize correct specs after the template is instantiated.
958 if (isa<CXXDestructorDecl>(New) && New->getParent()->isDependentType())
959 return false;
960
961 // If the old exception specification hasn't been parsed yet, or the new
962 // exception specification can't be computed yet, remember that we need to
963 // perform this check when we get to the end of the outermost
Richard Smith88f45492014-11-22 03:09:05 +0000964 // lexically-surrounding class.
Richard Smith5159bbad2018-09-05 22:30:37 +0000965 if (exceptionSpecNotKnownYet(Old) || exceptionSpecNotKnownYet(New)) {
966 DelayedOverridingExceptionSpecChecks.push_back({New, Old});
Richard Smith0b3a4622014-11-13 20:01:57 +0000967 return false;
Richard Smith88f45492014-11-22 03:09:05 +0000968 }
Richard Smith5159bbad2018-09-05 22:30:37 +0000969
Francois Picheta8032e92011-05-24 02:11:43 +0000970 unsigned DiagID = diag::err_override_exception_spec;
Reid Kleckner39aa8952019-08-27 17:52:03 +0000971 if (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +0000972 DiagID = diag::ext_override_exception_spec;
Corentin Jabotaf475172022-01-27 13:55:08 +0100973 return CheckExceptionSpecSubset(
974 PDiag(DiagID), PDiag(diag::err_deep_exception_specs_differ),
975 PDiag(diag::note_overridden_virtual_function),
976 PDiag(diag::ext_override_exception_spec),
977 Old->getType()->castAs<FunctionProtoType>(),
978 Old->hasCXXExplicitFunctionObjectParameter(), Old->getLocation(),
979 New->getType()->castAs<FunctionProtoType>(),
980 New->hasCXXExplicitFunctionObjectParameter(), New->getLocation());
Sebastian Redl4915e632009-10-11 09:03:14 +0000981}
982
Richard Smithfbf60b72019-12-13 14:10:13 -0800983static CanThrowResult canSubStmtsThrow(Sema &Self, const Stmt *S) {
Richard Smithf623c962012-04-17 00:58:00 +0000984 CanThrowResult R = CT_Cannot;
Richard Smithfbf60b72019-12-13 14:10:13 -0800985 for (const Stmt *SubStmt : S->children()) {
986 if (!SubStmt)
987 continue;
988 R = mergeCanThrow(R, Self.canThrow(SubStmt));
Benjamin Kramer642f1732015-07-02 21:03:14 +0000989 if (R == CT_Can)
990 break;
991 }
Richard Smithf623c962012-04-17 00:58:00 +0000992 return R;
993}
994
Xun Li516803d2020-06-15 16:27:41 -0700995CanThrowResult Sema::canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
996 SourceLocation Loc) {
Richard Smithf623c962012-04-17 00:58:00 +0000997 // As an extension, we assume that __attribute__((nothrow)) functions don't
998 // throw.
ZERO-N28e30b42024-03-07 00:07:15 +0800999 if (isa_and_nonnull<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
Richard Smithf623c962012-04-17 00:58:00 +00001000 return CT_Cannot;
1001
Richard Smith3a8f13a2016-12-03 00:29:06 +00001002 QualType T;
1003
1004 // In C++1z, just look at the function type of the callee.
ZERO-N28e30b42024-03-07 00:07:15 +08001005 if (S.getLangOpts().CPlusPlus17 && isa_and_nonnull<CallExpr>(E)) {
Richard Smith3a8f13a2016-12-03 00:29:06 +00001006 E = cast<CallExpr>(E)->getCallee();
1007 T = E->getType();
1008 if (T->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1009 // Sadly we don't preserve the actual type as part of the "bound member"
1010 // placeholder, so we need to reconstruct it.
1011 E = E->IgnoreParenImpCasts();
1012
1013 // Could be a call to a pointer-to-member or a plain member access.
1014 if (auto *Op = dyn_cast<BinaryOperator>(E)) {
1015 assert(Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI);
1016 T = Op->getRHS()->getType()
1017 ->castAs<MemberPointerType>()->getPointeeType();
1018 } else {
1019 T = cast<MemberExpr>(E)->getMemberDecl()->getType();
1020 }
1021 }
1022 } else if (const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D))
1023 T = VD->getType();
1024 else
1025 // If we have no clue what we're calling, assume the worst.
1026 return CT_Can;
1027
Richard Smithf623c962012-04-17 00:58:00 +00001028 const FunctionProtoType *FT;
1029 if ((FT = T->getAs<FunctionProtoType>())) {
1030 } else if (const PointerType *PT = T->getAs<PointerType>())
1031 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1032 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1033 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1034 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1035 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1036 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1037 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1038
1039 if (!FT)
1040 return CT_Can;
1041
Xun Li516803d2020-06-15 16:27:41 -07001042 if (Loc.isValid() || (Loc.isInvalid() && E))
1043 FT = S.ResolveExceptionSpec(Loc.isInvalid() ? E->getBeginLoc() : Loc, FT);
Richard Smithf623c962012-04-17 00:58:00 +00001044 if (!FT)
1045 return CT_Can;
1046
Richard Smitheaf11ad2018-05-03 03:58:32 +00001047 return FT->canThrow();
Richard Smithf623c962012-04-17 00:58:00 +00001048}
1049
Richard Smithfbf60b72019-12-13 14:10:13 -08001050static CanThrowResult canVarDeclThrow(Sema &Self, const VarDecl *VD) {
1051 CanThrowResult CT = CT_Cannot;
1052
1053 // Initialization might throw.
1054 if (!VD->isUsableInConstantExpressions(Self.Context))
1055 if (const Expr *Init = VD->getInit())
1056 CT = mergeCanThrow(CT, Self.canThrow(Init));
1057
1058 // Destructor might throw.
1059 if (VD->needsDestruction(Self.Context) == QualType::DK_cxx_destructor) {
1060 if (auto *RD =
1061 VD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
1062 if (auto *Dtor = RD->getDestructor()) {
1063 CT = mergeCanThrow(
Xun Li516803d2020-06-15 16:27:41 -07001064 CT, Sema::canCalleeThrow(Self, nullptr, Dtor, VD->getLocation()));
Richard Smithfbf60b72019-12-13 14:10:13 -08001065 }
1066 }
1067 }
1068
1069 // If this is a decomposition declaration, bindings might throw.
1070 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
Jason Riceabc88122025-01-29 12:43:52 -08001071 for (auto *B : DD->flat_bindings())
Richard Smithfbf60b72019-12-13 14:10:13 -08001072 if (auto *HD = B->getHoldingVar())
1073 CT = mergeCanThrow(CT, canVarDeclThrow(Self, HD));
1074
1075 return CT;
1076}
1077
Richard Smithf623c962012-04-17 00:58:00 +00001078static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1079 if (DC->isTypeDependent())
1080 return CT_Dependent;
1081
1082 if (!DC->getTypeAsWritten()->isReferenceType())
1083 return CT_Cannot;
1084
1085 if (DC->getSubExpr()->isTypeDependent())
1086 return CT_Dependent;
1087
1088 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
1089}
1090
1091static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
Mital Ashokb608b222024-06-20 14:43:14 +01001092 // A typeid of a type is a constant and does not throw.
Richard Smithf623c962012-04-17 00:58:00 +00001093 if (DC->isTypeOperand())
1094 return CT_Cannot;
1095
Mital Ashok3ad31e12024-06-17 18:31:54 +01001096 if (DC->isValueDependent())
Richard Smithf623c962012-04-17 00:58:00 +00001097 return CT_Dependent;
1098
Mital Ashokb608b222024-06-20 14:43:14 +01001099 // If this operand is not evaluated it cannot possibly throw.
1100 if (!DC->isPotentiallyEvaluated())
1101 return CT_Cannot;
1102
1103 // Can throw std::bad_typeid if a nullptr is dereferenced.
1104 if (DC->hasNullCheck())
1105 return CT_Can;
1106
1107 return S.canThrow(DC->getExprOperand());
Richard Smithf623c962012-04-17 00:58:00 +00001108}
1109
Richard Smithfbf60b72019-12-13 14:10:13 -08001110CanThrowResult Sema::canThrow(const Stmt *S) {
Richard Smithf623c962012-04-17 00:58:00 +00001111 // C++ [expr.unary.noexcept]p3:
1112 // [Can throw] if in a potentially-evaluated context the expression would
1113 // contain:
Richard Smithfbf60b72019-12-13 14:10:13 -08001114 switch (S->getStmtClass()) {
Bill Wendling7c44da22018-10-31 03:48:47 +00001115 case Expr::ConstantExprClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001116 return canThrow(cast<ConstantExpr>(S)->getSubExpr());
Bill Wendling7c44da22018-10-31 03:48:47 +00001117
Richard Smithf623c962012-04-17 00:58:00 +00001118 case Expr::CXXThrowExprClass:
1119 // - a potentially evaluated throw-expression
1120 return CT_Can;
1121
1122 case Expr::CXXDynamicCastExprClass: {
1123 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1124 // where T is a reference type, that requires a run-time check
Richard Smithfbf60b72019-12-13 14:10:13 -08001125 auto *CE = cast<CXXDynamicCastExpr>(S);
1126 // FIXME: Properly determine whether a variably-modified type can throw.
1127 if (CE->getType()->isVariablyModifiedType())
1128 return CT_Can;
1129 CanThrowResult CT = canDynamicCastThrow(CE);
Richard Smithf623c962012-04-17 00:58:00 +00001130 if (CT == CT_Can)
1131 return CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001132 return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
Richard Smithf623c962012-04-17 00:58:00 +00001133 }
1134
1135 case Expr::CXXTypeidExprClass:
Mital Ashok3ad31e12024-06-17 18:31:54 +01001136 // - a potentially evaluated typeid expression applied to a (possibly
1137 // parenthesized) built-in unary * operator applied to a pointer to a
1138 // polymorphic class type
Richard Smithfbf60b72019-12-13 14:10:13 -08001139 return canTypeidThrow(*this, cast<CXXTypeidExpr>(S));
Richard Smithf623c962012-04-17 00:58:00 +00001140
1141 // - a potentially evaluated call to a function, member function, function
1142 // pointer, or member function pointer that does not have a non-throwing
1143 // exception-specification
1144 case Expr::CallExprClass:
1145 case Expr::CXXMemberCallExprClass:
1146 case Expr::CXXOperatorCallExprClass:
1147 case Expr::UserDefinedLiteralClass: {
Richard Smithfbf60b72019-12-13 14:10:13 -08001148 const CallExpr *CE = cast<CallExpr>(S);
Richard Smithf623c962012-04-17 00:58:00 +00001149 CanThrowResult CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001150 if (CE->isTypeDependent())
Richard Smithf623c962012-04-17 00:58:00 +00001151 CT = CT_Dependent;
1152 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
1153 CT = CT_Cannot;
Eli Friedman5a8738f2013-06-25 01:55:41 +00001154 else
Richard Smithfbf60b72019-12-13 14:10:13 -08001155 CT = canCalleeThrow(*this, CE, CE->getCalleeDecl());
Richard Smithf623c962012-04-17 00:58:00 +00001156 if (CT == CT_Can)
1157 return CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001158 return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
Richard Smithf623c962012-04-17 00:58:00 +00001159 }
1160
1161 case Expr::CXXConstructExprClass:
1162 case Expr::CXXTemporaryObjectExprClass: {
Richard Smithfbf60b72019-12-13 14:10:13 -08001163 auto *CE = cast<CXXConstructExpr>(S);
1164 // FIXME: Properly determine whether a variably-modified type can throw.
1165 if (CE->getType()->isVariablyModifiedType())
1166 return CT_Can;
1167 CanThrowResult CT = canCalleeThrow(*this, CE, CE->getConstructor());
Richard Smithf623c962012-04-17 00:58:00 +00001168 if (CT == CT_Can)
1169 return CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001170 return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
Richard Smithf623c962012-04-17 00:58:00 +00001171 }
1172
Richard Smithfbf60b72019-12-13 14:10:13 -08001173 case Expr::CXXInheritedCtorInitExprClass: {
1174 auto *ICIE = cast<CXXInheritedCtorInitExpr>(S);
1175 return canCalleeThrow(*this, ICIE, ICIE->getConstructor());
1176 }
Richard Smith5179eb72016-06-28 19:03:57 +00001177
Richard Smithf623c962012-04-17 00:58:00 +00001178 case Expr::LambdaExprClass: {
Richard Smithfbf60b72019-12-13 14:10:13 -08001179 const LambdaExpr *Lambda = cast<LambdaExpr>(S);
Richard Smithf623c962012-04-17 00:58:00 +00001180 CanThrowResult CT = CT_Cannot;
James Y Knight53c76162015-07-17 18:21:37 +00001181 for (LambdaExpr::const_capture_init_iterator
1182 Cap = Lambda->capture_init_begin(),
1183 CapEnd = Lambda->capture_init_end();
Richard Smithf623c962012-04-17 00:58:00 +00001184 Cap != CapEnd; ++Cap)
1185 CT = mergeCanThrow(CT, canThrow(*Cap));
1186 return CT;
1187 }
1188
1189 case Expr::CXXNewExprClass: {
Richard Smithfbf60b72019-12-13 14:10:13 -08001190 auto *NE = cast<CXXNewExpr>(S);
Richard Smithf623c962012-04-17 00:58:00 +00001191 CanThrowResult CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001192 if (NE->isTypeDependent())
Richard Smithf623c962012-04-17 00:58:00 +00001193 CT = CT_Dependent;
1194 else
Richard Smithfbf60b72019-12-13 14:10:13 -08001195 CT = canCalleeThrow(*this, NE, NE->getOperatorNew());
Richard Smithf623c962012-04-17 00:58:00 +00001196 if (CT == CT_Can)
1197 return CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001198 return mergeCanThrow(CT, canSubStmtsThrow(*this, NE));
Richard Smithf623c962012-04-17 00:58:00 +00001199 }
1200
1201 case Expr::CXXDeleteExprClass: {
Richard Smithfbf60b72019-12-13 14:10:13 -08001202 auto *DE = cast<CXXDeleteExpr>(S);
Aaron Ballman5ff7f472025-01-09 08:29:19 -05001203 CanThrowResult CT = CT_Cannot;
Richard Smithfbf60b72019-12-13 14:10:13 -08001204 QualType DTy = DE->getDestroyedType();
Richard Smithf623c962012-04-17 00:58:00 +00001205 if (DTy.isNull() || DTy->isDependentType()) {
1206 CT = CT_Dependent;
1207 } else {
Aaron Ballman5ff7f472025-01-09 08:29:19 -05001208 // C++20 [expr.delete]p6: If the value of the operand of the delete-
1209 // expression is not a null pointer value and the selected deallocation
1210 // function (see below) is not a destroying operator delete, the delete-
1211 // expression will invoke the destructor (if any) for the object or the
1212 // elements of the array being deleted.
Aaron Ballman91354fb2024-12-05 14:26:33 -05001213 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
Aaron Ballman5ff7f472025-01-09 08:29:19 -05001214 if (const auto *RD = DTy->getAsCXXRecordDecl()) {
1215 if (const CXXDestructorDecl *DD = RD->getDestructor();
1216 DD && DD->isCalledByDelete(OperatorDelete))
1217 CT = canCalleeThrow(*this, DE, DD);
Richard Smithf623c962012-04-17 00:58:00 +00001218 }
Aaron Ballman5ff7f472025-01-09 08:29:19 -05001219
1220 // We always look at the exception specification of the operator delete.
1221 CT = mergeCanThrow(CT, canCalleeThrow(*this, DE, OperatorDelete));
1222
1223 // If we know we can throw, we're done.
1224 if (CT == CT_Can)
1225 return CT;
Richard Smithf623c962012-04-17 00:58:00 +00001226 }
Richard Smithfbf60b72019-12-13 14:10:13 -08001227 return mergeCanThrow(CT, canSubStmtsThrow(*this, DE));
Richard Smithf623c962012-04-17 00:58:00 +00001228 }
1229
1230 case Expr::CXXBindTemporaryExprClass: {
Richard Smithfbf60b72019-12-13 14:10:13 -08001231 auto *BTE = cast<CXXBindTemporaryExpr>(S);
Richard Smithf623c962012-04-17 00:58:00 +00001232 // The bound temporary has to be destroyed again, which might throw.
Richard Smithfbf60b72019-12-13 14:10:13 -08001233 CanThrowResult CT =
1234 canCalleeThrow(*this, BTE, BTE->getTemporary()->getDestructor());
Richard Smithf623c962012-04-17 00:58:00 +00001235 if (CT == CT_Can)
1236 return CT;
Richard Smithfbf60b72019-12-13 14:10:13 -08001237 return mergeCanThrow(CT, canSubStmtsThrow(*this, BTE));
Richard Smithf623c962012-04-17 00:58:00 +00001238 }
1239
Richard Smith4a4e90a2019-12-13 14:11:04 -08001240 case Expr::PseudoObjectExprClass: {
1241 auto *POE = cast<PseudoObjectExpr>(S);
1242 CanThrowResult CT = CT_Cannot;
1243 for (const Expr *E : POE->semantics()) {
1244 CT = mergeCanThrow(CT, canThrow(E));
1245 if (CT == CT_Can)
1246 break;
1247 }
1248 return CT;
1249 }
1250
Richard Smithf623c962012-04-17 00:58:00 +00001251 // ObjC message sends are like function calls, but never have exception
1252 // specs.
1253 case Expr::ObjCMessageExprClass:
1254 case Expr::ObjCPropertyRefExprClass:
1255 case Expr::ObjCSubscriptRefExprClass:
1256 return CT_Can;
1257
1258 // All the ObjC literals that are implemented as calls are
1259 // potentially throwing unless we decide to close off that
1260 // possibility.
1261 case Expr::ObjCArrayLiteralClass:
1262 case Expr::ObjCDictionaryLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00001263 case Expr::ObjCBoxedExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001264 return CT_Can;
1265
1266 // Many other things have subexpressions, so we have to test those.
1267 // Some are simple:
Richard Smith9f690bd2015-10-27 06:02:45 +00001268 case Expr::CoawaitExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001269 case Expr::ConditionalOperatorClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00001270 case Expr::CoyieldExprClass:
Richard Smith778dc0f2019-10-19 00:04:38 +00001271 case Expr::CXXRewrittenBinaryOperatorClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00001272 case Expr::CXXStdInitializerListExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001273 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00001274 case Expr::DesignatedInitUpdateExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001275 case Expr::ExprWithCleanupsClass:
1276 case Expr::ExtVectorElementExprClass:
1277 case Expr::InitListExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00001278 case Expr::ArrayInitLoopExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001279 case Expr::MemberExprClass:
1280 case Expr::ObjCIsaExprClass:
1281 case Expr::ObjCIvarRefExprClass:
1282 case Expr::ParenExprClass:
1283 case Expr::ParenListExprClass:
1284 case Expr::ShuffleVectorExprClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001285 case Expr::StmtExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00001286 case Expr::ConvertVectorExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001287 case Expr::VAArgExprClass:
Alan Zhao95a4c0c2023-01-04 15:12:00 -08001288 case Expr::CXXParenListInitExprClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001289 return canSubStmtsThrow(*this, S);
1290
1291 case Expr::CompoundLiteralExprClass:
1292 case Expr::CXXConstCastExprClass:
Anastasia Stulovaa6a237f2020-05-18 11:02:01 +01001293 case Expr::CXXAddrspaceCastExprClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001294 case Expr::CXXReinterpretCastExprClass:
1295 case Expr::BuiltinBitCastExprClass:
1296 // FIXME: Properly determine whether a variably-modified type can throw.
1297 if (cast<Expr>(S)->getType()->isVariablyModifiedType())
1298 return CT_Can;
1299 return canSubStmtsThrow(*this, S);
Richard Smithf623c962012-04-17 00:58:00 +00001300
1301 // Some might be dependent for other reasons.
1302 case Expr::ArraySubscriptExprClass:
Florian Hahn8f3f88d2020-06-01 19:42:03 +01001303 case Expr::MatrixSubscriptExprClass:
Erich Keane39adc8f2024-04-25 10:22:03 -07001304 case Expr::ArraySectionExprClass:
Alexey Bataev7ac9efb2020-02-05 09:33:05 -05001305 case Expr::OMPArrayShapingExprClass:
Alexey Bataev13a15042020-04-01 15:06:38 -04001306 case Expr::OMPIteratorExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001307 case Expr::BinaryOperatorClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001308 case Expr::DependentCoawaitExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001309 case Expr::CompoundAssignOperatorClass:
1310 case Expr::CStyleCastExprClass:
1311 case Expr::CXXStaticCastExprClass:
1312 case Expr::CXXFunctionalCastExprClass:
1313 case Expr::ImplicitCastExprClass:
1314 case Expr::MaterializeTemporaryExprClass:
1315 case Expr::UnaryOperatorClass: {
Richard Smithfbf60b72019-12-13 14:10:13 -08001316 // FIXME: Properly determine whether a variably-modified type can throw.
1317 if (auto *CE = dyn_cast<CastExpr>(S))
1318 if (CE->getType()->isVariablyModifiedType())
1319 return CT_Can;
1320 CanThrowResult CT =
1321 cast<Expr>(S)->isTypeDependent() ? CT_Dependent : CT_Cannot;
1322 return mergeCanThrow(CT, canSubStmtsThrow(*this, S));
Richard Smithf623c962012-04-17 00:58:00 +00001323 }
1324
Richard Smith852c9db2013-04-20 22:23:05 +00001325 case Expr::CXXDefaultArgExprClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001326 return canThrow(cast<CXXDefaultArgExpr>(S)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001327
1328 case Expr::CXXDefaultInitExprClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001329 return canThrow(cast<CXXDefaultInitExpr>(S)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001330
Richard Smithfbf60b72019-12-13 14:10:13 -08001331 case Expr::ChooseExprClass: {
1332 auto *CE = cast<ChooseExpr>(S);
1333 if (CE->isTypeDependent() || CE->isValueDependent())
Richard Smithf623c962012-04-17 00:58:00 +00001334 return CT_Dependent;
Richard Smithfbf60b72019-12-13 14:10:13 -08001335 return canThrow(CE->getChosenSubExpr());
1336 }
Richard Smithf623c962012-04-17 00:58:00 +00001337
1338 case Expr::GenericSelectionExprClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001339 if (cast<GenericSelectionExpr>(S)->isResultDependent())
Richard Smithf623c962012-04-17 00:58:00 +00001340 return CT_Dependent;
Richard Smithfbf60b72019-12-13 14:10:13 -08001341 return canThrow(cast<GenericSelectionExpr>(S)->getResultExpr());
Richard Smithf623c962012-04-17 00:58:00 +00001342
1343 // Some expressions are always dependent.
1344 case Expr::CXXDependentScopeMemberExprClass:
1345 case Expr::CXXUnresolvedConstructExprClass:
1346 case Expr::DependentScopeDeclRefExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00001347 case Expr::CXXFoldExprClass:
Haojian Wu733edf92020-03-19 16:30:40 +01001348 case Expr::RecoveryExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001349 return CT_Dependent;
1350
1351 case Expr::AsTypeExprClass:
1352 case Expr::BinaryConditionalOperatorClass:
1353 case Expr::BlockExprClass:
1354 case Expr::CUDAKernelCallExprClass:
1355 case Expr::DeclRefExprClass:
1356 case Expr::ObjCBridgedCastExprClass:
1357 case Expr::ObjCIndirectCopyRestoreExprClass:
1358 case Expr::ObjCProtocolExprClass:
1359 case Expr::ObjCSelectorExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00001360 case Expr::ObjCAvailabilityCheckExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001361 case Expr::OffsetOfExprClass:
1362 case Expr::PackExpansionExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001363 case Expr::SubstNonTypeTemplateParmExprClass:
1364 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00001365 case Expr::FunctionParmPackExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001366 case Expr::UnaryExprOrTypeTraitExprClass:
1367 case Expr::UnresolvedLookupExprClass:
1368 case Expr::UnresolvedMemberExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00001369 case Expr::TypoExprClass:
Richard Smith4a4e90a2019-12-13 14:11:04 -08001370 // FIXME: Many of the above can throw.
Richard Smithf623c962012-04-17 00:58:00 +00001371 return CT_Cannot;
1372
1373 case Expr::AddrLabelExprClass:
1374 case Expr::ArrayTypeTraitExprClass:
1375 case Expr::AtomicExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001376 case Expr::TypeTraitExprClass:
1377 case Expr::CXXBoolLiteralExprClass:
1378 case Expr::CXXNoexceptExprClass:
1379 case Expr::CXXNullPtrLiteralExprClass:
1380 case Expr::CXXPseudoDestructorExprClass:
1381 case Expr::CXXScalarValueInitExprClass:
1382 case Expr::CXXThisExprClass:
1383 case Expr::CXXUuidofExprClass:
1384 case Expr::CharacterLiteralClass:
1385 case Expr::ExpressionTraitExprClass:
1386 case Expr::FloatingLiteralClass:
1387 case Expr::GNUNullExprClass:
1388 case Expr::ImaginaryLiteralClass:
1389 case Expr::ImplicitValueInitExprClass:
1390 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00001391 case Expr::FixedPointLiteralClass:
Richard Smith410306b2016-12-12 02:53:20 +00001392 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00001393 case Expr::NoInitExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001394 case Expr::ObjCEncodeExprClass:
1395 case Expr::ObjCStringLiteralClass:
1396 case Expr::ObjCBoolLiteralExprClass:
1397 case Expr::OpaqueValueExprClass:
1398 case Expr::PredefinedExprClass:
1399 case Expr::SizeOfPackExprClass:
cor3ntinad1a65f2024-01-27 10:23:38 +01001400 case Expr::PackIndexingExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001401 case Expr::StringLiteralClass:
Eric Fiselier708afb52019-05-16 21:04:15 +00001402 case Expr::SourceLocExprClass:
Mariya Podchishchaeva41c6e432024-06-20 14:38:46 +02001403 case Expr::EmbedExprClass:
Saar Raz5d98ba62019-10-15 15:24:26 +00001404 case Expr::ConceptSpecializationExprClass:
Saar Raza0f50d72020-01-18 09:11:43 +02001405 case Expr::RequiresExprClass:
Chris B89fb8492024-08-31 10:59:08 -05001406 case Expr::HLSLOutArgExprClass:
erichkeane010d0112024-12-10 12:55:15 -08001407 case Stmt::OpenACCEnterDataConstructClass:
1408 case Stmt::OpenACCExitDataConstructClass:
erichkeanee34cc7c2024-12-17 07:39:20 -08001409 case Stmt::OpenACCWaitConstructClass:
erichkeaned5cec382025-03-03 10:26:53 -08001410 case Stmt::OpenACCCacheConstructClass:
erichkeane4bbdb012024-12-19 06:11:36 -08001411 case Stmt::OpenACCInitConstructClass:
1412 case Stmt::OpenACCShutdownConstructClass:
erichkeane21c785d2025-01-03 10:00:12 -08001413 case Stmt::OpenACCSetConstructClass:
erichkeanedb81e8c2025-01-06 11:59:04 -08001414 case Stmt::OpenACCUpdateConstructClass:
Richard Smithf623c962012-04-17 00:58:00 +00001415 // These expressions can never throw.
1416 return CT_Cannot;
1417
John McCall5e77d762013-04-16 07:28:30 +00001418 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00001419 case Expr::MSPropertySubscriptExprClass:
John McCall5e77d762013-04-16 07:28:30 +00001420 llvm_unreachable("Invalid class for expression");
1421
Richard Smithfbf60b72019-12-13 14:10:13 -08001422 // Most statements can throw if any substatement can throw.
Erich Keanef6557782024-02-13 06:02:13 -08001423 case Stmt::OpenACCComputeConstructClass:
Erich Keane42f4e502024-06-05 06:21:48 -07001424 case Stmt::OpenACCLoopConstructClass:
erichkeane39351f82024-11-07 14:17:55 -08001425 case Stmt::OpenACCCombinedConstructClass:
erichkeane010d0112024-12-10 12:55:15 -08001426 case Stmt::OpenACCDataConstructClass:
1427 case Stmt::OpenACCHostDataConstructClass:
erichkeane99a91332025-01-22 12:22:03 -08001428 case Stmt::OpenACCAtomicConstructClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001429 case Stmt::AttributedStmtClass:
1430 case Stmt::BreakStmtClass:
1431 case Stmt::CapturedStmtClass:
Tom Honermann8fb42302025-01-22 16:39:08 -05001432 case Stmt::SYCLKernelCallStmtClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001433 case Stmt::CaseStmtClass:
1434 case Stmt::CompoundStmtClass:
1435 case Stmt::ContinueStmtClass:
1436 case Stmt::CoreturnStmtClass:
1437 case Stmt::CoroutineBodyStmtClass:
1438 case Stmt::CXXCatchStmtClass:
1439 case Stmt::CXXForRangeStmtClass:
1440 case Stmt::DefaultStmtClass:
1441 case Stmt::DoStmtClass:
1442 case Stmt::ForStmtClass:
1443 case Stmt::GCCAsmStmtClass:
1444 case Stmt::GotoStmtClass:
1445 case Stmt::IndirectGotoStmtClass:
1446 case Stmt::LabelStmtClass:
1447 case Stmt::MSAsmStmtClass:
1448 case Stmt::MSDependentExistsStmtClass:
1449 case Stmt::NullStmtClass:
1450 case Stmt::ObjCAtCatchStmtClass:
1451 case Stmt::ObjCAtFinallyStmtClass:
1452 case Stmt::ObjCAtSynchronizedStmtClass:
1453 case Stmt::ObjCAutoreleasePoolStmtClass:
1454 case Stmt::ObjCForCollectionStmtClass:
1455 case Stmt::OMPAtomicDirectiveClass:
Haojian Wu31bb7592024-08-05 14:04:09 +02001456 case Stmt::OMPAssumeDirectiveClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001457 case Stmt::OMPBarrierDirectiveClass:
1458 case Stmt::OMPCancelDirectiveClass:
1459 case Stmt::OMPCancellationPointDirectiveClass:
1460 case Stmt::OMPCriticalDirectiveClass:
1461 case Stmt::OMPDistributeDirectiveClass:
1462 case Stmt::OMPDistributeParallelForDirectiveClass:
1463 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1464 case Stmt::OMPDistributeSimdDirectiveClass:
1465 case Stmt::OMPFlushDirectiveClass:
Alexey Bataevc112e9412020-02-28 09:52:15 -05001466 case Stmt::OMPDepobjDirectiveClass:
Alexey Bataevfcba7c32020-03-20 07:03:01 -04001467 case Stmt::OMPScanDirectiveClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001468 case Stmt::OMPForDirectiveClass:
1469 case Stmt::OMPForSimdDirectiveClass:
1470 case Stmt::OMPMasterDirectiveClass:
1471 case Stmt::OMPMasterTaskLoopDirectiveClass:
Fazlay Rabbi42bb88e2022-06-24 08:42:21 -07001472 case Stmt::OMPMaskedTaskLoopDirectiveClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001473 case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
Fazlay Rabbi73e5d7b2022-06-28 14:35:43 -07001474 case Stmt::OMPMaskedTaskLoopSimdDirectiveClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001475 case Stmt::OMPOrderedDirectiveClass:
Michael Kruseb1191202021-03-03 17:15:32 -06001476 case Stmt::OMPCanonicalLoopClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001477 case Stmt::OMPParallelDirectiveClass:
1478 case Stmt::OMPParallelForDirectiveClass:
1479 case Stmt::OMPParallelForSimdDirectiveClass:
1480 case Stmt::OMPParallelMasterDirectiveClass:
Jennifer Yubb83f8e2022-06-16 16:32:30 -07001481 case Stmt::OMPParallelMaskedDirectiveClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001482 case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
Fazlay Rabbid64ba892022-06-30 10:59:33 -07001483 case Stmt::OMPParallelMaskedTaskLoopDirectiveClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001484 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
Fazlay Rabbi38bcd482022-06-30 17:08:17 -07001485 case Stmt::OMPParallelMaskedTaskLoopSimdDirectiveClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001486 case Stmt::OMPParallelSectionsDirectiveClass:
1487 case Stmt::OMPSectionDirectiveClass:
1488 case Stmt::OMPSectionsDirectiveClass:
1489 case Stmt::OMPSimdDirectiveClass:
Michael Kruse6c050052021-02-12 11:26:59 -08001490 case Stmt::OMPTileDirectiveClass:
Zahira Ammarguellatcf69b4c2025-02-13 07:14:36 -05001491 case Stmt::OMPStripeDirectiveClass:
Michael Krusea2223612021-06-10 14:24:17 -05001492 case Stmt::OMPUnrollDirectiveClass:
Michael Kruse80865c012024-07-18 10:35:32 +02001493 case Stmt::OMPReverseDirectiveClass:
Michael Kruse5c93a942024-07-19 09:24:40 +02001494 case Stmt::OMPInterchangeDirectiveClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001495 case Stmt::OMPSingleDirectiveClass:
1496 case Stmt::OMPTargetDataDirectiveClass:
1497 case Stmt::OMPTargetDirectiveClass:
1498 case Stmt::OMPTargetEnterDataDirectiveClass:
1499 case Stmt::OMPTargetExitDataDirectiveClass:
1500 case Stmt::OMPTargetParallelDirectiveClass:
1501 case Stmt::OMPTargetParallelForDirectiveClass:
1502 case Stmt::OMPTargetParallelForSimdDirectiveClass:
1503 case Stmt::OMPTargetSimdDirectiveClass:
1504 case Stmt::OMPTargetTeamsDirectiveClass:
1505 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1506 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1507 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1508 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1509 case Stmt::OMPTargetUpdateDirectiveClass:
Fazlay Rabbie4c72982023-08-09 15:28:09 -07001510 case Stmt::OMPScopeDirectiveClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001511 case Stmt::OMPTaskDirectiveClass:
1512 case Stmt::OMPTaskgroupDirectiveClass:
1513 case Stmt::OMPTaskLoopDirectiveClass:
1514 case Stmt::OMPTaskLoopSimdDirectiveClass:
1515 case Stmt::OMPTaskwaitDirectiveClass:
1516 case Stmt::OMPTaskyieldDirectiveClass:
Jennifer Yuea64e662022-11-01 14:46:12 -07001517 case Stmt::OMPErrorDirectiveClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001518 case Stmt::OMPTeamsDirectiveClass:
1519 case Stmt::OMPTeamsDistributeDirectiveClass:
1520 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1521 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1522 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
Mike Rice410f09a2021-03-15 13:09:46 -07001523 case Stmt::OMPInteropDirectiveClass:
Mike Riceb7899ba2021-03-22 18:13:29 -07001524 case Stmt::OMPDispatchDirectiveClass:
cchen1a43fd22021-04-09 14:00:36 -05001525 case Stmt::OMPMaskedDirectiveClass:
alokmishra.besu000875c2021-09-17 16:03:01 -05001526 case Stmt::OMPMetaDirectiveClass:
Mike Rice6f9c2512021-10-28 08:10:40 -07001527 case Stmt::OMPGenericLoopDirectiveClass:
Mike Rice79f661e2022-03-15 08:35:59 -07001528 case Stmt::OMPTeamsGenericLoopDirectiveClass:
Mike Rice6bd8dc92022-03-18 11:02:02 -07001529 case Stmt::OMPTargetTeamsGenericLoopDirectiveClass:
Mike Rice2cedaee2022-03-22 10:55:21 -07001530 case Stmt::OMPParallelGenericLoopDirectiveClass:
Mike Ricef82ec552022-03-23 15:37:06 -07001531 case Stmt::OMPTargetParallelGenericLoopDirectiveClass:
Richard Smithfbf60b72019-12-13 14:10:13 -08001532 case Stmt::ReturnStmtClass:
1533 case Stmt::SEHExceptStmtClass:
1534 case Stmt::SEHFinallyStmtClass:
1535 case Stmt::SEHLeaveStmtClass:
1536 case Stmt::SEHTryStmtClass:
1537 case Stmt::SwitchStmtClass:
1538 case Stmt::WhileStmtClass:
1539 return canSubStmtsThrow(*this, S);
1540
1541 case Stmt::DeclStmtClass: {
1542 CanThrowResult CT = CT_Cannot;
1543 for (const Decl *D : cast<DeclStmt>(S)->decls()) {
1544 if (auto *VD = dyn_cast<VarDecl>(D))
1545 CT = mergeCanThrow(CT, canVarDeclThrow(*this, VD));
1546
1547 // FIXME: Properly determine whether a variably-modified type can throw.
1548 if (auto *TND = dyn_cast<TypedefNameDecl>(D))
1549 if (TND->getUnderlyingType()->isVariablyModifiedType())
1550 return CT_Can;
1551 if (auto *VD = dyn_cast<ValueDecl>(D))
1552 if (VD->getType()->isVariablyModifiedType())
1553 return CT_Can;
1554 }
1555 return CT;
1556 }
1557
1558 case Stmt::IfStmtClass: {
1559 auto *IS = cast<IfStmt>(S);
1560 CanThrowResult CT = CT_Cannot;
1561 if (const Stmt *Init = IS->getInit())
1562 CT = mergeCanThrow(CT, canThrow(Init));
1563 if (const Stmt *CondDS = IS->getConditionVariableDeclStmt())
1564 CT = mergeCanThrow(CT, canThrow(CondDS));
1565 CT = mergeCanThrow(CT, canThrow(IS->getCond()));
1566
1567 // For 'if constexpr', consider only the non-discarded case.
1568 // FIXME: We should add a DiscardedStmt marker to the AST.
Kazu Hirata6ad07882023-01-14 12:31:01 -08001569 if (std::optional<const Stmt *> Case = IS->getNondiscardedCase(Context))
Richard Smithfbf60b72019-12-13 14:10:13 -08001570 return *Case ? mergeCanThrow(CT, canThrow(*Case)) : CT;
1571
1572 CanThrowResult Then = canThrow(IS->getThen());
1573 CanThrowResult Else = IS->getElse() ? canThrow(IS->getElse()) : CT_Cannot;
1574 if (Then == Else)
1575 return mergeCanThrow(CT, Then);
1576
1577 // For a dependent 'if constexpr', the result is dependent if it depends on
1578 // the value of the condition.
1579 return mergeCanThrow(CT, IS->isConstexpr() ? CT_Dependent
1580 : mergeCanThrow(Then, Else));
1581 }
1582
1583 case Stmt::CXXTryStmtClass: {
1584 auto *TS = cast<CXXTryStmt>(S);
1585 // try /*...*/ catch (...) { H } can throw only if H can throw.
1586 // Any other try-catch can throw if any substatement can throw.
1587 const CXXCatchStmt *FinalHandler = TS->getHandler(TS->getNumHandlers() - 1);
1588 if (!FinalHandler->getExceptionDecl())
1589 return canThrow(FinalHandler->getHandlerBlock());
1590 return canSubStmtsThrow(*this, S);
1591 }
1592
1593 case Stmt::ObjCAtThrowStmtClass:
1594 return CT_Can;
1595
1596 case Stmt::ObjCAtTryStmtClass: {
1597 auto *TS = cast<ObjCAtTryStmt>(S);
1598
1599 // @catch(...) need not be last in Objective-C. Walk backwards until we
1600 // see one or hit the @try.
1601 CanThrowResult CT = CT_Cannot;
1602 if (const Stmt *Finally = TS->getFinallyStmt())
1603 CT = mergeCanThrow(CT, canThrow(Finally));
1604 for (unsigned I = TS->getNumCatchStmts(); I != 0; --I) {
1605 const ObjCAtCatchStmt *Catch = TS->getCatchStmt(I - 1);
1606 CT = mergeCanThrow(CT, canThrow(Catch));
1607 // If we reach a @catch(...), no earlier exceptions can escape.
1608 if (Catch->hasEllipsis())
1609 return CT;
1610 }
1611
1612 // Didn't find an @catch(...). Exceptions from the @try body can escape.
1613 return mergeCanThrow(CT, canThrow(TS->getTryBody()));
1614 }
1615
Erich Keaneeba69b52021-04-23 08:22:35 -07001616 case Stmt::SYCLUniqueStableNameExprClass:
1617 return CT_Cannot;
Erich Keaned412cea2024-10-03 08:34:43 -07001618 case Stmt::OpenACCAsteriskSizeExprClass:
1619 return CT_Cannot;
Richard Smithfbf60b72019-12-13 14:10:13 -08001620 case Stmt::NoStmtClass:
1621 llvm_unreachable("Invalid class for statement");
Richard Smithf623c962012-04-17 00:58:00 +00001622 }
1623 llvm_unreachable("Bogus StmtClass");
1624}
1625
Sebastian Redl4915e632009-10-11 09:03:14 +00001626} // end namespace clang