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