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