clang 23.0.0git
SemaExceptionSpec.cpp
Go to the documentation of this file.
1//===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- C++ -*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ exception specification testing.
10//
11//===----------------------------------------------------------------------===//
12
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/StmtObjC.h"
18#include "clang/AST/StmtSYCL.h"
19#include "clang/AST/TypeLoc.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include <optional>
26
27namespace clang {
28
30{
31 if (const PointerType *PtrTy = T->getAs<PointerType>())
32 T = PtrTy->getPointeeType();
33 else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
34 T = RefTy->getPointeeType();
35 else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
36 T = MPTy->getPointeeType();
37 return T->getAs<FunctionProtoType>();
38}
39
40/// HACK: 2014-11-14 libstdc++ had a bug where it shadows std::swap with a
41/// member swap function then tries to call std::swap unqualified from the
42/// exception specification of that function. This function detects whether
43/// we're in such a case and turns off delay-parsing of exception
44/// specifications. Libstdc++ 6.1 (released 2016-04-27) appears to have
45/// resolved it as side-effect of commit ddb63209a8d (2015-06-05).
47 auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
48
49 if (!getPreprocessor().NeedsStdLibCxxWorkaroundBefore(2016'04'27))
50 return false;
51 // All the problem cases are member functions named "swap" within class
52 // templates declared directly within namespace std or std::__debug or
53 // std::__profile.
54 if (!RD || !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
55 !D.getIdentifier() || !D.getIdentifier()->isStr("swap"))
56 return false;
57
58 auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext());
59 if (!ND)
60 return false;
61
62 bool IsInStd = ND->isStdNamespace();
63 if (!IsInStd) {
64 // This isn't a direct member of namespace std, but it might still be
65 // libstdc++'s std::__debug::array or std::__profile::array.
66 IdentifierInfo *II = ND->getIdentifier();
67 if (!II || !(II->isStr("__debug") || II->isStr("__profile")) ||
68 !ND->isInStdNamespace())
69 return false;
70 }
71
72 // Only apply this hack within a system header.
73 if (!Context.getSourceManager().isInSystemHeader(D.getBeginLoc()))
74 return false;
75
76 return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
77 .Case("array", true)
78 .Case("pair", IsInStd)
79 .Case("priority_queue", IsInStd)
80 .Case("stack", IsInStd)
81 .Case("queue", IsInStd)
82 .Default(false);
83}
84
87
88 if (NoexceptExpr->isTypeDependent() ||
89 NoexceptExpr->containsUnexpandedParameterPack()) {
91 return NoexceptExpr;
92 }
93
94 llvm::APSInt Result;
96 NoexceptExpr, Context.BoolTy, Result, CCEKind::Noexcept);
97
98 if (Converted.isInvalid()) {
100 // Fill in an expression of 'false' as a fixup.
101 auto *BoolExpr = new (Context)
102 CXXBoolLiteralExpr(false, Context.BoolTy, NoexceptExpr->getBeginLoc());
103 llvm::APSInt Value{1};
104 Value = 0;
105 return ConstantExpr::Create(Context, BoolExpr, APValue{Value});
106 }
107
108 if (Converted.get()->isValueDependent()) {
110 return Converted;
111 }
112
113 if (!Converted.isInvalid())
115 return Converted;
116}
117
119 // C++11 [except.spec]p2:
120 // A type cv T, "array of T", or "function returning T" denoted
121 // in an exception-specification is adjusted to type T, "pointer to T", or
122 // "pointer to function returning T", respectively.
123 //
124 // We also apply this rule in C++98.
125 if (T->isArrayType())
126 T = Context.getArrayDecayedType(T);
127 else if (T->isFunctionType())
128 T = Context.getPointerType(T);
129
130 int Kind = 0;
131 QualType PointeeT = T;
132 if (const PointerType *PT = T->getAs<PointerType>()) {
133 PointeeT = PT->getPointeeType();
134 Kind = 1;
135
136 // cv void* is explicitly permitted, despite being a pointer to an
137 // incomplete type.
138 if (PointeeT->isVoidType())
139 return false;
140 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
141 PointeeT = RT->getPointeeType();
142 Kind = 2;
143
144 if (RT->isRValueReferenceType()) {
145 // C++11 [except.spec]p2:
146 // A type denoted in an exception-specification shall not denote [...]
147 // an rvalue reference type.
148 Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
149 << T << Range;
150 return true;
151 }
152 }
153
154 // C++11 [except.spec]p2:
155 // A type denoted in an exception-specification shall not denote an
156 // incomplete type other than a class currently being defined [...].
157 // A type denoted in an exception-specification shall not denote a
158 // pointer or reference to an incomplete type, other than (cv) void* or a
159 // pointer or reference to a class currently being defined.
160 // In Microsoft mode, downgrade this to a warning.
161 unsigned DiagID = diag::err_incomplete_in_exception_spec;
162 bool ReturnValueOnError = true;
163 if (getLangOpts().MSVCCompat) {
164 DiagID = diag::ext_incomplete_in_exception_spec;
165 ReturnValueOnError = false;
166 }
167 if (auto *RD = PointeeT->getAsRecordDecl();
168 !(RD && RD->isBeingDefined()) &&
169 RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range))
170 return ReturnValueOnError;
171
172 // WebAssembly reference types can't be used in exception specifications.
173 if (PointeeT.isWebAssemblyReferenceType()) {
174 Diag(Range.getBegin(), diag::err_wasm_reftype_exception_spec);
175 return true;
176 }
177
178 // The MSVC compatibility mode doesn't extend to sizeless types,
179 // so diagnose them separately.
180 if (PointeeT->isSizelessType() && Kind != 1) {
181 Diag(Range.getBegin(), diag::err_sizeless_in_exception_spec)
182 << (Kind == 2 ? 1 : 0) << PointeeT << Range;
183 return true;
184 }
185
186 return false;
187}
188
190 // C++17 removes this rule in favor of putting exception specifications into
191 // the type system.
193 return false;
194
195 if (const PointerType *PT = T->getAs<PointerType>())
196 T = PT->getPointeeType();
197 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
198 T = PT->getPointeeType();
199 else
200 return false;
201
202 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
203 if (!FnT)
204 return false;
205
206 return FnT->hasExceptionSpec();
207}
208
209const FunctionProtoType *
211 if (FPT->getExceptionSpecType() == EST_Unparsed) {
212 Diag(Loc, diag::err_exception_spec_not_parsed);
213 return nullptr;
214 }
215
217 return FPT;
218
219 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
220 const FunctionProtoType *SourceFPT =
221 SourceDecl->getType()->castAs<FunctionProtoType>();
222
223 // If the exception specification has already been resolved, just return it.
225 return SourceFPT;
226
227 // Compute or instantiate the exception specification now.
228 if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
229 EvaluateImplicitExceptionSpec(Loc, SourceDecl);
230 else
231 InstantiateExceptionSpec(Loc, SourceDecl);
232
233 const FunctionProtoType *Proto =
234 SourceDecl->getType()->castAs<FunctionProtoType>();
236 Diag(Loc, diag::err_exception_spec_not_parsed);
237 Proto = nullptr;
238 }
239 return Proto;
240}
241
242void
245 // If we've fully resolved the exception specification, notify listeners.
247 if (auto *Listener = getASTMutationListener())
248 Listener->ResolvedExceptionSpec(FD);
249
250 for (FunctionDecl *Redecl : FD->redecls())
251 Context.adjustExceptionSpec(Redecl, ESI);
252}
253
256 FD->getType()->castAs<FunctionProtoType>()->getExceptionSpecType();
257 if (EST == EST_Unparsed)
258 return true;
259 else if (EST != EST_Unevaluated)
260 return false;
261 const DeclContext *DC = FD->getLexicalDeclContext();
262 return DC->isRecord() && cast<RecordDecl>(DC)->isBeingDefined();
263}
264
266 Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
267 const FunctionProtoType *Old, SourceLocation OldLoc,
268 const FunctionProtoType *New, SourceLocation NewLoc,
269 bool *MissingExceptionSpecification = nullptr,
270 bool *MissingEmptyExceptionSpecification = nullptr,
271 bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false);
272
273/// Determine whether a function has an implicitly-generated exception
274/// specification.
277 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
278 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
279 return false;
280
281 // For a function that the user didn't declare:
282 // - if this is a destructor, its exception specification is implicit.
283 // - if this is 'operator delete' or 'operator delete[]', the exception
284 // specification is as-if an explicit exception specification was given
285 // (per [basic.stc.dynamic]p2).
286 if (!Decl->getTypeSourceInfo())
288
289 auto *Ty = Decl->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
290 return !Ty->hasExceptionSpec();
291}
292
294 // Just completely ignore this under -fno-exceptions prior to C++17.
295 // In C++17 onwards, the exception specification is part of the type and
296 // we will diagnose mismatches anyway, so it's better to check for them here.
297 if (!getLangOpts().CXXExceptions && !getLangOpts().CPlusPlus17)
298 return false;
299
300 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
301 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
302 bool MissingExceptionSpecification = false;
303 bool MissingEmptyExceptionSpecification = false;
304
305 unsigned DiagID = diag::err_mismatched_exception_spec;
306 bool ReturnValueOnError = true;
307 if (getLangOpts().MSVCCompat) {
308 DiagID = diag::ext_mismatched_exception_spec;
309 ReturnValueOnError = false;
310 }
311
312 // If we're befriending a member function of a class that's currently being
313 // defined, we might not be able to work out its exception specification yet.
314 // If not, defer the check until later.
317 return false;
318 }
319
320 // Check the types as written: they must match before any exception
321 // specification adjustment is applied.
323 *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
324 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
325 New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
326 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
327 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
328 // C++11 [except.spec]p4 [DR1492]:
329 // If a declaration of a function has an implicit
330 // exception-specification, other declarations of the function shall
331 // not specify an exception-specification.
332 if (getLangOpts().CPlusPlus11 && getLangOpts().CXXExceptions &&
334 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
336 if (Old->getLocation().isValid())
337 Diag(Old->getLocation(), diag::note_previous_declaration);
338 }
339 return false;
340 }
341
342 // The failure was something other than an missing exception
343 // specification; return an error, except in MS mode where this is a warning.
344 if (!MissingExceptionSpecification)
345 return ReturnValueOnError;
346
347 const auto *NewProto = New->getType()->castAs<FunctionProtoType>();
348
349 // The new function declaration is only missing an empty exception
350 // specification "throw()". If the throw() specification came from a
351 // function in a system header that has C linkage, just add an empty
352 // exception specification to the "new" declaration. Note that C library
353 // implementations are permitted to add these nothrow exception
354 // specifications.
355 //
356 // Likewise if the old function is a builtin.
357 if (MissingEmptyExceptionSpecification &&
358 (Old->getLocation().isInvalid() ||
359 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
360 Old->getBuiltinID()) &&
361 Old->isExternC()) {
362 New->setType(Context.getFunctionType(
363 NewProto->getReturnType(), NewProto->getParamTypes(),
364 NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
365 return false;
366 }
367
368 const auto *OldProto = Old->getType()->castAs<FunctionProtoType>();
369
370 FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
371 if (ESI.Type == EST_Dynamic) {
372 // FIXME: What if the exceptions are described in terms of the old
373 // prototype's parameters?
374 ESI.Exceptions = OldProto->exceptions();
375 }
376
377 if (ESI.Type == EST_NoexceptFalse)
378 ESI.Type = EST_None;
379 if (ESI.Type == EST_NoexceptTrue)
380 ESI.Type = EST_BasicNoexcept;
381
382 // For dependent noexcept, we can't just take the expression from the old
383 // prototype. It likely contains references to the old prototype's parameters.
384 if (ESI.Type == EST_DependentNoexcept) {
385 New->setInvalidDecl();
386 } else {
387 // Update the type of the function with the appropriate exception
388 // specification.
389 New->setType(Context.getFunctionType(
390 NewProto->getReturnType(), NewProto->getParamTypes(),
391 NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
392 }
393
394 if (getLangOpts().MSVCCompat && isDynamicExceptionSpec(ESI.Type)) {
395 DiagID = diag::ext_missing_exception_specification;
396 ReturnValueOnError = false;
397 } else if (New->isReplaceableGlobalAllocationFunction() &&
398 ESI.Type != EST_DependentNoexcept) {
399 // Allow missing exception specifications in redeclarations as an extension,
400 // when declaring a replaceable global allocation function.
401 DiagID = diag::ext_missing_exception_specification;
402 ReturnValueOnError = false;
403 } else if (ESI.Type == EST_NoThrow) {
404 // Don't emit any warning for missing 'nothrow' in MSVC.
405 if (getLangOpts().MSVCCompat) {
406 return false;
407 }
408 // Allow missing attribute 'nothrow' in redeclarations, since this is a very
409 // common omission.
410 DiagID = diag::ext_missing_exception_specification;
411 ReturnValueOnError = false;
412 } else {
413 DiagID = diag::err_missing_exception_specification;
414 ReturnValueOnError = true;
415 }
416
417 // Warn about the lack of exception specification.
418 SmallString<128> ExceptionSpecString;
419 llvm::raw_svector_ostream OS(ExceptionSpecString);
420 switch (OldProto->getExceptionSpecType()) {
421 case EST_DynamicNone:
422 OS << "throw()";
423 break;
424
425 case EST_Dynamic: {
426 OS << "throw(";
427 bool OnFirstException = true;
428 for (const auto &E : OldProto->exceptions()) {
429 if (OnFirstException)
430 OnFirstException = false;
431 else
432 OS << ", ";
433
434 OS << E.getAsString(getPrintingPolicy());
435 }
436 OS << ")";
437 break;
438 }
439
441 OS << "noexcept";
442 break;
443
446 case EST_NoexceptTrue:
447 OS << "noexcept(";
448 assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
449 OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
450 OS << ")";
451 break;
452 case EST_NoThrow:
453 OS <<"__attribute__((nothrow))";
454 break;
455 case EST_None:
456 case EST_MSAny:
457 case EST_Unevaluated:
459 case EST_Unparsed:
460 llvm_unreachable("This spec type is compatible with none.");
461 }
462
463 SourceLocation FixItLoc;
464 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
465 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
466 // FIXME: Preserve enough information so that we can produce a correct fixit
467 // location when there is a trailing return type.
468 if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
469 if (!FTLoc.getTypePtr()->hasTrailingReturn())
470 FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
471 }
472
473 if (FixItLoc.isInvalid())
474 Diag(New->getLocation(), DiagID)
475 << New << OS.str();
476 else {
477 Diag(New->getLocation(), DiagID)
478 << New << OS.str()
479 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
480 }
481
482 if (Old->getLocation().isValid())
483 Diag(Old->getLocation(), diag::note_previous_declaration);
484
485 return ReturnValueOnError;
486}
487
489 const FunctionProtoType *Old, SourceLocation OldLoc,
490 const FunctionProtoType *New, SourceLocation NewLoc) {
491 if (!getLangOpts().CXXExceptions)
492 return false;
493
494 unsigned DiagID = diag::err_mismatched_exception_spec;
495 if (getLangOpts().MSVCCompat)
496 DiagID = diag::ext_mismatched_exception_spec;
498 *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
499 Old, OldLoc, New, NewLoc);
500
501 // In Microsoft mode, mismatching exception specifications just cause a warning.
502 if (getLangOpts().MSVCCompat)
503 return false;
504 return Result;
505}
506
507/// CheckEquivalentExceptionSpec - Check if the two types have compatible
508/// exception specifications. See C++ [except.spec]p3.
509///
510/// \return \c false if the exception specifications match, \c true if there is
511/// a problem. If \c true is returned, either a diagnostic has already been
512/// produced or \c *MissingExceptionSpecification is set to \c true.
514 Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
515 const FunctionProtoType *Old, SourceLocation OldLoc,
516 const FunctionProtoType *New, SourceLocation NewLoc,
517 bool *MissingExceptionSpecification,
518 bool *MissingEmptyExceptionSpecification,
519 bool AllowNoexceptAllMatchWithNoSpec, bool IsOperatorNew) {
520 if (MissingExceptionSpecification)
521 *MissingExceptionSpecification = false;
522
523 if (MissingEmptyExceptionSpecification)
524 *MissingEmptyExceptionSpecification = false;
525
526 Old = S.ResolveExceptionSpec(NewLoc, Old);
527 if (!Old)
528 return false;
529 New = S.ResolveExceptionSpec(NewLoc, New);
530 if (!New)
531 return false;
532
533 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
534 // - both are non-throwing, regardless of their form,
535 // - both have the form noexcept(constant-expression) and the constant-
536 // expressions are equivalent,
537 // - both are dynamic-exception-specifications that have the same set of
538 // adjusted types.
539 //
540 // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
541 // of the form throw(), noexcept, or noexcept(constant-expression) where the
542 // constant-expression yields true.
543 //
544 // C++0x [except.spec]p4: If any declaration of a function has an exception-
545 // specifier that is not a noexcept-specification allowing all exceptions,
546 // all declarations [...] of that function shall have a compatible
547 // exception-specification.
548 //
549 // That last point basically means that noexcept(false) matches no spec.
550 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
551
553 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
554
555 assert(!isUnresolvedExceptionSpec(OldEST) &&
556 !isUnresolvedExceptionSpec(NewEST) &&
557 "Shouldn't see unknown exception specifications here");
558
559 CanThrowResult OldCanThrow = Old->canThrow();
560 CanThrowResult NewCanThrow = New->canThrow();
561
562 // Any non-throwing specifications are compatible.
563 if (OldCanThrow == CT_Cannot && NewCanThrow == CT_Cannot)
564 return false;
565
566 // Any throws-anything specifications are usually compatible.
567 if (OldCanThrow == CT_Can && OldEST != EST_Dynamic &&
568 NewCanThrow == CT_Can && NewEST != EST_Dynamic) {
569 // The exception is that the absence of an exception specification only
570 // matches noexcept(false) for functions, as described above.
571 if (!AllowNoexceptAllMatchWithNoSpec &&
572 ((OldEST == EST_None && NewEST == EST_NoexceptFalse) ||
573 (OldEST == EST_NoexceptFalse && NewEST == EST_None))) {
574 // This is the disallowed case.
575 } else {
576 return false;
577 }
578 }
579
580 // C++14 [except.spec]p3:
581 // Two exception-specifications are compatible if [...] both have the form
582 // noexcept(constant-expression) and the constant-expressions are equivalent
583 if (OldEST == EST_DependentNoexcept && NewEST == EST_DependentNoexcept) {
584 llvm::FoldingSetNodeID OldFSN, NewFSN;
585 Old->getNoexceptExpr()->Profile(OldFSN, S.Context, true);
586 New->getNoexceptExpr()->Profile(NewFSN, S.Context, true);
587 if (OldFSN == NewFSN)
588 return false;
589 }
590
591 // Dynamic exception specifications with the same set of adjusted types
592 // are compatible.
593 if (OldEST == EST_Dynamic && NewEST == EST_Dynamic) {
594 bool Success = true;
595 // Both have a dynamic exception spec. Collect the first set, then compare
596 // to the second.
597 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
598 for (const auto &I : Old->exceptions())
599 OldTypes.insert(S.Context.getCanonicalType(I).getUnqualifiedType());
600
601 for (const auto &I : New->exceptions()) {
603 if (OldTypes.count(TypePtr))
604 NewTypes.insert(TypePtr);
605 else {
606 Success = false;
607 break;
608 }
609 }
610
611 if (Success && OldTypes.size() == NewTypes.size())
612 return false;
613 }
614
615 // As a special compatibility feature, under C++0x we accept no spec and
616 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
617 // This is because the implicit declaration changed, but old code would break.
618 if (S.getLangOpts().CPlusPlus11 && IsOperatorNew) {
619 const FunctionProtoType *WithExceptions = nullptr;
620 if (OldEST == EST_None && NewEST == EST_Dynamic)
621 WithExceptions = New;
622 else if (OldEST == EST_Dynamic && NewEST == EST_None)
623 WithExceptions = Old;
624 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
625 // One has no spec, the other throw(something). If that something is
626 // std::bad_alloc, all conditions are met.
627 QualType Exception = *WithExceptions->exception_begin();
628 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
629 IdentifierInfo* Name = ExRecord->getIdentifier();
630 if (Name && Name->getName() == "bad_alloc") {
631 // It's called bad_alloc, but is it in std?
632 if (ExRecord->isInStdNamespace()) {
633 return false;
634 }
635 }
636 }
637 }
638 }
639
640 // If the caller wants to handle the case that the new function is
641 // incompatible due to a missing exception specification, let it.
642 if (MissingExceptionSpecification && OldEST != EST_None &&
643 NewEST == EST_None) {
644 // The old type has an exception specification of some sort, but
645 // the new type does not.
646 *MissingExceptionSpecification = true;
647
648 if (MissingEmptyExceptionSpecification && OldCanThrow == CT_Cannot) {
649 // The old type has a throw() or noexcept(true) exception specification
650 // and the new type has no exception specification, and the caller asked
651 // to handle this itself.
652 *MissingEmptyExceptionSpecification = true;
653 }
654
655 return true;
656 }
657
658 S.Diag(NewLoc, DiagID);
659 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
660 S.Diag(OldLoc, NoteID);
661 return true;
662}
663
665 const PartialDiagnostic &NoteID,
666 const FunctionProtoType *Old,
667 SourceLocation OldLoc,
668 const FunctionProtoType *New,
669 SourceLocation NewLoc) {
670 if (!getLangOpts().CXXExceptions)
671 return false;
672 return CheckEquivalentExceptionSpecImpl(*this, DiagID, NoteID, Old, OldLoc,
673 New, NewLoc);
674}
675
676bool Sema::handlerCanCatch(QualType HandlerType, QualType ExceptionType) {
677 // [except.handle]p3:
678 // A handler is a match for an exception object of type E if:
679
680 // HandlerType must be ExceptionType or derived from it, or pointer or
681 // reference to such types.
682 const ReferenceType *RefTy = HandlerType->getAs<ReferenceType>();
683 if (RefTy)
684 HandlerType = RefTy->getPointeeType();
685
686 // -- the handler is of type cv T or cv T& and E and T are the same type
687 if (Context.hasSameUnqualifiedType(ExceptionType, HandlerType))
688 return true;
689
690 // FIXME: ObjC pointer types?
691 if (HandlerType->isPointerType() || HandlerType->isMemberPointerType()) {
692 if (RefTy && (!HandlerType.isConstQualified() ||
693 HandlerType.isVolatileQualified()))
694 return false;
695
696 // -- the handler is of type cv T or const T& where T is a pointer or
697 // pointer to member type and E is std::nullptr_t
698 if (ExceptionType->isNullPtrType())
699 return true;
700
701 // -- the handler is of type cv T or const T& where T is a pointer or
702 // pointer to member type and E is a pointer or pointer to member type
703 // that can be converted to T by one or more of
704 // -- a qualification conversion
705 // -- a function pointer conversion
706 bool LifetimeConv;
707 // FIXME: Should we treat the exception as catchable if a lifetime
708 // conversion is required?
709 if (IsQualificationConversion(ExceptionType, HandlerType, false,
710 LifetimeConv) ||
711 IsFunctionConversion(ExceptionType, HandlerType))
712 return true;
713
714 // -- a standard pointer conversion [...]
715 if (!ExceptionType->isPointerType() || !HandlerType->isPointerType())
716 return false;
717
718 // Handle the "qualification conversion" portion.
719 Qualifiers EQuals, HQuals;
720 ExceptionType = Context.getUnqualifiedArrayType(
721 ExceptionType->getPointeeType(), EQuals);
722 HandlerType =
723 Context.getUnqualifiedArrayType(HandlerType->getPointeeType(), HQuals);
724 if (!HQuals.compatiblyIncludes(EQuals, getASTContext()))
725 return false;
726
727 if (HandlerType->isVoidType() && ExceptionType->isObjectType())
728 return true;
729
730 // The only remaining case is a derived-to-base conversion.
731 }
732
733 // -- the handler is of type cg T or cv T& and T is an unambiguous public
734 // base class of E
735 if (!ExceptionType->isRecordType() || !HandlerType->isRecordType())
736 return false;
737 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
738 /*DetectVirtual=*/false);
739 if (!IsDerivedFrom(SourceLocation(), ExceptionType, HandlerType, Paths) ||
740 Paths.isAmbiguous(Context.getCanonicalType(HandlerType)))
741 return false;
742
743 // Do this check from a context without privileges.
744 switch (CheckBaseClassAccess(SourceLocation(), HandlerType, ExceptionType,
745 Paths.front(),
746 /*Diagnostic*/ 0,
747 /*ForceCheck*/ true,
748 /*ForceUnprivileged*/ true)) {
749 case AR_accessible: return true;
750 case AR_inaccessible: return false;
751 case AR_dependent:
752 llvm_unreachable("access check dependent for unprivileged context");
753 case AR_delayed:
754 llvm_unreachable("access check delayed in non-declaration");
755 }
756 llvm_unreachable("unexpected access check result");
757}
758
760 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
761 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
762 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
763 SourceLocation SuperLoc, const FunctionProtoType *Subset,
764 bool SkipSubsetFirstParameter, SourceLocation SubLoc) {
765
766 // Just auto-succeed under -fno-exceptions.
767 if (!getLangOpts().CXXExceptions)
768 return false;
769
770 // FIXME: As usual, we could be more specific in our error messages, but
771 // that better waits until we've got types with source locations.
772
773 if (!SubLoc.isValid())
774 SubLoc = SuperLoc;
775
776 // Resolve the exception specifications, if needed.
777 Superset = ResolveExceptionSpec(SuperLoc, Superset);
778 if (!Superset)
779 return false;
780 Subset = ResolveExceptionSpec(SubLoc, Subset);
781 if (!Subset)
782 return false;
783
786 assert(!isUnresolvedExceptionSpec(SuperEST) &&
787 !isUnresolvedExceptionSpec(SubEST) &&
788 "Shouldn't see unknown exception specifications here");
789
790 // If there are dependent noexcept specs, assume everything is fine. Unlike
791 // with the equivalency check, this is safe in this case, because we don't
792 // want to merge declarations. Checks after instantiation will catch any
793 // omissions we make here.
794 if (SuperEST == EST_DependentNoexcept || SubEST == EST_DependentNoexcept)
795 return false;
796
797 CanThrowResult SuperCanThrow = Superset->canThrow();
798 CanThrowResult SubCanThrow = Subset->canThrow();
799
800 // If the superset contains everything or the subset contains nothing, we're
801 // done.
802 if ((SuperCanThrow == CT_Can && SuperEST != EST_Dynamic) ||
803 SubCanThrow == CT_Cannot)
804 return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset,
805 SkipSupersetFirstParameter, SuperLoc, Subset,
806 SkipSubsetFirstParameter, SubLoc);
807
808 // Allow __declspec(nothrow) to be missing on redeclaration as an extension in
809 // some cases.
810 if (NoThrowDiagID.getDiagID() != 0 && SubCanThrow == CT_Can &&
811 SuperCanThrow == CT_Cannot && SuperEST == EST_NoThrow) {
812 Diag(SubLoc, NoThrowDiagID);
813 if (NoteID.getDiagID() != 0)
814 Diag(SuperLoc, NoteID);
815 return true;
816 }
817
818 // If the subset contains everything or the superset contains nothing, we've
819 // failed.
820 if ((SubCanThrow == CT_Can && SubEST != EST_Dynamic) ||
821 SuperCanThrow == CT_Cannot) {
822 Diag(SubLoc, DiagID);
823 if (NoteID.getDiagID() != 0)
824 Diag(SuperLoc, NoteID);
825 return true;
826 }
827
828 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
829 "Exception spec subset: non-dynamic case slipped through.");
830
831 // Neither contains everything or nothing. Do a proper comparison.
832 for (QualType SubI : Subset->exceptions()) {
833 if (const ReferenceType *RefTy = SubI->getAs<ReferenceType>())
834 SubI = RefTy->getPointeeType();
835
836 // Make sure it's in the superset.
837 bool Contained = false;
838 for (QualType SuperI : Superset->exceptions()) {
839 // [except.spec]p5:
840 // the target entity shall allow at least the exceptions allowed by the
841 // source
842 //
843 // We interpret this as meaning that a handler for some target type would
844 // catch an exception of each source type.
845 if (handlerCanCatch(SuperI, SubI)) {
846 Contained = true;
847 break;
848 }
849 }
850 if (!Contained) {
851 Diag(SubLoc, DiagID);
852 if (NoteID.getDiagID() != 0)
853 Diag(SuperLoc, NoteID);
854 return true;
855 }
856 }
857 // We've run half the gauntlet.
858 return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset,
859 SkipSupersetFirstParameter, SuperLoc, Subset,
860 SkipSupersetFirstParameter, SubLoc);
861}
862
863static bool
865 const PartialDiagnostic &NoteID, QualType Target,
866 SourceLocation TargetLoc, QualType Source,
867 SourceLocation SourceLoc) {
869 if (!TFunc)
870 return false;
871 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
872 if (!SFunc)
873 return false;
874
875 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
876 SFunc, SourceLoc);
877}
878
880 const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
881 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
882 SourceLocation TargetLoc, const FunctionProtoType *Source,
883 bool SkipSourceFirstParameter, SourceLocation SourceLoc) {
884 auto RetDiag = DiagID;
885 RetDiag << 0;
887 *this, RetDiag, PDiag(),
888 Target->getReturnType(), TargetLoc, Source->getReturnType(),
889 SourceLoc))
890 return true;
891
892 // We shouldn't even be testing this unless the arguments are otherwise
893 // compatible.
894 assert((Target->getNumParams() - (unsigned)SkipTargetFirstParameter) ==
895 (Source->getNumParams() - (unsigned)SkipSourceFirstParameter) &&
896 "Functions have different argument counts.");
897 for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
898 auto ParamDiag = DiagID;
899 ParamDiag << 1;
901 *this, ParamDiag, PDiag(),
902 Target->getParamType(i + (SkipTargetFirstParameter ? 1 : 0)),
903 TargetLoc, Source->getParamType(SkipSourceFirstParameter ? 1 : 0),
904 SourceLoc))
905 return true;
906 }
907 return false;
908}
909
911 // First we check for applicability.
912 // Target type must be a function, function pointer or function reference.
913 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
914 if (!ToFunc || ToFunc->hasDependentExceptionSpec())
915 return false;
916
917 // SourceType must be a function or function pointer.
918 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
919 if (!FromFunc || FromFunc->hasDependentExceptionSpec())
920 return false;
921
922 unsigned DiagID = diag::err_incompatible_exception_specs;
923 unsigned NestedDiagID = diag::err_deep_exception_specs_differ;
924 // This is not an error in C++17 onwards, unless the noexceptness doesn't
925 // match, but in that case we have a full-on type mismatch, not just a
926 // type sugar mismatch.
927 if (getLangOpts().CPlusPlus17) {
928 DiagID = diag::warn_incompatible_exception_specs;
929 NestedDiagID = diag::warn_deep_exception_specs_differ;
930 }
931
932 // Now we've got the correct types on both sides, check their compatibility.
933 // This means that the source of the conversion can only throw a subset of
934 // the exceptions of the target, and any exception specs on arguments or
935 // return types must be equivalent.
936 //
937 // FIXME: If there is a nested dependent exception specification, we should
938 // not be checking it here. This is fine:
939 // template<typename T> void f() {
940 // void (*p)(void (*) throw(T));
941 // void (*q)(void (*) throw(int)) = p;
942 // }
943 // ... because it might be instantiated with T=int.
944 return CheckExceptionSpecSubset(PDiag(DiagID), PDiag(NestedDiagID), PDiag(),
945 PDiag(), ToFunc, 0,
946 From->getSourceRange().getBegin(), FromFunc,
947 0, SourceLocation()) &&
948 !getLangOpts().CPlusPlus17;
949}
950
952 const CXXMethodDecl *Old) {
953 // If the new exception specification hasn't been parsed yet, skip the check.
954 // We'll get called again once it's been parsed.
955 if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
957 return false;
958
959 // Don't check uninstantiated template destructors at all. We can only
960 // synthesize correct specs after the template is instantiated.
961 if (isa<CXXDestructorDecl>(New) && New->getParent()->isDependentType())
962 return false;
963
964 // If the old exception specification hasn't been parsed yet, or the new
965 // exception specification can't be computed yet, remember that we need to
966 // perform this check when we get to the end of the outermost
967 // lexically-surrounding class.
970 return false;
971 }
972
973 unsigned DiagID = diag::err_override_exception_spec;
974 if (getLangOpts().MSVCCompat)
975 DiagID = diag::ext_override_exception_spec;
977 PDiag(DiagID), PDiag(diag::err_deep_exception_specs_differ),
978 PDiag(diag::note_overridden_virtual_function),
979 PDiag(diag::ext_override_exception_spec),
982 New->getType()->castAs<FunctionProtoType>(),
983 New->hasCXXExplicitFunctionObjectParameter(), New->getLocation());
984}
985
988 for (const Stmt *SubStmt : S->children()) {
989 if (!SubStmt)
990 continue;
991 R = mergeCanThrow(R, Self.canThrow(SubStmt));
992 if (R == CT_Can)
993 break;
994 }
995 return R;
996}
997
999 SourceLocation Loc) {
1000 // As an extension, we assume that __attribute__((nothrow)) functions don't
1001 // throw.
1002 if (isa_and_nonnull<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
1003 return CT_Cannot;
1004
1005 QualType T;
1006
1007 // In C++1z, just look at the function type of the callee.
1008 if (S.getLangOpts().CPlusPlus17 && isa_and_nonnull<CallExpr>(E)) {
1009 E = cast<CallExpr>(E)->getCallee();
1010 T = E->getType();
1011 if (T->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1012 // Sadly we don't preserve the actual type as part of the "bound member"
1013 // placeholder, so we need to reconstruct it.
1014 E = E->IgnoreParenImpCasts();
1015
1016 // Could be a call to a pointer-to-member or a plain member access.
1017 if (auto *Op = dyn_cast<BinaryOperator>(E)) {
1018 assert(Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI);
1019 T = Op->getRHS()->getType()
1020 ->castAs<MemberPointerType>()->getPointeeType();
1021 } else {
1022 T = cast<MemberExpr>(E)->getMemberDecl()->getType();
1023 }
1024 }
1025 } else if (const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D))
1026 T = VD->getType();
1027 else
1028 // If we have no clue what we're calling, assume the worst.
1029 return CT_Can;
1030
1031 const FunctionProtoType *FT;
1032 if ((FT = T->getAs<FunctionProtoType>())) {
1033 } else if (const PointerType *PT = T->getAs<PointerType>())
1034 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1035 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1036 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1037 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1038 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1039 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1040 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1041
1042 if (!FT)
1043 return CT_Can;
1044
1045 if (Loc.isValid() || (Loc.isInvalid() && E))
1046 FT = S.ResolveExceptionSpec(Loc.isInvalid() ? E->getBeginLoc() : Loc, FT);
1047 if (!FT)
1048 return CT_Can;
1049
1050 return FT->canThrow();
1051}
1052
1055
1056 // Initialization might throw.
1057 if (!VD->isUsableInConstantExpressions(Self.Context))
1058 if (const Expr *Init = VD->getInit())
1059 CT = mergeCanThrow(CT, Self.canThrow(Init));
1060
1061 // Destructor might throw.
1063 if (auto *RD =
1065 if (auto *Dtor = RD->getDestructor()) {
1066 CT = mergeCanThrow(
1067 CT, Sema::canCalleeThrow(Self, nullptr, Dtor, VD->getLocation()));
1068 }
1069 }
1070 }
1071
1072 // If this is a decomposition declaration, bindings might throw.
1073 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
1074 for (auto *B : DD->flat_bindings())
1075 if (auto *HD = B->getHoldingVar())
1076 CT = mergeCanThrow(CT, canVarDeclThrow(Self, HD));
1077
1078 return CT;
1079}
1080
1082 if (DC->isTypeDependent())
1083 return CT_Dependent;
1084
1085 if (!DC->getTypeAsWritten()->isReferenceType())
1086 return CT_Cannot;
1087
1088 if (DC->getSubExpr()->isTypeDependent())
1089 return CT_Dependent;
1090
1091 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
1092}
1093
1095 // A typeid of a type is a constant and does not throw.
1096 if (DC->isTypeOperand())
1097 return CT_Cannot;
1098
1099 if (DC->isValueDependent())
1100 return CT_Dependent;
1101
1102 // If this operand is not evaluated it cannot possibly throw.
1103 if (!DC->isPotentiallyEvaluated())
1104 return CT_Cannot;
1105
1106 // Can throw std::bad_typeid if a nullptr is dereferenced.
1107 if (DC->hasNullCheck())
1108 return CT_Can;
1109
1110 return S.canThrow(DC->getExprOperand());
1111}
1112
1114 // C++ [expr.unary.noexcept]p3:
1115 // [Can throw] if in a potentially-evaluated context the expression would
1116 // contain:
1117 switch (S->getStmtClass()) {
1118 case Expr::ConstantExprClass:
1119 return canThrow(cast<ConstantExpr>(S)->getSubExpr());
1120
1121 case Expr::CXXThrowExprClass:
1122 // - a potentially evaluated throw-expression
1123 return CT_Can;
1124
1125 case Expr::CXXDynamicCastExprClass: {
1126 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1127 // where T is a reference type, that requires a run-time check
1128 auto *CE = cast<CXXDynamicCastExpr>(S);
1129 // FIXME: Properly determine whether a variably-modified type can throw.
1130 if (CE->getType()->isVariablyModifiedType())
1131 return CT_Can;
1133 if (CT == CT_Can)
1134 return CT;
1135 return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
1136 }
1137
1138 case Expr::CXXTypeidExprClass:
1139 // - a potentially evaluated typeid expression applied to a (possibly
1140 // parenthesized) built-in unary * operator applied to a pointer to a
1141 // polymorphic class type
1142 return canTypeidThrow(*this, cast<CXXTypeidExpr>(S));
1143
1144 // - a potentially evaluated call to a function, member function, function
1145 // pointer, or member function pointer that does not have a non-throwing
1146 // exception-specification
1147 case Expr::CallExprClass:
1148 case Expr::CXXMemberCallExprClass:
1149 case Expr::CXXOperatorCallExprClass:
1150 case Expr::UserDefinedLiteralClass: {
1151 const CallExpr *CE = cast<CallExpr>(S);
1152 CanThrowResult CT;
1153 if (CE->isTypeDependent())
1154 CT = CT_Dependent;
1156 CT = CT_Cannot;
1157 else
1158 CT = canCalleeThrow(*this, CE, CE->getCalleeDecl());
1159 if (CT == CT_Can)
1160 return CT;
1161 return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
1162 }
1163
1164 case Expr::CXXConstructExprClass:
1165 case Expr::CXXTemporaryObjectExprClass: {
1166 auto *CE = cast<CXXConstructExpr>(S);
1167 // FIXME: Properly determine whether a variably-modified type can throw.
1168 if (CE->getType()->isVariablyModifiedType())
1169 return CT_Can;
1170 CanThrowResult CT = canCalleeThrow(*this, CE, CE->getConstructor());
1171 if (CT == CT_Can)
1172 return CT;
1173 return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
1174 }
1175
1176 case Expr::CXXInheritedCtorInitExprClass: {
1177 auto *ICIE = cast<CXXInheritedCtorInitExpr>(S);
1178 return canCalleeThrow(*this, ICIE, ICIE->getConstructor());
1179 }
1180
1181 case Expr::LambdaExprClass: {
1182 const LambdaExpr *Lambda = cast<LambdaExpr>(S);
1185 Cap = Lambda->capture_init_begin(),
1186 CapEnd = Lambda->capture_init_end();
1187 Cap != CapEnd; ++Cap)
1188 CT = mergeCanThrow(CT, canThrow(*Cap));
1189 return CT;
1190 }
1191
1192 case Expr::CXXNewExprClass: {
1193 auto *NE = cast<CXXNewExpr>(S);
1194 CanThrowResult CT;
1195 if (NE->isTypeDependent())
1196 CT = CT_Dependent;
1197 else
1198 CT = canCalleeThrow(*this, NE, NE->getOperatorNew());
1199 if (CT == CT_Can)
1200 return CT;
1201 return mergeCanThrow(CT, canSubStmtsThrow(*this, NE));
1202 }
1203
1204 case Expr::CXXDeleteExprClass: {
1205 auto *DE = cast<CXXDeleteExpr>(S);
1207 QualType DTy = DE->getDestroyedType();
1208 if (DTy.isNull() || DTy->isDependentType()) {
1209 CT = CT_Dependent;
1210 } else {
1211 // C++20 [expr.delete]p6: If the value of the operand of the delete-
1212 // expression is not a null pointer value and the selected deallocation
1213 // function (see below) is not a destroying operator delete, the delete-
1214 // expression will invoke the destructor (if any) for the object or the
1215 // elements of the array being deleted.
1216 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1217 if (const auto *RD = DTy->getAsCXXRecordDecl()) {
1218 if (const CXXDestructorDecl *DD = RD->getDestructor();
1219 DD && DD->isCalledByDelete(OperatorDelete))
1220 CT = canCalleeThrow(*this, DE, DD);
1221 }
1222
1223 // We always look at the exception specification of the operator delete.
1224 CT = mergeCanThrow(CT, canCalleeThrow(*this, DE, OperatorDelete));
1225
1226 // If we know we can throw, we're done.
1227 if (CT == CT_Can)
1228 return CT;
1229 }
1230 return mergeCanThrow(CT, canSubStmtsThrow(*this, DE));
1231 }
1232
1233 case Expr::CXXBindTemporaryExprClass: {
1234 auto *BTE = cast<CXXBindTemporaryExpr>(S);
1235 // The bound temporary has to be destroyed again, which might throw.
1236 CanThrowResult CT =
1237 canCalleeThrow(*this, BTE, BTE->getTemporary()->getDestructor());
1238 if (CT == CT_Can)
1239 return CT;
1240 return mergeCanThrow(CT, canSubStmtsThrow(*this, BTE));
1241 }
1242
1243 case Expr::PseudoObjectExprClass: {
1244 auto *POE = cast<PseudoObjectExpr>(S);
1246 for (const Expr *E : POE->semantics()) {
1247 CT = mergeCanThrow(CT, canThrow(E));
1248 if (CT == CT_Can)
1249 break;
1250 }
1251 return CT;
1252 }
1253
1254 case Stmt::SYCLKernelCallStmtClass: {
1255 auto *SKCS = cast<SYCLKernelCallStmt>(S);
1256 if (getLangOpts().SYCLIsDevice)
1257 return canSubStmtsThrow(*this,
1258 SKCS->getOutlinedFunctionDecl()->getBody());
1259 assert(getLangOpts().SYCLIsHost);
1260 return canSubStmtsThrow(*this, SKCS->getKernelLaunchStmt());
1261 }
1262
1263 case Stmt::UnresolvedSYCLKernelCallStmtClass:
1264 return CT_Dependent;
1265
1266 // ObjC message sends are like function calls, but never have exception
1267 // specs.
1268 case Expr::ObjCMessageExprClass:
1269 case Expr::ObjCPropertyRefExprClass:
1270 case Expr::ObjCSubscriptRefExprClass:
1271 return CT_Can;
1272
1273 // All the ObjC literals that are implemented as calls are
1274 // potentially throwing unless we decide to close off that
1275 // possibility.
1276 case Expr::ObjCArrayLiteralClass:
1277 case Expr::ObjCDictionaryLiteralClass:
1278 case Expr::ObjCBoxedExprClass:
1279 return CT_Can;
1280
1281 // Many other things have subexpressions, so we have to test those.
1282 // Some are simple:
1283 case Expr::CoawaitExprClass:
1284 case Expr::ConditionalOperatorClass:
1285 case Expr::CoyieldExprClass:
1286 case Expr::CXXRewrittenBinaryOperatorClass:
1287 case Expr::CXXStdInitializerListExprClass:
1288 case Expr::DesignatedInitExprClass:
1289 case Expr::DesignatedInitUpdateExprClass:
1290 case Expr::ExprWithCleanupsClass:
1291 case Expr::ExtVectorElementExprClass:
1292 case Expr::MatrixElementExprClass:
1293 case Expr::InitListExprClass:
1294 case Expr::ArrayInitLoopExprClass:
1295 case Expr::MemberExprClass:
1296 case Expr::ObjCIsaExprClass:
1297 case Expr::ObjCIvarRefExprClass:
1298 case Expr::ParenExprClass:
1299 case Expr::ParenListExprClass:
1300 case Expr::ShuffleVectorExprClass:
1301 case Expr::StmtExprClass:
1302 case Expr::ConvertVectorExprClass:
1303 case Expr::VAArgExprClass:
1304 case Expr::CXXParenListInitExprClass:
1305 return canSubStmtsThrow(*this, S);
1306
1307 case Expr::CompoundLiteralExprClass:
1308 case Expr::CXXConstCastExprClass:
1309 case Expr::CXXAddrspaceCastExprClass:
1310 case Expr::CXXReinterpretCastExprClass:
1311 case Expr::BuiltinBitCastExprClass:
1312 // FIXME: Properly determine whether a variably-modified type can throw.
1313 if (cast<Expr>(S)->getType()->isVariablyModifiedType())
1314 return CT_Can;
1315 return canSubStmtsThrow(*this, S);
1316
1317 // Some might be dependent for other reasons.
1318 case Expr::ArraySubscriptExprClass:
1319 case Expr::MatrixSubscriptExprClass:
1320 case Expr::MatrixSingleSubscriptExprClass:
1321 case Expr::ArraySectionExprClass:
1322 case Expr::OMPArrayShapingExprClass:
1323 case Expr::OMPIteratorExprClass:
1324 case Expr::BinaryOperatorClass:
1325 case Expr::DependentCoawaitExprClass:
1326 case Expr::CompoundAssignOperatorClass:
1327 case Expr::CStyleCastExprClass:
1328 case Expr::CXXStaticCastExprClass:
1329 case Expr::CXXFunctionalCastExprClass:
1330 case Expr::ImplicitCastExprClass:
1331 case Expr::MaterializeTemporaryExprClass:
1332 case Expr::UnaryOperatorClass: {
1333 // FIXME: Properly determine whether a variably-modified type can throw.
1334 if (auto *CE = dyn_cast<CastExpr>(S))
1335 if (CE->getType()->isVariablyModifiedType())
1336 return CT_Can;
1337 CanThrowResult CT =
1338 cast<Expr>(S)->isTypeDependent() ? CT_Dependent : CT_Cannot;
1339 return mergeCanThrow(CT, canSubStmtsThrow(*this, S));
1340 }
1341
1342 case Expr::CXXDefaultArgExprClass:
1344
1345 case Expr::CXXDefaultInitExprClass:
1347
1348 case Expr::ChooseExprClass: {
1349 auto *CE = cast<ChooseExpr>(S);
1350 if (CE->isTypeDependent() || CE->isValueDependent())
1351 return CT_Dependent;
1352 return canThrow(CE->getChosenSubExpr());
1353 }
1354
1355 case Expr::GenericSelectionExprClass:
1356 if (cast<GenericSelectionExpr>(S)->isResultDependent())
1357 return CT_Dependent;
1358 return canThrow(cast<GenericSelectionExpr>(S)->getResultExpr());
1359
1360 // Some expressions are always dependent.
1361 case Expr::CXXDependentScopeMemberExprClass:
1362 case Expr::CXXUnresolvedConstructExprClass:
1363 case Expr::DependentScopeDeclRefExprClass:
1364 case Expr::CXXFoldExprClass:
1365 case Expr::RecoveryExprClass:
1366 return CT_Dependent;
1367
1368 case Expr::AsTypeExprClass:
1369 case Expr::BinaryConditionalOperatorClass:
1370 case Expr::BlockExprClass:
1371 case Expr::CUDAKernelCallExprClass:
1372 case Expr::DeclRefExprClass:
1373 case Expr::ObjCBridgedCastExprClass:
1374 case Expr::ObjCIndirectCopyRestoreExprClass:
1375 case Expr::ObjCProtocolExprClass:
1376 case Expr::ObjCSelectorExprClass:
1377 case Expr::ObjCAvailabilityCheckExprClass:
1378 case Expr::OffsetOfExprClass:
1379 case Expr::PackExpansionExprClass:
1380 case Expr::SubstNonTypeTemplateParmExprClass:
1381 case Expr::SubstNonTypeTemplateParmPackExprClass:
1382 case Expr::FunctionParmPackExprClass:
1383 case Expr::UnaryExprOrTypeTraitExprClass:
1384 case Expr::UnresolvedLookupExprClass:
1385 case Expr::UnresolvedMemberExprClass:
1386 // FIXME: Many of the above can throw.
1387 return CT_Cannot;
1388
1389 case Expr::AddrLabelExprClass:
1390 case Expr::ArrayTypeTraitExprClass:
1391 case Expr::AtomicExprClass:
1392 case Expr::TypeTraitExprClass:
1393 case Expr::CXXBoolLiteralExprClass:
1394 case Expr::CXXNoexceptExprClass:
1395 case Expr::CXXNullPtrLiteralExprClass:
1396 case Expr::CXXPseudoDestructorExprClass:
1397 case Expr::CXXReflectExprClass:
1398 case Expr::CXXScalarValueInitExprClass:
1399 case Expr::CXXThisExprClass:
1400 case Expr::CXXUuidofExprClass:
1401 case Expr::CharacterLiteralClass:
1402 case Expr::ExpressionTraitExprClass:
1403 case Expr::FloatingLiteralClass:
1404 case Expr::GNUNullExprClass:
1405 case Expr::ImaginaryLiteralClass:
1406 case Expr::ImplicitValueInitExprClass:
1407 case Expr::IntegerLiteralClass:
1408 case Expr::FixedPointLiteralClass:
1409 case Expr::ArrayInitIndexExprClass:
1410 case Expr::NoInitExprClass:
1411 case Expr::ObjCEncodeExprClass:
1412 case Expr::ObjCStringLiteralClass:
1413 case Expr::ObjCBoolLiteralExprClass:
1414 case Expr::OpaqueValueExprClass:
1415 case Expr::PredefinedExprClass:
1416 case Expr::SizeOfPackExprClass:
1417 case Expr::PackIndexingExprClass:
1418 case Expr::StringLiteralClass:
1419 case Expr::SourceLocExprClass:
1420 case Expr::EmbedExprClass:
1421 case Expr::ConceptSpecializationExprClass:
1422 case Expr::RequiresExprClass:
1423 case Expr::HLSLOutArgExprClass:
1424 case Stmt::OpenACCEnterDataConstructClass:
1425 case Stmt::OpenACCExitDataConstructClass:
1426 case Stmt::OpenACCWaitConstructClass:
1427 case Stmt::OpenACCCacheConstructClass:
1428 case Stmt::OpenACCInitConstructClass:
1429 case Stmt::OpenACCShutdownConstructClass:
1430 case Stmt::OpenACCSetConstructClass:
1431 case Stmt::OpenACCUpdateConstructClass:
1432 // These expressions can never throw.
1433 return CT_Cannot;
1434
1435 case Expr::MSPropertyRefExprClass:
1436 case Expr::MSPropertySubscriptExprClass:
1437 llvm_unreachable("Invalid class for expression");
1438
1439 // Most statements can throw if any substatement can throw.
1440 case Stmt::OpenACCComputeConstructClass:
1441 case Stmt::OpenACCLoopConstructClass:
1442 case Stmt::OpenACCCombinedConstructClass:
1443 case Stmt::OpenACCDataConstructClass:
1444 case Stmt::OpenACCHostDataConstructClass:
1445 case Stmt::OpenACCAtomicConstructClass:
1446 case Stmt::AttributedStmtClass:
1447 case Stmt::BreakStmtClass:
1448 case Stmt::CapturedStmtClass:
1449 case Stmt::CaseStmtClass:
1450 case Stmt::CompoundStmtClass:
1451 case Stmt::ContinueStmtClass:
1452 case Stmt::CoreturnStmtClass:
1453 case Stmt::CoroutineBodyStmtClass:
1454 case Stmt::CXXCatchStmtClass:
1455 case Stmt::CXXForRangeStmtClass:
1456 case Stmt::DefaultStmtClass:
1457 case Stmt::DoStmtClass:
1458 case Stmt::ForStmtClass:
1459 case Stmt::GCCAsmStmtClass:
1460 case Stmt::GotoStmtClass:
1461 case Stmt::IndirectGotoStmtClass:
1462 case Stmt::LabelStmtClass:
1463 case Stmt::MSAsmStmtClass:
1464 case Stmt::MSDependentExistsStmtClass:
1465 case Stmt::NullStmtClass:
1466 case Stmt::ObjCAtCatchStmtClass:
1467 case Stmt::ObjCAtFinallyStmtClass:
1468 case Stmt::ObjCAtSynchronizedStmtClass:
1469 case Stmt::ObjCAutoreleasePoolStmtClass:
1470 case Stmt::ObjCForCollectionStmtClass:
1471 case Stmt::OMPAtomicDirectiveClass:
1472 case Stmt::OMPAssumeDirectiveClass:
1473 case Stmt::OMPBarrierDirectiveClass:
1474 case Stmt::OMPCancelDirectiveClass:
1475 case Stmt::OMPCancellationPointDirectiveClass:
1476 case Stmt::OMPCriticalDirectiveClass:
1477 case Stmt::OMPDistributeDirectiveClass:
1478 case Stmt::OMPDistributeParallelForDirectiveClass:
1479 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1480 case Stmt::OMPDistributeSimdDirectiveClass:
1481 case Stmt::OMPFlushDirectiveClass:
1482 case Stmt::OMPDepobjDirectiveClass:
1483 case Stmt::OMPScanDirectiveClass:
1484 case Stmt::OMPForDirectiveClass:
1485 case Stmt::OMPForSimdDirectiveClass:
1486 case Stmt::OMPMasterDirectiveClass:
1487 case Stmt::OMPMasterTaskLoopDirectiveClass:
1488 case Stmt::OMPMaskedTaskLoopDirectiveClass:
1489 case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
1490 case Stmt::OMPMaskedTaskLoopSimdDirectiveClass:
1491 case Stmt::OMPOrderedDirectiveClass:
1492 case Stmt::OMPCanonicalLoopClass:
1493 case Stmt::OMPParallelDirectiveClass:
1494 case Stmt::OMPParallelForDirectiveClass:
1495 case Stmt::OMPParallelForSimdDirectiveClass:
1496 case Stmt::OMPParallelMasterDirectiveClass:
1497 case Stmt::OMPParallelMaskedDirectiveClass:
1498 case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
1499 case Stmt::OMPParallelMaskedTaskLoopDirectiveClass:
1500 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
1501 case Stmt::OMPParallelMaskedTaskLoopSimdDirectiveClass:
1502 case Stmt::OMPParallelSectionsDirectiveClass:
1503 case Stmt::OMPSectionDirectiveClass:
1504 case Stmt::OMPSectionsDirectiveClass:
1505 case Stmt::OMPSimdDirectiveClass:
1506 case Stmt::OMPTileDirectiveClass:
1507 case Stmt::OMPStripeDirectiveClass:
1508 case Stmt::OMPUnrollDirectiveClass:
1509 case Stmt::OMPReverseDirectiveClass:
1510 case Stmt::OMPInterchangeDirectiveClass:
1511 case Stmt::OMPFuseDirectiveClass:
1512 case Stmt::OMPSingleDirectiveClass:
1513 case Stmt::OMPTargetDataDirectiveClass:
1514 case Stmt::OMPTargetDirectiveClass:
1515 case Stmt::OMPTargetEnterDataDirectiveClass:
1516 case Stmt::OMPTargetExitDataDirectiveClass:
1517 case Stmt::OMPTargetParallelDirectiveClass:
1518 case Stmt::OMPTargetParallelForDirectiveClass:
1519 case Stmt::OMPTargetParallelForSimdDirectiveClass:
1520 case Stmt::OMPTargetSimdDirectiveClass:
1521 case Stmt::OMPTargetTeamsDirectiveClass:
1522 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1523 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1524 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1525 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1526 case Stmt::OMPTargetUpdateDirectiveClass:
1527 case Stmt::OMPScopeDirectiveClass:
1528 case Stmt::OMPTaskDirectiveClass:
1529 case Stmt::OMPTaskgroupDirectiveClass:
1530 case Stmt::OMPTaskLoopDirectiveClass:
1531 case Stmt::OMPTaskLoopSimdDirectiveClass:
1532 case Stmt::OMPTaskwaitDirectiveClass:
1533 case Stmt::OMPTaskyieldDirectiveClass:
1534 case Stmt::OMPErrorDirectiveClass:
1535 case Stmt::OMPTeamsDirectiveClass:
1536 case Stmt::OMPTeamsDistributeDirectiveClass:
1537 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1538 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1539 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1540 case Stmt::OMPInteropDirectiveClass:
1541 case Stmt::OMPDispatchDirectiveClass:
1542 case Stmt::OMPMaskedDirectiveClass:
1543 case Stmt::OMPMetaDirectiveClass:
1544 case Stmt::OMPGenericLoopDirectiveClass:
1545 case Stmt::OMPTeamsGenericLoopDirectiveClass:
1546 case Stmt::OMPTargetTeamsGenericLoopDirectiveClass:
1547 case Stmt::OMPParallelGenericLoopDirectiveClass:
1548 case Stmt::OMPTargetParallelGenericLoopDirectiveClass:
1549 case Stmt::ReturnStmtClass:
1550 case Stmt::SEHExceptStmtClass:
1551 case Stmt::SEHFinallyStmtClass:
1552 case Stmt::SEHLeaveStmtClass:
1553 case Stmt::SEHTryStmtClass:
1554 case Stmt::SwitchStmtClass:
1555 case Stmt::WhileStmtClass:
1556 case Stmt::DeferStmtClass:
1557 return canSubStmtsThrow(*this, S);
1558
1559 case Stmt::DeclStmtClass: {
1561 for (const Decl *D : cast<DeclStmt>(S)->decls()) {
1562 if (auto *VD = dyn_cast<VarDecl>(D))
1563 CT = mergeCanThrow(CT, canVarDeclThrow(*this, VD));
1564
1565 // FIXME: Properly determine whether a variably-modified type can throw.
1566 if (auto *TND = dyn_cast<TypedefNameDecl>(D))
1567 if (TND->getUnderlyingType()->isVariablyModifiedType())
1568 return CT_Can;
1569 if (auto *VD = dyn_cast<ValueDecl>(D))
1570 if (VD->getType()->isVariablyModifiedType())
1571 return CT_Can;
1572 }
1573 return CT;
1574 }
1575
1576 case Stmt::IfStmtClass: {
1577 auto *IS = cast<IfStmt>(S);
1579 if (const Stmt *Init = IS->getInit())
1580 CT = mergeCanThrow(CT, canThrow(Init));
1581 if (const Stmt *CondDS = IS->getConditionVariableDeclStmt())
1582 CT = mergeCanThrow(CT, canThrow(CondDS));
1583 CT = mergeCanThrow(CT, canThrow(IS->getCond()));
1584
1585 // For 'if constexpr', consider only the non-discarded case.
1586 // FIXME: We should add a DiscardedStmt marker to the AST.
1587 if (std::optional<const Stmt *> Case = IS->getNondiscardedCase(Context))
1588 return *Case ? mergeCanThrow(CT, canThrow(*Case)) : CT;
1589
1590 CanThrowResult Then = canThrow(IS->getThen());
1591 CanThrowResult Else = IS->getElse() ? canThrow(IS->getElse()) : CT_Cannot;
1592 if (Then == Else)
1593 return mergeCanThrow(CT, Then);
1594
1595 // For a dependent 'if constexpr', the result is dependent if it depends on
1596 // the value of the condition.
1597 return mergeCanThrow(CT, IS->isConstexpr() ? CT_Dependent
1598 : mergeCanThrow(Then, Else));
1599 }
1600
1601 case Stmt::CXXTryStmtClass: {
1602 auto *TS = cast<CXXTryStmt>(S);
1603 // try /*...*/ catch (...) { H } can throw only if H can throw.
1604 // Any other try-catch can throw if any substatement can throw.
1605 const CXXCatchStmt *FinalHandler = TS->getHandler(TS->getNumHandlers() - 1);
1606 if (!FinalHandler->getExceptionDecl())
1607 return canThrow(FinalHandler->getHandlerBlock());
1608 return canSubStmtsThrow(*this, S);
1609 }
1610
1611 case Stmt::ObjCAtThrowStmtClass:
1612 return CT_Can;
1613
1614 case Stmt::ObjCAtTryStmtClass: {
1615 auto *TS = cast<ObjCAtTryStmt>(S);
1616
1617 // @catch(...) need not be last in Objective-C. Walk backwards until we
1618 // see one or hit the @try.
1620 if (const Stmt *Finally = TS->getFinallyStmt())
1621 CT = mergeCanThrow(CT, canThrow(Finally));
1622 for (unsigned I = TS->getNumCatchStmts(); I != 0; --I) {
1623 const ObjCAtCatchStmt *Catch = TS->getCatchStmt(I - 1);
1624 CT = mergeCanThrow(CT, canThrow(Catch));
1625 // If we reach a @catch(...), no earlier exceptions can escape.
1626 if (Catch->hasEllipsis())
1627 return CT;
1628 }
1629
1630 // Didn't find an @catch(...). Exceptions from the @try body can escape.
1631 return mergeCanThrow(CT, canThrow(TS->getTryBody()));
1632 }
1633
1634 case Stmt::SYCLUniqueStableNameExprClass:
1635 return CT_Cannot;
1636 case Stmt::OpenACCAsteriskSizeExprClass:
1637 return CT_Cannot;
1638 case Stmt::NoStmtClass:
1639 llvm_unreachable("Invalid class for statement");
1640 }
1641 llvm_unreachable("Bogus StmtClass");
1642}
1643
1644} // end namespace clang
Defines the Diagnostic-related interfaces.
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
Defines the clang::Preprocessor interface.
Defines the SourceManager interface.
Defines the Objective-C statement AST node classes.
Expr * getExpr()
Get 'expr' part of the associated expression/statement.
This file defines SYCL AST classes used to represent calls to SYCL kernels.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
Pointer to a block type.
Definition TypeBase.h:3550
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:724
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:28
Stmt * getHandlerBlock() const
Definition StmtCXX.h:51
VarDecl * getExceptionDecl() const
Definition StmtCXX.h:49
Represents a C++ destructor within a class.
Definition DeclCXX.h:2876
bool isCalledByDelete(const FunctionDecl *OpDel=nullptr) const
Will this destructor ever be called when considering which deallocation function is associated with t...
Definition DeclCXX.cpp:3208
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition ExprCXX.h:482
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:849
bool isTypeOperand() const
Definition ExprCXX.h:885
Expr * getExprOperand() const
Definition ExprCXX.h:896
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:134
bool hasNullCheck() const
Whether this is of a form like "typeid(*ptr)" that can throw a std::bad_typeid if a pointer is a null...
Definition ExprCXX.cpp:200
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
Expr * getCallee()
Definition Expr.h:3093
Decl * getCalleeDecl()
Definition Expr.h:3123
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CastKind getCastKind() const
Definition Expr.h:3723
Expr * getSubExpr()
Definition Expr.h:3729
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:350
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
bool isRecord() const
Definition DeclBase.h:2189
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1921
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2104
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2351
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3958
This represents one expression.
Definition Expr.h:112
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition Expr.h:241
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3090
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3086
QualType getType() const
Definition Expr.h:144
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2000
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3763
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3866
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3619
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5315
bool hasDependentExceptionSpec() const
Return whether this function has a dependent exception spec.
Definition Type.cpp:3893
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5622
unsigned getNumExceptions() const
Return the number of types in the exception specification.
Definition TypeBase.h:5665
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5628
CanThrowResult canThrow() const
Determine whether this function type has a non-throwing exception specification.
Definition Type.cpp:3914
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5680
ArrayRef< QualType > exceptions() const
Definition TypeBase.h:5769
exception_iterator exception_begin() const
Definition TypeBase.h:5773
FunctionDecl * getExceptionSpecDecl() const
If this function type has an exception specification which hasn't been determined yet (either because...
Definition TypeBase.h:5690
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1969
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2107
Expr *const * const_capture_init_iterator
Const iterator that walks over the capture initialization arguments.
Definition ExprCXX.h:2081
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2095
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3661
Represents Objective-C's @catch statement.
Definition StmtObjC.h:77
bool hasEllipsis() const
Definition StmtObjC.h:113
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3336
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8472
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition Type.cpp:2984
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8461
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3581
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD)
Evaluate the implicit exception specification for a defaulted special member function.
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function)
@ AR_dependent
Definition Sema.h:1680
@ AR_accessible
Definition Sema.h:1678
@ AR_inaccessible
Definition Sema.h:1679
@ AR_delayed
Definition Sema.h:1681
Preprocessor & getPreprocessor() const
Definition Sema.h:938
ASTContext & Context
Definition Sema.h:1300
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
ASTContext & getASTContext() const
Definition Sema.h:939
SmallVector< std::pair< FunctionDecl *, FunctionDecl * >, 2 > DelayedEquivalentExceptionSpecChecks
All the function redeclarations seen during a class definition that had their exception spec checks d...
Definition Sema.h:6658
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1204
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, bool SkipTargetFirstParameter, SourceLocation TargetLoc, const FunctionProtoType *Source, bool SkipSourceFirstParameter, SourceLocation SourceLoc)
CheckParamExceptionSpec - Check if the parameter and return types of the two functions have equivalen...
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
const LangOptions & getLangOpts() const
Definition Sema.h:932
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr, ExceptionSpecificationType &EST)
Check the given noexcept-specifier, convert its expression, and compute the appropriate ExceptionSpec...
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedOverridingExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
Definition Sema.h:6650
bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D)
Determine if we're in a case where we need to (incorrectly) eagerly parse an exception specification ...
bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, const FunctionProtoType *Superset, bool SkipSupersetFirstParameter, SourceLocation SuperLoc, const FunctionProtoType *Subset, bool SkipSubsetFirstParameter, SourceLocation SubLoc)
CheckExceptionSpecSubset - Check whether the second function type's exception specification is a subs...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1438
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
CanThrowResult canThrow(const Stmt *E)
bool handlerCanCatch(QualType HandlerType, QualType ExceptionType)
bool CheckDistantExceptionSpec(QualType T)
CheckDistantExceptionSpec - Check if the given type is a pointer or pointer to member to a function w...
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:651
static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, SourceLocation Loc=SourceLocation())
Determine whether the callee of a particular function call can throw.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:86
@ NoStmtClass
Definition Stmt.h:89
child_range children()
Definition Stmt.cpp:304
StmtClass getStmtClass() const
Definition Stmt.h:1485
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1437
A container of type source information.
Definition TypeBase.h:8359
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition Type.cpp:2611
bool isVoidType() const
Definition TypeBase.h:8991
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isPointerType() const
Definition TypeBase.h:8625
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9285
bool isReferenceType() const
Definition TypeBase.h:8649
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2790
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9171
bool isMemberPointerType() const
Definition TypeBase.h:8706
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2516
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9218
bool isNullPtrType() const
Definition TypeBase.h:9028
bool isRecordType() const
Definition TypeBase.h:8752
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2863
const Expr * getInit() const
Definition Decl.h:1368
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition Decl.cpp:2540
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus11
@ CPlusPlus17
CanThrowResult
Possible results from evaluation of a noexcept expression.
static const FunctionProtoType * GetUnderlyingFunction(QualType T)
bool isDynamicExceptionSpec(ExceptionSpecificationType ESpecType)
static bool CheckEquivalentExceptionSpecImpl(Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc, bool *MissingExceptionSpecification=nullptr, bool *MissingEmptyExceptionSpecification=nullptr, bool AllowNoexceptAllMatchWithNoSpec=false, bool IsOperatorNew=false)
CheckEquivalentExceptionSpec - Check if the two types have compatible exception specifications.
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ Success
Annotation was successful.
Definition Parser.h:65
static bool hasImplicitExceptionSpec(FunctionDecl *Decl)
Determine whether a function has an implicitly-generated exception specification.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
CanThrowResult mergeCanThrow(CanThrowResult CT1, CanThrowResult CT2)
@ Result
The result type of a method or function.
Definition TypeBase.h:905
static CanThrowResult canVarDeclThrow(Sema &Self, const VarDecl *VD)
static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC)
static CanThrowResult canSubStmtsThrow(Sema &Self, const Stmt *S)
static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC)
static bool CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID, QualType Target, SourceLocation TargetLoc, QualType Source, SourceLocation SourceLoc)
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:846
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
static bool exceptionSpecNotKnownYet(const FunctionDecl *FD)
Holds information about the various types of exception specification.
Definition TypeBase.h:5372
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5374