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