clang 22.0.0git
Sema.h
Go to the documentation of this file.
1//===--- Sema.h - Semantic Analysis & AST Building --------------*- 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 defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/ASTLambda.h"
20#include "clang/AST/Attr.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/DeclBase.h"
24#include "clang/AST/DeclCXX.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
33#include "clang/AST/StmtCXX.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
39#include "clang/Basic/Cuda.h"
43#include "clang/Basic/LLVM.h"
44#include "clang/Basic/Lambda.h"
46#include "clang/Basic/Module.h"
58#include "clang/Sema/Attr.h"
60#include "clang/Sema/DeclSpec.h"
66#include "clang/Sema/Scope.h"
67#include "clang/Sema/SemaBase.h"
70#include "clang/Sema/Weak.h"
71#include "llvm/ADT/APInt.h"
72#include "llvm/ADT/ArrayRef.h"
73#include "llvm/ADT/BitmaskEnum.h"
74#include "llvm/ADT/DenseMap.h"
75#include "llvm/ADT/DenseSet.h"
76#include "llvm/ADT/FloatingPointMode.h"
77#include "llvm/ADT/FoldingSet.h"
78#include "llvm/ADT/MapVector.h"
79#include "llvm/ADT/PointerIntPair.h"
80#include "llvm/ADT/PointerUnion.h"
81#include "llvm/ADT/STLExtras.h"
82#include "llvm/ADT/STLForwardCompat.h"
83#include "llvm/ADT/STLFunctionalExtras.h"
84#include "llvm/ADT/SetVector.h"
85#include "llvm/ADT/SmallBitVector.h"
86#include "llvm/ADT/SmallPtrSet.h"
87#include "llvm/ADT/SmallSet.h"
88#include "llvm/ADT/SmallVector.h"
89#include "llvm/ADT/StringExtras.h"
90#include "llvm/ADT/StringMap.h"
91#include "llvm/ADT/TinyPtrVector.h"
92#include "llvm/Support/Allocator.h"
93#include "llvm/Support/Compiler.h"
94#include "llvm/Support/Error.h"
95#include "llvm/Support/ErrorHandling.h"
96#include <cassert>
97#include <climits>
98#include <cstddef>
99#include <cstdint>
100#include <deque>
101#include <functional>
102#include <iterator>
103#include <memory>
104#include <optional>
105#include <string>
106#include <tuple>
107#include <type_traits>
108#include <utility>
109#include <vector>
110
111namespace llvm {
112struct InlineAsmIdentifierInfo;
113} // namespace llvm
114
115namespace clang {
116class ADLResult;
117class APValue;
119class ASTConsumer;
120class ASTContext;
121class ASTDeclReader;
123class ASTReader;
124class ASTWriter;
125class CXXBasePath;
126class CXXBasePaths;
129enum class ComparisonCategoryType : unsigned char;
131class DarwinSDKInfo;
132class DeclGroupRef;
136class Designation;
137class IdentifierInfo;
143enum class LangAS : unsigned int;
145class LookupResult;
148class ModuleLoader;
152class ObjCMethodDecl;
153struct OverloadCandidate;
154enum class OverloadCandidateParamOrder : char;
155enum OverloadCandidateRewriteKind : unsigned;
157class Preprocessor;
158class SemaAMDGPU;
159class SemaARM;
160class SemaAVR;
161class SemaBPF;
163class SemaCUDA;
164class SemaDirectX;
165class SemaHLSL;
166class SemaHexagon;
167class SemaLoongArch;
168class SemaM68k;
169class SemaMIPS;
170class SemaMSP430;
171class SemaNVPTX;
172class SemaObjC;
173class SemaOpenACC;
174class SemaOpenCL;
175class SemaOpenMP;
176class SemaPPC;
177class SemaPseudoObject;
178class SemaRISCV;
179class SemaSPIRV;
180class SemaSYCL;
181class SemaSwift;
182class SemaSystemZ;
183class SemaWasm;
184class SemaX86;
186class TemplateArgument;
191class Token;
192class TypeConstraint;
197
198namespace sema {
199class BlockScopeInfo;
200class Capture;
207class LambdaScopeInfo;
208class SemaPPCallbacks;
210} // namespace sema
211
212// AssignmentAction - This is used by all the assignment diagnostic functions
213// to represent what is actually causing the operation
224
225namespace threadSafety {
226class BeforeSet;
227void threadSafetyCleanup(BeforeSet *Cache);
228} // namespace threadSafety
229
230// FIXME: No way to easily map from TemplateTypeParmTypes to
231// TemplateTypeParmDecls, so we have this horrible PointerUnion.
232typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *,
233 const TemplateSpecializationType *,
234 const SubstBuiltinTemplatePackType *>,
237
238/// Describes whether we've seen any nullability information for the given
239/// file.
241 /// The first pointer declarator (of any pointer kind) in the file that does
242 /// not have a corresponding nullability annotation.
244
245 /// The end location for the first pointer declarator in the file. Used for
246 /// placing fix-its.
248
249 /// Which kind of pointer declarator we saw.
250 uint8_t PointerKind;
251
252 /// Whether we saw any type nullability annotations in the given file.
253 bool SawTypeNullability = false;
254};
255
256/// A mapping from file IDs to a record of whether we've seen nullability
257/// information in that file.
259 /// A mapping from file IDs to the nullability information for each file ID.
260 llvm::DenseMap<FileID, FileNullability> Map;
261
262 /// A single-element cache based on the file ID.
263 struct {
266 } Cache;
267
268public:
270 // Check the single-element cache.
271 if (file == Cache.File)
272 return Cache.Nullability;
273
274 // It's not in the single-element cache; flush the cache if we have one.
275 if (!Cache.File.isInvalid()) {
276 Map[Cache.File] = Cache.Nullability;
277 }
278
279 // Pull this entry into the cache.
280 Cache.File = file;
281 Cache.Nullability = Map[file];
282 return Cache.Nullability;
283 }
284};
285
286/// Tracks expected type during expression parsing, for use in code completion.
287/// The type is tied to a particular token, all functions that update or consume
288/// the type take a start location of the token they are looking at as a
289/// parameter. This avoids updating the type on hot paths in the parser.
291public:
293 : Ctx(Ctx), Enabled(Enabled) {}
294
298 /// Handles e.g. BaseType{ .D = Tok...
300 const Designation &D);
301 /// Computing a type for the function argument may require running
302 /// overloading, so we postpone its computation until it is actually needed.
303 ///
304 /// Clients should be very careful when using this function, as it stores a
305 /// function_ref, clients should make sure all calls to get() with the same
306 /// location happen while function_ref is alive.
307 ///
308 /// The callback should also emit signature help as a side-effect, but only
309 /// if the completion point has been reached.
311 llvm::function_ref<QualType()> ComputeType);
312
315 SourceLocation OpLoc);
318 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
319 /// Handles all type casts, including C-style cast, C++ casts, etc.
321
322 /// Get the expected type associated with this location, if any.
323 ///
324 /// If the location is a function argument, determining the expected type
325 /// involves considering all function overloads and the arguments so far.
326 /// In this case, signature help for these function overloads will be reported
327 /// as a side-effect (only if the completion point has been reached).
329 if (!Enabled || Tok != ExpectedLoc)
330 return QualType();
331 if (!Type.isNull())
332 return Type;
333 if (ComputeType)
334 return ComputeType();
335 return QualType();
336 }
337
338private:
339 ASTContext *Ctx;
340 bool Enabled;
341 /// Start position of a token for which we store expected type.
342 SourceLocation ExpectedLoc;
343 /// Expected type for a token starting at ExpectedLoc.
345 /// A function to compute expected type at ExpectedLoc. It is only considered
346 /// if Type is null.
347 llvm::function_ref<QualType()> ComputeType;
348};
349
351 SkipBodyInfo() = default;
352 bool ShouldSkip = false;
354 NamedDecl *Previous = nullptr;
355 NamedDecl *New = nullptr;
356};
357
358/// Describes the result of template argument deduction.
359///
360/// The TemplateDeductionResult enumeration describes the result of
361/// template argument deduction, as returned from
362/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
363/// structure provides additional information about the results of
364/// template argument deduction, e.g., the deduced template argument
365/// list (if successful) or the specific template parameters or
366/// deduced arguments that were involved in the failure.
368 /// Template argument deduction was successful.
370 /// The declaration was invalid; do nothing.
372 /// Template argument deduction exceeded the maximum template
373 /// instantiation depth (which has already been diagnosed).
375 /// Template argument deduction did not deduce a value
376 /// for every template parameter.
378 /// Template argument deduction did not deduce a value for every
379 /// expansion of an expanded template parameter pack.
381 /// Template argument deduction produced inconsistent
382 /// deduced values for the given template parameter.
384 /// Template argument deduction failed due to inconsistent
385 /// cv-qualifiers on a template parameter type that would
386 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
387 /// but were given a non-const "X".
389 /// Substitution of the deduced template argument values
390 /// resulted in an error.
392 /// After substituting deduced template arguments, a dependent
393 /// parameter type did not match the corresponding argument.
395 /// After substituting deduced template arguments, an element of
396 /// a dependent parameter type did not match the corresponding element
397 /// of the corresponding argument (when deducing from an initializer list).
399 /// A non-depnedent component of the parameter did not match the
400 /// corresponding component of the argument.
402 /// When performing template argument deduction for a function
403 /// template, there were too many call arguments.
405 /// When performing template argument deduction for a function
406 /// template, there were too few call arguments.
408 /// The explicitly-specified template arguments were not valid
409 /// template arguments for the given template.
411 /// Checking non-dependent argument conversions failed.
413 /// The deduced arguments did not satisfy the constraints associated
414 /// with the template.
416 /// Deduction failed; that's all we know.
418 /// CUDA Target attributes do not match.
420 /// Some error which was already diagnosed.
422};
423
424/// Kinds of C++ special members.
434
435/// The kind of conversion being performed.
437 /// An implicit conversion.
439 /// A C-style cast.
441 /// A functional-style cast.
443 /// A cast other than a C-style cast.
445 /// A conversion for an operand of a builtin overloaded operator.
447};
448
449enum class TagUseKind {
450 Reference, // Reference to a tag: 'struct foo *X;'
451 Declaration, // Fwd decl of a tag: 'struct foo;'
452 Definition, // Definition of a tag: 'struct foo { int X; } Y;'
453 Friend // Friend declaration: 'friend struct foo;'
454};
455
456/// Used with attributes/effects with a boolean condition, e.g. `nonblocking`.
457enum class FunctionEffectMode : uint8_t {
458 None, // effect is not present.
459 False, // effect(false).
460 True, // effect(true).
461 Dependent // effect(expr) where expr is dependent.
462};
463
464/// pragma clang section kind
467 BSS = 1,
468 Data = 2,
470 Text = 4,
472};
473
474enum class PragmaClangSectionAction { Set = 0, Clear = 1 };
475
477 Native, // #pragma options align=native
478 Natural, // #pragma options align=natural
479 Packed, // #pragma options align=packed
480 Power, // #pragma options align=power
481 Mac68k, // #pragma options align=mac68k
482 Reset // #pragma options align=reset
483};
484
485enum class TUFragmentKind {
486 /// The global module fragment, between 'module;' and a module-declaration.
488 /// A normal translation unit fragment. For a non-module unit, this is the
489 /// entire translation unit. Otherwise, it runs from the module-declaration
490 /// to the private-module-fragment (if any) or the end of the TU (if not).
492 /// The private module fragment, between 'module :private;' and the end of
493 /// the translation unit.
495};
496
509
510// Used for emitting the right warning by DefaultVariadicArgumentPromotion
518
527
528// Contexts where using non-trivial C union types can be disallowed. This is
529// passed to err_non_trivial_c_union_in_invalid_context.
531 // Function parameter.
533 // Function return.
535 // Default-initialized object.
537 // Variable with automatic storage duration.
539 // Initializer expression that might copy from another object.
541 // Assignment.
543 // Compound literal.
545 // Block capture.
547 // lvalue-to-rvalue conversion of volatile type.
549};
550
551/// Describes the result of the name lookup and resolution performed
552/// by \c Sema::ClassifyName().
554 /// This name is not a type or template in this context, but might be
555 /// something else.
557 /// Classification failed; an error has been produced.
559 /// The name has been typo-corrected to a keyword.
561 /// The name was classified as a type.
563 /// The name was classified as a specific non-type, non-template
564 /// declaration. ActOnNameClassifiedAsNonType should be called to
565 /// convert the declaration to an expression.
567 /// The name was classified as an ADL-only function name.
568 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
569 /// result to an expression.
571 /// The name denotes a member of a dependent type that could not be
572 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
573 /// convert the result to an expression.
575 /// The name was classified as an overload set, and an expression
576 /// representing that overload set has been formed.
577 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
578 /// expression referencing the overload set.
580 /// The name was classified as a template whose specializations are types.
582 /// The name was classified as a variable template name.
584 /// The name was classified as a function template name.
586 /// The name was classified as an ADL-only function template name.
588 /// The name was classified as a concept name.
590};
591
593 // Address discrimination argument of __ptrauth.
595
596 // Extra discriminator argument of __ptrauth.
598};
599
600/// Common ways to introduce type names without a tag for use in diagnostics.
601/// Keep in sync with err_tag_reference_non_tag.
613
614enum class OffsetOfKind {
615 // Not parsing a type within __builtin_offsetof.
617 // Parsing a type within __builtin_offsetof.
619 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
620 // To improve our diagnostic message.
622};
623
624/// Describes the kind of merge to perform for availability
625/// attributes (including "deprecated", "unavailable", and "availability").
627 /// Don't merge availability attributes at all.
629 /// Merge availability attributes for a redeclaration, which requires
630 /// an exact match.
632 /// Merge availability attributes for an override, which requires
633 /// an exact match or a weakening of constraints.
635 /// Merge availability attributes for an implementation of
636 /// a protocol requirement.
638 /// Merge availability attributes for an implementation of
639 /// an optional protocol requirement.
641};
642
644 /// The triviality of a method unaffected by "trivial_abi".
646
647 /// The triviality of a method affected by "trivial_abi".
649};
650
652
653enum class AllowFoldKind {
656};
657
658/// Context in which we're performing a usual arithmetic conversion.
659enum class ArithConvKind {
660 /// An arithmetic operation.
662 /// A bitwise operation.
664 /// A comparison.
666 /// A conditional (?:) operator.
668 /// A compound assignment expression.
670};
671
672// Used for determining in which context a type is allowed to be passed to a
673// vararg function.
681
682/// AssignConvertType - All of the 'assignment' semantic checks return this
683/// enum to indicate whether the assignment was allowed. These checks are
684/// done for simple assignments, as well as initialization, return from
685/// function, argument passing, etc. The query is phrased in terms of a
686/// source and destination type.
688 /// Compatible - the types are compatible according to the standard.
690
691 /// CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because
692 /// a void * can implicitly convert to another pointer type, which we
693 /// differentiate for better diagnostic behavior.
695
696 /// PointerToInt - The assignment converts a pointer to an int, which we
697 /// accept as an extension.
699
700 /// IntToPointer - The assignment converts an int to a pointer, which we
701 /// accept as an extension.
703
704 /// FunctionVoidPointer - The assignment is between a function pointer and
705 /// void*, which the standard doesn't allow, but we accept as an extension.
707
708 /// IncompatiblePointer - The assignment is between two pointers types that
709 /// are not compatible, but we accept them as an extension.
711
712 /// IncompatibleFunctionPointer - The assignment is between two function
713 /// pointers types that are not compatible, but we accept them as an
714 /// extension.
716
717 /// IncompatibleFunctionPointerStrict - The assignment is between two
718 /// function pointer types that are not identical, but are compatible,
719 /// unless compiled with -fsanitize=cfi, in which case the type mismatch
720 /// may trip an indirect call runtime check.
722
723 /// IncompatiblePointerSign - The assignment is between two pointers types
724 /// which point to integers which have a different sign, but are otherwise
725 /// identical. This is a subset of the above, but broken out because it's by
726 /// far the most common case of incompatible pointers.
728
729 /// CompatiblePointerDiscardsQualifiers - The assignment discards
730 /// c/v/r qualifiers, which we accept as an extension.
732
733 /// IncompatiblePointerDiscardsQualifiers - The assignment
734 /// discards qualifiers that we don't permit to be discarded,
735 /// like address spaces.
737
738 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
739 /// changes address spaces in nested pointer types which is not allowed.
740 /// For instance, converting __private int ** to __generic int ** is
741 /// illegal even though __private could be converted to __generic.
743
744 /// IncompatibleNestedPointerQualifiers - The assignment is between two
745 /// nested pointer types, and the qualifiers other than the first two
746 /// levels differ e.g. char ** -> const char **, but we accept them as an
747 /// extension.
749
750 /// IncompatibleVectors - The assignment is between two vector types that
751 /// have the same size, which we accept as an extension.
753
754 /// IntToBlockPointer - The assignment converts an int to a block
755 /// pointer. We disallow this.
757
758 /// IncompatibleBlockPointer - The assignment is between two block
759 /// pointers types that are not compatible.
761
762 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
763 /// id type and something else (that is incompatible with it). For example,
764 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
766
767 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
768 /// object with __weak qualifier.
770
771 /// Incompatible - We reject this conversion outright, it is invalid to
772 /// represent it in the AST.
774};
775
776/// The scope in which to find allocation functions.
778 /// Only look for allocation functions in the global scope.
780 /// Only look for allocation functions in the scope of the
781 /// allocated class.
783 /// Look for allocation functions in both the global scope
784 /// and in the scope of the allocated class.
786};
787
788/// Describes the result of an "if-exists" condition check.
789enum class IfExistsResult {
790 /// The symbol exists.
792
793 /// The symbol does not exist.
795
796 /// The name is a dependent name, so the results will differ
797 /// from one instantiation to the next.
799
800 /// An error occurred.
802};
803
804enum class CorrectTypoKind {
805 NonError, // CorrectTypo used in a non error recovery situation.
806 ErrorRecovery // CorrectTypo used in normal error recovery.
807};
808
809enum class OverloadKind {
810 /// This is a legitimate overload: the existing declarations are
811 /// functions or function templates with different signatures.
813
814 /// This is not an overload because the signature exactly matches
815 /// an existing declaration.
817
818 /// This is not an overload because the lookup results contain a
819 /// non-function.
821};
822
823/// Contexts in which a converted constant expression is required.
824enum class CCEKind {
825 CaseValue, ///< Expression in a case label.
826 Enumerator, ///< Enumerator value with fixed underlying type.
827 TemplateArg, ///< Value of a non-type template parameter.
828 TempArgStrict, ///< As above, but applies strict template checking
829 ///< rules.
830 ArrayBound, ///< Array bound in array declarator or new-expression.
831 ExplicitBool, ///< Condition in an explicit(bool) specifier.
832 Noexcept, ///< Condition in a noexcept(bool) specifier.
833 StaticAssertMessageSize, ///< Call to size() in a static assert
834 ///< message.
835 StaticAssertMessageData, ///< Call to data() in a static assert
836 ///< message.
837};
838
839/// Enums for the diagnostics of target, target_version and target_clones.
840namespace DiagAttrParams {
844} // end namespace DiagAttrParams
845
846void inferNoReturnAttr(Sema &S, const Decl *D);
847
848#ifdef __GNUC__
849#pragma GCC diagnostic push
850#pragma GCC diagnostic ignored "-Wattributes"
851#endif
852/// Sema - This implements semantic analysis and AST building for C.
853/// \nosubgrouping
854class Sema final : public SemaBase {
855#ifdef __GNUC__
856#pragma GCC diagnostic pop
857#endif
858 // Table of Contents
859 // -----------------
860 // 1. Semantic Analysis (Sema.cpp)
861 // 2. API Notes (SemaAPINotes.cpp)
862 // 3. C++ Access Control (SemaAccess.cpp)
863 // 4. Attributes (SemaAttr.cpp)
864 // 5. Availability Attribute Handling (SemaAvailability.cpp)
865 // 6. Bounds Safety (SemaBoundsSafety.cpp)
866 // 7. Casts (SemaCast.cpp)
867 // 8. Extra Semantic Checking (SemaChecking.cpp)
868 // 9. C++ Coroutines (SemaCoroutine.cpp)
869 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
870 // 11. Declarations (SemaDecl.cpp)
871 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
872 // 13. C++ Declarations (SemaDeclCXX.cpp)
873 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
874 // 15. Expressions (SemaExpr.cpp)
875 // 16. C++ Expressions (SemaExprCXX.cpp)
876 // 17. Member Access Expressions (SemaExprMember.cpp)
877 // 18. Initializers (SemaInit.cpp)
878 // 19. C++ Lambda Expressions (SemaLambda.cpp)
879 // 20. Name Lookup (SemaLookup.cpp)
880 // 21. Modules (SemaModule.cpp)
881 // 22. C++ Overloading (SemaOverload.cpp)
882 // 23. Statements (SemaStmt.cpp)
883 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
884 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
885 // 26. C++ Templates (SemaTemplate.cpp)
886 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
887 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
888 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
889 // 30. C++ Template Declaration Instantiation
890 // (SemaTemplateInstantiateDecl.cpp)
891 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
892 // 32. Constraints and Concepts (SemaConcept.cpp)
893 // 33. Types (SemaType.cpp)
894 // 34. FixIt Helpers (SemaFixItUtils.cpp)
895 // 35. Function Effects (SemaFunctionEffects.cpp)
896
897 /// \name Semantic Analysis
898 /// Implementations are in Sema.cpp
899 ///@{
900
901public:
902 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
904 CodeCompleteConsumer *CompletionConsumer = nullptr);
905 ~Sema();
906
907 /// Perform initialization that occurs after the parser has been
908 /// initialized but before it parses anything.
909 void Initialize();
910
911 /// This virtual key function only exists to limit the emission of debug info
912 /// describing the Sema class. GCC and Clang only emit debug info for a class
913 /// with a vtable when the vtable is emitted. Sema is final and not
914 /// polymorphic, but the debug info size savings are so significant that it is
915 /// worth adding a vtable just to take advantage of this optimization.
917
918 const LangOptions &getLangOpts() const { return LangOpts; }
921
924 Preprocessor &getPreprocessor() const { return PP; }
925 ASTContext &getASTContext() const { return Context; }
929
931 StringRef Platform);
933
934 /// Registers an external source. If an external source already exists,
935 /// creates a multiplex external source and appends to it.
936 ///
937 ///\param[in] E - A non-null external sema source.
938 ///
940
941 /// Print out statistics about the semantic analysis.
942 void PrintStats() const;
943
944 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
945 /// guaranteed). Produces a warning if we're low on stack space and allocates
946 /// more in that case. Use this in code that may recurse deeply (for example,
947 /// in template instantiation) to avoid stack overflow.
949 llvm::function_ref<void()> Fn);
950
951 /// Returns default addr space for method qualifiers.
953
954 /// Load weak undeclared identifiers from the external source.
956
957 /// Determine if VD, which must be a variable or function, is an external
958 /// symbol that nonetheless can't be referenced from outside this translation
959 /// unit because its type has no linkage and it's not extern "C".
960 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
961
962 /// Obtain a sorted list of functions that are undefined but ODR-used.
964 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
965
966 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
968 /// Retrieves list of suspicious delete-expressions that will be checked at
969 /// the end of translation unit.
970 const llvm::MapVector<FieldDecl *, DeleteLocs> &
972
973 /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
974 /// This is closely coupled to the SemaDiagnosticBuilder class and
975 /// should not be used elsewhere.
976 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
977
978 void addImplicitTypedef(StringRef Name, QualType T);
979
980 /// Whether uncompilable error has occurred. This includes error happens
981 /// in deferred diagnostics.
982 bool hasUncompilableErrorOccurred() const;
983
984 /// Looks through the macro-expansion chain for the given
985 /// location, looking for a macro expansion with the given name.
986 /// If one is found, returns true and sets the location to that
987 /// expansion loc.
988 bool findMacroSpelling(SourceLocation &loc, StringRef name);
989
990 /// Calls \c Lexer::getLocForEndOfToken()
991 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
992
993 /// Calls \c Lexer::findNextToken() to find the next token, and if the
994 /// locations of both ends of the token can be resolved it return that
995 /// range; Otherwise it returns an invalid SourceRange.
997 SourceLocation Loc, bool IncludeMacros, bool IncludeComments,
998 std::optional<tok::TokenKind> ExpectedToken = std::nullopt);
999
1000 /// Retrieve the module loader associated with the preprocessor.
1002
1003 /// Invent a new identifier for parameters of abbreviated templates.
1006 unsigned Index);
1007
1009
1010 // Emit all deferred diagnostics.
1011 void emitDeferredDiags();
1012
1013 /// This is called before the very first declaration in the translation unit
1014 /// is parsed. Note that the ASTContext may have already injected some
1015 /// declarations.
1017 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1018 /// translation unit when EOF is reached and all but the top-level scope is
1019 /// popped.
1022
1023 /// Determines the active Scope associated with the given declaration
1024 /// context.
1025 ///
1026 /// This routine maps a declaration context to the active Scope object that
1027 /// represents that declaration context in the parser. It is typically used
1028 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1029 /// declarations) that injects a name for name-lookup purposes and, therefore,
1030 /// must update the Scope.
1031 ///
1032 /// \returns The scope corresponding to the given declaraion context, or NULL
1033 /// if no such scope is open.
1035
1036 void PushFunctionScope();
1037 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1039
1040 /// This is used to inform Sema what the current TemplateParameterDepth
1041 /// is during Parsing. Currently it is used to pass on the depth
1042 /// when parsing generic lambda 'auto' parameters.
1043 void RecordParsingTemplateParameterDepth(unsigned Depth);
1044
1045 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1047 unsigned OpenMPCaptureLevel = 0);
1048
1049 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1050 /// time after they've been popped.
1052 Sema *Self;
1053
1054 public:
1055 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1057 };
1058
1060 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1061
1062 /// Pop a function (or block or lambda or captured region) scope from the
1063 /// stack.
1064 ///
1065 /// \param WP The warning policy to use for CFG-based warnings, or null if
1066 /// such warnings should not be produced.
1067 /// \param D The declaration corresponding to this function scope, if
1068 /// producing CFG-based warnings.
1069 /// \param BlockType The type of the block expression, if D is a BlockDecl.
1072 const Decl *D = nullptr,
1073 QualType BlockType = QualType());
1074
1076
1081
1082 void PushCompoundScope(bool IsStmtExpr);
1083 void PopCompoundScope();
1084
1085 /// Determine whether any errors occurred within this function/method/
1086 /// block.
1088
1089 /// Retrieve the current block, if any.
1091
1092 /// Get the innermost lambda or block enclosing the current location, if any.
1093 /// This looks through intervening non-lambda, non-block scopes such as local
1094 /// functions.
1096
1097 /// Retrieve the current lambda scope info, if any.
1098 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1099 /// lambda scope info ignoring all inner capturing scopes that are not
1100 /// lambda scopes.
1102 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1103
1104 /// Retrieve the current generic lambda info, if any.
1106
1107 /// Retrieve the current captured region, if any.
1109
1110 void ActOnComment(SourceRange Comment);
1111
1112 /// Retrieve the parser's current scope.
1113 ///
1114 /// This routine must only be used when it is certain that semantic analysis
1115 /// and the parser are in precisely the same context, which is not the case
1116 /// when, e.g., we are performing any kind of template instantiation.
1117 /// Therefore, the only safe places to use this scope are in the parser
1118 /// itself and in routines directly invoked from the parser and *never* from
1119 /// template substitution or instantiation.
1120 Scope *getCurScope() const { return CurScope; }
1121
1123
1127
1128 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1129 const FunctionDecl *FD = nullptr);
1131 const PartialDiagnostic &PD,
1132 const FunctionDecl *FD = nullptr) {
1133 return targetDiag(Loc, PD.getDiagID(), FD) << PD;
1134 }
1135
1136 /// Check if the type is allowed to be used for the current target.
1138 ValueDecl *D = nullptr);
1139
1140 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1141 /// cast. If there is already an implicit cast, merge into the existing one.
1142 /// If isLvalue, the result of the cast is an lvalue.
1145 const CXXCastPath *BasePath = nullptr,
1147
1148 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1149 /// to the conversion from scalar type ScalarTy to the Boolean type.
1151
1152 /// If \p AllowLambda is true, treat lambda as function.
1153 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1154
1155 /// Returns a pointer to the innermost enclosing function, or nullptr if the
1156 /// current context is not inside a function. If \p AllowLambda is true,
1157 /// this can return the call operator of an enclosing lambda, otherwise
1158 /// lambdas are skipped when looking for an enclosing function.
1159 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1160
1161 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1162 /// the method decl for the method being parsed. If we're currently
1163 /// in a 'block', this returns the containing context.
1165
1166 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1167 /// or C function we're in, otherwise return null. If we're currently
1168 /// in a 'block', this returns the containing context.
1170
1171 /// Warn if we're implicitly casting from a _Nullable pointer type to a
1172 /// _Nonnull one.
1174 SourceLocation Loc);
1175
1176 /// Warn when implicitly casting 0 to nullptr.
1177 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1178
1179 /// Warn when implicitly changing function effects.
1181 SourceLocation Loc);
1182
1183 /// makeUnavailableInSystemHeader - There is an error in the current
1184 /// context. If we're still in a system header, and we can plausibly
1185 /// make the relevant declaration unavailable instead of erroring, do
1186 /// so and return true.
1188 UnavailableAttr::ImplicitReason reason);
1189
1190 /// Retrieve a suitable printing policy for diagnostics.
1194
1195 /// Retrieve a suitable printing policy for diagnostics.
1197 const Preprocessor &PP);
1198
1199 /// Scope actions.
1201
1202 /// Determine whether \param D is function like (function or function
1203 /// template) for parsing.
1205
1206 /// The maximum alignment, same as in llvm::Value. We duplicate them here
1207 /// because that allows us not to duplicate the constants in clang code,
1208 /// which we must to since we can't directly use the llvm constants.
1209 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1210 ///
1211 /// This is the greatest alignment value supported by load, store, and alloca
1212 /// instructions, and global values.
1213 static const unsigned MaxAlignmentExponent = 32;
1214 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1215
1216 /// Flag indicating whether or not to collect detailed statistics.
1218
1219 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1220
1221 /// Stack containing information about each of the nested
1222 /// function, block, and method scopes that are currently active.
1224
1225 /// The index of the first FunctionScope that corresponds to the current
1226 /// context.
1228
1229 /// Track the number of currently active capturing scopes.
1231
1232 llvm::BumpPtrAllocator BumpAlloc;
1233
1234 /// The kind of translation unit we are processing.
1235 ///
1236 /// When we're processing a complete translation unit, Sema will perform
1237 /// end-of-translation-unit semantic tasks (such as creating
1238 /// initializers for tentative definitions in C) once parsing has
1239 /// completed. Modules and precompiled headers perform different kinds of
1240 /// checks.
1242
1243 /// Translation Unit Scope - useful to Objective-C actions that need
1244 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1245 /// For example, user-defined classes, built-in "id" type, etc.
1247
1249 return CurScope->incrementMSManglingNumber();
1250 }
1251
1252 /// Try to recover by turning the given expression into a
1253 /// call. Returns true if recovery was attempted or an error was
1254 /// emitted; this may also leave the ExprResult invalid.
1256 bool ForceComplain = false,
1257 bool (*IsPlausibleResult)(QualType) = nullptr);
1258
1259 /// Figure out if an expression could be turned into a call.
1260 ///
1261 /// Use this when trying to recover from an error where the programmer may
1262 /// have written just the name of a function instead of actually calling it.
1263 ///
1264 /// \param E - The expression to examine.
1265 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1266 /// with no arguments, this parameter is set to the type returned by such a
1267 /// call; otherwise, it is set to an empty QualType.
1268 /// \param OverloadSet - If the expression is an overloaded function
1269 /// name, this parameter is populated with the decls of the various
1270 /// overloads.
1271 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1272 UnresolvedSetImpl &NonTemplateOverloads);
1273
1277
1280
1288
1289 /// A RAII object to enter scope of a compound statement.
1291 public:
1292 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1293 S.ActOnStartOfCompoundStmt(IsStmtExpr);
1294 }
1295
1296 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1297
1298 private:
1299 Sema &S;
1300 };
1301
1302 /// An RAII helper that pops function a function scope on exit.
1308 if (Active)
1309 S.PopFunctionScopeInfo();
1310 }
1311 void disable() { Active = false; }
1312 };
1313
1315 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1316 }
1317
1318 /// Worker object for performing CFG-based warnings.
1321
1322 /// Callback to the parser to parse templated functions when needed.
1323 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1326
1328 LateTemplateParser = LTP;
1329 OpaqueParser = P;
1330 }
1331
1332 /// Callback to the parser to parse a type expressed as a string.
1333 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1335
1336 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1337 /// This is used as part of a hack to omit that class from ADL results.
1339
1340 /// Is the last error level diagnostic immediate. This is used to determined
1341 /// whether the next info diagnostic should be immediate.
1343
1344 class DelayedDiagnostics;
1345
1347 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1349 };
1352
1353 /// A class which encapsulates the logic for delaying diagnostics
1354 /// during parsing and other processing.
1356 /// The current pool of diagnostics into which delayed
1357 /// diagnostics should go.
1358 sema::DelayedDiagnosticPool *CurPool = nullptr;
1359
1360 public:
1362
1363 /// Adds a delayed diagnostic.
1364 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1365
1366 /// Determines whether diagnostics should be delayed.
1367 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1368
1369 /// Returns the current delayed-diagnostics pool.
1370 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1371
1372 /// Enter a new scope. Access and deprecation diagnostics will be
1373 /// collected in this pool.
1376 state.SavedPool = CurPool;
1377 CurPool = &pool;
1378 return state;
1379 }
1380
1381 /// Leave a delayed-diagnostic state that was previously pushed.
1382 /// Do not emit any of the diagnostics. This is performed as part
1383 /// of the bookkeeping of popping a pool "properly".
1385 CurPool = state.SavedPool;
1386 }
1387
1388 /// Enter a new scope where access and deprecation diagnostics are
1389 /// not delayed.
1392 state.SavedPool = CurPool;
1393 CurPool = nullptr;
1394 return state;
1395 }
1396
1397 /// Undo a previous pushUndelayed().
1399 assert(CurPool == nullptr);
1400 CurPool = state.SavedPool;
1401 }
1403
1407
1408 /// Diagnostics that are emitted only if we discover that the given function
1409 /// must be codegen'ed. Because handling these correctly adds overhead to
1410 /// compilation, this is currently only enabled for CUDA compilations.
1411 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1412
1413 /// CurContext - This is the current declaration context of parsing.
1415
1417 assert(AMDGPUPtr);
1418 return *AMDGPUPtr;
1419 }
1420
1422 assert(ARMPtr);
1423 return *ARMPtr;
1424 }
1425
1427 assert(AVRPtr);
1428 return *AVRPtr;
1429 }
1430
1432 assert(BPFPtr);
1433 return *BPFPtr;
1434 }
1435
1437 assert(CodeCompletionPtr);
1438 return *CodeCompletionPtr;
1439 }
1440
1442 assert(CUDAPtr);
1443 return *CUDAPtr;
1444 }
1445
1447 assert(DirectXPtr);
1448 return *DirectXPtr;
1449 }
1450
1452 assert(HLSLPtr);
1453 return *HLSLPtr;
1454 }
1455
1457 assert(HexagonPtr);
1458 return *HexagonPtr;
1459 }
1460
1462 assert(LoongArchPtr);
1463 return *LoongArchPtr;
1464 }
1465
1467 assert(M68kPtr);
1468 return *M68kPtr;
1469 }
1470
1472 assert(MIPSPtr);
1473 return *MIPSPtr;
1474 }
1475
1477 assert(MSP430Ptr);
1478 return *MSP430Ptr;
1479 }
1480
1482 assert(NVPTXPtr);
1483 return *NVPTXPtr;
1484 }
1485
1487 assert(ObjCPtr);
1488 return *ObjCPtr;
1489 }
1490
1492 assert(OpenACCPtr);
1493 return *OpenACCPtr;
1494 }
1495
1497 assert(OpenCLPtr);
1498 return *OpenCLPtr;
1499 }
1500
1502 assert(OpenMPPtr && "SemaOpenMP is dead");
1503 return *OpenMPPtr;
1504 }
1505
1507 assert(PPCPtr);
1508 return *PPCPtr;
1509 }
1510
1512 assert(PseudoObjectPtr);
1513 return *PseudoObjectPtr;
1514 }
1515
1517 assert(RISCVPtr);
1518 return *RISCVPtr;
1519 }
1520
1522 assert(SPIRVPtr);
1523 return *SPIRVPtr;
1524 }
1525
1527 assert(SYCLPtr);
1528 return *SYCLPtr;
1529 }
1530
1532 assert(SwiftPtr);
1533 return *SwiftPtr;
1534 }
1535
1537 assert(SystemZPtr);
1538 return *SystemZPtr;
1539 }
1540
1542 assert(WasmPtr);
1543 return *WasmPtr;
1544 }
1545
1547 assert(X86Ptr);
1548 return *X86Ptr;
1549 }
1550
1551 /// Source of additional semantic information.
1553
1554protected:
1555 friend class Parser;
1557 friend class ASTReader;
1558 friend class ASTDeclReader;
1559 friend class ASTWriter;
1560
1561private:
1562 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1563 bool WarnedDarwinSDKInfoMissing = false;
1564
1565 StackExhaustionHandler StackHandler;
1566
1567 Sema(const Sema &) = delete;
1568 void operator=(const Sema &) = delete;
1569
1570 /// The handler for the FileChanged preprocessor events.
1571 ///
1572 /// Used for diagnostics that implement custom semantic analysis for #include
1573 /// directives, like -Wpragma-pack.
1574 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1575
1576 /// The parser's current scope.
1577 ///
1578 /// The parser maintains this state here.
1579 Scope *CurScope;
1580
1581 mutable IdentifierInfo *Ident_super;
1582
1583 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1584 std::unique_ptr<SemaARM> ARMPtr;
1585 std::unique_ptr<SemaAVR> AVRPtr;
1586 std::unique_ptr<SemaBPF> BPFPtr;
1587 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1588 std::unique_ptr<SemaCUDA> CUDAPtr;
1589 std::unique_ptr<SemaDirectX> DirectXPtr;
1590 std::unique_ptr<SemaHLSL> HLSLPtr;
1591 std::unique_ptr<SemaHexagon> HexagonPtr;
1592 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1593 std::unique_ptr<SemaM68k> M68kPtr;
1594 std::unique_ptr<SemaMIPS> MIPSPtr;
1595 std::unique_ptr<SemaMSP430> MSP430Ptr;
1596 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1597 std::unique_ptr<SemaObjC> ObjCPtr;
1598 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1599 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1600 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1601 std::unique_ptr<SemaPPC> PPCPtr;
1602 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1603 std::unique_ptr<SemaRISCV> RISCVPtr;
1604 std::unique_ptr<SemaSPIRV> SPIRVPtr;
1605 std::unique_ptr<SemaSYCL> SYCLPtr;
1606 std::unique_ptr<SemaSwift> SwiftPtr;
1607 std::unique_ptr<SemaSystemZ> SystemZPtr;
1608 std::unique_ptr<SemaWasm> WasmPtr;
1609 std::unique_ptr<SemaX86> X86Ptr;
1610
1611 ///@}
1612
1613 //
1614 //
1615 // -------------------------------------------------------------------------
1616 //
1617 //
1618
1619 /// \name API Notes
1620 /// Implementations are in SemaAPINotes.cpp
1621 ///@{
1622
1623public:
1624 /// Map any API notes provided for this declaration to attributes on the
1625 /// declaration.
1626 ///
1627 /// Triggered by declaration-attribute processing.
1628 void ProcessAPINotes(Decl *D);
1629 /// Apply the 'Nullability:' annotation to the specified declaration
1630 void ApplyNullability(Decl *D, NullabilityKind Nullability);
1631 /// Apply the 'Type:' annotation to the specified declaration
1632 void ApplyAPINotesType(Decl *D, StringRef TypeString);
1633
1634 /// Whether APINotes should be gathered for all applicable Swift language
1635 /// versions, without being applied. Leaving clients of the current module
1636 /// to select and apply the correct version.
1638 return APINotes.captureVersionIndependentSwift();
1639 }
1640 ///@}
1641
1642 //
1643 //
1644 // -------------------------------------------------------------------------
1645 //
1646 //
1647
1648 /// \name C++ Access Control
1649 /// Implementations are in SemaAccess.cpp
1650 ///@{
1651
1652public:
1659
1660 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1661 /// Returns true on error (when the previous member decl access specifier
1662 /// is different from the new member decl access specifier).
1663 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1664 NamedDecl *PrevMemberDecl,
1665 AccessSpecifier LexicalAS);
1666
1667 /// Perform access-control checking on a previously-unresolved member
1668 /// access which has now been resolved to a member.
1670 DeclAccessPair FoundDecl);
1672 DeclAccessPair FoundDecl);
1673
1674 /// Checks access to an overloaded operator new or delete.
1676 SourceRange PlacementRange,
1677 CXXRecordDecl *NamingClass,
1678 DeclAccessPair FoundDecl,
1679 bool Diagnose = true);
1680
1681 /// Checks access to a constructor.
1683 DeclAccessPair FoundDecl,
1684 const InitializedEntity &Entity,
1685 bool IsCopyBindingRefToTemp = false);
1686
1687 /// Checks access to a constructor.
1689 DeclAccessPair FoundDecl,
1690 const InitializedEntity &Entity,
1691 const PartialDiagnostic &PDiag);
1693 CXXDestructorDecl *Dtor,
1694 const PartialDiagnostic &PDiag,
1695 QualType objectType = QualType());
1696
1697 /// Checks access to the target of a friend declaration.
1699
1700 /// Checks access to a member.
1702 CXXRecordDecl *NamingClass,
1704
1705 /// Checks implicit access to a member in a structured binding.
1708 CXXRecordDecl *DecomposedClass,
1709 DeclAccessPair Field);
1711 const SourceRange &,
1712 DeclAccessPair FoundDecl);
1713
1714 /// Checks access to an overloaded member operator, including
1715 /// conversion operators.
1717 Expr *ArgExpr,
1718 DeclAccessPair FoundDecl);
1720 ArrayRef<Expr *> ArgExprs,
1721 DeclAccessPair FoundDecl);
1723 DeclAccessPair FoundDecl);
1724
1725 /// Checks access for a hierarchy conversion.
1726 ///
1727 /// \param ForceCheck true if this check should be performed even if access
1728 /// control is disabled; some things rely on this for semantics
1729 /// \param ForceUnprivileged true if this check should proceed as if the
1730 /// context had no special privileges
1732 QualType Derived, const CXXBasePath &Path,
1733 unsigned DiagID, bool ForceCheck = false,
1734 bool ForceUnprivileged = false);
1735
1737 SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1738 const CXXBasePath &Path, unsigned DiagID,
1739 llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1740 bool ForceCheck = false, bool ForceUnprivileged = false);
1741
1742 /// Checks access to all the declarations in the given result set.
1743 void CheckLookupAccess(const LookupResult &R);
1744
1745 /// Checks access to Target from the given class. The check will take access
1746 /// specifiers into account, but no member access expressions and such.
1747 ///
1748 /// \param Target the declaration to check if it can be accessed
1749 /// \param NamingClass the class in which the lookup was started.
1750 /// \param BaseType type of the left side of member access expression.
1751 /// \p BaseType and \p NamingClass are used for C++ access control.
1752 /// Depending on the lookup case, they should be set to the following:
1753 /// - lhs.target (member access without a qualifier):
1754 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1755 /// - lhs.X::target (member access with a qualifier):
1756 /// BaseType is the type of 'lhs', NamingClass is 'X'
1757 /// - X::target (qualified lookup without member access):
1758 /// BaseType is null, NamingClass is 'X'.
1759 /// - target (unqualified lookup).
1760 /// BaseType is null, NamingClass is the parent class of 'target'.
1761 /// \return true if the Target is accessible from the Class, false otherwise.
1762 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1763 QualType BaseType);
1764
1765 /// Is the given member accessible for the purposes of deciding whether to
1766 /// define a special member function as deleted?
1768 DeclAccessPair Found, QualType ObjectType,
1769 SourceLocation Loc,
1770 const PartialDiagnostic &Diag);
1773 QualType ObjectType) {
1774 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1775 SourceLocation(), PDiag());
1776 }
1777
1779 const DependentDiagnostic &DD,
1780 const MultiLevelTemplateArgumentList &TemplateArgs);
1782
1783 ///@}
1784
1785 //
1786 //
1787 // -------------------------------------------------------------------------
1788 //
1789 //
1790
1791 /// \name Attributes
1792 /// Implementations are in SemaAttr.cpp
1793 ///@{
1794
1795public:
1796 /// Controls member pointer representation format under the MS ABI.
1799
1800 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1801
1802 /// Source location for newly created implicit MSInheritanceAttrs
1804
1810
1816
1818 PSK_Reset = 0x0, // #pragma ()
1819 PSK_Set = 0x1, // #pragma (value)
1820 PSK_Push = 0x2, // #pragma (push[, id])
1821 PSK_Pop = 0x4, // #pragma (pop[, id])
1822 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1823 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1824 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1825 };
1826
1832
1833 // #pragma pack and align.
1835 public:
1836 // `Native` represents default align mode, which may vary based on the
1837 // platform.
1838 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1839
1840 // #pragma pack info constructor
1841 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1842 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1843 assert(Num == PackNumber && "The pack number has been truncated.");
1844 }
1845
1846 // #pragma align info constructor
1848 : PackAttr(false), AlignMode(M),
1849 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1850
1851 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1852
1854
1855 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1856 // integer encoding for it. This should only be passed to
1857 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1858 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
1859 std::uint32_t Encoding{};
1860 if (Info.IsXLStack())
1861 Encoding |= IsXLMask;
1862
1863 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1864
1865 if (Info.IsPackAttr())
1866 Encoding |= PackAttrMask;
1867
1868 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1869
1870 return Encoding;
1871 }
1872
1873 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1874 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1876 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1877 int PackNumber = (Encoding & PackNumMask) >> 4;
1878
1879 if (Encoding & PackAttrMask)
1880 return AlignPackInfo(M, PackNumber, IsXL);
1881
1882 return AlignPackInfo(M, IsXL);
1883 }
1884
1885 bool IsPackAttr() const { return PackAttr; }
1886
1887 bool IsAlignAttr() const { return !PackAttr; }
1888
1889 Mode getAlignMode() const { return AlignMode; }
1890
1891 unsigned getPackNumber() const { return PackNumber; }
1892
1893 bool IsPackSet() const {
1894 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1895 // attriute on a decl.
1896 return PackNumber != UninitPackVal && PackNumber != 0;
1897 }
1898
1899 bool IsXLStack() const { return XLStack; }
1900
1901 bool operator==(const AlignPackInfo &Info) const {
1902 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
1903 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
1904 Info.XLStack);
1905 }
1906
1907 bool operator!=(const AlignPackInfo &Info) const {
1908 return !(*this == Info);
1909 }
1910
1911 private:
1912 /// \brief True if this is a pragma pack attribute,
1913 /// not a pragma align attribute.
1914 bool PackAttr;
1915
1916 /// \brief The alignment mode that is in effect.
1917 Mode AlignMode;
1918
1919 /// \brief The pack number of the stack.
1920 unsigned char PackNumber;
1921
1922 /// \brief True if it is a XL #pragma align/pack stack.
1923 bool XLStack;
1924
1925 /// \brief Uninitialized pack value.
1926 static constexpr unsigned char UninitPackVal = -1;
1927
1928 // Masks to encode and decode an AlignPackInfo.
1929 static constexpr uint32_t IsXLMask{0x0000'0001};
1930 static constexpr uint32_t AlignModeMask{0x0000'0006};
1931 static constexpr uint32_t PackAttrMask{0x00000'0008};
1932 static constexpr uint32_t PackNumMask{0x0000'01F0};
1933 };
1934
1935 template <typename ValueType> struct PragmaStack {
1947
1948 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
1949 llvm::StringRef StackSlotLabel, ValueType Value) {
1950 if (Action == PSK_Reset) {
1952 CurrentPragmaLocation = PragmaLocation;
1953 return;
1954 }
1955 if (Action & PSK_Push)
1956 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
1957 PragmaLocation);
1958 else if (Action & PSK_Pop) {
1959 if (!StackSlotLabel.empty()) {
1960 // If we've got a label, try to find it and jump there.
1961 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
1962 return x.StackSlotLabel == StackSlotLabel;
1963 });
1964 // If we found the label so pop from there.
1965 if (I != Stack.rend()) {
1966 CurrentValue = I->Value;
1967 CurrentPragmaLocation = I->PragmaLocation;
1968 Stack.erase(std::prev(I.base()), Stack.end());
1969 }
1970 } else if (!Stack.empty()) {
1971 // We do not have a label, just pop the last entry.
1972 CurrentValue = Stack.back().Value;
1973 CurrentPragmaLocation = Stack.back().PragmaLocation;
1974 Stack.pop_back();
1975 }
1976 }
1977 if (Action & PSK_Set) {
1979 CurrentPragmaLocation = PragmaLocation;
1980 }
1981 }
1982
1983 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
1984 // method body to restore the stacks on exit, so it works like this:
1985 //
1986 // struct S {
1987 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
1988 // void Method {}
1989 // #pragma <name>(pop, InternalPragmaSlot)
1990 // };
1991 //
1992 // It works even with #pragma vtordisp, although MSVC doesn't support
1993 // #pragma vtordisp(push [, id], n)
1994 // syntax.
1995 //
1996 // Push / pop a named sentinel slot.
1997 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
1998 assert((Action == PSK_Push || Action == PSK_Pop) &&
1999 "Can only push / pop #pragma stack sentinels!");
2000 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
2001 }
2002
2003 // Constructors.
2004 explicit PragmaStack(const ValueType &Default)
2006
2007 bool hasValue() const { return CurrentValue != DefaultValue; }
2008
2010 ValueType DefaultValue; // Value used for PSK_Reset action.
2011 ValueType CurrentValue;
2013 };
2014 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2015 // we shouldn't do so if they're in a module).
2016
2017 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2018 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
2019 ///
2020 /// 0: Suppress all vtordisps
2021 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2022 /// structors
2023 /// 2: Always insert vtordisps to support RTTI on partially constructed
2024 /// objects
2027 // The current #pragma align/pack values and locations at each #include.
2034 // Segment #pragmas.
2039
2040 // #pragma strict_gs_check.
2042
2043 // This stack tracks the current state of Sema.CurFPFeatures.
2046 FPOptionsOverride result;
2047 if (!FpPragmaStack.hasValue()) {
2048 result = FPOptionsOverride();
2049 } else {
2050 result = FpPragmaStack.CurrentValue;
2051 }
2052 return result;
2053 }
2054
2061
2062 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2063 // Actions should be performed only if we enter / exit a C++ method body.
2065 public:
2066 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2068
2069 private:
2070 Sema &S;
2071 StringRef SlotLabel;
2072 bool ShouldAct;
2073 };
2074
2075 /// Last section used with #pragma init_seg.
2078
2079 /// Sections used with #pragma alloc_text.
2080 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2081
2082 /// VisContext - Manages the stack for \#pragma GCC visibility.
2083 void *VisContext; // Really a "PragmaVisStack*"
2084
2085 /// This an attribute introduced by \#pragma clang attribute.
2092
2093 /// A push'd group of PragmaAttributeEntries.
2095 /// The location of the push attribute.
2097 /// The namespace of this push group.
2100 };
2101
2103
2104 /// The declaration that is currently receiving an attribute from the
2105 /// #pragma attribute stack.
2107
2108 /// This represents the last location of a "#pragma clang optimize off"
2109 /// directive if such a directive has not been closed by an "on" yet. If
2110 /// optimizations are currently "on", this is set to an invalid location.
2112
2113 /// Get the location for the currently active "\#pragma clang optimize
2114 /// off". If this location is invalid, then the state of the pragma is "on".
2118
2119 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2120 /// whether the optimizations in the list passed to the pragma should be
2121 /// turned off or on. This boolean is true by default because command line
2122 /// options are honored when `#pragma optimize("", on)`.
2123 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2125
2126 /// Set of no-builtin functions listed by \#pragma function.
2128
2129 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2130 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2132
2133 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2135
2136 /// Add gsl::Pointer attribute to std::container::iterator
2137 /// \param ND The declaration that introduces the name
2138 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2139 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2140
2141 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2143
2144 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2146
2147 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2149
2150 /// Add [[gsl::Pointer]] attributes for std:: types.
2152
2153 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2154 StringRef ParamName);
2155 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2156 // can be the name of a function parameter, we need to parse the function
2157 // declaration and rest of the parameters before processesing 'X'. Therefore
2158 // do this lazily instead of processing while parsing the annotation itself.
2160
2161 /// Add _Nullable attributes for std:: types.
2163
2164 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2167 PragmaClangSectionKind SecKind,
2168 StringRef SecName);
2169
2170 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2172 SourceLocation PragmaLoc);
2173
2174 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2175 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2176 StringRef SlotLabel, Expr *Alignment);
2177
2178 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2179 /// (unless they are value dependent or type dependent). Returns false
2180 /// and emits a diagnostic if one or more of the arguments could not be
2181 /// folded into a constant.
2184
2189
2191 SourceLocation IncludeLoc);
2193
2194 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2196
2197 /// ActOnPragmaMSComment - Called on well formed
2198 /// \#pragma comment(kind, "arg").
2200 StringRef Arg);
2201
2202 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2203 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2204 StringRef Value);
2205
2206 /// Are precise floating point semantics currently enabled?
2208 return !CurFPFeatures.getAllowFPReassociate() &&
2209 !CurFPFeatures.getNoSignedZero() &&
2210 !CurFPFeatures.getAllowReciprocal() &&
2211 !CurFPFeatures.getAllowApproxFunc();
2212 }
2213
2216
2217 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2218 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2220
2221 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2222 /// pointers_to_members(representation method[, general purpose
2223 /// representation]).
2226 SourceLocation PragmaLoc);
2227
2228 /// Called on well formed \#pragma vtordisp().
2229 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2231
2232 bool UnifySection(StringRef SectionName, int SectionFlags,
2233 NamedDecl *TheDecl);
2234 bool UnifySection(StringRef SectionName, int SectionFlags,
2235 SourceLocation PragmaSectionLocation);
2236
2237 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2238 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2239 PragmaMsStackAction Action,
2240 llvm::StringRef StackSlotLabel,
2241 StringLiteral *SegmentName, llvm::StringRef PragmaName);
2242
2243 /// Called on well formed \#pragma section().
2244 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2245 StringLiteral *SegmentName);
2246
2247 /// Called on well-formed \#pragma init_seg().
2248 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2249 StringLiteral *SegmentName);
2250
2251 /// Called on well-formed \#pragma alloc_text().
2253 SourceLocation PragmaLocation, StringRef Section,
2254 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2255 &Functions);
2256
2257 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2258 /// strict_gs_check.
2260 PragmaMsStackAction Action,
2261 bool Value);
2262
2263 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2264 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2265 SourceLocation PragmaLoc);
2266
2268 SourceLocation PragmaLoc,
2271 const IdentifierInfo *Namespace);
2272
2273 /// Called on well-formed '\#pragma clang attribute pop'.
2275 const IdentifierInfo *Namespace);
2276
2277 /// Adds the attributes that have been specified using the
2278 /// '\#pragma clang attribute push' directives to the given declaration.
2279 void AddPragmaAttributes(Scope *S, Decl *D);
2280
2282 llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
2284 return [this](SourceLocation Loc, PartialDiagnostic PD) {
2285 // This bypasses a lot of the filters in the diag engine, as it's
2286 // to be used to attach notes to diagnostics which have already
2287 // been filtered through.
2288 DiagnosticBuilder Builder(Diags.Report(Loc, PD.getDiagID()));
2289 PD.Emit(Builder);
2290 };
2291 }
2292
2298
2300
2301 /// Called on well formed \#pragma clang optimize.
2302 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2303
2304 /// #pragma optimize("[optimization-list]", on | off).
2305 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2306
2307 /// Call on well formed \#pragma function.
2308 void
2310 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2311
2312 /// Only called on function definitions; if there is a pragma in scope
2313 /// with the effect of a range-based optnone, consider marking the function
2314 /// with attribute optnone.
2316
2317 /// Only called on function definitions; if there is a `#pragma alloc_text`
2318 /// that decides which code section the function should be in, add
2319 /// attribute section to the function.
2321
2322 /// Adds the 'optnone' attribute to the function declaration if there
2323 /// are no conflicts; Loc represents the location causing the 'optnone'
2324 /// attribute to be added (usually because of a pragma).
2326
2327 /// Only called on function definitions; if there is a MSVC #pragma optimize
2328 /// in scope, consider changing the function's attributes based on the
2329 /// optimization list passed to the pragma.
2331
2332 /// Only called on function definitions; if there is a pragma in scope
2333 /// with the effect of a range-based no_builtin, consider marking the function
2334 /// with attribute no_builtin.
2336
2337 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2338 /// add an appropriate visibility attribute.
2340
2341 /// FreeVisContext - Deallocate and null out VisContext.
2342 void FreeVisContext();
2343
2344 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2345 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2346 SourceLocation PragmaLoc);
2347
2348 /// ActOnPragmaFPContract - Called on well formed
2349 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2350 /// \#pragma clang fp contract
2352
2353 /// Called on well formed
2354 /// \#pragma clang fp reassociate
2355 /// or
2356 /// \#pragma clang fp reciprocal
2358 bool IsEnabled);
2359
2360 /// ActOnPragmaFenvAccess - Called on well formed
2361 /// \#pragma STDC FENV_ACCESS
2362 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2363
2364 /// ActOnPragmaCXLimitedRange - Called on well formed
2365 /// \#pragma STDC CX_LIMITED_RANGE
2368
2369 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2372
2373 /// Called to set constant rounding mode for floating point operations.
2374 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2375
2376 /// Called to set exception behavior for floating point operations.
2378
2379 /// PushNamespaceVisibilityAttr - Note that we've entered a
2380 /// namespace with a visibility attribute.
2381 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2382 SourceLocation Loc);
2383
2384 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2385 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2386 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2387
2388 /// Handles semantic checking for features that are common to all attributes,
2389 /// such as checking whether a parameter was properly specified, or the
2390 /// correct number of arguments were passed, etc. Returns true if the
2391 /// attribute has been diagnosed.
2392 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2393 bool SkipArgCountCheck = false);
2394 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2395 bool SkipArgCountCheck = false);
2396
2397 ///@}
2398
2399 //
2400 //
2401 // -------------------------------------------------------------------------
2402 //
2403 //
2404
2405 /// \name Availability Attribute Handling
2406 /// Implementations are in SemaAvailability.cpp
2407 ///@{
2408
2409public:
2410 /// Issue any -Wunguarded-availability warnings in \c FD
2412
2414
2415 /// Retrieve the current function, if any, that should be analyzed for
2416 /// potential availability violations.
2418
2420 const ObjCInterfaceDecl *UnknownObjCClass,
2421 bool ObjCPropertyAccess,
2422 bool AvoidPartialAvailabilityChecks,
2423 ObjCInterfaceDecl *ClassReceiver);
2424
2426
2427 std::pair<AvailabilityResult, const NamedDecl *>
2428 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2429 ObjCInterfaceDecl *ClassReceiver);
2430 ///@}
2431
2432 //
2433 //
2434 // -------------------------------------------------------------------------
2435 //
2436 //
2437
2438 /// \name Bounds Safety
2439 /// Implementations are in SemaBoundsSafety.cpp
2440 ///@{
2441public:
2442 /// Check if applying the specified attribute variant from the "counted by"
2443 /// family of attributes to FieldDecl \p FD is semantically valid. If
2444 /// semantically invalid diagnostics will be emitted explaining the problems.
2445 ///
2446 /// \param FD The FieldDecl to apply the attribute to
2447 /// \param E The count expression on the attribute
2448 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2449 /// attributes. If the false the attribute is from
2450 /// "counted_by" family of attributes.
2451 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2452 /// of attributes. If false the attribute does not have the
2453 /// suffix.
2454 ///
2455 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2456 /// \p CountInBytes and \p OrNull both being true indicates the
2457 /// `counted_by_or_null` attribute.
2458 ///
2459 /// \returns false iff semantically valid.
2460 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2461 bool OrNull);
2462
2463 /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2464 /// `__counted_by_or_null` pointer type \param LHSTy.
2465 ///
2466 /// \param LHSTy The type being assigned to. Checks will only be performed if
2467 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2468 /// \param RHSExpr The expression being assigned from.
2469 /// \param Action The type assignment being performed
2470 /// \param Loc The SourceLocation to use for error diagnostics
2471 /// \param Assignee The ValueDecl being assigned. This is used to compute
2472 /// the name of the assignee. If the assignee isn't known this can
2473 /// be set to nullptr.
2474 /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2475 /// Assignee to compute the name of the assignee use the fully
2476 /// qualified name, otherwise use the unqualified name.
2477 ///
2478 /// \returns True iff no diagnostic where emitted, false otherwise.
2480 QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2481 SourceLocation Loc, const ValueDecl *Assignee,
2482 bool ShowFullyQualifiedAssigneeName);
2483
2484 /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2485 /// pointer.
2486 ///
2487 /// \param Entity The entity being initialized
2488 /// \param Kind The kind of initialization being performed
2489 /// \param Action The type assignment being performed
2490 /// \param LHSTy The type being assigned to. Checks will only be performed if
2491 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2492 /// \param RHSExpr The expression being used for initialization.
2493 ///
2494 /// \returns True iff no diagnostic where emitted, false otherwise.
2496 const InitializationKind &Kind,
2497 AssignmentAction Action,
2498 QualType LHSType, Expr *RHSExpr);
2499
2500 /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2501 /// or counted_by_or_null pointers in \param E.
2502 ///
2503 /// \param E the expression to check
2504 ///
2505 /// \returns True iff no diagnostic where emitted, false otherwise.
2507 ///@}
2508
2509 //
2510 //
2511 // -------------------------------------------------------------------------
2512 //
2513 //
2514
2515 /// \name Casts
2516 /// Implementations are in SemaCast.cpp
2517 ///@{
2518
2519public:
2525
2526 /// ActOnCXXNamedCast - Parse
2527 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2529 SourceLocation LAngleBracketLoc, Declarator &D,
2530 SourceLocation RAngleBracketLoc,
2531 SourceLocation LParenLoc, Expr *E,
2532 SourceLocation RParenLoc);
2533
2535 TypeSourceInfo *Ty, Expr *E,
2536 SourceRange AngleBrackets, SourceRange Parens);
2537
2539 ExprResult Operand,
2540 SourceLocation RParenLoc);
2541
2543 Expr *Operand, SourceLocation RParenLoc);
2544
2545 // Checks that reinterpret casts don't have undefined behavior.
2546 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2547 bool IsDereference, SourceRange Range);
2548
2549 // Checks that the vector type should be initialized from a scalar
2550 // by splatting the value rather than populating a single element.
2551 // This is the case for AltiVecVector types as well as with
2552 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2553 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2554
2555 // Checks if the -faltivec-src-compat=gcc option is specified.
2556 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2557 // treated the same way as they are when trying to initialize
2558 // these vectors on gcc (an error is emitted).
2560 QualType SrcTy);
2561
2563 SourceLocation RParenLoc, Expr *Op);
2564
2566 SourceLocation LParenLoc,
2567 Expr *CastExpr,
2568 SourceLocation RParenLoc);
2569
2570 ///@}
2571
2572 //
2573 //
2574 // -------------------------------------------------------------------------
2575 //
2576 //
2577
2578 /// \name Extra Semantic Checking
2579 /// Implementations are in SemaChecking.cpp
2580 ///@{
2581
2582public:
2583 /// Used to change context to isConstantEvaluated without pushing a heavy
2584 /// ExpressionEvaluationContextRecord object.
2586
2591
2593 unsigned ByteNo) const;
2594
2596 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2597 FAPK_Variadic, // values to format are passed as variadic arguments
2598 FAPK_VAList, // values to format are passed in a va_list
2599 FAPK_Elsewhere, // values to format are not passed to this function
2600 };
2601
2602 // Used to grab the relevant information from a FormatAttr and a
2603 // FunctionDeclaration.
2609
2610 /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2611 /// populate the FormatStringInfo parameter with the attribute's correct
2612 /// format_idx and firstDataArg. Returns true when the format fits the
2613 /// function and the FormatStringInfo has been populated.
2614 static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2615 unsigned FirstArg, FormatStringInfo *FSI);
2616 static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2617 bool HasImplicitThisParam, bool IsVariadic,
2618 FormatStringInfo *FSI);
2619
2620 // Used by C++ template instantiation.
2622
2623 /// ConvertVectorExpr - Handle __builtin_convertvector
2625 SourceLocation BuiltinLoc,
2626 SourceLocation RParenLoc);
2627
2628 static StringRef GetFormatStringTypeName(FormatStringType FST);
2629 static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2630 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2631 static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2632
2633 bool FormatStringHasSArg(const StringLiteral *FExpr);
2634
2635 /// Check for comparisons of floating-point values using == and !=. Issue a
2636 /// warning if the comparison is not likely to do what the programmer
2637 /// intended.
2638 void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2639 const Expr *RHS, BinaryOperatorKind Opcode);
2640
2641 /// Register a magic integral constant to be used as a type tag.
2642 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2643 uint64_t MagicValue, QualType Type,
2644 bool LayoutCompatible, bool MustBeNull);
2645
2648
2652
2654
2655 /// If true, \c Type should be compared with other expression's types for
2656 /// layout-compatibility.
2657 LLVM_PREFERRED_TYPE(bool)
2659 LLVM_PREFERRED_TYPE(bool)
2660 unsigned MustBeNull : 1;
2661 };
2662
2663 /// A pair of ArgumentKind identifier and magic value. This uniquely
2664 /// identifies the magic value.
2665 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2666
2667 /// Diagnoses the current set of gathered accesses. This happens at the end of
2668 /// each expression evaluation context. Diagnostics are emitted only for
2669 /// accesses gathered in the current evaluation context.
2671
2672 /// This function checks if the expression is in the sef of potentially
2673 /// misaligned members and it is converted to some pointer type T with lower
2674 /// or equal alignment requirements. If so it removes it. This is used when
2675 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2676 /// void*).
2677 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2678
2679 /// Returns true if `From` is a function or pointer to a function with the
2680 /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2681 /// function without this attribute.
2682 bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2683
2684 /// This function calls Action when it determines that E designates a
2685 /// misaligned member due to the packed attribute. This is used to emit
2686 /// local diagnostics like in reference binding.
2688 Expr *E,
2689 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2690 Action);
2691
2692 enum class AtomicArgumentOrder { API, AST };
2694 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2695 SourceLocation RParenLoc, MultiExprArg Args,
2698
2699 /// Check to see if a given expression could have '.c_str()' called on it.
2700 bool hasCStrMethod(const Expr *E);
2701
2702 /// Diagnose pointers that are always non-null.
2703 /// \param E the expression containing the pointer
2704 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2705 /// compared to a null pointer
2706 /// \param IsEqual True when the comparison is equal to a null pointer
2707 /// \param Range Extra SourceRange to highlight in the diagnostic
2710 bool IsEqual, SourceRange Range);
2711
2712 /// CheckParmsForFunctionDef - Check that the parameters of the given
2713 /// function are appropriate for the definition of a function. This
2714 /// takes care of any checks that cannot be performed on the
2715 /// declaration itself, e.g., that the types of each of the function
2716 /// parameters are complete.
2718 bool CheckParameterNames);
2719
2720 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2721 /// pointer cast increases the alignment requirements.
2722 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2723
2724 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2725 /// to weak/__unsafe_unretained type.
2726 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2727
2728 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2729 /// to weak/__unsafe_unretained expression.
2730 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2731
2732 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2733 /// statement as a \p Body, and it is located on the same line.
2734 ///
2735 /// This helps prevent bugs due to typos, such as:
2736 /// if (condition);
2737 /// do_stuff();
2738 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2739 unsigned DiagID);
2740
2741 /// Warn if a for/while loop statement \p S, which is followed by
2742 /// \p PossibleBody, has a suspicious null statement as a body.
2743 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2744
2745 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2746 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2747 SourceLocation OpLoc);
2748
2749 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2751 const TypeSourceInfo *Derived);
2752
2753 /// CheckFunctionCall - Check a direct function call for various correctness
2754 /// and safety properties not strictly enforced by the C type system.
2755 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2756 const FunctionProtoType *Proto);
2757
2764
2765 /// \param FPOnly restricts the arguments to floating-point types.
2766 std::optional<QualType>
2767 BuiltinVectorMath(CallExpr *TheCall,
2770 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2771
2772 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2773 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2774
2775 /// Handles the checks for format strings, non-POD arguments to vararg
2776 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2777 /// attributes and AArch64 SME attributes.
2778 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2779 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2780 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2781 VariadicCallType CallType);
2782
2783 /// Verify that two format strings (as understood by attribute(format) and
2784 /// attribute(format_matches) are compatible. If they are incompatible,
2785 /// diagnostics are emitted with the assumption that \c
2786 /// AuthoritativeFormatString is correct and
2787 /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2788 /// diagnostics will point to it and a note will refer to \c
2789 /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2790 bool
2792 const StringLiteral *AuthoritativeFormatString,
2793 const StringLiteral *TestedFormatString,
2794 const Expr *FunctionCallArg = nullptr);
2795
2796 /// Verify that one format string (as understood by attribute(format)) is
2797 /// self-consistent; for instance, that it doesn't have multiple positional
2798 /// arguments referring to the same argument in incompatible ways. Diagnose
2799 /// if it isn't.
2801
2802 /// \brief Enforce the bounds of a TCB
2803 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2804 /// directly calls other functions in the same TCB as marked by the
2805 /// enforce_tcb and enforce_tcb_leaf attributes.
2806 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2807 const NamedDecl *Callee);
2808
2809 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2810
2811 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2812 /// TheCall is a constant expression.
2813 bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
2814 llvm::APSInt &Result);
2815
2816 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2817 /// TheCall is a constant expression in the range [Low, High].
2818 bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
2819 int High, bool RangeIsError = true);
2820
2821 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2822 /// TheCall is a constant expression is a multiple of Num..
2823 bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
2824 unsigned Multiple);
2825
2826 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2827 /// constant expression representing a power of 2.
2828 bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum);
2829
2830 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2831 /// a constant expression representing an arbitrary byte value shifted left by
2832 /// a multiple of 8 bits.
2833 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
2834 unsigned ArgBits);
2835
2836 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2837 /// TheCall is a constant expression representing either a shifted byte value,
2838 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2839 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2840 /// Arm MVE intrinsics.
2841 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum,
2842 unsigned ArgBits);
2843
2844 /// Checks that a call expression's argument count is at least the desired
2845 /// number. This is useful when doing custom type-checking on a variadic
2846 /// function. Returns true on error.
2847 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2848
2849 /// Checks that a call expression's argument count is at most the desired
2850 /// number. This is useful when doing custom type-checking on a variadic
2851 /// function. Returns true on error.
2852 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
2853
2854 /// Checks that a call expression's argument count is in the desired range.
2855 /// This is useful when doing custom type-checking on a variadic function.
2856 /// Returns true on error.
2857 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
2858 unsigned MaxArgCount);
2859
2860 /// Checks that a call expression's argument count is the desired number.
2861 /// This is useful when doing custom type-checking. Returns true on error.
2862 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
2863
2864 /// Returns true if the argument consists of one contiguous run of 1s with any
2865 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
2866 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
2867 /// since all 1s are not contiguous.
2868 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2869
2871 bool *ICContext = nullptr,
2872 bool IsListInit = false);
2873
2874 bool
2879 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
2881
2882private:
2883 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2884 const ArraySubscriptExpr *ASE = nullptr,
2885 bool AllowOnePastEnd = true, bool IndexNegated = false);
2886 void CheckArrayAccess(const Expr *E);
2887
2888 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2889 const FunctionProtoType *Proto);
2890
2891 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2892 /// such as function pointers returned from functions.
2893 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
2894
2895 /// CheckConstructorCall - Check a constructor call for correctness and safety
2896 /// properties not enforced by the C type system.
2897 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
2899 const FunctionProtoType *Proto, SourceLocation Loc);
2900
2901 /// Warn if a pointer or reference argument passed to a function points to an
2902 /// object that is less aligned than the parameter. This can happen when
2903 /// creating a typedef with a lower alignment than the original type and then
2904 /// calling functions defined in terms of the original type.
2905 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
2906 StringRef ParamName, QualType ArgTy, QualType ParamTy);
2907
2908 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
2909
2910 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2911 CallExpr *TheCall);
2912
2913 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2914 CallExpr *TheCall);
2915
2916 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
2917
2918 /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
2919 /// or '__builtin_c23_va_start' for validity. Emit an error and return true
2920 /// on failure; return false on success.
2921 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
2922 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
2923
2924 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2925 /// friends. This is declared to take (...), so we have to check everything.
2926 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
2927
2928 /// BuiltinSemaBuiltinFPClassification - Handle functions like
2929 /// __builtin_isnan and friends. This is declared to take (...), so we have
2930 /// to check everything.
2931 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
2932 unsigned BuiltinID);
2933
2934 /// Perform semantic analysis for a call to __builtin_complex.
2935 bool BuiltinComplex(CallExpr *TheCall);
2936 bool BuiltinOSLogFormat(CallExpr *TheCall);
2937
2938 /// BuiltinPrefetch - Handle __builtin_prefetch.
2939 /// This is declared to take (const void*, ...) and can take two
2940 /// optional constant int args.
2941 bool BuiltinPrefetch(CallExpr *TheCall);
2942
2943 /// Handle __builtin_alloca_with_align. This is declared
2944 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
2945 /// than 8.
2946 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
2947
2948 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
2949 bool BuiltinArithmeticFence(CallExpr *TheCall);
2950
2951 /// BuiltinAssume - Handle __assume (MS Extension).
2952 /// __assume does not evaluate its arguments, and should warn if its argument
2953 /// has side effects.
2954 bool BuiltinAssume(CallExpr *TheCall);
2955
2956 /// Handle __builtin_assume_aligned. This is declared
2957 /// as (const void*, size_t, ...) and can take one optional constant int arg.
2958 bool BuiltinAssumeAligned(CallExpr *TheCall);
2959
2960 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
2961 /// This checks that the target supports __builtin_longjmp and
2962 /// that val is a constant 1.
2963 bool BuiltinLongjmp(CallExpr *TheCall);
2964
2965 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2966 /// This checks that the target supports __builtin_setjmp.
2967 bool BuiltinSetjmp(CallExpr *TheCall);
2968
2969 /// We have a call to a function like __sync_fetch_and_add, which is an
2970 /// overloaded function based on the pointer type of its first argument.
2971 /// The main BuildCallExpr routines have already promoted the types of
2972 /// arguments because all of these calls are prototyped as void(...).
2973 ///
2974 /// This function goes through and does final semantic checking for these
2975 /// builtins, as well as generating any warnings.
2976 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
2977
2978 /// BuiltinNontemporalOverloaded - We have a call to
2979 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2980 /// overloaded function based on the pointer type of its last argument.
2981 ///
2982 /// This function goes through and does final semantic checking for these
2983 /// builtins.
2984 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
2985 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
2987
2988 /// \param FPOnly restricts the arguments to floating-point types.
2989 bool BuiltinElementwiseMath(CallExpr *TheCall,
2992 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
2993
2994 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
2995
2996 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
2998 bool BuiltinCountedByRef(CallExpr *TheCall);
2999
3000 // Matrix builtin handling.
3001 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
3002 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
3003 ExprResult CallResult);
3004 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
3005 ExprResult CallResult);
3006
3007 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3008 /// functions) for correct use of format strings.
3009 /// Returns true if a format string has been fully checked.
3010 bool CheckFormatArguments(const FormatAttr *Format,
3011 ArrayRef<const Expr *> Args, bool IsCXXMember,
3012 VariadicCallType CallType, SourceLocation Loc,
3013 SourceRange Range,
3014 llvm::SmallBitVector &CheckedVarArgs);
3015 bool CheckFormatString(const FormatMatchesAttr *Format,
3016 ArrayRef<const Expr *> Args, bool IsCXXMember,
3017 VariadicCallType CallType, SourceLocation Loc,
3018 SourceRange Range,
3019 llvm::SmallBitVector &CheckedVarArgs);
3020 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3021 FormatArgumentPassingKind FAPK,
3022 const StringLiteral *ReferenceFormatString,
3023 unsigned format_idx, unsigned firstDataArg,
3025 SourceLocation Loc, SourceRange range,
3026 llvm::SmallBitVector &CheckedVarArgs);
3027
3028 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3029
3030 /// Warn when using the wrong abs() function.
3031 void CheckAbsoluteValueFunction(const CallExpr *Call,
3032 const FunctionDecl *FDecl);
3033
3034 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3035
3036 /// Check for dangerous or invalid arguments to memset().
3037 ///
3038 /// This issues warnings on known problematic, dangerous or unspecified
3039 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3040 /// function calls.
3041 ///
3042 /// \param Call The call expression to diagnose.
3043 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3044 IdentifierInfo *FnName);
3045
3046 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3047 // be the size of the source, instead of the destination.
3048 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3049
3050 // Warn on anti-patterns as the 'size' argument to strncat.
3051 // The correct size argument should look like following:
3052 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3053 void CheckStrncatArguments(const CallExpr *Call,
3054 const IdentifierInfo *FnName);
3055
3056 /// Alerts the user that they are attempting to free a non-malloc'd object.
3057 void CheckFreeArguments(const CallExpr *E);
3058
3059 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3060 SourceLocation ReturnLoc, bool isObjCMethod = false,
3061 const AttrVec *Attrs = nullptr,
3062 const FunctionDecl *FD = nullptr);
3063
3064 /// Diagnoses "dangerous" implicit conversions within the given
3065 /// expression (which is a full expression). Implements -Wconversion
3066 /// and -Wsign-compare.
3067 ///
3068 /// \param CC the "context" location of the implicit conversion, i.e.
3069 /// the most location of the syntactic entity requiring the implicit
3070 /// conversion
3071 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3072
3073 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3074 /// Input argument E is a logical expression.
3076
3077 /// Diagnose when expression is an integer constant expression and its
3078 /// evaluation results in integer overflow
3079 void CheckForIntOverflow(const Expr *E);
3080 void CheckUnsequencedOperations(const Expr *E);
3081
3082 /// Perform semantic checks on a completed expression. This will either
3083 /// be a full-expression or a default argument expression.
3084 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3085 bool IsConstexpr = false);
3086
3087 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3088 Expr *Init);
3089
3090 /// A map from magic value to type information.
3091 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3092 TypeTagForDatatypeMagicValues;
3093
3094 /// Peform checks on a call of a function with argument_with_type_tag
3095 /// or pointer_with_type_tag attributes.
3096 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3097 const ArrayRef<const Expr *> ExprArgs,
3098 SourceLocation CallSiteLoc);
3099
3100 /// Check if we are taking the address of a packed field
3101 /// as this may be a problem if the pointer value is dereferenced.
3102 void CheckAddressOfPackedMember(Expr *rhs);
3103
3104 /// Helper class that collects misaligned member designations and
3105 /// their location info for delayed diagnostics.
3106 struct MisalignedMember {
3107 Expr *E;
3108 RecordDecl *RD;
3109 ValueDecl *MD;
3110 CharUnits Alignment;
3111
3112 MisalignedMember() : E(), RD(), MD() {}
3113 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3114 CharUnits Alignment)
3115 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
3116 explicit MisalignedMember(Expr *E)
3117 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3118
3119 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3120 };
3121
3122 /// Adds an expression to the set of gathered misaligned members.
3123 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3124 CharUnits Alignment);
3125 ///@}
3126
3127 //
3128 //
3129 // -------------------------------------------------------------------------
3130 //
3131 //
3132
3133 /// \name C++ Coroutines
3134 /// Implementations are in SemaCoroutine.cpp
3135 ///@{
3136
3137public:
3138 /// The C++ "std::coroutine_traits" template, which is defined in
3139 /// <coroutine_traits>
3141
3143 StringRef Keyword);
3147
3150 UnresolvedLookupExpr *Lookup);
3152 Expr *Awaiter, bool IsImplicit = false);
3154 UnresolvedLookupExpr *Lookup);
3157 bool IsImplicit = false);
3162
3163 // As a clang extension, enforces that a non-coroutine function must be marked
3164 // with [[clang::coro_wrapper]] if it returns a type marked with
3165 // [[clang::coro_return_type]].
3166 // Expects that FD is not a coroutine.
3168 /// Lookup 'coroutine_traits' in std namespace and std::experimental
3169 /// namespace. The namespace found is recorded in Namespace.
3171 SourceLocation FuncLoc);
3172 /// Check that the expression co_await promise.final_suspend() shall not be
3173 /// potentially-throwing.
3174 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3175
3176 ///@}
3177
3178 //
3179 //
3180 // -------------------------------------------------------------------------
3181 //
3182 //
3183
3184 /// \name C++ Scope Specifiers
3185 /// Implementations are in SemaCXXScopeSpec.cpp
3186 ///@{
3187
3188public:
3189 // Marks SS invalid if it represents an incomplete type.
3191 // Complete an enum decl, maybe without a scope spec.
3193 CXXScopeSpec *SS = nullptr);
3194
3195 /// Compute the DeclContext that is associated with the given type.
3196 ///
3197 /// \param T the type for which we are attempting to find a DeclContext.
3198 ///
3199 /// \returns the declaration context represented by the type T,
3200 /// or NULL if the declaration context cannot be computed (e.g., because it is
3201 /// dependent and not the current instantiation).
3203
3204 /// Compute the DeclContext that is associated with the given
3205 /// scope specifier.
3206 ///
3207 /// \param SS the C++ scope specifier as it appears in the source
3208 ///
3209 /// \param EnteringContext when true, we will be entering the context of
3210 /// this scope specifier, so we can retrieve the declaration context of a
3211 /// class template or class template partial specialization even if it is
3212 /// not the current instantiation.
3213 ///
3214 /// \returns the declaration context represented by the scope specifier @p SS,
3215 /// or NULL if the declaration context cannot be computed (e.g., because it is
3216 /// dependent and not the current instantiation).
3218 bool EnteringContext = false);
3220
3221 /// If the given nested name specifier refers to the current
3222 /// instantiation, return the declaration that corresponds to that
3223 /// current instantiation (C++0x [temp.dep.type]p1).
3224 ///
3225 /// \param NNS a dependent nested name specifier.
3227
3228 /// The parser has parsed a global nested-name-specifier '::'.
3229 ///
3230 /// \param CCLoc The location of the '::'.
3231 ///
3232 /// \param SS The nested-name-specifier, which will be updated in-place
3233 /// to reflect the parsed nested-name-specifier.
3234 ///
3235 /// \returns true if an error occurred, false otherwise.
3237
3238 /// The parser has parsed a '__super' nested-name-specifier.
3239 ///
3240 /// \param SuperLoc The location of the '__super' keyword.
3241 ///
3242 /// \param ColonColonLoc The location of the '::'.
3243 ///
3244 /// \param SS The nested-name-specifier, which will be updated in-place
3245 /// to reflect the parsed nested-name-specifier.
3246 ///
3247 /// \returns true if an error occurred, false otherwise.
3249 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3250
3251 /// Determines whether the given declaration is an valid acceptable
3252 /// result for name lookup of a nested-name-specifier.
3253 /// \param SD Declaration checked for nested-name-specifier.
3254 /// \param IsExtension If not null and the declaration is accepted as an
3255 /// extension, the pointed variable is assigned true.
3257 bool *CanCorrect = nullptr);
3258
3259 /// If the given nested-name-specifier begins with a bare identifier
3260 /// (e.g., Base::), perform name lookup for that identifier as a
3261 /// nested-name-specifier within the given scope, and return the result of
3262 /// that name lookup.
3264
3265 /// Keeps information about an identifier in a nested-name-spec.
3266 ///
3268 /// The type of the object, if we're parsing nested-name-specifier in
3269 /// a member access expression.
3271
3272 /// The identifier preceding the '::'.
3274
3275 /// The location of the identifier.
3277
3278 /// The location of the '::'.
3280
3281 /// Creates info object for the most typical case.
3283 SourceLocation ColonColonLoc,
3286 CCLoc(ColonColonLoc) {}
3287
3289 SourceLocation ColonColonLoc, QualType ObjectType)
3291 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3292 };
3293
3294 /// Build a new nested-name-specifier for "identifier::", as described
3295 /// by ActOnCXXNestedNameSpecifier.
3296 ///
3297 /// \param S Scope in which the nested-name-specifier occurs.
3298 /// \param IdInfo Parser information about an identifier in the
3299 /// nested-name-spec.
3300 /// \param EnteringContext If true, enter the context specified by the
3301 /// nested-name-specifier.
3302 /// \param SS Optional nested name specifier preceding the identifier.
3303 /// \param ScopeLookupResult Provides the result of name lookup within the
3304 /// scope of the nested-name-specifier that was computed at template
3305 /// definition time.
3306 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3307 /// error recovery and what kind of recovery is performed.
3308 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3309 /// are allowed. The bool value pointed by this parameter is set to
3310 /// 'true' if the identifier is treated as if it was followed by ':',
3311 /// not '::'.
3312 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3313 ///
3314 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3315 /// that it contains an extra parameter \p ScopeLookupResult, which provides
3316 /// the result of name lookup within the scope of the nested-name-specifier
3317 /// that was computed at template definition time.
3318 ///
3319 /// If ErrorRecoveryLookup is true, then this call is used to improve error
3320 /// recovery. This means that it should not emit diagnostics, it should
3321 /// just return true on failure. It also means it should only return a valid
3322 /// scope if it *knows* that the result is correct. It should not return in a
3323 /// dependent context, for example. Nor will it extend \p SS with the scope
3324 /// specifier.
3325 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3326 bool EnteringContext, CXXScopeSpec &SS,
3327 NamedDecl *ScopeLookupResult,
3328 bool ErrorRecoveryLookup,
3329 bool *IsCorrectedToColon = nullptr,
3330 bool OnlyNamespace = false);
3331
3332 /// The parser has parsed a nested-name-specifier 'identifier::'.
3333 ///
3334 /// \param S The scope in which this nested-name-specifier occurs.
3335 ///
3336 /// \param IdInfo Parser information about an identifier in the
3337 /// nested-name-spec.
3338 ///
3339 /// \param EnteringContext Whether we're entering the context nominated by
3340 /// this nested-name-specifier.
3341 ///
3342 /// \param SS The nested-name-specifier, which is both an input
3343 /// parameter (the nested-name-specifier before this type) and an
3344 /// output parameter (containing the full nested-name-specifier,
3345 /// including this new type).
3346 ///
3347 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3348 /// are allowed. The bool value pointed by this parameter is set to 'true'
3349 /// if the identifier is treated as if it was followed by ':', not '::'.
3350 ///
3351 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3352 ///
3353 /// \returns true if an error occurred, false otherwise.
3354 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3355 bool EnteringContext, CXXScopeSpec &SS,
3356 bool *IsCorrectedToColon = nullptr,
3357 bool OnlyNamespace = false);
3358
3359 /// The parser has parsed a nested-name-specifier
3360 /// 'template[opt] template-name < template-args >::'.
3361 ///
3362 /// \param S The scope in which this nested-name-specifier occurs.
3363 ///
3364 /// \param SS The nested-name-specifier, which is both an input
3365 /// parameter (the nested-name-specifier before this type) and an
3366 /// output parameter (containing the full nested-name-specifier,
3367 /// including this new type).
3368 ///
3369 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3370 /// \param TemplateName the template name.
3371 /// \param TemplateNameLoc The location of the template name.
3372 /// \param LAngleLoc The location of the opening angle bracket ('<').
3373 /// \param TemplateArgs The template arguments.
3374 /// \param RAngleLoc The location of the closing angle bracket ('>').
3375 /// \param CCLoc The location of the '::'.
3376 ///
3377 /// \param EnteringContext Whether we're entering the context of the
3378 /// nested-name-specifier.
3379 ///
3380 ///
3381 /// \returns true if an error occurred, false otherwise.
3383 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3384 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3385 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3386 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3387
3389 SourceLocation ColonColonLoc);
3390
3392 const DeclSpec &DS,
3393 SourceLocation ColonColonLoc,
3394 QualType Type);
3395
3396 /// IsInvalidUnlessNestedName - This method is used for error recovery
3397 /// purposes to determine whether the specified identifier is only valid as
3398 /// a nested name specifier, for example a namespace name. It is
3399 /// conservatively correct to always return false from this method.
3400 ///
3401 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3403 NestedNameSpecInfo &IdInfo,
3404 bool EnteringContext);
3405
3406 /// Given a C++ nested-name-specifier, produce an annotation value
3407 /// that the parser can use later to reconstruct the given
3408 /// nested-name-specifier.
3409 ///
3410 /// \param SS A nested-name-specifier.
3411 ///
3412 /// \returns A pointer containing all of the information in the
3413 /// nested-name-specifier \p SS.
3415
3416 /// Given an annotation pointer for a nested-name-specifier, restore
3417 /// the nested-name-specifier structure.
3418 ///
3419 /// \param Annotation The annotation pointer, produced by
3420 /// \c SaveNestedNameSpecifierAnnotation().
3421 ///
3422 /// \param AnnotationRange The source range corresponding to the annotation.
3423 ///
3424 /// \param SS The nested-name-specifier that will be updated with the contents
3425 /// of the annotation pointer.
3426 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3427 SourceRange AnnotationRange,
3428 CXXScopeSpec &SS);
3429
3430 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3431
3432 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3433 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3434 /// After this method is called, according to [C++ 3.4.3p3], names should be
3435 /// looked up in the declarator-id's scope, until the declarator is parsed and
3436 /// ActOnCXXExitDeclaratorScope is called.
3437 /// The 'SS' should be a non-empty valid CXXScopeSpec.
3439
3440 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3441 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3442 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3443 /// Used to indicate that names should revert to being looked up in the
3444 /// defining scope.
3446
3447 ///@}
3448
3449 //
3450 //
3451 // -------------------------------------------------------------------------
3452 //
3453 //
3454
3455 /// \name Declarations
3456 /// Implementations are in SemaDecl.cpp
3457 ///@{
3458
3459public:
3461
3462 /// The index of the first InventedParameterInfo that refers to the current
3463 /// context.
3465
3466 /// A RAII object to temporarily push a declaration context.
3468 private:
3469 Sema &S;
3470 DeclContext *SavedContext;
3471 ProcessingContextState SavedContextState;
3472 QualType SavedCXXThisTypeOverride;
3473 unsigned SavedFunctionScopesStart;
3474 unsigned SavedInventedParameterInfosStart;
3475
3476 public:
3477 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3478 : S(S), SavedContext(S.CurContext),
3479 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3480 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3481 SavedFunctionScopesStart(S.FunctionScopesStart),
3482 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3483 assert(ContextToPush && "pushing null context");
3484 S.CurContext = ContextToPush;
3485 if (NewThisContext)
3486 S.CXXThisTypeOverride = QualType();
3487 // Any saved FunctionScopes do not refer to this context.
3488 S.FunctionScopesStart = S.FunctionScopes.size();
3489 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3490 }
3491
3492 void pop() {
3493 if (!SavedContext)
3494 return;
3495 S.CurContext = SavedContext;
3496 S.DelayedDiagnostics.popUndelayed(SavedContextState);
3497 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3498 S.FunctionScopesStart = SavedFunctionScopesStart;
3499 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3500 SavedContext = nullptr;
3501 }
3502
3504 };
3505
3506 void DiagnoseInvalidJumps(Stmt *Body);
3507
3508 /// The function definitions which were renamed as part of typo-correction
3509 /// to match their respective declarations. We want to keep track of them
3510 /// to ensure that we don't emit a "redefinition" error if we encounter a
3511 /// correctly named definition after the renamed definition.
3513
3514 /// A cache of the flags available in enumerations with the flag_bits
3515 /// attribute.
3516 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3517
3518 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3519 /// declared. Rare. May alias another identifier, declared or undeclared.
3520 ///
3521 /// For aliases, the target identifier is used as a key for eventual
3522 /// processing when the target is declared. For the single-identifier form,
3523 /// the sole identifier is used as the key. Each entry is a `SetVector`
3524 /// (ordered by parse order) of aliases (identified by the alias name) in case
3525 /// of multiple aliases to the same undeclared identifier.
3526 llvm::MapVector<
3528 llvm::SetVector<
3530 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3532
3533 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3534 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3535 /// to define functions that occur in multiple standards to call the version
3536 /// in the currently selected standard.
3537 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *> ExtnameUndeclaredIdentifiers;
3538
3539 /// Set containing all typedefs that are likely unused.
3542
3546
3547 /// The set of file scoped decls seen so far that have not been used
3548 /// and must warn if not used. Only contains the first declaration.
3550
3554
3555 /// All the tentative definitions encountered in the TU.
3557
3558 /// All the external declarations encoutered and used in the TU.
3560
3561 /// Generally null except when we temporarily switch decl contexts,
3562 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3564
3565 /// Is the module scope we are in a C++ Header Unit?
3567 return ModuleScopes.empty() ? false
3568 : ModuleScopes.back().Module->isHeaderUnit();
3569 }
3570
3571 /// Get the module owning an entity.
3572 Module *getOwningModule(const Decl *Entity) {
3573 return Entity->getOwningModule();
3574 }
3575
3576 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3577
3579 /// Returns the TypeDeclType for the given type declaration,
3580 /// as ASTContext::getTypeDeclType would, but
3581 /// performs the required semantic checks for name lookup of said entity.
3582 void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD,
3583 SourceLocation NameLoc);
3584
3585 /// If the identifier refers to a type name within this scope,
3586 /// return the declaration of that type.
3587 ///
3588 /// This routine performs ordinary name lookup of the identifier II
3589 /// within the given scope, with optional C++ scope specifier SS, to
3590 /// determine whether the name refers to a type. If so, returns an
3591 /// opaque pointer (actually a QualType) corresponding to that
3592 /// type. Otherwise, returns NULL.
3594 Scope *S, CXXScopeSpec *SS = nullptr,
3595 bool isClassName = false, bool HasTrailingDot = false,
3596 ParsedType ObjectType = nullptr,
3597 bool IsCtorOrDtorName = false,
3598 bool WantNontrivialTypeSourceInfo = false,
3599 bool IsClassTemplateDeductionContext = true,
3600 ImplicitTypenameContext AllowImplicitTypename =
3602 IdentifierInfo **CorrectedII = nullptr);
3603
3604 /// isTagName() - This method is called *for error recovery purposes only*
3605 /// to determine if the specified name is a valid tag name ("struct foo"). If
3606 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3607 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3608 /// diagnose cases in C where the user forgot to specify the tag.
3610
3611 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3612 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3613 /// then downgrade the missing typename error to a warning.
3614 /// This is needed for MSVC compatibility; Example:
3615 /// @code
3616 /// template<class T> class A {
3617 /// public:
3618 /// typedef int TYPE;
3619 /// };
3620 /// template<class T> class B : public A<T> {
3621 /// public:
3622 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3623 /// };
3624 /// @endcode
3625 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3627 Scope *S, CXXScopeSpec *SS,
3628 ParsedType &SuggestedType,
3629 bool IsTemplateName = false);
3630
3631 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3632 /// type name has failed in a dependent context. In these situations, we
3633 /// automatically form a DependentTypeName that will retry lookup in a related
3634 /// scope during instantiation.
3636 SourceLocation NameLoc,
3637 bool IsTemplateTypeArg);
3638
3639 class NameClassification {
3641 union {
3646 };
3647
3648 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3649
3650 public:
3653
3656
3657 static NameClassification Error() {
3658 return NameClassification(NameClassificationKind::Error);
3659 }
3660
3661 static NameClassification Unknown() {
3662 return NameClassification(NameClassificationKind::Unknown);
3663 }
3664
3665 static NameClassification OverloadSet(ExprResult E) {
3666 NameClassification Result(NameClassificationKind::OverloadSet);
3667 Result.Expr = E;
3668 return Result;
3669 }
3670
3671 static NameClassification NonType(NamedDecl *D) {
3672 NameClassification Result(NameClassificationKind::NonType);
3673 Result.NonTypeDecl = D;
3674 return Result;
3675 }
3676
3677 static NameClassification UndeclaredNonType() {
3678 return NameClassification(NameClassificationKind::UndeclaredNonType);
3679 }
3680
3681 static NameClassification DependentNonType() {
3682 return NameClassification(NameClassificationKind::DependentNonType);
3683 }
3684
3685 static NameClassification TypeTemplate(TemplateName Name) {
3686 NameClassification Result(NameClassificationKind::TypeTemplate);
3687 Result.Template = Name;
3688 return Result;
3689 }
3690
3691 static NameClassification VarTemplate(TemplateName Name) {
3692 NameClassification Result(NameClassificationKind::VarTemplate);
3693 Result.Template = Name;
3694 return Result;
3695 }
3696
3697 static NameClassification FunctionTemplate(TemplateName Name) {
3699 Result.Template = Name;
3700 return Result;
3701 }
3702
3703 static NameClassification Concept(TemplateName Name) {
3704 NameClassification Result(NameClassificationKind::Concept);
3705 Result.Template = Name;
3706 return Result;
3707 }
3708
3709 static NameClassification UndeclaredTemplate(TemplateName Name) {
3711 Result.Template = Name;
3712 return Result;
3713 }
3714
3715 NameClassificationKind getKind() const { return Kind; }
3716
3719 return Expr;
3720 }
3721
3723 assert(Kind == NameClassificationKind::Type);
3724 return Type;
3725 }
3726
3728 assert(Kind == NameClassificationKind::NonType);
3729 return NonTypeDecl;
3730 }
3731
3740
3742 switch (Kind) {
3744 return TNK_Type_template;
3746 return TNK_Function_template;
3748 return TNK_Var_template;
3750 return TNK_Concept_template;
3753 default:
3754 llvm_unreachable("unsupported name classification.");
3755 }
3756 }
3757 };
3758
3759 /// Perform name lookup on the given name, classifying it based on
3760 /// the results of name lookup and the following token.
3761 ///
3762 /// This routine is used by the parser to resolve identifiers and help direct
3763 /// parsing. When the identifier cannot be found, this routine will attempt
3764 /// to correct the typo and classify based on the resulting name.
3765 ///
3766 /// \param S The scope in which we're performing name lookup.
3767 ///
3768 /// \param SS The nested-name-specifier that precedes the name.
3769 ///
3770 /// \param Name The identifier. If typo correction finds an alternative name,
3771 /// this pointer parameter will be updated accordingly.
3772 ///
3773 /// \param NameLoc The location of the identifier.
3774 ///
3775 /// \param NextToken The token following the identifier. Used to help
3776 /// disambiguate the name.
3777 ///
3778 /// \param CCC The correction callback, if typo correction is desired.
3779 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3780 IdentifierInfo *&Name, SourceLocation NameLoc,
3781 const Token &NextToken,
3782 CorrectionCandidateCallback *CCC = nullptr);
3783
3784 /// Act on the result of classifying a name as an undeclared (ADL-only)
3785 /// non-type declaration.
3787 SourceLocation NameLoc);
3788 /// Act on the result of classifying a name as an undeclared member of a
3789 /// dependent base class.
3791 IdentifierInfo *Name,
3792 SourceLocation NameLoc,
3793 bool IsAddressOfOperand);
3794 /// Act on the result of classifying a name as a specific non-type
3795 /// declaration.
3798 SourceLocation NameLoc,
3799 const Token &NextToken);
3800 /// Act on the result of classifying a name as an overload set.
3802
3803 /// Describes the detailed kind of a template name. Used in diagnostics.
3815
3816 /// Determine whether it's plausible that E was intended to be a
3817 /// template-name.
3819 if (!getLangOpts().CPlusPlus || E.isInvalid())
3820 return false;
3821 Dependent = false;
3822 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
3823 return !DRE->hasExplicitTemplateArgs();
3824 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
3825 return !ME->hasExplicitTemplateArgs();
3826 Dependent = true;
3827 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
3828 return !DSDRE->hasExplicitTemplateArgs();
3829 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
3830 return !DSME->hasExplicitTemplateArgs();
3831 // Any additional cases recognized here should also be handled by
3832 // diagnoseExprIntendedAsTemplateName.
3833 return false;
3834 }
3835
3836 void warnOnReservedIdentifier(const NamedDecl *D);
3838
3840
3842 MultiTemplateParamsArg TemplateParameterLists);
3843
3844 /// Attempt to fold a variable-sized type to a constant-sized type, returning
3845 /// true if we were successful.
3847 SourceLocation Loc,
3848 unsigned FailedFoldDiagID);
3849
3850 /// Register the given locally-scoped extern "C" declaration so
3851 /// that it can be found later for redeclarations. We include any extern "C"
3852 /// declaration that is not visible in the translation unit here, not just
3853 /// function-scope declarations.
3855
3856 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3857 /// If T is the name of a class, then each of the following shall have a
3858 /// name different from T:
3859 /// - every static data member of class T;
3860 /// - every member function of class T
3861 /// - every member of class T that is itself a type;
3862 /// \returns true if the declaration name violates these rules.
3864
3865 /// Diagnose a declaration whose declarator-id has the given
3866 /// nested-name-specifier.
3867 ///
3868 /// \param SS The nested-name-specifier of the declarator-id.
3869 ///
3870 /// \param DC The declaration context to which the nested-name-specifier
3871 /// resolves.
3872 ///
3873 /// \param Name The name of the entity being declared.
3874 ///
3875 /// \param Loc The location of the name of the entity being declared.
3876 ///
3877 /// \param IsMemberSpecialization Whether we are declaring a member
3878 /// specialization.
3879 ///
3880 /// \param TemplateId The template-id, if any.
3881 ///
3882 /// \returns true if we cannot safely recover from this error, false
3883 /// otherwise.
3886 TemplateIdAnnotation *TemplateId,
3887 bool IsMemberSpecialization);
3888
3890
3891 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
3892
3894 unsigned &IntVal);
3895
3896 /// Diagnose function specifiers on a declaration of an identifier that
3897 /// does not identify a function.
3898 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
3899
3900 /// Return the declaration shadowed by the given typedef \p D, or null
3901 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3903 const LookupResult &R);
3904
3905 /// Return the declaration shadowed by the given variable \p D, or null
3906 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3908
3909 /// Return the declaration shadowed by the given variable \p D, or null
3910 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3912 const LookupResult &R);
3913 /// Diagnose variable or built-in function shadowing. Implements
3914 /// -Wshadow.
3915 ///
3916 /// This method is called whenever a VarDecl is added to a "useful"
3917 /// scope.
3918 ///
3919 /// \param ShadowedDecl the declaration that is shadowed by the given variable
3920 /// \param R the lookup of the name
3921 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
3922 const LookupResult &R);
3923
3924 /// Check -Wshadow without the advantage of a previous lookup.
3925 void CheckShadow(Scope *S, VarDecl *D);
3926
3927 /// Warn if 'E', which is an expression that is about to be modified, refers
3928 /// to a shadowing declaration.
3930
3931 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
3932 /// when these variables are captured by the lambda.
3934
3935 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
3936 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3937 TypedefNameDecl *NewTD);
3940 TypeSourceInfo *TInfo,
3942
3943 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3944 /// declares a typedef-name, either using the 'typedef' type specifier or via
3945 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3949 TypeSourceInfo *TInfo,
3951 MultiTemplateParamsArg TemplateParamLists,
3952 bool &AddToScope,
3954
3955private:
3956 // Perform a check on an AsmLabel to verify its consistency and emit
3957 // diagnostics in case of an error.
3958 void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
3959 TypeSourceInfo *TInfo, VarDecl *);
3960
3961public:
3962 /// Perform semantic checking on a newly-created variable
3963 /// declaration.
3964 ///
3965 /// This routine performs all of the type-checking required for a
3966 /// variable declaration once it has been built. It is used both to
3967 /// check variables after they have been parsed and their declarators
3968 /// have been translated into a declaration, and to check variables
3969 /// that have been instantiated from a template.
3970 ///
3971 /// Sets NewVD->isInvalidDecl() if an error was encountered.
3972 ///
3973 /// Returns true if the variable declaration is a redeclaration.
3974 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
3975 void CheckVariableDeclarationType(VarDecl *NewVD);
3976 void CheckCompleteVariableDeclaration(VarDecl *VD);
3977
3978 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
3979 TypeSourceInfo *TInfo,
3980 LookupResult &Previous,
3981 MultiTemplateParamsArg TemplateParamLists,
3982 bool &AddToScope);
3983
3984 /// AddOverriddenMethods - See if a method overrides any in the base classes,
3985 /// and if so, check that it's a valid override and remember it.
3986 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
3987
3988 /// Perform semantic checking of a new function declaration.
3989 ///
3990 /// Performs semantic analysis of the new function declaration
3991 /// NewFD. This routine performs all semantic checking that does not
3992 /// require the actual declarator involved in the declaration, and is
3993 /// used both for the declaration of functions as they are parsed
3994 /// (called via ActOnDeclarator) and for the declaration of functions
3995 /// that have been instantiated via C++ template instantiation (called
3996 /// via InstantiateDecl).
3997 ///
3998 /// \param IsMemberSpecialization whether this new function declaration is
3999 /// a member specialization (that replaces any definition provided by the
4000 /// previous declaration).
4001 ///
4002 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4003 ///
4004 /// \returns true if the function declaration is a redeclaration.
4005 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4006 LookupResult &Previous,
4007 bool IsMemberSpecialization, bool DeclIsDefn);
4008
4009 /// Checks if the new declaration declared in dependent context must be
4010 /// put in the same redeclaration chain as the specified declaration.
4011 ///
4012 /// \param D Declaration that is checked.
4013 /// \param PrevDecl Previous declaration found with proper lookup method for
4014 /// the same declaration name.
4015 /// \returns True if D must be added to the redeclaration chain which PrevDecl
4016 /// belongs to.
4017 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4018
4019 /// Determines if we can perform a correct type check for \p D as a
4020 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4021 /// best-effort check.
4022 ///
4023 /// \param NewD The new declaration.
4024 /// \param OldD The old declaration.
4025 /// \param NewT The portion of the type of the new declaration to check.
4026 /// \param OldT The portion of the type of the old declaration to check.
4027 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4028 QualType NewT, QualType OldT);
4029 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4030 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4031
4032 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4033 /// containing class. Otherwise it will return implicit SectionAttr if the
4034 /// function is a definition and there is an active value on CodeSegStack
4035 /// (from the current #pragma code-seg value).
4036 ///
4037 /// \param FD Function being declared.
4038 /// \param IsDefinition Whether it is a definition or just a declaration.
4039 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4040 /// nullptr if no attribute should be added.
4041 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4042 bool IsDefinition);
4043
4044 /// Common checks for a parameter-declaration that should apply to both
4045 /// function parameters and non-type template parameters.
4046 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4047
4048 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4049 /// to introduce parameters into function prototype scope.
4050 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4051 SourceLocation ExplicitThisLoc = {});
4052
4053 /// Synthesizes a variable for a parameter arising from a
4054 /// typedef.
4055 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4056 QualType T);
4057 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4058 SourceLocation NameLoc,
4059 const IdentifierInfo *Name, QualType T,
4060 TypeSourceInfo *TSInfo, StorageClass SC);
4061
4062 /// Emit diagnostics if the initializer or any of its explicit or
4063 /// implicitly-generated subexpressions require copying or
4064 /// default-initializing a type that is or contains a C union type that is
4065 /// non-trivial to copy or default-initialize.
4066 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4067
4068 // These flags are passed to checkNonTrivialCUnion.
4074
4075 /// Emit diagnostics if a non-trivial C union type or a struct that contains
4076 /// a non-trivial C union is used in an invalid context.
4078 NonTrivialCUnionContext UseContext,
4079 unsigned NonTrivialKind);
4080
4081 /// Certain globally-unique variables might be accidentally duplicated if
4082 /// built into multiple shared libraries with hidden visibility. This can
4083 /// cause problems if the variable is mutable, its initialization is
4084 /// effectful, or its address is taken.
4087
4088 /// AddInitializerToDecl - Adds the initializer Init to the
4089 /// declaration dcl. If DirectInit is true, this is C++ direct
4090 /// initialization rather than copy initialization.
4091 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4092 void ActOnUninitializedDecl(Decl *dcl);
4093
4094 /// ActOnInitializerError - Given that there was an error parsing an
4095 /// initializer for the given declaration, try to at least re-establish
4096 /// invariants such as whether a variable's type is either dependent or
4097 /// complete.
4098 void ActOnInitializerError(Decl *Dcl);
4099
4100 void ActOnCXXForRangeDecl(Decl *D);
4102 IdentifierInfo *Ident,
4103 ParsedAttributes &Attrs);
4104
4105 /// Check if VD needs to be dllexport/dllimport due to being in a
4106 /// dllexport/import function.
4109
4110 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4111 /// any semantic actions necessary after any initializer has been attached.
4112 void FinalizeDeclaration(Decl *D);
4114 ArrayRef<Decl *> Group);
4115
4116 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4117 /// group, performing any necessary semantic checking.
4119
4120 /// Should be called on all declarations that might have attached
4121 /// documentation comments.
4122 void ActOnDocumentableDecl(Decl *D);
4124
4125 enum class FnBodyKind {
4126 /// C++26 [dcl.fct.def.general]p1
4127 /// function-body:
4128 /// ctor-initializer[opt] compound-statement
4129 /// function-try-block
4131 /// = default ;
4133 /// deleted-function-body
4134 ///
4135 /// deleted-function-body:
4136 /// = delete ;
4137 /// = delete ( unevaluated-string ) ;
4139 };
4140
4142 SourceLocation LocAfterDecls);
4144 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4145 SkipBodyInfo *SkipBody = nullptr);
4147 MultiTemplateParamsArg TemplateParamLists,
4148 SkipBodyInfo *SkipBody = nullptr,
4149 FnBodyKind BodyKind = FnBodyKind::Other);
4151 SkipBodyInfo *SkipBody = nullptr,
4152 FnBodyKind BodyKind = FnBodyKind::Other);
4154
4155 /// Determine whether we can delay parsing the body of a function or
4156 /// function template until it is used, assuming we don't care about emitting
4157 /// code for that function.
4158 ///
4159 /// This will be \c false if we may need the body of the function in the
4160 /// middle of parsing an expression (where it's impractical to switch to
4161 /// parsing a different function), for instance, if it's constexpr in C++11
4162 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4163 bool canDelayFunctionBody(const Declarator &D);
4164
4165 /// Determine whether we can skip parsing the body of a function
4166 /// definition, assuming we don't care about analyzing its body or emitting
4167 /// code for that function.
4168 ///
4169 /// This will be \c false only if we may need the body of the function in
4170 /// order to parse the rest of the program (for instance, if it is
4171 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4172 bool canSkipFunctionBody(Decl *D);
4173
4174 /// Given the set of return statements within a function body,
4175 /// compute the variables that are subject to the named return value
4176 /// optimization.
4177 ///
4178 /// Each of the variables that is subject to the named return value
4179 /// optimization will be marked as NRVO variables in the AST, and any
4180 /// return statement that has a marked NRVO variable as its NRVO candidate can
4181 /// use the named return value optimization.
4182 ///
4183 /// This function applies a very simplistic algorithm for NRVO: if every
4184 /// return statement in the scope of a variable has the same NRVO candidate,
4185 /// that candidate is an NRVO variable.
4187
4188 /// Performs semantic analysis at the end of a function body.
4189 ///
4190 /// \param RetainFunctionScopeInfo If \c true, the client is responsible for
4191 /// releasing the associated \p FunctionScopeInfo. This is useful when
4192 /// building e.g. LambdaExprs.
4194 bool IsInstantiation = false,
4195 bool RetainFunctionScopeInfo = false);
4198
4199 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4200 /// attribute for which parsing is delayed.
4202
4203 /// Diagnose any unused parameters in the given sequence of
4204 /// ParmVarDecl pointers.
4206
4207 /// Diagnose whether the size of parameters or return value of a
4208 /// function or obj-c method definition is pass-by-value and larger than a
4209 /// specified threshold.
4210 void
4212 QualType ReturnTy, NamedDecl *D);
4213
4215 SourceLocation RParenLoc);
4216
4219
4220 void ActOnPopScope(SourceLocation Loc, Scope *S);
4221
4222 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4223 /// no declarator (e.g. "struct foo;") is parsed.
4225 const ParsedAttributesView &DeclAttrs,
4226 RecordDecl *&AnonRecord);
4227
4228 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4229 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4230 /// parameters to cope with template friend declarations.
4232 const ParsedAttributesView &DeclAttrs,
4233 MultiTemplateParamsArg TemplateParams,
4234 bool IsExplicitInstantiation,
4235 RecordDecl *&AnonRecord,
4236 SourceLocation EllipsisLoc = {});
4237
4238 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4239 /// anonymous structure or union. Anonymous unions are a C++ feature
4240 /// (C++ [class.union]) and a C11 feature; anonymous structures
4241 /// are a C11 feature and GNU C++ extension.
4242 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4243 RecordDecl *Record,
4244 const PrintingPolicy &Policy);
4245
4246 /// Called once it is known whether
4247 /// a tag declaration is an anonymous union or struct.
4249
4250 /// Emit diagnostic warnings for placeholder members.
4251 /// We can only do that after the class is fully constructed,
4252 /// as anonymous union/structs can insert placeholders
4253 /// in their parent scope (which might be a Record).
4255
4256 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4257 /// Microsoft C anonymous structure.
4258 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4259 /// Example:
4260 ///
4261 /// struct A { int a; };
4262 /// struct B { struct A; int b; };
4263 ///
4264 /// void foo() {
4265 /// B var;
4266 /// var.a = 3;
4267 /// }
4268 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4269 RecordDecl *Record);
4270
4271 /// Given a non-tag type declaration, returns an enum useful for indicating
4272 /// what kind of non-tag type this is.
4273 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4274
4275 /// Determine whether a tag with a given kind is acceptable
4276 /// as a redeclaration of the given tag declaration.
4277 ///
4278 /// \returns true if the new tag kind is acceptable, false otherwise.
4280 bool isDefinition, SourceLocation NewTagLoc,
4281 const IdentifierInfo *Name);
4282
4283 /// This is invoked when we see 'struct foo' or 'struct {'. In the
4284 /// former case, Name will be non-null. In the later case, Name will be null.
4285 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4286 /// a reference/declaration/definition of a tag.
4287 ///
4288 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4289 /// trailing-type-specifier) other than one in an alias-declaration.
4290 ///
4291 /// \param SkipBody If non-null, will be set to indicate if the caller should
4292 /// skip the definition of this tag and treat it as if it were a declaration.
4293 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4294 SourceLocation KWLoc, CXXScopeSpec &SS,
4295 IdentifierInfo *Name, SourceLocation NameLoc,
4296 const ParsedAttributesView &Attr, AccessSpecifier AS,
4297 SourceLocation ModulePrivateLoc,
4298 MultiTemplateParamsArg TemplateParameterLists,
4299 bool &OwnedDecl, bool &IsDependent,
4300 SourceLocation ScopedEnumKWLoc,
4301 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4302 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4303 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4304
4305 /// ActOnField - Each field of a C struct/union is passed into this in order
4306 /// to create a FieldDecl object for it.
4307 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4308 Declarator &D, Expr *BitfieldWidth);
4309
4310 /// HandleField - Analyze a field of a C struct or a C++ data member.
4311 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4312 Declarator &D, Expr *BitfieldWidth,
4313 InClassInitStyle InitStyle, AccessSpecifier AS);
4314
4315 /// Build a new FieldDecl and check its well-formedness.
4316 ///
4317 /// This routine builds a new FieldDecl given the fields name, type,
4318 /// record, etc. \p PrevDecl should refer to any previous declaration
4319 /// with the same name and in the same scope as the field to be
4320 /// created.
4321 ///
4322 /// \returns a new FieldDecl.
4323 ///
4324 /// \todo The Declarator argument is a hack. It will be removed once
4325 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4326 TypeSourceInfo *TInfo, RecordDecl *Record,
4327 SourceLocation Loc, bool Mutable,
4328 Expr *BitfieldWidth, InClassInitStyle InitStyle,
4329 SourceLocation TSSL, AccessSpecifier AS,
4330 NamedDecl *PrevDecl, Declarator *D = nullptr);
4331
4333
4334 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4335 /// class and class extensions. For every class \@interface and class
4336 /// extension \@interface, if the last ivar is a bitfield of any type,
4337 /// then add an implicit `char :0` ivar to the end of that interface.
4338 void ActOnLastBitfield(SourceLocation DeclStart,
4339 SmallVectorImpl<Decl *> &AllIvarDecls);
4340
4341 // This is used for both record definitions and ObjC interface declarations.
4342 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4343 ArrayRef<Decl *> Fields, SourceLocation LBrac,
4344 SourceLocation RBrac, const ParsedAttributesView &AttrList);
4345
4346 /// ActOnTagStartDefinition - Invoked when we have entered the
4347 /// scope of a tag's definition (e.g., for an enumeration, class,
4348 /// struct, or union).
4349 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4350
4351 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4352 /// Differently from C++, actually parse the body and reject / error out
4353 /// in case of a structural mismatch.
4354 bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4355
4357
4358 /// Invoked when we enter a tag definition that we're skipping.
4360
4361 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4362 /// C++ record definition's base-specifiers clause and are starting its
4363 /// member declarations.
4365 SourceLocation FinalLoc,
4366 bool IsFinalSpelledSealed,
4367 bool IsAbstract,
4368 SourceLocation TriviallyRelocatable,
4369 SourceLocation Replaceable,
4370 SourceLocation LBraceLoc);
4371
4372 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4373 /// the definition of a tag (enumeration, class, struct, or union).
4375 SourceRange BraceRange);
4376
4379
4381
4382 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4383 /// error parsing the definition of a tag.
4385
4387 EnumConstantDecl *LastEnumConst,
4388 SourceLocation IdLoc, IdentifierInfo *Id,
4389 Expr *val);
4390
4391 /// Check that this is a valid underlying type for an enum declaration.
4393
4394 /// Check whether this is a valid redeclaration of a previous enumeration.
4395 /// \return true if the redeclaration was invalid.
4396 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4397 QualType EnumUnderlyingTy, bool IsFixed,
4398 const EnumDecl *Prev);
4399
4400 /// Determine whether the body of an anonymous enumeration should be skipped.
4401 /// \param II The name of the first enumerator.
4403 SourceLocation IILoc);
4404
4405 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4406 SourceLocation IdLoc, IdentifierInfo *Id,
4407 const ParsedAttributesView &Attrs,
4408 SourceLocation EqualLoc, Expr *Val,
4409 SkipBodyInfo *SkipBody = nullptr);
4410 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4411 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4412 const ParsedAttributesView &Attr);
4413
4414 /// Set the current declaration context until it gets popped.
4415 void PushDeclContext(Scope *S, DeclContext *DC);
4416 void PopDeclContext();
4417
4418 /// EnterDeclaratorContext - Used when we must lookup names in the context
4419 /// of a declarator's nested name specifier.
4422
4423 /// Enter a template parameter scope, after it's been associated with a
4424 /// particular DeclContext. Causes lookup within the scope to chain through
4425 /// enclosing contexts in the correct order.
4427
4428 /// Push the parameters of D, which must be a function, into scope.
4431
4432 /// Add this decl to the scope shadowed decl chains.
4433 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4434
4435 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4436 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4437 /// true if 'D' belongs to the given declaration context.
4438 ///
4439 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4440 /// enclosing namespace set of the context, rather than contained
4441 /// directly within it.
4442 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4443 bool AllowInlineNamespace = false) const;
4444
4445 /// Finds the scope corresponding to the given decl context, if it
4446 /// happens to be an enclosing scope. Otherwise return NULL.
4448
4449 /// Subroutines of ActOnDeclarator().
4451 TypeSourceInfo *TInfo);
4453
4454 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4456 NamedDecl *New, Decl *Old,
4458
4459 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4460 /// same name and scope as a previous declaration 'Old'. Figure out
4461 /// how to resolve this situation, merging decls or emitting
4462 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4464 LookupResult &OldDecls);
4465
4466 /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4467 /// definition visible.
4468 /// This method performs any necessary cleanup on the parser state to discard
4469 /// child nodes from newly parsed decl we are retiring.
4470 void CleanupMergedEnum(Scope *S, Decl *New);
4471
4472 /// MergeFunctionDecl - We just parsed a function 'New' from
4473 /// declarator D which has the same name and scope as a previous
4474 /// declaration 'Old'. Figure out how to resolve this situation,
4475 /// merging decls or emitting diagnostics as appropriate.
4476 ///
4477 /// In C++, New and Old must be declarations that are not
4478 /// overloaded. Use IsOverload to determine whether New and Old are
4479 /// overloaded, and to select the Old declaration that New should be
4480 /// merged with.
4481 ///
4482 /// Returns true if there was an error, false otherwise.
4484 bool MergeTypeWithOld, bool NewDeclIsDefn);
4485
4486 /// Completes the merge of two function declarations that are
4487 /// known to be compatible.
4488 ///
4489 /// This routine handles the merging of attributes and other
4490 /// properties of function declarations from the old declaration to
4491 /// the new declaration, once we know that New is in fact a
4492 /// redeclaration of Old.
4493 ///
4494 /// \returns false
4496 Scope *S, bool MergeTypeWithOld);
4498
4499 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4500 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4501 /// situation, merging decls or emitting diagnostics as appropriate.
4502 ///
4503 /// Tentative definition rules (C99 6.9.2p2) are checked by
4504 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4505 /// definitions here, since the initializer hasn't been attached.
4507
4508 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4509 /// scope as a previous declaration 'Old'. Figure out how to merge their
4510 /// types, emitting diagnostics as appropriate.
4511 ///
4512 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4513 /// back to here in AddInitializerToDecl. We can't check them before the
4514 /// initializer is attached.
4515 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4516
4517 /// We've just determined that \p Old and \p New both appear to be definitions
4518 /// of the same variable. Either diagnose or fix the problem.
4519 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4521
4522 /// Filters out lookup results that don't fall within the given scope
4523 /// as determined by isDeclInScope.
4525 bool ConsiderLinkage, bool AllowInlineNamespace);
4526
4527 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4528 /// have compatible owning modules.
4530
4531 /// [module.interface]p6:
4532 /// A redeclaration of an entity X is implicitly exported if X was introduced
4533 /// by an exported declaration; otherwise it shall not be exported.
4535
4536 /// A wrapper function for checking the semantic restrictions of
4537 /// a redeclaration within a module.
4539
4540 /// Check the redefinition in C++20 Modules.
4541 ///
4542 /// [basic.def.odr]p14:
4543 /// For any definable item D with definitions in multiple translation units,
4544 /// - if D is a non-inline non-templated function or variable, or
4545 /// - if the definitions in different translation units do not satisfy the
4546 /// following requirements,
4547 /// the program is ill-formed; a diagnostic is required only if the
4548 /// definable item is attached to a named module and a prior definition is
4549 /// reachable at the point where a later definition occurs.
4550 /// - Each such definition shall not be attached to a named module
4551 /// ([module.unit]).
4552 /// - Each such definition shall consist of the same sequence of tokens, ...
4553 /// ...
4554 ///
4555 /// Return true if the redefinition is not allowed. Return false otherwise.
4556 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4557
4559
4560 /// If it's a file scoped decl that must warn if not used, keep track
4561 /// of it.
4563
4564 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4566
4569 DiagReceiverTy DiagReceiver);
4570 void DiagnoseUnusedDecl(const NamedDecl *ND);
4571
4572 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4573 /// unless they are marked attr(unused).
4574 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4575
4576 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4577 /// variable.
4578 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4579
4580 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4581 /// from S, where a non-field would be declared. This routine copes
4582 /// with the difference between C and C++ scoping rules in structs and
4583 /// unions. For example, the following code is well-formed in C but
4584 /// ill-formed in C++:
4585 /// @code
4586 /// struct S6 {
4587 /// enum { BAR } e;
4588 /// };
4589 ///
4590 /// void test_S6() {
4591 /// struct S6 a;
4592 /// a.e = BAR;
4593 /// }
4594 /// @endcode
4595 /// For the declaration of BAR, this routine will return a different
4596 /// scope. The scope S will be the scope of the unnamed enumeration
4597 /// within S6. In C++, this routine will return the scope associated
4598 /// with S6, because the enumeration's scope is a transparent
4599 /// context but structures can contain non-field names. In C, this
4600 /// routine will return the translation unit scope, since the
4601 /// enumeration's scope is a transparent context and structures cannot
4602 /// contain non-field names.
4604
4606 SourceLocation Loc);
4607
4608 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4609 /// file scope. lazily create a decl for it. ForRedeclaration is true
4610 /// if we're creating this built-in in anticipation of redeclaring the
4611 /// built-in.
4612 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4613 bool ForRedeclaration, SourceLocation Loc);
4614
4615 /// Get the outermost AttributedType node that sets a calling convention.
4616 /// Valid types should not have multiple attributes with different CCs.
4617 const AttributedType *getCallingConvAttributedType(QualType T) const;
4618
4619 /// GetNameForDeclarator - Determine the full declaration name for the
4620 /// given Declarator.
4622
4623 /// Retrieves the declaration name from a parsed unqualified-id.
4625
4626 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4627 /// we are currently parsing the initializer.
4629
4630 /// Look for a locally scoped extern "C" declaration by the given name.
4632
4635
4636 /// Adjust the \c DeclContext for a function or variable that might be a
4637 /// function-local external declaration.
4639
4641
4642 /// Checks if the variant/multiversion functions are compatible.
4644 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4645 const PartialDiagnostic &NoProtoDiagID,
4646 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4647 const PartialDiagnosticAt &NoSupportDiagIDAt,
4648 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4649 bool ConstexprSupported, bool CLinkageMayDiffer);
4650
4651 /// type checking declaration initializers (C99 6.7.8)
4653 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4654
4657 SourceRange Range, bool DirectInit,
4658 Expr *Init);
4659
4661 Expr *Init);
4662
4664
4665 // Heuristically tells if the function is `get_return_object` member of a
4666 // coroutine promise_type by matching the function name.
4667 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4668 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4669
4670 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4671 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4673 Scope *S);
4674
4675 /// If this function is a C++ replaceable global allocation function
4676 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4677 /// adds any function attributes that we know a priori based on the standard.
4678 ///
4679 /// We need to check for duplicate attributes both here and where user-written
4680 /// attributes are applied to declarations.
4682 FunctionDecl *FD);
4683
4684 /// Adds any function attributes that we know a priori based on
4685 /// the declaration of this function.
4686 ///
4687 /// These attributes can apply both to implicitly-declared builtins
4688 /// (like __builtin___printf_chk) or to library-declared functions
4689 /// like NSLog or printf.
4690 ///
4691 /// We need to check for duplicate attributes both here and where user-written
4692 /// attributes are applied to declarations.
4694
4695 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4696 /// the correct width, and that the field type is valid.
4697 /// Returns false on success.
4699 const IdentifierInfo *FieldName, QualType FieldTy,
4700 bool IsMsStruct, Expr *BitWidth);
4701
4702 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4703 /// enum. If AllowMask is true, then we also allow the complement of a valid
4704 /// value, to be used as a mask.
4705 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4706 bool AllowMask) const;
4707
4708 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4709 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4710 SourceLocation WeakNameLoc);
4711
4712 /// ActOnPragmaRedefineExtname - Called on well formed
4713 /// \#pragma redefine_extname oldname newname.
4715 IdentifierInfo *AliasName,
4716 SourceLocation PragmaLoc,
4717 SourceLocation WeakNameLoc,
4718 SourceLocation AliasNameLoc);
4719
4720 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4721 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4722 SourceLocation PragmaLoc,
4723 SourceLocation WeakNameLoc,
4724 SourceLocation AliasNameLoc);
4725
4726 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4729 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4730 OMPDiscarded, // Discarded due to OpenMP hostness
4731 TemplateDiscarded, // Discarded due to uninstantiated templates
4733 };
4734 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4735 bool Final = false);
4736
4737 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4739
4740 /// Function or variable declarations to be checked for whether the deferred
4741 /// diagnostics should be emitted.
4743
4744private:
4745 /// Map of current shadowing declarations to shadowed declarations. Warn if
4746 /// it looks like the user is trying to modify the shadowing declaration.
4747 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4748
4749 // We need this to handle
4750 //
4751 // typedef struct {
4752 // void *foo() { return 0; }
4753 // } A;
4754 //
4755 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4756 // for example. If 'A', foo will have external linkage. If we have '*A',
4757 // foo will have no linkage. Since we can't know until we get to the end
4758 // of the typedef, this function finds out if D might have non-external
4759 // linkage. Callers should verify at the end of the TU if it D has external
4760 // linkage or not.
4761 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4762
4763 ///@}
4764
4765 //
4766 //
4767 // -------------------------------------------------------------------------
4768 //
4769 //
4770
4771 /// \name Declaration Attribute Handling
4772 /// Implementations are in SemaDeclAttr.cpp
4773 ///@{
4774
4775public:
4776 /// Describes the kind of priority given to an availability attribute.
4777 ///
4778 /// The sum of priorities deteremines the final priority of the attribute.
4779 /// The final priority determines how the attribute will be merged.
4780 /// An attribute with a lower priority will always remove higher priority
4781 /// attributes for the specified platform when it is being applied. An
4782 /// attribute with a higher priority will not be applied if the declaration
4783 /// already has an availability attribute with a lower priority for the
4784 /// specified platform. The final prirority values are not expected to match
4785 /// the values in this enumeration, but instead should be treated as a plain
4786 /// integer value. This enumeration just names the priority weights that are
4787 /// used to calculate that final vaue.
4789 /// The availability attribute was specified explicitly next to the
4790 /// declaration.
4792
4793 /// The availability attribute was applied using '#pragma clang attribute'.
4795
4796 /// The availability attribute for a specific platform was inferred from
4797 /// an availability attribute for another platform.
4799 };
4800
4801 /// Describes the reason a calling convention specification was ignored, used
4802 /// for diagnostics.
4809
4810 /// A helper function to provide Attribute Location for the Attr types
4811 /// AND the ParsedAttr.
4812 template <typename AttrInfo>
4813 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
4814 getAttrLoc(const AttrInfo &AL) {
4815 return AL.getLocation();
4816 }
4818
4819 /// If Expr is a valid integer constant, get the value of the integer
4820 /// expression and return success or failure. May output an error.
4821 ///
4822 /// Negative argument is implicitly converted to unsigned, unless
4823 /// \p StrictlyUnsigned is true.
4824 template <typename AttrInfo>
4825 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
4826 unsigned Idx = UINT_MAX,
4827 bool StrictlyUnsigned = false) {
4828 std::optional<llvm::APSInt> I = llvm::APSInt(32);
4829 if (Expr->isTypeDependent() ||
4831 if (Idx != UINT_MAX)
4832 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
4833 << &AI << Idx << AANT_ArgumentIntegerConstant
4834 << Expr->getSourceRange();
4835 else
4836 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
4838 return false;
4839 }
4840
4841 if (!I->isIntN(32)) {
4842 Diag(Expr->getExprLoc(), diag::err_ice_too_large)
4843 << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
4844 return false;
4845 }
4846
4847 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
4848 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
4849 << &AI << /*non-negative*/ 1;
4850 return false;
4851 }
4852
4853 Val = (uint32_t)I->getZExtValue();
4854 return true;
4855 }
4856
4857 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
4858 /// \#pragma weak during processing of other Decls.
4859 /// I couldn't figure out a clean way to generate these in-line, so
4860 /// we store them here and handle separately -- which is a hack.
4861 /// It would be best to refactor this.
4863
4864 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
4866
4870
4871 /// ExtVectorDecls - This is a list all the extended vector types. This allows
4872 /// us to associate a raw vector type with one of the ext_vector type names.
4873 /// This is only necessary for issuing pretty diagnostics.
4875
4876 /// Check if the argument \p E is a ASCII string literal. If not emit an error
4877 /// and return false, otherwise set \p Str to the value of the string literal
4878 /// and return true.
4880 const Expr *E, StringRef &Str,
4881 SourceLocation *ArgLocation = nullptr);
4882
4883 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
4884 /// If not emit an error and return false. If the argument is an identifier it
4885 /// will emit an error with a fixit hint and treat it as if it was a string
4886 /// literal.
4887 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4888 StringRef &Str,
4889 SourceLocation *ArgLocation = nullptr);
4890
4891 /// Determine if type T is a valid subject for a nonnull and similar
4892 /// attributes. Dependent types are considered valid so they can be checked
4893 /// during instantiation time. By default, we look through references (the
4894 /// behavior used by nonnull), but if the second parameter is true, then we
4895 /// treat a reference type as valid.
4896 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4897
4898 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
4899 /// declaration.
4900 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4901 Expr *OE);
4902
4903 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
4904 /// declaration.
4905 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
4906 Expr *ParamExpr);
4907
4908 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4909 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4910
4911 AvailabilityAttr *mergeAvailabilityAttr(
4912 NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
4913 bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
4914 VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
4915 bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
4916 int Priority, IdentifierInfo *IIEnvironment);
4917
4918 TypeVisibilityAttr *
4920 TypeVisibilityAttr::VisibilityType Vis);
4921 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
4922 VisibilityAttr::VisibilityType Vis);
4923 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
4924 StringRef Name);
4925
4926 /// Used to implement to perform semantic checking on
4927 /// attribute((section("foo"))) specifiers.
4928 ///
4929 /// In this case, "foo" is passed in to be checked. If the section
4930 /// specifier is invalid, return an Error that indicates the problem.
4931 ///
4932 /// This is a simple quality of implementation feature to catch errors
4933 /// and give good diagnostics in cases when the assembler or code generator
4934 /// would otherwise reject the section specifier.
4935 llvm::Error isValidSectionSpecifier(StringRef Str);
4936 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4937 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
4938 StringRef Name);
4939
4940 // Check for things we'd like to warn about. Multiversioning issues are
4941 // handled later in the process, once we know how many exist.
4942 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4943
4944 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
4945 StringRef NewUserDiagnostic);
4946 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
4947 IdentifierInfo *Format, int FormatIdx,
4948 int FirstArg);
4949 FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
4950 const AttributeCommonInfo &CI,
4951 IdentifierInfo *Format,
4952 int FormatIdx,
4953 StringLiteral *FormatStr);
4954
4955 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
4956 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4957 bool IsPackExpansion);
4959 bool IsPackExpansion);
4960
4961 /// AddAlignValueAttr - Adds an align_value attribute to a particular
4962 /// declaration.
4963 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
4964
4965 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
4966 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
4969
4971 bool BestCase,
4972 MSInheritanceModel SemanticSpelling);
4973
4975
4976 /// AddModeAttr - Adds a mode attribute to a particular declaration.
4977 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
4978 bool InInstantiation = false);
4979 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
4980 const AttributeCommonInfo &CI,
4981 const IdentifierInfo *Ident);
4982 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
4983 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
4984 const AttributeCommonInfo &CI);
4985 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
4986 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
4987 const InternalLinkageAttr &AL);
4988
4989 /// Check validaty of calling convention attribute \p attr. If \p FD
4990 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
4991 /// target. Otherwise, it is specified by \p CFT.
4993 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
4995
4996 /// Checks a regparm attribute, returning true if it is ill-formed and
4997 /// otherwise setting numParams to the appropriate value.
4998 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4999
5000 /// Create an CUDALaunchBoundsAttr attribute.
5001 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
5002 Expr *MaxThreads,
5003 Expr *MinBlocks,
5004 Expr *MaxBlocks);
5005
5006 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
5007 /// declaration.
5008 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5009 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
5010
5011 /// Add a cluster_dims attribute to a particular declaration.
5012 CUDAClusterDimsAttr *createClusterDimsAttr(const AttributeCommonInfo &CI,
5013 Expr *X, Expr *Y, Expr *Z);
5014 void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
5015 Expr *Y, Expr *Z);
5016 /// Add a no_cluster attribute to a particular declaration.
5017 void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI);
5018
5019 enum class RetainOwnershipKind { NS, CF, OS };
5020
5021 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5022 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5023
5024 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5025
5026 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5027 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5028 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5029 const AttributeCommonInfo &CI,
5030 bool BestCase,
5031 MSInheritanceModel Model);
5032
5033 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5034 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5035 const EnforceTCBLeafAttr &AL);
5036
5037 /// Helper for delayed processing TransparentUnion or
5038 /// BPFPreserveAccessIndexAttr attribute.
5040 const ParsedAttributesView &AttrList);
5041
5042 // Options for ProcessDeclAttributeList().
5046
5049 Result.IncludeCXX11Attributes = Val;
5050 return Result;
5051 }
5052
5055 Result.IgnoreTypeAttributes = Val;
5056 return Result;
5057 }
5058
5059 // Should C++11 attributes be processed?
5061
5062 // Should any type attributes encountered be ignored?
5063 // If this option is false, a diagnostic will be emitted for any type
5064 // attributes of a kind that does not "slide" from the declaration to
5065 // the decl-specifier-seq.
5067 };
5068
5069 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5070 /// attribute list to the specified decl, ignoring any type attributes.
5072 const ParsedAttributesView &AttrList,
5073 const ProcessDeclAttributeOptions &Options =
5075
5076 /// Annotation attributes are the only attributes allowed after an access
5077 /// specifier.
5079 const ParsedAttributesView &AttrList);
5080
5081 /// checkUnusedDeclAttributes - Given a declarator which is not being
5082 /// used to build a declaration, complain about any decl attributes
5083 /// which might be lying around on it.
5085
5086 void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5087
5088 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5089 /// \#pragma weak needs a non-definition decl and source may not have one.
5091 SourceLocation Loc);
5092
5093 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5094 /// applied to it, possibly with an alias.
5095 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5096
5097 void ProcessPragmaWeak(Scope *S, Decl *D);
5098 // Decl attributes - this routine is the top level dispatcher.
5099 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5100
5102
5103 /// Given a set of delayed diagnostics, re-emit them as if they had
5104 /// been delayed in the current context instead of in the given pool.
5105 /// Essentially, this just moves them to the current pool.
5107
5108 /// Check if IdxExpr is a valid parameter index for a function or
5109 /// instance method D. May output an error.
5110 ///
5111 /// \returns true if IdxExpr is a valid index.
5112 template <typename AttrInfo>
5114 const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5115 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5116 bool CanIndexVariadicArguments = false) {
5118
5119 // In C++ the implicit 'this' function parameter also counts.
5120 // Parameters are counted from one.
5121 bool HP = hasFunctionProto(D);
5122 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
5123 bool IV = HP && isFunctionOrMethodVariadic(D);
5124 unsigned NumParams =
5125 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
5126
5127 std::optional<llvm::APSInt> IdxInt;
5128 if (IdxExpr->isTypeDependent() ||
5129 !(IdxInt = IdxExpr->getIntegerConstantExpr(Context))) {
5130 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5131 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5132 << IdxExpr->getSourceRange();
5133 return false;
5134 }
5135
5136 unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX);
5137 if (IdxSource < 1 ||
5138 ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5139 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5140 << &AI << AttrArgNum << IdxExpr->getSourceRange();
5141 return false;
5142 }
5143 if (HasImplicitThisParam && !CanIndexImplicitThis) {
5144 if (IdxSource == 1) {
5145 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5146 << &AI << IdxExpr->getSourceRange();
5147 return false;
5148 }
5149 }
5150
5151 Idx = ParamIdx(IdxSource, D);
5152 return true;
5153 }
5154
5155 ///@}
5156
5157 //
5158 //
5159 // -------------------------------------------------------------------------
5160 //
5161 //
5162
5163 /// \name C++ Declarations
5164 /// Implementations are in SemaDeclCXX.cpp
5165 ///@{
5166
5167public:
5169
5170 /// Called before parsing a function declarator belonging to a function
5171 /// declaration.
5173 unsigned TemplateParameterDepth);
5174
5175 /// Called after parsing a function declarator belonging to a function
5176 /// declaration.
5178
5179 // Act on C++ namespaces
5181 SourceLocation NamespaceLoc,
5182 SourceLocation IdentLoc, IdentifierInfo *Ident,
5183 SourceLocation LBrace,
5184 const ParsedAttributesView &AttrList,
5185 UsingDirectiveDecl *&UsingDecl, bool IsNested);
5186
5187 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5188 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5189 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5190
5192
5193 /// Retrieve the special "std" namespace, which may require us to
5194 /// implicitly define the namespace.
5196
5198 EnumDecl *getStdAlignValT() const;
5199
5202 QualType AllocType, SourceLocation);
5203
5205 const IdentifierInfo *MemberOrBase);
5206
5208 /// The '<=>' operator was used in an expression and a builtin operator
5209 /// was selected.
5211 /// A defaulted 'operator<=>' needed the comparison category. This
5212 /// typically only applies to 'std::strong_ordering', due to the implicit
5213 /// fallback return value.
5215 };
5216
5217 /// Lookup the specified comparison category types in the standard
5218 /// library, an check the VarDecls possibly returned by the operator<=>
5219 /// builtins for that type.
5220 ///
5221 /// \return The type of the comparison category type corresponding to the
5222 /// specified Kind, or a null type if an error occurs
5224 SourceLocation Loc,
5226
5227 /// Tests whether Ty is an instance of std::initializer_list and, if
5228 /// it is and Element is not NULL, assigns the element type to Element.
5229 bool isStdInitializerList(QualType Ty, QualType *Element);
5230
5231 /// Tests whether Ty is an instance of std::type_identity and, if
5232 /// it is and TypeArgument is not NULL, assigns the element type to Element.
5233 /// If MalformedDecl is not null, and type_identity was ruled out due to being
5234 /// incorrectly structured despite having the correct name, the faulty Decl
5235 /// will be assigned to MalformedDecl.
5236 bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5237 const Decl **MalformedDecl = nullptr);
5238
5239 /// Looks for the std::initializer_list template and instantiates it
5240 /// with Element, or emits an error if it's not found.
5241 ///
5242 /// \returns The instantiated template, or null on error.
5244
5245 /// Looks for the std::type_identity template and instantiates it
5246 /// with Type, or returns a null type if type_identity has not been declared
5247 ///
5248 /// \returns The instantiated template, or null if std::type_identity is not
5249 /// declared
5251
5252 /// Determine whether Ctor is an initializer-list constructor, as
5253 /// defined in [dcl.init.list]p2.
5254 bool isInitListConstructor(const FunctionDecl *Ctor);
5255
5256 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5257 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5258 SourceLocation IdentLoc,
5259 IdentifierInfo *NamespcName,
5260 const ParsedAttributesView &AttrList);
5261
5263
5264 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5265 SourceLocation AliasLoc, IdentifierInfo *Alias,
5266 CXXScopeSpec &SS, SourceLocation IdentLoc,
5267 IdentifierInfo *Ident);
5268
5269 /// Remove decls we can't actually see from a lookup being used to declare
5270 /// shadow using decls.
5271 ///
5272 /// \param S - The scope of the potential shadow decl
5273 /// \param Previous - The lookup of a potential shadow decl's name.
5274 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5275
5276 /// Hides a using shadow declaration. This is required by the current
5277 /// using-decl implementation when a resolvable using declaration in a
5278 /// class is followed by a declaration which would hide or override
5279 /// one or more of the using decl's targets; for example:
5280 ///
5281 /// struct Base { void foo(int); };
5282 /// struct Derived : Base {
5283 /// using Base::foo;
5284 /// void foo(int);
5285 /// };
5286 ///
5287 /// The governing language is C++03 [namespace.udecl]p12:
5288 ///
5289 /// When a using-declaration brings names from a base class into a
5290 /// derived class scope, member functions in the derived class
5291 /// override and/or hide member functions with the same name and
5292 /// parameter types in a base class (rather than conflicting).
5293 ///
5294 /// There are two ways to implement this:
5295 /// (1) optimistically create shadow decls when they're not hidden
5296 /// by existing declarations, or
5297 /// (2) don't create any shadow decls (or at least don't make them
5298 /// visible) until we've fully parsed/instantiated the class.
5299 /// The problem with (1) is that we might have to retroactively remove
5300 /// a shadow decl, which requires several O(n) operations because the
5301 /// decl structures are (very reasonably) not designed for removal.
5302 /// (2) avoids this but is very fiddly and phase-dependent.
5303 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5304
5305 /// Determines whether to create a using shadow decl for a particular
5306 /// decl, given the set of decls existing prior to this using lookup.
5308 const LookupResult &PreviousDecls,
5309 UsingShadowDecl *&PrevShadow);
5310
5311 /// Builds a shadow declaration corresponding to a 'using' declaration.
5314 UsingShadowDecl *PrevDecl);
5315
5316 /// Checks that the given using declaration is not an invalid
5317 /// redeclaration. Note that this is checking only for the using decl
5318 /// itself, not for any ill-formedness among the UsingShadowDecls.
5320 bool HasTypenameKeyword,
5321 const CXXScopeSpec &SS,
5322 SourceLocation NameLoc,
5323 const LookupResult &Previous);
5324
5325 /// Checks that the given nested-name qualifier used in a using decl
5326 /// in the current context is appropriately related to the current
5327 /// scope. If an error is found, diagnoses it and returns true.
5328 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5329 /// the result of that lookup. UD is likewise nullptr, except when we have an
5330 /// already-populated UsingDecl whose shadow decls contain the same
5331 /// information (i.e. we're instantiating a UsingDecl with non-dependent
5332 /// scope).
5333 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5334 const CXXScopeSpec &SS,
5335 const DeclarationNameInfo &NameInfo,
5336 SourceLocation NameLoc,
5337 const LookupResult *R = nullptr,
5338 const UsingDecl *UD = nullptr);
5339
5340 /// Builds a using declaration.
5341 ///
5342 /// \param IsInstantiation - Whether this call arises from an
5343 /// instantiation of an unresolved using declaration. We treat
5344 /// the lookup differently for these declarations.
5346 SourceLocation UsingLoc,
5347 bool HasTypenameKeyword,
5348 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5349 DeclarationNameInfo NameInfo,
5350 SourceLocation EllipsisLoc,
5351 const ParsedAttributesView &AttrList,
5352 bool IsInstantiation, bool IsUsingIfExists);
5354 SourceLocation UsingLoc,
5355 SourceLocation EnumLoc,
5356 SourceLocation NameLoc,
5357 TypeSourceInfo *EnumType, EnumDecl *ED);
5358 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5359 ArrayRef<NamedDecl *> Expansions);
5360
5361 /// Additional checks for a using declaration referring to a constructor name.
5363
5364 /// Given a derived-class using shadow declaration for a constructor and the
5365 /// correspnding base class constructor, find or create the implicit
5366 /// synthesized derived class constructor to use for this initialization.
5369 ConstructorUsingShadowDecl *DerivedShadow);
5370
5372 SourceLocation UsingLoc,
5373 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5374 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5375 const ParsedAttributesView &AttrList);
5377 SourceLocation UsingLoc,
5378 SourceLocation EnumLoc, SourceRange TyLoc,
5379 const IdentifierInfo &II, ParsedType Ty,
5380 const CXXScopeSpec &SS);
5382 MultiTemplateParamsArg TemplateParams,
5383 SourceLocation UsingLoc, UnqualifiedId &Name,
5384 const ParsedAttributesView &AttrList,
5385 TypeResult Type, Decl *DeclFromDeclSpec);
5386
5387 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5388 /// including handling of its default argument expressions.
5389 ///
5390 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5392 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5394 bool HadMultipleCandidates, bool IsListInitialization,
5395 bool IsStdInitListInitialization, bool RequiresZeroInit,
5396 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5397
5398 /// Build a CXXConstructExpr whose constructor has already been resolved if
5399 /// it denotes an inherited constructor.
5401 SourceLocation ConstructLoc, QualType DeclInitType,
5402 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5403 bool HadMultipleCandidates, bool IsListInitialization,
5404 bool IsStdInitListInitialization, bool RequiresZeroInit,
5405 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5406
5407 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5408 // the constructor can be elidable?
5410 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5411 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5412 bool HadMultipleCandidates, bool IsListInitialization,
5413 bool IsStdInitListInitialization, bool RequiresZeroInit,
5414 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5415
5417 SourceLocation InitLoc);
5418
5419 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5420 /// constructed variable.
5421 void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit);
5422
5423 /// Helper class that collects exception specifications for
5424 /// implicitly-declared special member functions.
5426 // Pointer to allow copying
5427 Sema *Self;
5428 // We order exception specifications thus:
5429 // noexcept is the most restrictive, but is only used in C++11.
5430 // throw() comes next.
5431 // Then a throw(collected exceptions)
5432 // Finally no specification, which is expressed as noexcept(false).
5433 // throw(...) is used instead if any called function uses it.
5434 ExceptionSpecificationType ComputedEST;
5435 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5436 SmallVector<QualType, 4> Exceptions;
5437
5438 void ClearExceptions() {
5439 ExceptionsSeen.clear();
5440 Exceptions.clear();
5441 }
5442
5443 public:
5445 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5446 if (!Self.getLangOpts().CPlusPlus11)
5447 ComputedEST = EST_DynamicNone;
5448 }
5449
5450 /// Get the computed exception specification type.
5452 assert(!isComputedNoexcept(ComputedEST) &&
5453 "noexcept(expr) should not be a possible result");
5454 return ComputedEST;
5455 }
5456
5457 /// The number of exceptions in the exception specification.
5458 unsigned size() const { return Exceptions.size(); }
5459
5460 /// The set of exceptions in the exception specification.
5461 const QualType *data() const { return Exceptions.data(); }
5462
5463 /// Integrate another called method into the collected data.
5464 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5465
5466 /// Integrate an invoked expression into the collected data.
5467 void CalledExpr(Expr *E) { CalledStmt(E); }
5468
5469 /// Integrate an invoked statement into the collected data.
5470 void CalledStmt(Stmt *S);
5471
5472 /// Overwrite an EPI's exception specification with this
5473 /// computed exception specification.
5476 ESI.Type = getExceptionSpecType();
5477 if (ESI.Type == EST_Dynamic) {
5478 ESI.Exceptions = Exceptions;
5479 } else if (ESI.Type == EST_None) {
5480 /// C++11 [except.spec]p14:
5481 /// The exception-specification is noexcept(false) if the set of
5482 /// potential exceptions of the special member function contains "any"
5483 ESI.Type = EST_NoexceptFalse;
5484 ESI.NoexceptExpr =
5485 Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get();
5486 }
5487 return ESI;
5488 }
5489 };
5490
5491 /// Evaluate the implicit exception specification for a defaulted
5492 /// special member function.
5494
5495 /// Check the given exception-specification and update the
5496 /// exception specification information with the results.
5497 void checkExceptionSpecification(bool IsTopLevel,
5499 ArrayRef<ParsedType> DynamicExceptions,
5500 ArrayRef<SourceRange> DynamicExceptionRanges,
5501 Expr *NoexceptExpr,
5502 SmallVectorImpl<QualType> &Exceptions,
5504
5505 /// Add an exception-specification to the given member or friend function
5506 /// (or function template). The exception-specification was parsed
5507 /// after the function itself was declared.
5509 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5510 ArrayRef<ParsedType> DynamicExceptions,
5511 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5512
5513 class InheritedConstructorInfo;
5514
5515 /// Determine if a special member function should have a deleted
5516 /// definition when it is defaulted.
5518 InheritedConstructorInfo *ICI = nullptr,
5519 bool Diagnose = false);
5520
5521 /// Produce notes explaining why a defaulted function was defined as deleted.
5523
5524 /// Declare the implicit default constructor for the given class.
5525 ///
5526 /// \param ClassDecl The class declaration into which the implicit
5527 /// default constructor will be added.
5528 ///
5529 /// \returns The implicitly-declared default constructor.
5532
5533 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5534 /// defining this constructor as the default constructor.
5537
5538 /// Declare the implicit destructor for the given class.
5539 ///
5540 /// \param ClassDecl The class declaration into which the implicit
5541 /// destructor will be added.
5542 ///
5543 /// \returns The implicitly-declared destructor.
5545
5546 /// DefineImplicitDestructor - Checks for feasibility of
5547 /// defining this destructor as the default destructor.
5548 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5550
5551 /// Build an exception spec for destructors that don't have one.
5552 ///
5553 /// C++11 says that user-defined destructors with no exception spec get one
5554 /// that looks as if the destructor was implicitly declared.
5556
5557 /// Define the specified inheriting constructor.
5560
5561 /// Declare the implicit copy constructor for the given class.
5562 ///
5563 /// \param ClassDecl The class declaration into which the implicit
5564 /// copy constructor will be added.
5565 ///
5566 /// \returns The implicitly-declared copy constructor.
5568
5569 /// DefineImplicitCopyConstructor - Checks for feasibility of
5570 /// defining this constructor as the copy constructor.
5571 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5573
5574 /// Declare the implicit move constructor for the given class.
5575 ///
5576 /// \param ClassDecl The Class declaration into which the implicit
5577 /// move constructor will be added.
5578 ///
5579 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5580 /// declared.
5582
5583 /// DefineImplicitMoveConstructor - Checks for feasibility of
5584 /// defining this constructor as the move constructor.
5585 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5587
5588 /// Declare the implicit copy assignment operator for the given class.
5589 ///
5590 /// \param ClassDecl The class declaration into which the implicit
5591 /// copy assignment operator will be added.
5592 ///
5593 /// \returns The implicitly-declared copy assignment operator.
5595
5596 /// Defines an implicitly-declared copy assignment operator.
5597 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5598 CXXMethodDecl *MethodDecl);
5599
5600 /// Declare the implicit move assignment operator for the given class.
5601 ///
5602 /// \param ClassDecl The Class declaration into which the implicit
5603 /// move assignment operator will be added.
5604 ///
5605 /// \returns The implicitly-declared move assignment operator, or NULL if it
5606 /// wasn't declared.
5608
5609 /// Defines an implicitly-declared move assignment operator.
5610 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5611 CXXMethodDecl *MethodDecl);
5612
5613 /// Check a completed declaration of an implicit special member.
5615
5616 /// Determine whether the given function is an implicitly-deleted
5617 /// special member function.
5619
5620 /// Check whether 'this' shows up in the type of a static member
5621 /// function after the (naturally empty) cv-qualifier-seq would be.
5622 ///
5623 /// \returns true if an error occurred.
5625
5626 /// Whether this' shows up in the exception specification of a static
5627 /// member function.
5629
5630 /// Check whether 'this' shows up in the attributes of the given
5631 /// static member function.
5632 ///
5633 /// \returns true if an error occurred.
5635
5637 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5638
5640
5641 /// Given a constructor and the set of arguments provided for the
5642 /// constructor, convert the arguments and add any required default arguments
5643 /// to form a proper call to this constructor.
5644 ///
5645 /// \returns true if an error occurred, false otherwise.
5647 QualType DeclInitType, MultiExprArg ArgsPtr,
5648 SourceLocation Loc,
5649 SmallVectorImpl<Expr *> &ConvertedArgs,
5650 bool AllowExplicit = false,
5651 bool IsListInitialization = false);
5652
5653 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5654 /// initializer for the declaration 'Dcl'.
5655 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5656 /// static data member of class X, names should be looked up in the scope of
5657 /// class X.
5659
5660 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5661 /// initializer for the declaration 'Dcl'.
5662 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5663
5664 /// Define the "body" of the conversion from a lambda object to a
5665 /// function pointer.
5666 ///
5667 /// This routine doesn't actually define a sensible body; rather, it fills
5668 /// in the initialization expression needed to copy the lambda object into
5669 /// the block, and IR generation actually generates the real body of the
5670 /// block pointer conversion.
5671 void
5673 CXXConversionDecl *Conv);
5674
5675 /// Define the "body" of the conversion from a lambda object to a
5676 /// block pointer.
5677 ///
5678 /// This routine doesn't actually define a sensible body; rather, it fills
5679 /// in the initialization expression needed to copy the lambda object into
5680 /// the block, and IR generation actually generates the real body of the
5681 /// block pointer conversion.
5683 CXXConversionDecl *Conv);
5684
5685 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5686 /// linkage specification, including the language and (if present)
5687 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5688 /// language string literal. LBraceLoc, if valid, provides the location of
5689 /// the '{' brace. Otherwise, this linkage specification does not
5690 /// have any braces.
5692 Expr *LangStr, SourceLocation LBraceLoc);
5693
5694 /// ActOnFinishLinkageSpecification - Complete the definition of
5695 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5696 /// valid, it's the position of the closing '}' brace in a linkage
5697 /// specification that uses braces.
5699 SourceLocation RBraceLoc);
5700
5701 //===--------------------------------------------------------------------===//
5702 // C++ Classes
5703 //
5704
5705 /// Get the class that is directly named by the current context. This is the
5706 /// class for which an unqualified-id in this scope could name a constructor
5707 /// or destructor.
5708 ///
5709 /// If the scope specifier denotes a class, this will be that class.
5710 /// If the scope specifier is empty, this will be the class whose
5711 /// member-specification we are currently within. Otherwise, there
5712 /// is no such class.
5714
5715 /// isCurrentClassName - Determine whether the identifier II is the
5716 /// name of the class type currently being defined. In the case of
5717 /// nested classes, this will only return true if II is the name of
5718 /// the innermost class.
5719 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5720 const CXXScopeSpec *SS = nullptr);
5721
5722 /// Determine whether the identifier II is a typo for the name of
5723 /// the class type currently being defined. If so, update it to the identifier
5724 /// that should have been used.
5726
5727 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5729 SourceLocation ColonLoc,
5730 const ParsedAttributesView &Attrs);
5731
5732 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5733 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5734 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
5735 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
5736 /// present (but parsing it has been deferred).
5737 NamedDecl *
5739 MultiTemplateParamsArg TemplateParameterLists,
5740 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5741 InClassInitStyle InitStyle);
5742
5743 /// Enter a new C++ default initializer scope. After calling this, the
5744 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
5745 /// parsing or instantiating the initializer failed.
5747
5748 /// This is invoked after parsing an in-class initializer for a
5749 /// non-static C++ class member, and after instantiating an in-class
5750 /// initializer in a class template. Such actions are deferred until the class
5751 /// is complete.
5753 SourceLocation EqualLoc,
5755
5756 /// Handle a C++ member initializer using parentheses syntax.
5758 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
5759 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
5760 const DeclSpec &DS, SourceLocation IdLoc,
5761 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
5762 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
5763
5764 /// Handle a C++ member initializer using braced-init-list syntax.
5765 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
5766 CXXScopeSpec &SS,
5767 IdentifierInfo *MemberOrBase,
5768 ParsedType TemplateTypeTy,
5769 const DeclSpec &DS, SourceLocation IdLoc,
5770 Expr *InitList, SourceLocation EllipsisLoc);
5771
5772 /// Handle a C++ member initializer.
5773 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
5774 CXXScopeSpec &SS,
5775 IdentifierInfo *MemberOrBase,
5776 ParsedType TemplateTypeTy,
5777 const DeclSpec &DS, SourceLocation IdLoc,
5778 Expr *Init, SourceLocation EllipsisLoc);
5779
5781 SourceLocation IdLoc);
5782
5784 TypeSourceInfo *BaseTInfo, Expr *Init,
5785 CXXRecordDecl *ClassDecl,
5786 SourceLocation EllipsisLoc);
5787
5789 CXXRecordDecl *ClassDecl);
5790
5793
5795 ArrayRef<CXXCtorInitializer *> Initializers = {});
5796
5797 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5798 /// mark all the non-trivial destructors of its members and bases as
5799 /// referenced.
5800 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5801 CXXRecordDecl *Record);
5802
5803 /// Mark destructors of virtual bases of this class referenced. In the Itanium
5804 /// C++ ABI, this is done when emitting a destructor for any non-abstract
5805 /// class. In the Microsoft C++ ABI, this is done any time a class's
5806 /// destructor is referenced.
5808 SourceLocation Location, CXXRecordDecl *ClassDecl,
5809 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
5810 nullptr);
5811
5812 /// Do semantic checks to allow the complete destructor variant to be emitted
5813 /// when the destructor is defined in another translation unit. In the Itanium
5814 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
5815 /// can be emitted in separate TUs. To emit the complete variant, run a subset
5816 /// of the checks performed when emitting a regular destructor.
5817 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
5818 CXXDestructorDecl *Dtor);
5819
5820 /// The list of classes whose vtables have been used within
5821 /// this translation unit, and the source locations at which the
5822 /// first use occurred.
5823 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
5824
5825 /// The list of vtables that are required but have not yet been
5826 /// materialized.
5828
5829 /// The set of classes whose vtables have been used within
5830 /// this translation unit, and a bit that will be true if the vtable is
5831 /// required to be emitted (otherwise, it should be emitted only if needed
5832 /// by code generation).
5833 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5834
5835 /// Load any externally-stored vtable uses.
5837
5838 /// Note that the vtable for the given class was used at the
5839 /// given location.
5841 bool DefinitionRequired = false);
5842
5843 /// Mark the exception specifications of all virtual member functions
5844 /// in the given class as needed.
5846 const CXXRecordDecl *RD);
5847
5848 /// MarkVirtualMembersReferenced - Will mark all members of the given
5849 /// CXXRecordDecl referenced.
5851 bool ConstexprOnly = false);
5852
5853 /// Define all of the vtables that have been used in this
5854 /// translation unit and reference any virtual members used by those
5855 /// vtables.
5856 ///
5857 /// \returns true if any work was done, false otherwise.
5858 bool DefineUsedVTables();
5859
5860 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5861 /// special functions, such as the default constructor, copy
5862 /// constructor, or destructor, to the given C++ class (C++
5863 /// [special]p1). This routine can only be executed just before the
5864 /// definition of the class is complete.
5866
5867 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5868 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
5870 bool AnyErrors);
5871
5872 /// Check class-level dllimport/dllexport attribute. The caller must
5873 /// ensure that referenceDLLExportedClassMethods is called some point later
5874 /// when all outer classes of Class are complete.
5877
5879
5880 /// Perform propagation of DLL attributes from a derived class to a
5881 /// templated base class for MS compatibility.
5883 CXXRecordDecl *Class, Attr *ClassAttr,
5884 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5885 SourceLocation BaseLoc);
5886
5887 /// Perform semantic checks on a class definition that has been
5888 /// completing, introducing implicitly-declared members, checking for
5889 /// abstract types, etc.
5890 ///
5891 /// \param S The scope in which the class was parsed. Null if we didn't just
5892 /// parse a class definition.
5893 /// \param Record The completed class.
5895
5896 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
5897 /// conditions that are needed for the attribute to have an effect.
5899
5900 /// Check that VTable Pointer authentication is only being set on the first
5901 /// first instantiation of the vtable
5903
5905 Decl *TagDecl, SourceLocation LBrac,
5906 SourceLocation RBrac,
5907 const ParsedAttributesView &AttrList);
5908
5909 /// Perform any semantic analysis which needs to be delayed until all
5910 /// pending class member declarations have been parsed.
5913
5914 /// This is used to implement the constant expression evaluation part of the
5915 /// attribute enable_if extension. There is nothing in standard C++ which
5916 /// would require reentering parameters.
5919 llvm::function_ref<Scope *()> EnterScope);
5921
5922 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
5923 /// parsing a top-level (non-nested) C++ class, and we are now
5924 /// parsing those parts of the given Method declaration that could
5925 /// not be parsed earlier (C++ [class.mem]p2), such as default
5926 /// arguments. This action should enter the scope of the given
5927 /// Method declaration as if we had just parsed the qualified method
5928 /// name. However, it should not bring the parameters into scope;
5929 /// that will be performed by ActOnDelayedCXXMethodParameter.
5931 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5933
5934 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5935 /// processing the delayed method declaration for Method. The method
5936 /// declaration is now considered finished. There may be a separate
5937 /// ActOnStartOfFunctionDef action later (not necessarily
5938 /// immediately!) for this method, if it was also defined inside the
5939 /// class body.
5942
5944
5945 bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
5946 StringEvaluationContext EvalContext,
5947 bool ErrorOnInvalidMessage);
5948 bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
5949 StringEvaluationContext EvalContext,
5950 bool ErrorOnInvalidMessage);
5951
5953 Expr *AssertExpr, Expr *AssertMessageExpr,
5954 SourceLocation RParenLoc);
5956 Expr *AssertExpr, Expr *AssertMessageExpr,
5957 SourceLocation RParenLoc, bool Failed);
5958
5959 /// Try to print more useful information about a failed static_assert
5960 /// with expression \E
5961 void DiagnoseStaticAssertDetails(const Expr *E);
5962
5963 /// If E represents a built-in type trait, or a known standard type trait,
5964 /// try to print more information about why the type type-trait failed.
5965 /// This assumes we already evaluated the expression to a false boolean value.
5966 void DiagnoseTypeTraitDetails(const Expr *E);
5967
5968 /// Handle a friend type declaration. This works in tandem with
5969 /// ActOnTag.
5970 ///
5971 /// Notes on friend class templates:
5972 ///
5973 /// We generally treat friend class declarations as if they were
5974 /// declaring a class. So, for example, the elaborated type specifier
5975 /// in a friend declaration is required to obey the restrictions of a
5976 /// class-head (i.e. no typedefs in the scope chain), template
5977 /// parameters are required to match up with simple template-ids, &c.
5978 /// However, unlike when declaring a template specialization, it's
5979 /// okay to refer to a template specialization without an empty
5980 /// template parameter declaration, e.g.
5981 /// friend class A<T>::B<unsigned>;
5982 /// We permit this as a special case; if there are any template
5983 /// parameters present at all, require proper matching, i.e.
5984 /// template <> template <class T> friend class A<int>::B;
5985 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5986 MultiTemplateParamsArg TemplateParams,
5987 SourceLocation EllipsisLoc);
5989 MultiTemplateParamsArg TemplateParams);
5990
5991 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5992 /// the well-formedness of the constructor declarator @p D with type @p
5993 /// R. If there are any errors in the declarator, this routine will
5994 /// emit diagnostics and set the invalid bit to true. In any case, the type
5995 /// will be updated to reflect a well-formed type for the constructor and
5996 /// returned.
5998 StorageClass &SC);
5999
6000 /// CheckConstructor - Checks a fully-formed constructor for
6001 /// well-formedness, issuing any diagnostics required. Returns true if
6002 /// the constructor declarator is invalid.
6004
6005 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6006 /// the well-formednes of the destructor declarator @p D with type @p
6007 /// R. If there are any errors in the declarator, this routine will
6008 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6009 /// will be updated to reflect a well-formed type for the destructor and
6010 /// returned.
6012 StorageClass &SC);
6013
6014 /// CheckDestructor - Checks a fully-formed destructor definition for
6015 /// well-formedness, issuing any diagnostics required. Returns true
6016 /// on error.
6018
6019 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6020 /// well-formednes of the conversion function declarator @p D with
6021 /// type @p R. If there are any errors in the declarator, this routine
6022 /// will emit diagnostics and return true. Otherwise, it will return
6023 /// false. Either way, the type @p R will be updated to reflect a
6024 /// well-formed type for the conversion operator.
6026
6027 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6028 /// the declaration of the given C++ conversion function. This routine
6029 /// is responsible for recording the conversion function in the C++
6030 /// class, if possible.
6032
6033 /// Check the validity of a declarator that we parsed for a deduction-guide.
6034 /// These aren't actually declarators in the grammar, so we need to check that
6035 /// the user didn't specify any pieces that are not part of the
6036 /// deduction-guide grammar. Return true on invalid deduction-guide.
6038 StorageClass &SC);
6039
6041
6044 SourceLocation DefaultLoc);
6046
6047 /// Kinds of defaulted comparison operator functions.
6048 enum class DefaultedComparisonKind : unsigned char {
6049 /// This is not a defaultable comparison operator.
6051 /// This is an operator== that should be implemented as a series of
6052 /// subobject comparisons.
6054 /// This is an operator<=> that should be implemented as a series of
6055 /// subobject comparisons.
6057 /// This is an operator!= that should be implemented as a rewrite in terms
6058 /// of a == comparison.
6060 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
6061 /// terms of a <=> comparison.
6063 };
6064
6068 FunctionDecl *Spaceship);
6071
6073 QualType R, bool IsLambda,
6074 DeclContext *DC = nullptr);
6076 DeclarationName Name, QualType R);
6078
6079 //===--------------------------------------------------------------------===//
6080 // C++ Derived Classes
6081 //
6082
6083 /// Check the validity of a C++ base class specifier.
6084 ///
6085 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6086 /// and returns NULL otherwise.
6088 SourceRange SpecifierRange, bool Virtual,
6089 AccessSpecifier Access,
6090 TypeSourceInfo *TInfo,
6091 SourceLocation EllipsisLoc);
6092
6093 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6094 /// one entry in the base class list of a class specifier, for
6095 /// example:
6096 /// class foo : public bar, virtual private baz {
6097 /// 'public bar' and 'virtual private baz' are each base-specifiers.
6098 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6099 const ParsedAttributesView &Attrs, bool Virtual,
6100 AccessSpecifier Access, ParsedType basetype,
6101 SourceLocation BaseLoc,
6102 SourceLocation EllipsisLoc);
6103
6104 /// Performs the actual work of attaching the given base class
6105 /// specifiers to a C++ class.
6108
6109 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6110 /// class, after checking whether there are any duplicate base
6111 /// classes.
6112 void ActOnBaseSpecifiers(Decl *ClassDecl,
6114
6115 /// Determine whether the type \p Derived is a C++ class that is
6116 /// derived from the type \p Base.
6117 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6119 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6123 CXXBasePaths &Paths);
6124
6125 // FIXME: I don't like this name.
6126 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6127
6129 SourceLocation Loc, SourceRange Range,
6130 CXXCastPath *BasePath = nullptr,
6131 bool IgnoreAccess = false);
6132
6133 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6134 /// conversion (where Derived and Base are class types) is
6135 /// well-formed, meaning that the conversion is unambiguous (and
6136 /// that all of the base classes are accessible). Returns true
6137 /// and emits a diagnostic if the code is ill-formed, returns false
6138 /// otherwise. Loc is the location where this routine should point to
6139 /// if there is an error, and Range is the source range to highlight
6140 /// if there is an error.
6141 ///
6142 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6143 /// diagnostic for the respective type of error will be suppressed, but the
6144 /// check for ill-formed code will still be performed.
6146 unsigned InaccessibleBaseID,
6147 unsigned AmbiguousBaseConvID,
6148 SourceLocation Loc, SourceRange Range,
6149 DeclarationName Name, CXXCastPath *BasePath,
6150 bool IgnoreAccess = false);
6151
6152 /// Builds a string representing ambiguous paths from a
6153 /// specific derived class to different subobjects of the same base
6154 /// class.
6155 ///
6156 /// This function builds a string that can be used in error messages
6157 /// to show the different paths that one can take through the
6158 /// inheritance hierarchy to go from the derived class to different
6159 /// subobjects of a base class. The result looks something like this:
6160 /// @code
6161 /// struct D -> struct B -> struct A
6162 /// struct D -> struct C -> struct A
6163 /// @endcode
6164 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6165
6167 const CXXMethodDecl *Old);
6168
6169 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6170 /// covariant, according to C++ [class.virtual]p5.
6172 const CXXMethodDecl *Old);
6173
6174 // Check that the overriding method has no explicit object parameter.
6176 const CXXMethodDecl *Old);
6177
6178 /// Mark the given method pure.
6179 ///
6180 /// \param Method the method to be marked pure.
6181 ///
6182 /// \param InitRange the source range that covers the "0" initializer.
6184
6185 /// CheckOverrideControl - Check C++11 override control semantics.
6187
6188 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6189 /// not used in the declaration of an overriding method.
6191
6192 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6193 /// function overrides a virtual member function marked 'final', according to
6194 /// C++11 [class.virtual]p4.
6196 const CXXMethodDecl *Old);
6197
6208
6209 struct TypeDiagnoser;
6210
6213 TypeDiagnoser &Diagnoser);
6214 template <typename... Ts>
6216 const Ts &...Args) {
6217 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6218 return RequireNonAbstractType(Loc, T, Diagnoser);
6219 }
6220
6221 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6222
6223 //===--------------------------------------------------------------------===//
6224 // C++ Overloaded Operators [C++ 13.5]
6225 //
6226
6227 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6228 /// of this overloaded operator is well-formed. If so, returns false;
6229 /// otherwise, emits appropriate diagnostics and returns true.
6231
6232 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6233 /// of this literal operator function is well-formed. If so, returns
6234 /// false; otherwise, emits appropriate diagnostics and returns true.
6236
6237 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6238 /// found in an explicit(bool) specifier.
6240
6241 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6242 /// Returns true if the explicit specifier is now resolved.
6244
6245 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6246 /// C++ if/switch/while/for statement.
6247 /// e.g: "if (int x = f()) {...}"
6249
6250 // Emitting members of dllexported classes is delayed until the class
6251 // (including field initializers) is fully parsed.
6254
6255 /// Merge the exception specifications of two variable declarations.
6256 ///
6257 /// This is called when there's a redeclaration of a VarDecl. The function
6258 /// checks if the redeclaration might have an exception specification and
6259 /// validates compatibility and merges the specs if necessary.
6261
6262 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6263 /// function, once we already know that they have the same
6264 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6265 /// error, false otherwise.
6267
6268 /// Helpers for dealing with blocks and functions.
6270
6271 /// CheckExtraCXXDefaultArguments - Check for any extra default
6272 /// arguments in the declarator, which is not a function declaration
6273 /// or definition and therefore is not permitted to have default
6274 /// arguments. This routine should be invoked for every declarator
6275 /// that is not a function declaration or definition.
6277
6281
6282 /// Perform semantic analysis for the variable declaration that
6283 /// occurs within a C++ catch clause, returning the newly-created
6284 /// variable.
6286 SourceLocation StartLoc,
6287 SourceLocation IdLoc,
6288 const IdentifierInfo *Id);
6289
6290 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6291 /// handler.
6293
6295
6296 /// Handle a friend tag declaration where the scope specifier was
6297 /// templated.
6299 unsigned TagSpec, SourceLocation TagLoc,
6300 CXXScopeSpec &SS, IdentifierInfo *Name,
6301 SourceLocation NameLoc,
6302 SourceLocation EllipsisLoc,
6304 MultiTemplateParamsArg TempParamLists);
6305
6307 SourceLocation DeclStart, Declarator &D,
6308 Expr *BitfieldWidth,
6309 InClassInitStyle InitStyle,
6310 AccessSpecifier AS,
6311 const ParsedAttr &MSPropertyAttr);
6312
6313 /// Diagnose why the specified class does not have a trivial special member of
6314 /// the given kind.
6317
6318 /// Determine whether a defaulted or deleted special member function is
6319 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6320 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6324 bool Diagnose = false);
6325
6326 /// For a defaulted function, the kind of defaulted function that it is.
6328 LLVM_PREFERRED_TYPE(CXXSpecialMemberKind)
6329 unsigned SpecialMember : 8;
6330 unsigned Comparison : 8;
6331
6332 public:
6334 : SpecialMember(llvm::to_underlying(CXXSpecialMemberKind::Invalid)),
6335 Comparison(llvm::to_underlying(DefaultedComparisonKind::None)) {}
6337 : SpecialMember(llvm::to_underlying(CSM)),
6338 Comparison(llvm::to_underlying(DefaultedComparisonKind::None)) {}
6340 : SpecialMember(llvm::to_underlying(CXXSpecialMemberKind::Invalid)),
6341 Comparison(llvm::to_underlying(Comp)) {}
6342
6343 bool isSpecialMember() const {
6344 return static_cast<CXXSpecialMemberKind>(SpecialMember) !=
6346 }
6347 bool isComparison() const {
6348 return static_cast<DefaultedComparisonKind>(Comparison) !=
6350 }
6351
6352 explicit operator bool() const {
6353 return isSpecialMember() || isComparison();
6354 }
6355
6357 return static_cast<CXXSpecialMemberKind>(SpecialMember);
6358 }
6360 return static_cast<DefaultedComparisonKind>(Comparison);
6361 }
6362
6363 /// Get the index of this function kind for use in diagnostics.
6364 unsigned getDiagnosticIndex() const {
6365 static_assert(llvm::to_underlying(CXXSpecialMemberKind::Invalid) >
6366 llvm::to_underlying(CXXSpecialMemberKind::Destructor),
6367 "invalid should have highest index");
6368 static_assert((unsigned)DefaultedComparisonKind::None == 0,
6369 "none should be equal to zero");
6370 return SpecialMember + Comparison;
6371 }
6372 };
6373
6374 /// Determine the kind of defaulting that would be done for a given function.
6375 ///
6376 /// If the function is both a default constructor and a copy / move
6377 /// constructor (due to having a default argument for the first parameter),
6378 /// this picks CXXSpecialMemberKind::DefaultConstructor.
6379 ///
6380 /// FIXME: Check that case is properly handled by all callers.
6381 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
6382
6383 /// Handle a C++11 empty-declaration and attribute-declaration.
6385 SourceLocation SemiLoc);
6386
6388 /// Diagnose issues that are non-constant or that are extensions.
6390 /// Identify whether this function satisfies the formal rules for constexpr
6391 /// functions in the current lanugage mode (with no extensions).
6393 };
6394
6395 // Check whether a function declaration satisfies the requirements of a
6396 // constexpr function definition or a constexpr constructor definition. If so,
6397 // return true. If not, produce appropriate diagnostics (unless asked not to
6398 // by Kind) and return false.
6399 //
6400 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6402 CheckConstexprKind Kind);
6403
6404 /// Diagnose methods which overload virtual methods in a base class
6405 /// without overriding any.
6407
6408 /// Check if a method overloads virtual methods in a base class without
6409 /// overriding any.
6410 void
6412 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6413 void
6415 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6416
6417 /// ActOnParamDefaultArgument - Check whether the default argument
6418 /// provided for a function parameter is well-formed. If so, attach it
6419 /// to the parameter declaration.
6420 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6421 Expr *defarg);
6422
6423 /// ActOnParamUnparsedDefaultArgument - We've seen a default
6424 /// argument for a function parameter, but we can't parse it yet
6425 /// because we're inside a class definition. Note that this default
6426 /// argument will be parsed later.
6428 SourceLocation ArgLoc);
6429
6430 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6431 /// the default argument for the parameter param failed.
6433 Expr *DefaultArg);
6435 SourceLocation EqualLoc);
6436 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6437 SourceLocation EqualLoc);
6438
6439 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6440 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6441 StringLiteral *Message = nullptr);
6442 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
6443
6444 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6445 StringLiteral *DeletedMessage = nullptr);
6449
6450 NamedDecl *
6452 MultiTemplateParamsArg TemplateParamLists);
6455 RecordDecl *ClassDecl,
6456 const IdentifierInfo *Name);
6457
6459 SourceLocation Loc);
6461
6462 /// Stack containing information needed when in C++2a an 'auto' is encountered
6463 /// in a function declaration parameter type specifier in order to invent a
6464 /// corresponding template parameter in the enclosing abbreviated function
6465 /// template. This information is also present in LambdaScopeInfo, stored in
6466 /// the FunctionScopes stack.
6468
6469 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6470 std::unique_ptr<CXXFieldCollector> FieldCollector;
6471
6473 /// Set containing all declared private fields that are not used.
6475
6477
6478 /// PureVirtualClassDiagSet - a set of class declarations which we have
6479 /// emitted a list of pure virtual functions. Used to prevent emitting the
6480 /// same list more than once.
6481 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6482
6486
6487 /// All the delegating constructors seen so far in the file, used for
6488 /// cycle detection at the end of the TU.
6490
6491 /// The C++ "std" namespace, where the standard library resides.
6493
6494 /// The C++ "std::initializer_list" template, which is defined in
6495 /// <initializer_list>.
6497
6498 /// The C++ "std::type_identity" template, which is defined in
6499 /// <type_traits>.
6501
6502 // Contains the locations of the beginning of unparsed default
6503 // argument locations.
6504 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6505
6506 /// UndefinedInternals - all the used, undefined objects which require a
6507 /// definition in this translation unit.
6508 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6509
6510 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6512
6513 /// The C++ special members which we are currently in the process of
6514 /// declaring. If this process recursively triggers the declaration of the
6515 /// same special member, we should act as if it is not yet declared.
6517
6519
6520 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6521
6524 ParsingClassDepth++;
6526 }
6528 ParsingClassDepth--;
6530 }
6531
6533 CXXScopeSpec &SS,
6534 ParsedType TemplateTypeTy,
6535 IdentifierInfo *MemberOrBase);
6536
6537private:
6538 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6539 QualType ResultTy,
6540 ArrayRef<QualType> Args);
6541 // Helper for ActOnFields to check for all function pointer members.
6542 bool EntirelyFunctionPointers(const RecordDecl *Record);
6543
6544 // A cache representing if we've fully checked the various comparison category
6545 // types stored in ASTContext. The bit-index corresponds to the integer value
6546 // of a ComparisonCategoryType enumerator.
6547 llvm::SmallBitVector FullyCheckedComparisonCategories;
6548
6549 /// Check if there is a field shadowing.
6550 void CheckShadowInheritedFields(const SourceLocation &Loc,
6551 DeclarationName FieldName,
6552 const CXXRecordDecl *RD,
6553 bool DeclIsField = true);
6554
6555 ///@}
6556
6557 //
6558 //
6559 // -------------------------------------------------------------------------
6560 //
6561 //
6562
6563 /// \name C++ Exception Specifications
6564 /// Implementations are in SemaExceptionSpec.cpp
6565 ///@{
6566
6567public:
6568 /// All the overriding functions seen during a class definition
6569 /// that had their exception spec checks delayed, plus the overridden
6570 /// function.
6573
6574 /// All the function redeclarations seen during a class definition that had
6575 /// their exception spec checks delayed, plus the prior declaration they
6576 /// should be checked against. Except during error recovery, the new decl
6577 /// should always be a friend declaration, as that's the only valid way to
6578 /// redeclare a special member before its class is complete.
6581
6582 /// Determine if we're in a case where we need to (incorrectly) eagerly
6583 /// parse an exception specification to work around a libstdc++ bug.
6585
6586 /// Check the given noexcept-specifier, convert its expression, and compute
6587 /// the appropriate ExceptionSpecificationType.
6588 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6590
6591 CanThrowResult canThrow(const Stmt *E);
6592 /// Determine whether the callee of a particular function call can throw.
6593 /// E, D and Loc are all optional.
6594 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6597 const FunctionProtoType *FPT);
6600
6601 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6602 /// exception specification. Incomplete types, or pointers to incomplete types
6603 /// other than void are not allowed.
6604 ///
6605 /// \param[in,out] T The exception type. This will be decayed to a pointer
6606 /// type
6607 /// when the input is an array or a function type.
6609
6610 /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6611 /// pointer to member to a function with an exception specification. This
6612 /// means that it is invalid to add another level of indirection.
6615
6616 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6617 /// exception specifications. Exception specifications are equivalent if
6618 /// they allow exactly the same set of exception types. It does not matter how
6619 /// that is achieved. See C++ [except.spec]p2.
6621 SourceLocation OldLoc,
6622 const FunctionProtoType *New,
6623 SourceLocation NewLoc);
6625 const PartialDiagnostic &NoteID,
6626 const FunctionProtoType *Old,
6627 SourceLocation OldLoc,
6628 const FunctionProtoType *New,
6629 SourceLocation NewLoc);
6630 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6631
6632 /// CheckExceptionSpecSubset - Check whether the second function type's
6633 /// exception specification is a subset (or equivalent) of the first function
6634 /// type. This is used by override and pointer assignment checks.
6636 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6637 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6638 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6639 SourceLocation SuperLoc, const FunctionProtoType *Subset,
6640 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6641
6642 /// CheckParamExceptionSpec - Check if the parameter and return types of the
6643 /// two functions have equivalent exception specs. This is part of the
6644 /// assignment and override compatibility check. We do not check the
6645 /// parameters of parameter function pointers recursively, as no sane
6646 /// programmer would even be able to write such a function type.
6648 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6649 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6650 SourceLocation TargetLoc, const FunctionProtoType *Source,
6651 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6652
6653 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6654
6655 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6656 /// spec is a subset of base spec.
6658 const CXXMethodDecl *Old);
6659
6660 ///@}
6661
6662 //
6663 //
6664 // -------------------------------------------------------------------------
6665 //
6666 //
6667
6668 /// \name Expressions
6669 /// Implementations are in SemaExpr.cpp
6670 ///@{
6671
6672public:
6673 /// Describes how the expressions currently being parsed are
6674 /// evaluated at run-time, if at all.
6676 /// The current expression and its subexpressions occur within an
6677 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6678 /// \c sizeof, where the type of the expression may be significant but
6679 /// no code will be generated to evaluate the value of the expression at
6680 /// run time.
6682
6683 /// The current expression occurs within a braced-init-list within
6684 /// an unevaluated operand. This is mostly like a regular unevaluated
6685 /// context, except that we still instantiate constexpr functions that are
6686 /// referenced here so that we can perform narrowing checks correctly.
6688
6689 /// The current expression occurs within a discarded statement.
6690 /// This behaves largely similarly to an unevaluated operand in preventing
6691 /// definitions from being required, but not in other ways.
6693
6694 /// The current expression occurs within an unevaluated
6695 /// operand that unconditionally permits abstract references to
6696 /// fields, such as a SIZE operator in MS-style inline assembly.
6698
6699 /// The current context is "potentially evaluated" in C++11 terms,
6700 /// but the expression is evaluated at compile-time (like the values of
6701 /// cases in a switch statement).
6703
6704 /// In addition of being constant evaluated, the current expression
6705 /// occurs in an immediate function context - either a consteval function
6706 /// or a consteval if statement.
6708
6709 /// The current expression is potentially evaluated at run time,
6710 /// which means that code may be generated to evaluate the value of the
6711 /// expression at run time.
6713
6714 /// The current expression is potentially evaluated, but any
6715 /// declarations referenced inside that expression are only used if
6716 /// in fact the current expression is used.
6717 ///
6718 /// This value is used when parsing default function arguments, for which
6719 /// we would like to provide diagnostics (e.g., passing non-POD arguments
6720 /// through varargs) but do not want to mark declarations as "referenced"
6721 /// until the default argument is used.
6723 };
6724
6725 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6726 /// to a variable (constant) that may or may not be odr-used in this Expr, and
6727 /// we won't know until all lvalue-to-rvalue and discarded value conversions
6728 /// have been applied to all subexpressions of the enclosing full expression.
6729 /// This is cleared at the end of each full expression.
6732
6733 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6734
6735 /// Data structure used to record current or nested
6736 /// expression evaluation contexts.
6738 /// The expression evaluation context.
6740
6741 /// Whether the enclosing context needed a cleanup.
6743
6744 /// The number of active cleanup objects when we entered
6745 /// this expression evaluation context.
6747
6749
6750 /// The lambdas that are present within this context, if it
6751 /// is indeed an unevaluated context.
6753
6754 /// The declaration that provides context for lambda expressions
6755 /// and block literals if the normal declaration context does not
6756 /// suffice, e.g., in a default function argument.
6758
6759 /// If we are processing a decltype type, a set of call expressions
6760 /// for which we have deferred checking the completeness of the return type.
6762
6763 /// If we are processing a decltype type, a set of temporary binding
6764 /// expressions for which we have deferred checking the destructor.
6766
6768
6769 /// Expressions appearing as the LHS of a volatile assignment in this
6770 /// context. We produce a warning for these when popping the context if
6771 /// they are not discarded-value expressions nor unevaluated operands.
6773
6774 /// Set of candidates for starting an immediate invocation.
6777
6778 /// Set of DeclRefExprs referencing a consteval function when used in a
6779 /// context not already known to be immediately invoked.
6781
6782 /// P2718R0 - Lifetime extension in range-based for loops.
6783 /// MaterializeTemporaryExprs in for-range-init expressions which need to
6784 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
6785 /// InLifetimeExtendingContext is true.
6787
6788 /// Small set of gathered accesses to potentially misaligned members
6789 /// due to the packed attribute.
6791
6792 /// \brief Describes whether we are in an expression constext which we have
6793 /// to handle differently.
6801
6802 // A context can be nested in both a discarded statement context and
6803 // an immediate function context, so they need to be tracked independently.
6807
6809
6810 // We are in a constant context, but we also allow
6811 // non constant expressions, for example for array bounds (which may be
6812 // VLAs).
6814
6815 /// Whether we are currently in a context in which all temporaries must be
6816 /// lifetime-extended, even if they're not bound to a reference (for
6817 /// example, in a for-range initializer).
6819
6820 /// Whether evaluating an expression for a switch case label.
6821 bool IsCaseExpr = false;
6822
6823 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
6825
6826 // When evaluating immediate functions in the initializer of a default
6827 // argument or default member initializer, this is the declaration whose
6828 // default initializer is being evaluated and the location of the call
6829 // or constructor definition.
6833 : Loc(Loc), Decl(Decl), Context(Context) {
6834 assert(Decl && Context && "invalid initialization context");
6835 }
6836
6838 ValueDecl *Decl = nullptr;
6840 };
6841 std::optional<InitializationContext> DelayedDefaultInitializationContext;
6842
6853
6859
6866
6871
6876 // C++23 [expr.const]p14:
6877 // An expression or conversion is in an immediate function
6878 // context if it is potentially evaluated and either:
6879 // * its innermost enclosing non-block scope is a function
6880 // parameter scope of an immediate function, or
6881 // * its enclosing statement is enclosed by the compound-
6882 // statement of a consteval if statement.
6885 }
6886
6894 };
6895
6897 assert(!ExprEvalContexts.empty() &&
6898 "Must be in an expression evaluation context");
6899 return ExprEvalContexts.back();
6900 }
6901
6903 assert(!ExprEvalContexts.empty() &&
6904 "Must be in an expression evaluation context");
6905 return ExprEvalContexts.back();
6906 }
6907
6909 assert(ExprEvalContexts.size() >= 2 &&
6910 "Must be in an expression evaluation context");
6911 return ExprEvalContexts[ExprEvalContexts.size() - 2];
6912 }
6913
6915 return const_cast<Sema *>(this)->parentEvaluationContext();
6916 }
6917
6922
6923 /// Increment when we find a reference; decrement when we find an ignored
6924 /// assignment. Ultimately the value is 0 if every reference is an ignored
6925 /// assignment.
6926 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
6927
6928 /// Used to control the generation of ExprWithCleanups.
6930
6931 /// ExprCleanupObjects - This is the stack of objects requiring
6932 /// cleanup that are created by the current full expression.
6934
6935 /// Determine whether the use of this declaration is valid, without
6936 /// emitting diagnostics.
6937 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
6938 // A version of DiagnoseUseOfDecl that should be used if overload resolution
6939 // has been used to find this declaration, which means we don't have to bother
6940 // checking the trailing requires clause.
6942 return DiagnoseUseOfDecl(
6943 D, Loc, /*UnknownObjCClass=*/nullptr, /*ObjCPropertyAccess=*/false,
6944 /*AvoidPartialAvailabilityChecks=*/false, /*ClassReceiver=*/nullptr,
6945 /*SkipTrailingRequiresClause=*/true);
6946 }
6947
6948 /// Determine whether the use of this declaration is valid, and
6949 /// emit any corresponding diagnostics.
6950 ///
6951 /// This routine diagnoses various problems with referencing
6952 /// declarations that can occur when using a declaration. For example,
6953 /// it might warn if a deprecated or unavailable declaration is being
6954 /// used, or produce an error (and return true) if a C++0x deleted
6955 /// function is being used.
6956 ///
6957 /// \returns true if there was an error (this declaration cannot be
6958 /// referenced), false otherwise.
6960 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
6961 bool ObjCPropertyAccess = false,
6962 bool AvoidPartialAvailabilityChecks = false,
6963 ObjCInterfaceDecl *ClassReciever = nullptr,
6964 bool SkipTrailingRequiresClause = false);
6965
6966 /// Emit a note explaining that this function is deleted.
6968
6969 /// DiagnoseSentinelCalls - This routine checks whether a call or
6970 /// message-send is to a declaration with the sentinel attribute, and
6971 /// if so, it checks that the requirements of the sentinel are
6972 /// satisfied.
6974 ArrayRef<Expr *> Args);
6975
6977 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
6980
6982 ExpressionEvaluationContext NewContext, FunctionDecl *FD);
6983
6986 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
6990
6992
6996
6997 /// Check whether E, which is either a discarded-value expression or an
6998 /// unevaluated operand, is a simple-assignment to a volatlie-qualified
6999 /// lvalue, and if so, remove it from the list of volatile-qualified
7000 /// assignments that we are going to warn are deprecated.
7002
7004
7005 // Functions for marking a declaration referenced. These functions also
7006 // contain the relevant logic for marking if a reference to a function or
7007 // variable is an odr-use (in the C++11 sense). There are separate variants
7008 // for expressions referring to a decl; these exist because odr-use marking
7009 // needs to be delayed for some constant variables when we build one of the
7010 // named expressions.
7011 //
7012 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
7013 // should usually be true. This only needs to be set to false if the lack of
7014 // odr-use cannot be determined from the current context (for instance,
7015 // because the name denotes a virtual function and was written without an
7016 // explicit nested-name-specifier).
7017 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
7018
7019 /// Mark a function referenced, and check whether it is odr-used
7020 /// (C++ [basic.def.odr]p2, C99 6.9p3)
7022 bool MightBeOdrUse = true);
7023
7024 /// Mark a variable referenced, and check whether it is odr-used
7025 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
7026 /// used directly for normal expressions referring to VarDecl.
7028
7029 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7030 ///
7031 /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7032 /// be handled with care if the DeclRefExpr is not newly-created.
7033 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7034
7035 /// Perform reference-marking and odr-use handling for a MemberExpr.
7037
7038 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7041 unsigned CapturingScopeIndex);
7042
7044 void CleanupVarDeclMarking();
7045
7046 /// Try to capture the given variable.
7047 ///
7048 /// \param Var The variable to capture.
7049 ///
7050 /// \param Loc The location at which the capture occurs.
7051 ///
7052 /// \param Kind The kind of capture, which may be implicit (for either a
7053 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7054 ///
7055 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7056 /// an explicit lambda capture.
7057 ///
7058 /// \param BuildAndDiagnose Whether we are actually supposed to add the
7059 /// captures or diagnose errors. If false, this routine merely check whether
7060 /// the capture can occur without performing the capture itself or complaining
7061 /// if the variable cannot be captured.
7062 ///
7063 /// \param CaptureType Will be set to the type of the field used to capture
7064 /// this variable in the innermost block or lambda. Only valid when the
7065 /// variable can be captured.
7066 ///
7067 /// \param DeclRefType Will be set to the type of a reference to the capture
7068 /// from within the current scope. Only valid when the variable can be
7069 /// captured.
7070 ///
7071 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7072 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7073 /// This is useful when enclosing lambdas must speculatively capture
7074 /// variables that may or may not be used in certain specializations of
7075 /// a nested generic lambda.
7076 ///
7077 /// \returns true if an error occurred (i.e., the variable cannot be
7078 /// captured) and false if the capture succeeded.
7080 TryCaptureKind Kind, SourceLocation EllipsisLoc,
7081 bool BuildAndDiagnose, QualType &CaptureType,
7082 QualType &DeclRefType,
7083 const unsigned *const FunctionScopeIndexToStopAt);
7084
7085 /// Try to capture the given variable.
7088 SourceLocation EllipsisLoc = SourceLocation());
7089
7090 /// Checks if the variable must be captured.
7092
7093 /// Given a variable, determine the type that a reference to that
7094 /// variable will have in the given scope.
7096
7097 /// Mark all of the declarations referenced within a particular AST node as
7098 /// referenced. Used when template instantiation instantiates a non-dependent
7099 /// type -- entities referenced by the type are now referenced.
7101
7102 /// Mark any declarations that appear within this expression or any
7103 /// potentially-evaluated subexpressions as "referenced".
7104 ///
7105 /// \param SkipLocalVariables If true, don't mark local variables as
7106 /// 'referenced'.
7107 /// \param StopAt Subexpressions that we shouldn't recurse into.
7109 bool SkipLocalVariables = false,
7110 ArrayRef<const Expr *> StopAt = {});
7111
7112 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7113 /// conversion.
7114 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7115
7116 /// Conditionally issue a diagnostic based on the statements's reachability
7117 /// analysis.
7118 ///
7119 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7120 /// the function body is parsed, and then do a basic reachability analysis to
7121 /// determine if the statement is reachable. If it is unreachable, the
7122 /// diagnostic will not be emitted.
7123 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7124 const PartialDiagnostic &PD);
7125
7126 /// Conditionally issue a diagnostic based on the current
7127 /// evaluation context.
7128 ///
7129 /// \param Statement If Statement is non-null, delay reporting the
7130 /// diagnostic until the function body is parsed, and then do a basic
7131 /// reachability analysis to determine if the statement is reachable.
7132 /// If it is unreachable, the diagnostic will not be emitted.
7133 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7134 const PartialDiagnostic &PD);
7135 /// Similar, but diagnostic is only produced if all the specified statements
7136 /// are reachable.
7137 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7138 const PartialDiagnostic &PD);
7139
7140 // Primary Expressions.
7141 SourceRange getExprRange(Expr *E) const;
7142
7143 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7144 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7145 bool HasTrailingLParen, bool IsAddressOfOperand,
7146 CorrectionCandidateCallback *CCC = nullptr,
7147 bool IsInlineAsmIdentifier = false,
7148 Token *KeywordReplacement = nullptr);
7149
7150 /// Decomposes the given name into a DeclarationNameInfo, its location, and
7151 /// possibly a list of template arguments.
7152 ///
7153 /// If this produces template arguments, it is permitted to call
7154 /// DecomposeTemplateName.
7155 ///
7156 /// This actually loses a lot of source location information for
7157 /// non-standard name kinds; we should consider preserving that in
7158 /// some way.
7159 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7160 TemplateArgumentListInfo &Buffer,
7161 DeclarationNameInfo &NameInfo,
7162 const TemplateArgumentListInfo *&TemplateArgs);
7163
7164 /// Diagnose a lookup that found results in an enclosing class during error
7165 /// recovery. This usually indicates that the results were found in a
7166 /// dependent base class that could not be searched as part of a template
7167 /// definition. Always issues a diagnostic (though this may be only a warning
7168 /// in MS compatibility mode).
7169 ///
7170 /// Return \c true if the error is unrecoverable, or \c false if the caller
7171 /// should attempt to recover using these lookup results.
7172 bool DiagnoseDependentMemberLookup(const LookupResult &R);
7173
7174 /// Diagnose an empty lookup.
7175 ///
7176 /// \return false if new lookup candidates were found
7177 bool
7178 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7179 CorrectionCandidateCallback &CCC,
7180 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7181 ArrayRef<Expr *> Args = {},
7182 DeclContext *LookupCtx = nullptr);
7183
7184 /// If \p D cannot be odr-used in the current expression evaluation context,
7185 /// return a reason explaining why. Otherwise, return NOUR_None.
7187
7188 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7189 SourceLocation Loc,
7190 const CXXScopeSpec *SS = nullptr);
7191 DeclRefExpr *
7192 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7193 const DeclarationNameInfo &NameInfo,
7194 const CXXScopeSpec *SS = nullptr,
7195 NamedDecl *FoundD = nullptr,
7196 SourceLocation TemplateKWLoc = SourceLocation(),
7197 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7198
7199 /// BuildDeclRefExpr - Build an expression that references a
7200 /// declaration that does not require a closure capture.
7201 DeclRefExpr *
7202 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7203 const DeclarationNameInfo &NameInfo,
7204 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7205 SourceLocation TemplateKWLoc = SourceLocation(),
7206 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7207
7208 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7209 bool HasTrailingLParen);
7210
7211 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7212 /// declaration name, generally during template instantiation.
7213 /// There's a large number of things which don't need to be done along
7214 /// this path.
7216 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7217 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7218
7219 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7220 bool NeedsADL,
7221 bool AcceptInvalidDecl = false);
7222
7223 /// Complete semantic analysis for a reference to the given declaration.
7225 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7226 NamedDecl *FoundD = nullptr,
7227 const TemplateArgumentListInfo *TemplateArgs = nullptr,
7228 bool AcceptInvalidDecl = false);
7229
7230 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7231 // where Tokens representing function local predefined macros (such as
7232 // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7233 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7234
7235 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7236 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7237 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7238
7239 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7240
7241 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7243 Scope *UDLScope = nullptr);
7244 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7245 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7246 MultiExprArg Val);
7247 ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7248 unsigned NumUserSpecifiedExprs,
7249 SourceLocation InitLoc,
7250 SourceLocation LParenLoc,
7251 SourceLocation RParenLoc);
7252
7253 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7254 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle
7255 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7256 /// from multiple tokens. However, the common case is that StringToks points
7257 /// to one string.
7258 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7259 Scope *UDLScope = nullptr);
7260
7261 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7262
7263 /// ControllingExprOrType is either an opaque pointer coming out of a
7264 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7265 /// into two so we don't take a void *, but that's awkward because one of
7266 /// the operands is either a ParsedType or an Expr *, which doesn't lend
7267 /// itself to generic code very well.
7268 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7269 SourceLocation DefaultLoc,
7270 SourceLocation RParenLoc,
7271 bool PredicateIsExpr,
7272 void *ControllingExprOrType,
7273 ArrayRef<ParsedType> ArgTypes,
7274 ArrayRef<Expr *> ArgExprs);
7275 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7276 /// it'd be better to split this interface into two so we don't take a
7277 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7278 /// isn't a trivial change.
7279 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7280 SourceLocation DefaultLoc,
7281 SourceLocation RParenLoc,
7282 bool PredicateIsExpr,
7283 void *ControllingExprOrType,
7284 ArrayRef<TypeSourceInfo *> Types,
7285 ArrayRef<Expr *> Exprs);
7286
7287 // Binary/Unary Operators. 'Tok' is the token for the operator.
7288 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7289 Expr *InputExpr, bool IsAfterAmp = false);
7290 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7291 Expr *Input, bool IsAfterAmp = false);
7292
7293 /// Unary Operators. 'Tok' is the token for the operator.
7294 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7295 Expr *Input, bool IsAfterAmp = false);
7296
7297 /// Determine whether the given expression is a qualified member
7298 /// access expression, of a form that could be turned into a pointer to member
7299 /// with the address-of operator.
7300 bool isQualifiedMemberAccess(Expr *E);
7301 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7302 const Expr *Op,
7303 const CXXMethodDecl *MD);
7304
7305 /// CheckAddressOfOperand - The operand of & must be either a function
7306 /// designator or an lvalue designating an object. If it is an lvalue, the
7307 /// object cannot be declared with storage class register or be a bit field.
7308 /// Note: The usual conversions are *not* applied to the operand of the &
7309 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7310 /// In C++, the operand might be an overloaded function name, in which case
7311 /// we allow the '&' but retain the overloaded-function type.
7312 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7313
7314 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7315 /// _Alignas(type-name) .
7316 /// [dcl.align] An alignment-specifier of the form
7317 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7318 ///
7319 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7320 /// _Alignas(_Alignof(type-name)).
7321 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7322 SourceLocation OpLoc, SourceRange R);
7323 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7324 SourceLocation OpLoc, SourceRange R);
7325
7326 /// Build a sizeof or alignof expression given a type operand.
7327 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7328 SourceLocation OpLoc,
7329 UnaryExprOrTypeTrait ExprKind,
7330 SourceRange R);
7331
7332 /// Build a sizeof or alignof expression given an expression
7333 /// operand.
7334 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7335 UnaryExprOrTypeTrait ExprKind);
7336
7337 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7338 /// expr and the same for @c alignof and @c __alignof
7339 /// Note that the ArgRange is invalid if isType is false.
7340 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7341 UnaryExprOrTypeTrait ExprKind,
7342 bool IsType, void *TyOrEx,
7343 SourceRange ArgRange);
7344
7345 /// Check for operands with placeholder types and complain if found.
7346 /// Returns ExprError() if there was an error and no recovery was possible.
7348 bool CheckVecStepExpr(Expr *E);
7349
7350 /// Check the constraints on expression operands to unary type expression
7351 /// and type traits.
7352 ///
7353 /// Completes any types necessary and validates the constraints on the operand
7354 /// expression. The logic mostly mirrors the type-based overload, but may
7355 /// modify the expression as it completes the type for that expression through
7356 /// template instantiation, etc.
7358
7359 /// Check the constraints on operands to unary expression and type
7360 /// traits.
7361 ///
7362 /// This will complete any types necessary, and validate the various
7363 /// constraints on those operands.
7364 ///
7365 /// The UsualUnaryConversions() function is *not* called by this routine.
7366 /// C99 6.3.2.1p[2-4] all state:
7367 /// Except when it is the operand of the sizeof operator ...
7368 ///
7369 /// C++ [expr.sizeof]p4
7370 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7371 /// standard conversions are not applied to the operand of sizeof.
7372 ///
7373 /// This policy is followed for all of the unary trait expressions.
7374 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7375 SourceRange ExprRange,
7376 UnaryExprOrTypeTrait ExprKind,
7377 StringRef KWName);
7378
7379 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7380 tok::TokenKind Kind, Expr *Input);
7381
7382 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7383 MultiExprArg ArgExprs,
7384 SourceLocation RLoc);
7385 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7386 Expr *Idx, SourceLocation RLoc);
7387
7388 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7389 Expr *ColumnIdx,
7390 SourceLocation RBLoc);
7391
7392 /// ConvertArgumentsForCall - Converts the arguments specified in
7393 /// Args/NumArgs to the parameter types of the function FDecl with
7394 /// function prototype Proto. Call is the call expression itself, and
7395 /// Fn is the function expression. For a C++ member function, this
7396 /// routine does not attempt to convert the object argument. Returns
7397 /// true if the call is ill-formed.
7398 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7399 const FunctionProtoType *Proto,
7400 ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7401 bool ExecConfig = false);
7402
7403 /// CheckStaticArrayArgument - If the given argument corresponds to a static
7404 /// array parameter, check that it is non-null, and that if it is formed by
7405 /// array-to-pointer decay, the underlying array is sufficiently large.
7406 ///
7407 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7408 /// the array type derivation, then for each call to the function, the value
7409 /// of the corresponding actual argument shall provide access to the first
7410 /// element of an array with at least as many elements as specified by the
7411 /// size expression.
7412 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7413 const Expr *ArgExpr);
7414
7415 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7416 /// This provides the location of the left/right parens and a list of comma
7417 /// locations.
7418 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7419 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7420 Expr *ExecConfig = nullptr);
7421
7422 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7423 /// This provides the location of the left/right parens and a list of comma
7424 /// locations.
7425 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7426 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7427 Expr *ExecConfig = nullptr,
7428 bool IsExecConfig = false,
7429 bool AllowRecovery = false);
7430
7431 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7432 // with the specified CallArgs
7433 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7434 MultiExprArg CallArgs);
7435
7437
7438 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7439 /// i.e. an expression not of \p OverloadTy. The expression should
7440 /// unary-convert to an expression of function-pointer or
7441 /// block-pointer type.
7442 ///
7443 /// \param NDecl the declaration being called, if available
7445 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7446 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7447 Expr *Config = nullptr, bool IsExecConfig = false,
7448 ADLCallKind UsesADL = ADLCallKind::NotADL);
7449
7451 ParsedType &Ty, SourceLocation RParenLoc,
7452 Expr *CastExpr);
7453
7454 /// Prepares for a scalar cast, performing all the necessary stages
7455 /// except the final cast and returning the kind required.
7457
7458 /// Build an altivec or OpenCL literal.
7460 SourceLocation RParenLoc, Expr *E,
7461 TypeSourceInfo *TInfo);
7462
7463 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7464 /// the ParenListExpr into a sequence of comma binary operators.
7466
7468 SourceLocation RParenLoc, Expr *InitExpr);
7469
7471 TypeSourceInfo *TInfo,
7472 SourceLocation RParenLoc,
7473 Expr *LiteralExpr);
7474
7475 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7476 SourceLocation RBraceLoc);
7477
7478 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7479 SourceLocation RBraceLoc);
7480
7481 /// Binary Operators. 'Tok' is the token for the operator.
7483 Expr *LHSExpr, Expr *RHSExpr);
7485 Expr *LHSExpr, Expr *RHSExpr,
7486 bool ForFoldExpression = false);
7487
7488 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7489 /// operator @p Opc at location @c TokLoc. This routine only supports
7490 /// built-in operations; ActOnBinOp handles overloaded operators.
7492 Expr *LHSExpr, Expr *RHSExpr,
7493 bool ForFoldExpression = false);
7495 UnresolvedSetImpl &Functions);
7496
7497 /// Look for instances where it is likely the comma operator is confused with
7498 /// another operator. There is an explicit list of acceptable expressions for
7499 /// the left hand side of the comma operator, otherwise emit a warning.
7500 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7501
7502 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7503 /// in the case of a the GNU conditional expr extension.
7505 SourceLocation ColonLoc, Expr *CondExpr,
7506 Expr *LHSExpr, Expr *RHSExpr);
7507
7508 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7510 LabelDecl *TheDecl);
7511
7512 void ActOnStartStmtExpr();
7513 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7514 SourceLocation RPLoc);
7516 SourceLocation RPLoc, unsigned TemplateDepth);
7517 // Handle the final expression in a statement expression.
7519 void ActOnStmtExprError();
7520
7521 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
7524 bool isBrackets; // true if [expr], false if .ident
7525 union {
7528 } U;
7529 };
7530
7531 /// __builtin_offsetof(type, a.b[123][456].c)
7533 TypeSourceInfo *TInfo,
7534 ArrayRef<OffsetOfComponent> Components,
7535 SourceLocation RParenLoc);
7538 ParsedType ParsedArgTy,
7539 ArrayRef<OffsetOfComponent> Components,
7540 SourceLocation RParenLoc);
7541
7542 // __builtin_choose_expr(constExpr, expr1, expr2)
7543 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7544 Expr *LHSExpr, Expr *RHSExpr,
7545 SourceLocation RPLoc);
7546
7547 // __builtin_va_arg(expr, type)
7549 SourceLocation RPLoc);
7551 TypeSourceInfo *TInfo, SourceLocation RPLoc);
7552
7553 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7554 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7556 SourceLocation BuiltinLoc,
7557 SourceLocation RPLoc);
7558
7559 // #embed
7561 StringLiteral *BinaryData, StringRef FileName);
7562
7563 // Build a potentially resolved SourceLocExpr.
7565 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7566 DeclContext *ParentContext);
7567
7568 // __null
7570
7571 bool CheckCaseExpression(Expr *E);
7572
7573 //===------------------------- "Block" Extension ------------------------===//
7574
7575 /// ActOnBlockStart - This callback is invoked when a block literal is
7576 /// started.
7577 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7578
7579 /// ActOnBlockArguments - This callback allows processing of block arguments.
7580 /// If there are no arguments, this is still invoked.
7581 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7582 Scope *CurScope);
7583
7584 /// ActOnBlockError - If there is an error parsing a block, this callback
7585 /// is invoked to pop the information about the block from the action impl.
7586 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7587
7588 /// ActOnBlockStmtExpr - This is called when the body of a block statement
7589 /// literal was successfully completed. ^(int x){...}
7591 Scope *CurScope);
7592
7593 //===---------------------------- Clang Extensions ----------------------===//
7594
7595 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7596 /// provided arguments.
7597 ///
7598 /// __builtin_convertvector( value, dst type )
7599 ///
7601 SourceLocation BuiltinLoc,
7602 SourceLocation RParenLoc);
7603
7604 //===---------------------------- OpenCL Features -----------------------===//
7605
7606 /// Parse a __builtin_astype expression.
7607 ///
7608 /// __builtin_astype( value, dst type )
7609 ///
7610 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7611 SourceLocation BuiltinLoc,
7612 SourceLocation RParenLoc);
7613
7614 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7616 SourceLocation BuiltinLoc,
7617 SourceLocation RParenLoc);
7618
7619 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7621 ArrayRef<Expr *> SubExprs,
7622 QualType T = QualType());
7623
7624 /// Cast a base object to a member's actual type.
7625 ///
7626 /// There are two relevant checks:
7627 ///
7628 /// C++ [class.access.base]p7:
7629 ///
7630 /// If a class member access operator [...] is used to access a non-static
7631 /// data member or non-static member function, the reference is ill-formed
7632 /// if the left operand [...] cannot be implicitly converted to a pointer to
7633 /// the naming class of the right operand.
7634 ///
7635 /// C++ [expr.ref]p7:
7636 ///
7637 /// If E2 is a non-static data member or a non-static member function, the
7638 /// program is ill-formed if the class of which E2 is directly a member is
7639 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7640 ///
7641 /// Note that the latter check does not consider access; the access of the
7642 /// "real" base class is checked as appropriate when checking the access of
7643 /// the member name.
7645 NestedNameSpecifier Qualifier,
7646 NamedDecl *FoundDecl,
7647 NamedDecl *Member);
7648
7649 /// CheckCallReturnType - Checks that a call expression's return type is
7650 /// complete. Returns true on failure. The location passed in is the location
7651 /// that best represents the call.
7652 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7653 CallExpr *CE, FunctionDecl *FD);
7654
7655 /// Emit a warning for all pending noderef expressions that we recorded.
7656 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
7657
7659
7660 /// Instantiate or parse a C++ default argument expression as necessary.
7661 /// Return true on error.
7663 ParmVarDecl *Param, Expr *Init = nullptr,
7664 bool SkipImmediateInvocations = true);
7665
7666 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7667 /// the default expr if needed.
7669 ParmVarDecl *Param, Expr *Init = nullptr);
7670
7671 /// Wrap the expression in a ConstantExpr if it is a potential immediate
7672 /// invocation.
7674
7676
7677 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7678 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7679
7680 /// Abstract base class used for diagnosing integer constant
7681 /// expression violations.
7683 public:
7685
7687
7688 virtual SemaDiagnosticBuilder
7689 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7691 SourceLocation Loc) = 0;
7694 };
7695
7696 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7697 /// and reports the appropriate diagnostics. Returns false on success.
7698 /// Can optionally return the value of the expression.
7701 VerifyICEDiagnoser &Diagnoser,
7705 unsigned DiagID,
7708 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7712 AllowFoldKind CanFold = AllowFoldKind::No) {
7713 return VerifyIntegerConstantExpression(E, nullptr, CanFold);
7714 }
7715
7716 /// DiagnoseAssignmentAsCondition - Given that an expression is
7717 /// being used as a boolean condition, warn if it's an assignment.
7719
7720 /// Redundant parentheses over an equality comparison can indicate
7721 /// that the user intended an assignment used as condition.
7723
7725 public:
7727 FullExprArg(Sema &actions) : E(nullptr) {}
7728
7729 ExprResult release() { return E; }
7730
7731 Expr *get() const { return E; }
7732
7733 Expr *operator->() { return E; }
7734
7735 private:
7736 // FIXME: No need to make the entire Sema class a friend when it's just
7737 // Sema::MakeFullExpr that needs access to the constructor below.
7738 friend class Sema;
7739
7740 explicit FullExprArg(Expr *expr) : E(expr) {}
7741
7742 Expr *E;
7743 };
7744
7746 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
7747 }
7749 return FullExprArg(
7750 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
7751 }
7753 ExprResult FE =
7754 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
7755 /*DiscardedValue*/ true);
7756 return FullExprArg(FE.get());
7757 }
7758
7759 class ConditionResult {
7760 Decl *ConditionVar;
7761 ExprResult Condition;
7762 bool Invalid;
7763 std::optional<bool> KnownValue;
7764
7765 friend class Sema;
7766 ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
7767 bool IsConstexpr)
7768 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
7769 if (IsConstexpr && Condition.get()) {
7770 if (std::optional<llvm::APSInt> Val =
7771 Condition.get()->getIntegerConstantExpr(S.Context)) {
7772 KnownValue = !!(*Val);
7773 }
7774 }
7775 }
7776 explicit ConditionResult(bool Invalid)
7777 : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
7778 KnownValue(std::nullopt) {}
7779
7780 public:
7781 ConditionResult() : ConditionResult(false) {}
7782 bool isInvalid() const { return Invalid; }
7783 std::pair<VarDecl *, Expr *> get() const {
7784 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
7785 Condition.get());
7786 }
7787 std::optional<bool> getKnownValue() const { return KnownValue; }
7788 };
7790
7791 /// CheckBooleanCondition - Diagnose problems involving the use of
7792 /// the given expression as a boolean condition (e.g. in an if
7793 /// statement). Also performs the standard function and array
7794 /// decays, possibly changing the input variable.
7795 ///
7796 /// \param Loc - A location associated with the condition, e.g. the
7797 /// 'if' keyword.
7798 /// \return true iff there were any errors
7800 bool IsConstexpr = false);
7801
7802 enum class ConditionKind {
7803 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
7804 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
7805 Switch ///< An integral condition for a 'switch' statement.
7806 };
7807
7808 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
7809 ConditionKind CK, bool MissingOK = false);
7810
7811 QualType CheckConditionalOperands( // C99 6.5.15
7813 ExprObjectKind &OK, SourceLocation QuestionLoc);
7814
7815 /// Emit a specialized diagnostic when one expression is a null pointer
7816 /// constant and the other is not a pointer. Returns true if a diagnostic is
7817 /// emitted.
7818 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7819 SourceLocation QuestionLoc);
7820
7821 /// type checking for vector binary operators.
7823 SourceLocation Loc, bool IsCompAssign,
7824 bool AllowBothBool, bool AllowBoolConversion,
7825 bool AllowBoolOperation, bool ReportInvalid);
7826
7827 /// Return a signed ext_vector_type that is of identical size and number of
7828 /// elements. For floating point vectors, return an integer type of identical
7829 /// size and number of elements. In the non ext_vector_type case, search from
7830 /// the largest type to the smallest type to avoid cases where long long ==
7831 /// long, where long gets picked over long long.
7834
7835 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7836 /// operates on extended vector types. Instead of producing an IntTy result,
7837 /// like a scalar comparison, a vector comparison produces a vector of integer
7838 /// types.
7840 SourceLocation Loc,
7841 BinaryOperatorKind Opc);
7843 SourceLocation Loc,
7844 BinaryOperatorKind Opc);
7846 SourceLocation Loc,
7847 BinaryOperatorKind Opc);
7848
7849 // type checking for sizeless vector binary operators.
7851 SourceLocation Loc, bool IsCompAssign,
7852 ArithConvKind OperationKind);
7853
7854 /// Type checking for matrix binary operators.
7856 SourceLocation Loc,
7857 bool IsCompAssign);
7859 SourceLocation Loc, bool IsCompAssign);
7860
7861 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
7862 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
7863 /// VLST) allowed?
7864 ///
7865 /// This will also return false if the two given types do not make sense from
7866 /// the perspective of SVE bitcasts.
7867 bool isValidSveBitcast(QualType srcType, QualType destType);
7868
7869 /// Are the two types matrix types and do they have the same dimensions i.e.
7870 /// do they have the same number of rows and the same number of columns?
7872
7873 bool areVectorTypesSameSize(QualType srcType, QualType destType);
7874
7875 /// Are the two types lax-compatible vector types? That is, given
7876 /// that one of them is a vector, do they have equal storage sizes,
7877 /// where the storage size is the number of elements times the element
7878 /// size?
7879 ///
7880 /// This will also return false if either of the types is neither a
7881 /// vector nor a real type.
7882 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
7883
7884 /// Is this a legal conversion between two types, one of which is
7885 /// known to be a vector type?
7886 bool isLaxVectorConversion(QualType srcType, QualType destType);
7887
7888 // This returns true if at least one of the types is an altivec vector.
7889 bool anyAltivecTypes(QualType srcType, QualType destType);
7890
7891 // type checking C++ declaration initializers (C++ [dcl.init]).
7892
7893 /// Check a cast of an unknown-any type. We intentionally only
7894 /// trigger this for C-style casts.
7897 ExprValueKind &VK, CXXCastPath &Path);
7898
7899 /// Force an expression with unknown-type to an expression of the
7900 /// given type.
7902
7903 /// Type-check an expression that's being passed to an
7904 /// __unknown_anytype parameter.
7906 QualType &paramType);
7907
7908 // CheckMatrixCast - Check type constraints for matrix casts.
7909 // We allow casting between matrixes of the same dimensions i.e. when they
7910 // have the same number of rows and column. Returns true if the cast is
7911 // invalid.
7912 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7913 CastKind &Kind);
7914
7915 // CheckVectorCast - check type constraints for vectors.
7916 // Since vectors are an extension, there are no C standard reference for this.
7917 // We allow casting between vectors and integer datatypes of the same size.
7918 // returns true if the cast is invalid
7919 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7920 CastKind &Kind);
7921
7922 /// Prepare `SplattedExpr` for a vector splat operation, adding
7923 /// implicit casts if necessary.
7924 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
7925
7926 // CheckExtVectorCast - check type constraints for extended vectors.
7927 // Since vectors are an extension, there are no C standard reference for this.
7928 // We allow casting between vectors and integer datatypes of the same size,
7929 // or vectors and the element type of that vector.
7930 // returns the cast expr
7932 CastKind &Kind);
7933
7935 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
7936 }
7937
7938 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
7939 // functions and arrays to their respective pointers (C99 6.3.2.1), and
7940 // promotes floating-piont types according to the language semantics.
7942
7943 // UsualUnaryFPConversions - promotes floating-point types according to the
7944 // current language semantics.
7946
7947 /// CallExprUnaryConversions - a special case of an unary conversion
7948 /// performed on a function designator of a call expression.
7950
7951 // DefaultFunctionArrayConversion - converts functions and arrays
7952 // to their respective pointers (C99 6.3.2.1).
7954
7955 // DefaultFunctionArrayLvalueConversion - converts functions and
7956 // arrays to their respective pointers and performs the
7957 // lvalue-to-rvalue conversion.
7959 bool Diagnose = true);
7960
7961 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
7962 // the operand. This function is a no-op if the operand has a function type
7963 // or an array type.
7965
7966 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
7967 // do not have a prototype. Integer promotions are performed on each
7968 // argument, and arguments that have type float are promoted to double.
7970
7972 const FunctionProtoType *Proto,
7973 Expr *Fn);
7974
7975 /// Determine the degree of POD-ness for an expression.
7976 /// Incomplete types are considered POD, since this check can be performed
7977 /// when we're in an unevaluated context.
7979
7980 /// Check to see if the given expression is a valid argument to a variadic
7981 /// function, issuing a diagnostic if not.
7982 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
7983
7984 /// GatherArgumentsForCall - Collector argument expressions for various
7985 /// form of call prototypes.
7987 SourceLocation CallLoc, FunctionDecl *FDecl,
7988 const FunctionProtoType *Proto, unsigned FirstParam,
7991 bool AllowExplicit = false, bool IsListInitialization = false);
7992
7993 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
7994 // will create a runtime trap if the resulting type is not a POD type.
7996 FunctionDecl *FDecl);
7997
7998 // Check that the usual arithmetic conversions can be performed on this pair
7999 // of expressions that might be of enumeration type.
8001 ArithConvKind ACK);
8002
8003 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8004 // operands and then handles various conversions that are common to binary
8005 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8006 // routine returns the first non-arithmetic type found. The client is
8007 // responsible for emitting appropriate error diagnostics.
8009 SourceLocation Loc, ArithConvKind ACK);
8010
8012 switch (ConvTy) {
8013 default:
8014 return false;
8018 return true;
8019 }
8020 llvm_unreachable("impossible");
8021 }
8022
8023 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8024 /// assignment conversion type specified by ConvTy. This returns true if the
8025 /// conversion was invalid or false if the conversion was accepted.
8027 QualType DstType, QualType SrcType,
8028 Expr *SrcExpr, AssignmentAction Action,
8029 bool *Complained = nullptr);
8030
8031 /// CheckAssignmentConstraints - Perform type checking for assignment,
8032 /// argument passing, variable initialization, and function return values.
8033 /// C99 6.5.16.
8035 QualType LHSType,
8036 QualType RHSType);
8037
8038 /// Check assignment constraints and optionally prepare for a conversion of
8039 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8040 /// is true.
8042 ExprResult &RHS, CastKind &Kind,
8043 bool ConvertRHS = true);
8044
8045 /// Check assignment constraints for an assignment of RHS to LHSType.
8046 ///
8047 /// \param LHSType The destination type for the assignment.
8048 /// \param RHS The source expression for the assignment.
8049 /// \param Diagnose If \c true, diagnostics may be produced when checking
8050 /// for assignability. If a diagnostic is produced, \p RHS will be
8051 /// set to ExprError(). Note that this function may still return
8052 /// without producing a diagnostic, even for an invalid assignment.
8053 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8054 /// in an audited Core Foundation API and does not need to be checked
8055 /// for ARC retain issues.
8056 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8057 /// conversions necessary to perform the assignment. If \c false,
8058 /// \p Diagnose must also be \c false.
8060 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8061 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8062
8063 // If the lhs type is a transparent union, check whether we
8064 // can initialize the transparent union with the given expression.
8066 ExprResult &RHS);
8067
8068 /// the following "Check" methods will return a valid/converted QualType
8069 /// or a null QualType (indicating an error diagnostic was issued).
8070
8071 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8073 ExprResult &RHS);
8074
8075 /// Diagnose cases where a scalar was implicitly converted to a vector and
8076 /// diagnose the underlying types. Otherwise, diagnose the error
8077 /// as invalid vector logical operands for non-C++ cases.
8079 ExprResult &RHS);
8080
8082 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8083 BinaryOperatorKind Opc);
8084 QualType CheckRemainderOperands( // C99 6.5.5
8085 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8086 bool IsCompAssign = false);
8087 QualType CheckAdditionOperands( // C99 6.5.6
8088 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8089 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8091 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8092 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8093 QualType CheckShiftOperands( // C99 6.5.7
8094 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8095 BinaryOperatorKind Opc, bool IsCompAssign = false);
8097 QualType CheckCompareOperands( // C99 6.5.8/9
8098 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8099 BinaryOperatorKind Opc);
8100 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8101 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8102 BinaryOperatorKind Opc);
8103 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8104 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8105 BinaryOperatorKind Opc);
8106 // CheckAssignmentOperands is used for both simple and compound assignment.
8107 // For simple assignment, pass both expressions and a null converted type.
8108 // For compound assignment, pass both expressions and the converted type.
8109 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8110 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8111 BinaryOperatorKind Opc);
8112
8113 /// To be used for checking whether the arguments being passed to
8114 /// function exceeds the number of parameters expected for it.
8115 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8116 bool PartialOverloading = false) {
8117 // We check whether we're just after a comma in code-completion.
8118 if (NumArgs > 0 && PartialOverloading)
8119 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8120 return NumArgs > NumParams;
8121 }
8122
8123 /// Whether the AST is currently being rebuilt to correct immediate
8124 /// invocations. Immediate invocation candidates and references to consteval
8125 /// functions aren't tracked when this is set.
8127
8133
8134 /// Determines whether we are currently in a context that
8135 /// is not evaluated as per C++ [expr] p5.
8138 }
8139
8143
8147
8151
8158
8159 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8161 assert(!ExprEvalContexts.empty() &&
8162 "Must be in an expression evaluation context");
8163 for (const auto &Ctx : llvm::reverse(ExprEvalContexts)) {
8165 Ctx.DelayedDefaultInitializationContext)
8166 return Ctx.DelayedDefaultInitializationContext;
8167 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8168 Ctx.isUnevaluated())
8169 break;
8170 }
8171 return std::nullopt;
8172 }
8173
8174 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8176 assert(!ExprEvalContexts.empty() &&
8177 "Must be in an expression evaluation context");
8178 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8179 for (auto &Ctx : llvm::reverse(ExprEvalContexts)) {
8181 !Ctx.DelayedDefaultInitializationContext && Res)
8182 break;
8183 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8184 Ctx.isUnevaluated())
8185 break;
8186 Res = Ctx.DelayedDefaultInitializationContext;
8187 }
8188 return Res;
8189 }
8190
8194
8195 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8196 /// SelfAssigned when inside a CXXMethodDecl.
8197 const FieldDecl *
8199
8201
8202 template <typename... Ts>
8204 const Ts &...Args) {
8205 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8206 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8207 }
8208
8209 template <typename... Ts>
8210 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8211 const Ts &...Args) {
8212 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8214 }
8215
8216 /// Abstract class used to diagnose incomplete types.
8219
8220 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
8221 virtual ~TypeDiagnoser() {}
8222 };
8223
8224 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8225 protected:
8226 unsigned DiagID;
8227 std::tuple<const Ts &...> Args;
8228
8229 template <std::size_t... Is>
8231 std::index_sequence<Is...>) const {
8232 // Apply all tuple elements to the builder in order.
8233 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8234 (void)Dummy;
8235 }
8236
8237 public:
8238 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8239 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8240 assert(DiagID != 0 && "no diagnostic for type diagnoser");
8241 }
8242
8243 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8244 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8245 emit(DB, std::index_sequence_for<Ts...>());
8246 DB << T;
8247 }
8248 };
8249
8250 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8251 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8252 /// For example, a diagnostic with no other parameters would generally have
8253 /// the form "...%select{incomplete|sizeless}0 type %1...".
8254 template <typename... Ts>
8256 public:
8257 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8258 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8259
8260 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8261 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8262 this->emit(DB, std::index_sequence_for<Ts...>());
8263 DB << T->isSizelessType() << T;
8264 }
8265 };
8266
8267 /// Check an argument list for placeholders that we won't try to
8268 /// handle later.
8270
8271 /// The C++ "std::source_location::__impl" struct, defined in
8272 /// <source_location>.
8274
8275 /// A stack of expression evaluation contexts.
8277
8278 // Set of failed immediate invocations to avoid double diagnosing.
8280
8281 /// List of SourceLocations where 'self' is implicitly retained inside a
8282 /// block.
8285
8286 /// Do an explicit extend of the given block pointer if we're in ARC.
8288
8289 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8292
8293private:
8294 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8295
8296 /// Methods for marking which expressions involve dereferencing a pointer
8297 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8298 /// they are parsed, meaning that a noderef pointer may not be accessed. For
8299 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8300 /// `*p`, but need to check that `address of` is called on it. This requires
8301 /// keeping a container of all pending expressions and checking if the address
8302 /// of them are eventually taken.
8303 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8304 void CheckAddressOfNoDeref(const Expr *E);
8305
8306 ///@}
8307
8308 //
8309 //
8310 // -------------------------------------------------------------------------
8311 //
8312 //
8313
8314 /// \name C++ Expressions
8315 /// Implementations are in SemaExprCXX.cpp
8316 ///@{
8317
8318public:
8319 /// The C++ "std::bad_alloc" class, which is defined by the C++
8320 /// standard library.
8322
8323 /// The C++ "std::align_val_t" enum class, which is defined by the C++
8324 /// standard library.
8326
8327 /// The C++ "type_info" declaration, which is defined in <typeinfo>.
8329
8330 /// A flag to remember whether the implicit forms of operator new and delete
8331 /// have been declared.
8333
8334 /// Delete-expressions to be analyzed at the end of translation unit
8335 ///
8336 /// This list contains class members, and locations of delete-expressions
8337 /// that could not be proven as to whether they mismatch with new-expression
8338 /// used in initializer of the field.
8339 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8340
8341 /// Handle the result of the special case name lookup for inheriting
8342 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8343 /// constructor names in member using declarations, even if 'X' is not the
8344 /// name of the corresponding type.
8346 SourceLocation NameLoc,
8347 const IdentifierInfo &Name);
8348
8350 SourceLocation NameLoc, Scope *S,
8351 CXXScopeSpec &SS, bool EnteringContext);
8353 Scope *S, CXXScopeSpec &SS,
8354 ParsedType ObjectType, bool EnteringContext);
8355
8357 ParsedType ObjectType);
8358
8359 /// Build a C++ typeid expression with a type operand.
8360 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8361 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8362
8363 /// Build a C++ typeid expression with an expression operand.
8364 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8365 Expr *Operand, SourceLocation RParenLoc);
8366
8367 /// ActOnCXXTypeid - Parse typeid( something ).
8369 bool isType, void *TyOrExpr,
8370 SourceLocation RParenLoc);
8371
8372 /// Build a Microsoft __uuidof expression with a type operand.
8373 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8374 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8375
8376 /// Build a Microsoft __uuidof expression with an expression operand.
8377 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8378 Expr *Operand, SourceLocation RParenLoc);
8379
8380 /// ActOnCXXUuidof - Parse __uuidof( something ).
8382 bool isType, void *TyOrExpr,
8383 SourceLocation RParenLoc);
8384
8385 //// ActOnCXXThis - Parse 'this' pointer.
8387
8388 /// Check whether the type of 'this' is valid in the current context.
8390
8391 /// Build a CXXThisExpr and mark it referenced in the current context.
8392 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8394
8395 /// Try to retrieve the type of the 'this' pointer.
8396 ///
8397 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8399
8400 /// When non-NULL, the C++ 'this' expression is allowed despite the
8401 /// current context not being a non-static member function. In such cases,
8402 /// this provides the type used for 'this'.
8404
8405 /// RAII object used to temporarily allow the C++ 'this' expression
8406 /// to be used, with the given qualifiers on the current class type.
8408 Sema &S;
8409 QualType OldCXXThisTypeOverride;
8410 bool Enabled;
8411
8412 public:
8413 /// Introduce a new scope where 'this' may be allowed (when enabled),
8414 /// using the given declaration (which is either a class template or a
8415 /// class) along with the given qualifiers.
8416 /// along with the qualifiers placed on '*this'.
8417 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8418 bool Enabled = true);
8419
8421 };
8422
8423 /// Make sure the value of 'this' is actually available in the current
8424 /// context, if it is a potentially evaluated context.
8425 ///
8426 /// \param Loc The location at which the capture of 'this' occurs.
8427 ///
8428 /// \param Explicit Whether 'this' is explicitly captured in a lambda
8429 /// capture list.
8430 ///
8431 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8432 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8433 /// This is useful when enclosing lambdas must speculatively capture
8434 /// 'this' that may or may not be used in certain specializations of
8435 /// a nested generic lambda (depending on whether the name resolves to
8436 /// a non-static member function or a static function).
8437 /// \return returns 'true' if failed, 'false' if success.
8439 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8440 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8441 bool ByCopy = false);
8442
8443 /// Determine whether the given type is the type of *this that is used
8444 /// outside of the body of a member function for a type that is currently
8445 /// being defined.
8447
8448 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8450
8451 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8453
8454 //// ActOnCXXThrow - Parse throw expressions.
8457 bool IsThrownVarInScope);
8458
8459 /// CheckCXXThrowOperand - Validate the operand of a throw.
8460 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8461
8462 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8463 /// Can be interpreted either as function-style casting ("int(x)")
8464 /// or class type construction ("ClassType(x,y,z)")
8465 /// or creation of a value-initialized type ("int()").
8467 SourceLocation LParenOrBraceLoc,
8468 MultiExprArg Exprs,
8469 SourceLocation RParenOrBraceLoc,
8470 bool ListInitialization);
8471
8473 SourceLocation LParenLoc,
8474 MultiExprArg Exprs,
8475 SourceLocation RParenLoc,
8476 bool ListInitialization);
8477
8478 /// Parsed a C++ 'new' expression (C++ 5.3.4).
8479 ///
8480 /// E.g.:
8481 /// @code new (memory) int[size][4] @endcode
8482 /// or
8483 /// @code ::new Foo(23, "hello") @endcode
8484 ///
8485 /// \param StartLoc The first location of the expression.
8486 /// \param UseGlobal True if 'new' was prefixed with '::'.
8487 /// \param PlacementLParen Opening paren of the placement arguments.
8488 /// \param PlacementArgs Placement new arguments.
8489 /// \param PlacementRParen Closing paren of the placement arguments.
8490 /// \param TypeIdParens If the type is in parens, the source range.
8491 /// \param D The type to be allocated, as well as array dimensions.
8492 /// \param Initializer The initializing expression or initializer-list, or
8493 /// null if there is none.
8494 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8495 SourceLocation PlacementLParen,
8496 MultiExprArg PlacementArgs,
8497 SourceLocation PlacementRParen,
8498 SourceRange TypeIdParens, Declarator &D,
8499 Expr *Initializer);
8501 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8502 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8503 SourceRange TypeIdParens, QualType AllocType,
8504 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8505 SourceRange DirectInitRange, Expr *Initializer);
8506
8507 /// Determine whether \p FD is an aligned allocation or deallocation
8508 /// function that is unavailable.
8510
8511 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8512 /// function that is unavailable.
8514 SourceLocation Loc);
8515
8516 /// Checks that a type is suitable as the allocated type
8517 /// in a new-expression.
8518 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8519 SourceRange R);
8520
8521 /// Finds the overloads of operator new and delete that are appropriate
8522 /// for the allocation.
8524 SourceLocation StartLoc, SourceRange Range,
8526 QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP,
8527 MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew,
8528 FunctionDecl *&OperatorDelete, bool Diagnose = true);
8529
8530 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8531 /// delete. These are:
8532 /// @code
8533 /// // C++03:
8534 /// void* operator new(std::size_t) throw(std::bad_alloc);
8535 /// void* operator new[](std::size_t) throw(std::bad_alloc);
8536 /// void operator delete(void *) throw();
8537 /// void operator delete[](void *) throw();
8538 /// // C++11:
8539 /// void* operator new(std::size_t);
8540 /// void* operator new[](std::size_t);
8541 /// void operator delete(void *) noexcept;
8542 /// void operator delete[](void *) noexcept;
8543 /// // C++1y:
8544 /// void* operator new(std::size_t);
8545 /// void* operator new[](std::size_t);
8546 /// void operator delete(void *) noexcept;
8547 /// void operator delete[](void *) noexcept;
8548 /// void operator delete(void *, std::size_t) noexcept;
8549 /// void operator delete[](void *, std::size_t) noexcept;
8550 /// @endcode
8551 /// Note that the placement and nothrow forms of new are *not* implicitly
8552 /// declared. Their use requires including <new>.
8555 ArrayRef<QualType> Params);
8556
8558 DeclarationName Name, FunctionDecl *&Operator,
8560 bool Diagnose = true);
8563 DeclarationName Name,
8564 bool Diagnose = true);
8566 CXXRecordDecl *RD,
8567 bool Diagnose,
8568 bool LookForGlobal);
8569
8570 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8571 /// @code ::delete ptr; @endcode
8572 /// or
8573 /// @code delete [] ptr; @endcode
8574 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8575 bool ArrayForm, Expr *Operand);
8577 bool IsDelete, bool CallCanBeVirtual,
8578 bool WarnOnNonAbstractTypes,
8579 SourceLocation DtorLoc);
8580
8582 Expr *Operand, SourceLocation RParen);
8584 SourceLocation RParen);
8585
8587 SourceLocation OpLoc,
8588 tok::TokenKind OpKind,
8589 ParsedType &ObjectType,
8590 bool &MayBePseudoDestructor);
8591
8593 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8594 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8595 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8596
8598 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8599 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8600 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8601
8603 SourceLocation OpLoc,
8604 tok::TokenKind OpKind,
8605 SourceLocation TildeLoc,
8606 const DeclSpec &DS);
8607
8608 /// MaybeCreateExprWithCleanups - If the current full-expression
8609 /// requires any cleanups, surround it with a ExprWithCleanups node.
8610 /// Otherwise, just returns the passed-in expression.
8614
8615 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8616 return ActOnFinishFullExpr(
8617 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8618 }
8620 bool DiscardedValue, bool IsConstexpr = false,
8621 bool IsTemplateArgument = false);
8623
8624 /// Process the expression contained within a decltype. For such expressions,
8625 /// certain semantic checks on temporaries are delayed until this point, and
8626 /// are omitted for the 'topmost' call in the decltype expression. If the
8627 /// topmost call bound a temporary, strip that temporary off the expression.
8629
8630 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8631 bool IsUDSuffix);
8632
8634
8635 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8636 SourceLocation StmtLoc,
8637 ConditionKind CK);
8638
8639 /// Check the use of the given variable as a C++ condition in an if,
8640 /// while, do-while, or switch statement.
8642 SourceLocation StmtLoc, ConditionKind CK);
8643
8644 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8645 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8646
8647 /// Helper function to determine whether this is the (deprecated) C++
8648 /// conversion from a string literal to a pointer to non-const char or
8649 /// non-const wchar_t (for narrow and wide string literals,
8650 /// respectively).
8652
8653 /// PerformImplicitConversion - Perform an implicit conversion of the
8654 /// expression From to the type ToType using the pre-computed implicit
8655 /// conversion sequence ICS. Returns the converted
8656 /// expression. Action is the kind of conversion we're performing,
8657 /// used in the error message.
8659 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8660 AssignmentAction Action,
8662
8663 /// PerformImplicitConversion - Perform an implicit conversion of the
8664 /// expression From to the type ToType by following the standard
8665 /// conversion sequence SCS. Returns the converted
8666 /// expression. Flavor is the context in which we're performing this
8667 /// conversion, for use in error messages.
8669 const StandardConversionSequence &SCS,
8670 AssignmentAction Action,
8672
8673 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8674
8675 /// Parsed one of the type trait support pseudo-functions.
8678 SourceLocation RParenLoc);
8681 SourceLocation RParenLoc);
8682
8683 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8684 /// pseudo-functions.
8686 ParsedType LhsTy, Expr *DimExpr,
8687 SourceLocation RParen);
8688
8690 TypeSourceInfo *TSInfo, Expr *DimExpr,
8691 SourceLocation RParen);
8692
8693 /// ActOnExpressionTrait - Parsed one of the unary type trait support
8694 /// pseudo-functions.
8696 Expr *Queried, SourceLocation RParen);
8697
8699 Expr *Queried, SourceLocation RParen);
8700
8703 bool isIndirect);
8705 ExprResult &RHS,
8706 SourceLocation QuestionLoc);
8707
8709 ExprResult &LHS, ExprResult &RHS,
8710 SourceLocation QuestionLoc);
8711
8712 //// Determines if a type is trivially relocatable
8713 /// according to the C++26 rules.
8714 // FIXME: This is in Sema because it requires
8715 // overload resolution, can we move to ASTContext?
8718
8719 //// Determines if a type is replaceable
8720 /// according to the C++26 rules.
8721 // FIXME: This is in Sema because it requires
8722 // overload resolution, can we move to ASTContext?
8724
8725 /// Check the operands of ?: under C++ semantics.
8726 ///
8727 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8728 /// extension. In this case, LHS == Cond. (But they're not aliases.)
8729 ///
8730 /// This function also implements GCC's vector extension and the
8731 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8732 /// permit the use of a?b:c where the type of a is that of a integer vector
8733 /// with the same number of elements and size as the vectors of b and c. If
8734 /// one of either b or c is a scalar it is implicitly converted to match the
8735 /// type of the vector. Otherwise the expression is ill-formed. If both b and
8736 /// c are scalars, then b and c are checked and converted to the type of a if
8737 /// possible.
8738 ///
8739 /// The expressions are evaluated differently for GCC's and OpenCL's
8740 /// extensions. For the GCC extension, the ?: operator is evaluated as
8741 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8742 /// For the OpenCL extensions, the ?: operator is evaluated as
8743 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
8744 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
8746 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8747 ExprObjectKind &OK, SourceLocation questionLoc);
8748
8749 /// Find a merged pointer type and convert the two expressions to it.
8750 ///
8751 /// This finds the composite pointer type for \p E1 and \p E2 according to
8752 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8753 /// it. It does not emit diagnostics (FIXME: that's not true if \p
8754 /// ConvertArgs is \c true).
8755 ///
8756 /// \param Loc The location of the operator requiring these two expressions to
8757 /// be converted to the composite pointer type.
8758 ///
8759 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
8760 /// type.
8762 bool ConvertArgs = true);
8764 ExprResult &E2, bool ConvertArgs = true) {
8765 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8766 QualType Composite =
8767 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
8768 E1 = E1Tmp;
8769 E2 = E2Tmp;
8770 return Composite;
8771 }
8772
8773 /// MaybeBindToTemporary - If the passed in expression has a record type with
8774 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
8775 /// it simply returns the passed in expression.
8777
8778 /// IgnoredValueConversions - Given that an expression's result is
8779 /// syntactically ignored, perform any conversions that are
8780 /// required.
8782
8784
8787 const DeclarationNameInfo &TargetNameInfo);
8788
8790 SourceLocation KeywordLoc,
8791 bool IsIfExists, CXXScopeSpec &SS,
8792 UnqualifiedId &Name);
8793
8796 ArrayRef<ParmVarDecl *> LocalParameters,
8797 Scope *BodyScope);
8801 CXXScopeSpec &SS,
8802 SourceLocation NameLoc,
8803 const IdentifierInfo *TypeName,
8804 TemplateIdAnnotation *TemplateId);
8806 SourceLocation NoexceptLoc);
8808 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8809 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8812 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8816 bool IsSatisfied, SourceLocation NoexceptLoc,
8823 BuildNestedRequirement(StringRef InvalidConstraintEntity,
8824 const ASTConstraintSatisfaction &Satisfaction);
8827 SourceLocation LParenLoc,
8828 ArrayRef<ParmVarDecl *> LocalParameters,
8829 SourceLocation RParenLoc,
8831 SourceLocation ClosingBraceLoc);
8832
8833private:
8834 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
8835 bool IsDelete);
8836
8837 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8838 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8839 bool DeleteWasArrayForm);
8840
8841 ///@}
8842
8843 //
8844 //
8845 // -------------------------------------------------------------------------
8846 //
8847 //
8848
8849 /// \name Member Access Expressions
8850 /// Implementations are in SemaExprMember.cpp
8851 ///@{
8852
8853public:
8854 /// Check whether an expression might be an implicit class member access.
8856 bool IsAddressOfOperand);
8857
8858 /// Builds an expression which might be an implicit member expression.
8860 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
8861 const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
8862
8863 /// Builds an implicit member access expression. The current context
8864 /// is known to be an instance method, and the given unqualified lookup
8865 /// set is known to contain only instance members, at least one of which
8866 /// is from an appropriate type.
8868 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8869 LookupResult &R,
8870 const TemplateArgumentListInfo *TemplateArgs,
8871 bool IsDefiniteInstance, const Scope *S);
8872
8874 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
8875 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8876 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
8877 const TemplateArgumentListInfo *TemplateArgs);
8878
8879 /// The main callback when the parser finds something like
8880 /// expression . [nested-name-specifier] identifier
8881 /// expression -> [nested-name-specifier] identifier
8882 /// where 'identifier' encompasses a fairly broad spectrum of
8883 /// possibilities, including destructor and operator references.
8884 ///
8885 /// \param OpKind either tok::arrow or tok::period
8886 /// \param ObjCImpDecl the current Objective-C \@implementation
8887 /// decl; this is an ugly hack around the fact that Objective-C
8888 /// \@implementations aren't properly put in the context chain
8890 tok::TokenKind OpKind, CXXScopeSpec &SS,
8891 SourceLocation TemplateKWLoc,
8892 UnqualifiedId &Member, Decl *ObjCImpDecl);
8893
8894 MemberExpr *
8895 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
8896 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
8897 ValueDecl *Member, DeclAccessPair FoundDecl,
8898 bool HadMultipleCandidates,
8899 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
8901 const TemplateArgumentListInfo *TemplateArgs = nullptr);
8902
8903 // Check whether the declarations we found through a nested-name
8904 // specifier in a member expression are actually members of the base
8905 // type. The restriction here is:
8906 //
8907 // C++ [expr.ref]p2:
8908 // ... In these cases, the id-expression shall name a
8909 // member of the class or of one of its base classes.
8910 //
8911 // So it's perfectly legitimate for the nested-name specifier to name
8912 // an unrelated class, and for us to find an overload set including
8913 // decls from classes which are not superclasses, as long as the decl
8914 // we actually pick through overload resolution is from a superclass.
8915 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
8916 const CXXScopeSpec &SS,
8917 const LookupResult &R);
8918
8919 // This struct is for use by ActOnMemberAccess to allow
8920 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
8921 // changing the access operator from a '.' to a '->' (to see if that is the
8922 // change needed to fix an error about an unknown member, e.g. when the class
8923 // defines a custom operator->).
8929
8931 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
8932 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8933 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
8934 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
8935 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
8936
8939 bool IsArrow, const CXXScopeSpec &SS,
8940 SourceLocation TemplateKWLoc,
8941 NamedDecl *FirstQualifierInScope, LookupResult &R,
8942 const TemplateArgumentListInfo *TemplateArgs,
8943 const Scope *S, bool SuppressQualifierCheck = false,
8944 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
8945
8946 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
8947 SourceLocation OpLoc,
8948 const CXXScopeSpec &SS, FieldDecl *Field,
8949 DeclAccessPair FoundDecl,
8950 const DeclarationNameInfo &MemberNameInfo);
8951
8952 /// Perform conversions on the LHS of a member access expression.
8954
8956 const CXXScopeSpec &SS, SourceLocation nameLoc,
8957 IndirectFieldDecl *indirectField,
8958 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
8959 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
8960
8961private:
8962 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
8963
8964 ///@}
8965
8966 //
8967 //
8968 // -------------------------------------------------------------------------
8969 //
8970 //
8971
8972 /// \name Initializers
8973 /// Implementations are in SemaInit.cpp
8974 ///@{
8975
8976public:
8977 /// Stack of types that correspond to the parameter entities that are
8978 /// currently being copy-initialized. Can be empty.
8980
8981 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
8983
8984 bool IsStringInit(Expr *Init, const ArrayType *AT);
8985
8986 /// Determine whether we can perform aggregate initialization for the purposes
8987 /// of overload resolution.
8989 const InitializedEntity &Entity, InitListExpr *From);
8990
8992 SourceLocation EqualOrColonLoc,
8993 bool GNUSyntax, ExprResult Init);
8994
8995 /// Check that the lifetime of the initializer (and its subobjects) is
8996 /// sufficient for initializing the entity, and perform lifetime extension
8997 /// (when permitted) if not.
8999
9002 bool BoundToLvalueReference);
9003
9004 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9005 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9006 /// we don't have xvalues there.
9008
9012
9016 SourceLocation EqualLoc, ExprResult Init,
9017 bool TopLevelOfInitList = false,
9018 bool AllowExplicit = false);
9019
9021 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9022 const InitializationKind &Kind, MultiExprArg Init);
9023
9024 ///@}
9025
9026 //
9027 //
9028 // -------------------------------------------------------------------------
9029 //
9030 //
9031
9032 /// \name C++ Lambda Expressions
9033 /// Implementations are in SemaLambda.cpp
9034 ///@{
9035
9036public:
9037 /// Create a new lambda closure type.
9039 TypeSourceInfo *Info,
9040 unsigned LambdaDependencyKind,
9041 LambdaCaptureDefault CaptureDefault);
9042
9043 /// Number lambda for linkage purposes if necessary.
9045 std::optional<CXXRecordDecl::LambdaNumbering>
9046 NumberingOverride = std::nullopt);
9047
9048 /// Endow the lambda scope info with the relevant properties.
9049 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9050 SourceRange IntroducerRange,
9051 LambdaCaptureDefault CaptureDefault,
9052 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9053 bool Mutable);
9054
9057
9059 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9060 TemplateParameterList *TemplateParams);
9061
9062 void
9064 SourceLocation CallOperatorLoc,
9065 const AssociatedConstraint &TrailingRequiresClause,
9066 TypeSourceInfo *MethodTyInfo,
9067 ConstexprSpecKind ConstexprKind, StorageClass SC,
9069 bool HasExplicitResultType);
9070
9071 /// Returns true if the explicit object parameter was invalid.
9073 SourceLocation CallLoc);
9074
9075 /// Perform initialization analysis of the init-capture and perform
9076 /// any implicit conversions such as an lvalue-to-rvalue conversion if
9077 /// not being used to initialize a reference.
9079 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9080 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9082 Loc, ByRef, EllipsisLoc, std::nullopt, Id,
9084 }
9086 SourceLocation EllipsisLoc,
9087 UnsignedOrNone NumExpansions,
9088 IdentifierInfo *Id,
9089 bool DirectInit, Expr *&Init);
9090
9091 /// Create a dummy variable within the declcontext of the lambda's
9092 /// call operator, for name lookup purposes for a lambda init capture.
9093 ///
9094 /// CodeGen handles emission of lambda captures, ignoring these dummy
9095 /// variables appropriately.
9097 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9098 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9099
9100 /// Add an init-capture to a lambda scope.
9101 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9102
9103 /// Note that we have finished the explicit captures for the
9104 /// given lambda.
9106
9107 /// Deduce a block or lambda's return type based on the return
9108 /// statements present in the body.
9110
9111 /// Once the Lambdas capture are known, we can start to create the closure,
9112 /// call operator method, and keep track of the captures.
9113 /// We do the capture lookup here, but they are not actually captured until
9114 /// after we know what the qualifiers of the call operator are.
9116 Scope *CurContext);
9117
9118 /// This is called after parsing the explicit template parameter list
9119 /// on a lambda (if it exists) in C++2a.
9121 SourceLocation LAngleLoc,
9122 ArrayRef<NamedDecl *> TParams,
9123 SourceLocation RAngleLoc,
9124 ExprResult RequiresClause);
9125
9127 SourceLocation MutableLoc);
9128
9130 Scope *LambdaScope,
9132
9133 /// ActOnStartOfLambdaDefinition - This is called just before we start
9134 /// parsing the body of a lambda; it analyzes the explicit captures and
9135 /// arguments, and sets up various data-structures for the body of the
9136 /// lambda.
9138 Declarator &ParamInfo, const DeclSpec &DS);
9139
9140 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9141 /// is invoked to pop the information about the lambda.
9142 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9143 bool IsInstantiation = false);
9144
9145 /// ActOnLambdaExpr - This is called when the body of a lambda expression
9146 /// was successfully completed.
9148
9149 /// Does copying/destroying the captured variable have side effects?
9150 bool CaptureHasSideEffects(const sema::Capture &From);
9151
9152 /// Diagnose if an explicit lambda capture is unused. Returns true if a
9153 /// diagnostic is emitted.
9154 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9155 SourceRange FixItRange,
9156 const sema::Capture &From);
9157
9158 /// Build a FieldDecl suitable to hold the given capture.
9160
9161 /// Initialize the given capture with a suitable expression.
9163 SourceLocation ImplicitCaptureLoc,
9164 bool IsOpenMPMapping = false);
9165
9166 /// Complete a lambda-expression having processed and attached the
9167 /// lambda body.
9169
9170 /// Get the return type to use for a lambda's conversion function(s) to
9171 /// function pointer type, given the type of the call operator.
9172 QualType
9174 CallingConv CC);
9175
9177 SourceLocation ConvLocation,
9178 CXXConversionDecl *Conv, Expr *Src);
9179
9181 : private FunctionScopeRAII {
9182 public:
9184 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9186 bool ShouldAddDeclsFromParentScope = true);
9187 };
9188
9189 /// Compute the mangling number context for a lambda expression or
9190 /// block literal. Also return the extra mangling decl if any.
9191 ///
9192 /// \param DC - The DeclContext containing the lambda expression or
9193 /// block literal.
9194 std::tuple<MangleNumberingContext *, Decl *>
9196
9197 ///@}
9198
9199 //
9200 //
9201 // -------------------------------------------------------------------------
9202 //
9203 //
9204
9205 /// \name Name Lookup
9206 ///
9207 /// These routines provide name lookup that is used during semantic
9208 /// analysis to resolve the various kinds of names (identifiers,
9209 /// overloaded operator names, constructor names, etc.) into zero or
9210 /// more declarations within a particular scope. The major entry
9211 /// points are LookupName, which performs unqualified name lookup,
9212 /// and LookupQualifiedName, which performs qualified name lookup.
9213 ///
9214 /// All name lookup is performed based on some specific criteria,
9215 /// which specify what names will be visible to name lookup and how
9216 /// far name lookup should work. These criteria are important both
9217 /// for capturing language semantics (certain lookups will ignore
9218 /// certain names, for example) and for performance, since name
9219 /// lookup is often a bottleneck in the compilation of C++. Name
9220 /// lookup criteria is specified via the LookupCriteria enumeration.
9221 ///
9222 /// The results of name lookup can vary based on the kind of name
9223 /// lookup performed, the current language, and the translation
9224 /// unit. In C, for example, name lookup will either return nothing
9225 /// (no entity found) or a single declaration. In C++, name lookup
9226 /// can additionally refer to a set of overloaded functions or
9227 /// result in an ambiguity. All of the possible results of name
9228 /// lookup are captured by the LookupResult class, which provides
9229 /// the ability to distinguish among them.
9230 ///
9231 /// Implementations are in SemaLookup.cpp
9232 ///@{
9233
9234public:
9235 /// Tracks whether we are in a context where typo correction is
9236 /// disabled.
9238
9239 /// The number of typos corrected by CorrectTypo.
9241
9242 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9243 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9244
9245 /// A cache containing identifiers for which typo correction failed and
9246 /// their locations, so that repeated attempts to correct an identifier in a
9247 /// given location are ignored if typo correction already failed for it.
9249
9250 /// SpecialMemberOverloadResult - The overloading result for a special member
9251 /// function.
9252 ///
9253 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9254 /// integer are used to determine whether overload resolution succeeded.
9256 public:
9258
9259 private:
9260 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9261
9262 public:
9265 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9266
9267 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
9268 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9269
9270 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
9271 void setKind(Kind K) { Pair.setInt(K); }
9272 };
9273
9274 class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode,
9276 public:
9277 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
9278 : FastFoldingSetNode(ID) {}
9279 };
9280
9281 /// A cache of special member function overload resolution results
9282 /// for C++ records.
9283 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
9284
9286
9287 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9288 // TODO: make this is a typesafe union.
9291
9292 /// Describes the kind of name lookup to perform.
9294 /// Ordinary name lookup, which finds ordinary names (functions,
9295 /// variables, typedefs, etc.) in C and most kinds of names
9296 /// (functions, variables, members, types, etc.) in C++.
9298 /// Tag name lookup, which finds the names of enums, classes,
9299 /// structs, and unions.
9301 /// Label name lookup.
9303 /// Member name lookup, which finds the names of
9304 /// class/struct/union members.
9306 /// Look up of an operator name (e.g., operator+) for use with
9307 /// operator overloading. This lookup is similar to ordinary name
9308 /// lookup, but will ignore any declarations that are class members.
9310 /// Look up a name following ~ in a destructor name. This is an ordinary
9311 /// lookup, but prefers tags to typedefs.
9313 /// Look up of a name that precedes the '::' scope resolution
9314 /// operator in C++. This lookup completely ignores operator, object,
9315 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9317 /// Look up a namespace name within a C++ using directive or
9318 /// namespace alias definition, ignoring non-namespace names (C++
9319 /// [basic.lookup.udir]p1).
9321 /// Look up all declarations in a scope with the given name,
9322 /// including resolved using declarations. This is appropriate
9323 /// for checking redeclarations for a using declaration.
9325 /// Look up an ordinary name that is going to be redeclared as a
9326 /// name with linkage. This lookup ignores any declarations that
9327 /// are outside of the current scope unless they have linkage. See
9328 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9330 /// Look up a friend of a local class. This lookup does not look
9331 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9333 /// Look up the name of an Objective-C protocol.
9335 /// Look up implicit 'self' parameter of an objective-c method.
9337 /// Look up the name of an OpenMP user-defined reduction operation.
9339 /// Look up the name of an OpenMP user-defined mapper.
9341 /// Look up any declaration with any name.
9343 };
9344
9345 /// The possible outcomes of name lookup for a literal operator.
9347 /// The lookup resulted in an error.
9349 /// The lookup found no match but no diagnostic was issued.
9351 /// The lookup found a single 'cooked' literal operator, which
9352 /// expects a normal literal to be built and passed to it.
9354 /// The lookup found a single 'raw' literal operator, which expects
9355 /// a string literal containing the spelling of the literal token.
9357 /// The lookup found an overload set of literal operator templates,
9358 /// which expect the characters of the spelling of the literal token to be
9359 /// passed as a non-type template argument pack.
9361 /// The lookup found an overload set of literal operator templates,
9362 /// which expect the character type and characters of the spelling of the
9363 /// string literal token to be passed as template arguments.
9365 };
9366
9367 SpecialMemberOverloadResult
9369 bool VolatileArg, bool RValueThis, bool ConstThis,
9370 bool VolatileThis);
9371
9373
9374 /// Look up a name, looking for a single declaration. Return
9375 /// null if the results were absent, ambiguous, or overloaded.
9376 ///
9377 /// It is preferable to use the elaborated form and explicitly handle
9378 /// ambiguity and overloaded.
9380 Scope *S, DeclarationName Name, SourceLocation Loc,
9381 LookupNameKind NameKind,
9383
9384 /// Lookup a builtin function, when name lookup would otherwise
9385 /// fail.
9386 bool LookupBuiltin(LookupResult &R);
9387 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9388
9389 /// Perform unqualified name lookup starting from a given
9390 /// scope.
9391 ///
9392 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9393 /// used to find names within the current scope. For example, 'x' in
9394 /// @code
9395 /// int x;
9396 /// int f() {
9397 /// return x; // unqualified name look finds 'x' in the global scope
9398 /// }
9399 /// @endcode
9400 ///
9401 /// Different lookup criteria can find different names. For example, a
9402 /// particular scope can have both a struct and a function of the same
9403 /// name, and each can be found by certain lookup criteria. For more
9404 /// information about lookup criteria, see the documentation for the
9405 /// class LookupCriteria.
9406 ///
9407 /// @param S The scope from which unqualified name lookup will
9408 /// begin. If the lookup criteria permits, name lookup may also search
9409 /// in the parent scopes.
9410 ///
9411 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9412 /// look up and the lookup kind), and is updated with the results of lookup
9413 /// including zero or more declarations and possibly additional information
9414 /// used to diagnose ambiguities.
9415 ///
9416 /// @returns \c true if lookup succeeded and false otherwise.
9417 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9418 bool ForceNoCPlusPlus = false);
9419
9420 /// Perform qualified name lookup into a given context.
9421 ///
9422 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9423 /// names when the context of those names is explicit specified, e.g.,
9424 /// "std::vector" or "x->member", or as part of unqualified name lookup.
9425 ///
9426 /// Different lookup criteria can find different names. For example, a
9427 /// particular scope can have both a struct and a function of the same
9428 /// name, and each can be found by certain lookup criteria. For more
9429 /// information about lookup criteria, see the documentation for the
9430 /// class LookupCriteria.
9431 ///
9432 /// \param R captures both the lookup criteria and any lookup results found.
9433 ///
9434 /// \param LookupCtx The context in which qualified name lookup will
9435 /// search. If the lookup criteria permits, name lookup may also search
9436 /// in the parent contexts or (for C++ classes) base classes.
9437 ///
9438 /// \param InUnqualifiedLookup true if this is qualified name lookup that
9439 /// occurs as part of unqualified name lookup.
9440 ///
9441 /// \returns true if lookup succeeded, false if it failed.
9442 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9443 bool InUnqualifiedLookup = false);
9444
9445 /// Performs qualified name lookup or special type of lookup for
9446 /// "__super::" scope specifier.
9447 ///
9448 /// This routine is a convenience overload meant to be called from contexts
9449 /// that need to perform a qualified name lookup with an optional C++ scope
9450 /// specifier that might require special kind of lookup.
9451 ///
9452 /// \param R captures both the lookup criteria and any lookup results found.
9453 ///
9454 /// \param LookupCtx The context in which qualified name lookup will
9455 /// search.
9456 ///
9457 /// \param SS An optional C++ scope-specifier.
9458 ///
9459 /// \returns true if lookup succeeded, false if it failed.
9460 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9461 CXXScopeSpec &SS);
9462
9463 /// Performs name lookup for a name that was parsed in the
9464 /// source code, and may contain a C++ scope specifier.
9465 ///
9466 /// This routine is a convenience routine meant to be called from
9467 /// contexts that receive a name and an optional C++ scope specifier
9468 /// (e.g., "N::M::x"). It will then perform either qualified or
9469 /// unqualified name lookup (with LookupQualifiedName or LookupName,
9470 /// respectively) on the given name and return those results. It will
9471 /// perform a special type of lookup for "__super::" scope specifier.
9472 ///
9473 /// @param S The scope from which unqualified name lookup will
9474 /// begin.
9475 ///
9476 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
9477 ///
9478 /// @param EnteringContext Indicates whether we are going to enter the
9479 /// context of the scope-specifier SS (if present).
9480 ///
9481 /// @returns True if any decls were found (but possibly ambiguous)
9483 QualType ObjectType, bool AllowBuiltinCreation = false,
9484 bool EnteringContext = false);
9485
9486 /// Perform qualified name lookup into all base classes of the given
9487 /// class.
9488 ///
9489 /// \param R captures both the lookup criteria and any lookup results found.
9490 ///
9491 /// \param Class The context in which qualified name lookup will
9492 /// search. Name lookup will search in all base classes merging the results.
9493 ///
9494 /// @returns True if any decls were found (but possibly ambiguous)
9496
9498 UnresolvedSetImpl &Functions);
9499
9500 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9501 /// If GnuLabelLoc is a valid source location, then this is a definition
9502 /// of an __label__ label name, otherwise it is a normal label definition
9503 /// or use.
9505 SourceLocation GnuLabelLoc = SourceLocation());
9506
9507 /// Perform a name lookup for a label with the specified name; this does not
9508 /// create a new label if the lookup fails.
9510
9511 /// Look up the constructors for the given class.
9513
9514 /// Look up the default constructor for the given class.
9516
9517 /// Look up the copying constructor for the given class.
9519 unsigned Quals);
9520
9521 /// Look up the copying assignment operator for the given class.
9523 bool RValueThis, unsigned ThisQuals);
9524
9525 /// Look up the moving constructor for the given class.
9527 unsigned Quals);
9528
9529 /// Look up the moving assignment operator for the given class.
9531 bool RValueThis, unsigned ThisQuals);
9532
9533 /// Look for the destructor of the given class.
9534 ///
9535 /// During semantic analysis, this routine should be used in lieu of
9536 /// CXXRecordDecl::getDestructor().
9537 ///
9538 /// \returns The destructor for this class.
9540
9541 /// Force the declaration of any implicitly-declared members of this
9542 /// class.
9544
9545 /// Make a merged definition of an existing hidden definition \p ND
9546 /// visible at the specified location.
9548
9549 /// Check ODR hashes for C/ObjC when merging types from modules.
9550 /// Differently from C++, actually parse the body and reject in case
9551 /// of a mismatch.
9552 template <typename T,
9553 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
9555 if (Duplicate->getODRHash() != Previous->getODRHash())
9556 return false;
9557
9558 // Make the previous decl visible.
9560 return true;
9561 }
9562
9563 /// Get the set of additional modules that should be checked during
9564 /// name lookup. A module and its imports become visible when instanting a
9565 /// template defined within it.
9566 llvm::DenseSet<Module *> &getLookupModules();
9567
9568 bool hasVisibleMergedDefinition(const NamedDecl *Def);
9570
9571 /// Determine if the template parameter \p D has a visible default argument.
9572 bool
9574 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9575 /// Determine if the template parameter \p D has a reachable default argument.
9577 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9578 /// Determine if the template parameter \p D has a reachable default argument.
9582
9583 /// Determine if there is a visible declaration of \p D that is an explicit
9584 /// specialization declaration for a specialization of a template. (For a
9585 /// member specialization, use hasVisibleMemberSpecialization.)
9587 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9588 /// Determine if there is a reachable declaration of \p D that is an explicit
9589 /// specialization declaration for a specialization of a template. (For a
9590 /// member specialization, use hasReachableMemberSpecialization.)
9592 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9593
9594 /// Determine if there is a visible declaration of \p D that is a member
9595 /// specialization declaration (as opposed to an instantiated declaration).
9597 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9598 /// Determine if there is a reachable declaration of \p D that is a member
9599 /// specialization declaration (as opposed to an instantiated declaration).
9601 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9602
9603 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9604
9605 /// Determine whether any declaration of an entity is visible.
9606 bool
9608 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9609 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9610 }
9611
9614 /// Determine whether any declaration of an entity is reachable.
9615 bool
9617 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9618 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9619 }
9621 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9622
9623 void diagnoseTypo(const TypoCorrection &Correction,
9624 const PartialDiagnostic &TypoDiag,
9625 bool ErrorRecovery = true);
9626
9627 /// Diagnose a successfully-corrected typo. Separated from the correction
9628 /// itself to allow external validation of the result, etc.
9629 ///
9630 /// \param Correction The result of performing typo correction.
9631 /// \param TypoDiag The diagnostic to produce. This will have the corrected
9632 /// string added to it (and usually also a fixit).
9633 /// \param PrevNote A note to use when indicating the location of the entity
9634 /// to which we are correcting. Will have the correction string added
9635 /// to it.
9636 /// \param ErrorRecovery If \c true (the default), the caller is going to
9637 /// recover from the typo as if the corrected string had been typed.
9638 /// In this case, \c PDiag must be an error, and we will attach a fixit
9639 /// to it.
9640 void diagnoseTypo(const TypoCorrection &Correction,
9641 const PartialDiagnostic &TypoDiag,
9642 const PartialDiagnostic &PrevNote,
9643 bool ErrorRecovery = true);
9644
9645 /// Find the associated classes and namespaces for
9646 /// argument-dependent lookup for a call with the given set of
9647 /// arguments.
9648 ///
9649 /// This routine computes the sets of associated classes and associated
9650 /// namespaces searched by argument-dependent lookup
9651 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9653 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9654 AssociatedNamespaceSet &AssociatedNamespaces,
9655 AssociatedClassSet &AssociatedClasses);
9656
9657 /// Produce a diagnostic describing the ambiguity that resulted
9658 /// from name lookup.
9659 ///
9660 /// \param Result The result of the ambiguous lookup to be diagnosed.
9662
9663 /// LookupLiteralOperator - Determine which literal operator should be used
9664 /// for a user-defined literal, per C++11 [lex.ext].
9665 ///
9666 /// Normal overload resolution is not used to select which literal operator to
9667 /// call for a user-defined literal. Look up the provided literal operator
9668 /// name, and filter the results to the appropriate set for the given argument
9669 /// types.
9672 bool AllowRaw, bool AllowTemplate,
9673 bool AllowStringTemplate, bool DiagnoseMissing,
9674 StringLiteral *StringLit = nullptr);
9675
9677 ArrayRef<Expr *> Args, ADLResult &Functions);
9678
9679 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9681 bool IncludeGlobalScope = true,
9682 bool LoadExternal = true);
9683 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9685 bool IncludeGlobalScope = true,
9686 bool IncludeDependentBases = false,
9687 bool LoadExternal = true);
9688
9689 /// Try to "correct" a typo in the source code by finding
9690 /// visible declarations whose names are similar to the name that was
9691 /// present in the source code.
9692 ///
9693 /// \param TypoName the \c DeclarationNameInfo structure that contains
9694 /// the name that was present in the source code along with its location.
9695 ///
9696 /// \param LookupKind the name-lookup criteria used to search for the name.
9697 ///
9698 /// \param S the scope in which name lookup occurs.
9699 ///
9700 /// \param SS the nested-name-specifier that precedes the name we're
9701 /// looking for, if present.
9702 ///
9703 /// \param CCC A CorrectionCandidateCallback object that provides further
9704 /// validation of typo correction candidates. It also provides flags for
9705 /// determining the set of keywords permitted.
9706 ///
9707 /// \param MemberContext if non-NULL, the context in which to look for
9708 /// a member access expression.
9709 ///
9710 /// \param EnteringContext whether we're entering the context described by
9711 /// the nested-name-specifier SS.
9712 ///
9713 /// \param OPT when non-NULL, the search for visible declarations will
9714 /// also walk the protocols in the qualified interfaces of \p OPT.
9715 ///
9716 /// \returns a \c TypoCorrection containing the corrected name if the typo
9717 /// along with information such as the \c NamedDecl where the corrected name
9718 /// was declared, and any additional \c NestedNameSpecifier needed to access
9719 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9721 Sema::LookupNameKind LookupKind, Scope *S,
9723 CorrectTypoKind Mode,
9724 DeclContext *MemberContext = nullptr,
9725 bool EnteringContext = false,
9726 const ObjCObjectPointerType *OPT = nullptr,
9727 bool RecordFailure = true);
9728
9729 /// Kinds of missing import. Note, the values of these enumerators correspond
9730 /// to %select values in diagnostics.
9738
9739 /// Diagnose that the specified declaration needs to be visible but
9740 /// isn't, and suggest a module import that would resolve the problem.
9742 MissingImportKind MIK, bool Recover = true);
9744 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
9745 MissingImportKind MIK, bool Recover);
9746
9747 /// Called on #pragma clang __debug dump II
9749
9750 /// Called on #pragma clang __debug dump E
9751 void ActOnPragmaDump(Expr *E);
9752
9753private:
9754 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
9755 //
9756 // The boolean value will be true to indicate that the namespace was loaded
9757 // from an AST/PCH file, or false otherwise.
9758 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
9759
9760 /// Whether we have already loaded known namespaces from an extenal
9761 /// source.
9762 bool LoadedExternalKnownNamespaces;
9763
9764 bool CppLookupName(LookupResult &R, Scope *S);
9765
9766 /// Determine if we could use all the declarations in the module.
9767 bool isUsableModule(const Module *M);
9768
9769 /// Helper for CorrectTypo used to create and populate a new
9770 /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
9771 /// skipped entirely.
9772 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
9773 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
9775 DeclContext *MemberContext, bool EnteringContext,
9776 const ObjCObjectPointerType *OPT, bool ErrorRecovery);
9777
9778 /// Cache for module units which is usable for current module.
9779 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
9780
9781 /// Record the typo correction failure and return an empty correction.
9782 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
9783 bool RecordFailure = true) {
9784 if (RecordFailure)
9785 TypoCorrectionFailures[Typo].insert(TypoLoc);
9786 return TypoCorrection();
9787 }
9788
9789 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
9790
9791 /// Determine whether two declarations should be linked together, given that
9792 /// the old declaration might not be visible and the new declaration might
9793 /// not have external linkage.
9794 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
9795 const NamedDecl *New) {
9796 if (isVisible(Old))
9797 return true;
9798 // See comment in below overload for why it's safe to compute the linkage
9799 // of the new declaration here.
9800 if (New->isExternallyDeclarable()) {
9801 assert(Old->isExternallyDeclarable() &&
9802 "should not have found a non-externally-declarable previous decl");
9803 return true;
9804 }
9805 return false;
9806 }
9807 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
9808
9809 ///@}
9810
9811 //
9812 //
9813 // -------------------------------------------------------------------------
9814 //
9815 //
9816
9817 /// \name Modules
9818 /// Implementations are in SemaModule.cpp
9819 ///@{
9820
9821public:
9822 /// Get the module unit whose scope we are currently within.
9824 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
9825 }
9826
9827 /// Is the module scope we are an implementation unit?
9829 return ModuleScopes.empty()
9830 ? false
9831 : ModuleScopes.back().Module->isModuleImplementation();
9832 }
9833
9834 // When loading a non-modular PCH files, this is used to restore module
9835 // visibility.
9837 VisibleModules.setVisible(Mod, ImportLoc);
9838 }
9839
9840 enum class ModuleDeclKind {
9841 Interface, ///< 'export module X;'
9842 Implementation, ///< 'module X;'
9843 PartitionInterface, ///< 'export module X:Y;'
9844 PartitionImplementation, ///< 'module X:Y;'
9845 };
9846
9847 /// An enumeration to represent the transition of states in parsing module
9848 /// fragments and imports. If we are not parsing a C++20 TU, or we find
9849 /// an error in state transition, the state is set to NotACXX20Module.
9851 FirstDecl, ///< Parsing the first decl in a TU.
9852 GlobalFragment, ///< after 'module;' but before 'module X;'
9853 ImportAllowed, ///< after 'module X;' but before any non-import decl.
9854 ImportFinished, ///< after any non-import decl.
9855 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
9856 ///< non-import decl.
9857 PrivateFragmentImportFinished, ///< after 'module :private;' but a
9858 ///< non-import decl has already been seen.
9859 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
9860 };
9861
9862 /// The parser has processed a module-declaration that begins the definition
9863 /// of a module interface or implementation.
9865 SourceLocation ModuleLoc, ModuleDeclKind MDK,
9866 ModuleIdPath Path, ModuleIdPath Partition,
9867 ModuleImportState &ImportState,
9868 bool SeenNoTrivialPPDirective);
9869
9870 /// The parser has processed a global-module-fragment declaration that begins
9871 /// the definition of the global module fragment of the current module unit.
9872 /// \param ModuleLoc The location of the 'module' keyword.
9874
9875 /// The parser has processed a private-module-fragment declaration that begins
9876 /// the definition of the private module fragment of the current module unit.
9877 /// \param ModuleLoc The location of the 'module' keyword.
9878 /// \param PrivateLoc The location of the 'private' keyword.
9880 SourceLocation PrivateLoc);
9881
9882 /// The parser has processed a module import declaration.
9883 ///
9884 /// \param StartLoc The location of the first token in the declaration. This
9885 /// could be the location of an '@', 'export', or 'import'.
9886 /// \param ExportLoc The location of the 'export' keyword, if any.
9887 /// \param ImportLoc The location of the 'import' keyword.
9888 /// \param Path The module toplevel name as an access path.
9889 /// \param IsPartition If the name is for a partition.
9891 SourceLocation ExportLoc,
9892 SourceLocation ImportLoc, ModuleIdPath Path,
9893 bool IsPartition = false);
9895 SourceLocation ExportLoc,
9896 SourceLocation ImportLoc, Module *M,
9897 ModuleIdPath Path = {});
9898
9899 /// The parser has processed a module import translated from a
9900 /// #include or similar preprocessing directive.
9901 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
9902 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
9903
9904 /// The parsed has entered a submodule.
9905 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
9906 /// The parser has left a submodule.
9907 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
9908
9909 /// Create an implicit import of the given module at the given
9910 /// source location, for error recovery, if possible.
9911 ///
9912 /// This routine is typically used when an entity found by name lookup
9913 /// is actually hidden within a module that we know about but the user
9914 /// has forgotten to import.
9915 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
9916 Module *Mod);
9917
9918 /// We have parsed the start of an export declaration, including the '{'
9919 /// (if present).
9920 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
9921 SourceLocation LBraceLoc);
9922
9923 /// Complete the definition of an export declaration.
9924 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
9925 SourceLocation RBraceLoc);
9926
9927private:
9928 /// The parser has begun a translation unit to be compiled as a C++20
9929 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
9930 void HandleStartOfHeaderUnit();
9931
9932 struct ModuleScope {
9933 SourceLocation BeginLoc;
9934 clang::Module *Module = nullptr;
9935 VisibleModuleSet OuterVisibleModules;
9936 };
9937 /// The modules we're currently parsing.
9938 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
9939
9940 /// For an interface unit, this is the implicitly imported interface unit.
9941 clang::Module *ThePrimaryInterface = nullptr;
9942
9943 /// The explicit global module fragment of the current translation unit.
9944 /// The explicit Global Module Fragment, as specified in C++
9945 /// [module.global.frag].
9946 clang::Module *TheGlobalModuleFragment = nullptr;
9947
9948 /// The implicit global module fragments of the current translation unit.
9949 ///
9950 /// The contents in the implicit global module fragment can't be discarded.
9951 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
9952
9953 /// Namespace definitions that we will export when they finish.
9954 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
9955
9956 /// In a C++ standard module, inline declarations require a definition to be
9957 /// present at the end of a definition domain. This set holds the decls to
9958 /// be checked at the end of the TU.
9959 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
9960
9961 /// Helper function to judge if we are in module purview.
9962 /// Return false if we are not in a module.
9963 bool isCurrentModulePurview() const;
9964
9965 /// Enter the scope of the explicit global module fragment.
9966 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
9967 /// Leave the scope of the explicit global module fragment.
9968 void PopGlobalModuleFragment();
9969
9970 /// Enter the scope of an implicit global module fragment.
9971 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
9972 /// Leave the scope of an implicit global module fragment.
9973 void PopImplicitGlobalModuleFragment();
9974
9975 VisibleModuleSet VisibleModules;
9976
9977 /// Whether we had imported any named modules.
9978 bool HadImportedNamedModules = false;
9979 /// The set of instantiations we need to check if they references TU-local
9980 /// entity from TUs. This only makes sense if we imported any named modules.
9981 llvm::SmallVector<std::pair<FunctionDecl *, SourceLocation>>
9982 PendingCheckReferenceForTULocal;
9983 /// Implement [basic.link]p18, which requires that we can't use TU-local
9984 /// entities from other TUs (ignoring header units).
9985 void checkReferenceToTULocalFromOtherTU(FunctionDecl *FD,
9986 SourceLocation PointOfInstantiation);
9987 /// Implement [basic.link]p17, which diagnose for non TU local exposure in
9988 /// module interface or module partition.
9989 void checkExposure(const TranslationUnitDecl *TU);
9990
9991 ///@}
9992
9993 //
9994 //
9995 // -------------------------------------------------------------------------
9996 //
9997 //
9998
9999 /// \name C++ Overloading
10000 /// Implementations are in SemaOverload.cpp
10001 ///@{
10002
10003public:
10004 /// Whether deferrable diagnostics should be deferred.
10005 bool DeferDiags = false;
10006
10007 /// RAII class to control scope of DeferDiags.
10009 Sema &S;
10010 bool SavedDeferDiags = false;
10011
10012 public:
10014 : S(S), SavedDeferDiags(S.DeferDiags) {
10015 S.DeferDiags = SavedDeferDiags || DeferDiags;
10016 }
10017 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
10018 };
10019
10020 /// Flag indicating if Sema is building a recovery call expression.
10021 ///
10022 /// This flag is used to avoid building recovery call expressions
10023 /// if Sema is already doing so, which would cause infinite recursions.
10025
10026 /// Determine whether the given New declaration is an overload of the
10027 /// declarations in Old. This routine returns OverloadKind::Match or
10028 /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
10029 /// New has the same signature as some function in Old (C++ 1.3.10) or if the
10030 /// Old declarations aren't functions (or function templates) at all. When it
10031 /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
10032 /// will point to the decl that New cannot be overloaded with. This decl may
10033 /// be a UsingShadowDecl on top of the underlying declaration.
10034 ///
10035 /// Example: Given the following input:
10036 ///
10037 /// void f(int, float); // #1
10038 /// void f(int, int); // #2
10039 /// int f(int, int); // #3
10040 ///
10041 /// When we process #1, there is no previous declaration of "f", so IsOverload
10042 /// will not be used.
10043 ///
10044 /// When we process #2, Old contains only the FunctionDecl for #1. By
10045 /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10046 /// they have different signatures), so this routine returns
10047 /// OverloadKind::Overload; MatchedDecl is unchanged.
10048 ///
10049 /// When we process #3, Old is an overload set containing #1 and #2. We
10050 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10051 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10052 /// types of functions are not part of the signature), IsOverload returns
10053 /// OverloadKind::Match and MatchedDecl will be set to point to the
10054 /// FunctionDecl for #2.
10055 ///
10056 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10057 /// class by a using declaration. The rules for whether to hide shadow
10058 /// declarations ignore some properties which otherwise figure into a function
10059 /// template's signature.
10061 const LookupResult &OldDecls, NamedDecl *&OldDecl,
10062 bool UseMemberUsingDeclRules);
10064 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10065
10066 // Checks whether MD constitutes an override the base class method BaseMD.
10067 // When checking for overrides, the object object members are ignored.
10068 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10069 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10070
10071 enum class AllowedExplicit {
10072 /// Allow no explicit functions to be used.
10074 /// Allow explicit conversion functions but not explicit constructors.
10076 /// Allow both explicit conversion functions and explicit constructors.
10078 };
10079
10081 Expr *From, QualType ToType, bool SuppressUserConversions,
10082 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10083 bool AllowObjCWritebackConversion);
10084
10085 /// PerformImplicitConversion - Perform an implicit conversion of the
10086 /// expression From to the type ToType. Returns the
10087 /// converted expression. Flavor is the kind of conversion we're
10088 /// performing, used in the error message. If @p AllowExplicit,
10089 /// explicit user-defined conversions are permitted.
10091 AssignmentAction Action,
10092 bool AllowExplicit = false);
10093
10094 /// IsIntegralPromotion - Determines whether the conversion from the
10095 /// expression From (whose potentially-adjusted type is FromType) to
10096 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10097 /// sets PromotedType to the promoted type.
10098 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10099
10100 /// IsFloatingPointPromotion - Determines whether the conversion from
10101 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10102 /// returns true and sets PromotedType to the promoted type.
10103 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10104
10105 /// Determine if a conversion is a complex promotion.
10106 ///
10107 /// A complex promotion is defined as a complex -> complex conversion
10108 /// where the conversion between the underlying real types is a
10109 /// floating-point or integral promotion.
10110 bool IsComplexPromotion(QualType FromType, QualType ToType);
10111
10112 /// IsPointerConversion - Determines whether the conversion of the
10113 /// expression From, which has the (possibly adjusted) type FromType,
10114 /// can be converted to the type ToType via a pointer conversion (C++
10115 /// 4.10). If so, returns true and places the converted type (that
10116 /// might differ from ToType in its cv-qualifiers at some level) into
10117 /// ConvertedType.
10118 ///
10119 /// This routine also supports conversions to and from block pointers
10120 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10121 /// pointers to interfaces. FIXME: Once we've determined the
10122 /// appropriate overloading rules for Objective-C, we may want to
10123 /// split the Objective-C checks into a different routine; however,
10124 /// GCC seems to consider all of these conversions to be pointer
10125 /// conversions, so for now they live here. IncompatibleObjC will be
10126 /// set if the conversion is an allowed Objective-C conversion that
10127 /// should result in a warning.
10128 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10129 bool InOverloadResolution, QualType &ConvertedType,
10130 bool &IncompatibleObjC);
10131
10132 /// isObjCPointerConversion - Determines whether this is an
10133 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10134 /// with the same arguments and return values.
10135 bool isObjCPointerConversion(QualType FromType, QualType ToType,
10136 QualType &ConvertedType, bool &IncompatibleObjC);
10137 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10138 QualType &ConvertedType);
10139
10140 /// FunctionParamTypesAreEqual - This routine checks two function proto types
10141 /// for equality of their parameter types. Caller has already checked that
10142 /// they have same number of parameters. If the parameters are different,
10143 /// ArgPos will have the parameter index of the first different parameter.
10144 /// If `Reversed` is true, the parameters of `NewType` will be compared in
10145 /// reverse order. That's useful if one of the functions is being used as a
10146 /// C++20 synthesized operator overload with a reversed parameter order.
10149 unsigned *ArgPos = nullptr,
10150 bool Reversed = false);
10151
10153 const FunctionProtoType *NewType,
10154 unsigned *ArgPos = nullptr,
10155 bool Reversed = false);
10156
10157 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10158 const FunctionDecl *NewFunction,
10159 unsigned *ArgPos = nullptr,
10160 bool Reversed = false);
10161
10162 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10163 /// function types. Catches different number of parameter, mismatch in
10164 /// parameter types, and different return types.
10166 QualType ToType);
10167
10168 /// CheckPointerConversion - Check the pointer conversion from the
10169 /// expression From to the type ToType. This routine checks for
10170 /// ambiguous or inaccessible derived-to-base pointer
10171 /// conversions for which IsPointerConversion has already returned
10172 /// true. It returns true and produces a diagnostic if there was an
10173 /// error, or returns false otherwise.
10174 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10175 CXXCastPath &BasePath, bool IgnoreBaseAccess,
10176 bool Diagnose = true);
10177
10178 /// IsMemberPointerConversion - Determines whether the conversion of the
10179 /// expression From, which has the (possibly adjusted) type FromType, can be
10180 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10181 /// If so, returns true and places the converted type (that might differ from
10182 /// ToType in its cv-qualifiers at some level) into ConvertedType.
10183 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10184 bool InOverloadResolution,
10185 QualType &ConvertedType);
10186
10196 /// CheckMemberPointerConversion - Check the member pointer conversion from
10197 /// the expression From to the type ToType. This routine checks for ambiguous
10198 /// or virtual or inaccessible base-to-derived member pointer conversions for
10199 /// which IsMemberPointerConversion has already returned true. It produces a
10200 // diagnostic if there was an error.
10202 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10203 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10204 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10205
10206 /// IsQualificationConversion - Determines whether the conversion from
10207 /// an rvalue of type FromType to ToType is a qualification conversion
10208 /// (C++ 4.4).
10209 ///
10210 /// \param ObjCLifetimeConversion Output parameter that will be set to
10211 /// indicate when the qualification conversion involves a change in the
10212 /// Objective-C object lifetime.
10213 bool IsQualificationConversion(QualType FromType, QualType ToType,
10214 bool CStyle, bool &ObjCLifetimeConversion);
10215
10216 /// Determine whether the conversion from FromType to ToType is a valid
10217 /// conversion of ExtInfo/ExtProtoInfo on the nested function type.
10218 /// More precisely, this method checks whether FromType can be transformed
10219 /// into an exact match for ToType, by transforming its extended function
10220 /// type information in legal manner (e.g. by strictly stripping "noreturn"
10221 /// or "noexcept", or by stripping "noescape" for arguments).
10222 bool IsFunctionConversion(QualType FromType, QualType ToType) const;
10223
10224 /// Same as `IsFunctionConversion`, but if this would return true, it sets
10225 /// `ResultTy` to `ToType`.
10226 bool TryFunctionConversion(QualType FromType, QualType ToType,
10227 QualType &ResultTy) const;
10228
10231 DeclarationName Name,
10232 OverloadCandidateSet &CandidateSet,
10233 FunctionDecl *Fn, MultiExprArg Args,
10234 bool IsMember = false);
10235
10237 FunctionDecl *Fun);
10239 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
10241
10242 /// PerformContextuallyConvertToBool - Perform a contextual conversion
10243 /// of the expression From to bool (C++0x [conv]p3).
10245
10246 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10247 /// conversion of the expression From to an Objective-C pointer type.
10248 /// Returns a valid but null ExprResult if no conversion sequence exists.
10250
10252 CCEKind CCE,
10253 NamedDecl *Dest = nullptr);
10254
10256 llvm::APSInt &Value, CCEKind CCE);
10258 APValue &Value, CCEKind CCE,
10259 NamedDecl *Dest = nullptr);
10260
10261 /// EvaluateConvertedConstantExpression - Evaluate an Expression
10262 /// That is a converted constant expression
10263 /// (which was built with BuildConvertedConstantExpression)
10266 CCEKind CCE, bool RequireInt,
10267 const APValue &PreNarrowingValue);
10268
10269 /// Abstract base class used to perform a contextual implicit
10270 /// conversion from an expression to any type passing a filter.
10272 public:
10275
10279
10280 /// Determine whether the specified type is a valid destination type
10281 /// for this conversion.
10282 virtual bool match(QualType T) = 0;
10283
10284 /// Emits a diagnostic complaining that the expression does not have
10285 /// integral or enumeration type.
10287 QualType T) = 0;
10288
10289 /// Emits a diagnostic when the expression has incomplete class type.
10290 virtual SemaDiagnosticBuilder
10292
10293 /// Emits a diagnostic when the only matching conversion function
10294 /// is explicit.
10296 SourceLocation Loc,
10297 QualType T,
10298 QualType ConvTy) = 0;
10299
10300 /// Emits a note for the explicit conversion function.
10301 virtual SemaDiagnosticBuilder
10303
10304 /// Emits a diagnostic when there are multiple possible conversion
10305 /// functions.
10307 QualType T) = 0;
10308
10309 /// Emits a note for one of the candidate conversions.
10310 virtual SemaDiagnosticBuilder
10312
10313 /// Emits a diagnostic when we picked a conversion function
10314 /// (for cases when we are not allowed to pick a conversion function).
10316 SourceLocation Loc,
10317 QualType T,
10318 QualType ConvTy) = 0;
10319
10321 };
10322
10324 bool AllowScopedEnumerations;
10325
10326 public:
10327 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10328 bool SuppressConversion)
10330 AllowScopedEnumerations(AllowScopedEnumerations) {}
10331
10332 /// Match an integral or (possibly scoped) enumeration type.
10333 bool match(QualType T) override;
10334
10336 QualType T) override {
10337 return diagnoseNotInt(S, Loc, T);
10338 }
10339
10340 /// Emits a diagnostic complaining that the expression does not have
10341 /// integral or enumeration type.
10343 QualType T) = 0;
10344 };
10345
10346 /// Perform a contextual implicit conversion.
10349 ContextualImplicitConverter &Converter);
10350
10351 /// ReferenceCompareResult - Expresses the result of comparing two
10352 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10353 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10355 /// Ref_Incompatible - The two types are incompatible, so direct
10356 /// reference binding is not possible.
10358 /// Ref_Related - The two types are reference-related, which means
10359 /// that their unqualified forms (T1 and T2) are either the same
10360 /// or T1 is a base class of T2.
10362 /// Ref_Compatible - The two types are reference-compatible.
10364 };
10365
10366 // Fake up a scoped enumeration that still contextually converts to bool.
10368 /// The conversions that would be performed on an lvalue of type T2 when
10369 /// binding a reference of type T1 to it, as determined when evaluating
10370 /// whether T1 is reference-compatible with T2.
10381 };
10383
10384 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10385 /// determine whether they are reference-compatible,
10386 /// reference-related, or incompatible, for use in C++ initialization by
10387 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10388 /// type, and the first type (T1) is the pointee type of the reference
10389 /// type being initialized.
10392 ReferenceConversions *Conv = nullptr);
10393
10394 /// AddOverloadCandidate - Adds the given function to the set of
10395 /// candidate functions, using the given function call arguments. If
10396 /// @p SuppressUserConversions, then don't allow user-defined
10397 /// conversions via constructors or conversion operators.
10398 ///
10399 /// \param PartialOverloading true if we are performing "partial" overloading
10400 /// based on an incomplete set of function arguments. This feature is used by
10401 /// code completion.
10404 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10405 bool PartialOverloading = false, bool AllowExplicit = true,
10406 bool AllowExplicitConversion = false,
10407 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10408 ConversionSequenceList EarlyConversions = {},
10410 bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10411
10412 /// Add all of the function declarations in the given function set to
10413 /// the overload candidate set.
10415 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10416 OverloadCandidateSet &CandidateSet,
10417 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10418 bool SuppressUserConversions = false, bool PartialOverloading = false,
10419 bool FirstArgumentIsBase = false);
10420
10421 /// AddMethodCandidate - Adds a named decl (which is some kind of
10422 /// method) as a method candidate to the given overload set.
10423 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10424 Expr::Classification ObjectClassification,
10425 ArrayRef<Expr *> Args,
10426 OverloadCandidateSet &CandidateSet,
10427 bool SuppressUserConversion = false,
10428 OverloadCandidateParamOrder PO = {});
10429
10430 /// AddMethodCandidate - Adds the given C++ member function to the set
10431 /// of candidate functions, using the given function call arguments
10432 /// and the object argument (@c Object). For example, in a call
10433 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10434 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10435 /// allow user-defined conversions via constructors or conversion
10436 /// operators.
10437 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10438 CXXRecordDecl *ActingContext, QualType ObjectType,
10439 Expr::Classification ObjectClassification,
10440 ArrayRef<Expr *> Args,
10441 OverloadCandidateSet &CandidateSet,
10442 bool SuppressUserConversions = false,
10443 bool PartialOverloading = false,
10444 ConversionSequenceList EarlyConversions = {},
10446 bool StrictPackMatch = false);
10447
10448 /// Add a C++ member function template as a candidate to the candidate
10449 /// set, using template argument deduction to produce an appropriate member
10450 /// function template specialization.
10452 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10453 CXXRecordDecl *ActingContext,
10454 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10455 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10456 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10457 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10458
10459 /// Add a C++ function template specialization as a candidate
10460 /// in the candidate set, using template argument deduction to produce
10461 /// an appropriate function template specialization.
10463 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10464 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10465 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10466 bool PartialOverloading = false, bool AllowExplicit = true,
10467 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10469 bool AggregateCandidateDeduction = false);
10470
10472 /// Do not consider any user-defined conversions when constructing the
10473 /// initializing sequence.
10475
10476 /// Before constructing the initializing sequence, we check whether the
10477 /// parameter type and argument type contain any user defined conversions.
10478 /// If so, do not initialize them. This effectively bypasses some undesired
10479 /// instantiation before checking constaints, which might otherwise result
10480 /// in non-SFINAE errors e.g. recursive constraints.
10482
10489 };
10490
10491 /// Check that implicit conversion sequences can be formed for each argument
10492 /// whose corresponding parameter has a non-dependent type, per DR1391's
10493 /// [temp.deduct.call]p10.
10496 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10498 CheckNonDependentConversionsFlag UserConversionFlag,
10499 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10500 Expr::Classification ObjectClassification = {},
10501 OverloadCandidateParamOrder PO = {});
10502
10503 /// AddConversionCandidate - Add a C++ conversion function as a
10504 /// candidate in the candidate set (C++ [over.match.conv],
10505 /// C++ [over.match.copy]). From is the expression we're converting from,
10506 /// and ToType is the type that we're eventually trying to convert to
10507 /// (which may or may not be the same type as the type that the
10508 /// conversion function produces).
10510 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10511 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10512 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10513 bool AllowExplicit, bool AllowResultConversion = true,
10514 bool StrictPackMatch = false);
10515
10516 /// Adds a conversion function template specialization
10517 /// candidate to the overload set, using template argument deduction
10518 /// to deduce the template arguments of the conversion function
10519 /// template from the type that we are converting to (C++
10520 /// [temp.deduct.conv]).
10522 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10523 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10524 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10525 bool AllowExplicit, bool AllowResultConversion = true);
10526
10527 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10528 /// converts the given @c Object to a function pointer via the
10529 /// conversion function @c Conversion, and then attempts to call it
10530 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10531 /// the type of function that we'll eventually be calling.
10532 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10533 DeclAccessPair FoundDecl,
10534 CXXRecordDecl *ActingContext,
10535 const FunctionProtoType *Proto, Expr *Object,
10536 ArrayRef<Expr *> Args,
10537 OverloadCandidateSet &CandidateSet);
10538
10539 /// Add all of the non-member operator function declarations in the given
10540 /// function set to the overload candidate set.
10542 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10543 OverloadCandidateSet &CandidateSet,
10544 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10545
10546 /// Add overload candidates for overloaded operators that are
10547 /// member functions.
10548 ///
10549 /// Add the overloaded operator candidates that are member functions
10550 /// for the operator Op that was used in an operator expression such
10551 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10552 /// CandidateSet will store the added overload candidates. (C++
10553 /// [over.match.oper]).
10555 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10556 OverloadCandidateSet &CandidateSet,
10558
10559 /// AddBuiltinCandidate - Add a candidate for a built-in
10560 /// operator. ResultTy and ParamTys are the result and parameter types
10561 /// of the built-in candidate, respectively. Args and NumArgs are the
10562 /// arguments being passed to the candidate. IsAssignmentOperator
10563 /// should be true when this built-in candidate is an assignment
10564 /// operator. NumContextualBoolArguments is the number of arguments
10565 /// (at the beginning of the argument list) that will be contextually
10566 /// converted to bool.
10567 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10568 OverloadCandidateSet &CandidateSet,
10569 bool IsAssignmentOperator = false,
10570 unsigned NumContextualBoolArguments = 0);
10571
10572 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10573 /// operator overloads to the candidate set (C++ [over.built]), based
10574 /// on the operator @p Op and the arguments given. For example, if the
10575 /// operator is a binary '+', this routine might add "int
10576 /// operator+(int, int)" to cover integer addition.
10578 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10579 OverloadCandidateSet &CandidateSet);
10580
10581 /// Add function candidates found via argument-dependent lookup
10582 /// to the set of overloading candidates.
10583 ///
10584 /// This routine performs argument-dependent name lookup based on the
10585 /// given function name (which may also be an operator name) and adds
10586 /// all of the overload candidates found by ADL to the overload
10587 /// candidate set (C++ [basic.lookup.argdep]).
10589 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10590 TemplateArgumentListInfo *ExplicitTemplateArgs,
10591 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10592
10593 /// Check the enable_if expressions on the given function. Returns the first
10594 /// failing attribute, or NULL if they were all successful.
10595 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10596 ArrayRef<Expr *> Args,
10597 bool MissingImplicitThis = false);
10598
10599 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10600 /// non-ArgDependent DiagnoseIfAttrs.
10601 ///
10602 /// Argument-dependent diagnose_if attributes should be checked each time a
10603 /// function is used as a direct callee of a function call.
10604 ///
10605 /// Returns true if any errors were emitted.
10606 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10607 const Expr *ThisArg,
10608 ArrayRef<const Expr *> Args,
10609 SourceLocation Loc);
10610
10611 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10612 /// ArgDependent DiagnoseIfAttrs.
10613 ///
10614 /// Argument-independent diagnose_if attributes should be checked on every use
10615 /// of a function.
10616 ///
10617 /// Returns true if any errors were emitted.
10618 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10619 SourceLocation Loc);
10620
10621 /// Determine if \p A and \p B are equivalent internal linkage declarations
10622 /// from different modules, and thus an ambiguity error can be downgraded to
10623 /// an extension warning.
10624 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10625 const NamedDecl *B);
10627 SourceLocation Loc, const NamedDecl *D,
10628 ArrayRef<const NamedDecl *> Equiv);
10629
10630 // Emit as a 'note' the specific overload candidate
10632 const NamedDecl *Found, const FunctionDecl *Fn,
10634 QualType DestType = QualType(), bool TakingAddress = false);
10635
10636 // Emit as a series of 'note's all template and non-templates identified by
10637 // the expression Expr
10638 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10639 bool TakingAddress = false);
10640
10641 /// Returns whether the given function's address can be taken or not,
10642 /// optionally emitting a diagnostic if the address can't be taken.
10643 ///
10644 /// Returns false if taking the address of the function is illegal.
10645 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10646 bool Complain = false,
10647 SourceLocation Loc = SourceLocation());
10648
10649 // [PossiblyAFunctionType] --> [Return]
10650 // NonFunctionType --> NonFunctionType
10651 // R (A) --> R(A)
10652 // R (*)(A) --> R (A)
10653 // R (&)(A) --> R (A)
10654 // R (S::*)(A) --> R (A)
10655 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10656
10657 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10658 /// an overloaded function (C++ [over.over]), where @p From is an
10659 /// expression with overloaded function type and @p ToType is the type
10660 /// we're trying to resolve to. For example:
10661 ///
10662 /// @code
10663 /// int f(double);
10664 /// int f(int);
10665 ///
10666 /// int (*pfd)(double) = f; // selects f(double)
10667 /// @endcode
10668 ///
10669 /// This routine returns the resulting FunctionDecl if it could be
10670 /// resolved, and NULL otherwise. When @p Complain is true, this
10671 /// routine will emit diagnostics if there is an error.
10672 FunctionDecl *
10673 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10674 bool Complain, DeclAccessPair &Found,
10675 bool *pHadMultipleCandidates = nullptr);
10676
10677 /// Given an expression that refers to an overloaded function, try to
10678 /// resolve that function to a single function that can have its address
10679 /// taken. This will modify `Pair` iff it returns non-null.
10680 ///
10681 /// This routine can only succeed if from all of the candidates in the
10682 /// overload set for SrcExpr that can have their addresses taken, there is one
10683 /// candidate that is more constrained than the rest.
10684 FunctionDecl *
10685 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10686
10687 /// Given an overloaded function, tries to turn it into a non-overloaded
10688 /// function reference using resolveAddressOfSingleOverloadCandidate. This
10689 /// will perform access checks, diagnose the use of the resultant decl, and,
10690 /// if requested, potentially perform a function-to-pointer decay.
10691 ///
10692 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10693 /// Otherwise, returns true. This may emit diagnostics and return true.
10695 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10696
10697 /// Given an expression that refers to an overloaded function, try to
10698 /// resolve that overloaded function expression down to a single function.
10699 ///
10700 /// This routine can only resolve template-ids that refer to a single function
10701 /// template, where that template-id refers to a single template whose
10702 /// template arguments are either provided by the template-id or have
10703 /// defaults, as described in C++0x [temp.arg.explicit]p3.
10704 ///
10705 /// If no template-ids are found, no diagnostics are emitted and NULL is
10706 /// returned.
10708 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10709 TemplateSpecCandidateSet *FailedTSC = nullptr,
10710 bool ForTypeDeduction = false);
10711
10712 // Resolve and fix an overloaded expression that can be resolved
10713 // because it identifies a single function template specialization.
10714 //
10715 // Last three arguments should only be supplied if Complain = true
10716 //
10717 // Return true if it was logically possible to so resolve the
10718 // expression, regardless of whether or not it succeeded. Always
10719 // returns true if 'complain' is set.
10721 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10722 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10723 QualType DestTypeForComplaining = QualType(),
10724 unsigned DiagIDForComplaining = 0);
10725
10726 /// Add the overload candidates named by callee and/or found by argument
10727 /// dependent lookup to the given overload set.
10728 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10729 ArrayRef<Expr *> Args,
10730 OverloadCandidateSet &CandidateSet,
10731 bool PartialOverloading = false);
10732
10733 /// Add the call candidates from the given set of lookup results to the given
10734 /// overload set. Non-function lookup results are ignored.
10736 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
10737 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
10738
10739 // An enum used to represent the different possible results of building a
10740 // range-based for loop.
10746
10747 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
10748 /// given LookupResult is non-empty, it is assumed to describe a member which
10749 /// will be invoked. Otherwise, the function will be found via argument
10750 /// dependent lookup.
10751 /// CallExpr is set to a valid expression and FRS_Success returned on success,
10752 /// otherwise CallExpr is set to ExprError() and some non-success value
10753 /// is returned.
10755 SourceLocation RangeLoc,
10756 const DeclarationNameInfo &NameInfo,
10757 LookupResult &MemberLookup,
10758 OverloadCandidateSet *CandidateSet,
10759 Expr *Range, ExprResult *CallExpr);
10760
10761 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10762 /// (which eventually refers to the declaration Func) and the call
10763 /// arguments Args/NumArgs, attempt to resolve the function call down
10764 /// to a specific function. If overload resolution succeeds, returns
10765 /// the call expression produced by overload resolution.
10766 /// Otherwise, emits diagnostics and returns ExprError.
10768 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
10769 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
10770 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
10771
10772 /// Constructs and populates an OverloadedCandidateSet from
10773 /// the given function.
10774 /// \returns true when an the ExprResult output parameter has been set.
10776 MultiExprArg Args, SourceLocation RParenLoc,
10777 OverloadCandidateSet *CandidateSet,
10779
10783 const UnresolvedSetImpl &Fns,
10784 bool PerformADL = true);
10785
10786 /// Create a unary operation that may resolve to an overloaded
10787 /// operator.
10788 ///
10789 /// \param OpLoc The location of the operator itself (e.g., '*').
10790 ///
10791 /// \param Opc The UnaryOperatorKind that describes this operator.
10792 ///
10793 /// \param Fns The set of non-member functions that will be
10794 /// considered by overload resolution. The caller needs to build this
10795 /// set based on the context using, e.g.,
10796 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10797 /// set should not contain any member functions; those will be added
10798 /// by CreateOverloadedUnaryOp().
10799 ///
10800 /// \param Input The input argument.
10803 const UnresolvedSetImpl &Fns, Expr *input,
10804 bool RequiresADL = true);
10805
10806 /// Perform lookup for an overloaded binary operator.
10809 const UnresolvedSetImpl &Fns,
10810 ArrayRef<Expr *> Args, bool RequiresADL = true);
10811
10812 /// Create a binary operation that may resolve to an overloaded
10813 /// operator.
10814 ///
10815 /// \param OpLoc The location of the operator itself (e.g., '+').
10816 ///
10817 /// \param Opc The BinaryOperatorKind that describes this operator.
10818 ///
10819 /// \param Fns The set of non-member functions that will be
10820 /// considered by overload resolution. The caller needs to build this
10821 /// set based on the context using, e.g.,
10822 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10823 /// set should not contain any member functions; those will be added
10824 /// by CreateOverloadedBinOp().
10825 ///
10826 /// \param LHS Left-hand argument.
10827 /// \param RHS Right-hand argument.
10828 /// \param PerformADL Whether to consider operator candidates found by ADL.
10829 /// \param AllowRewrittenCandidates Whether to consider candidates found by
10830 /// C++20 operator rewrites.
10831 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
10832 /// the function in question. Such a function is never a candidate in
10833 /// our overload resolution. This also enables synthesizing a three-way
10834 /// comparison from < and == as described in C++20 [class.spaceship]p1.
10836 const UnresolvedSetImpl &Fns, Expr *LHS,
10837 Expr *RHS, bool RequiresADL = true,
10838 bool AllowRewrittenCandidates = true,
10839 FunctionDecl *DefaultedFn = nullptr);
10841 const UnresolvedSetImpl &Fns,
10842 Expr *LHS, Expr *RHS,
10843 FunctionDecl *DefaultedFn);
10844
10846 SourceLocation RLoc, Expr *Base,
10847 MultiExprArg Args);
10848
10849 /// BuildCallToMemberFunction - Build a call to a member
10850 /// function. MemExpr is the expression that refers to the member
10851 /// function (and includes the object parameter), Args/NumArgs are the
10852 /// arguments to the function call (not including the object
10853 /// parameter). The caller needs to validate that the member
10854 /// expression refers to a non-static member function or an overloaded
10855 /// member function.
10857 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
10858 SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
10859 bool IsExecConfig = false, bool AllowRecovery = false);
10860
10861 /// BuildCallToObjectOfClassType - Build a call to an object of class
10862 /// type (C++ [over.call.object]), which can end up invoking an
10863 /// overloaded function call operator (@c operator()) or performing a
10864 /// user-defined conversion on the object argument.
10866 SourceLocation LParenLoc,
10867 MultiExprArg Args,
10868 SourceLocation RParenLoc);
10869
10870 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
10871 /// (if one exists), where @c Base is an expression of class type and
10872 /// @c Member is the name of the member we're trying to find.
10874 SourceLocation OpLoc,
10875 bool *NoArrowOperatorFound = nullptr);
10876
10879 bool HadMultipleCandidates);
10880
10881 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
10882 /// to a literal operator described by the provided lookup results.
10885 SourceLocation LitEndLoc,
10886 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10887
10888 /// FixOverloadedFunctionReference - E is an expression that refers to
10889 /// a C++ overloaded function (possibly with some parentheses and
10890 /// perhaps a '&' around it). We have resolved the overloaded function
10891 /// to the function declaration Fn, so patch up the expression E to
10892 /// refer (possibly indirectly) to Fn. Returns the new expr.
10894 FunctionDecl *Fn);
10896 DeclAccessPair FoundDecl,
10897 FunctionDecl *Fn);
10898
10899 /// - Returns a selector which best matches given argument list or
10900 /// nullptr if none could be found
10902 bool IsInstance,
10904
10905 ///@}
10906
10907 //
10908 //
10909 // -------------------------------------------------------------------------
10910 //
10911 //
10912
10913 /// \name Statements
10914 /// Implementations are in SemaStmt.cpp
10915 ///@{
10916
10917public:
10918 /// Stack of active SEH __finally scopes. Can be empty.
10920
10921 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
10923
10925 bool HasLeadingEmptyMacro = false);
10926
10928 SourceLocation EndLoc);
10930
10931 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
10932 /// whose result is unused, warn.
10933 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
10934
10935 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
10939 ArrayRef<Stmt *> Elts, bool isStmtExpr);
10940
10942
10945 SourceLocation DotDotDotLoc, ExprResult RHS,
10946 SourceLocation ColonLoc);
10947
10948 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
10949 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
10950
10952 SourceLocation ColonLoc, Stmt *SubStmt,
10953 Scope *CurScope);
10955 SourceLocation ColonLoc, Stmt *SubStmt);
10956
10958 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
10960 Stmt *SubStmt);
10961
10962 /// Check whether the given statement can have musttail applied to it,
10963 /// issuing a diagnostic and returning false if not. In the success case,
10964 /// the statement is rewritten to remove implicit nodes from the return
10965 /// value.
10966 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
10967
10969 SourceLocation LParenLoc, Stmt *InitStmt,
10971 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
10973 SourceLocation LParenLoc, Stmt *InitStmt,
10975 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
10976
10978
10980 SourceLocation LParenLoc, Stmt *InitStmt,
10982 SourceLocation RParenLoc);
10984 Stmt *Body);
10985
10986 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
10987 /// integer not in the range of enum values.
10988 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
10989 Expr *SrcExpr);
10990
10993 Stmt *Body);
10995 SourceLocation WhileLoc, SourceLocation CondLParen,
10996 Expr *Cond, SourceLocation CondRParen);
10997
10999 Stmt *First, ConditionResult Second,
11000 FullExprArg Third, SourceLocation RParenLoc,
11001 Stmt *Body);
11002
11003 /// In an Objective C collection iteration statement:
11004 /// for (x in y)
11005 /// x can be an arbitrary l-value expression. Bind it up as a
11006 /// full-expression.
11008
11010 /// Initial building of a for-range statement.
11012 /// Instantiation or recovery rebuild of a for-range statement. Don't
11013 /// attempt any typo-correction.
11015 /// Determining whether a for-range statement could be built. Avoid any
11016 /// unnecessary or irreversible actions.
11018 };
11019
11020 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
11021 ///
11022 /// C++11 [stmt.ranged]:
11023 /// A range-based for statement is equivalent to
11024 ///
11025 /// {
11026 /// auto && __range = range-init;
11027 /// for ( auto __begin = begin-expr,
11028 /// __end = end-expr;
11029 /// __begin != __end;
11030 /// ++__begin ) {
11031 /// for-range-declaration = *__begin;
11032 /// statement
11033 /// }
11034 /// }
11035 ///
11036 /// The body of the loop is not available yet, since it cannot be analysed
11037 /// until we have determined the type of the for-range-declaration.
11039 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11040 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11041 SourceLocation RParenLoc, BuildForRangeKind Kind,
11042 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11043
11044 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11045 StmtResult BuildCXXForRangeStmt(
11046 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11047 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11048 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11049 BuildForRangeKind Kind,
11050 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11051
11052 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11053 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11054 /// body cannot be performed until after the type of the range variable is
11055 /// determined.
11056 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11057
11058 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11059 LabelDecl *TheDecl);
11060 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11061 SourceLocation StarLoc, Expr *DestExp);
11062 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
11063 LabelDecl *Label, SourceLocation LabelLoc);
11064 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
11065 LabelDecl *Label, SourceLocation LabelLoc);
11066
11069
11072
11073 bool isMoveEligible() const { return S != None; };
11075 };
11077
11078 /// Determine whether the given expression might be move-eligible or
11079 /// copy-elidable in either a (co_)return statement or throw expression,
11080 /// without considering function return type, if applicable.
11081 ///
11082 /// \param E The expression being returned from the function or block,
11083 /// being thrown, or being co_returned from a coroutine. This expression
11084 /// might be modified by the implementation.
11085 ///
11086 /// \param Mode Overrides detection of current language mode
11087 /// and uses the rules for C++23.
11088 ///
11089 /// \returns An aggregate which contains the Candidate and isMoveEligible
11090 /// and isCopyElidable methods. If Candidate is non-null, it means
11091 /// isMoveEligible() would be true under the most permissive language
11092 /// standard.
11093 NamedReturnInfo getNamedReturnInfo(
11095
11096 /// Determine whether the given NRVO candidate variable is move-eligible or
11097 /// copy-elidable, without considering function return type.
11098 ///
11099 /// \param VD The NRVO candidate variable.
11100 ///
11101 /// \returns An aggregate which contains the Candidate and isMoveEligible
11102 /// and isCopyElidable methods. If Candidate is non-null, it means
11103 /// isMoveEligible() would be true under the most permissive language
11104 /// standard.
11105 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11106
11107 /// Updates given NamedReturnInfo's move-eligible and
11108 /// copy-elidable statuses, considering the function
11109 /// return type criteria as applicable to return statements.
11110 ///
11111 /// \param Info The NamedReturnInfo object to update.
11112 ///
11113 /// \param ReturnType This is the return type of the function.
11114 /// \returns The copy elision candidate, in case the initial return expression
11115 /// was copy elidable, or nullptr otherwise.
11116 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11117 QualType ReturnType);
11118
11119 /// Perform the initialization of a potentially-movable value, which
11120 /// is the result of return value.
11121 ///
11122 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11123 /// treat returned lvalues as rvalues in certain cases (to prefer move
11124 /// construction), then falls back to treating them as lvalues if that failed.
11127 const NamedReturnInfo &NRInfo, Expr *Value,
11128 bool SupressSimplerImplicitMoves = false);
11129
11131
11132 /// Deduce the return type for a function from a returned expression, per
11133 /// C++1y [dcl.spec.auto]p6.
11135 SourceLocation ReturnLoc, Expr *RetExpr,
11136 const AutoType *AT);
11137
11138 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11139 Scope *CurScope);
11140 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11141 bool AllowRecovery = false);
11142
11143 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11144 /// for capturing scopes.
11146 NamedReturnInfo &NRInfo,
11147 bool SupressSimplerImplicitMoves);
11148
11149 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11150 /// and creates a proper catch handler from them.
11152 Stmt *HandlerBlock);
11153
11154 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11155 /// handlers and creates a try statement from them.
11157 ArrayRef<Stmt *> Handlers);
11158
11159 void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11160
11161 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11162 SourceLocation TryLoc, Stmt *TryBlock,
11163 Stmt *Handler);
11165 Stmt *Block);
11170
11172 bool IsIfExists,
11173 NestedNameSpecifierLoc QualifierLoc,
11174 DeclarationNameInfo NameInfo,
11175 Stmt *Nested);
11177 bool IsIfExists, CXXScopeSpec &SS,
11178 UnqualifiedId &Name, Stmt *Nested);
11179
11180 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11181 CapturedRegionKind Kind, unsigned NumParams);
11182 typedef std::pair<StringRef, QualType> CapturedParamNameType;
11183 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11184 CapturedRegionKind Kind,
11186 unsigned OpenMPCaptureLevel = 0);
11190 SourceLocation Loc,
11191 unsigned NumParams);
11192
11193private:
11194 /// Check whether the given statement can have musttail applied to it,
11195 /// issuing a diagnostic and returning false if not.
11196 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11197
11198 /// Check if the given expression contains 'break' or 'continue'
11199 /// statement that produces control flow different from GCC.
11200 void CheckBreakContinueBinding(Expr *E);
11201
11202 ///@}
11203
11204 //
11205 //
11206 // -------------------------------------------------------------------------
11207 //
11208 //
11209
11210 /// \name `inline asm` Statement
11211 /// Implementations are in SemaStmtAsm.cpp
11212 ///@{
11213
11214public:
11215 ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel);
11216 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11217 bool IsVolatile, unsigned NumOutputs,
11218 unsigned NumInputs, IdentifierInfo **Names,
11219 MultiExprArg Constraints, MultiExprArg Exprs,
11220 Expr *AsmString, MultiExprArg Clobbers,
11221 unsigned NumLabels, SourceLocation RParenLoc);
11222
11224 llvm::InlineAsmIdentifierInfo &Info);
11226 SourceLocation TemplateKWLoc,
11227 UnqualifiedId &Id,
11228 bool IsUnevaluatedContext);
11229 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11230 SourceLocation AsmLoc);
11232 SourceLocation AsmLoc);
11234 ArrayRef<Token> AsmToks, StringRef AsmString,
11235 unsigned NumOutputs, unsigned NumInputs,
11236 ArrayRef<StringRef> Constraints,
11237 ArrayRef<StringRef> Clobbers,
11238 ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11239 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11240 SourceLocation Location, bool AlwaysCreate);
11241
11242 ///@}
11243
11244 //
11245 //
11246 // -------------------------------------------------------------------------
11247 //
11248 //
11249
11250 /// \name Statement Attribute Handling
11251 /// Implementations are in SemaStmtAttr.cpp
11252 ///@{
11253
11254public:
11255 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11256 const AttributeCommonInfo &A);
11257 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11258 const AttributeCommonInfo &A);
11259
11260 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11262
11263 /// Process the attributes before creating an attributed statement. Returns
11264 /// the semantic attributes that have been processed.
11265 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11267
11269 SourceRange Range);
11271 const IdentifierInfo *AttrName,
11272 SourceRange Range);
11273
11274 ///@}
11275
11276 //
11277 //
11278 // -------------------------------------------------------------------------
11279 //
11280 //
11281
11282 /// \name C++ Templates
11283 /// Implementations are in SemaTemplate.cpp
11284 ///@{
11285
11286public:
11287 // Saves the current floating-point pragma stack and clear it in this Sema.
11289 public:
11291 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11292 S.FpPragmaStack.Stack.clear();
11293 }
11294 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11295
11296 private:
11297 Sema &S;
11299 };
11300
11302 CurFPFeatures = FPO;
11303 FpPragmaStack.CurrentValue = FPO.getChangesFrom(FPOptions(LangOpts));
11304 }
11305
11311
11312 /// The number of SFINAE diagnostics that have been trapped.
11314
11319
11320 typedef llvm::MapVector<const FunctionDecl *,
11321 std::unique_ptr<LateParsedTemplate>>
11324
11325 /// Determine the number of levels of enclosing template parameters. This is
11326 /// only usable while parsing. Note that this does not include dependent
11327 /// contexts in which no template parameters have yet been declared, such as
11328 /// in a terse function template or generic lambda before the first 'auto' is
11329 /// encountered.
11330 unsigned getTemplateDepth(Scope *S) const;
11331
11333 bool AllowFunctionTemplates = true,
11334 bool AllowDependent = true);
11336 bool AllowFunctionTemplates = true,
11337 bool AllowDependent = true,
11338 bool AllowNonTemplateFunctions = false);
11339 /// Try to interpret the lookup result D as a template-name.
11340 ///
11341 /// \param D A declaration found by name lookup.
11342 /// \param AllowFunctionTemplates Whether function templates should be
11343 /// considered valid results.
11344 /// \param AllowDependent Whether unresolved using declarations (that might
11345 /// name templates) should be considered valid results.
11347 bool AllowFunctionTemplates = true,
11348 bool AllowDependent = true);
11349
11351 /// Whether and why a template name is required in this lookup.
11353 public:
11354 /// Template name is required if TemplateKWLoc is valid.
11356 : TemplateKW(TemplateKWLoc) {}
11357 /// Template name is unconditionally required.
11359
11361 return TemplateKW.value_or(SourceLocation());
11362 }
11363 bool hasTemplateKeyword() const {
11364 return getTemplateKeywordLoc().isValid();
11365 }
11366 bool isRequired() const { return TemplateKW != SourceLocation(); }
11367 explicit operator bool() const { return isRequired(); }
11368
11369 private:
11370 std::optional<SourceLocation> TemplateKW;
11371 };
11372
11374 /// This is not assumed to be a template name.
11376 /// This is assumed to be a template name because lookup found nothing.
11378 /// This is assumed to be a template name because lookup found one or more
11379 /// functions (but no function templates).
11381 };
11382
11383 bool
11385 QualType ObjectType, bool EnteringContext,
11386 RequiredTemplateKind RequiredTemplate = SourceLocation(),
11387 AssumedTemplateKind *ATK = nullptr,
11388 bool AllowTypoCorrection = true);
11389
11391 bool hasTemplateKeyword,
11392 const UnqualifiedId &Name,
11393 ParsedType ObjectType, bool EnteringContext,
11395 bool &MemberOfUnknownSpecialization,
11396 bool Disambiguation = false);
11397
11398 /// Try to resolve an undeclared template name as a type template.
11399 ///
11400 /// Sets II to the identifier corresponding to the template name, and updates
11401 /// Name to a corresponding (typo-corrected) type template name and TNK to
11402 /// the corresponding kind, if possible.
11404 TemplateNameKind &TNK,
11405 SourceLocation NameLoc,
11406 IdentifierInfo *&II);
11407
11408 /// Determine whether a particular identifier might be the name in a C++1z
11409 /// deduction-guide declaration.
11410 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11411 SourceLocation NameLoc, CXXScopeSpec &SS,
11412 ParsedTemplateTy *Template = nullptr);
11413
11415 SourceLocation IILoc, Scope *S,
11416 const CXXScopeSpec *SS,
11417 TemplateTy &SuggestedTemplate,
11418 TemplateNameKind &SuggestedKind);
11419
11420 /// Determine whether we would be unable to instantiate this template (because
11421 /// it either has no definition, or is in the process of being instantiated).
11423 SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11424 bool InstantiatedFromMember, const NamedDecl *Pattern,
11425 const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11426 bool Complain = true, bool *Unreachable = nullptr);
11427
11428 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11429 /// that the template parameter 'PrevDecl' is being shadowed by a new
11430 /// declaration at location Loc. Returns true to indicate that this is
11431 /// an error, and false otherwise.
11432 ///
11433 /// \param Loc The location of the declaration that shadows a template
11434 /// parameter.
11435 ///
11436 /// \param PrevDecl The template parameter that the declaration shadows.
11437 ///
11438 /// \param SupportedForCompatibility Whether to issue the diagnostic as
11439 /// a warning for compatibility with older versions of clang.
11440 /// Ignored when MSVC compatibility is enabled.
11442 bool SupportedForCompatibility = false);
11443
11444 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11445 /// the parameter D to reference the templated declaration and return a
11446 /// pointer to the template declaration. Otherwise, do nothing to D and return
11447 /// null.
11449
11450 /// ActOnTypeParameter - Called when a C++ template type parameter
11451 /// (e.g., "typename T") has been parsed. Typename specifies whether
11452 /// the keyword "typename" was used to declare the type parameter
11453 /// (otherwise, "class" was used), and KeyLoc is the location of the
11454 /// "class" or "typename" keyword. ParamName is the name of the
11455 /// parameter (NULL indicates an unnamed template parameter) and
11456 /// ParamNameLoc is the location of the parameter name (if any).
11457 /// If the type parameter has a default argument, it will be added
11458 /// later via ActOnTypeParameterDefault.
11460 SourceLocation EllipsisLoc,
11461 SourceLocation KeyLoc,
11462 IdentifierInfo *ParamName,
11463 SourceLocation ParamNameLoc, unsigned Depth,
11464 unsigned Position, SourceLocation EqualLoc,
11465 ParsedType DefaultArg, bool HasTypeConstraint);
11466
11468
11469 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11471 TemplateTypeParmDecl *ConstrainedParameter,
11472 SourceLocation EllipsisLoc);
11473 bool BuildTypeConstraint(const CXXScopeSpec &SS,
11475 TemplateTypeParmDecl *ConstrainedParameter,
11476 SourceLocation EllipsisLoc,
11477 bool AllowUnexpandedPack);
11478
11479 /// Attach a type-constraint to a template parameter.
11480 /// \returns true if an error occurred. This can happen if the
11481 /// immediately-declared constraint could not be formed (e.g. incorrect number
11482 /// of arguments for the named concept).
11484 DeclarationNameInfo NameInfo,
11485 TemplateDecl *NamedConcept, NamedDecl *FoundDecl,
11486 const TemplateArgumentListInfo *TemplateArgs,
11487 TemplateTypeParmDecl *ConstrainedParameter,
11488 SourceLocation EllipsisLoc);
11489
11491 NonTypeTemplateParmDecl *NewConstrainedParm,
11492 NonTypeTemplateParmDecl *OrigConstrainedParm,
11493 SourceLocation EllipsisLoc);
11494
11495 /// Require the given type to be a structural type, and diagnose if it is not.
11496 ///
11497 /// \return \c true if an error was produced.
11499
11500 /// Check that the type of a non-type template parameter is
11501 /// well-formed.
11502 ///
11503 /// \returns the (possibly-promoted) parameter type if valid;
11504 /// otherwise, produces a diagnostic and returns a NULL type.
11506 SourceLocation Loc);
11508
11510 unsigned Depth, unsigned Position,
11511 SourceLocation EqualLoc,
11512 Expr *DefaultArg);
11513
11514 /// ActOnTemplateTemplateParameter - Called when a C++ template template
11515 /// parameter (e.g. T in template <template <typename> class T> class array)
11516 /// has been parsed. S is the current scope.
11518 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind,
11519 bool TypenameKeyword, TemplateParameterList *Params,
11520 SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11521 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11522 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11523
11524 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11525 /// constrained by RequiresClause, that contains the template parameters in
11526 /// Params.
11528 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11529 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11530 SourceLocation RAngleLoc, Expr *RequiresClause);
11531
11532 /// The context in which we are checking a template parameter list.
11534 // For this context, Class, Variable, TypeAlias, and non-pack Template
11535 // Template Parameters are treated uniformly.
11537
11544 };
11545
11546 /// Checks the validity of a template parameter list, possibly
11547 /// considering the template parameter list from a previous
11548 /// declaration.
11549 ///
11550 /// If an "old" template parameter list is provided, it must be
11551 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11552 /// template parameter list.
11553 ///
11554 /// \param NewParams Template parameter list for a new template
11555 /// declaration. This template parameter list will be updated with any
11556 /// default arguments that are carried through from the previous
11557 /// template parameter list.
11558 ///
11559 /// \param OldParams If provided, template parameter list from a
11560 /// previous declaration of the same template. Default template
11561 /// arguments will be merged from the old template parameter list to
11562 /// the new template parameter list.
11563 ///
11564 /// \param TPC Describes the context in which we are checking the given
11565 /// template parameter list.
11566 ///
11567 /// \param SkipBody If we might have already made a prior merged definition
11568 /// of this template visible, the corresponding body-skipping information.
11569 /// Default argument redefinition is not an error when skipping such a body,
11570 /// because (under the ODR) we can assume the default arguments are the same
11571 /// as the prior merged definition.
11572 ///
11573 /// \returns true if an error occurred, false otherwise.
11575 TemplateParameterList *OldParams,
11577 SkipBodyInfo *SkipBody = nullptr);
11578
11579 /// Match the given template parameter lists to the given scope
11580 /// specifier, returning the template parameter list that applies to the
11581 /// name.
11582 ///
11583 /// \param DeclStartLoc the start of the declaration that has a scope
11584 /// specifier or a template parameter list.
11585 ///
11586 /// \param DeclLoc The location of the declaration itself.
11587 ///
11588 /// \param SS the scope specifier that will be matched to the given template
11589 /// parameter lists. This scope specifier precedes a qualified name that is
11590 /// being declared.
11591 ///
11592 /// \param TemplateId The template-id following the scope specifier, if there
11593 /// is one. Used to check for a missing 'template<>'.
11594 ///
11595 /// \param ParamLists the template parameter lists, from the outermost to the
11596 /// innermost template parameter lists.
11597 ///
11598 /// \param IsFriend Whether to apply the slightly different rules for
11599 /// matching template parameters to scope specifiers in friend
11600 /// declarations.
11601 ///
11602 /// \param IsMemberSpecialization will be set true if the scope specifier
11603 /// denotes a fully-specialized type, and therefore this is a declaration of
11604 /// a member specialization.
11605 ///
11606 /// \returns the template parameter list, if any, that corresponds to the
11607 /// name that is preceded by the scope specifier @p SS. This template
11608 /// parameter list may have template parameters (if we're declaring a
11609 /// template) or may have no template parameters (if we're declaring a
11610 /// template specialization), or may be NULL (if what we're declaring isn't
11611 /// itself a template).
11613 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11614 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11615 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11616 bool &IsMemberSpecialization, bool &Invalid,
11617 bool SuppressDiagnostic = false);
11618
11619 /// Returns the template parameter list with all default template argument
11620 /// information.
11622
11624 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11625 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11626 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11627 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11628 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11629 TemplateParameterList **OuterTemplateParamLists,
11630 SkipBodyInfo *SkipBody = nullptr);
11631
11632 /// Translates template arguments as provided by the parser
11633 /// into template arguments used by semantic analysis.
11636
11637 /// Convert a parsed type into a parsed template argument. This is mostly
11638 /// trivial, except that we may have parsed a C++17 deduced class template
11639 /// specialization type, in which case we should form a template template
11640 /// argument instead of a type template argument.
11642
11644
11647 SourceLocation TemplateLoc,
11648 TemplateArgumentListInfo &TemplateArgs,
11649 Scope *Scope, bool ForNestedNameSpecifier);
11650
11652 ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
11653 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
11654 SourceLocation TemplateKWLoc, TemplateTy Template,
11655 const IdentifierInfo *TemplateII,
11656 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11657 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11658 bool IsCtorOrDtorName = false, bool IsClassName = false,
11659 ImplicitTypenameContext AllowImplicitTypename =
11661
11662 /// Parsed an elaborated-type-specifier that refers to a template-id,
11663 /// such as \c class T::template apply<U>.
11665 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11666 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11667 SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11668 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11669
11672 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11674
11675 /// Get the specialization of the given variable template corresponding to
11676 /// the specified argument list, or a null-but-valid result if the arguments
11677 /// are dependent.
11679 SourceLocation TemplateLoc,
11680 SourceLocation TemplateNameLoc,
11681 const TemplateArgumentListInfo &TemplateArgs,
11682 bool SetWrittenArgs);
11683
11684 /// Form a reference to the specialization of the given variable template
11685 /// corresponding to the specified argument list, or a null-but-valid result
11686 /// if the arguments are dependent.
11688 const DeclarationNameInfo &NameInfo,
11690 SourceLocation TemplateLoc,
11691 const TemplateArgumentListInfo *TemplateArgs);
11692
11694 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
11696 const TemplateArgumentListInfo *TemplateArgs);
11697
11699 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11700 const DeclarationNameInfo &ConceptNameInfo,
11701 NamedDecl *FoundDecl, TemplateDecl *NamedConcept,
11702 const TemplateArgumentListInfo *TemplateArgs,
11703 bool DoCheckConstraintSatisfaction = true);
11704
11707 bool TemplateKeyword, TemplateDecl *TD,
11708 SourceLocation Loc);
11709
11711 SourceLocation TemplateKWLoc, LookupResult &R,
11712 bool RequiresADL,
11713 const TemplateArgumentListInfo *TemplateArgs);
11714
11715 // We actually only call this from template instantiation.
11718 const DeclarationNameInfo &NameInfo,
11719 const TemplateArgumentListInfo *TemplateArgs,
11720 bool IsAddressOfOperand);
11721
11723 return Pack.pack_size() - 1 - *ArgPackSubstIndex;
11724 }
11725
11728 Arg = Arg.pack_elements()[*ArgPackSubstIndex];
11729 if (Arg.isPackExpansion())
11730 Arg = Arg.getPackExpansionPattern();
11731 return Arg;
11732 }
11733
11735 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP,
11736 SourceLocation loc, TemplateArgument Replacement,
11737 UnsignedOrNone PackIndex, bool Final);
11738
11739 /// Form a template name from a name that is syntactically required to name a
11740 /// template, either due to use of the 'template' keyword or because a name in
11741 /// this syntactic context is assumed to name a template (C++
11742 /// [temp.names]p2-4).
11743 ///
11744 /// This action forms a template name given the name of the template and its
11745 /// optional scope specifier. This is used when the 'template' keyword is used
11746 /// or when the parsing context unambiguously treats a following '<' as
11747 /// introducing a template argument list. Note that this may produce a
11748 /// non-dependent template name if we can perform the lookup now and identify
11749 /// the named template.
11750 ///
11751 /// For example, given "x.MetaFun::template apply", the scope specifier
11752 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
11753 /// of the "template" keyword, and "apply" is the \p Name.
11755 SourceLocation TemplateKWLoc,
11756 const UnqualifiedId &Name,
11757 ParsedType ObjectType,
11758 bool EnteringContext, TemplateTy &Template,
11759 bool AllowInjectedClassName = false);
11760
11762 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11763 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
11765 MultiTemplateParamsArg TemplateParameterLists,
11766 SkipBodyInfo *SkipBody = nullptr);
11767
11768 /// Check the non-type template arguments of a class template
11769 /// partial specialization according to C++ [temp.class.spec]p9.
11770 ///
11771 /// \param TemplateNameLoc the location of the template name.
11772 /// \param PrimaryTemplate the template parameters of the primary class
11773 /// template.
11774 /// \param NumExplicit the number of explicitly-specified template arguments.
11775 /// \param TemplateArgs the template arguments of the class template
11776 /// partial specialization.
11777 ///
11778 /// \returns \c true if there was an error, \c false otherwise.
11780 TemplateDecl *PrimaryTemplate,
11781 unsigned NumExplicitArgs,
11787
11789 MultiTemplateParamsArg TemplateParameterLists,
11790 Declarator &D);
11791
11792 /// Diagnose cases where we have an explicit template specialization
11793 /// before/after an explicit template instantiation, producing diagnostics
11794 /// for those cases where they are required and determining whether the
11795 /// new specialization/instantiation will have any effect.
11796 ///
11797 /// \param NewLoc the location of the new explicit specialization or
11798 /// instantiation.
11799 ///
11800 /// \param NewTSK the kind of the new explicit specialization or
11801 /// instantiation.
11802 ///
11803 /// \param PrevDecl the previous declaration of the entity.
11804 ///
11805 /// \param PrevTSK the kind of the old explicit specialization or
11806 /// instantiatin.
11807 ///
11808 /// \param PrevPointOfInstantiation if valid, indicates where the previous
11809 /// declaration was instantiated (either implicitly or explicitly).
11810 ///
11811 /// \param HasNoEffect will be set to true to indicate that the new
11812 /// specialization or instantiation has no effect and should be ignored.
11813 ///
11814 /// \returns true if there was an error that should prevent the introduction
11815 /// of the new declaration into the AST, false otherwise.
11817 SourceLocation NewLoc,
11818 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
11819 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
11820 SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
11821
11822 /// Perform semantic analysis for the given dependent function
11823 /// template specialization.
11824 ///
11825 /// The only possible way to get a dependent function template specialization
11826 /// is with a friend declaration, like so:
11827 ///
11828 /// \code
11829 /// template <class T> void foo(T);
11830 /// template <class T> class A {
11831 /// friend void foo<>(T);
11832 /// };
11833 /// \endcode
11834 ///
11835 /// There really isn't any useful analysis we can do here, so we
11836 /// just store the information.
11838 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
11840
11841 /// Perform semantic analysis for the given function template
11842 /// specialization.
11843 ///
11844 /// This routine performs all of the semantic analysis required for an
11845 /// explicit function template specialization. On successful completion,
11846 /// the function declaration \p FD will become a function template
11847 /// specialization.
11848 ///
11849 /// \param FD the function declaration, which will be updated to become a
11850 /// function template specialization.
11851 ///
11852 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
11853 /// if any. Note that this may be valid info even when 0 arguments are
11854 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
11855 /// as it anyway contains info on the angle brackets locations.
11856 ///
11857 /// \param Previous the set of declarations that may be specialized by
11858 /// this function specialization.
11859 ///
11860 /// \param QualifiedFriend whether this is a lookup for a qualified friend
11861 /// declaration with no explicit template argument list that might be
11862 /// befriending a function template specialization.
11864 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
11865 LookupResult &Previous, bool QualifiedFriend = false);
11866
11867 /// Perform semantic analysis for the given non-template member
11868 /// specialization.
11869 ///
11870 /// This routine performs all of the semantic analysis required for an
11871 /// explicit member function specialization. On successful completion,
11872 /// the function declaration \p FD will become a member function
11873 /// specialization.
11874 ///
11875 /// \param Member the member declaration, which will be updated to become a
11876 /// specialization.
11877 ///
11878 /// \param Previous the set of declarations, one of which may be specialized
11879 /// by this function specialization; the set will be modified to contain the
11880 /// redeclared member.
11883
11884 // Explicit instantiation of a class template specialization
11886 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
11887 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
11888 TemplateTy Template, SourceLocation TemplateNameLoc,
11889 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
11890 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
11891
11892 // Explicit instantiation of a member class of a class template.
11894 SourceLocation TemplateLoc,
11895 unsigned TagSpec, SourceLocation KWLoc,
11896 CXXScopeSpec &SS, IdentifierInfo *Name,
11897 SourceLocation NameLoc,
11898 const ParsedAttributesView &Attr);
11899
11901 SourceLocation TemplateLoc,
11902 Declarator &D);
11903
11904 /// If the given template parameter has a default template
11905 /// argument, substitute into that default template argument and
11906 /// return the corresponding template argument.
11908 TemplateDecl *Template, SourceLocation TemplateKWLoc,
11909 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
11910 ArrayRef<TemplateArgument> SugaredConverted,
11911 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
11912
11913 /// Returns the top most location responsible for the definition of \p N.
11914 /// If \p N is a a template specialization, this is the location
11915 /// of the top of the instantiation stack.
11916 /// Otherwise, the location of \p N is returned.
11918
11919 /// Specifies the context in which a particular template
11920 /// argument is being checked.
11922 /// The template argument was specified in the code or was
11923 /// instantiated with some deduced template arguments.
11925
11926 /// The template argument was deduced via template argument
11927 /// deduction.
11929
11930 /// The template argument was deduced from an array bound
11931 /// via template argument deduction.
11933 };
11934
11942
11943 /// The checked, converted argument will be added to the
11944 /// end of these vectors.
11946
11947 /// The check is being performed in the context of partial ordering.
11949
11950 /// If true, assume these template arguments are
11951 /// the injected template arguments for a template template parameter.
11952 /// This will relax the requirement that all its possible uses are valid:
11953 /// TTP checking is loose, and assumes that invalid uses will be diagnosed
11954 /// during instantiation.
11956
11957 /// Is set to true when, in the context of TTP matching, a pack parameter
11958 /// matches non-pack arguments.
11959 bool StrictPackMatch = false;
11960 };
11961
11962 /// Check that the given template argument corresponds to the given
11963 /// template parameter.
11964 ///
11965 /// \param Param The template parameter against which the argument will be
11966 /// checked.
11967 ///
11968 /// \param Arg The template argument, which may be updated due to conversions.
11969 ///
11970 /// \param Template The template in which the template argument resides.
11971 ///
11972 /// \param TemplateLoc The location of the template name for the template
11973 /// whose argument list we're matching.
11974 ///
11975 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
11976 /// the template argument list.
11977 ///
11978 /// \param ArgumentPackIndex The index into the argument pack where this
11979 /// argument will be placed. Only valid if the parameter is a parameter pack.
11980 ///
11981 /// \param CTAK Describes how we arrived at this particular template argument:
11982 /// explicitly written, deduced, etc.
11983 ///
11984 /// \returns true on error, false otherwise.
11986 NamedDecl *Template, SourceLocation TemplateLoc,
11987 SourceLocation RAngleLoc,
11988 unsigned ArgumentPackIndex,
11991
11992 /// Check that the given template arguments can be provided to
11993 /// the given template, converting the arguments along the way.
11994 ///
11995 /// \param Template The template to which the template arguments are being
11996 /// provided.
11997 ///
11998 /// \param TemplateLoc The location of the template name in the source.
11999 ///
12000 /// \param TemplateArgs The list of template arguments. If the template is
12001 /// a template template parameter, this function may extend the set of
12002 /// template arguments to also include substituted, defaulted template
12003 /// arguments.
12004 ///
12005 /// \param PartialTemplateArgs True if the list of template arguments is
12006 /// intentionally partial, e.g., because we're checking just the initial
12007 /// set of template arguments.
12008 ///
12009 /// \param Converted Will receive the converted, canonicalized template
12010 /// arguments.
12011 ///
12012 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
12013 /// contain the converted forms of the template arguments as written.
12014 /// Otherwise, \p TemplateArgs will not be modified.
12015 ///
12016 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
12017 /// receive true if the cause for the error is the associated constraints of
12018 /// the template not being satisfied by the template arguments.
12019 ///
12020 /// \param DefaultArgs any default arguments from template specialization
12021 /// deduction.
12022 ///
12023 /// \returns true if an error occurred, false otherwise.
12025 SourceLocation TemplateLoc,
12026 TemplateArgumentListInfo &TemplateArgs,
12027 const DefaultArguments &DefaultArgs,
12028 bool PartialTemplateArgs,
12030 bool UpdateArgsWithConversions = true,
12031 bool *ConstraintsNotSatisfied = nullptr);
12032
12035 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
12036 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
12037 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions = true,
12038 bool *ConstraintsNotSatisfied = nullptr);
12039
12042 SmallVectorImpl<TemplateArgument> &SugaredConverted,
12043 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
12044
12045 /// Check a template argument against its corresponding
12046 /// template type parameter.
12047 ///
12048 /// This routine implements the semantics of C++ [temp.arg.type]. It
12049 /// returns true if an error occurred, and false otherwise.
12051
12052 /// Check a template argument against its corresponding
12053 /// non-type template parameter.
12054 ///
12055 /// This routine implements the semantics of C++ [temp.arg.nontype].
12056 /// If an error occurred, it returns ExprError(); otherwise, it
12057 /// returns the converted template argument. \p ParamType is the
12058 /// type of the non-type template parameter after it has been instantiated.
12060 QualType InstantiatedParamType, Expr *Arg,
12061 TemplateArgument &SugaredConverted,
12062 TemplateArgument &CanonicalConverted,
12063 bool StrictCheck,
12065
12066 /// Check a template argument against its corresponding
12067 /// template template parameter.
12068 ///
12069 /// This routine implements the semantics of C++ [temp.arg.template].
12070 /// It returns true if an error occurred, and false otherwise.
12072 TemplateParameterList *Params,
12074 bool PartialOrdering,
12075 bool *StrictPackMatch);
12076
12079 const TemplateArgumentLoc &Arg);
12080
12082 std::optional<SourceRange> ParamRange = {});
12084
12085 /// Given a non-type template argument that refers to a
12086 /// declaration and the type of its corresponding non-type template
12087 /// parameter, produce an expression that properly refers to that
12088 /// declaration.
12089 /// FIXME: This is used in some contexts where the resulting expression
12090 /// doesn't need to live too long. It would be useful if this function
12091 /// could return a temporary expression.
12093 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
12094 NamedDecl *TemplateParam = nullptr);
12097 SourceLocation Loc);
12098
12099 /// Enumeration describing how template parameter lists are compared
12100 /// for equality.
12102 /// We are matching the template parameter lists of two templates
12103 /// that might be redeclarations.
12104 ///
12105 /// \code
12106 /// template<typename T> struct X;
12107 /// template<typename T> struct X;
12108 /// \endcode
12110
12111 /// We are matching the template parameter lists of two template
12112 /// template parameters as part of matching the template parameter lists
12113 /// of two templates that might be redeclarations.
12114 ///
12115 /// \code
12116 /// template<template<int I> class TT> struct X;
12117 /// template<template<int Value> class Other> struct X;
12118 /// \endcode
12120
12121 /// We are determining whether the template-parameters are equivalent
12122 /// according to C++ [temp.over.link]/6. This comparison does not consider
12123 /// constraints.
12124 ///
12125 /// \code
12126 /// template<C1 T> void f(T);
12127 /// template<C2 T> void f(T);
12128 /// \endcode
12130 };
12131
12132 // A struct to represent the 'new' declaration, which is either itself just
12133 // the named decl, or the important information we need about it in order to
12134 // do constraint comparisons.
12136 const NamedDecl *ND = nullptr;
12137 const DeclContext *DC = nullptr;
12138 const DeclContext *LexicalDC = nullptr;
12139 SourceLocation Loc;
12140
12141 public:
12144 const DeclContext *LexicalDeclCtx,
12145 SourceLocation Loc)
12146
12147 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12148 assert(DC && LexicalDC &&
12149 "Constructor only for cases where we have the information to put "
12150 "in here");
12151 }
12152
12153 // If this was constructed with no information, we cannot do substitution
12154 // for constraint comparison, so make sure we can check that.
12155 bool isInvalid() const { return !ND && !DC; }
12156
12157 const NamedDecl *getDecl() const { return ND; }
12158
12159 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12160
12162 return ND ? ND->getLexicalDeclContext() : LexicalDC;
12163 }
12164
12166 return ND ? ND->getDeclContext() : DC;
12167 }
12168
12169 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12170 };
12171
12172 /// Determine whether the given template parameter lists are
12173 /// equivalent.
12174 ///
12175 /// \param New The new template parameter list, typically written in the
12176 /// source code as part of a new template declaration.
12177 ///
12178 /// \param Old The old template parameter list, typically found via
12179 /// name lookup of the template declared with this template parameter
12180 /// list.
12181 ///
12182 /// \param Complain If true, this routine will produce a diagnostic if
12183 /// the template parameter lists are not equivalent.
12184 ///
12185 /// \param Kind describes how we are to match the template parameter lists.
12186 ///
12187 /// \param TemplateArgLoc If this source location is valid, then we
12188 /// are actually checking the template parameter list of a template
12189 /// argument (New) against the template parameter list of its
12190 /// corresponding template template parameter (Old). We produce
12191 /// slightly different diagnostics in this scenario.
12192 ///
12193 /// \returns True if the template parameter lists are equal, false
12194 /// otherwise.
12196 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12197 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12199 SourceLocation TemplateArgLoc = SourceLocation());
12200
12202 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12204 SourceLocation TemplateArgLoc = SourceLocation()) {
12205 return TemplateParameterListsAreEqual(nullptr, New, nullptr, Old, Complain,
12206 Kind, TemplateArgLoc);
12207 }
12208
12209 /// Check whether a template can be declared within this scope.
12210 ///
12211 /// If the template declaration is valid in this scope, returns
12212 /// false. Otherwise, issues a diagnostic and returns true.
12213 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12214
12215 /// Called when the parser has parsed a C++ typename
12216 /// specifier, e.g., "typename T::type".
12217 ///
12218 /// \param S The scope in which this typename type occurs.
12219 /// \param TypenameLoc the location of the 'typename' keyword
12220 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12221 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12222 /// \param IdLoc the location of the identifier.
12223 /// \param IsImplicitTypename context where T::type refers to a type.
12225 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12226 const IdentifierInfo &II, SourceLocation IdLoc,
12228
12229 /// Called when the parser has parsed a C++ typename
12230 /// specifier that ends in a template-id, e.g.,
12231 /// "typename MetaFun::template apply<T1, T2>".
12232 ///
12233 /// \param S The scope in which this typename type occurs.
12234 /// \param TypenameLoc the location of the 'typename' keyword
12235 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12236 /// \param TemplateLoc the location of the 'template' keyword, if any.
12237 /// \param TemplateName The template name.
12238 /// \param TemplateII The identifier used to name the template.
12239 /// \param TemplateIILoc The location of the template name.
12240 /// \param LAngleLoc The location of the opening angle bracket ('<').
12241 /// \param TemplateArgs The template arguments.
12242 /// \param RAngleLoc The location of the closing angle bracket ('>').
12244 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12245 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12246 TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12247 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12248 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12249
12251 SourceLocation KeywordLoc,
12252 NestedNameSpecifierLoc QualifierLoc,
12253 const IdentifierInfo &II, SourceLocation IILoc,
12254 TypeSourceInfo **TSI, bool DeducedTSTContext);
12255
12257 SourceLocation KeywordLoc,
12258 NestedNameSpecifierLoc QualifierLoc,
12259 const IdentifierInfo &II, SourceLocation IILoc,
12260 bool DeducedTSTContext = true);
12261
12262 /// Rebuilds a type within the context of the current instantiation.
12263 ///
12264 /// The type \p T is part of the type of an out-of-line member definition of
12265 /// a class template (or class template partial specialization) that was
12266 /// parsed and constructed before we entered the scope of the class template
12267 /// (or partial specialization thereof). This routine will rebuild that type
12268 /// now that we have entered the declarator's scope, which may produce
12269 /// different canonical types, e.g.,
12270 ///
12271 /// \code
12272 /// template<typename T>
12273 /// struct X {
12274 /// typedef T* pointer;
12275 /// pointer data();
12276 /// };
12277 ///
12278 /// template<typename T>
12279 /// typename X<T>::pointer X<T>::data() { ... }
12280 /// \endcode
12281 ///
12282 /// Here, the type "typename X<T>::pointer" will be created as a
12283 /// DependentNameType, since we do not know that we can look into X<T> when we
12284 /// parsed the type. This function will rebuild the type, performing the
12285 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12286 /// canonical type is the same as the canonical type of T*, allowing the
12287 /// return types of the out-of-line definition and the declaration to match.
12289 SourceLocation Loc,
12290 DeclarationName Name);
12292
12294
12295 /// Rebuild the template parameters now that we know we're in a current
12296 /// instantiation.
12297 bool
12299
12300 /// Produces a formatted string that describes the binding of
12301 /// template parameters to template arguments.
12302 std::string
12304 const TemplateArgumentList &Args);
12305
12306 std::string
12308 const TemplateArgument *Args,
12309 unsigned NumArgs);
12310
12314
12315 /// ActOnDependentIdExpression - Handle a dependent id-expression that
12316 /// was just parsed. This is only possible with an explicit scope
12317 /// specifier naming a dependent type.
12319 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12320 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12321 const TemplateArgumentListInfo *TemplateArgs);
12322
12325 SourceLocation TemplateKWLoc,
12326 const DeclarationNameInfo &NameInfo,
12327 const TemplateArgumentListInfo *TemplateArgs);
12328
12329 // Calculates whether the expression Constraint depends on an enclosing
12330 // template, for the purposes of [temp.friend] p9.
12331 // TemplateDepth is the 'depth' of the friend function, which is used to
12332 // compare whether a declaration reference is referring to a containing
12333 // template, or just the current friend function. A 'lower' TemplateDepth in
12334 // the AST refers to a 'containing' template. As the constraint is
12335 // uninstantiated, this is relative to the 'top' of the TU.
12336 bool
12338 unsigned TemplateDepth,
12339 const Expr *Constraint);
12340
12341 /// Find the failed Boolean condition within a given Boolean
12342 /// constant expression, and describe it with a string.
12343 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12344
12346
12348 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12349 const IdentifierInfo *Name, SourceLocation NameLoc);
12350
12352 Expr *ConstraintExpr,
12353 const ParsedAttributesView &Attrs);
12354
12356 bool &AddToScope);
12358
12359 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12360 const CXXScopeSpec &SS,
12361 const IdentifierInfo *Name,
12362 SourceLocation TagLoc, SourceLocation NameLoc);
12363
12365 CachedTokens &Toks);
12368
12369 /// We've found a use of a templated declaration that would trigger an
12370 /// implicit instantiation. Check that any relevant explicit specializations
12371 /// and partial specializations are visible/reachable, and diagnose if not.
12374
12375 ///@}
12376
12377 //
12378 //
12379 // -------------------------------------------------------------------------
12380 //
12381 //
12382
12383 /// \name C++ Template Argument Deduction
12384 /// Implementations are in SemaTemplateDeduction.cpp
12385 ///@{
12386
12387public:
12388 /// When true, access checking violations are treated as SFINAE
12389 /// failures rather than hard errors.
12391
12392 /// RAII class used to determine whether SFINAE has
12393 /// trapped any errors that occur during template argument
12394 /// deduction.
12396 Sema &SemaRef;
12397 unsigned PrevSFINAEErrors;
12398 bool PrevInNonInstantiationSFINAEContext;
12399 bool PrevAccessCheckingSFINAE;
12400 bool PrevLastDiagnosticIgnored;
12401
12402 public:
12403 /// \param ForValidityCheck If true, discard all diagnostics (from the
12404 /// immediate context) instead of adding them to the currently active
12405 /// \ref TemplateDeductionInfo (as returned by \ref isSFINAEContext).
12406 explicit SFINAETrap(Sema &SemaRef, bool ForValidityCheck = false)
12407 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
12408 PrevInNonInstantiationSFINAEContext(
12410 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
12411 PrevLastDiagnosticIgnored(
12412 SemaRef.getDiagnostics().isLastDiagnosticIgnored()) {
12413 if (ForValidityCheck || !SemaRef.isSFINAEContext())
12414 SemaRef.InNonInstantiationSFINAEContext = true;
12415 SemaRef.AccessCheckingSFINAE = ForValidityCheck;
12416 }
12417
12419 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
12420 SemaRef.InNonInstantiationSFINAEContext =
12421 PrevInNonInstantiationSFINAEContext;
12422 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
12423 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
12424 PrevLastDiagnosticIgnored);
12425 }
12426
12427 /// Determine whether any SFINAE errors have been trapped.
12428 bool hasErrorOccurred() const {
12429 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
12430 }
12431 };
12432
12433 /// RAII class used to indicate that we are performing provisional
12434 /// semantic analysis to determine the validity of a construct, so
12435 /// typo-correction and diagnostics in the immediate context (not within
12436 /// implicitly-instantiated templates) should be suppressed.
12438 Sema &SemaRef;
12439 // FIXME: Using a SFINAETrap for this is a hack.
12440 SFINAETrap Trap;
12441 bool PrevDisableTypoCorrection;
12442
12443 public:
12444 explicit TentativeAnalysisScope(Sema &SemaRef)
12445 : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12446 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12447 SemaRef.DisableTypoCorrection = true;
12448 }
12450 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12451 }
12452 };
12453
12454 /// For each declaration that involved template argument deduction, the
12455 /// set of diagnostics that were suppressed during that template argument
12456 /// deduction.
12457 ///
12458 /// FIXME: Serialize this structure to the AST file.
12459 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12462
12463 /// Compare types for equality with respect to possibly compatible
12464 /// function types (noreturn adjustment, implicit calling conventions). If any
12465 /// of parameter and argument is not a function, just perform type comparison.
12466 ///
12467 /// \param P the template parameter type.
12468 ///
12469 /// \param A the argument type.
12471
12472 /// Allocate a TemplateArgumentLoc where all locations have
12473 /// been initialized to the given location.
12474 ///
12475 /// \param Arg The template argument we are producing template argument
12476 /// location information for.
12477 ///
12478 /// \param NTTPType For a declaration template argument, the type of
12479 /// the non-type template parameter that corresponds to this template
12480 /// argument. Can be null if no type sugar is available to add to the
12481 /// type from the template argument.
12482 ///
12483 /// \param Loc The source location to use for the resulting template
12484 /// argument.
12487 SourceLocation Loc,
12488 NamedDecl *TemplateParam = nullptr);
12489
12490 /// Get a template argument mapping the given template parameter to itself,
12491 /// e.g. for X in \c template<int X>, this would return an expression template
12492 /// argument referencing X.
12494 SourceLocation Location);
12495
12496 /// Adjust the type \p ArgFunctionType to match the calling convention,
12497 /// noreturn, and optionally the exception specification of \p FunctionType.
12498 /// Deduction often wants to ignore these properties when matching function
12499 /// types.
12501 bool AdjustExceptionSpec = false);
12502
12505 ArrayRef<TemplateArgument> TemplateArgs,
12507
12510 ArrayRef<TemplateArgument> TemplateArgs,
12512
12513 /// Deduce the template arguments of the given template from \p FromType.
12514 /// Used to implement the IsDeducible constraint for alias CTAD per C++
12515 /// [over.match.class.deduct]p4.
12516 ///
12517 /// It only supports class or type alias templates.
12521
12526 bool NumberOfArgumentsMustMatch);
12527
12528 /// Substitute the explicitly-provided template arguments into the
12529 /// given function template according to C++ [temp.arg.explicit].
12530 ///
12531 /// \param FunctionTemplate the function template into which the explicit
12532 /// template arguments will be substituted.
12533 ///
12534 /// \param ExplicitTemplateArgs the explicitly-specified template
12535 /// arguments.
12536 ///
12537 /// \param Deduced the deduced template arguments, which will be populated
12538 /// with the converted and checked explicit template arguments.
12539 ///
12540 /// \param ParamTypes will be populated with the instantiated function
12541 /// parameters.
12542 ///
12543 /// \param FunctionType if non-NULL, the result type of the function template
12544 /// will also be instantiated and the pointed-to value will be updated with
12545 /// the instantiated function type.
12546 ///
12547 /// \param Info if substitution fails for any reason, this object will be
12548 /// populated with more information about the failure.
12549 ///
12550 /// \returns TemplateDeductionResult::Success if substitution was successful,
12551 /// or some failure condition.
12554 TemplateArgumentListInfo &ExplicitTemplateArgs,
12558
12559 /// brief A function argument from which we performed template argument
12560 // deduction for a call.
12573
12574 /// Finish template argument deduction for a function template,
12575 /// checking the deduced template arguments for completeness and forming
12576 /// the function template specialization.
12577 ///
12578 /// \param OriginalCallArgs If non-NULL, the original call arguments against
12579 /// which the deduced argument types should be compared.
12580 /// \param CheckNonDependent Callback before substituting into the declaration
12581 /// with the deduced template arguments.
12582 /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12583 /// some breakages introduced by CWG2369, where non-user-defined conversions
12584 /// are checked first before the constraints.
12588 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12590 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12591 bool PartialOverloading, bool PartialOrdering,
12592 bool ForOverloadSetAddressResolution,
12593 llvm::function_ref<bool(bool)> CheckNonDependent =
12594 [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12595 return false;
12596 });
12597
12598 /// Perform template argument deduction from a function call
12599 /// (C++ [temp.deduct.call]).
12600 ///
12601 /// \param FunctionTemplate the function template for which we are performing
12602 /// template argument deduction.
12603 ///
12604 /// \param ExplicitTemplateArgs the explicit template arguments provided
12605 /// for this call.
12606 ///
12607 /// \param Args the function call arguments
12608 ///
12609 /// \param Specialization if template argument deduction was successful,
12610 /// this will be set to the function template specialization produced by
12611 /// template argument deduction.
12612 ///
12613 /// \param Info the argument will be updated to provide additional information
12614 /// about template argument deduction.
12615 ///
12616 /// \param CheckNonDependent A callback to invoke to check conversions for
12617 /// non-dependent parameters, between deduction and substitution, per DR1391.
12618 /// If this returns true, substitution will be skipped and we return
12619 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12620 /// passed the parameter types (after substituting explicit template
12621 /// arguments).
12622 ///
12623 /// \returns the result of template argument deduction.
12626 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12628 bool PartialOverloading, bool AggregateDeductionCandidate,
12629 bool PartialOrdering, QualType ObjectType,
12630 Expr::Classification ObjectClassification,
12631 bool ForOverloadSetAddressResolution,
12632 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12633
12634 /// Deduce template arguments when taking the address of a function
12635 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12636 /// a template.
12637 ///
12638 /// \param FunctionTemplate the function template for which we are performing
12639 /// template argument deduction.
12640 ///
12641 /// \param ExplicitTemplateArgs the explicitly-specified template
12642 /// arguments.
12643 ///
12644 /// \param ArgFunctionType the function type that will be used as the
12645 /// "argument" type (A) when performing template argument deduction from the
12646 /// function template's function type. This type may be NULL, if there is no
12647 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
12648 ///
12649 /// \param Specialization if template argument deduction was successful,
12650 /// this will be set to the function template specialization produced by
12651 /// template argument deduction.
12652 ///
12653 /// \param Info the argument will be updated to provide additional information
12654 /// about template argument deduction.
12655 ///
12656 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12657 /// the address of a function template per [temp.deduct.funcaddr] and
12658 /// [over.over]. If \c false, we are looking up a function template
12659 /// specialization based on its signature, per [temp.deduct.decl].
12660 ///
12661 /// \returns the result of template argument deduction.
12664 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
12666 bool IsAddressOfFunction = false);
12667
12668 /// Deduce template arguments for a templated conversion
12669 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
12670 /// conversion function template specialization.
12673 Expr::Classification ObjectClassification, QualType ToType,
12675
12676 /// Deduce template arguments for a function template when there is
12677 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
12678 ///
12679 /// \param FunctionTemplate the function template for which we are performing
12680 /// template argument deduction.
12681 ///
12682 /// \param ExplicitTemplateArgs the explicitly-specified template
12683 /// arguments.
12684 ///
12685 /// \param Specialization if template argument deduction was successful,
12686 /// this will be set to the function template specialization produced by
12687 /// template argument deduction.
12688 ///
12689 /// \param Info the argument will be updated to provide additional information
12690 /// about template argument deduction.
12691 ///
12692 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12693 /// the address of a function template in a context where we do not have a
12694 /// target type, per [over.over]. If \c false, we are looking up a function
12695 /// template specialization based on its signature, which only happens when
12696 /// deducing a function parameter type from an argument that is a template-id
12697 /// naming a function template specialization.
12698 ///
12699 /// \returns the result of template argument deduction.
12702 TemplateArgumentListInfo *ExplicitTemplateArgs,
12705 bool IsAddressOfFunction = false);
12706
12707 /// Substitute Replacement for \p auto in \p TypeWithAuto
12708 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
12709 /// Substitute Replacement for auto in TypeWithAuto
12711 QualType Replacement);
12712
12713 // Substitute auto in TypeWithAuto for a Dependent auto type
12715
12716 // Substitute auto in TypeWithAuto for a Dependent auto type
12719
12720 /// Completely replace the \c auto in \p TypeWithAuto by
12721 /// \p Replacement. This does not retain any \c auto type sugar.
12722 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
12724 QualType Replacement);
12725
12726 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
12727 ///
12728 /// Note that this is done even if the initializer is dependent. (This is
12729 /// necessary to support partial ordering of templates using 'auto'.)
12730 /// A dependent type will be produced when deducing from a dependent type.
12731 ///
12732 /// \param Type the type pattern using the auto type-specifier.
12733 /// \param Init the initializer for the variable whose type is to be deduced.
12734 /// \param Result if type deduction was successful, this will be set to the
12735 /// deduced type.
12736 /// \param Info the argument will be updated to provide additional information
12737 /// about template argument deduction.
12738 /// \param DependentDeduction Set if we should permit deduction in
12739 /// dependent cases. This is necessary for template partial ordering
12740 /// with 'auto' template parameters. The template parameter depth to be
12741 /// used should be specified in the 'Info' parameter.
12742 /// \param IgnoreConstraints Set if we should not fail if the deduced type
12743 /// does not satisfy the type-constraint in the auto
12744 /// type.
12748 bool DependentDeduction = false,
12749 bool IgnoreConstraints = false,
12750 TemplateSpecCandidateSet *FailedTSC = nullptr);
12751 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
12753 bool Diagnose = true);
12754
12756 SourceLocation Loc);
12757
12758 /// Returns the more specialized class template partial specialization
12759 /// according to the rules of partial ordering of class template partial
12760 /// specializations (C++ [temp.class.order]).
12761 ///
12762 /// \param PS1 the first class template partial specialization
12763 ///
12764 /// \param PS2 the second class template partial specialization
12765 ///
12766 /// \returns the more specialized class template partial specialization. If
12767 /// neither partial specialization is more specialized, returns NULL.
12772
12775
12779
12782
12784 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
12785 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
12786 bool PartialOrdering, bool *StrictPackMatch);
12787
12788 /// Mark which template parameters are used in a given expression.
12789 ///
12790 /// \param E the expression from which template parameters will be deduced.
12791 ///
12792 /// \param Used a bit vector whose elements will be set to \c true
12793 /// to indicate when the corresponding template parameter will be
12794 /// deduced.
12795 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
12796 unsigned Depth, llvm::SmallBitVector &Used);
12797
12798 /// Mark which template parameters are named in a given expression.
12799 ///
12800 /// Unlike MarkUsedTemplateParameters, this excludes parameter that
12801 /// are used but not directly named by an expression - i.e. it excludes
12802 /// any template parameter that denotes the type of a referenced NTTP.
12803 ///
12804 /// \param Used a bit vector whose elements will be set to \c true
12805 /// to indicate when the corresponding template parameter will be
12806 /// deduced.
12808 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used);
12809
12810 /// Mark which template parameters can be deduced from a given
12811 /// template argument list.
12812 ///
12813 /// \param TemplateArgs the template argument list from which template
12814 /// parameters will be deduced.
12815 ///
12816 /// \param Used a bit vector whose elements will be set to \c true
12817 /// to indicate when the corresponding template parameter will be
12818 /// deduced.
12819 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
12820 bool OnlyDeduced, unsigned Depth,
12821 llvm::SmallBitVector &Used);
12822
12824 unsigned Depth, llvm::SmallBitVector &Used);
12825
12827 unsigned Depth, llvm::SmallBitVector &Used);
12828
12829 void
12831 llvm::SmallBitVector &Deduced) {
12833 }
12834
12835 /// Marks all of the template parameters that will be deduced by a
12836 /// call to the given function template.
12837 static void
12840 llvm::SmallBitVector &Deduced);
12841
12842 /// Returns the more specialized function template according
12843 /// to the rules of function template partial ordering (C++
12844 /// [temp.func.order]).
12845 ///
12846 /// \param FT1 the first function template
12847 ///
12848 /// \param FT2 the second function template
12849 ///
12850 /// \param TPOC the context in which we are performing partial ordering of
12851 /// function templates.
12852 ///
12853 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
12854 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
12855 /// when calling a member function.
12856 ///
12857 /// \param RawObj1Ty The type of the object parameter of FT1 if a member
12858 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
12859 /// template from a member function
12860 ///
12861 /// \param RawObj2Ty The type of the object parameter of FT2 if a member
12862 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
12863 /// template from a member function
12864 ///
12865 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
12866 /// candidate with a reversed parameter order. In this case, the corresponding
12867 /// P/A pairs between FT1 and FT2 are reversed.
12868 ///
12869 /// \returns the more specialized function template. If neither
12870 /// template is more specialized, returns NULL.
12873 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
12874 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
12875 bool PartialOverloading = false);
12876
12877 /// Retrieve the most specialized of the given function template
12878 /// specializations.
12879 ///
12880 /// \param SpecBegin the start iterator of the function template
12881 /// specializations that we will be comparing.
12882 ///
12883 /// \param SpecEnd the end iterator of the function template
12884 /// specializations, paired with \p SpecBegin.
12885 ///
12886 /// \param Loc the location where the ambiguity or no-specializations
12887 /// diagnostic should occur.
12888 ///
12889 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
12890 /// no matching candidates.
12891 ///
12892 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
12893 /// occurs.
12894 ///
12895 /// \param CandidateDiag partial diagnostic used for each function template
12896 /// specialization that is a candidate in the ambiguous ordering. One
12897 /// parameter in this diagnostic should be unbound, which will correspond to
12898 /// the string describing the template arguments for the function template
12899 /// specialization.
12900 ///
12901 /// \returns the most specialized function template specialization, if
12902 /// found. Otherwise, returns SpecEnd.
12903 UnresolvedSetIterator
12904 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
12905 TemplateSpecCandidateSet &FailedCandidates,
12906 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
12907 const PartialDiagnostic &AmbigDiag,
12908 const PartialDiagnostic &CandidateDiag,
12909 bool Complain = true, QualType TargetType = QualType());
12910
12911 /// Returns the more constrained function according to the rules of
12912 /// partial ordering by constraints (C++ [temp.constr.order]).
12913 ///
12914 /// \param FD1 the first function
12915 ///
12916 /// \param FD2 the second function
12917 ///
12918 /// \returns the more constrained function. If neither function is
12919 /// more constrained, returns NULL.
12920 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
12921 FunctionDecl *FD2);
12922
12923 ///@}
12924
12925 //
12926 //
12927 // -------------------------------------------------------------------------
12928 //
12929 //
12930
12931 /// \name C++ Template Deduction Guide
12932 /// Implementations are in SemaTemplateDeductionGuide.cpp
12933 ///@{
12934
12935 /// Declare implicit deduction guides for a class template if we've
12936 /// not already done so.
12937 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
12938 SourceLocation Loc);
12939
12940 FunctionTemplateDecl *DeclareAggregateDeductionGuideFromInitList(
12941 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
12942 SourceLocation Loc);
12943
12944 ///@}
12945
12946 //
12947 //
12948 // -------------------------------------------------------------------------
12949 //
12950 //
12951
12952 /// \name C++ Template Instantiation
12953 /// Implementations are in SemaTemplateInstantiate.cpp
12954 ///@{
12955
12956public:
12957 /// A helper class for building up ExtParameterInfos.
12960 bool HasInteresting = false;
12961
12962 public:
12963 /// Set the ExtParameterInfo for the parameter at the given index,
12964 ///
12966 assert(Infos.size() <= index);
12967 Infos.resize(index);
12968 Infos.push_back(info);
12969
12970 if (!HasInteresting)
12971 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
12972 }
12973
12974 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
12975 /// ExtParameterInfo array we've built up.
12977 getPointerOrNull(unsigned numParams) {
12978 if (!HasInteresting)
12979 return nullptr;
12980 Infos.resize(numParams);
12981 return Infos.data();
12982 }
12983 };
12984
12985 /// The current instantiation scope used to store local
12986 /// variables.
12988
12989 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
12991
12992 /// A mapping from parameters with unparsed default arguments to the
12993 /// set of instantiations of each parameter.
12994 ///
12995 /// This mapping is a temporary data structure used when parsing
12996 /// nested class templates or nested classes of class templates,
12997 /// where we might end up instantiating an inner class before the
12998 /// default arguments of its methods have been parsed.
13000
13001 using InstantiatingSpecializationsKey = llvm::PointerIntPair<Decl *, 2>;
13002
13009
13011 : S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
13012 auto [_, Created] = S.InstantiatingSpecializations.insert(Key);
13013 if (!Created)
13014 Key = {};
13015 }
13016
13018 if (Key.getOpaqueValue()) {
13019 [[maybe_unused]] bool Erased =
13020 S.InstantiatingSpecializations.erase(Key);
13021 assert(Erased);
13022 }
13023 }
13024
13025 operator bool() const { return Key.getOpaqueValue() == nullptr; }
13026
13027 private:
13028 Sema &S;
13030 };
13031
13032 /// A context in which code is being synthesized (where a source location
13033 /// alone is not sufficient to identify the context). This covers template
13034 /// instantiation and various forms of implicitly-generated functions.
13036 /// The kind of template instantiation we are performing
13038 /// We are instantiating a template declaration. The entity is
13039 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
13041
13042 /// We are instantiating a default argument for a template
13043 /// parameter. The Entity is the template parameter whose argument is
13044 /// being instantiated, the Template is the template, and the
13045 /// TemplateArgs/NumTemplateArguments provide the template arguments as
13046 /// specified.
13048
13049 /// We are instantiating a default argument for a function.
13050 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
13051 /// provides the template arguments as specified.
13053
13054 /// We are substituting explicit template arguments provided for
13055 /// a function template. The entity is a FunctionTemplateDecl.
13057
13058 /// We are substituting template argument determined as part of
13059 /// template argument deduction for either a class template
13060 /// partial specialization or a function template. The
13061 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
13062 /// a TemplateDecl.
13064
13065 /// We are substituting into a lambda expression.
13067
13068 /// We are substituting prior template arguments into a new
13069 /// template parameter. The template parameter itself is either a
13070 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
13072
13073 /// We are checking the validity of a default template argument that
13074 /// has been used when naming a template-id.
13076
13077 /// We are computing the exception specification for a defaulted special
13078 /// member function.
13080
13081 /// We are instantiating the exception specification for a function
13082 /// template which was deferred until it was needed.
13084
13085 /// We are instantiating a requirement of a requires expression.
13087
13088 /// We are checking the satisfaction of a nested requirement of a requires
13089 /// expression.
13091
13092 /// We are declaring an implicit special member function.
13094
13095 /// We are declaring an implicit 'operator==' for a defaulted
13096 /// 'operator<=>'.
13098
13099 /// We are defining a synthesized function (such as a defaulted special
13100 /// member).
13102
13103 // We are checking the constraints associated with a constrained entity or
13104 // the constraint expression of a concept. This includes the checks that
13105 // atomic constraints have the type 'bool' and that they can be constant
13106 // evaluated.
13108
13109 // We are substituting template arguments into a constraint expression.
13111
13112 // We are normalizing a constraint expression.
13114
13115 // Instantiating a Requires Expression parameter clause.
13117
13118 // We are substituting into the parameter mapping of an atomic constraint
13119 // during normalization.
13121
13122 /// We are rewriting a comparison operator in terms of an operator<=>.
13124
13125 /// We are initializing a structured binding.
13127
13128 /// We are marking a class as __dllexport.
13130
13131 /// We are building an implied call from __builtin_dump_struct. The
13132 /// arguments are in CallArgs.
13134
13135 /// Added for Template instantiation observation.
13136 /// Memoization means we are _not_ instantiating a template because
13137 /// it is already instantiated (but we entered a context where we
13138 /// would have had to if it was not already instantiated).
13140
13141 /// We are building deduction guides for a class.
13143
13144 /// We are instantiating a type alias template declaration.
13146
13147 /// We are performing partial ordering for template template parameters.
13149 } Kind;
13150
13151 /// Was the enclosing context a non-instantiation SFINAE context?
13153
13154 /// Whether we're substituting into constraints.
13156
13157 /// Whether we're substituting into the parameter mapping of a constraint.
13159
13160 /// The point of instantiation or synthesis within the source code.
13162
13163 /// The entity that is being synthesized.
13165
13166 /// The template (or partial specialization) in which we are
13167 /// performing the instantiation, for substitutions of prior template
13168 /// arguments.
13170
13171 union {
13172 /// The list of template arguments we are substituting, if they
13173 /// are not part of the entity.
13175
13176 /// The list of argument expressions in a synthesized call.
13177 const Expr *const *CallArgs;
13178 };
13179
13180 // FIXME: Wrap this union around more members, or perhaps store the
13181 // kind-specific members in the RAII object owning the context.
13182 union {
13183 /// The number of template arguments in TemplateArgs.
13185
13186 /// The number of expressions in CallArgs.
13187 unsigned NumCallArgs;
13188
13189 /// The special member being declared or defined.
13191 };
13192
13197
13198 /// The template deduction info object associated with the
13199 /// substitution or checking of explicit or deduced template arguments.
13201
13202 /// The source range that covers the construct that cause
13203 /// the instantiation, e.g., the template-id that causes a class
13204 /// template instantiation.
13206
13214
13215 /// Determines whether this template is an actual instantiation
13216 /// that should be counted toward the maximum instantiation depth.
13217 bool isInstantiationRecord() const;
13218 };
13219
13220 /// A stack object to be created when performing template
13221 /// instantiation.
13222 ///
13223 /// Construction of an object of type \c InstantiatingTemplate
13224 /// pushes the current instantiation onto the stack of active
13225 /// instantiations. If the size of this stack exceeds the maximum
13226 /// number of recursive template instantiations, construction
13227 /// produces an error and evaluates true.
13228 ///
13229 /// Destruction of this object will pop the named instantiation off
13230 /// the stack.
13232 /// Note that we are instantiating a class template,
13233 /// function template, variable template, alias template,
13234 /// or a member thereof.
13235 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13236 Decl *Entity,
13237 SourceRange InstantiationRange = SourceRange());
13238
13240 /// Note that we are instantiating an exception specification
13241 /// of a function template.
13242 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13244 SourceRange InstantiationRange = SourceRange());
13245
13246 /// Note that we are instantiating a type alias template declaration.
13247 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13248 TypeAliasTemplateDecl *Entity,
13249 ArrayRef<TemplateArgument> TemplateArgs,
13250 SourceRange InstantiationRange = SourceRange());
13251
13252 /// Note that we are instantiating a default argument in a
13253 /// template-id.
13254 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13256 ArrayRef<TemplateArgument> TemplateArgs,
13257 SourceRange InstantiationRange = SourceRange());
13258
13259 /// Note that we are substituting either explicitly-specified or
13260 /// deduced template arguments during function template argument deduction.
13261 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13263 ArrayRef<TemplateArgument> TemplateArgs,
13265 sema::TemplateDeductionInfo &DeductionInfo,
13266 SourceRange InstantiationRange = SourceRange());
13267
13268 /// Note that we are instantiating as part of template
13269 /// argument deduction for a class template declaration.
13270 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13272 ArrayRef<TemplateArgument> TemplateArgs,
13273 sema::TemplateDeductionInfo &DeductionInfo,
13274 SourceRange InstantiationRange = SourceRange());
13275
13276 /// Note that we are instantiating as part of template
13277 /// argument deduction for a class template partial
13278 /// specialization.
13279 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13281 ArrayRef<TemplateArgument> TemplateArgs,
13282 sema::TemplateDeductionInfo &DeductionInfo,
13283 SourceRange InstantiationRange = SourceRange());
13284
13285 /// Note that we are instantiating as part of template
13286 /// argument deduction for a variable template partial
13287 /// specialization.
13288 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13290 ArrayRef<TemplateArgument> TemplateArgs,
13291 sema::TemplateDeductionInfo &DeductionInfo,
13292 SourceRange InstantiationRange = SourceRange());
13293
13294 /// Note that we are instantiating a default argument for a function
13295 /// parameter.
13296 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13297 ParmVarDecl *Param,
13298 ArrayRef<TemplateArgument> TemplateArgs,
13299 SourceRange InstantiationRange = SourceRange());
13300
13301 /// Note that we are substituting prior template arguments into a
13302 /// non-type parameter.
13303 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13305 ArrayRef<TemplateArgument> TemplateArgs,
13306 SourceRange InstantiationRange);
13307
13308 /// Note that we are substituting prior template arguments into a
13309 /// template template parameter.
13310 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13312 ArrayRef<TemplateArgument> TemplateArgs,
13313 SourceRange InstantiationRange);
13314
13315 /// Note that we are checking the default template argument
13316 /// against the template parameter for a given template-id.
13317 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13319 ArrayRef<TemplateArgument> TemplateArgs,
13320 SourceRange InstantiationRange);
13321
13323 /// \brief Note that we are checking the constraints associated with some
13324 /// constrained entity (a concept declaration or a template with associated
13325 /// constraints).
13326 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13328 ArrayRef<TemplateArgument> TemplateArgs,
13329 SourceRange InstantiationRange);
13330
13332 /// \brief Note that we are checking a constraint expression associated
13333 /// with a template declaration or as part of the satisfaction check of a
13334 /// concept.
13335 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13337 sema::TemplateDeductionInfo &DeductionInfo,
13338 SourceRange InstantiationRange);
13339
13341 /// \brief Note that we are normalizing a constraint expression.
13342 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13344 SourceRange InstantiationRange);
13345
13347 /// \brief Note that we are subtituting into the parameter mapping of an
13348 /// atomic constraint during constraint normalization.
13349 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13351 SourceRange InstantiationRange);
13352
13353 /// \brief Note that we are substituting template arguments into a part of
13354 /// a requirement of a requires expression.
13355 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13357 sema::TemplateDeductionInfo &DeductionInfo,
13358 SourceRange InstantiationRange = SourceRange());
13359
13360 /// \brief Note that we are checking the satisfaction of the constraint
13361 /// expression inside of a nested requirement.
13362 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13364 SourceRange InstantiationRange = SourceRange());
13365
13366 /// \brief Note that we are checking a requires clause.
13367 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13368 const RequiresExpr *E,
13369 sema::TemplateDeductionInfo &DeductionInfo,
13370 SourceRange InstantiationRange);
13371
13373 /// \brief Note that we are building deduction guides.
13374 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13376 SourceRange InstantiationRange = SourceRange());
13377
13379 /// \brief Note that we are partial ordering template template parameters.
13380 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13382 SourceRange InstantiationRange = SourceRange());
13383
13384 /// Note that we have finished instantiating this template.
13385 void Clear();
13386
13388
13389 /// Determines whether we have exceeded the maximum
13390 /// recursive template instantiations.
13391 bool isInvalid() const { return Invalid; }
13392
13393 private:
13394 Sema &SemaRef;
13395 bool Invalid;
13396
13399 SourceLocation PointOfInstantiation,
13400 SourceRange InstantiationRange, Decl *Entity,
13401 NamedDecl *Template = nullptr,
13402 ArrayRef<TemplateArgument> TemplateArgs = {},
13403 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
13404
13406
13407 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13408 };
13409
13410 bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13411 const MultiLevelTemplateArgumentList &TemplateArgs,
13412 TemplateArgumentLoc &Output,
13413 SourceLocation Loc = {},
13414 const DeclarationName &Entity = {});
13415 bool
13416 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13417 const MultiLevelTemplateArgumentList &TemplateArgs,
13418 TemplateArgumentListInfo &Outputs);
13419
13420 /// Substitute concept template arguments in the constraint expression
13421 /// of a concept-id. This is used to implement [temp.constr.normal].
13423 SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE,
13424 const Expr *ConstraintExpr,
13425 const MultiLevelTemplateArgumentList &MLTAL);
13426
13428 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
13429 const MultiLevelTemplateArgumentList &TemplateArgs,
13430 TemplateArgumentListInfo &Out, bool BuildPackExpansionTypes);
13431
13432 /// Retrieve the template argument list(s) that should be used to
13433 /// instantiate the definition of the given declaration.
13434 ///
13435 /// \param ND the declaration for which we are computing template
13436 /// instantiation arguments.
13437 ///
13438 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13439 /// the decl context where it will be created. In this case, the `Innermost`
13440 /// should likely be provided. If ND is non-null, this is ignored.
13441 ///
13442 /// \param Innermost if non-NULL, specifies a template argument list for the
13443 /// template declaration passed as ND.
13444 ///
13445 /// \param RelativeToPrimary true if we should get the template
13446 /// arguments relative to the primary template, even when we're
13447 /// dealing with a specialization. This is only relevant for function
13448 /// template specializations.
13449 ///
13450 /// \param Pattern If non-NULL, indicates the pattern from which we will be
13451 /// instantiating the definition of the given declaration, \p ND. This is
13452 /// used to determine the proper set of template instantiation arguments for
13453 /// friend function template specializations.
13454 ///
13455 /// \param ForConstraintInstantiation when collecting arguments,
13456 /// ForConstraintInstantiation indicates we should continue looking when
13457 /// encountering a lambda generic call operator, and continue looking for
13458 /// arguments on an enclosing class template.
13459 ///
13460 /// \param SkipForSpecialization when specified, any template specializations
13461 /// in a traversal would be ignored.
13462 ///
13463 /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13464 /// when encountering a specialized member function template, rather than
13465 /// returning immediately.
13466 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13467 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13468 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13469 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13470 bool ForConstraintInstantiation = false,
13471 bool SkipForSpecialization = false,
13472 bool ForDefaultArgumentSubstitution = false);
13473
13474 /// RAII object to handle the state changes required to synthesize
13475 /// a function body.
13477 Sema &S;
13478 Sema::ContextRAII SavedContext;
13479 bool PushedCodeSynthesisContext = false;
13480
13481 public:
13483 : S(S), SavedContext(S, DC) {
13484 auto *FD = dyn_cast<FunctionDecl>(DC);
13485 S.PushFunctionScope();
13486 S.PushExpressionEvaluationContextForFunction(
13488 if (FD)
13489 FD->setWillHaveBody(true);
13490 else
13491 assert(isa<ObjCMethodDecl>(DC));
13492 }
13493
13495 assert(!PushedCodeSynthesisContext);
13496
13499 Ctx.PointOfInstantiation = UseLoc;
13500 Ctx.Entity = cast<Decl>(S.CurContext);
13501 S.pushCodeSynthesisContext(Ctx);
13502
13503 PushedCodeSynthesisContext = true;
13504 }
13505
13507 if (PushedCodeSynthesisContext)
13508 S.popCodeSynthesisContext();
13509 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
13510 FD->setWillHaveBody(false);
13511 S.CheckImmediateEscalatingFunctionDefinition(FD, S.getCurFunction());
13512 }
13513 S.PopExpressionEvaluationContext();
13514 S.PopFunctionScopeInfo();
13515 }
13516 };
13517
13518 /// List of active code synthesis contexts.
13519 ///
13520 /// This vector is treated as a stack. As synthesis of one entity requires
13521 /// synthesis of another, additional contexts are pushed onto the stack.
13523
13524 /// Specializations whose definitions are currently being instantiated.
13525 llvm::DenseSet<InstantiatingSpecializationsKey> InstantiatingSpecializations;
13526
13527 /// Non-dependent types used in templates that have already been instantiated
13528 /// by some template instantiation.
13529 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13530
13531 /// Extra modules inspected when performing a lookup during a template
13532 /// instantiation. Computed lazily.
13534
13535 /// Cache of additional modules that should be used for name lookup
13536 /// within the current template instantiation. Computed lazily; use
13537 /// getLookupModules() to get a complete set.
13538 llvm::DenseSet<Module *> LookupModulesCache;
13539
13540 /// Map from the most recent declaration of a namespace to the most
13541 /// recent visible declaration of that namespace.
13542 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13543
13544 /// Whether we are in a SFINAE context that is not associated with
13545 /// template instantiation.
13546 ///
13547 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
13548 /// of a template instantiation or template argument deduction.
13550
13551 /// The number of \p CodeSynthesisContexts that are not template
13552 /// instantiations and, therefore, should not be counted as part of the
13553 /// instantiation depth.
13554 ///
13555 /// When the instantiation depth reaches the user-configurable limit
13556 /// \p LangOptions::InstantiationDepth we will abort instantiation.
13557 // FIXME: Should we have a similar limit for other forms of synthesis?
13559
13560 /// The depth of the context stack at the point when the most recent
13561 /// error or warning was produced.
13562 ///
13563 /// This value is used to suppress printing of redundant context stacks
13564 /// when there are multiple errors or warnings in the same instantiation.
13565 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13567
13568 /// The template instantiation callbacks to trace or track
13569 /// instantiations (objects can be chained).
13570 ///
13571 /// This callbacks is used to print, trace or track template
13572 /// instantiations as they are being constructed.
13573 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
13575
13576 /// The current index into pack expansion arguments that will be
13577 /// used for substitution of parameter packs.
13578 ///
13579 /// The pack expansion index will be none to indicate that parameter packs
13580 /// should be instantiated as themselves. Otherwise, the index specifies
13581 /// which argument within the parameter pack will be used for substitution.
13583
13584 /// RAII object used to change the argument pack substitution index
13585 /// within a \c Sema object.
13586 ///
13587 /// See \c ArgPackSubstIndex for more information.
13589 Sema &Self;
13590 UnsignedOrNone OldSubstIndex;
13591
13592 public:
13594 : Self(Self),
13595 OldSubstIndex(std::exchange(Self.ArgPackSubstIndex, NewSubstIndex)) {}
13596
13597 ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13598 };
13599
13600 bool pushCodeSynthesisContext(CodeSynthesisContext Ctx);
13602
13613 /// Prints the current instantiation stack through a series of
13614 /// notes.
13619
13620 /// Determines whether we are currently in a context where
13621 /// template argument substitution failures are not considered
13622 /// errors.
13623 ///
13624 /// \returns An empty \c Optional if we're not in a SFINAE context.
13625 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
13626 /// template-deduction context object, which can be used to capture
13627 /// diagnostics that will be suppressed.
13628 std::optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
13629
13630 /// Perform substitution on the type T with a given set of template
13631 /// arguments.
13632 ///
13633 /// This routine substitutes the given template arguments into the
13634 /// type T and produces the instantiated type.
13635 ///
13636 /// \param T the type into which the template arguments will be
13637 /// substituted. If this type is not dependent, it will be returned
13638 /// immediately.
13639 ///
13640 /// \param Args the template arguments that will be
13641 /// substituted for the top-level template parameters within T.
13642 ///
13643 /// \param Loc the location in the source code where this substitution
13644 /// is being performed. It will typically be the location of the
13645 /// declarator (if we're instantiating the type of some declaration)
13646 /// or the location of the type in the source code (if, e.g., we're
13647 /// instantiating the type of a cast expression).
13648 ///
13649 /// \param Entity the name of the entity associated with a declaration
13650 /// being instantiated (if any). May be empty to indicate that there
13651 /// is no such entity (if, e.g., this is a type that occurs as part of
13652 /// a cast expression) or that the entity has no name (e.g., an
13653 /// unnamed function parameter).
13654 ///
13655 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
13656 /// acceptable as the top level type of the result.
13657 ///
13658 /// \param IsIncompleteSubstitution If provided, the pointee will be set
13659 /// whenever substitution would perform a replacement with a null or
13660 /// non-existent template argument.
13661 ///
13662 /// \returns If the instantiation succeeds, the instantiated
13663 /// type. Otherwise, produces diagnostics and returns a NULL type.
13665 const MultiLevelTemplateArgumentList &TemplateArgs,
13666 SourceLocation Loc, DeclarationName Entity,
13667 bool AllowDeducedTST = false);
13668
13670 const MultiLevelTemplateArgumentList &TemplateArgs,
13671 SourceLocation Loc, DeclarationName Entity,
13672 bool *IsIncompleteSubstitution = nullptr);
13673
13675 const MultiLevelTemplateArgumentList &TemplateArgs,
13676 SourceLocation Loc, DeclarationName Entity);
13677
13678 /// A form of SubstType intended specifically for instantiating the
13679 /// type of a FunctionDecl. Its purpose is solely to force the
13680 /// instantiation of default-argument expressions and to avoid
13681 /// instantiating an exception-specification.
13683 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
13684 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
13685 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
13687 const MultiLevelTemplateArgumentList &Args);
13690 SmallVectorImpl<QualType> &ExceptionStorage,
13691 const MultiLevelTemplateArgumentList &Args);
13692 ParmVarDecl *
13694 const MultiLevelTemplateArgumentList &TemplateArgs,
13695 int indexAdjustment, UnsignedOrNone NumExpansions,
13696 bool ExpectParameterPack, bool EvaluateConstraints = true);
13697
13698 /// Substitute the given template arguments into the given set of
13699 /// parameters, producing the set of parameter types that would be generated
13700 /// from such a substitution.
13702 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
13703 const MultiLevelTemplateArgumentList &TemplateArgs,
13704 SmallVectorImpl<QualType> &ParamTypes,
13706 ExtParameterInfoBuilder &ParamInfos);
13707
13708 /// Substitute the given template arguments into the default argument.
13710 const MultiLevelTemplateArgumentList &TemplateArgs,
13711 bool ForCallExpr = false);
13713 const MultiLevelTemplateArgumentList &TemplateArgs);
13714 /// Substitute an expression as if it is a address-of-operand, which makes it
13715 /// act like a CXXIdExpression rather than an attempt to call.
13717 const MultiLevelTemplateArgumentList &TemplateArgs);
13718
13719 // A RAII type used by the TemplateDeclInstantiator and TemplateInstantiator
13720 // to disable constraint evaluation, then restore the state.
13721 template <typename InstTy> struct ConstraintEvalRAII {
13722 InstTy &TI;
13724
13726 : TI(TI), OldValue(TI.getEvaluateConstraints()) {
13727 TI.setEvaluateConstraints(false);
13728 }
13729 ~ConstraintEvalRAII() { TI.setEvaluateConstraints(OldValue); }
13730 };
13731
13732 // Must be used instead of SubstExpr at 'constraint checking' time.
13735 const MultiLevelTemplateArgumentList &TemplateArgs);
13736 // Unlike the above, this does not evaluate constraints.
13738 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
13739
13740 /// Substitute the given template arguments into a list of
13741 /// expressions, expanding pack expansions if required.
13742 ///
13743 /// \param Exprs The list of expressions to substitute into.
13744 ///
13745 /// \param IsCall Whether this is some form of call, in which case
13746 /// default arguments will be dropped.
13747 ///
13748 /// \param TemplateArgs The set of template arguments to substitute.
13749 ///
13750 /// \param Outputs Will receive all of the substituted arguments.
13751 ///
13752 /// \returns true if an error occurred, false otherwise.
13753 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
13754 const MultiLevelTemplateArgumentList &TemplateArgs,
13755 SmallVectorImpl<Expr *> &Outputs);
13756
13758 const MultiLevelTemplateArgumentList &TemplateArgs);
13759
13762 bool CXXDirectInit);
13763
13764 /// Perform substitution on the base class specifiers of the
13765 /// given class template specialization.
13766 ///
13767 /// Produces a diagnostic and returns true on error, returns false and
13768 /// attaches the instantiated base classes to the class template
13769 /// specialization if successful.
13770 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13771 const MultiLevelTemplateArgumentList &TemplateArgs);
13772
13773 /// Instantiate the definition of a class from a given pattern.
13774 ///
13775 /// \param PointOfInstantiation The point of instantiation within the
13776 /// source code.
13777 ///
13778 /// \param Instantiation is the declaration whose definition is being
13779 /// instantiated. This will be either a class template specialization
13780 /// or a member class of a class template specialization.
13781 ///
13782 /// \param Pattern is the pattern from which the instantiation
13783 /// occurs. This will be either the declaration of a class template or
13784 /// the declaration of a member class of a class template.
13785 ///
13786 /// \param TemplateArgs The template arguments to be substituted into
13787 /// the pattern.
13788 ///
13789 /// \param TSK the kind of implicit or explicit instantiation to perform.
13790 ///
13791 /// \param Complain whether to complain if the class cannot be instantiated
13792 /// due to the lack of a definition.
13793 ///
13794 /// \returns true if an error occurred, false otherwise.
13795 bool InstantiateClass(SourceLocation PointOfInstantiation,
13796 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13797 const MultiLevelTemplateArgumentList &TemplateArgs,
13798 TemplateSpecializationKind TSK, bool Complain = true);
13799
13800private:
13801 bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
13802 CXXRecordDecl *Instantiation,
13803 CXXRecordDecl *Pattern,
13804 const MultiLevelTemplateArgumentList &TemplateArgs,
13805 TemplateSpecializationKind TSK, bool Complain);
13806
13807public:
13808 /// Instantiate the definition of an enum from a given pattern.
13809 ///
13810 /// \param PointOfInstantiation The point of instantiation within the
13811 /// source code.
13812 /// \param Instantiation is the declaration whose definition is being
13813 /// instantiated. This will be a member enumeration of a class
13814 /// temploid specialization, or a local enumeration within a
13815 /// function temploid specialization.
13816 /// \param Pattern The templated declaration from which the instantiation
13817 /// occurs.
13818 /// \param TemplateArgs The template arguments to be substituted into
13819 /// the pattern.
13820 /// \param TSK The kind of implicit or explicit instantiation to perform.
13821 ///
13822 /// \return \c true if an error occurred, \c false otherwise.
13823 bool InstantiateEnum(SourceLocation PointOfInstantiation,
13824 EnumDecl *Instantiation, EnumDecl *Pattern,
13825 const MultiLevelTemplateArgumentList &TemplateArgs,
13827
13828 /// Instantiate the definition of a field from the given pattern.
13829 ///
13830 /// \param PointOfInstantiation The point of instantiation within the
13831 /// source code.
13832 /// \param Instantiation is the declaration whose definition is being
13833 /// instantiated. This will be a class of a class temploid
13834 /// specialization, or a local enumeration within a function temploid
13835 /// specialization.
13836 /// \param Pattern The templated declaration from which the instantiation
13837 /// occurs.
13838 /// \param TemplateArgs The template arguments to be substituted into
13839 /// the pattern.
13840 ///
13841 /// \return \c true if an error occurred, \c false otherwise.
13843 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
13844 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
13845
13847 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
13848
13850 SourceLocation PointOfInstantiation,
13851 ClassTemplateSpecializationDecl *ClassTemplateSpec,
13852 TemplateSpecializationKind TSK, bool Complain,
13853 bool PrimaryStrictPackMatch);
13854
13855 /// Instantiates the definitions of all of the member
13856 /// of the given class, which is an instantiation of a class template
13857 /// or a member class of a template.
13858 void
13859 InstantiateClassMembers(SourceLocation PointOfInstantiation,
13860 CXXRecordDecl *Instantiation,
13861 const MultiLevelTemplateArgumentList &TemplateArgs,
13863
13864 /// Instantiate the definitions of all of the members of the
13865 /// given class template specialization, which was named as part of an
13866 /// explicit instantiation.
13868 SourceLocation PointOfInstantiation,
13869 ClassTemplateSpecializationDecl *ClassTemplateSpec,
13871
13874 const MultiLevelTemplateArgumentList &TemplateArgs);
13875
13876 /// Do template substitution on declaration name info.
13879 const MultiLevelTemplateArgumentList &TemplateArgs);
13881 SubstTemplateName(SourceLocation TemplateKWLoc,
13882 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
13883 SourceLocation NameLoc,
13884 const MultiLevelTemplateArgumentList &TemplateArgs);
13885
13887 const MultiLevelTemplateArgumentList &TemplateArgs,
13888 bool EvaluateConstraint);
13889
13890 /// Determine whether we are currently performing template instantiation.
13893 }
13894
13895 /// Determine whether we are currently performing constraint substitution.
13897 return !CodeSynthesisContexts.empty() &&
13898 CodeSynthesisContexts.back().InConstraintSubstitution;
13899 }
13900
13902 return !CodeSynthesisContexts.empty() &&
13903 CodeSynthesisContexts.back().InParameterMappingSubstitution &&
13905 }
13906
13907 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
13908
13909 /// \brief create a Requirement::SubstitutionDiagnostic with only a
13910 /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
13913
13914 ///@}
13915
13916 //
13917 //
13918 // -------------------------------------------------------------------------
13919 //
13920 //
13921
13922 /// \name C++ Template Declaration Instantiation
13923 /// Implementations are in SemaTemplateInstantiateDecl.cpp
13924 ///@{
13925
13926public:
13927 /// An entity for which implicit template instantiation is required.
13928 ///
13929 /// The source location associated with the declaration is the first place in
13930 /// the source code where the declaration was "used". It is not necessarily
13931 /// the point of instantiation (which will be either before or after the
13932 /// namespace-scope declaration that triggered this implicit instantiation),
13933 /// However, it is the location that diagnostics should generally refer to,
13934 /// because users will need to know what code triggered the instantiation.
13935 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
13936
13937 /// The queue of implicit template instantiations that are required
13938 /// but have not yet been performed.
13939 std::deque<PendingImplicitInstantiation> PendingInstantiations;
13940
13941 /// Queue of implicit template instantiations that cannot be performed
13942 /// eagerly.
13944
13948
13949 /// The queue of implicit template instantiations that are required
13950 /// and must be performed within the current local scope.
13951 ///
13952 /// This queue is only used for member functions of local classes in
13953 /// templates, which must be instantiated in the same scope as their
13954 /// enclosing function, so that they can reference function-local
13955 /// types, static variables, enumerators, etc.
13956 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
13957
13959 public:
13961 : S(S), AtEndOfTU(AtEndOfTU) {
13962 SavedPendingLocalImplicitInstantiations.swap(
13963 S.PendingLocalImplicitInstantiations);
13964 }
13965
13966 void perform() {
13967 S.PerformPendingInstantiations(/*LocalOnly=*/true,
13968 /*AtEndOfTU=*/AtEndOfTU);
13969 }
13970
13972 assert(S.PendingLocalImplicitInstantiations.empty() &&
13973 "there shouldn't be any pending local implicit instantiations");
13974 SavedPendingLocalImplicitInstantiations.swap(
13975 S.PendingLocalImplicitInstantiations);
13976 }
13977
13978 private:
13979 Sema &S;
13980 bool AtEndOfTU;
13981 std::deque<PendingImplicitInstantiation>
13982 SavedPendingLocalImplicitInstantiations;
13983 };
13984
13985 /// Records and restores the CurFPFeatures state on entry/exit of compound
13986 /// statements.
13988 public:
13991 FPOptionsOverride getOverrides() { return OldOverrides; }
13992
13993 private:
13994 Sema &S;
13995 FPOptions OldFPFeaturesState;
13996 FPOptionsOverride OldOverrides;
13997 LangOptions::FPEvalMethodKind OldEvalMethod;
13998 SourceLocation OldFPPragmaLocation;
13999 };
14000
14002 public:
14003 GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
14004 : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
14005 if (!Enabled)
14006 return;
14007
14008 S.SavedPendingInstantiations.emplace_back();
14009 S.SavedPendingInstantiations.back().swap(S.PendingInstantiations);
14010
14011 S.SavedVTableUses.emplace_back();
14012 S.SavedVTableUses.back().swap(S.VTableUses);
14013 }
14014
14015 void perform() {
14016 if (Enabled) {
14017 S.DefineUsedVTables();
14018 S.PerformPendingInstantiations(/*LocalOnly=*/false,
14019 /*AtEndOfTU=*/AtEndOfTU);
14020 }
14021 }
14022
14024 if (!Enabled)
14025 return;
14026
14027 // Restore the set of pending vtables.
14028 assert(S.VTableUses.empty() &&
14029 "VTableUses should be empty before it is discarded.");
14030 S.VTableUses.swap(S.SavedVTableUses.back());
14031 S.SavedVTableUses.pop_back();
14032
14033 // Restore the set of pending implicit instantiations.
14034 if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
14035 AtEndOfTU) {
14036 assert(S.PendingInstantiations.empty() &&
14037 "PendingInstantiations should be empty before it is discarded.");
14038 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
14039 S.SavedPendingInstantiations.pop_back();
14040 } else {
14041 // Template instantiations in the PCH may be delayed until the TU.
14042 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
14043 S.PendingInstantiations.insert(
14044 S.PendingInstantiations.end(),
14045 S.SavedPendingInstantiations.back().begin(),
14046 S.SavedPendingInstantiations.back().end());
14047 S.SavedPendingInstantiations.pop_back();
14048 }
14049 }
14050
14051 private:
14052 Sema &S;
14053 bool Enabled;
14054 bool AtEndOfTU;
14055 };
14056
14058 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
14059
14070
14071 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14072 const Decl *Pattern, Decl *Inst,
14073 LateInstantiatedAttrVec *LateAttrs = nullptr,
14074 LocalInstantiationScope *OuterMostScope = nullptr);
14075
14076 /// Update instantiation attributes after template was late parsed.
14077 ///
14078 /// Some attributes are evaluated based on the body of template. If it is
14079 /// late parsed, such attributes cannot be evaluated when declaration is
14080 /// instantiated. This function is used to update instantiation attributes
14081 /// when template definition is ready.
14082 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
14083
14084 void
14086 const Decl *Pattern, Decl *Inst,
14087 LateInstantiatedAttrVec *LateAttrs = nullptr,
14088 LocalInstantiationScope *OuterMostScope = nullptr);
14089
14090 /// In the MS ABI, we need to instantiate default arguments of dllexported
14091 /// default constructors along with the constructor definition. This allows IR
14092 /// gen to emit a constructor closure which calls the default constructor with
14093 /// its default arguments.
14095
14097 ParmVarDecl *Param);
14098 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
14100
14101 /// Instantiate (or find existing instantiation of) a function template with a
14102 /// given set of template arguments.
14103 ///
14104 /// Usually this should not be used, and template argument deduction should be
14105 /// used in its place.
14108 SourceLocation Loc,
14111
14112 /// Instantiate the definition of the given function from its
14113 /// template.
14114 ///
14115 /// \param PointOfInstantiation the point at which the instantiation was
14116 /// required. Note that this is not precisely a "point of instantiation"
14117 /// for the function, but it's close.
14118 ///
14119 /// \param Function the already-instantiated declaration of a
14120 /// function template specialization or member function of a class template
14121 /// specialization.
14122 ///
14123 /// \param Recursive if true, recursively instantiates any functions that
14124 /// are required by this instantiation.
14125 ///
14126 /// \param DefinitionRequired if true, then we are performing an explicit
14127 /// instantiation where the body of the function is required. Complain if
14128 /// there is no such body.
14129 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
14131 bool Recursive = false,
14132 bool DefinitionRequired = false,
14133 bool AtEndOfTU = false);
14136 const TemplateArgumentList *PartialSpecArgs,
14138 SourceLocation PointOfInstantiation,
14139 LateInstantiatedAttrVec *LateAttrs = nullptr,
14140 LocalInstantiationScope *StartingScope = nullptr);
14141
14142 /// Instantiates a variable template specialization by completing it
14143 /// with appropriate type information and initializer.
14145 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14146 const MultiLevelTemplateArgumentList &TemplateArgs);
14147
14148 /// BuildVariableInstantiation - Used after a new variable has been created.
14149 /// Sets basic variable data and decides whether to postpone the
14150 /// variable instantiation.
14151 void
14153 const MultiLevelTemplateArgumentList &TemplateArgs,
14154 LateInstantiatedAttrVec *LateAttrs,
14155 DeclContext *Owner,
14156 LocalInstantiationScope *StartingScope,
14157 bool InstantiatingVarTemplate = false,
14158 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14159
14160 /// Instantiate the initializer of a variable.
14162 VarDecl *Var, VarDecl *OldVar,
14163 const MultiLevelTemplateArgumentList &TemplateArgs);
14164
14165 /// Instantiate the definition of the given variable from its
14166 /// template.
14167 ///
14168 /// \param PointOfInstantiation the point at which the instantiation was
14169 /// required. Note that this is not precisely a "point of instantiation"
14170 /// for the variable, but it's close.
14171 ///
14172 /// \param Var the already-instantiated declaration of a templated variable.
14173 ///
14174 /// \param Recursive if true, recursively instantiates any functions that
14175 /// are required by this instantiation.
14176 ///
14177 /// \param DefinitionRequired if true, then we are performing an explicit
14178 /// instantiation where a definition of the variable is required. Complain
14179 /// if there is no such definition.
14180 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14181 VarDecl *Var, bool Recursive = false,
14182 bool DefinitionRequired = false,
14183 bool AtEndOfTU = false);
14184
14187 const MultiLevelTemplateArgumentList &TemplateArgs);
14188
14189 /// Find the instantiation of the given declaration within the
14190 /// current instantiation.
14191 ///
14192 /// This routine is intended to be used when \p D is a declaration
14193 /// referenced from within a template, that needs to mapped into the
14194 /// corresponding declaration within an instantiation. For example,
14195 /// given:
14196 ///
14197 /// \code
14198 /// template<typename T>
14199 /// struct X {
14200 /// enum Kind {
14201 /// KnownValue = sizeof(T)
14202 /// };
14203 ///
14204 /// bool getKind() const { return KnownValue; }
14205 /// };
14206 ///
14207 /// template struct X<int>;
14208 /// \endcode
14209 ///
14210 /// In the instantiation of X<int>::getKind(), we need to map the \p
14211 /// EnumConstantDecl for \p KnownValue (which refers to
14212 /// X<T>::<Kind>::KnownValue) to its instantiation
14213 /// (X<int>::<Kind>::KnownValue).
14214 /// \p FindInstantiatedDecl performs this mapping from within the
14215 /// instantiation of X<int>.
14216 NamedDecl *
14218 const MultiLevelTemplateArgumentList &TemplateArgs,
14219 bool FindingInstantiatedContext = false);
14220
14221 /// Finds the instantiation of the given declaration context
14222 /// within the current instantiation.
14223 ///
14224 /// \returns NULL if there was an error
14225 DeclContext *
14227 const MultiLevelTemplateArgumentList &TemplateArgs);
14228
14229 Decl *SubstDecl(Decl *D, DeclContext *Owner,
14230 const MultiLevelTemplateArgumentList &TemplateArgs);
14231
14232 /// Substitute the name and return type of a defaulted 'operator<=>' to form
14233 /// an implicit 'operator=='.
14235 FunctionDecl *Spaceship);
14236
14237 /// Performs template instantiation for all implicit template
14238 /// instantiations we have seen until this point.
14239 void PerformPendingInstantiations(bool LocalOnly = false,
14240 bool AtEndOfTU = true);
14241
14244 const MultiLevelTemplateArgumentList &TemplateArgs,
14245 bool EvaluateConstraints = true);
14246
14248 const DeclContext *Pattern,
14249 const MultiLevelTemplateArgumentList &TemplateArgs);
14250
14251private:
14252 /// Introduce the instantiated local variables into the local
14253 /// instantiation scope.
14254 void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14255 const FunctionDecl *PatternDecl,
14257 /// Introduce the instantiated function parameters into the local
14258 /// instantiation scope, and set the parameter names to those used
14259 /// in the template.
14260 bool addInstantiatedParametersToScope(
14261 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14263 const MultiLevelTemplateArgumentList &TemplateArgs);
14264
14265 /// Introduce the instantiated captures of the lambda into the local
14266 /// instantiation scope.
14267 bool addInstantiatedCapturesToScope(
14268 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14270 const MultiLevelTemplateArgumentList &TemplateArgs);
14271
14272 int ParsingClassDepth = 0;
14273
14274 class SavePendingParsedClassStateRAII {
14275 public:
14276 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14277
14278 ~SavePendingParsedClassStateRAII() {
14279 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14280 "there shouldn't be any pending delayed exception spec checks");
14281 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14282 "there shouldn't be any pending delayed exception spec checks");
14283 swapSavedState();
14284 }
14285
14286 private:
14287 Sema &S;
14289 SavedOverridingExceptionSpecChecks;
14291 SavedEquivalentExceptionSpecChecks;
14292
14293 void swapSavedState() {
14294 SavedOverridingExceptionSpecChecks.swap(
14295 S.DelayedOverridingExceptionSpecChecks);
14296 SavedEquivalentExceptionSpecChecks.swap(
14297 S.DelayedEquivalentExceptionSpecChecks);
14298 }
14299 };
14300
14301 ///@}
14302
14303 //
14304 //
14305 // -------------------------------------------------------------------------
14306 //
14307 //
14308
14309 /// \name C++ Variadic Templates
14310 /// Implementations are in SemaTemplateVariadic.cpp
14311 ///@{
14312
14313public:
14314 /// Determine whether an unexpanded parameter pack might be permitted in this
14315 /// location. Useful for error recovery.
14317
14318 /// The context in which an unexpanded parameter pack is
14319 /// being diagnosed.
14320 ///
14321 /// Note that the values of this enumeration line up with the first
14322 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14324 /// An arbitrary expression.
14326
14327 /// The base type of a class type.
14329
14330 /// The type of an arbitrary declaration.
14332
14333 /// The type of a data member.
14335
14336 /// The size of a bit-field.
14338
14339 /// The expression in a static assertion.
14341
14342 /// The fixed underlying type of an enumeration.
14344
14345 /// The enumerator value.
14347
14348 /// A using declaration.
14350
14351 /// A friend declaration.
14353
14354 /// A declaration qualifier.
14356
14357 /// An initializer.
14359
14360 /// A default argument.
14362
14363 /// The type of a non-type template parameter.
14365
14366 /// The type of an exception.
14368
14369 /// Explicit specialization.
14371
14372 /// Partial specialization.
14374
14375 /// Microsoft __if_exists.
14377
14378 /// Microsoft __if_not_exists.
14380
14381 /// Lambda expression.
14383
14384 /// Block expression.
14386
14387 /// A type constraint.
14389
14390 // A requirement in a requires-expression.
14392
14393 // A requires-clause.
14395 };
14396
14397 /// Diagnose unexpanded parameter packs.
14398 ///
14399 /// \param Loc The location at which we should emit the diagnostic.
14400 ///
14401 /// \param UPPC The context in which we are diagnosing unexpanded
14402 /// parameter packs.
14403 ///
14404 /// \param Unexpanded the set of unexpanded parameter packs.
14405 ///
14406 /// \returns true if an error occurred, false otherwise.
14410
14411 /// If the given type contains an unexpanded parameter pack,
14412 /// diagnose the error.
14413 ///
14414 /// \param Loc The source location where a diagnostc should be emitted.
14415 ///
14416 /// \param T The type that is being checked for unexpanded parameter
14417 /// packs.
14418 ///
14419 /// \returns true if an error occurred, false otherwise.
14422
14423 /// If the given expression contains an unexpanded parameter
14424 /// pack, diagnose the error.
14425 ///
14426 /// \param E The expression that is being checked for unexpanded
14427 /// parameter packs.
14428 ///
14429 /// \returns true if an error occurred, false otherwise.
14432
14433 /// If the given requirees-expression contains an unexpanded reference to one
14434 /// of its own parameter packs, diagnose the error.
14435 ///
14436 /// \param RE The requiress-expression that is being checked for unexpanded
14437 /// parameter packs.
14438 ///
14439 /// \returns true if an error occurred, false otherwise.
14441
14442 /// If the given nested-name-specifier contains an unexpanded
14443 /// parameter pack, diagnose the error.
14444 ///
14445 /// \param SS The nested-name-specifier that is being checked for
14446 /// unexpanded parameter packs.
14447 ///
14448 /// \returns true if an error occurred, false otherwise.
14451
14452 /// If the given name contains an unexpanded parameter pack,
14453 /// diagnose the error.
14454 ///
14455 /// \param NameInfo The name (with source location information) that
14456 /// is being checked for unexpanded parameter packs.
14457 ///
14458 /// \returns true if an error occurred, false otherwise.
14461
14462 /// If the given template name contains an unexpanded parameter pack,
14463 /// diagnose the error.
14464 ///
14465 /// \param Loc The location of the template name.
14466 ///
14467 /// \param Template The template name that is being checked for unexpanded
14468 /// parameter packs.
14469 ///
14470 /// \returns true if an error occurred, false otherwise.
14474
14475 /// If the given template argument contains an unexpanded parameter
14476 /// pack, diagnose the error.
14477 ///
14478 /// \param Arg The template argument that is being checked for unexpanded
14479 /// parameter packs.
14480 ///
14481 /// \returns true if an error occurred, false otherwise.
14484
14485 /// Collect the set of unexpanded parameter packs within the given
14486 /// template argument.
14487 ///
14488 /// \param Arg The template argument that will be traversed to find
14489 /// unexpanded parameter packs.
14491 TemplateArgument Arg,
14493
14494 /// Collect the set of unexpanded parameter packs within the given
14495 /// template argument.
14496 ///
14497 /// \param Arg The template argument that will be traversed to find
14498 /// unexpanded parameter packs.
14502
14503 /// Collect the set of unexpanded parameter packs within the given
14504 /// type.
14505 ///
14506 /// \param T The type that will be traversed to find
14507 /// unexpanded parameter packs.
14510
14511 /// Collect the set of unexpanded parameter packs within the given
14512 /// type.
14513 ///
14514 /// \param TL The type that will be traversed to find
14515 /// unexpanded parameter packs.
14518
14519 /// Collect the set of unexpanded parameter packs within the given
14520 /// nested-name-specifier.
14521 ///
14522 /// \param NNS The nested-name-specifier that will be traversed to find
14523 /// unexpanded parameter packs.
14527
14528 /// Collect the set of unexpanded parameter packs within the given
14529 /// name.
14530 ///
14531 /// \param NameInfo The name that will be traversed to find
14532 /// unexpanded parameter packs.
14534 const DeclarationNameInfo &NameInfo,
14536
14537 /// Collect the set of unexpanded parameter packs within the given
14538 /// expression.
14541
14542 /// Invoked when parsing a template argument.
14543 ///
14544 /// \param Arg the template argument, which may already be invalid.
14545 ///
14546 /// If it is followed by ellipsis, this function is called before
14547 /// `ActOnPackExpansion`.
14550
14551 /// Invoked when parsing a template argument followed by an
14552 /// ellipsis, which creates a pack expansion.
14553 ///
14554 /// \param Arg The template argument preceding the ellipsis, which
14555 /// may already be invalid.
14556 ///
14557 /// \param EllipsisLoc The location of the ellipsis.
14559 SourceLocation EllipsisLoc);
14560
14561 /// Invoked when parsing a type followed by an ellipsis, which
14562 /// creates a pack expansion.
14563 ///
14564 /// \param Type The type preceding the ellipsis, which will become
14565 /// the pattern of the pack expansion.
14566 ///
14567 /// \param EllipsisLoc The location of the ellipsis.
14569
14570 /// Construct a pack expansion type from the pattern of the pack
14571 /// expansion.
14573 SourceLocation EllipsisLoc,
14574 UnsignedOrNone NumExpansions);
14575
14576 /// Construct a pack expansion type from the pattern of the pack
14577 /// expansion.
14578 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14579 SourceLocation EllipsisLoc,
14580 UnsignedOrNone NumExpansions);
14581
14582 /// Invoked when parsing an expression followed by an ellipsis, which
14583 /// creates a pack expansion.
14584 ///
14585 /// \param Pattern The expression preceding the ellipsis, which will become
14586 /// the pattern of the pack expansion.
14587 ///
14588 /// \param EllipsisLoc The location of the ellipsis.
14589 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14590
14591 /// Invoked when parsing an expression followed by an ellipsis, which
14592 /// creates a pack expansion.
14593 ///
14594 /// \param Pattern The expression preceding the ellipsis, which will become
14595 /// the pattern of the pack expansion.
14596 ///
14597 /// \param EllipsisLoc The location of the ellipsis.
14598 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14599 UnsignedOrNone NumExpansions);
14600
14601 /// Determine whether we could expand a pack expansion with the
14602 /// given set of parameter packs into separate arguments by repeatedly
14603 /// transforming the pattern.
14604 ///
14605 /// \param EllipsisLoc The location of the ellipsis that identifies the
14606 /// pack expansion.
14607 ///
14608 /// \param PatternRange The source range that covers the entire pattern of
14609 /// the pack expansion.
14610 ///
14611 /// \param Unexpanded The set of unexpanded parameter packs within the
14612 /// pattern.
14613 ///
14614 /// \param ShouldExpand Will be set to \c true if the transformer should
14615 /// expand the corresponding pack expansions into separate arguments. When
14616 /// set, \c NumExpansions must also be set.
14617 ///
14618 /// \param RetainExpansion Whether the caller should add an unexpanded
14619 /// pack expansion after all of the expanded arguments. This is used
14620 /// when extending explicitly-specified template argument packs per
14621 /// C++0x [temp.arg.explicit]p9.
14622 ///
14623 /// \param NumExpansions The number of separate arguments that will be in
14624 /// the expanded form of the corresponding pack expansion. This is both an
14625 /// input and an output parameter, which can be set by the caller if the
14626 /// number of expansions is known a priori (e.g., due to a prior substitution)
14627 /// and will be set by the callee when the number of expansions is known.
14628 /// The callee must set this value when \c ShouldExpand is \c true; it may
14629 /// set this value in other cases.
14630 ///
14631 /// \returns true if an error occurred (e.g., because the parameter packs
14632 /// are to be instantiated with arguments of different lengths), false
14633 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
14634 /// must be set.
14636 SourceLocation EllipsisLoc, SourceRange PatternRange,
14638 const MultiLevelTemplateArgumentList &TemplateArgs,
14639 bool FailOnPackProducingTemplates, bool &ShouldExpand,
14640 bool &RetainExpansion, UnsignedOrNone &NumExpansions);
14641
14642 /// Determine the number of arguments in the given pack expansion
14643 /// type.
14644 ///
14645 /// This routine assumes that the number of arguments in the expansion is
14646 /// consistent across all of the unexpanded parameter packs in its pattern.
14647 ///
14648 /// Returns an empty Optional if the type can't be expanded.
14650 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
14651
14654 const MultiLevelTemplateArgumentList &TemplateArgs);
14655
14656 /// Determine whether the given declarator contains any unexpanded
14657 /// parameter packs.
14658 ///
14659 /// This routine is used by the parser to disambiguate function declarators
14660 /// with an ellipsis prior to the ')', e.g.,
14661 ///
14662 /// \code
14663 /// void f(T...);
14664 /// \endcode
14665 ///
14666 /// To determine whether we have an (unnamed) function parameter pack or
14667 /// a variadic function.
14668 ///
14669 /// \returns true if the declarator contains any unexpanded parameter packs,
14670 /// false otherwise.
14672
14673 /// Returns the pattern of the pack expansion for a template argument.
14674 ///
14675 /// \param OrigLoc The template argument to expand.
14676 ///
14677 /// \param Ellipsis Will be set to the location of the ellipsis.
14678 ///
14679 /// \param NumExpansions Will be set to the number of expansions that will
14680 /// be generated from this pack expansion, if known a priori.
14683 SourceLocation &Ellipsis,
14684 UnsignedOrNone &NumExpansions) const;
14685
14686 /// Given a template argument that contains an unexpanded parameter pack, but
14687 /// which has already been substituted, attempt to determine the number of
14688 /// elements that will be produced once this argument is fully-expanded.
14689 ///
14690 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
14691 /// avoid actually expanding the pack where possible.
14693
14694 /// Called when an expression computing the size of a parameter pack
14695 /// is parsed.
14696 ///
14697 /// \code
14698 /// template<typename ...Types> struct count {
14699 /// static const unsigned value = sizeof...(Types);
14700 /// };
14701 /// \endcode
14702 ///
14703 //
14704 /// \param OpLoc The location of the "sizeof" keyword.
14705 /// \param Name The name of the parameter pack whose size will be determined.
14706 /// \param NameLoc The source location of the name of the parameter pack.
14707 /// \param RParenLoc The location of the closing parentheses.
14709 IdentifierInfo &Name,
14710 SourceLocation NameLoc,
14711 SourceLocation RParenLoc);
14712
14713 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
14714 SourceLocation EllipsisLoc,
14715 SourceLocation LSquareLoc, Expr *IndexExpr,
14716 SourceLocation RSquareLoc);
14717
14718 ExprResult BuildPackIndexingExpr(Expr *PackExpression,
14719 SourceLocation EllipsisLoc, Expr *IndexExpr,
14720 SourceLocation RSquareLoc,
14721 ArrayRef<Expr *> ExpandedExprs = {},
14722 bool FullySubstituted = false);
14723
14724 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
14725 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
14726 tok::TokenKind Operator,
14727 SourceLocation EllipsisLoc, Expr *RHS,
14728 SourceLocation RParenLoc);
14729 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
14730 SourceLocation LParenLoc, Expr *LHS,
14731 BinaryOperatorKind Operator,
14732 SourceLocation EllipsisLoc, Expr *RHS,
14733 SourceLocation RParenLoc,
14734 UnsignedOrNone NumExpansions);
14735 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
14736 BinaryOperatorKind Operator);
14737
14738 ///@}
14739
14740 //
14741 //
14742 // -------------------------------------------------------------------------
14743 //
14744 //
14745
14746 /// \name Constraints and Concepts
14747 /// Implementations are in SemaConcept.cpp
14748 ///@{
14749
14750public:
14752 const llvm::FoldingSetNodeID &ID) {
14753 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
14754 SatisfactionStack.emplace_back(Can, ID);
14755 }
14756
14757 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
14758
14760 const llvm::FoldingSetNodeID &ID) const {
14761 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
14762 return llvm::is_contained(SatisfactionStack,
14763 SatisfactionStackEntryTy{Can, ID});
14764 }
14765
14767 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
14768
14769 // Resets the current SatisfactionStack for cases where we are instantiating
14770 // constraints as a 'side effect' of normal instantiation in a way that is not
14771 // indicative of recursive definition.
14774 Sema &SemaRef;
14775
14776 public:
14778 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
14779 }
14780
14782 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
14783 }
14784 };
14785
14788 SatisfactionStack.swap(NewSS);
14789 }
14790
14792 llvm::PointerUnion<const NamedDecl *,
14794
14795 /// Check whether the given expression is a valid constraint expression.
14796 /// A diagnostic is emitted if it is not, false is returned, and
14797 /// PossibleNonPrimary will be set to true if the failure might be due to a
14798 /// non-primary expression being used as an atomic constraint.
14799 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
14800 bool *PossibleNonPrimary = nullptr,
14801 bool IsTrailingRequiresClause = false);
14802
14803 /// \brief Check whether the given list of constraint expressions are
14804 /// satisfied (as if in a 'conjunction') given template arguments.
14805 /// \param Template the template-like entity that triggered the constraints
14806 /// check (either a concept or a constrained entity).
14807 /// \param ConstraintExprs a list of constraint expressions, treated as if
14808 /// they were 'AND'ed together.
14809 /// \param TemplateArgLists the list of template arguments to substitute into
14810 /// the constraint expression.
14811 /// \param TemplateIDRange The source range of the template id that
14812 /// caused the constraints check.
14813 /// \param Satisfaction if true is returned, will contain details of the
14814 /// satisfaction, with enough information to diagnose an unsatisfied
14815 /// expression.
14816 /// \returns true if an error occurred and satisfaction could not be checked,
14817 /// false otherwise.
14820 ArrayRef<AssociatedConstraint> AssociatedConstraints,
14821 const MultiLevelTemplateArgumentList &TemplateArgLists,
14822 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
14823 const ConceptReference *TopLevelConceptId = nullptr,
14824 Expr **ConvertedExpr = nullptr);
14825
14826 /// \brief Check whether the given non-dependent constraint expression is
14827 /// satisfied. Returns false and updates Satisfaction with the satisfaction
14828 /// verdict if successful, emits a diagnostic and returns true if an error
14829 /// occurred and satisfaction could not be determined.
14830 ///
14831 /// \returns true if an error occurred, false otherwise.
14832 bool
14834 ConstraintSatisfaction &Satisfaction);
14835
14836 /// Check whether the given function decl's trailing requires clause is
14837 /// satisfied, if any. Returns false and updates Satisfaction with the
14838 /// satisfaction verdict if successful, emits a diagnostic and returns true if
14839 /// an error occurred and satisfaction could not be determined.
14840 ///
14841 /// \returns true if an error occurred, false otherwise.
14843 ConstraintSatisfaction &Satisfaction,
14844 SourceLocation UsageLoc = SourceLocation(),
14845 bool ForOverloadResolution = false);
14846
14847 // Calculates whether two constraint expressions are equal irrespective of a
14848 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
14849 // 'New', which are the "source" of the constraint, since this is necessary
14850 // for figuring out the relative 'depth' of the constraint. The depth of the
14851 // 'primary template' and the 'instantiated from' templates aren't necessarily
14852 // the same, such as a case when one is a 'friend' defined in a class.
14854 const Expr *OldConstr,
14856 const Expr *NewConstr);
14857
14858 // Calculates whether the friend function depends on an enclosing template for
14859 // the purposes of [temp.friend] p9.
14861
14862 /// \brief Ensure that the given template arguments satisfy the constraints
14863 /// associated with the given template, emitting a diagnostic if they do not.
14864 ///
14865 /// \param Template The template to which the template arguments are being
14866 /// provided.
14867 ///
14868 /// \param TemplateArgs The converted, canonicalized template arguments.
14869 ///
14870 /// \param TemplateIDRange The source range of the template id that
14871 /// caused the constraints check.
14872 ///
14873 /// \returns true if the constrains are not satisfied or could not be checked
14874 /// for satisfaction, false if the constraints are satisfied.
14877 const MultiLevelTemplateArgumentList &TemplateArgs,
14878 SourceRange TemplateIDRange);
14879
14880 bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
14882 ArrayRef<TemplateArgument> TemplateArgs,
14883 ConstraintSatisfaction &Satisfaction);
14884
14885 /// \brief Emit diagnostics explaining why a constraint expression was deemed
14886 /// unsatisfied.
14887 /// \param First whether this is the first time an unsatisfied constraint is
14888 /// diagnosed for this error.
14890 SourceLocation Loc = {},
14891 bool First = true);
14892
14893 /// \brief Emit diagnostics explaining why a constraint expression was deemed
14894 /// unsatisfied.
14895 void
14897 bool First = true);
14898
14901 ArrayRef<AssociatedConstraint> AssociatedConstraints);
14902
14903 /// \brief Check whether the given declaration's associated constraints are
14904 /// at least as constrained than another declaration's according to the
14905 /// partial ordering of constraints.
14906 ///
14907 /// \param Result If no error occurred, receives the result of true if D1 is
14908 /// at least constrained than D2, and false otherwise.
14909 ///
14910 /// \returns true if an error occurred, false otherwise.
14911 bool IsAtLeastAsConstrained(const NamedDecl *D1,
14913 const NamedDecl *D2,
14915 bool &Result);
14916
14917 /// If D1 was not at least as constrained as D2, but would've been if a pair
14918 /// of atomic constraints involved had been declared in a concept and not
14919 /// repeated in two separate places in code.
14920 /// \returns true if such a diagnostic was emitted, false otherwise.
14924
14925 /// Cache the satisfaction of an atomic constraint.
14926 /// The key is based on the unsubstituted expression and the parameter
14927 /// mapping. This lets us not substituting the mapping more than once,
14928 /// which is (very!) expensive.
14929 /// FIXME: this should be private.
14930 llvm::DenseMap<llvm::FoldingSetNodeID,
14933
14934private:
14935 /// Caches pairs of template-like decls whose associated constraints were
14936 /// checked for subsumption and whether or not the first's constraints did in
14937 /// fact subsume the second's.
14938 llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
14939 SubsumptionCache;
14940 /// Caches the normalized associated constraints of declarations (concepts or
14941 /// constrained declarations). If an error occurred while normalizing the
14942 /// associated constraints of the template or concept, nullptr will be cached
14943 /// here.
14944 llvm::DenseMap<ConstrainedDeclOrNestedRequirement, NormalizedConstraint *>
14945 NormalizationCache;
14946
14947 /// Cache whether the associated constraint of a declaration
14948 /// is satisfied.
14949 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
14950 SatisfactionCache;
14951
14952 // The current stack of constraint satisfactions, so we can exit-early.
14954
14955 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
14956 /// LocalInstantiationScope of the current non-lambda function. For lambdas,
14957 /// use LambdaScopeForCallOperatorInstantiationRAII.
14958 bool
14959 SetupConstraintScope(FunctionDecl *FD,
14960 std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
14961 const MultiLevelTemplateArgumentList &MLTAL,
14963
14964 /// Used during constraint checking, sets up the constraint template argument
14965 /// lists, and calls SetupConstraintScope to set up the
14966 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
14967 std::optional<MultiLevelTemplateArgumentList>
14968 SetupConstraintCheckingTemplateArgumentsAndScope(
14969 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
14971
14972 ///@}
14973
14974 //
14975 //
14976 // -------------------------------------------------------------------------
14977 //
14978 //
14979
14980 /// \name Types
14981 /// Implementations are in SemaType.cpp
14982 ///@{
14983
14984public:
14985 /// A mapping that describes the nullability we've seen in each header file.
14987
14988 static int getPrintable(int I) { return I; }
14989 static unsigned getPrintable(unsigned I) { return I; }
14990 static bool getPrintable(bool B) { return B; }
14991 static const char *getPrintable(const char *S) { return S; }
14992 static StringRef getPrintable(StringRef S) { return S; }
14993 static const std::string &getPrintable(const std::string &S) { return S; }
14994 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
14995 return II;
14996 }
14998 static QualType getPrintable(QualType T) { return T; }
14999 static SourceRange getPrintable(SourceRange R) { return R; }
15001 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
15003
15004 enum class CompleteTypeKind {
15005 /// Apply the normal rules for complete types. In particular,
15006 /// treat all sizeless types as incomplete.
15008
15009 /// Relax the normal rules for complete types so that they include
15010 /// sizeless built-in types.
15012
15013 // FIXME: Eventually we should flip the default to Normal and opt in
15014 // to AcceptSizeless rather than opt out of it.
15016 };
15017
15019 const DeclSpec *DS = nullptr);
15021 const DeclSpec *DS = nullptr);
15022
15023 /// Build a pointer type.
15024 ///
15025 /// \param T The type to which we'll be building a pointer.
15026 ///
15027 /// \param Loc The location of the entity whose type involves this
15028 /// pointer type or, if there is no such entity, the location of the
15029 /// type that will have pointer type.
15030 ///
15031 /// \param Entity The name of the entity that involves the pointer
15032 /// type, if known.
15033 ///
15034 /// \returns A suitable pointer type, if there are no
15035 /// errors. Otherwise, returns a NULL type.
15037 DeclarationName Entity);
15038
15039 /// Build a reference type.
15040 ///
15041 /// \param T The type to which we'll be building a reference.
15042 ///
15043 /// \param Loc The location of the entity whose type involves this
15044 /// reference type or, if there is no such entity, the location of the
15045 /// type that will have reference type.
15046 ///
15047 /// \param Entity The name of the entity that involves the reference
15048 /// type, if known.
15049 ///
15050 /// \returns A suitable reference type, if there are no
15051 /// errors. Otherwise, returns a NULL type.
15053 DeclarationName Entity);
15054
15055 /// Build an array type.
15056 ///
15057 /// \param T The type of each element in the array.
15058 ///
15059 /// \param ASM C99 array size modifier (e.g., '*', 'static').
15060 ///
15061 /// \param ArraySize Expression describing the size of the array.
15062 ///
15063 /// \param Brackets The range from the opening '[' to the closing ']'.
15064 ///
15065 /// \param Entity The name of the entity that involves the array
15066 /// type, if known.
15067 ///
15068 /// \returns A suitable array type, if there are no errors. Otherwise,
15069 /// returns a NULL type.
15071 unsigned Quals, SourceRange Brackets,
15072 DeclarationName Entity);
15074
15075 /// Build an ext-vector type.
15076 ///
15077 /// Run the required checks for the extended vector type.
15079 SourceLocation AttrLoc);
15080 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
15081 SourceLocation AttrLoc);
15082
15084 Expr *CountExpr,
15085 bool CountInBytes,
15086 bool OrNull);
15087
15088 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
15089 /// expression is uninstantiated. If instantiated it will apply the
15090 /// appropriate address space to the type. This function allows dependent
15091 /// template variables to be used in conjunction with the address_space
15092 /// attribute
15093 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
15094 SourceLocation AttrLoc);
15095
15096 /// Same as above, but constructs the AddressSpace index if not provided.
15098 SourceLocation AttrLoc);
15099
15101
15103
15104 /// Build a function type.
15105 ///
15106 /// This routine checks the function type according to C++ rules and
15107 /// under the assumption that the result type and parameter types have
15108 /// just been instantiated from a template. It therefore duplicates
15109 /// some of the behavior of GetTypeForDeclarator, but in a much
15110 /// simpler form that is only suitable for this narrow use case.
15111 ///
15112 /// \param T The return type of the function.
15113 ///
15114 /// \param ParamTypes The parameter types of the function. This array
15115 /// will be modified to account for adjustments to the types of the
15116 /// function parameters.
15117 ///
15118 /// \param Loc The location of the entity whose type involves this
15119 /// function type or, if there is no such entity, the location of the
15120 /// type that will have function type.
15121 ///
15122 /// \param Entity The name of the entity that involves the function
15123 /// type, if known.
15124 ///
15125 /// \param EPI Extra information about the function type. Usually this will
15126 /// be taken from an existing function with the same prototype.
15127 ///
15128 /// \returns A suitable function type, if there are no errors. The
15129 /// unqualified type will always be a FunctionProtoType.
15130 /// Otherwise, returns a NULL type.
15132 SourceLocation Loc, DeclarationName Entity,
15134
15135 /// Build a member pointer type \c T Class::*.
15136 ///
15137 /// \param T the type to which the member pointer refers.
15138 /// \param Class the class type into which the member pointer points.
15139 /// \param Loc the location where this type begins
15140 /// \param Entity the name of the entity that will have this member pointer
15141 /// type
15142 ///
15143 /// \returns a member pointer type, if successful, or a NULL type if there was
15144 /// an error.
15146 CXXRecordDecl *Cls, SourceLocation Loc,
15147 DeclarationName Entity);
15148
15149 /// Build a block pointer type.
15150 ///
15151 /// \param T The type to which we'll be building a block pointer.
15152 ///
15153 /// \param Loc The source location, used for diagnostics.
15154 ///
15155 /// \param Entity The name of the entity that involves the block pointer
15156 /// type, if known.
15157 ///
15158 /// \returns A suitable block pointer type, if there are no
15159 /// errors. Otherwise, returns a NULL type.
15161 DeclarationName Entity);
15162
15163 /// Build a paren type including \p T.
15166
15167 /// Build a Read-only Pipe type.
15168 ///
15169 /// \param T The type to which we'll be building a Pipe.
15170 ///
15171 /// \param Loc We do not use it for now.
15172 ///
15173 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15174 /// a NULL type.
15176
15177 /// Build a Write-only Pipe type.
15178 ///
15179 /// \param T The type to which we'll be building a Pipe.
15180 ///
15181 /// \param Loc We do not use it for now.
15182 ///
15183 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15184 /// a NULL type.
15186
15187 /// Build a bit-precise integer type.
15188 ///
15189 /// \param IsUnsigned Boolean representing the signedness of the type.
15190 ///
15191 /// \param BitWidth Size of this int type in bits, or an expression
15192 /// representing that.
15193 ///
15194 /// \param Loc Location of the keyword.
15195 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15196
15197 /// GetTypeForDeclarator - Convert the type for the specified
15198 /// declarator to Type instances.
15199 ///
15200 /// The result of this call will never be null, but the associated
15201 /// type may be a null type if there's an unrecoverable error.
15204
15205 /// Package the given type and TSI into a ParsedType.
15208 TypeSourceInfo **TInfo = nullptr);
15209
15211
15212 // Check whether the size of array element of type \p EltTy is a multiple of
15213 // its alignment and return false if it isn't.
15215
15216 void
15217 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15218 SourceLocation FallbackLoc,
15219 SourceLocation ConstQualLoc = SourceLocation(),
15220 SourceLocation VolatileQualLoc = SourceLocation(),
15221 SourceLocation RestrictQualLoc = SourceLocation(),
15222 SourceLocation AtomicQualLoc = SourceLocation(),
15223 SourceLocation UnalignedQualLoc = SourceLocation());
15224
15225 /// Retrieve the keyword associated
15227
15228 /// Adjust the calling convention of a method to be the ABI default if it
15229 /// wasn't specified explicitly. This handles method types formed from
15230 /// function type typedefs and typename template arguments.
15231 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15232 bool IsCtorOrDtor, SourceLocation Loc);
15233
15234 // Check if there is an explicit attribute, but only look through parens.
15235 // The intent is to look for an attribute on the current declarator, but not
15236 // one that came from a typedef.
15238
15239 /// Check whether a nullability type specifier can be added to the given
15240 /// type through some means not written in source (e.g. API notes).
15241 ///
15242 /// \param Type The type to which the nullability specifier will be
15243 /// added. On success, this type will be updated appropriately.
15244 ///
15245 /// \param Nullability The nullability specifier to add.
15246 ///
15247 /// \param DiagLoc The location to use for diagnostics.
15248 ///
15249 /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15250 /// array type (e.g., because it will decay to a pointer).
15251 ///
15252 /// \param OverrideExisting Whether to override an existing, locally-specified
15253 /// nullability specifier rather than complaining about the conflict.
15254 ///
15255 /// \returns true if nullability cannot be applied, false otherwise.
15257 NullabilityKind Nullability,
15258 SourceLocation DiagLoc,
15259 bool AllowArrayTypes,
15260 bool OverrideExisting);
15261
15262 /// Get the type of expression E, triggering instantiation to complete the
15263 /// type if necessary -- that is, if the expression refers to a templated
15264 /// static data member of incomplete array type.
15265 ///
15266 /// May still return an incomplete type if instantiation was not possible or
15267 /// if the type is incomplete for a different reason. Use
15268 /// RequireCompleteExprType instead if a diagnostic is expected for an
15269 /// incomplete expression type.
15271
15273
15274 /// Ensure that the type of the given expression is complete.
15275 ///
15276 /// This routine checks whether the expression \p E has a complete type. If
15277 /// the expression refers to an instantiable construct, that instantiation is
15278 /// performed as needed to complete its type. Furthermore
15279 /// Sema::RequireCompleteType is called for the expression's type (or in the
15280 /// case of a reference type, the referred-to type).
15281 ///
15282 /// \param E The expression whose type is required to be complete.
15283 /// \param Kind Selects which completeness rules should be applied.
15284 /// \param Diagnoser The object that will emit a diagnostic if the type is
15285 /// incomplete.
15286 ///
15287 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15288 /// otherwise.
15290 TypeDiagnoser &Diagnoser);
15291 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15292
15293 template <typename... Ts>
15294 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15295 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15297 }
15298
15299 // Returns the underlying type of a decltype with the given expression.
15301
15303 /// If AsUnevaluated is false, E is treated as though it were an evaluated
15304 /// context, such as when building a type for decltype(auto).
15305 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15306
15307 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15308 SourceLocation Loc,
15309 SourceLocation EllipsisLoc);
15310 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15311 SourceLocation Loc, SourceLocation EllipsisLoc,
15312 bool FullySubstituted = false,
15313 ArrayRef<QualType> Expansions = {});
15314
15315 using UTTKind = UnaryTransformType::UTTKind;
15317 SourceLocation Loc);
15323 SourceLocation Loc);
15325 SourceLocation Loc);
15327 SourceLocation Loc);
15328
15330 return BuiltinRemoveReference(BaseType, UTTKind::RemoveCVRef, Loc);
15331 }
15332
15334 SourceLocation Loc);
15336 SourceLocation Loc);
15337
15338 bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15339
15340 /// Ensure that the type T is a literal type.
15341 ///
15342 /// This routine checks whether the type @p T is a literal type. If @p T is an
15343 /// incomplete type, an attempt is made to complete it. If @p T is a literal
15344 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15345 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15346 /// it the type @p T), along with notes explaining why the type is not a
15347 /// literal type, and returns true.
15348 ///
15349 /// @param Loc The location in the source that the non-literal type
15350 /// diagnostic should refer to.
15351 ///
15352 /// @param T The type that this routine is examining for literalness.
15353 ///
15354 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15355 ///
15356 /// @returns @c true if @p T is not a literal type and a diagnostic was
15357 /// emitted, @c false otherwise.
15359 TypeDiagnoser &Diagnoser);
15360 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15361
15362 template <typename... Ts>
15363 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15364 const Ts &...Args) {
15365 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15366 return RequireLiteralType(Loc, T, Diagnoser);
15367 }
15368
15371 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
15372 }
15373
15374 /// Ensure that the type T is a complete type.
15375 ///
15376 /// This routine checks whether the type @p T is complete in any
15377 /// context where a complete type is required. If @p T is a complete
15378 /// type, returns false. If @p T is a class template specialization,
15379 /// this routine then attempts to perform class template
15380 /// instantiation. If instantiation fails, or if @p T is incomplete
15381 /// and cannot be completed, issues the diagnostic @p diag (giving it
15382 /// the type @p T) and returns true.
15383 ///
15384 /// @param Loc The location in the source that the incomplete type
15385 /// diagnostic should refer to.
15386 ///
15387 /// @param T The type that this routine is examining for completeness.
15388 ///
15389 /// @param Kind Selects which completeness rules should be applied.
15390 ///
15391 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15392 /// @c false otherwise.
15394 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15396 CompleteTypeKind Kind, unsigned DiagID);
15397
15399 TypeDiagnoser &Diagnoser) {
15400 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
15401 }
15402 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15403 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
15404 }
15405
15406 template <typename... Ts>
15407 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15408 const Ts &...Args) {
15409 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15410 return RequireCompleteType(Loc, T, Diagnoser);
15411 }
15412
15413 /// Determine whether a declaration is visible to name lookup.
15414 bool isVisible(const NamedDecl *D) {
15415 return D->isUnconditionallyVisible() ||
15416 isAcceptableSlow(D, AcceptableKind::Visible);
15417 }
15418
15419 /// Determine whether a declaration is reachable.
15420 bool isReachable(const NamedDecl *D) {
15421 // All visible declarations are reachable.
15422 return D->isUnconditionallyVisible() ||
15423 isAcceptableSlow(D, AcceptableKind::Reachable);
15424 }
15425
15426 /// Determine whether a declaration is acceptable (visible/reachable).
15428 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15429 }
15430
15431 /// Determine if \p D and \p Suggested have a structurally compatible
15432 /// layout as described in C11 6.2.7/1.
15433 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15434
15435 /// Determine if \p D has a visible definition. If not, suggest a declaration
15436 /// that should be made visible to expose the definition.
15437 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15438 bool OnlyNeedComplete = false);
15440 NamedDecl *Hidden;
15441 return hasVisibleDefinition(const_cast<NamedDecl *>(D), &Hidden);
15442 }
15443 /// Determine if \p D has a definition which allows we redefine it in current
15444 /// TU. \p Suggested is the definition that should be made visible to expose
15445 /// the definition.
15446 bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
15447 bool &Visible);
15449 NamedDecl *Hidden;
15450 return isRedefinitionAllowedFor(const_cast<NamedDecl *>(D), &Hidden,
15451 Visible);
15452 }
15453
15454 /// Determine if \p D has a reachable definition. If not, suggest a
15455 /// declaration that should be made reachable to expose the definition.
15456 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15457 bool OnlyNeedComplete = false);
15459 NamedDecl *Hidden;
15460 return hasReachableDefinition(D, &Hidden);
15461 }
15462
15463 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15464 AcceptableKind Kind,
15465 bool OnlyNeedComplete = false);
15467 NamedDecl *Hidden;
15468 return hasAcceptableDefinition(D, &Hidden, Kind);
15469 }
15470
15471 /// Try to parse the conditional expression attached to an effect attribute
15472 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15473 /// optional on error.
15474 std::optional<FunctionEffectMode>
15475 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15476
15477private:
15478 /// The implementation of RequireCompleteType
15479 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15480 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15481
15482 /// Nullability type specifiers.
15483 IdentifierInfo *Ident__Nonnull = nullptr;
15484 IdentifierInfo *Ident__Nullable = nullptr;
15485 IdentifierInfo *Ident__Nullable_result = nullptr;
15486 IdentifierInfo *Ident__Null_unspecified = nullptr;
15487
15488 ///@}
15489
15490 //
15491 //
15492 // -------------------------------------------------------------------------
15493 //
15494 //
15495
15496 /// \name FixIt Helpers
15497 /// Implementations are in SemaFixItUtils.cpp
15498 ///@{
15499
15500public:
15501 /// Get a string to suggest for zero-initialization of a type.
15503 SourceLocation Loc) const;
15504 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15505
15506 ///@}
15507
15508 //
15509 //
15510 // -------------------------------------------------------------------------
15511 //
15512 //
15513
15514 /// \name Function Effects
15515 /// Implementations are in SemaFunctionEffects.cpp
15516 ///@{
15517public:
15520
15523 std::optional<FunctionEffectWithCondition>
15524 Old; // Invalid when 'Kind' is 'Added'.
15525 std::optional<FunctionEffectWithCondition>
15526 New; // Invalid when 'Kind' is 'Removed'.
15527
15528 StringRef effectName() const {
15529 if (Old)
15530 return Old.value().Effect.name();
15531 return New.value().Effect.name();
15532 }
15533
15534 /// Describes the result of effects differing between a base class's virtual
15535 /// method and an overriding method in a subclass.
15536 enum class OverrideResult {
15539 Merge // Merge missing effect from base to derived.
15540 };
15541
15542 /// Return true if adding or removing the effect as part of a type
15543 /// conversion should generate a diagnostic.
15545 const FunctionEffectsRef &SrcFX,
15546 QualType DstType,
15547 const FunctionEffectsRef &DstFX) const;
15548
15549 /// Return true if adding or removing the effect in a redeclaration should
15550 /// generate a diagnostic.
15551 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
15552 const FunctionEffectsRef &OldFX,
15553 const FunctionDecl &NewFunction,
15554 const FunctionEffectsRef &NewFX) const;
15555
15556 /// Return true if adding or removing the effect in a C++ virtual method
15557 /// override should generate a diagnostic.
15559 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
15560 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
15561 };
15562
15563 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
15564 /// Caller should short-circuit by checking for equality first.
15566 const FunctionEffectsRef &New);
15567 };
15568
15569 /// All functions/lambdas/blocks which have bodies and which have a non-empty
15570 /// FunctionEffectsRef to be verified.
15572
15573 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
15574 /// are all null.
15576
15577public:
15578 /// Warn and return true if adding a function effect to a set would create a
15579 /// conflict.
15582 SourceLocation NewAttrLoc);
15583
15584 // Report a failure to merge function effects between declarations due to a
15585 // conflict.
15586 void
15588 SourceLocation NewLoc,
15589 SourceLocation OldLoc);
15590
15591 /// Inline checks from the start of maybeAddDeclWithEffects, to
15592 /// minimize performance impact on code not using effects.
15593 template <class FuncOrBlockDecl>
15594 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
15595 if (Context.hasAnyFunctionEffects())
15596 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
15598 }
15599
15600 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
15601 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15602
15603 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
15604 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15605
15607
15608 ///@}
15609};
15610
15611DeductionFailureInfo
15613 sema::TemplateDeductionInfo &Info);
15614
15615/// Contains a late templated function.
15616/// Will be parsed at the end of the translation unit, used by Sema & Parser.
15619 /// The template function declaration to be late parsed.
15621 /// Floating-point options in the point of definition.
15623};
15624
15625template <>
15627 PragmaMsStackAction Action,
15628 llvm::StringRef StackSlotLabel,
15630
15631} // end namespace clang
15632
15633#endif
#define V(N, I)
Forward declaration of all AST node types.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines Expressions and AST nodes for C++2a concepts.
Defines enumerations for expression traits intrinsics.
Token Tok
The Token.
FormatToken * Previous
The previous token in the unwrapped line.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines several types used to describe C++ lambda expressions that are shared between the parser and ...
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::Module class, which describes a module in the source code.
#define SM(sm)
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
AccessResult
A copy of Sema's enum without AR_delayed.
CastType
Definition SemaCast.cpp:49
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, bool inFunctionCall, VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
Sema::AllowedExplicit AllowedExplicit
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
Defines a utilitiy for warning once when close to out of stack space.
Defines the clang::TemplateNameKind enum.
Defines the clang::TokenKind enum and support functions.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
TypePropertyCache< Private > Cache
Definition Type.cpp:4785
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
Represents a member of a struct/union/class.
Definition Decl.h:3160
a trap message and trap category.
A class for storing results from argument-dependent lookup.
Definition Lookup.h:871
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:34
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:430
Writes an AST file containing the contents of a translation unit.
Definition ASTWriter.h:97
Represents an access specifier followed by colon ':'.
Definition DeclCXX.h:86
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2721
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
Attr - This represents one attribute.
Definition Attr.h:45
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3496
A binding in a decomposition declaration.
Definition DeclCXX.h:4185
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4654
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2943
Represents a C++ base or member initializer.
Definition DeclCXX.h:2369
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2628
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
CXXFieldCollector - Used to keep track of CXXFieldDecls during parsing of C++ classes.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
Represents the this expression in C++.
Definition ExprCXX.h:1155
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:69
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition Decl.h:4926
CaseStmt - Represent a case statement.
Definition Stmt.h:1920
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3610
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
Declaration of a class template.
Represents a class template specialization, which refers to a class template with a given set of temp...
Abstract interface for a consumer of code-completion information.
Declaration of a C++20 concept.
A reference to a concept and its template args, as it appears in the code.
Definition ASTConcept.h:130
Represents the specialization of a concept - evaluates to a prvalue of type bool.
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition DeclCXX.h:3677
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
The information about the darwin SDK that was used during this compilation.
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition DeclBase.h:1382
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
Captures information about "declaration specifiers".
Definition DeclSpec.h:217
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:859
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
The name of a declaration.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
A decomposition declaration.
Definition DeclCXX.h:4249
Captures a template argument whose value has been deduced via c++ template argument deduction.
Definition Template.h:331
A dependently-generated diagnostic.
Designation - Represent a full designation, which is a sequence of designators.
Definition Designator.h:208
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3423
Represents an enum.
Definition Decl.h:4007
Store information needed for an explicit specifier.
Definition DeclCXX.h:1924
The return type of classify().
Definition Expr.h:337
This represents one expression.
Definition Expr.h:112
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:802
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
An abstract interface that should be implemented by external AST sources that also provide informatio...
virtual void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs)
Read the set of tentative definitions known to the external Sema source.
virtual void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls)
Read the set of unused file-scope declarations known to the external Sema source.
virtual void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls)
Read the set of ext_vector type declarations known to the external Sema source.
virtual void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls)
Read the set of delegating constructors known to the external Sema source.
Represents difference between two FPOptions values.
FPOptionsOverride getChangesFrom(const FPOptions &Base) const
Return difference with the given option set.
Represents a member of a struct/union/class.
Definition Decl.h:3160
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
A mapping from file IDs to a record of whether we've seen nullability information in that file.
Definition Sema.h:258
FileNullability & operator[](FileID file)
Definition Sema.h:269
FileNullability Nullability
Definition Sema.h:265
Represents a function declaration or definition.
Definition Decl.h:2000
A mutable set of FunctionEffect::Kind.
Definition TypeBase.h:5108
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5222
Kind
Identifies the particular effect.
Definition TypeBase.h:4870
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5054
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4843
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
Declaration of a template function.
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4476
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4450
One of these records is kept for each identifier that is lexed.
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:615
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3467
Describes an C or C++ initializer list.
Definition Expr.h:5233
Describes the kind of initialization being performed, along with location information for tokens rela...
Describes the sequence of initializations required to initialize a given object or reference with a s...
Describes an entity that is being initialized.
Represents the declaration of a label.
Definition Decl.h:524
FPEvalMethodKind
Possible float expression evaluation method choices.
ComplexRangeKind
Controls the various implementations for complex multiplication and.
FPExceptionModeKind
Possible floating point exception behavior.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Represents a lazily-loaded vector of data.
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:369
Represents the results of name lookup.
Definition Lookup.h:147
A global _GUID constant.
Definition DeclCXX.h:4398
An instance of this class represents the declaration of a property member.
Definition DeclCXX.h:4344
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4922
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
Abstract interface for a module loader.
Describes a module or submodule.
Definition Module.h:144
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
This represents a decl that may have a name.
Definition Decl.h:274
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:7896
Wrapper for void* pointer.
Definition Ownership.h:51
static OpaquePtr make(QualType P)
Definition Ownership.h:61
OpenCL supported extensions and optional core features.
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1153
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:298
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
Represents a parameter to a function.
Definition Decl.h:1790
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:937
Represents the parsed form of a C++ template argument.
void Emit(const DiagnosticBuilder &DB) const
PreferredTypeBuilder(ASTContext *Ctx, bool Enabled)
Definition Sema.h:292
void enterFunctionArgument(SourceLocation Tok, llvm::function_ref< QualType()> ComputeType)
Computing a type for the function argument may require running overloading, so we postpone its comput...
void enterCondition(Sema &S, SourceLocation Tok)
void enterTypeCast(SourceLocation Tok, QualType CastType)
Handles all type casts, including C-style cast, C++ casts, etc.
void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base)
void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS)
void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc)
void enterReturn(Sema &S, SourceLocation Tok)
void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType, const Designation &D)
Handles e.g. BaseType{ .D = Tok...
void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op)
void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc)
void enterVariableInit(SourceLocation Tok, Decl *D)
QualType get(SourceLocation Tok) const
Get the expected type associated with this location, if any.
Definition Sema.h:328
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Stores the type being destroyed by a pseudo-destructor expression.
Definition ExprCXX.h:2696
A (possibly-)qualified type.
Definition TypeBase.h:937
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
Represents a struct/union/class.
Definition Decl.h:4312
Represents the body of a requires-expression.
Definition DeclCXX.h:2098
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Smart pointer class that efficiently represents Objective-C method names.
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaBase(Sema &S)
Definition SemaBase.cpp:7
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
Definition Sema.h:1841
bool operator==(const AlignPackInfo &Info) const
Definition Sema.h:1901
static AlignPackInfo getFromRawEncoding(unsigned Encoding)
Definition Sema.h:1873
unsigned getPackNumber() const
Definition Sema.h:1891
bool IsXLStack() const
Definition Sema.h:1899
bool IsPackSet() const
Definition Sema.h:1893
AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
Definition Sema.h:1847
bool IsAlignAttr() const
Definition Sema.h:1887
bool IsPackAttr() const
Definition Sema.h:1885
bool operator!=(const AlignPackInfo &Info) const
Definition Sema.h:1907
AlignPackInfo(bool IsXL)
Definition Sema.h:1851
static uint32_t getRawEncoding(const AlignPackInfo &Info)
Definition Sema.h:1858
Mode getAlignMode() const
Definition Sema.h:1889
ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
Definition Sema.h:13593
BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
Definition Sema.h:8238
void diagnose(Sema &S, SourceLocation Loc, QualType T) override
Definition Sema.h:8243
void emit(const SemaDiagnosticBuilder &DB, std::index_sequence< Is... >) const
Definition Sema.h:8230
std::tuple< const Ts &... > Args
Definition Sema.h:8227
CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled=true)
Introduce a new scope where 'this' may be allowed (when enabled), using the given declaration (which ...
CompoundScopeRAII(Sema &S, bool IsStmtExpr=false)
Definition Sema.h:1292
std::pair< VarDecl *, Expr * > get() const
Definition Sema.h:7783
std::optional< bool > getKnownValue() const
Definition Sema.h:7787
A RAII object to temporarily push a declaration context.
Definition Sema.h:3467
ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext=true)
Definition Sema.h:3477
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10271
virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when the only matching conversion function is explicit.
virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when there are multiple possible conversion functions.
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10276
virtual bool match(QualType T)=0
Determine whether the specified type is a valid destination type for this conversion.
virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when the expression has incomplete class type.
DefaultedComparisonKind asComparison() const
Definition Sema.h:6359
DefaultedFunctionKind(CXXSpecialMemberKind CSM)
Definition Sema.h:6336
unsigned getDiagnosticIndex() const
Get the index of this function kind for use in diagnostics.
Definition Sema.h:6364
DefaultedFunctionKind(DefaultedComparisonKind Comp)
Definition Sema.h:6339
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6356
DeferDiagsRAII(Sema &S, bool DeferDiags)
Definition Sema.h:10013
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1355
DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool)
Enter a new scope.
Definition Sema.h:1374
void popUndelayed(DelayedDiagnosticsState state)
Undo a previous pushUndelayed().
Definition Sema.h:1398
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1367
sema::DelayedDiagnosticPool * getCurrentPool() const
Returns the current delayed-diagnostics pool.
Definition Sema.h:1370
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
void popWithoutEmitting(DelayedDiagnosticsState state)
Leave a delayed-diagnostic state that was previously pushed.
Definition Sema.h:1384
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1390
A helper class for building up ExtParameterInfos.
Definition Sema.h:12958
const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams)
Return a pointer (suitable for setting in an ExtProtoInfo) to the ExtParameterInfo array we've built ...
Definition Sema.h:12977
void set(unsigned index, FunctionProtoType::ExtParameterInfo info)
Set the ExtParameterInfo for the parameter at the given index,.
Definition Sema.h:12965
FPOptionsOverride getOverrides()
Definition Sema.h:13991
FullExprArg(Sema &actions)
Definition Sema.h:7727
ExprResult release()
Definition Sema.h:7729
friend class Sema
Definition Sema.h:7738
Expr * get() const
Definition Sema.h:7731
GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
Definition Sema.h:14003
SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
Definition Sema.h:10335
virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
bool match(QualType T) override
Match an integral or (possibly scoped) enumeration type.
ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion)
Definition Sema.h:10327
unsigned size() const
The number of exceptions in the exception specification.
Definition Sema.h:5458
ExceptionSpecificationType getExceptionSpecType() const
Get the computed exception specification type.
Definition Sema.h:5451
const QualType * data() const
The set of exceptions in the exception specification.
Definition Sema.h:5461
void CalledStmt(Stmt *S)
Integrate an invoked statement into the collected data.
void CalledExpr(Expr *E)
Integrate an invoked expression into the collected data.
Definition Sema.h:5467
FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const
Overwrite an EPI's exception specification with this computed exception specification.
Definition Sema.h:5474
LambdaScopeForCallOperatorInstantiationRAII(Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope=true)
LocalEagerInstantiationScope(Sema &S, bool AtEndOfTU)
Definition Sema.h:13960
static NameClassification DependentNonType()
Definition Sema.h:3681
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3691
ExprResult getExpression() const
Definition Sema.h:3717
NameClassification(const IdentifierInfo *Keyword)
Definition Sema.h:3654
static NameClassification Unknown()
Definition Sema.h:3661
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3665
NameClassificationKind getKind() const
Definition Sema.h:3715
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3709
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3697
NamedDecl * getNonTypeDecl() const
Definition Sema.h:3727
NameClassification(ParsedType Type)
Definition Sema.h:3651
TemplateName getTemplateName() const
Definition Sema.h:3732
ParsedType getType() const
Definition Sema.h:3722
TemplateNameKind getTemplateNameKind() const
Definition Sema.h:3741
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3671
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3703
static NameClassification UndeclaredNonType()
Definition Sema.h:3677
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3685
static NameClassification Error()
Definition Sema.h:3657
void operator()(sema::FunctionScopeInfo *Scope) const
Definition Sema.cpp:2468
PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct)
Definition SemaAttr.cpp:29
RequiredTemplateKind(TemplateNameIsRequiredTag)
Template name is unconditionally required.
Definition Sema.h:11358
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11360
RequiredTemplateKind(SourceLocation TemplateKWLoc=SourceLocation())
Template name is required if TemplateKWLoc is valid.
Definition Sema.h:11355
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12395
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12428
SFINAETrap(Sema &SemaRef, bool ForValidityCheck=false)
Definition Sema.h:12406
A derivative of BoundTypeDiagnoser for which the diagnostic's type parameter is preceded by a 0/1 enu...
Definition Sema.h:8255
void diagnose(Sema &S, SourceLocation Loc, QualType T) override
Definition Sema.h:8260
SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
Definition Sema.h:8257
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
Definition Sema.h:9277
SpecialMemberOverloadResult(CXXMethodDecl *MD)
Definition Sema.h:9264
CXXMethodDecl * getMethod() const
Definition Sema.h:9267
void setMethod(CXXMethodDecl *MD)
Definition Sema.h:9268
void addContextNote(SourceLocation UseLoc)
Definition Sema.h:13494
SynthesizedFunctionScope(Sema &S, DeclContext *DC)
Definition Sema.h:13482
SourceLocation getLocation() const
Definition Sema.h:12169
bool ContainsDecl(const NamedDecl *ND) const
Definition Sema.h:12159
const DeclContext * getDeclContext() const
Definition Sema.h:12165
TemplateCompareNewDeclInfo(const DeclContext *DeclCtx, const DeclContext *LexicalDeclCtx, SourceLocation Loc)
Definition Sema.h:12143
const NamedDecl * getDecl() const
Definition Sema.h:12157
TemplateCompareNewDeclInfo(const NamedDecl *ND)
Definition Sema.h:12142
const DeclContext * getLexicalDeclContext() const
Definition Sema.h:12161
TentativeAnalysisScope(Sema &SemaRef)
Definition Sema.h:12444
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
VerifyICEDiagnoser(bool Suppress=false)
Definition Sema.h:7686
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
void DeclareGlobalNewDelete()
DeclareGlobalNewDelete - Declare the global forms of operator new and delete.
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
QualType CheckSizelessVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function with the cfi_unchecked_callee attribute b...
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
QualType BuildParenType(QualType T)
Build a paren type including T.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1416
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition Sema.h:3559
FunctionDecl * FindUsualDeallocationFunction(SourceLocation StartLoc, ImplicitDeallocationParameters, DeclarationName Name, bool Diagnose=true)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc)
ActOnCXXTypeid - Parse typeid( something ).
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition Sema.h:13538
ExprResult ActOnCXXParenListInitExpr(ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn)
pragma optimize("[optimization-list]", on | off).
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraint)
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc)
ActOnCXXUuidof - Parse __uuidof( something ).
bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is a constant expression represen...
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E, UnresolvedLookupExpr *Lookup)
Build a call to 'operator co_await' if there is a suitable operator for the given expression.
ConceptDecl * ActOnStartConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, const IdentifierInfo *Name, SourceLocation NameLoc)
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8160
bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs (unless they are value dependent ...
Definition SemaAttr.cpp:503
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13522
bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base, const TypeSourceInfo *Derived)
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef< const Expr * > Args, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any non-ArgDependent DiagnoseIf...
bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum, unsigned Multiple)
BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr TheCall is a constant expr...
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From)
PerformContextuallyConvertToObjCPointer - Perform a contextual conversion of the expression From to a...
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result)
Constructs and populates an OverloadedCandidateSet from the given function.
SmallVector< Scope *, 2 > CurrentSEHFinally
Stack of active SEH __finally scopes. Can be empty.
Definition Sema.h:10919
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12987
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2541
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1120
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls)
MergeTypedefNameDecl - We just parsed a typedef 'New' which has the same name and scope as a previous...
TemplateDeductionResult DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType, sema::TemplateDeductionInfo &Info)
Deduce the template arguments of the given template from FromType.
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
friend class ASTWriter
Definition Sema.h:1559
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope, LabelDecl *Label, SourceLocation LabelLoc)
SmallVector< SmallVector< VTableUse, 16 >, 8 > SavedVTableUses
Definition Sema.h:13945
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
void PopParsingClass(ParsingClassState state)
Definition Sema.h:6527
void DiagnoseAbstractType(const CXXRecordDecl *RD)
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition Sema.h:10024
void LoadExternalWeakUndeclaredIdentifiers()
Load weak undeclared identifiers from the external source.
Definition Sema.cpp:1060
bool containsUnexpandedParameterPacks(Declarator &D)
Determine whether the given declarator contains any unexpanded parameter packs.
std::optional< QualType > BuiltinVectorMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
bool CheckExplicitObjectOverride(CXXMethodDecl *New, const CXXMethodDecl *Old)
llvm::SmallPtrSet< SpecialMemberDecl, 4 > SpecialMembersBeingDeclared
The C++ special members which we are currently in the process of declaring.
Definition Sema.h:6516
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc)
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs, SmallVectorImpl< const Attr * > &OutAttrs)
Process the attributes before creating an attributed statement.
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8210
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
llvm::DenseSet< Module * > & getLookupModules()
Get the set of additional modules that should be checked during name lookup.
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
bool isAlwaysConstantEvaluatedContext() const
Definition Sema.h:8128
bool isExternalWithNoLinkageType(const ValueDecl *VD) const
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can't b...
Definition Sema.cpp:934
bool isAttrContext() const
Definition Sema.h:6918
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested)
void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace)
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression's result is syntactically ignored,...
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8203
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition Sema.cpp:2641
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6278
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9293
@ LookupLabel
Label name lookup.
Definition Sema.h:9302
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9297
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9324
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9316
@ LookupOMPReductionName
Look up the name of an OpenMP user-defined reduction operation.
Definition Sema.h:9338
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9332
@ LookupObjCProtocolName
Look up the name of an Objective-C protocol.
Definition Sema.h:9334
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9329
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9309
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9336
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9320
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9305
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition Sema.h:9312
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9300
@ LookupOMPMapperName
Look up the name of an OpenMP user-defined mapper.
Definition Sema.h:9340
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9342
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition SemaExpr.cpp:411
llvm::DenseMap< IdentifierInfo *, SrcLocSet > IdentifierSourceLocations
Definition Sema.h:9243
LazyVector< TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2 > ExtVectorDeclsType
Definition Sema.h:4869
UnaryTransformType::UTTKind UTTKind
Definition Sema.h:15315
bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend)
Check that the expression co_await promise.final_suspend() shall not be potentially-throwing.
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc)
BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression is uninstantiated.
void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace)
Called on well-formed '#pragma clang attribute pop'.
void ActOnPopScope(SourceLocation Loc, Scope *S)
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement)
Completely replace the auto in TypeWithAuto by Replacement.
ExprResult ActOnConstantExpression(ExprResult Res)
void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value)
ActOnPragmaDetectMismatch - Call on well-formed #pragma detect_mismatch.
Definition SemaAttr.cpp:628
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:6215
SemaM68k & M68k()
Definition Sema.h:1466
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD)
Evaluate the implicit exception specification for a defaulted special member function.
bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod)
The parsed has entered a submodule.
bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind, unsigned &IntVal)
void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc)
Definition Sema.h:13603
StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef< Token > AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef< StringRef > Constraints, ArrayRef< StringRef > Clobbers, ArrayRef< Expr * > Exprs, SourceLocation EndLoc)
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E)
ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression found in an explicit(bool)...
bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum)
Returns true if the argument consists of one contiguous run of 1s with any number of 0s on either sid...
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
VarDecl * createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx)
Create a dummy variable within the declcontext of the lambda's call operator, for name lookup purpose...
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
void ActOnFinishCXXNonNestedClass()
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body)
ActOnLambdaExpr - This is called when the body of a lambda expression was successfully completed.
ExprResult SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr, const MultiLevelTemplateArgumentList &MLTAL)
Substitute concept template arguments in the constraint expression of a concept-id.
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
DelayedDiagnosticsState ParsingDeclState
Definition Sema.h:1350
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation.
bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack)
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
const Decl * PragmaAttributeCurrentTargetDecl
The declaration that is currently receiving an attribute from the pragma attribute stack.
Definition Sema.h:2106
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld, bool NewDeclIsDefn)
MergeFunctionDecl - We just parsed a function 'New' from declarator D which has the same name and sco...
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
bool hasReachableDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
MissingImportKind
Kinds of missing import.
Definition Sema.h:9731
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, ImplicitDeallocationParameters, bool Diagnose=true)
ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E)
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class)
Force the declaration of any implicitly-declared members of this class.
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, Expr *DefaultArg)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
bool areVectorTypesSameSize(QualType srcType, QualType destType)
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val, SkipBodyInfo *SkipBody=nullptr)
bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules)
TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
ActOnTemplateParameterList - Builds a TemplateParameterList, optionally constrained by RequiresClause...
static std::enable_if_t< std::is_base_of_v< Attr, AttrInfo >, SourceLocation > getAttrLoc(const AttrInfo &AL)
A helper function to provide Attribute Location for the Attr types AND the ParsedAttr.
Definition Sema.h:4814
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
void DiagnoseStaticAssertDetails(const Expr *E)
Try to print more useful information about a failed static_assert with expression \E.
void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
The parser has processed a module import translated from a include or similar preprocessing directive...
RetainOwnershipKind
Definition Sema.h:5019
OpaquePtr< QualType > TypeTy
Definition Sema.h:1276
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition SemaInit.cpp:168
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
void ActOnFinishDelayedMemberInitializers(Decl *Record)
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
bool CheckCXXThisType(SourceLocation Loc, QualType Type)
Check whether the type of 'this' is valid in the current context.
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class)
Perform qualified name lookup into all base classes of the given class.
void addImplicitTypedef(StringRef Name, QualType T)
Definition Sema.cpp:366
void PrintContextStack()
Definition Sema.h:13612
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword)
QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc)
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
StmtResult BuildAttributedStmt(SourceLocation AttrsLoc, ArrayRef< const Attr * > Attrs, Stmt *SubStmt)
Definition SemaStmt.cpp:631
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
SemaOpenMP & OpenMP()
Definition Sema.h:1501
void CheckDelegatingCtorCycles()
llvm::SmallSet< SourceLocation, 2 > SrcLocSet
Definition Sema.h:9242
void ActOnStartStmtExpr()
bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
llvm::function_ref< void(SourceLocation, PartialDiagnostic)> InstantiationContextDiagFuncRef
Definition Sema.h:2281
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6253
bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is visible.
Definition Sema.h:9607
bool FormatStringHasSArg(const StringLiteral *FExpr)
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
void ActOnStmtExprError()
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt={})
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
bool IsLastErrorImmediate
Is the last error level diagnostic immediate.
Definition Sema.h:1342
StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope)
bool BoundsSafetyCheckAssignmentToCountAttrPtr(QualType LHSTy, Expr *RHSExpr, AssignmentAction Action, SourceLocation Loc, const ValueDecl *Assignee, bool ShowFullyQualifiedAssigneeName)
Perform Bounds Safety Semantic checks for assigning to a __counted_by or __counted_by_or_null pointer...
void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode)
Called to set constant rounding mode for floating point operations.
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion)
AddAlignedAttr - Adds an aligned attribute to a particular declaration.
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
AccessResult CheckFriendAccess(NamedDecl *D)
Checks access to the target of a friend declaration.
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
static const IdentifierInfo * getPrintable(const IdentifierInfo *II)
Definition Sema.h:14994
StmtResult ActOnForEachLValueExpr(Expr *E)
In an Objective C collection iteration statement: for (x in y) x can be an arbitrary l-value expressi...
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1241
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition Sema.h:4727
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3541
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1813
QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc)
Looks for the std::type_identity template and instantiates it with Type, or returns a null type if ty...
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D)
ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a C++ if/switch/while/for statem...
std::optional< FunctionEffectMode > ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName)
Try to parse the conditional expression attached to an effect attribute (e.g.
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
void NoteAllFoundTemplates(TemplateName Name)
CXXRecordDecl * createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, unsigned LambdaDependencyKind, LambdaCaptureDefault CaptureDefault)
Create a new lambda closure type.
bool hasVisibleDefinition(const NamedDecl *D)
Definition Sema.h:15439
DelegatingCtorDeclsType DelegatingCtorDecls
All the delegating constructors seen so far in the file, used for cycle detection at the end of the T...
Definition Sema.h:6489
bool checkFunctionOrMethodParameterIndex(const Decl *D, const AttrInfo &AI, unsigned AttrArgNum, const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis=false, bool CanIndexVariadicArguments=false)
Check if IdxExpr is a valid parameter index for a function or instance method D.
Definition Sema.h:5113
void emitAndClearUnusedLocalTypedefWarnings()
Definition Sema.cpp:1151
bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs)
ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition Sema.h:6470
void ActOnForEachDeclStmt(DeclGroupPtrTy Decl)
Definition SemaStmt.cpp:85
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function)
TemplateName SubstTemplateName(SourceLocation TemplateKWLoc, NestedNameSpecifierLoc &QualifierLoc, TemplateName Name, SourceLocation NameLoc, const MultiLevelTemplateArgumentList &TemplateArgs)
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, const IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE)
AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular declaration.
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str)
VarDecl * buildCoroutinePromise(SourceLocation Loc)
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition Sema.h:1230
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, UnsignedOrNone NumExpansions, bool ExpectParameterPack, bool EvaluateConstraints=true)
ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen)
ActOnExpressionTrait - Parsed one of the unary type trait support pseudo-functions.
SemaCUDA & CUDA()
Definition Sema.h:1441
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD)
Check a completed declaration of an implicit special member.
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A, bool SkipArgCountCheck=false)
Handles semantic checking for features that are common to all attributes, such as checking whether a ...
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
Definition Sema.cpp:372
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:7803
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7805
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7804
void LateTemplateParserCB(void *P, LateParsedTemplate &LPT)
Callback to the parser to parse templated functions when needed.
Definition Sema.h:1323
void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc)
Adds the 'optnone' attribute to the function declaration if there are no conflicts; Loc represents th...
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Definition Sema.h:15398
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
static SourceRange getPrintable(SourceLocation L)
Definition Sema.h:15000
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
Decl * ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
bool needsRebuildOfDefaultArgOrInit() const
Definition Sema.h:8148
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicCallType::DoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
@ PartitionImplementation
'module X:Y;'
Definition Sema.h:9844
@ Interface
'export module X;'
Definition Sema.h:9841
@ Implementation
'module X;'
Definition Sema.h:9842
@ PartitionInterface
'export module X:Y;'
Definition Sema.h:9843
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition Sema.h:8290
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1223
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
void ActOnExitFunctionContext()
bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous)
Check ODR hashes for C/ObjC when merging types from modules.
Definition Sema.h:9554
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition Sema.h:10354
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10357
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10363
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10361
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:lifetime_capture_by(this)]] to STL container methods.
Definition SemaAttr.cpp:277
void RefersToMemberWithReducedAlignment(Expr *E, llvm::function_ref< void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action)
This function calls Action when it determines that E designates a misaligned member due to the packed...
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType)
Definition Sema.h:1771
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
@ AR_dependent
Definition Sema.h:1656
@ AR_accessible
Definition Sema.h:1654
@ AR_inaccessible
Definition Sema.h:1655
@ AR_delayed
Definition Sema.h:1657
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2444
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
@ Normal
Apply the normal rules for complete types.
Definition Sema.h:15007
@ AcceptSizeless
Relax the normal rules for complete types so that they include sizeless built-in types.
Definition Sema.h:15011
bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA)
Check whether the given statement can have musttail applied to it, issuing a diagnostic and returning...
Definition SemaStmt.cpp:660
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc)
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, SourceLocation EllipsisLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists)
Handle a friend tag declaration where the scope specifier was templated.
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
Preprocessor & getPreprocessor() const
Definition Sema.h:924
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:6896
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2313
StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope, LabelDecl *Label, SourceLocation LabelLoc)
QualType GetSignedSizelessVectorType(QualType V)
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro, Scope *CurContext)
Once the Lambdas capture are known, we can start to create the closure, call operator method,...
FunctionTemplateDecl * DeclareAggregateDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc)
Definition SemaCast.cpp:438
void AddTemplateParametersToLambdaCallOperator(CXXMethodDecl *CallOperator, CXXRecordDecl *Class, TemplateParameterList *TemplateParams)
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
class clang::Sema::DelayedDiagnostics DelayedDiagnostics
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
Annotation attributes are the only attributes allowed after an access specifier.
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool IsAssignmentOperator=false, unsigned NumContextualBoolArguments=0)
AddBuiltinCandidate - Add a candidate for a built-in operator.
llvm::SmallPtrSet< ConstantExpr *, 4 > FailedImmediateInvocations
Definition Sema.h:8279
void deduceOpenCLAddressSpace(ValueDecl *decl)
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl)
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2044
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition Sema.h:8191
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr)
static SourceRange getPrintable(const Expr *E)
Definition Sema.h:15001
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2038
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope)
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
void referenceDLLExportedClassMethods()
StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit=false)
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
DLLImportAttr * mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI)
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add function candidates found via argument-dependent lookup to the set of overloading candidates.
void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX)
Unconditionally add a Decl to DeclsWithEfffectsToVerify.
FunctionEffectKindSet AllEffectsToVerify
The union of all effects present on DeclsWithEffectsToVerify.
Definition Sema.h:15575
void setFunctionHasBranchIntoScope()
Definition Sema.cpp:2494
ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor)
ExprResult BuildCXXAssumeExpr(Expr *Assumption, const IdentifierInfo *AttrName, SourceRange Range)
ExtVectorDeclsType ExtVectorDecls
ExtVectorDecls - This is a list all the extended vector types.
Definition Sema.h:4874
ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val)
Definition SemaStmt.cpp:485
SourceLocation getOptimizeOffPragmaLocation() const
Get the location for the currently active "\#pragma clang optimizeoff". If this location is invalid,...
Definition Sema.h:2115
llvm::SmallSetVector< Expr *, 4 > MaybeODRUseExprSet
Store a set of either DeclRefExprs or MemberExprs that contain a reference to a variable (constant) t...
Definition Sema.h:6730
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg)
ActOnPragmaMSComment - Called on well formed #pragma comment(kind, "arg").
Definition SemaAttr.cpp:620
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc)
Build an ext-vector type.
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
SmallVector< AlignPackIncludeState, 8 > AlignPackIncludeStack
Definition Sema.h:2033
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
SimplerImplicitMoveMode
Definition Sema.h:11076
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
void PopParsingDeclaration(ParsingDeclState state, Decl *decl)
ErrorAttr * mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic)
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
bool CheckFormatStringsCompatible(FormatStringType FST, const StringLiteral *AuthoritativeFormatString, const StringLiteral *TestedFormatString, const Expr *FunctionCallArg=nullptr)
Verify that two format strings (as understood by attribute(format) and attribute(format_matches) are ...
void CheckMain(FunctionDecl *FD, const DeclSpec &D)
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext)
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
void ActOnComment(SourceRange Comment)
Definition Sema.cpp:2593
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init)
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
Definition Sema.h:4130
@ Default
= default ;
Definition Sema.h:4132
@ Delete
deleted-function-body
Definition Sema.h:4138
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit=nullptr)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal,...
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
bool RequireStructuralType(QualType T, SourceLocation Loc)
Require the given type to be a structural type, and diagnose if it is not.
ExprResult VerifyBitField(SourceLocation FieldLoc, const IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth)
VerifyBitField - verifies that a bit field expression is an ICE and has the correct width,...
concepts::Requirement * ActOnSimpleRequirement(Expr *E)
llvm::function_ref< void(llvm::raw_ostream &)> EntityPrinter
Definition Sema.h:13907
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue=true)
Definition SemaStmt.cpp:48
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
TemplateDeductionResult FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl< OriginalCallArg > const *OriginalCallArgs, bool PartialOverloading, bool PartialOrdering, bool ForOverloadSetAddressResolution, llvm::function_ref< bool(bool)> CheckNonDependent=[](bool) { return false;})
Finish template argument deduction for a function template, checking the deduced template arguments f...
void ActOnEndOfTranslationUnit()
ActOnEndOfTranslationUnit - This is called at the very end of the translation unit when EOF is reache...
Definition Sema.cpp:1230
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
ConceptDecl * ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C, Expr *ConstraintExpr, const ParsedAttributesView &Attrs)
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2045
void redelayDiagnostics(sema::DelayedDiagnosticPool &pool)
Given a set of delayed diagnostics, re-emit them as if they had been delayed in the current context i...
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD)
Diagnose methods which overload virtual methods in a base class without overriding any.
SemaHexagon & Hexagon()
Definition Sema.h:1456
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation=false, bool RetainFunctionScopeInfo=false)
Performs semantic analysis at the end of a function body.
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types?
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef)
Add an init-capture to a lambda scope.
FieldDecl * BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture)
Build a FieldDecl suitable to hold the given capture.
concepts::Requirement * ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc)
void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName)
Called on well formed #pragma bss_seg/data_seg/const_seg/code_seg.
Definition SemaAttr.cpp:847
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
void CheckThreadLocalForLargeAlignment(VarDecl *VD)
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc)
bool hasVisibleExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is an explicit specialization declaration for a...
bool IsInsideALocalClassWithinATemplateFunction()
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound=nullptr)
BuildOverloadedArrowExpr - Build a call to an overloaded operator-> (if one exists),...
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
llvm::DenseMap< llvm::FoldingSetNodeID, UnsubstitutedConstraintSatisfactionCacheResult > UnsubstitutedConstraintSatisfactionCache
Cache the satisfaction of an atomic constraint.
Definition Sema.h:14932
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
void ActOnTranslationUnitScope(Scope *S)
Scope actions.
Definition Sema.cpp:172
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand, Expr *Awaiter, bool IsImplicit=false)
SemaSYCL & SYCL()
Definition Sema.h:1526
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag)
Is the given member accessible for the purposes of deciding whether to define a special member functi...
concepts::Requirement::SubstitutionDiagnostic * createSubstDiagAt(SourceLocation Location, EntityPrinter Printer)
create a Requirement::SubstitutionDiagnostic with only a SubstitutedEntity and DiagLoc using ASTConte...
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
IdentifierInfo * getSuperIdentifier() const
Definition Sema.cpp:2868
StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:6908
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1650
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc)
void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, PragmaFloatControlKind Value)
ActOnPragmaFloatControl - Call on well-formed #pragma float_control.
Definition SemaAttr.cpp:663
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:833
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
LateParsedTemplateMapT LateParsedTemplateMap
Definition Sema.h:11323
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:11921
@ CTAK_DeducedFromArrayBound
The template argument was deduced from an array bound via template argument deduction.
Definition Sema.h:11932
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:11924
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:11928
bool SubstExprs(ArrayRef< Expr * > Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< Expr * > &Outputs)
Substitute the given template arguments into a list of expressions, expanding pack expansions if requ...
BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, const ParsedAttributesView &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition SemaDecl.cpp:671
void ActOnFinishFunctionDeclarationDeclarator(Declarator &D)
Called after parsing a function declarator belonging to a function declaration.
void ActOnPragmaMSPointersToMembers(LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc)
ActOnPragmaMSPointersToMembers - called on well formed #pragma pointers_to_members(representation met...
Definition SemaAttr.cpp:717
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
[module.interface]p6: A redeclaration of an entity X is implicitly exported if X was introduced by an...
void DiagnosePrecisionLossInComplexDivision()
ExprResult CheckUnevaluatedOperand(Expr *E)
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg)
ActOnParamDefaultArgument - Check whether the default argument provided for a function parameter is w...
bool DisableTypoCorrection
Tracks whether we are in a context where typo correction is disabled.
Definition Sema.h:9237
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand)
ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
SemaX86 & X86()
Definition Sema.h:1546
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Look for instances where it is likely the comma operator is confused with another operator.
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
llvm::DenseMap< NamedDecl *, NamedDecl * > VisibleNamespaceCache
Map from the most recent declaration of a namespace to the most recent visible declaration of that na...
Definition Sema.h:13542
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def)
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs)
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry)
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
ASTContext & Context
Definition Sema.h:1283
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading=false)
To be used for checking whether the arguments being passed to function exceeds the number of paramete...
Definition Sema.h:8115
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp:679
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
bool DiagIfReachable(SourceLocation Loc, ArrayRef< const Stmt * > Stmts, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the statements's reachability analysis.
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E)
LLVM_DECLARE_VIRTUAL_ANCHOR_FUNCTION()
This virtual key function only exists to limit the emission of debug info describing the Sema class.
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E)
Perform Bounds Safety semantic checks for uses of invalid uses counted_by or counted_by_or_null point...
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc)
ActOnCXXNullPtrLiteral - Parse 'nullptr'.
void ActOnCapturedRegionError()
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc)
Build a C++ typeid expression with a type operand.
void MarkUsedTemplateParametersForSubsumptionParameterMapping(const Expr *E, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are named in a given expression.
IdentifierSourceLocations TypoCorrectionFailures
A cache containing identifiers for which typo correction failed and their locations,...
Definition Sema.h:9248
FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC)
Definition Sema.h:7748
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc)
ActOnPragmaUnused - Called on well-formed '#pragma unused'.
Definition SemaAttr.cpp:935
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow)
Perform conversions on the LHS of a member access expression.
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition Sema.h:13549
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
concepts::TypeRequirement * BuildTypeRequirement(TypeSourceInfo *Type)
void DiagnoseTypeTraitDetails(const Expr *E)
If E represents a built-in type trait, or a known standard type trait, try to print more information ...
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod)
The parser has left a submodule.
void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, CheckNonDependentConversionsFlag UserConversionFlag, CXXRecordDecl *ActingContext=nullptr, QualType ObjectType=QualType(), Expr::Classification ObjectClassification={}, OverloadCandidateParamOrder PO={})
Check that implicit conversion sequences can be formed for each argument whose corresponding paramete...
void * SkippedDefinitionContext
Definition Sema.h:4356
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:15363
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
bool CheckCaseExpression(Expr *E)
void resetFPOptions(FPOptions FPO)
Definition Sema.h:11301
bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind)
Definition Sema.h:15466
bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument, const Decl **MalformedDecl=nullptr)
Tests whether Ty is an instance of std::type_identity and, if it is and TypeArgument is not NULL,...
bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType, bool &IncompatibleObjC)
isObjCPointerConversion - Determines whether this is an Objective-C pointer conversion.
bool currentModuleIsImplementation() const
Is the module scope we are an implementation unit?
Definition Sema.h:9828
DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path, bool IsPartition=false)
The parser has processed a module import declaration.
static bool getPrintable(bool B)
Definition Sema.h:14990
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1486
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult SubstConstraintExprWithoutSatisfaction(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, TrivialABIHandling TAH=TrivialABIHandling::IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain=false, bool(*IsPlausibleResult)(QualType)=nullptr)
Try to recover by turning the given expression into a call.
Definition Sema.cpp:2823
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
bool FunctionParamTypesAreEqual(ArrayRef< QualType > Old, ArrayRef< QualType > New, unsigned *ArgPos=nullptr, bool Reversed=false)
FunctionParamTypesAreEqual - This routine checks two function proto types for equality of their param...
SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags
Diagnostics that are emitted only if we discover that the given function must be codegen'ed.
Definition Sema.h:1411
void CheckDelayedMemberExceptionSpecs()
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:75
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
ExprResult BuildPackIndexingExpr(Expr *PackExpression, SourceLocation EllipsisLoc, Expr *IndexExpr, SourceLocation RSquareLoc, ArrayRef< Expr * > ExpandedExprs={}, bool FullySubstituted=false)
void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs)
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext)
void ActOnPragmaMSAllocText(SourceLocation PragmaLocation, StringRef Section, const SmallVector< std::tuple< IdentifierInfo *, SourceLocation > > &Functions)
Called on well-formed #pragma alloc_text().
Definition SemaAttr.cpp:899
ClassTemplateDecl * StdCoroutineTraitsCache
The C++ "std::coroutine_traits" template, which is defined in <coroutine_traits>
Definition Sema.h:3140
bool captureSwiftVersionIndependentAPINotes()
Whether APINotes should be gathered for all applicable Swift language versions, without being applied...
Definition Sema.h:1637
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2041
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void PrintInstantiationStack()
Definition Sema.h:13616
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used.
Definition Sema.h:3549
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
void CleanupVarDeclMarking()
bool CheckConstraintExpression(const Expr *CE, Token NextToken=Token(), bool *PossibleNonPrimary=nullptr, bool IsTrailingRequiresClause=false)
Check whether the given expression is a valid constraint expression.
ExprResult PerformImplicitObjectArgumentInitialization(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:754
bool isImmediateFunctionContext() const
Definition Sema.h:8140
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
ASTContext & getASTContext() const
Definition Sema.h:925
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1059
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:656
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:764
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef< QualType > Params)
DeclareGlobalAllocationFunction - Declares a single implicit global allocation function if it doesn't...
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE)
If the given requirees-expression contains an unexpanded reference to one of its own parameter packs,...
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
void CheckCoroutineWrapper(FunctionDecl *FD)
bool IsFloatingPointPromotion(QualType FromType, QualType ToType)
IsFloatingPointPromotion - Determines whether the conversion from FromType to ToType is a floating po...
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition Sema.h:6496
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
ASTContext::CXXRecordDeclRelocationInfo CheckCXX2CRelocatableAndReplaceable(const clang::CXXRecordDecl *D)
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD)
ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool)
Definition Sema.h:1404
void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules)
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
Decl * ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc)
We have parsed the start of an export declaration, including the '{' (if present).
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
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:6580
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
void PopExpressionEvaluationContext()
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N)
PragmaStack< StringLiteral * > ConstSegStack
Definition Sema.h:2037
StmtResult ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:755
void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc)
ActOnPragmaOptionsAlign - Called on well formed #pragma options align.
Definition SemaAttr.cpp:334
bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, const FunctionDecl *NewFunction, unsigned *ArgPos=nullptr, bool Reversed=false)
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition SemaExpr.cpp:883
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth)
Called before parsing a function declarator belonging to a function declaration.
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName)
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition SemaDecl.cpp:695
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2585
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, bool DoCheckConstraintSatisfaction=true)
ParsingClassState PushParsingClass()
Definition Sema.h:6523
@ FRS_Success
Definition Sema.h:10742
@ FRS_DiagnosticIssued
Definition Sema.h:10744
@ FRS_NoViableFunction
Definition Sema.h:10743
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
void ActOnPragmaCXLimitedRange(SourceLocation Loc, LangOptions::ComplexRangeKind Range)
ActOnPragmaCXLimitedRange - Called on well formed #pragma STDC CX_LIMITED_RANGE.
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
void ActOnPragmaFPExceptions(SourceLocation Loc, LangOptions::FPExceptionModeKind)
Called on well formed '#pragma clang fp' that has option 'exceptions'.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition SemaAttr.cpp:112
SmallVector< LateInstantiatedAttribute, 1 > LateInstantiatedAttrVec
Definition Sema.h:14069
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
llvm::SmallVector< DeleteExprLoc, 4 > DeleteLocs
Definition Sema.h:967
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9290
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose=true)
Checks access to an overloaded operator new or delete.
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, bool PartialOrdering, bool *StrictPackMatch)
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
unsigned TyposCorrected
The number of typos corrected by CorrectTypo.
Definition Sema.h:9240
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Sema.h:6048
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
Definition Sema.h:6062
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
Definition Sema.h:6059
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
Definition Sema.h:6056
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6050
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
Definition Sema.h:6053
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD=nullptr, CUDAFunctionTarget CFT=CUDAFunctionTarget::InvalidTarget)
Check validaty of calling convention attribute attr.
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen)
ActOnArrayTypeTrait - Parsed one of the binary type trait support pseudo-functions.
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)
llvm::SmallVector< QualType, 4 > CurrentParameterCopyTypes
Stack of types that correspond to the parameter entities that are currently being copy-initialized.
Definition Sema.h:8979
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType, bool &IncompatibleObjC)
IsPointerConversion - Determines whether the conversion of the expression From, which has the (possib...
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
SmallVector< const Decl * > DeclsWithEffectsToVerify
All functions/lambdas/blocks which have bodies and which have a non-empty FunctionEffectsRef to be ve...
Definition Sema.h:15571
@ Conversions
Allow explicit conversion functions but not explicit constructors.
Definition Sema.h:10075
@ All
Allow both explicit conversion functions and explicit constructors.
Definition Sema.h:10077
void ActOnFinishRequiresExpr()
QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull)
static const unsigned MaxAlignmentExponent
The maximum alignment, same as in llvm::Value.
Definition Sema.h:1213
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition Sema.h:6511
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, std::optional< Expr * > ArraySize, SourceRange DirectInitRange, Expr *Initializer)
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
void * SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS)
Given a C++ nested-name-specifier, produce an annotation value that the parser can use later to recon...
ValueDecl * tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase)
void ProcessPragmaWeak(Scope *S, Decl *D)
void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, DeclarationName Name, OverloadCandidateSet &CandidateSet, FunctionDecl *Fn, MultiExprArg Args, bool IsMember=false)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
NamedDecl * BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists)
Builds a using declaration.
bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum, llvm::APSInt &Result)
BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr TheCall is a constant expression.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
llvm::PointerUnion< const NamedDecl *, const concepts::NestedRequirement * > ConstrainedDeclOrNestedRequirement
Definition Sema.h:14791
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template, TemplateTemplateParmDecl *Param, const TemplateArgumentLoc &Arg)
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
void ActOnPragmaFPEvalMethod(SourceLocation Loc, LangOptions::FPEvalMethodKind Value)
Definition SemaAttr.cpp:636
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition Sema.h:3572
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
bool CheckAttrNoArgs(const ParsedAttr &CurrAttr)
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1655
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr)
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition Sema.cpp:2584
unsigned InventedParameterInfosStart
The index of the first InventedParameterInfo that refers to the current context.
Definition Sema.h:3464
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method, std::optional< CXXRecordDecl::LambdaNumbering > NumberingOverride=std::nullopt)
Number lambda for linkage purposes if necessary.
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, UnsignedOrNone NumExpansions)
unsigned NumSFINAEErrors
The number of SFINAE diagnostics that have been trapped.
Definition Sema.h:11313
void setFunctionHasIndirectGoto()
Definition Sema.cpp:2504
void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs)
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
bool CheckConstraintSatisfaction(ConstrainedDeclOrNestedRequirement Entity, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction, const ConceptReference *TopLevelConceptId=nullptr, Expr **ConvertedExpr=nullptr)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc)
Build a bit-precise integer type.
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition Sema.h:12101
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12119
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12109
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12129
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
NamedDecl * ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint)
ActOnTypeParameter - Called when a C++ template type parameter (e.g., "typename T") has been parsed.
SmallVectorImpl< Decl * > & WeakTopLevelDecls()
WeakTopLevelDeclDecls - access to #pragma weak-generated Decls.
Definition Sema.h:4865
EnumDecl * getStdAlignValT() const
const NormalizedConstraint * getNormalizedAssociatedConstraints(ConstrainedDeclOrNestedRequirement Entity, ArrayRef< AssociatedConstraint > AssociatedConstraints)
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1669
QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< TypeSourceInfo * > Types, ArrayRef< Expr * > Exprs)
ControllingExprOrType is either a TypeSourceInfo * or an Expr *.
ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping=false)
Initialize the given capture with a suitable expression.
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool StrictPackMatch=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8321
void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName)
ActOnPragmaClangSection - Called on well formed #pragma clang section.
Definition SemaAttr.cpp:389
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef< Expr * > Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses)
Find the associated classes and namespaces for argument-dependent lookup for a call with the given se...
AssumedTemplateKind
Definition Sema.h:11373
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11380
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11377
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...
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, OverloadCandidateParamOrder PO={})
Add a C++ member function template as a candidate to the candidate set, using template argument deduc...
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition SemaAttr.cpp:795
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, CheckTemplateArgumentInfo &CTAI, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body)
AtomicArgumentOrder
Definition Sema.h:2692
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2332
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken)
Act on the result of classifying a name as a specific non-type declaration.
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc)
Definition SemaCast.cpp:426
SourceRange getExprRange(Expr *E) const
Definition SemaExpr.cpp:506
bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS)
The parser has parsed a global nested-name-specifier '::'.
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
NamedReturnInfo getNamedReturnInfo(Expr *&E, SimplerImplicitMoveMode Mode=SimplerImplicitMoveMode::Normal)
Determine whether the given expression might be move-eligible or copy-elidable in either a (co_)retur...
void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind)
Called to set exception behavior for floating point operations.
bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool *IsCorrectedToColon=nullptr, bool OnlyNamespace=false)
The parser has parsed a nested-name-specifier 'identifier::'.
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
bool CheckFunctionReturnType(QualType T, SourceLocation Loc)
ArrayRef< InventedTemplateParameterInfo > getInventedParameterInfos() const
Definition Sema.h:11306
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:168
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
LazyVector< const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2 > UnusedFileScopedDeclsType
Definition Sema.h:3545
std::optional< ExpressionEvaluationContextRecord::InitializationContext > OutermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8175
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool TypenameKeyword, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e....
static DeclarationName getPrintable(DeclarationName N)
Definition Sema.h:14997
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition Sema.h:4565
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id, bool IsUDSuffix)
friend class ASTReader
Definition Sema.h:1557
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI)
Add a no_cluster attribute to a particular declaration.
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition SemaStmt.cpp:405
FPOptions & getCurFPFeatures()
Definition Sema.h:920
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8273
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2350
StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E)
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void PopCompoundScope()
Definition Sema.cpp:2483
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:15407
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
UnexpandedParameterPackContext
The context in which an unexpanded parameter pack is being diagnosed.
Definition Sema.h:14323
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition Sema.h:14343
@ UPPC_RequiresClause
Definition Sema.h:14394
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14349
@ UPPC_IfExists
Microsoft __if_exists.
Definition Sema.h:14376
@ UPPC_Requirement
Definition Sema.h:14391
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14367
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14346
@ UPPC_Lambda
Lambda expression.
Definition Sema.h:14382
@ UPPC_IfNotExists
Microsoft __if_not_exists.
Definition Sema.h:14379
@ UPPC_PartialSpecialization
Partial specialization.
Definition Sema.h:14373
@ UPPC_Initializer
An initializer.
Definition Sema.h:14358
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14328
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14352
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14361
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14331
@ UPPC_Expression
An arbitrary expression.
Definition Sema.h:14325
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14370
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14355
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14334
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14340
@ UPPC_Block
Block expression.
Definition Sema.h:14385
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14337
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14364
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14388
api_notes::APINotesManager APINotes
Definition Sema.h:1287
bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
bool IsLayoutCompatible(QualType T1, QualType T2) const
Decl * ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl, bool IsNested)
ActOnStartNamespaceDef - This is called at the start of a namespace definition.
llvm::DenseMap< Decl *, SmallVector< PartialDiagnosticAt, 1 > > SuppressedDiagnosticsMap
For each declaration that involved template argument deduction, the set of diagnostics that were supp...
Definition Sema.h:12460
void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool Mutable)
Endow the lambda scope info with the relevant properties.
const LangOptions & getLangOpts() const
Definition Sema.h:918
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
bool CaptureHasSideEffects(const sema::Capture &From)
Does copying/destroying the captured variable have side effects?
llvm::PointerIntPair< Decl *, 2 > InstantiatingSpecializationsKey
Definition Sema.h:13001
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent)
DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was not used in the declaration of ...
StmtResult ActOnFinishFullStmt(Stmt *Stmt)
SmallVector< VTableUse, 16 > VTableUses
The list of vtables that are required but have not yet been materialized.
Definition Sema.h:5827
void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation=false)
AddModeAttr - Adds a mode attribute to a particular declaration.
AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field)
Checks implicit access to a member in a structured binding.
void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope=true, bool LoadExternal=true)
StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, ConditionResult Cond, SourceLocation RParenLoc, Stmt *Body)
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
SourceLocation CurInitSegLoc
Definition Sema.h:2077
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispMode Value)
Called on well formed #pragma vtordisp().
Definition SemaAttr.cpp:724
SemaCodeCompletion & CodeCompletion()
Definition Sema.h:1436
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:220
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition Sema.h:3566
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, const DeclSpec &DS)
ActOnStartOfLambdaDefinition - This is called just before we start parsing the body of a lambda; it a...
SemaOpenACC & OpenACC()
Definition Sema.h:1491
void SwapSatisfactionStack(llvm::SmallVectorImpl< SatisfactionStackEntryTy > &NewSS)
Definition Sema.h:14786
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
ReuseLambdaContextDecl_t
Definition Sema.h:6984
@ ReuseLambdaContextDecl
Definition Sema.h:6984
void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef< CXXBaseSpecifier * > Bases)
ActOnBaseSpecifiers - Attach the given base specifiers to the class, after checking whether there are...
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
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...
void MarkExpressionAsImmediateEscalating(Expr *E)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
NamedDecl * findLocallyScopedExternCDecl(DeclarationName Name)
Look for a locally scoped extern "C" declaration by the given name.
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
void ActOnLambdaClosureParameters(Scope *LambdaScope, MutableArrayRef< DeclaratorChunk::ParamInfo > ParamInfo)
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
ASTConsumer & getASTConsumer() const
Definition Sema.h:926
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
bool isUnexpandedParameterPackPermitted()
Determine whether an unexpanded parameter pack might be permitted in this location.
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc)
Produce diagnostics if FD is an aligned allocation or deallocation function that is unavailable.
SemaBPF & BPF()
Definition Sema.h:1431
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
void * OpaqueParser
Definition Sema.h:1325
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
Preprocessor & PP
Definition Sema.h:1282
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc)
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.
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
bool MSPragmaOptimizeIsOn
The "on" or "off" argument passed by #pragma optimize, that denotes whether the optimizations in the ...
Definition Sema.h:2124
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
threadSafety::BeforeSet * ThreadSafetyDeclCache
Definition Sema.h:1320
SmallVector< PragmaAttributeGroup, 2 > PragmaAttributeStack
Definition Sema.h:2102
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived, const CXXBasePath &Path, unsigned DiagID, llvm::function_ref< void(PartialDiagnostic &PD)> SetupPDiag, bool ForceCheck=false, bool ForceUnprivileged=false)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:2116
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl)
Perform access-control checking on a previously-unresolved member access which has now been resolved ...
bool hasVisibleMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is a member specialization declaration (as oppo...
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
LazyVector< VarDecl *, ExternalSemaSource, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2 > TentativeDefinitionsType
Definition Sema.h:3553
SemaDirectX & DirectX()
Definition Sema.h:1446
llvm::SmallSetVector< const NamedDecl *, 16 > NamedDeclSetType
Definition Sema.h:6472
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization)
SemaMSP430 & MSP430()
Definition Sema.h:1476
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
friend class ASTDeclReader
Definition Sema.h:1558
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1281
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
NamedDecl * FindFirstQualifierInScope(Scope *S, NestedNameSpecifier NNS)
If the given nested-name-specifier begins with a bare identifier (e.g., Base::), perform name lookup ...
bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS)
ActOnCXXExitDeclaratorScope - Called when a declarator that previously invoked ActOnCXXEnterDeclarato...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
ExprResult PerformQualificationConversion(Expr *E, QualType Ty, ExprValueKind VK=VK_PRValue, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType)
IsMemberPointerConversion - Determines whether the conversion of the expression From,...
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
std::unique_ptr< sema::FunctionScopeInfo > CachedFunctionScope
Definition Sema.h:1219
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2559
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
static const uint64_t MaximumAlignment
Definition Sema.h:1214
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
llvm::DenseMap< unsigned, CXXDeductionGuideDecl * > AggregateDeductionCandidates
Definition Sema.h:8982
ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK)
Check the use of the given variable as a C++ condition in an if, while, do-while, or switch statement...
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS)
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:952
void ActOnStartOfCompoundStmt(bool IsStmtExpr)
Definition SemaStmt.cpp:416
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15420
CUDAClusterDimsAttr * createClusterDimsAttr(const AttributeCommonInfo &CI, Expr *X, Expr *Y, Expr *Z)
Add a cluster_dims attribute to a particular declaration.
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6474
SemaHLSL & HLSL()
Definition Sema.h:1451
VarTemplateSpecializationDecl * CompleteVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiates a variable template specialization by completing it with appropriate type information an...
llvm::MapVector< const FunctionDecl *, std::unique_ptr< LateParsedTemplate > > LateParsedTemplateMapT
Definition Sema.h:11322
bool CollectStats
Flag indicating whether or not to collect detailed statistics.
Definition Sema.h:1217
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9289
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind)
Definition Sema.cpp:1170
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
CXXRecordDecl * getStdBadAlloc() const
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization)
ActOnCXXTypeConstructExpr - Parse construction of a specified type.
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident)
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
ExpressionEvaluationContextRecord & currentEvaluationContext()
Definition Sema.h:6902
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand,...
void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst)
Update instantiation attributes after template was late parsed.
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
PragmaClangSection PragmaClangRelroSection
Definition Sema.h:1814
void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1471
IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName, unsigned Index)
Invent a new identifier for parameters of abbreviated templates.
Definition Sema.cpp:139
void InstantiateVariableInitializer(VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the initializer of a variable.
void CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc, SourceLocation CallOperatorLoc, const AssociatedConstraint &TrailingRequiresClause, TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, StorageClass SC, ArrayRef< ParmVarDecl * > Params, bool HasExplicitResultType)
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
SemaRISCV & RISCV()
Definition Sema.h:1516
bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType)
Checks access to Target from the given class.
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition Sema.h:15594
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition Sema.h:1803
llvm::DenseMap< CXXRecordDecl *, bool > VTablesUsed
The set of classes whose vtables have been used within this translation unit, and a bit that will be ...
Definition Sema.h:5833
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *RetExpr, const AutoType *AT)
Deduce the return type for a function from a returned expression, per C++1y [dcl.spec....
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:213
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes, bool OrNull)
Check if applying the specified attribute variant from the "counted by" family of attributes to Field...
ComparisonCategoryUsage
Definition Sema.h:5207
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
Definition Sema.h:5210
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5214
MemberPointerConversionDirection
Definition Sema.h:10195
SmallVector< PendingImplicitInstantiation, 1 > LateParsedInstantiations
Queue of implicit template instantiations that cannot be performed eagerly.
Definition Sema.h:13943
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6467
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:75
ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK)
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
void performFunctionEffectAnalysis(TranslationUnitDecl *TU)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
EltwiseBuiltinArgTyRestriction
Definition Sema.h:2758
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R)
Checks that a type is suitable as the allocated type in a new-expression.
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Diagnose cases where a scalar was implicitly converted to a vector and diagnose the underlying types.
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
static StringRef getPrintable(StringRef S)
Definition Sema.h:14992
SemaSwift & Swift()
Definition Sema.h:1531
NamedDecl * BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, TypeSourceInfo *EnumType, EnumDecl *ED)
void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based n...
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const
PragmaStack< AlignPackInfo > AlignPackStack
Definition Sema.h:2026
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
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:6572
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:6929
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition Sema.h:13574
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6504
StmtResult ActOnExprStmtError()
Definition SemaStmt.cpp:65
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2036
ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< TypeSourceInfo * > Args, SourceLocation RParenLoc)
const VarDecl * getCopyElisionCandidate(NamedReturnInfo &Info, QualType ReturnType)
Updates given NamedReturnInfo's move-eligible and copy-elidable statuses, considering the function re...
CXXRecordDecl * getCurrentInstantiationOf(NestedNameSpecifier NNS)
If the given nested name specifier refers to the current instantiation, return the declaration that c...
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed.
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
void completeExprArrayBound(Expr *E)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1124
std::function< TypeResult(StringRef, StringRef, SourceLocation)> ParseTypeFromStringCallback
Callback to the parser to parse a type expressed as a string.
Definition Sema.h:1334
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
llvm::StringMap< std::tuple< StringRef, SourceLocation > > FunctionToSectionMap
Sections used with pragma alloc_text.
Definition Sema.h:2080
bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS)
The parser has parsed a '__super' nested-name-specifier.
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1662
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, SourceLocation LParenLoc, ArrayRef< ParmVarDecl * > LocalParameters, SourceLocation RParenLoc, ArrayRef< concepts::Requirement * > Requirements, SourceLocation ClosingBraceLoc)
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr)
AddAllocAlignAttr - Adds an alloc_align attribute to a particular declaration.
bool hasExplicitCallingConv(QualType T)
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition SemaDecl.cpp:894
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro=false)
Definition SemaStmt.cpp:70
OpenCLOptions OpenCLFeatures
Definition Sema.h:1278
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
TemplateArgument getPackSubstitutedTemplateArgument(TemplateArgument Arg) const
Definition Sema.h:11727
ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand, UnresolvedLookupExpr *Lookup)
SmallVector< std::deque< PendingImplicitInstantiation >, 8 > SavedPendingInstantiations
Definition Sema.h:13947
void MarkVirtualBaseDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl< const CXXRecordDecl * > *DirectVirtualBases=nullptr)
Mark destructors of virtual bases of this class referenced.
llvm::SmallSetVector< StringRef, 4 > MSFunctionNoBuiltins
Set of no-builtin functions listed by #pragma function.
Definition Sema.h:2127
ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen)
void ExitDeclaratorContext(Scope *S)
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value)
Checks a regparm attribute, returning true if it is ill-formed and otherwise setting numParams to the...
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition Sema.cpp:848
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir)
RecordDecl * CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams)
bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D)
Determine if we're in a case where we need to (incorrectly) eagerly parse an exception specification ...
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
bool buildCoroutineParameterMoves(SourceLocation Loc)
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
Definition Sema.h:4742
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceRange TyLoc, const IdentifierInfo &II, ParsedType Ty, const CXXScopeSpec &SS)
DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc)
The parser has processed a global-module-fragment declaration that begins the definition of the globa...
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
UnsignedOrNone getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10382
FileNullabilityMap NullabilityMap
A mapping that describes the nullability we've seen in each header file.
Definition Sema.h:14986
ProcessingContextState ParsingClassState
Definition Sema.h:6522
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc)
Build a Microsoft __uuidof expression with a type operand.
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1314
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2478
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx, StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, StringLiteral *BinaryData, StringRef FileName)
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
bool isDeclaratorFunctionLike(Declarator &D)
Determine whether.
Definition Sema.cpp:2912
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent)
Determine whether it's plausible that E was intended to be a template-name.
Definition Sema.h:3818
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition Sema.h:2665
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15329
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
bool CheckNontrivialField(FieldDecl *FD)
void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList)
Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr attribute.
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr)
DiagnoseAssignmentEnum - Warn if assignment to enum is a constant integer not in the range of enum va...
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:6926
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
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...
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
TemplateDeductionResult SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< QualType > &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info)
Substitute the explicitly-provided template arguments into the given function template according to C...
ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E)
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
Check the validity of a C++ base class specifier.
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2296
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS, CXXRecordDecl *Cls, SourceLocation Loc, DeclarationName Entity)
Build a member pointer type T Class::*.
UnsignedOrNone getPackIndex(TemplateArgument Pack) const
Definition Sema.h:11722
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl)
The main callback when the parser finds something like expression .
ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S)
Builds an implicit member access expression.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition Sema.h:12999
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val, unsigned Idx=UINT_MAX, bool StrictlyUnsigned=false)
If Expr is a valid integer constant, get the value of the integer expression and return success or fa...
Definition Sema.h:4825
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body,...
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
std::pair< CXXRecordDecl *, SourceLocation > VTableUse
The list of classes whose vtables have been used within this translation unit, and the source locatio...
Definition Sema.h:5823
DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, ModuleIdPath Partition, ModuleImportState &ImportState, bool SeenNoTrivialPPDirective)
The parser has processed a module-declaration that begins the definition of a module interface or imp...
void MarkThisReferenced(CXXThisExpr *This)
void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody)
Warn if a for/while loop statement S, which is followed by PossibleBody, has a suspicious null statem...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:639
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15414
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition Sema.h:8144
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2076
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9823
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD)
AddOverriddenMethods - See if a method overrides any in the base classes, and if so,...
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
static bool isCast(CheckedConversionKind CCK)
Definition Sema.h:2520
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr * > ArgExprs)
ControllingExprOrType is either an opaque pointer coming out of a ParsedType or an Expr *.
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD, bool Diagnose, bool LookForGlobal)
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
Definition Sema.h:8011
bool hasReachableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a reachable default argument.
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2514
ParsedTemplateArgument ActOnTemplateTemplateArgument(const ParsedTemplateArgument &Arg)
Invoked when parsing a template argument.
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType)
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:6941
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, ADLResult &Functions)
void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl)
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition Sema.h:6481
void CheckTCBEnforcement(const SourceLocation CallExprLoc, const NamedDecl *Callee)
Enforce the bounds of a TCB CheckTCBEnforcement - Enforces that every function in a named TCB only di...
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult)
Given an expression that refers to an overloaded function, try to resolve that function to a single f...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1414
auto getDefaultDiagFunc()
Definition Sema.h:2283
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
VarDecl * BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id)
Perform semantic analysis for the variable declaration that occurs within a C++ catch clause,...
bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount)
Checks that a call expression's argument count is at least the desired number.
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose=true)
Finds the overloads of operator new and delete that are appropriate for the allocation.
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc)
ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const,addrspace}_cast's.
Definition SemaCast.cpp:314
DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc)
The parser has processed a private-module-fragment declaration that begins the definition of the priv...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition Sema.h:12461
ClassTemplateDecl * StdTypeIdentity
The C++ "std::type_identity" template, which is defined in <type_traits>.
Definition Sema.h:6500
SemaOpenCL & OpenCL()
Definition Sema.h:1496
void ActOnPragmaMSFunction(SourceLocation Loc, const llvm::SmallVectorImpl< StringRef > &NoBuiltins)
Call on well formed #pragma function.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition Sema.h:13956
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
void ActOnPragmaMSStruct(PragmaMSStructKind Kind)
ActOnPragmaMSStruct - Called on well formed #pragma ms_struct [on|off].
Definition SemaAttr.cpp:616
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool isPreciseFPEnabled()
Are precise floating point semantics currently enabled?
Definition Sema.h:2207
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
IdentifierInfo * getNullabilityKeyword(NullabilityKind nullability)
Retrieve the keyword associated.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression, SourceLocation EllipsisLoc, SourceLocation LSquareLoc, Expr *IndexExpr, SourceLocation RSquareLoc)
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName)
Called on well-formed #pragma init_seg().
Definition SemaAttr.cpp:890
AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp=false)
Checks access to a constructor.
static SourceRange getPrintable(TypeLoc TL)
Definition Sema.h:15002
bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType)
FormatArgumentPassingKind
Definition Sema.h:2595
@ FAPK_Elsewhere
Definition Sema.h:2599
@ FAPK_Fixed
Definition Sema.h:2596
@ FAPK_Variadic
Definition Sema.h:2597
@ FAPK_VAList
Definition Sema.h:2598
void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info)
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.
CXXMethodDecl * LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals)
Look up the moving assignment operator for the given class.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon=nullptr, bool OnlyNamespace=false)
Build a new nested-name-specifier for "identifier::", as described by ActOnCXXNestedNameSpecifier.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8136
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
llvm::DenseMap< ParmVarDecl *, llvm::TinyPtrVector< ParmVarDecl * > > UnparsedDefaultArgInstantiationsMap
Definition Sema.h:12990
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1630
StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, NamedReturnInfo &NRInfo, bool SupressSimplerImplicitMoves)
ActOnCapScopeReturnStmt - Utility routine to type-check return statements for capturing scopes.
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr, bool ForTypeDeduction=false)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
Stmt * MaybeCreateStmtWithCleanups(Stmt *SubStmt)
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl)
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer)
Parsed a C++ 'new' expression (C++ 5.3.4).
CXXConstructorDecl * LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the moving constructor for the given class.
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD)
Check that the C++ class annoated with "trivial_abi" satisfies all the conditions that are needed for...
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
StmtResult ActOnCapturedRegionEnd(Stmt *S)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
bool IsCXXReplaceableType(QualType T)
Determines if a type is replaceable according to the C++26 rules.
ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen)
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool isAcceptable(const NamedDecl *D, AcceptableKind Kind)
Determine whether a declaration is acceptable (visible/reachable).
Definition Sema.h:15427
void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS)
Given an annotation pointer for a nested-name-specifier, restore the nested-name-specifier structure.
QualType getDecltypeForExpr(Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
NamedDecl * DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II, SourceLocation Loc)
DeclClonePragmaWeak - clone existing decl (maybe definition), #pragma weak needs a non-definition dec...
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
CXXMethodDecl * LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals)
Look up the copying assignment operator for the given class.
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
std::pair< const NamedDecl *, llvm::FoldingSetNodeID > SatisfactionStackEntryTy
Definition Sema.h:14766
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
void CleanupMergedEnum(Scope *S, Decl *New)
CleanupMergedEnum - We have just merged the decl 'New' by making another definition visible.
StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp)
bool GlobalNewDeleteDeclared
A flag to remember whether the implicit forms of operator new and delete have been declared.
Definition Sema.h:8332
TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a template name from a name that is syntactically required to name a template,...
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition Sema.h:3563
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition Sema.h:6733
bool MSStructPragmaOn
Definition Sema.h:1800
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
ExprResult TransformToPotentiallyEvaluated(Expr *E)
CodeSegAttr * mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
void deduceHLSLAddressSpace(VarDecl *decl)
unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref< Scope *()> EnterScope)
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
SectionAttr * mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition Sema.h:13558
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT)
Determines if we can perform a correct type check for D as a redeclaration of PrevDecl.
ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL=true)
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:13891
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID)
Definition Sema.h:15402
SourceManager & getSourceManager() const
Definition Sema.h:923
void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
QualType BuiltinAddReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
QualType CXXThisTypeOverride
When non-NULL, the C++ 'this' expression is allowed despite the current context not being a non-stati...
Definition Sema.h:8403
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
static FormatStringType GetFormatStringType(StringRef FormatFlavor)
CallingConventionIgnoredReason
Describes the reason a calling convention specification was ignored, used for diagnostics.
Definition Sema.h:4803
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
bool CheckVecStepExpr(Expr *E)
bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason)
makeUnavailableInSystemHeader - There is an error in the current context.
Definition Sema.cpp:631
bool isModuleVisible(const Module *M, bool ModulePrivate=false)
void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversion=false, OverloadCandidateParamOrder PO={})
AddMethodCandidate - Adds a named decl (which is some kind of method) as a method candidate to the gi...
llvm::DenseMap< const EnumDecl *, llvm::APInt > FlagBitsCache
A cache of the flags available in enumerations with the flag_bits attribute.
Definition Sema.h:3516
bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool CheckRebuiltStmtAttributes(ArrayRef< const Attr * > Attrs)
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
bool hasVisibleMergedDefinition(const NamedDecl *Def)
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void getUndefinedButUsed(SmallVectorImpl< std::pair< NamedDecl *, SourceLocation > > &Undefined)
Obtain a sorted list of functions that are undefined but ODR-used.
Definition Sema.cpp:945
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc)
Declare implicit deduction guides for a class template if we've not already done so.
void diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc, const NamedDecl *D, ArrayRef< const NamedDecl * > Equiv)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn when implicitly changing function effects.
Definition Sema.cpp:695
ClassTemplateDecl * lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc)
Lookup 'coroutine_traits' in std namespace and std::experimental namespace.
bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Definition Sema.h:12201
void PerformPendingInstantiations(bool LocalOnly=false, bool AtEndOfTU=true)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
bool areMultiversionVariantFunctionsCompatible(const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer)
Checks if the variant/multiversion functions are compatible.
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value, bool SupressSimplerImplicitMoves=false)
Perform the initialization of a potentially-movable value, which is the result of return value.
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK)
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > TParams, SourceLocation RAngleLoc, ExprResult RequiresClause)
This is called after parsing the explicit template parameter list on a lambda (if it exists) in C++2a...
void PrintPragmaAttributeInstantiationPoint()
Definition Sema.h:2295
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition Sema.h:9283
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, SourceLocation IncludeLoc)
Definition SemaAttr.cpp:550
Decl * ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc)
ActOnStartLinkageSpecification - Parsed the beginning of a C++ linkage specification,...
bool ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc, QualType Type)
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
void FilterUsingLookup(Scope *S, LookupResult &lookup)
Remove decls we can't actually see from a lookup being used to declare shadow using decls.
bool inConstraintSubstitution() const
Determine whether we are currently performing constraint substitution.
Definition Sema.h:13896
CanThrowResult canThrow(const Stmt *E)
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
bool isThisOutsideMemberFunctionBody(QualType BaseType)
Determine whether the given type is the type of *this that is used outside of the body of a member fu...
bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str)
Verify that one format string (as understood by attribute(format)) is self-consistent; for instance,...
bool AccessCheckingSFINAE
When true, access checking violations are treated as SFINAE failures rather than hard errors.
Definition Sema.h:12390
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
StringEvaluationContext
Definition Sema.h:5943
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc)
PragmaClangSection PragmaClangTextSection
Definition Sema.h:1815
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks, ObjCInterfaceDecl *ClassReceiver)
CallExpr::ADLCallKind ADLCallKind
Definition Sema.h:7436
bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity, const InitializationKind &Kind, AssignmentAction Action, QualType LHSType, Expr *RHSExpr)
Perform Bounds Safety Semantic checks for initializing a Bounds Safety pointer.
LabelDecl * LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc=SourceLocation())
LookupOrCreateLabel - Do a name lookup of a label with the specified name.
NonTrivialCUnionKind
Definition Sema.h:4069
@ NTCUK_Destruct
Definition Sema.h:4071
@ NTCUK_Init
Definition Sema.h:4070
@ NTCUK_Copy
Definition Sema.h:4072
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
DelayedDiagnosticsState ProcessingContextState
Definition Sema.h:1351
void CheckLookupAccess(const LookupResult &R)
Checks access to all the declarations in the given result set.
concepts::ExprRequirement * BuildExprRequirement(Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement)
void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind, bool IsEnabled)
Called on well formed #pragma clang fp reassociate or #pragma clang fp reciprocal.
QualType BuildAtomicType(QualType T, SourceLocation Loc)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition Sema.h:8289
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1812
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
llvm::Error isValidSectionSpecifier(StringRef Str)
Used to implement to perform semantic checking on attribute((section("foo"))) specifiers.
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
ParsedType actOnLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init)
Perform initialization analysis of the init-capture and perform any implicit conversions such as an l...
Definition Sema.h:9078
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
bool anyAltivecTypes(QualType srcType, QualType destType)
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc)
std::pair< AvailabilityResult, const NamedDecl * > ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message, ObjCInterfaceDecl *ClassReceiver)
The diagnostic we should emit for D, and the declaration that originated it, or AR_Available.
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc)
Act on the result of classifying a name as an undeclared (ADL-only) non-type declaration.
StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind, ArrayRef< MaterializeTemporaryExpr * > LifetimeExtendTemps={})
ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition Sema.cpp:2344
bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX, const FunctionEffectWithCondition &EC, SourceLocation NewAttrLoc)
Warn and return true if adding a function effect to a set would create a conflict.
sema::FunctionScopeInfo * getCurFunctionAvailabilityContext()
Retrieve the current function, if any, that should be analyzed for potential availability violations.
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaRedefineExtname - Called on well formed #pragma redefine_extname oldname newname.
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
PragmaStack< MSVtorDispMode > VtorDispStack
Whether to insert vtordisps prior to virtual bases in the Microsoft C++ ABI.
Definition Sema.h:2025
TypeSourceInfo * ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
QualType CXXCheckConditionalOperands(ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc)
Check the operands of ?
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
TypeResult ActOnTypeName(Declarator &D)
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
MaybeODRUseExprSet MaybeODRUseExprs
Definition Sema.h:6731
void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro, SourceLocation MutableLoc)
ExternalSemaSource * getExternalSource() const
Definition Sema.h:928
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
unsigned FunctionScopesStart
The index of the first FunctionScope that corresponds to the current context.
Definition Sema.h:1227
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
Definition Sema.h:2083
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
FunctionDecl * BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl, QualType AllocType, SourceLocation)
QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs=true)
Definition Sema.h:8763
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation=false)
ActOnLambdaError - If there is an error parsing a lambda, this callback is invoked to pop the informa...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:224
static SourceRange getPrintable(SourceRange R)
Definition Sema.h:14999
void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks)
AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular declaration.
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
TopLevelStmtDecl * ActOnStartTopLevelStmtDecl(Scope *S)
concepts::Requirement * ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
UnsignedOrNone ArgPackSubstIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition Sema.h:13582
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc)
Invoked when parsing a template argument followed by an ellipsis, which creates a pack expansion.
void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II)
Try to resolve an undeclared template name as a type template.
ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, const IdentifierInfo &Name)
Handle the result of the special case name lookup for inheriting constructor declarations.
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
Decl * ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc)
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e....
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
void DiagnoseUnknownAttribute(const ParsedAttr &AL)
void PushSatisfactionStackEntry(const NamedDecl *D, const llvm::FoldingSetNodeID &ID)
Definition Sema.h:14751
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15369
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, const PartialDiagnostic &PD, const FunctionDecl *FD=nullptr)
Definition Sema.h:1130
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel=0)
Definition Sema.cpp:2874
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void emitDeferredDiags()
Definition Sema.cpp:2009
void setFunctionHasMustTail()
Definition Sema.cpp:2509
ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType)
void checkUnusedDeclAttributes(Declarator &D)
checkUnusedDeclAttributes - Given a declarator which is not being used to build a declaration,...
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
RecordDecl * CXXTypeInfoDecl
The C++ "type_info" declaration, which is defined in <typeinfo>.
Definition Sema.h:8328
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, SourceRange FixItRange, const sema::Capture &From)
Diagnose if an explicit lambda capture is unused.
void CheckCompleteVariableDeclaration(VarDecl *VD)
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr)
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
void PopSatisfactionStackEntry()
Definition Sema.h:14757
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class)
QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a pointer type.
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
void setFunctionHasBranchProtectedScope()
Definition Sema.cpp:2499
RedeclarationKind forRedeclarationInCurContext() const
bool hasReachableDefinition(NamedDecl *D)
Definition Sema.h:15458
void MergeVarDecl(VarDecl *New, LookupResult &Previous)
MergeVarDecl - We just parsed a variable 'New' which has the same name and scope as a previous declar...
bool isConstantEvaluatedContext() const
Definition Sema.h:2587
bool CheckAttrTarget(const ParsedAttr &CurrAttr)
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6492
QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, UnsignedOrNone NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init)
StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block)
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition SemaDecl.cpp:623
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param, const MultiLevelTemplateArgumentList &TemplateArgs, bool ForCallExpr=false)
Substitute the given template arguments into the default argument.
QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc)
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
bool BuiltinElementwiseTernaryMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::FloatTy)
void ActOnStartOfTranslationUnit()
This is called before the very first declaration in the translation unit is parsed.
Definition Sema.cpp:1164
StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind, ArrayRef< MaterializeTemporaryExpr * > LifetimeExtendTemps={})
BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
friend class Parser
Definition Sema.h:1555
ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A, SourceRange Range)
StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen)
CXXConstructorDecl * LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the copying constructor for the given class.
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
std::pair< StringRef, QualType > CapturedParamNameType
Definition Sema.h:11182
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc)
void ApplyNullability(Decl *D, NullabilityKind Nullability)
Apply the 'Nullability:' annotation to the specified declaration.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3537
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition SemaDecl.cpp:270
ExprResult SubstConstraintExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1552
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
ASTConsumer & Consumer
Definition Sema.h:1284
bool handlerCanCatch(QualType HandlerType, QualType ExceptionType)
RequiresExprBodyDecl * ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, ArrayRef< ParmVarDecl * > LocalParameters, Scope *BodyScope)
void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, bool SuppressUserConversions=false, bool PartialOverloading=false, bool FirstArgumentIsBase=false)
Add all of the function declarations in the given function set to the overload candidate set.
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand)
void ActOnFinishCXXMemberDecls()
Perform any semantic analysis which needs to be delayed until all pending class member declarations h...
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4628
bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
PragmaAlignPackDiagnoseKind
Definition Sema.h:2185
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:6933
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:123
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1319
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg, bool PartialOrdering, bool *StrictPackMatch)
Check a template argument against its corresponding template template parameter.
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1775
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:13939
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
ExprResult BuiltinShuffleVector(CallExpr *TheCall)
BuiltinShuffleVector - Handle __builtin_shufflevector.
bool CheckImplicitNullabilityTypeSpecifier(QualType &Type, NullabilityKind Nullability, SourceLocation DiagLoc, bool AllowArrayTypes, bool OverrideExisting)
Check whether a nullability type specifier can be added to the given type through some means not writ...
Decl * ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc)
ActOnFinishLinkageSpecification - Complete the definition of the C++ linkage specification LinkageSpe...
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition Sema.h:9850
@ PrivateFragmentImportFinished
after 'module :private;' but a non-import decl has already been seen.
Definition Sema.h:9857
@ ImportFinished
after any non-import decl.
Definition Sema.h:9854
@ PrivateFragmentImportAllowed
after 'module :private;' but before any non-import decl.
Definition Sema.h:9855
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9851
@ GlobalFragment
after 'module;' but before 'module X;'
Definition Sema.h:9852
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
Definition Sema.h:9859
@ ImportAllowed
after 'module X;' but before any non-import decl.
Definition Sema.h:9853
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
static QualType getPrintable(QualType T)
Definition Sema.h:14998
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition Sema.cpp:109
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested)
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl)
void incrementMSManglingNumber() const
Definition Sema.h:1248
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
bool CheckDistantExceptionSpec(QualType T)
CheckDistantExceptionSpec - Check if the given type is a pointer or pointer to member to a function w...
bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect=nullptr)
Determines whether the given declaration is an valid acceptable result for name lookup of a nested-na...
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr)
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
void AddNonMemberOperatorCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
Add all of the non-member operator function declarations in the given function set to the overload ca...
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X, Expr *Y, Expr *Z)
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition Sema.h:6675
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6697
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6687
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6702
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6692
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6712
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6681
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6707
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6722
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced.
Definition Sema.h:13566
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg)
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind, SourceLocation Loc)
AvailabilityPriority
Describes the kind of priority given to an availability attribute.
Definition Sema.h:4788
@ AP_PragmaClangAttribute
The availability attribute was applied using 'pragma clang attribute'.
Definition Sema.h:4794
@ AP_InferredFromOtherPlatform
The availability attribute for a specific platform was inferred from an availability attribute for an...
Definition Sema.h:4798
@ AP_Explicit
The availability attribute was specified explicitly next to the declaration.
Definition Sema.h:4791
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Parse a __builtin_astype expression.
StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block)
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc)
std::pair< SourceLocation, bool > DeleteExprLoc
Definition Sema.h:966
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, const ParsedAttributesView &DeclAttrs, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
bool inParameterMappingSubstitution() const
Definition Sema.h:13901
SemaPPC & PPC()
Definition Sema.h:1506
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace)
ActOnFinishNamespaceDef - This callback is called after a namespace is exited.
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
void RecordParsingTemplateParameterDepth(unsigned Depth)
This is used to inform Sema what the current TemplateParameterDepth is during Parsing.
Definition Sema.cpp:2357
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc)
Handle a C++ member initializer.
void ActOnAfterCompoundStatementLeadingPragmas()
Definition SemaStmt.cpp:420
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition SemaStmt.cpp:75
SmallVector< Decl *, 2 > WeakTopLevelDecl
WeakTopLevelDecl - Translation-unit scoped declarations generated by #pragma weak during processing o...
Definition Sema.h:4862
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
void actOnDelayedExceptionSpecification(Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member or friend function (or function template).
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1246
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
void DiagnoseUnterminatedPragmaAttribute()
void FreeVisContext()
FreeVisContext - Deallocate and null out VisContext.
bool SatisfactionStackContains(const NamedDecl *D, const llvm::FoldingSetNodeID &ID) const
Definition Sema.h:14759
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
UnsignedOrNone getFullyPackExpandedSize(TemplateArgument Arg)
Given a template argument that contains an unexpanded parameter pack, but which has already been subs...
LateTemplateParserCB * LateTemplateParser
Definition Sema.h:1324
void DiagnoseAmbiguousLookup(LookupResult &Result)
Produce a diagnostic describing the ambiguity that resulted from name lookup.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckExplicitObjectLambda(Declarator &D)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD)
Only called on function definitions; if there is a MSVC pragma optimize in scope, consider changing t...
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)
PopPragmaVisibility - Pop the top element of the visibility stack; used for '#pragma GCC visibility' ...
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Delete-expressions to be analyzed at the end of translation unit.
Definition Sema.h:8339
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl)
Checks if the new declaration declared in dependent context must be put in the same redeclaration cha...
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition Sema.h:3556
static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx, unsigned FirstArg, FormatStringInfo *FSI)
Given a function and its FormatAttr or FormatMatchesAttr info, attempts to populate the FormatStringI...
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
bool DeferDiags
Whether deferrable diagnostics should be deferred.
Definition Sema.h:10005
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC)
Get the return type to use for a lambda's conversion function(s) to function pointer type,...
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition Sema.h:8126
SemaSystemZ & SystemZ()
Definition Sema.h:1536
DarwinSDKInfo * getDarwinSDKInfoForAvailabilityChecking()
Definition Sema.cpp:123
bool isRedefinitionAllowedFor(const NamedDecl *D, bool &Visible)
Definition Sema.h:15448
const llvm::MapVector< FieldDecl *, DeleteLocs > & getMismatchingDeleteExpressions() const
Retrieves list of suspicious delete-expressions that will be checked at the end of translation unit.
Definition Sema.cpp:2896
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind, SourceLocation Loc)
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8276
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D)
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
MemberPointerConversionResult
Definition Sema.h:10187
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
void makeModuleVisible(Module *Mod, SourceLocation ImportLoc)
Definition Sema.h:9836
bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of TheCall is a constant expression re...
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList, Stmt *SubStmt)
Definition SemaStmt.cpp:648
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true, bool *Unreachable=nullptr)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind, SourceLocation Loc)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition Sema.h:1286
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs, bool SetWrittenArgs)
Get the specialization of the given variable template corresponding to the specified argument list,...
TemplateNameIsRequiredTag
Definition Sema.h:11350
@ TemplateNameIsRequired
Definition Sema.h:11350
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool FailOnPackProducingTemplates, bool &ShouldExpand, bool &RetainExpansion, UnsignedOrNone &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
NamedDecl * BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > Expansions)
MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc)
Handle a C++ member initializer using parentheses syntax.
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc)
Called when an expression computing the size of a parameter pack is parsed.
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:783
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
bool hasReachableExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is an explicit specialization declaration for...
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure.
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, CXXScopeSpec &SS, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration.
TypeSourceInfo * SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment)
ActOnPragmaPack - Called on well formed #pragma pack(...).
Definition SemaAttr.cpp:438
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
LazyVector< CXXConstructorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2 > DelegatingCtorDeclsType
Definition Sema.h:6485
LabelDecl * GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate)
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1285
CXXMethodDecl * CreateLambdaCallOperator(SourceRange IntroducerRange, CXXRecordDecl *Class)
void DiagnoseUnterminatedPragmaAlignPack()
Definition SemaAttr.cpp:589
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:7752
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:919
FPOptions CurFPFeatures
Definition Sema.h:1279
void ActOnStartSEHFinallyBlock()
TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
static bool CanBeGetReturnObject(const FunctionDecl *FD)
NamespaceDecl * getStdNamespace() const
void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P)
Definition Sema.h:1327
QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc)
llvm::SmallPtrSet< const CXXRecordDecl *, 8 > RecordDeclSetTy
Definition Sema.h:6476
ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator)
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship)
ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope)
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity)
Build an array type.
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:515
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2035
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types?
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
Attr * CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
Definition Sema.cpp:2935
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< ParsedType > Args, SourceLocation RParenLoc)
Parsed one of the type trait support pseudo-functions.
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition Sema.h:11533
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11543
@ TPC_FriendFunctionTemplate
Definition Sema.h:11541
@ TPC_ClassTemplateMember
Definition Sema.h:11539
@ TPC_FunctionTemplate
Definition Sema.h:11538
@ TPC_FriendClassTemplate
Definition Sema.h:11540
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11542
void ActOnPragmaVisibility(const IdentifierInfo *VisType, SourceLocation PragmaLoc)
ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... .
void ActOnAbortSEHFinallyBlock()
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc)
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
SemaAVR & AVR()
Definition Sema.h:1426
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
friend class InitializationSequence
Definition Sema.h:1556
bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl)
Certain globally-unique variables might be accidentally duplicated if built into multiple shared libr...
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
SourceLocation OptimizeOffPragmaLocation
This represents the last location of a "#pragma clang optimize off" directive if such a directive has...
Definition Sema.h:2111
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
void DiagnoseUnusedDecl(const NamedDecl *ND)
void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx)
bool hasAcceptableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules, Sema::AcceptableKind Kind)
Determine if the template parameter D has a reachable default argument.
QualType BuildReadPipeType(QualType T, SourceLocation Loc)
Build a Read-only Pipe type.
void PopDeclContext()
ExprResult VerifyIntegerConstantExpression(Expr *E, AllowFoldKind CanFold=AllowFoldKind::No)
Definition Sema.h:7711
void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init)
bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS)
ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global scope or nested-name-specifi...
TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location)
Get a template argument mapping the given template parameter to itself, e.g.
bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD, SourceLocation Loc)
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc)
Complete a lambda-expression having processed and attached the lambda body.
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found)
Checks access to a member.
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
concepts::NestedRequirement * BuildNestedRequirement(Expr *E)
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6508
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition Sema.h:13533
void PrintStats() const
Print out statistics about the semantic analysis.
Definition Sema.cpp:671
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
static unsigned getPrintable(unsigned I)
Definition Sema.h:14989
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc)
Handle a C++1z fold-expression: ( expr op ... op expr ).
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition Sema.h:1798
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W)
DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak applied to it,...
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
llvm::BumpPtrAllocator BumpAlloc
Definition Sema.h:1232
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
QualType BuildWritePipeType(QualType T, SourceLocation Loc)
Build a Write-only Pipe type.
void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddSurrogateCandidate - Adds a "surrogate" candidate function that converts the given Object to a fun...
SourceRange getRangeForNextToken(SourceLocation Loc, bool IncludeMacros, bool IncludeComments, std::optional< tok::TokenKind > ExpectedToken=std::nullopt)
Calls Lexer::findNextToken() to find the next token, and if the locations of both ends of the token c...
Definition Sema.cpp:88
MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs=nullptr)
BuildForRangeKind
Definition Sema.h:11009
@ BFRK_Check
Determining whether a for-range statement could be built.
Definition Sema.h:11017
@ BFRK_Build
Initial building of a for-range statement.
Definition Sema.h:11011
@ BFRK_Rebuild
Instantiation or recovery rebuild of a for-range statement.
Definition Sema.h:11014
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
SemaNVPTX & NVPTX()
Definition Sema.h:1481
void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD)
Check that VTable Pointer authentication is only being set on the first first instantiation of the vt...
StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock)
ActOnCXXCatchBlock - Takes an exception declaration and a handler block and creates a proper catch ha...
void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation, PragmaMsStackAction Action, bool Value)
ActOnPragmaMSStrictGuardStackCheck - Called on well formed #pragma strict_gs_check.
Definition SemaAttr.cpp:874
void ActOnUninitializedDecl(Decl *dcl)
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
void ApplyAPINotesType(Decl *D, StringRef TypeString)
Apply the 'Type:' annotation to the specified declaration.
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef< TemplateArgument > TemplateArgs, ConstraintSatisfaction &Satisfaction)
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc)
void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction, const Expr *ThisArg, ArrayRef< const Expr * > Args)
void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt)
ActOnCaseStmtBody - This installs a statement as the body of a case.
Definition SemaStmt.cpp:563
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind)
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
PragmaSectionKind
Definition Sema.h:2055
@ PSK_ConstSeg
Definition Sema.h:2058
@ PSK_DataSeg
Definition Sema.h:2056
@ PSK_CodeSeg
Definition Sema.h:2059
@ PSK_BSSSeg
Definition Sema.h:2057
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen)
TypeResult ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword, SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:626
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition SemaCast.cpp:337
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6252
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum)
BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a constant expression representing ...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
bool SubstTemplateArgumentsInParameterMapping(ArrayRef< TemplateArgumentLoc > Args, SourceLocation BaseLoc, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Out, bool BuildPackExpansionTypes)
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
CodeAlignAttr * BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E)
ExprResult ActOnStmtExprResult(ExprResult E)
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, IdentifierInfo *IIEnvironment)
void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate=false, VarTemplateSpecializationDecl *PrevVTSD=nullptr)
BuildVariableInstantiation - Used after a new variable has been created.
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
void ActOnCXXForRangeDecl(Decl *D)
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc)
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition Sema.h:3531
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2099
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, AcceptableKind Kind, bool OnlyNeedComplete=false)
UnsignedOrNone GetDecompositionElementCount(QualType DecompType, SourceLocation Loc)
PragmaClangSection PragmaClangBSSSection
Definition Sema.h:1811
Decl * ActOnDeclarator(Scope *S, Declarator &D)
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
DeclarationName VAListTagName
VAListTagName - The declaration name corresponding to __va_list_tag.
Definition Sema.h:1338
ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel)
AbstractDiagSelID
Definition Sema.h:6198
@ AbstractSynthesizedIvarType
Definition Sema.h:6205
@ AbstractVariableType
Definition Sema.h:6202
@ AbstractReturnType
Definition Sema.h:6200
@ AbstractNone
Definition Sema.h:6199
@ AbstractFieldType
Definition Sema.h:6203
@ AbstractArrayType
Definition Sema.h:6206
@ AbstractParamType
Definition Sema.h:6201
@ AbstractIvarType
Definition Sema.h:6204
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition SemaStmt.cpp:950
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiate the definition of an enum from a given pattern.
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
ExprResult CheckVarOrConceptTemplateTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs)
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
ExprResult SubstCXXIdExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
Substitute an expression as if it is a address-of-operand, which makes it act like a CXXIdExpression ...
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
void CheckAlignasUnderalignment(Decl *D)
SemaSPIRV & SPIRV()
Definition Sema.h:1521
ParsedType getConstructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext)
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx)
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition Sema.h:8325
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand)
Act on the result of classifying a name as an undeclared member of a dependent base class.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder=AtomicArgumentOrder::API)
Decl * ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc)
Complete the definition of an export declaration.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI)
Note that we have finished the explicit captures for the given lambda.
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind, SourceLocation Loc)
void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC)
ActOnPragmaFPContract - Called on well formed #pragma {STDC,OPENCL} FP_CONTRACT and #pragma clang fp ...
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc)
Called on well formed #pragma clang optimize.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
QualType PreferredConditionType(ConditionKind K) const
Definition Sema.h:7934
CUDALaunchBoundsAttr * CreateLaunchBoundsAttr(const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks)
Create an CUDALaunchBoundsAttr attribute.
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to 'begin' or 'end' for a C++11 for-range statement.
LiteralOperatorLookupResult
The possible outcomes of name lookup for a literal operator.
Definition Sema.h:9346
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9350
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9356
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9348
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9353
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9364
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9360
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
sema::FunctionScopeInfo * getEnclosingFunction() const
Definition Sema.cpp:2529
const ExpressionEvaluationContextRecord & parentEvaluationContext() const
Definition Sema.h:6914
SemaLoongArch & LoongArch()
Definition Sema.h:1461
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
CheckConstexprKind
Definition Sema.h:6387
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6392
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6389
ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, FunctionDecl *Fun)
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:13935
void CheckVariableDeclarationType(VarDecl *NewVD)
sema::CompoundScopeInfo & getCurCompoundScope() const
Definition SemaStmt.cpp:432
DeclContext * FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs)
Finds the instantiation of the given declaration context within the current instantiation.
sema::CapturedRegionScopeInfo * getCurCapturedRegion()
Retrieve the current captured region, if any.
Definition Sema.cpp:2888
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1275
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we're skipping.
void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E)
Warn when implicitly casting 0 to nullptr.
Definition Sema.cpp:707
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E)
CheckCXXThrowOperand - Validate the operand of a throw.
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II)
Called on pragma clang __debug dump II.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled)
ActOnPragmaFenvAccess - Called on well formed #pragma STDC FENV_ACCESS.
bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New)
void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc, ArithConvKind ACK)
Check that the usual arithmetic conversions can be performed on this pair of expressions that might b...
bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Perform substitution on the base class specifiers of the given class template specialization.
void LoadExternalVTableUses()
Load any externally-stored vtable uses.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
llvm::SmallPtrSet< const NamedDecl *, 4 > TypoCorrectedFunctionDefinitions
The function definitions which were renamed as part of typo-correction to match their respective decl...
Definition Sema.h:3512
void ActOnFinishOfCompoundStmt()
Definition SemaStmt.cpp:428
concepts::Requirement * ActOnNestedRequirement(Expr *Constraint)
void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB)
Cause the built diagnostic to be emitted on the DiagosticsEngine.
Definition Sema.cpp:1675
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
Decl * ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList)
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition Sema.h:15294
void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
AddAlignValueAttr - Adds an align_value attribute to a particular declaration.
UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(llvm::ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs)
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
static ConditionResult ConditionError()
Definition Sema.h:7789
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition SemaStmt.cpp:436
void NoteTemplateParameterLocation(const NamedDecl &Decl)
SemaWasm & Wasm()
Definition Sema.h:1541
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ActOnConvertVectorExpr - create a new convert-vector expression from the provided arguments.
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D)
void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
Check if a method overloads virtual methods in a base class without overriding any.
IdentifierResolver IdResolver
Definition Sema.h:3460
bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext)
IsInvalidUnlessNestedName - This method is used for error recovery purposes to determine whether the ...
llvm::DenseSet< QualType > InstantiatedNonDependentTypes
Non-dependent types used in templates that have already been instantiated by some template instantiat...
Definition Sema.h:13529
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that's being passed to an __unknown_anytype parameter.
LifetimeCaptureByAttr * ParseLifetimeCaptureByAttr(const ParsedAttr &AL, StringRef ParamName)
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
IsValueInFlagEnum - Determine if a value is allowed as part of a flag enum.
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
SemaPseudoObject & PseudoObject()
Definition Sema.h:1511
LabelDecl * LookupExistingLabel(IdentifierInfo *II, SourceLocation IdentLoc)
Perform a name lookup for a label with the specified name; this does not create a new label if the lo...
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2490
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt)
Definition SemaStmt.cpp:588
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11315
StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef< Stmt * > Handlers)
ActOnCXXTryBlock - Takes a try compound-statement and a number of handlers and creates a try statemen...
FullExprArg MakeFullExpr(Expr *Arg)
Definition Sema.h:7745
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition SemaDecl.cpp:714
void DiagnoseSizeOfParametersAndReturnValue(ArrayRef< ParmVarDecl * > Parameters, QualType ReturnTy, NamedDecl *D)
Diagnose whether the size of parameters or return value of a function or obj-c method definition is p...
void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD, SourceLocation NameLoc)
Returns the TypeDeclType for the given type declaration, as ASTContext::getTypeDeclType would,...
Definition SemaDecl.cpp:143
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false, bool PartialOverloading=false)
Returns the more specialized function template according to the rules of function template partial or...
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition Sema.h:8284
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1274
static int getPrintable(int I)
Definition Sema.h:14988
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName)
Called on well formed #pragma section().
Definition SemaAttr.cpp:885
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition Sema.h:9616
bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling)
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:12830
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope)
Definition SemaStmt.cpp:568
ExprResult ActOnCXXThis(SourceLocation Loc)
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
TemplateNameKindForDiagnostics
Describes the detailed kind of a template name. Used in diagnostics.
Definition Sema.h:3804
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
static const std::string & getPrintable(const std::string &S)
Definition Sema.h:14993
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
void warnOnReservedIdentifier(const NamedDecl *D)
StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc)
Definition SemaStmt.cpp:532
TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, UnsignedOrNone &NumExpansions) const
Returns the pattern of the pack expansion for a template argument.
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, UnsignedOrNone NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
bool isCheckingDefaultArgumentOrInitializer() const
Definition Sema.h:8152
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
SemaARM & ARM()
Definition Sema.h:1421
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, SourceLocation DefaultLoc)
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
llvm::DenseSet< InstantiatingSpecializationsKey > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition Sema.h:13525
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:322
bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R)
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation TriviallyRelocatable, SourceLocation Replaceable, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
static const char * getPrintable(const char *S)
Definition Sema.h:14991
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO={})
Add overload candidates for overloaded operators that are member functions.
ExprResult ActOnDecltypeExpression(Expr *E)
Process the expression contained within a decltype.
bool isAbstractType(SourceLocation Loc, QualType T)
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:652
QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a block pointer type.
PragmaMsStackAction
Definition Sema.h:1817
@ PSK_Push_Set
Definition Sema.h:1823
@ PSK_Reset
Definition Sema.h:1818
@ PSK_Pop_Set
Definition Sema.h:1824
StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body)
FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
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.
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers={})
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc)
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8615
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals, bool EvaluateConstraints=true)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc)
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc)
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod)
Create an implicit import of the given module at the given source location, for error recovery,...
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:292
Stmt - This represents one statement.
Definition Stmt.h:85
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
Exposes information about the current target.
Definition TargetInfo.h:226
A convenient class for passing around template argument information.
A template argument list.
Location wrapper for a TemplateArgument.
Represents a template argument.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
The base class of all kinds of template declarations (e.g., class, function, etc.).
This is a base class for callbacks that will be notified at every template instantiation.
Represents a C++ template name within the type system.
Stores a list of template parameters for a TemplateDecl and its derived classes.
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
A declaration that models statements at global scope.
Definition Decl.h:4617
The top declaration context.
Definition Decl.h:105
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
Represents a declaration of a type.
Definition Decl.h:3513
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
A container of type source information.
Definition TypeBase.h:8249
The base class of the type hierarchy.
Definition TypeBase.h:1833
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3667
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
Simple class containing the result of Sema::CorrectTypo.
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3392
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4128
A set of unresolved declarations.
The iterator over UnresolvedSets.
Represents a C++ using-declaration.
Definition DeclCXX.h:3591
Represents C++ using-directive.
Definition DeclCXX.h:3096
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3399
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
Represents a variable declaration or definition.
Definition Decl.h:926
Declaration of a variable template.
Represents a variable template specialization, which refers to a variable template with a given set o...
Represents a GCC generic vector type.
Definition TypeBase.h:4175
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2754
Consumes visible declarations found when searching for all visible names within a given scope or cont...
Definition Lookup.h:838
Captures information about a #pragma weak directive.
Definition Weak.h:25
The API notes manager helps find API notes associated with declarations.
A requires-expression requirement which queries the validity and properties of an expression ('simple...
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
A static requirement that can be used in a requires-expression to check properties of types and expre...
A requires-expression requirement which queries the existence of a type name or type template special...
Retains information about a block that is currently being parsed.
Definition ScopeInfo.h:790
Retains information about a captured region.
Definition ScopeInfo.h:816
Contains information about the compound statement currently being parsed.
Definition ScopeInfo.h:67
A collection of diagnostics which were delayed.
A diagnostic message which has been conditionally emitted pending the complete parsing of the current...
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
#define bool
Definition gpuintrin.h:32
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
Enums for the diagnostics of target, target_version and target_clones.
Definition Sema.h:840
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
llvm::DenseMap< int, SourceRange > ParsedSubjectMatchRuleSet
void threadSafetyCleanup(BeforeSet *Cache)
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
PragmaClangSectionAction
Definition Sema.h:474
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:55
ImplicitTypenameContext
Definition DeclSpec.h:1857
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
OverloadKind
Definition Sema.h:809
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:820
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:812
bool isa(CodeGen::Address addr)
Definition Address.h:330
OpaquePtr< TemplateName > ParsedTemplateTy
Definition Ownership.h:256
ArrayTypeTrait
Names for the array type traits.
Definition TypeTraits.h:42
@ CPlusPlus
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
VariadicCallType
Definition Sema.h:511
FunctionEffectMode
Used with attributes/effects with a boolean condition, e.g. nonblocking.
Definition Sema.h:457
CUDAFunctionTarget
Definition Cuda.h:60
CanThrowResult
Possible results from evaluation of a noexcept expression.
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
AllocationFunctionScope
The scope in which to find allocation functions.
Definition Sema.h:777
@ Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition Sema.h:785
PragmaMSCommentKind
Definition PragmaKinds.h:14
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:35
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
TryCaptureKind
Definition Sema.h:651
IfStatementKind
In an if statement, this denotes whether the statement is a constexpr or consteval if statement.
Definition Specifiers.h:39
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition Sema.h:659
@ BitwiseOp
A bitwise operation.
Definition Sema.h:663
@ Arithmetic
An arithmetic operation.
Definition Sema.h:661
@ Conditional
A conditional (?:) operator.
Definition Sema.h:667
@ CompAssign
A compound assignment expression.
Definition Sema.h:669
@ Comparison
A comparison.
Definition Sema.h:665
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:348
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:271
@ Success
Annotation was successful.
Definition Parser.h:65
CXXConstructionKind
Definition ExprCXX.h:1541
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:149
PointerAuthDiscArgKind
Definition Sema.h:592
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:602
@ TemplateTemplateArgument
Definition Sema.h:611
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
NonTrivialCUnionContext
Definition Sema.h:530
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:626
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:634
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:640
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:631
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:637
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:236
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
void inferNoReturnAttr(Sema &S, const Decl *D)
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:918
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:204
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:123
@ AS_none
Definition Specifiers.h:127
LazyOffsetPtr< Decl, GlobalDeclID, &ExternalASTSource::GetExternalDecl > LazyDeclPtr
A lazy pointer to a declaration.
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
CapturedRegionKind
The different kinds of captured statement.
StorageClass
Storage classes.
Definition Specifiers.h:248
Expr * Cond
};
llvm::MutableArrayRef< ImplicitConversionSequence > ConversionSequenceList
A list of implicit conversion sequences for the arguments of an OverloadCandidate.
Definition Overload.h:922
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
bool isFunctionOrMethodOrBlockForAttrSubject(const Decl *D)
Return true if the given decl has function type (function or function-typed variable) or an Objective...
Definition Attr.h:40
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition Overload.h:89
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
LambdaCaptureInitKind
Definition DeclSpec.h:2798
@ CopyInit
[a = b], [a = {b}]
Definition DeclSpec.h:2800
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
@ AANT_ArgumentIntegerConstant
PragmaOptionsAlignKind
Definition Sema.h:476
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:614
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3719
CorrectTypoKind
Definition Sema.h:804
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
const FunctionProtoType * T
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
bool isFunctionOrMethodVariadic(const Decl *D)
Definition Attr.h:112
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:687
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:710
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:773
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition Sema.h:702
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition Sema.h:752
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition Sema.h:742
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition Sema.h:769
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition Sema.h:756
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
Definition Sema.h:694
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition Sema.h:736
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:731
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition Sema.h:765
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:689
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition Sema.h:721
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition Sema.h:698
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition Sema.h:706
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition Sema.h:748
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition Sema.h:715
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:727
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition Sema.h:760
TagUseKind
Definition Sema.h:449
MSVtorDispMode
In the Microsoft ABI, this controls the placement of virtual displacement members used to implement v...
Definition LangOptions.h:38
PragmaClangSectionKind
pragma clang section kind
Definition Sema.h:465
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5878
TUFragmentKind
Definition Sema.h:485
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
NameClassificationKind
Describes the result of the name lookup and resolution performed by Sema::ClassifyName().
Definition Sema.h:553
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:585
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:560
@ DependentNonType
The name denotes a member of a dependent type that could not be resolved.
Definition Sema.h:574
@ UndeclaredTemplate
The name was classified as an ADL-only function template name.
Definition Sema.h:587
@ NonType
The name was classified as a specific non-type, non-template declaration.
Definition Sema.h:566
@ Unknown
This name is not a type or template in this context, but might be something else.
Definition Sema.h:556
@ Error
Classification failed; an error has been produced.
Definition Sema.h:558
@ Type
The name was classified as a type.
Definition Sema.h:562
@ TypeTemplate
The name was classified as a template whose specializations are types.
Definition Sema.h:581
@ Concept
The name was classified as a concept name.
Definition Sema.h:589
@ OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
Definition Sema.h:579
@ UndeclaredNonType
The name was classified as an ADL-only function name.
Definition Sema.h:570
@ VarTemplate
The name was classified as a variable template name.
Definition Sema.h:583
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:497
CastKind
CastKind - The kind of operation required for a conversion.
AllowFoldKind
Definition Sema.h:653
TranslationUnitKind
Describes the kind of translation unit being processed.
@ TU_Complete
The translation unit is a complete translation unit.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
ComparisonCategoryType
An enumeration representing the different comparison categories types.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
VarArgKind
Definition Sema.h:674
PragmaMSStructKind
Definition PragmaKinds.h:23
AssignmentAction
Definition Sema.h:214
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:425
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
@ TNK_Concept_template
The name refers to a concept.
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
BuiltinCountedByRefKind
Definition Sema.h:519
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool hasImplicitObjectParameter(const Decl *D)
Definition Attr.h:126
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition Lambda.h:22
PragmaFloatControlKind
Definition PragmaKinds.h:28
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:149
TypeAwareAllocationMode
Definition ExprCXX.h:2253
IfExistsResult
Describes the result of an "if-exists" condition check.
Definition Sema.h:789
@ Exists
The symbol exists.
Definition Sema.h:791
@ DoesNotExist
The symbol does not exist.
Definition Sema.h:794
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition Specifiers.h:410
bool hasFunctionProto(const Decl *D)
hasFunctionProto - Return true if the given decl has a argument information.
Definition Attr.h:55
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
unsigned getFunctionOrMethodNumParams(const Decl *D)
getFunctionOrMethodNumParams - Return number of function or method parameters.
Definition Attr.h:64
TPOC
The context in which partial ordering of function templates occurs.
Definition Template.h:302
TrivialABIHandling
Definition Sema.h:643
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:648
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:645
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:367
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:417
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:412
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:415
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:388
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:374
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:410
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:419
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:407
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:377
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:391
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:380
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:394
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:383
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:404
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:421
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:398
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:401
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
U cast(CodeGen::Address addr)
Definition Address.h:327
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:1215
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:824
@ CaseValue
Expression in a case label.
Definition Sema.h:825
@ StaticAssertMessageData
Call to data() in a static assert message.
Definition Sema.h:835
@ Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:826
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:833
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:832
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:830
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:828
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:831
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
SourceLocIdentKind
Definition Expr.h:4938
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5853
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5864
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5867
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5871
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
TypeTrait
Names for traits that operate specifically on types.
Definition TypeTraits.h:21
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2247
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Dynamic
throw(T1, T2)
PredefinedIdentKind
Definition Expr.h:1989
CheckedConversionKind
The kind of conversion being performed.
Definition Sema.h:436
@ Implicit
An implicit conversion.
Definition Sema.h:438
@ CStyleCast
A C-style cast.
Definition Sema.h:440
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:446
@ OtherCast
A cast other than a C-style cast.
Definition Sema.h:444
@ FunctionalCast
A functional-style cast.
Definition Sema.h:442
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition Specifiers.h:173
unsigned int uint32_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
int const char * function
Definition c++config.h:31
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:91
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
A structure used to record information about a failed template argument deduction,...
Describes whether we've seen any nullability information for the given file.
Definition Sema.h:240
SourceLocation PointerEndLoc
The end location for the first pointer declarator in the file.
Definition Sema.h:247
SourceLocation PointerLoc
The first pointer declarator (of any pointer kind) in the file that does not have a corresponding nul...
Definition Sema.h:243
bool SawTypeNullability
Whether we saw any type nullability annotations in the given file.
Definition Sema.h:253
uint8_t PointerKind
Which kind of pointer declarator we saw.
Definition Sema.h:250
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition TypeBase.h:4991
Holds information about the various types of exception specification.
Definition TypeBase.h:5311
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5313
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5316
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5319
Extra information about a function prototype.
Definition TypeBase.h:5339
Represents a complete lambda introducer.
Definition DeclSpec.h:2806
Contains a late templated function.
Definition Sema.h:15617
FPOptions FPO
Floating-point options in the point of definition.
Definition Sema.h:15622
Decl * D
The template function declaration to be late parsed.
Definition Sema.h:15620
A normalized constraint, as defined in C++ [temp.constr.normal], is either an atomic constraint,...
Definition SemaConcept.h:36
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:926
Describes how types, statements, expressions, and declarations should be printed.
SourceLocation CurrentPragmaLocation
Definition Sema.h:2030
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10474
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10481
CheckNonDependentConversionsFlag(bool SuppressUserConversions, bool OnlyInitializeNonUserDefinedConversions)
Definition Sema.h:10483
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:11959
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:11955
CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &)=delete
CheckTemplateArgumentInfo(bool PartialOrdering=false, bool MatchingTTP=false)
Definition Sema.h:11936
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:11948
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:11945
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:11945
CheckTemplateArgumentInfo & operator=(const CheckTemplateArgumentInfo &)=delete
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13035
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition Sema.h:13205
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool SavedInNonInstantiationSFINAEContext
Was the enclosing context a non-instantiation SFINAE context?
Definition Sema.h:13152
bool InParameterMappingSubstitution
Whether we're substituting into the parameter mapping of a constraint.
Definition Sema.h:13158
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition Sema.h:13174
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition Sema.h:13200
ArrayRef< TemplateArgument > template_arguments() const
Definition Sema.h:13193
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation,...
Definition Sema.h:13169
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13161
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13187
bool InConstraintSubstitution
Whether we're substituting into constraints.
Definition Sema.h:13155
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13177
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition Sema.h:13184
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:13037
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13129
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition Sema.h:13047
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13056
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition Sema.h:13075
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13126
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition Sema.h:13083
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition Sema.h:13090
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13133
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition Sema.h:13101
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13139
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition Sema.h:13066
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition Sema.h:13145
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13142
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition Sema.h:13148
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13063
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition Sema.h:13071
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13079
@ TemplateInstantiation
We are instantiating a template declaration.
Definition Sema.h:13040
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition Sema.h:13093
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13097
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13052
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13123
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition Sema.h:13086
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13164
CXXSpecialMemberKind SpecialMember
The special member being declared or defined.
Definition Sema.h:13190
bool isInstantiationRecord() const
Determines whether this template is an actual instantiation that should be counted toward the maximum...
InitializationContext(SourceLocation Loc, ValueDecl *Decl, DeclContext *Context)
Definition Sema.h:6831
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6737
SmallVector< CXXBindTemporaryExpr *, 8 > DelayedDecltypeBinds
If we are processing a decltype type, a set of temporary binding expressions for which we have deferr...
Definition Sema.h:6765
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6767
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6818
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6757
SmallVector< CallExpr *, 8 > DelayedDecltypeCalls
If we are processing a decltype type, a set of call expressions for which we have deferred checking t...
Definition Sema.h:6761
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6772
llvm::SmallPtrSet< DeclRefExpr *, 4 > ReferenceToConsteval
Set of DeclRefExprs referencing a consteval function when used in a context not already known to be i...
Definition Sema.h:6780
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6776
bool IsCaseExpr
Whether evaluating an expression for a switch case label.
Definition Sema.h:6821
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6786
enum clang::Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext
SmallVector< LambdaExpr *, 2 > Lambdas
The lambdas that are present within this context, if it is indeed an unevaluated context.
Definition Sema.h:6752
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6794
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition Sema.h:6824
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6790
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6742
std::optional< InitializationContext > DelayedDefaultInitializationContext
Definition Sema.h:6841
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext)
Definition Sema.h:6843
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6739
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6746
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2607
FunctionEffectDiffVector(const FunctionEffectsRef &Old, const FunctionEffectsRef &New)
Caller should short-circuit by checking for equality first.
std::optional< FunctionEffectWithCondition > Old
Definition Sema.h:15524
bool shouldDiagnoseConversion(QualType SrcType, const FunctionEffectsRef &SrcFX, QualType DstType, const FunctionEffectsRef &DstFX) const
Return true if adding or removing the effect as part of a type conversion should generate a diagnosti...
bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction, const FunctionEffectsRef &OldFX, const FunctionDecl &NewFunction, const FunctionEffectsRef &NewFX) const
Return true if adding or removing the effect in a redeclaration should generate a diagnostic.
StringRef effectName() const
Definition Sema.h:15528
OverrideResult shouldDiagnoseMethodOverride(const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX, const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const
Return true if adding or removing the effect in a C++ virtual method override should generate a diagn...
OverrideResult
Describes the result of effects differing between a base class's virtual method and an overriding met...
Definition Sema.h:15536
std::optional< FunctionEffectWithCondition > New
Definition Sema.h:15526
FunctionEffect::Kind EffectKind
Definition Sema.h:15521
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13391
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange=SourceRange())
Note that we are instantiating a class template, function template, variable template,...
void Clear()
Note that we have finished instantiating this template.
LocalInstantiationScope * Scope
Definition Sema.h:14062
LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D)
Definition Sema.h:14065
bool isMoveEligible() const
Definition Sema.h:11073
bool isCopyElidable() const
Definition Sema.h:11074
const VarDecl * Candidate
Definition Sema.h:11068
IdentifierInfo * Identifier
The identifier preceding the '::'.
Definition Sema.h:3273
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType=ParsedType())
Creates info object for the most typical case.
Definition Sema.h:3282
SourceLocation IdentifierLoc
The location of the identifier.
Definition Sema.h:3276
SourceLocation CCLoc
The location of the '::'.
Definition Sema.h:3279
ParsedType ObjectType
The type of the object, if we're parsing nested-name-specifier in a member access expression.
Definition Sema.h:3270
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType)
Definition Sema.h:3288
SourceLocation LocStart
Definition Sema.h:7523
IdentifierInfo * IdentInfo
Definition Sema.h:7526
OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType)
Definition Sema.h:12562
This an attribute introduced by #pragma clang attribute.
Definition Sema.h:2086
SmallVector< attr::SubjectMatchRule, 4 > MatchRules
Definition Sema.h:2089
A push'd group of PragmaAttributeEntries.
Definition Sema.h:2094
SourceLocation Loc
The location of the push attribute.
Definition Sema.h:2096
SmallVector< PragmaAttributeEntry, 2 > Entries
Definition Sema.h:2099
const IdentifierInfo * Namespace
The namespace of this push group.
Definition Sema.h:2098
SourceLocation PragmaLocation
Definition Sema.h:1808
PragmaMsStackAction Action
Definition Sema.h:1828
Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
Definition Sema.h:1941
llvm::StringRef StackSlotLabel
Definition Sema.h:1937
SourceLocation PragmaLocation
Definition Sema.h:1939
SourceLocation PragmaPushLocation
Definition Sema.h:1940
ValueType CurrentValue
Definition Sema.h:2011
void SentinelAction(PragmaMsStackAction Action, StringRef Label)
Definition Sema.h:1997
bool hasValue() const
Definition Sema.h:2007
SmallVector< Slot, 2 > Stack
Definition Sema.h:2009
ValueType DefaultValue
Definition Sema.h:2010
SourceLocation CurrentPragmaLocation
Definition Sema.h:2012
PragmaStack(const ValueType &Default)
Definition Sema.h:2004
void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value)
Definition Sema.h:1948
ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val)
Definition Sema.h:5053
ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val)
Definition Sema.h:5047
RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
Definition Sema.h:13010
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition Sema.h:10371
Abstract class used to diagnose incomplete types.
Definition Sema.h:8217
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
Definition Sema.h:2649
unsigned LayoutCompatible
If true, Type should be compared with other expression's types for layout-compatibility.
Definition Sema.h:2658
bool CheckSameAsPrevious
Definition Sema.h:353
NamedDecl * Previous
Definition Sema.h:354
SkipBodyInfo()=default
NamedDecl * New
Definition Sema.h:355
Information about a template-id annotation token.