clang 24.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"
41#include "clang/Basic/Cuda.h"
44#include "clang/Basic/LLVM.h"
45#include "clang/Basic/Lambda.h"
47#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"
71#include "clang/Sema/Weak.h"
72#include "llvm/ADT/APInt.h"
73#include "llvm/ADT/ArrayRef.h"
74#include "llvm/ADT/BitmaskEnum.h"
75#include "llvm/ADT/DenseMap.h"
76#include "llvm/ADT/DenseSet.h"
77#include "llvm/ADT/FloatingPointMode.h"
78#include "llvm/ADT/FoldingSet.h"
79#include "llvm/ADT/MapVector.h"
80#include "llvm/ADT/PointerIntPair.h"
81#include "llvm/ADT/PointerUnion.h"
82#include "llvm/ADT/STLExtras.h"
83#include "llvm/ADT/STLForwardCompat.h"
84#include "llvm/ADT/STLFunctionalExtras.h"
85#include "llvm/ADT/SetVector.h"
86#include "llvm/ADT/SmallBitVector.h"
87#include "llvm/ADT/SmallPtrSet.h"
88#include "llvm/ADT/SmallSet.h"
89#include "llvm/ADT/SmallVector.h"
90#include "llvm/ADT/StringExtras.h"
91#include "llvm/ADT/StringMap.h"
92#include "llvm/ADT/TinyPtrVector.h"
93#include "llvm/Support/Allocator.h"
94#include "llvm/Support/Compiler.h"
95#include "llvm/Support/Error.h"
96#include "llvm/Support/ErrorHandling.h"
97#include <cassert>
98#include <climits>
99#include <cstddef>
100#include <cstdint>
101#include <deque>
102#include <functional>
103#include <iterator>
104#include <memory>
105#include <optional>
106#include <string>
107#include <tuple>
108#include <type_traits>
109#include <utility>
110#include <vector>
111
112namespace llvm {
113struct InlineAsmIdentifierInfo;
114} // namespace llvm
115
116namespace clang {
117class ADLResult;
118class APValue;
120class ASTConsumer;
121class ASTContext;
122class ASTDeclReader;
124class ASTReader;
125class ASTWriter;
126class CXXBasePath;
127class CXXBasePaths;
130enum class ComparisonCategoryType : unsigned char;
132class DarwinSDKInfo;
133class DeclGroupRef;
137class Designation;
138class IdentifierInfo;
144enum class LangAS : unsigned int;
146class LookupResult;
149class ModuleLoader;
153class ObjCMethodDecl;
154struct OverloadCandidate;
155enum class OverloadCandidateParamOrder : char;
156enum OverloadCandidateRewriteKind : unsigned;
158class Preprocessor;
160class SemaAMDGPU;
161class SemaARM;
162class SemaAVR;
163class SemaBPF;
165class SemaCUDA;
166class SemaDirectX;
167class SemaHLSL;
168class SemaHexagon;
169class SemaLoongArch;
170class SemaM68k;
171class SemaMIPS;
172class SemaMSP430;
173class SemaNVPTX;
174class SemaObjC;
175class SemaOpenACC;
176class SemaOpenCL;
177class SemaOpenMP;
178class SemaPPC;
179class SemaPseudoObject;
180class SemaRISCV;
181class SemaSPIRV;
182class SemaSYCL;
183class SemaSwift;
184class SemaSystemZ;
185class SemaWasm;
186class SemaX86;
188class TemplateArgument;
190class TemplateInstantiationCallback;
193class Token;
194class TypeConstraint;
199
200namespace sema {
201class BlockScopeInfo;
202class Capture;
209class LambdaScopeInfo;
210class SemaPPCallbacks;
212} // namespace sema
213
214// AssignmentAction - This is used by all the assignment diagnostic functions
215// to represent what is actually causing the operation
226
227namespace threadSafety {
228class BeforeSet;
229void threadSafetyCleanup(BeforeSet *Cache);
230} // namespace threadSafety
231
232// FIXME: No way to easily map from TemplateTypeParmTypes to
233// TemplateTypeParmDecls, so we have this horrible PointerUnion.
234typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *,
235 const TemplateSpecializationType *,
236 const SubstBuiltinTemplatePackType *>,
239
240/// Describes whether we've seen any nullability information for the given
241/// file.
243 /// The first pointer declarator (of any pointer kind) in the file that does
244 /// not have a corresponding nullability annotation.
246
247 /// The end location for the first pointer declarator in the file. Used for
248 /// placing fix-its.
250
251 /// Which kind of pointer declarator we saw.
253
254 /// Whether we saw any type nullability annotations in the given file.
255 bool SawTypeNullability = false;
256};
257
258/// A mapping from file IDs to a record of whether we've seen nullability
259/// information in that file.
261 /// A mapping from file IDs to the nullability information for each file ID.
262 llvm::DenseMap<FileID, FileNullability> Map;
263
264 /// A single-element cache based on the file ID.
265 struct {
268 } Cache;
269
270public:
272 // Check the single-element cache.
273 if (file == Cache.File)
274 return Cache.Nullability;
275
276 // It's not in the single-element cache; flush the cache if we have one.
277 if (!Cache.File.isInvalid()) {
278 Map[Cache.File] = Cache.Nullability;
279 }
280
281 // Pull this entry into the cache.
282 Cache.File = file;
283 Cache.Nullability = Map[file];
284 return Cache.Nullability;
285 }
286};
287
288/// Tracks expected type during expression parsing, for use in code completion.
289/// The type is tied to a particular token, all functions that update or consume
290/// the type take a start location of the token they are looking at as a
291/// parameter. This avoids updating the type on hot paths in the parser.
293public:
295 : Ctx(Ctx), Enabled(Enabled) {}
296
300 /// Handles e.g. BaseType{ .D = Tok...
302 const Designation &D);
303 /// Computing a type for the function argument may require running
304 /// overloading, so we postpone its computation until it is actually needed.
305 ///
306 /// Clients should be very careful when using this function, as it stores a
307 /// function_ref, clients should make sure all calls to get() with the same
308 /// location happen while function_ref is alive.
309 ///
310 /// The callback should also emit signature help as a side-effect, but only
311 /// if the completion point has been reached.
313 llvm::function_ref<QualType()> ComputeType);
314
317 SourceLocation OpLoc);
320 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
321 /// Handles all type casts, including C-style cast, C++ casts, etc.
323
324 /// Get the expected type associated with this location, if any.
325 ///
326 /// If the location is a function argument, determining the expected type
327 /// involves considering all function overloads and the arguments so far.
328 /// In this case, signature help for these function overloads will be reported
329 /// as a side-effect (only if the completion point has been reached).
331 if (!Enabled || Tok != ExpectedLoc)
332 return QualType();
333 if (!Type.isNull())
334 return Type;
335 if (ComputeType)
336 return ComputeType();
337 return QualType();
338 }
339
340private:
341 ASTContext *Ctx;
342 bool Enabled;
343 /// Start position of a token for which we store expected type.
344 SourceLocation ExpectedLoc;
345 /// Expected type for a token starting at ExpectedLoc.
347 /// A function to compute expected type at ExpectedLoc. It is only considered
348 /// if Type is null.
349 llvm::function_ref<QualType()> ComputeType;
350};
351
353 SkipBodyInfo() = default;
354 bool ShouldSkip = false;
356 NamedDecl *Previous = nullptr;
357 NamedDecl *New = nullptr;
358};
359
360/// Describes the result of template argument deduction.
361///
362/// The TemplateDeductionResult enumeration describes the result of
363/// template argument deduction, as returned from
364/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
365/// structure provides additional information about the results of
366/// template argument deduction, e.g., the deduced template argument
367/// list (if successful) or the specific template parameters or
368/// deduced arguments that were involved in the failure.
370 /// Template argument deduction was successful.
372 /// The declaration was invalid; do nothing.
374 /// Template argument deduction exceeded the maximum template
375 /// instantiation depth (which has already been diagnosed).
377 /// Template argument deduction did not deduce a value
378 /// for every template parameter.
380 /// Template argument deduction did not deduce a value for every
381 /// expansion of an expanded template parameter pack.
383 /// Template argument deduction produced inconsistent
384 /// deduced values for the given template parameter.
386 /// Template argument deduction failed due to inconsistent
387 /// cv-qualifiers on a template parameter type that would
388 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
389 /// but were given a non-const "X".
391 /// Substitution of the deduced template argument values
392 /// resulted in an error.
394 /// After substituting deduced template arguments, a dependent
395 /// parameter type did not match the corresponding argument.
397 /// After substituting deduced template arguments, an element of
398 /// a dependent parameter type did not match the corresponding element
399 /// of the corresponding argument (when deducing from an initializer list).
401 /// A non-depnedent component of the parameter did not match the
402 /// corresponding component of the argument.
404 /// When performing template argument deduction for a function
405 /// template, there were too many call arguments.
407 /// When performing template argument deduction for a function
408 /// template, there were too few call arguments.
410 /// The explicitly-specified template arguments were not valid
411 /// template arguments for the given template.
413 /// Checking non-dependent argument conversions failed.
415 /// The deduced arguments did not satisfy the constraints associated
416 /// with the template.
418 /// Deduction failed; that's all we know.
420 /// CUDA Target attributes do not match.
422 /// Some error which was already diagnosed.
424};
425
426/// Kinds of C++ special members.
436
437/// The kind of conversion being performed.
439 /// An implicit conversion.
441 /// A C-style cast.
443 /// A functional-style cast.
445 /// A cast other than a C-style cast.
447 /// A conversion for an operand of a builtin overloaded operator.
449};
450
451enum class TagUseKind {
452 Reference, // Reference to a tag: 'struct foo *X;'
453 Declaration, // Fwd decl of a tag: 'struct foo;'
454 Definition, // Definition of a tag: 'struct foo { int X; } Y;'
455 Friend // Friend declaration: 'friend struct foo;'
456};
457
458/// Used with attributes/effects with a boolean condition, e.g. `nonblocking`.
460 None, // effect is not present.
461 False, // effect(false).
462 True, // effect(true).
463 Dependent // effect(expr) where expr is dependent.
464};
465
466/// pragma clang section kind
469 BSS = 1,
470 Data = 2,
472 Text = 4,
474};
475
476enum class PragmaClangSectionAction { Set = 0, Clear = 1 };
477
479 Native, // #pragma options align=native
480 Natural, // #pragma options align=natural
481 Packed, // #pragma options align=packed
482 Power, // #pragma options align=power
483 Mac68k, // #pragma options align=mac68k
484 Reset // #pragma options align=reset
485};
486
487enum class TUFragmentKind {
488 /// The global module fragment, between 'module;' and a module-declaration.
490 /// A normal translation unit fragment. For a non-module unit, this is the
491 /// entire translation unit. Otherwise, it runs from the module-declaration
492 /// to the private-module-fragment (if any) or the end of the TU (if not).
494 /// The private module fragment, between 'module :private;' and the end of
495 /// the translation unit.
497};
498
511
512// Used for emitting the right warning by DefaultVariadicArgumentPromotion
520
529
530// Contexts where using non-trivial C union types can be disallowed. This is
531// passed to err_non_trivial_c_union_in_invalid_context.
533 // Function parameter.
535 // Function return.
537 // Default-initialized object.
539 // Variable with automatic storage duration.
541 // Initializer expression that might copy from another object.
543 // Assignment.
545 // Compound literal.
547 // Block capture.
549 // lvalue-to-rvalue conversion of volatile type.
551};
552
553/// Describes the result of the name lookup and resolution performed
554/// by \c Sema::ClassifyName().
556 /// This name is not a type or template in this context, but might be
557 /// something else.
559 /// Classification failed; an error has been produced.
561 /// The name has been typo-corrected to a keyword.
563 /// The name was classified as a type.
565 /// The name was classified as a specific non-type, non-template
566 /// declaration. ActOnNameClassifiedAsNonType should be called to
567 /// convert the declaration to an expression.
569 /// The name was classified as an ADL-only function name.
570 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
571 /// result to an expression.
573 /// The name denotes a member of a dependent type that could not be
574 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
575 /// convert the result to an expression.
577 /// The name was classified as an overload set, and an expression
578 /// representing that overload set has been formed.
579 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
580 /// expression referencing the overload set.
582 /// The name was classified as a template whose specializations are types.
584 /// The name was classified as a variable template name.
586 /// The name was classified as a function template name.
588 /// The name was classified as an ADL-only function template name.
590 /// The name was classified as a concept name.
592};
593
595 // Address discrimination argument of __ptrauth.
597
598 // Extra discriminator argument of __ptrauth.
600};
601
602/// Common ways to introduce type names without a tag for use in diagnostics.
603/// Keep in sync with err_tag_reference_non_tag.
615
616enum class OffsetOfKind {
617 // Not parsing a type within __builtin_offsetof.
619 // Parsing a type within __builtin_offsetof.
621 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
622 // To improve our diagnostic message.
624};
625
626/// Describes the kind of merge to perform for availability
627/// attributes (including "deprecated", "unavailable", and "availability").
629 /// Don't merge availability attributes at all.
631 /// Merge availability attributes for a redeclaration, which requires
632 /// an exact match.
634 /// Merge availability attributes for an override, which requires
635 /// an exact match or a weakening of constraints.
637 /// Merge availability attributes for an implementation of
638 /// a protocol requirement.
640 /// Merge availability attributes for an implementation of
641 /// an optional protocol requirement.
643};
644
646 /// The triviality of a method unaffected by "trivial_abi".
648
649 /// The triviality of a method affected by "trivial_abi".
651};
652
654
655enum class AllowFoldKind {
658};
659
660/// Context in which we're performing a usual arithmetic conversion.
661enum class ArithConvKind {
662 /// An arithmetic operation.
664 /// A bitwise operation.
666 /// A comparison.
668 /// A conditional (?:) operator.
670 /// A compound assignment expression.
672};
673
674// Used for determining in which context a type is allowed to be passed to a
675// vararg function.
683
684/// AssignConvertType - All of the 'assignment' semantic checks return this
685/// enum to indicate whether the assignment was allowed. These checks are
686/// done for simple assignments, as well as initialization, return from
687/// function, argument passing, etc. The query is phrased in terms of a
688/// source and destination type.
690 /// Compatible - the types are compatible according to the standard.
692
693 /// CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because
694 /// a void * can implicitly convert to another pointer type, which we
695 /// differentiate for better diagnostic behavior.
697
698 /// PointerToInt - The assignment converts a pointer to an int, which we
699 /// accept as an extension.
701
702 /// IntToPointer - The assignment converts an int to a pointer, which we
703 /// accept as an extension.
705
706 /// FunctionVoidPointer - The assignment is between a function pointer and
707 /// void*, which the standard doesn't allow, but we accept as an extension.
709
710 /// IncompatiblePointer - The assignment is between two pointers types that
711 /// are not compatible, but we accept them as an extension.
713
714 /// IncompatibleFunctionPointer - The assignment is between two function
715 /// pointers types that are not compatible, but we accept them as an
716 /// extension.
718
719 /// IncompatibleFunctionPointerStrict - The assignment is between two
720 /// function pointer types that are not identical, but are compatible,
721 /// unless compiled with -fsanitize=cfi, in which case the type mismatch
722 /// may trip an indirect call runtime check.
724
725 /// IncompatiblePointerSign - The assignment is between two pointers types
726 /// which point to integers which have a different sign, but are otherwise
727 /// identical. This is a subset of the above, but broken out because it's by
728 /// far the most common case of incompatible pointers.
730
731 /// CompatiblePointerDiscardsQualifiers - The assignment discards
732 /// c/v/r qualifiers, which we accept as an extension.
734
735 /// IncompatiblePointerDiscardsQualifiers - The assignment
736 /// discards qualifiers that we don't permit to be discarded,
737 /// like address spaces.
739
740 /// IncompatiblePointerDiscardsOverflowBehavior - The assignment
741 /// discards overflow behavior annotations between otherwise compatible
742 /// pointer types.
744
745 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
746 /// changes address spaces in nested pointer types which is not allowed.
747 /// For instance, converting __private int ** to __generic int ** is
748 /// illegal even though __private could be converted to __generic.
750
751 /// IncompatibleNestedPointerQualifiers - The assignment is between two
752 /// nested pointer types, and the qualifiers other than the first two
753 /// levels differ e.g. char ** -> const char **, but we accept them as an
754 /// extension.
756
757 /// IncompatibleVectors - The assignment is between two vector types that
758 /// have the same size, which we accept as an extension.
760
761 /// IntToBlockPointer - The assignment converts an int to a block
762 /// pointer. We disallow this.
764
765 /// IncompatibleBlockPointer - The assignment is between two block
766 /// pointers types that are not compatible.
768
769 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
770 /// id type and something else (that is incompatible with it). For example,
771 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
773
774 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
775 /// object with __weak qualifier.
777
778 /// IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType
779 /// kinds, e.g., from __ob_trap to __ob_wrap or vice versa.
781
782 /// CompatibleOBTDiscards - Assignment discards overflow behavior
784
785 /// Incompatible - We reject this conversion outright, it is invalid to
786 /// represent it in the AST.
788};
789
790/// The scope in which to find allocation functions.
792 /// Only look for allocation functions in the global scope.
794 /// Only look for allocation functions in the scope of the
795 /// allocated class.
797 /// Look for allocation functions in both the global scope
798 /// and in the scope of the allocated class.
800};
801
802/// Describes the result of an "if-exists" condition check.
803enum class IfExistsResult {
804 /// The symbol exists.
806
807 /// The symbol does not exist.
809
810 /// The name is a dependent name, so the results will differ
811 /// from one instantiation to the next.
813
814 /// An error occurred.
816};
817
818enum class CorrectTypoKind {
819 NonError, // CorrectTypo used in a non error recovery situation.
820 ErrorRecovery // CorrectTypo used in normal error recovery.
821};
822
823enum class OverloadKind {
824 /// This is a legitimate overload: the existing declarations are
825 /// functions or function templates with different signatures.
827
828 /// This is not an overload because the signature exactly matches
829 /// an existing declaration.
831
832 /// This is not an overload because the lookup results contain a
833 /// non-function.
835};
836
837/// Contexts in which a converted constant expression is required.
838enum class CCEKind {
839 CaseValue, ///< Expression in a case label.
840 Enumerator, ///< Enumerator value with fixed underlying type.
841 TemplateArg, ///< Value of a non-type template parameter.
842 TempArgStrict, ///< As above, but applies strict template checking
843 ///< rules.
844 ArrayBound, ///< Array bound in array declarator or new-expression.
845 ExplicitBool, ///< Condition in an explicit(bool) specifier.
846 Noexcept, ///< Condition in a noexcept(bool) specifier.
847 StaticAssertMessageSize, ///< Call to size() in a static assert
848 ///< message.
849 StaticAssertMessageData, ///< Call to data() in a static assert
850 ///< message.
851 PackIndex ///< Index of a pack indexing expression or specifier.
852};
853
854/// Enums for the diagnostics of target, target_version and target_clones.
855namespace DiagAttrParams {
859} // end namespace DiagAttrParams
860
861void inferNoReturnAttr(Sema &S, Decl *D);
862
863#ifdef __GNUC__
864#pragma GCC diagnostic push
865#pragma GCC diagnostic ignored "-Wattributes"
866#endif
867/// Sema - This implements semantic analysis and AST building for C.
868/// \nosubgrouping
869class Sema final : public SemaBase {
870#ifdef __GNUC__
871#pragma GCC diagnostic pop
872#endif
873 // Table of Contents
874 // -----------------
875 // 1. Semantic Analysis (Sema.cpp)
876 // 2. API Notes (SemaAPINotes.cpp)
877 // 3. C++ Access Control (SemaAccess.cpp)
878 // 4. Attributes (SemaAttr.cpp)
879 // 5. Availability Attribute Handling (SemaAvailability.cpp)
880 // 6. Bounds Safety (SemaBoundsSafety.cpp)
881 // 7. Casts (SemaCast.cpp)
882 // 8. Extra Semantic Checking (SemaChecking.cpp)
883 // 9. C++ Coroutines (SemaCoroutine.cpp)
884 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
885 // 11. Declarations (SemaDecl.cpp)
886 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
887 // 13. C++ Declarations (SemaDeclCXX.cpp)
888 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
889 // 15. Expressions (SemaExpr.cpp)
890 // 16. C++ Expressions (SemaExprCXX.cpp)
891 // 17. Member Access Expressions (SemaExprMember.cpp)
892 // 18. Initializers (SemaInit.cpp)
893 // 19. C++ Lambda Expressions (SemaLambda.cpp)
894 // 20. Name Lookup (SemaLookup.cpp)
895 // 21. Modules (SemaModule.cpp)
896 // 22. C++ Overloading (SemaOverload.cpp)
897 // 23. Statements (SemaStmt.cpp)
898 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
899 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
900 // 26. C++ Templates (SemaTemplate.cpp)
901 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
902 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
903 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
904 // 30. C++ Template Declaration Instantiation
905 // (SemaTemplateInstantiateDecl.cpp)
906 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
907 // 32. Constraints and Concepts (SemaConcept.cpp)
908 // 33. Types (SemaType.cpp)
909 // 34. FixIt Helpers (SemaFixItUtils.cpp)
910 // 35. Function Effects (SemaFunctionEffects.cpp)
911 // 36. C++ Expansion Statements (SemaExpand.cpp)
912
913 /// \name Semantic Analysis
914 /// Implementations are in Sema.cpp
915 ///@{
916
917public:
918 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
920 CodeCompleteConsumer *CompletionConsumer = nullptr);
921 ~Sema();
922
923 /// Perform initialization that occurs after the parser has been
924 /// initialized but before it parses anything.
925 void Initialize();
926
927 /// This virtual key function only exists to limit the emission of debug info
928 /// describing the Sema class. GCC and Clang only emit debug info for a class
929 /// with a vtable when the vtable is emitted. Sema is final and not
930 /// polymorphic, but the debug info size savings are so significant that it is
931 /// worth adding a vtable just to take advantage of this optimization.
933
934 const LangOptions &getLangOpts() const { return LangOpts; }
937
940 Preprocessor &getPreprocessor() const { return PP; }
941 ASTContext &getASTContext() const { return Context; }
945
947 StringRef Platform);
949
950 /// Registers an external source. If an external source already exists,
951 /// creates a multiplex external source and appends to it.
952 ///
953 ///\param[in] E - A non-null external sema source.
954 ///
956
957 /// Print out statistics about the semantic analysis.
958 void PrintStats() const;
959
960 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
961 /// guaranteed). Produces a warning if we're low on stack space and allocates
962 /// more in that case. Use this in code that may recurse deeply (for example,
963 /// in template instantiation) to avoid stack overflow.
965 llvm::function_ref<void()> Fn);
966
967 /// Returns default addr space for method qualifiers.
969
970 /// Load weak undeclared identifiers from the external source.
972
973 /// Load #pragma redefine_extname'd undeclared identifiers from the external
974 /// source.
976
977 /// Determine if VD, which must be a variable or function, is an external
978 /// symbol that nonetheless can't be referenced from outside this translation
979 /// unit because its type has no linkage and it's not extern "C".
980 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
981
982 /// Determines whether the given source location is in the main file
983 /// and we're in a context where we should warn about unused entities.
984 bool isMainFileLoc(SourceLocation Loc) const;
985
986 /// Obtain a sorted list of functions that are undefined but ODR-used.
988 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
989
990 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
992 /// Retrieves list of suspicious delete-expressions that will be checked at
993 /// the end of translation unit.
994 const llvm::MapVector<FieldDecl *, DeleteLocs> &
996
997 /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
998 /// This is closely coupled to the SemaDiagnosticBuilder class and
999 /// should not be used elsewhere.
1000 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
1001
1002 void addImplicitTypedef(StringRef Name, QualType T);
1003
1004 /// Whether uncompilable error has occurred. This includes error happens
1005 /// in deferred diagnostics.
1006 bool hasUncompilableErrorOccurred() const;
1007
1008 /// Looks through the macro-expansion chain for the given
1009 /// location, looking for a macro expansion with the given name.
1010 /// If one is found, returns true and sets the location to that
1011 /// expansion loc.
1012 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1013
1014 /// Calls \c Lexer::getLocForEndOfToken()
1015 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1016
1017 /// Calls \c Lexer::findNextToken() to find the next token, and if the
1018 /// locations of both ends of the token can be resolved it return that
1019 /// range; Otherwise it returns an invalid SourceRange.
1021 SourceLocation Loc, bool IncludeMacros, bool IncludeComments,
1022 std::optional<tok::TokenKind> ExpectedToken = std::nullopt);
1023
1024 /// Retrieve the module loader associated with the preprocessor.
1026
1027 /// Invent a new identifier for parameters of abbreviated templates.
1030 unsigned Index);
1031
1033
1034 // Emit all deferred diagnostics.
1035 void emitDeferredDiags();
1036
1037 /// This is called before the very first declaration in the translation unit
1038 /// is parsed. Note that the ASTContext may have already injected some
1039 /// declarations.
1041 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1042 /// translation unit when EOF is reached and all but the top-level scope is
1043 /// popped.
1046
1047 /// Determines the active Scope associated with the given declaration
1048 /// context.
1049 ///
1050 /// This routine maps a declaration context to the active Scope object that
1051 /// represents that declaration context in the parser. It is typically used
1052 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1053 /// declarations) that injects a name for name-lookup purposes and, therefore,
1054 /// must update the Scope.
1055 ///
1056 /// \returns The scope corresponding to the given declaraion context, or NULL
1057 /// if no such scope is open.
1059
1060 void PushFunctionScope();
1061 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1063
1064 /// This is used to inform Sema what the current TemplateParameterDepth
1065 /// is during Parsing. Currently it is used to pass on the depth
1066 /// when parsing generic lambda 'auto' parameters.
1067 void RecordParsingTemplateParameterDepth(unsigned Depth);
1068
1069 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1071 unsigned OpenMPCaptureLevel = 0);
1072
1073 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1074 /// time after they've been popped.
1076 Sema *Self;
1077
1078 public:
1079 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1081 };
1082
1084 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1085
1086 /// Pop a function (or block or lambda or captured region) scope from the
1087 /// stack.
1088 ///
1089 /// \param WP The warning policy to use for CFG-based warnings, or null if
1090 /// such warnings should not be produced.
1091 /// \param D The declaration corresponding to this function scope, if
1092 /// producing CFG-based warnings.
1093 /// \param BlockType The type of the block expression, if D is a BlockDecl.
1096 Decl *D = nullptr, QualType BlockType = QualType());
1097
1099
1104
1105 void PushCompoundScope(bool IsStmtExpr);
1106 void PopCompoundScope();
1107
1108 /// Determine whether any errors occurred within this function/method/
1109 /// block.
1111
1112 /// Retrieve the current block, if any.
1114
1115 /// Get the innermost lambda or block enclosing the current location, if any.
1116 /// This looks through intervening non-lambda, non-block scopes such as local
1117 /// functions.
1119
1120 /// Retrieve the current lambda scope info, if any.
1121 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1122 /// lambda scope info ignoring all inner capturing scopes that are not
1123 /// lambda scopes.
1125 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1126
1127 /// Retrieve the current generic lambda info, if any.
1129
1130 /// Retrieve the current captured region, if any.
1132
1133 void ActOnComment(SourceRange Comment);
1134
1135 /// Retrieve the parser's current scope.
1136 ///
1137 /// This routine must only be used when it is certain that semantic analysis
1138 /// and the parser are in precisely the same context, which is not the case
1139 /// when, e.g., we are performing any kind of template instantiation.
1140 /// Therefore, the only safe places to use this scope are in the parser
1141 /// itself and in routines directly invoked from the parser and *never* from
1142 /// template substitution or instantiation.
1143 Scope *getCurScope() const { return CurScope; }
1144
1146
1150
1151 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1152 const FunctionDecl *FD = nullptr);
1154 const PartialDiagnostic &PD,
1155 const FunctionDecl *FD = nullptr) {
1156 return targetDiag(Loc, PD.getDiagID(), FD) << PD;
1157 }
1158
1159 /// Check if the type is allowed to be used for the current target.
1161 ValueDecl *D = nullptr);
1162
1163 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1164 /// cast. If there is already an implicit cast, merge into the existing one.
1165 /// If isLvalue, the result of the cast is an lvalue.
1168 const CXXCastPath *BasePath = nullptr,
1170
1171 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1172 /// to the conversion from scalar type ScalarTy to the Boolean type.
1174
1175 /// If \p AllowLambda is true, treat lambda as function.
1176 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1177
1178 /// Returns a pointer to the innermost enclosing function, or nullptr if the
1179 /// current context is not inside a function. If \p AllowLambda is true,
1180 /// this can return the call operator of an enclosing lambda, otherwise
1181 /// lambdas are skipped when looking for an enclosing function.
1182 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1183
1184 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1185 /// the method decl for the method being parsed. If we're currently
1186 /// in a 'block', this returns the containing context.
1188
1189 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1190 /// or C function we're in, otherwise return null. If we're currently
1191 /// in a 'block', this returns the containing context.
1193
1194 /// Warn if we're implicitly casting from a _Nullable pointer type to a
1195 /// _Nonnull one.
1197 SourceLocation Loc);
1198
1199 /// Warn when implicitly casting 0 to nullptr.
1200 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1201
1202 /// Warn when implicitly changing function effects.
1204 SourceLocation Loc);
1205
1206 /// makeUnavailableInSystemHeader - There is an error in the current
1207 /// context. If we're still in a system header, and we can plausibly
1208 /// make the relevant declaration unavailable instead of erroring, do
1209 /// so and return true.
1211 UnavailableAttr::ImplicitReason reason);
1212
1213 /// Retrieve a suitable printing policy for diagnostics.
1217
1218 /// Retrieve a suitable printing policy for diagnostics.
1220 const Preprocessor &PP);
1221
1222 /// Scope actions.
1224
1225 /// Determine whether \param D is function like (function or function
1226 /// template) for parsing.
1228
1229 /// The maximum alignment, same as in llvm::Value. We duplicate them here
1230 /// because that allows us not to duplicate the constants in clang code,
1231 /// which we must to since we can't directly use the llvm constants.
1232 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1233 ///
1234 /// This is the greatest alignment value supported by load, store, and alloca
1235 /// instructions, and global values.
1236 static const unsigned MaxAlignmentExponent = 32;
1237 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1238
1239 /// Flag indicating whether or not to collect detailed statistics.
1241
1242 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1243
1244 /// Stack containing information about each of the nested
1245 /// function, block, and method scopes that are currently active.
1247
1248 /// The index of the first FunctionScope that corresponds to the current
1249 /// context.
1251
1252 /// Track the number of currently active capturing scopes.
1254
1255 llvm::BumpPtrAllocator BumpAlloc;
1256
1257 /// The kind of translation unit we are processing.
1258 ///
1259 /// When we're processing a complete translation unit, Sema will perform
1260 /// end-of-translation-unit semantic tasks (such as creating
1261 /// initializers for tentative definitions in C) once parsing has
1262 /// completed. Modules and precompiled headers perform different kinds of
1263 /// checks.
1265
1266 /// Translation Unit Scope - useful to Objective-C actions that need
1267 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1268 /// For example, user-defined classes, built-in "id" type, etc.
1270
1272 return CurScope->incrementMSManglingNumber();
1273 }
1274
1275 /// Try to recover by turning the given expression into a
1276 /// call. Returns true if recovery was attempted or an error was
1277 /// emitted; this may also leave the ExprResult invalid.
1279 bool ForceComplain = false,
1280 bool (*IsPlausibleResult)(QualType) = nullptr);
1281
1282 // Adds implicit lifetime bound attribute for implicit this to its
1283 // TypeSourceInfo.
1285
1286 /// Figure out if an expression could be turned into a call.
1287 ///
1288 /// Use this when trying to recover from an error where the programmer may
1289 /// have written just the name of a function instead of actually calling it.
1290 ///
1291 /// \param E - The expression to examine.
1292 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1293 /// with no arguments, this parameter is set to the type returned by such a
1294 /// call; otherwise, it is set to an empty QualType.
1295 /// \param OverloadSet - If the expression is an overloaded function
1296 /// name, this parameter is populated with the decls of the various
1297 /// overloads.
1298 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1299 UnresolvedSetImpl &NonTemplateOverloads);
1300
1304
1307
1315
1316 std::unique_ptr<APINotesSelectorDiagnosticState> APINotesSelectorDiagnostics;
1317
1318 /// A RAII object to enter scope of a compound statement.
1320 public:
1321 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1322 S.ActOnStartOfCompoundStmt(IsStmtExpr);
1323 }
1324
1325 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1328
1329 private:
1330 Sema &S;
1331 };
1332
1333 /// An RAII helper that pops function a function scope on exit.
1339 if (Active)
1340 S.PopFunctionScopeInfo();
1341 }
1342 void disable() { Active = false; }
1343 };
1344
1346 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1347 }
1348
1349 /// Worker object for performing CFG-based warnings.
1352
1353 /// Callback to the parser to parse templated functions when needed.
1354 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1357
1359 LateTemplateParser = LTP;
1360 OpaqueParser = P;
1361 }
1362
1363 /// Callback to the parser to parse a type expressed as a string.
1364 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1366
1367 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1368 /// This is used as part of a hack to omit that class from ADL results.
1370
1371 /// Is the last error level diagnostic immediate. This is used to determined
1372 /// whether the next info diagnostic should be immediate.
1374
1375 /// Track if we're currently analyzing overflow behavior types in assignment
1376 /// context.
1378
1379 class DelayedDiagnostics;
1380
1382 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1384 };
1387
1388 /// A class which encapsulates the logic for delaying diagnostics
1389 /// during parsing and other processing.
1391 /// The current pool of diagnostics into which delayed
1392 /// diagnostics should go.
1393 sema::DelayedDiagnosticPool *CurPool = nullptr;
1394
1395 public:
1397
1398 /// Adds a delayed diagnostic.
1399 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1400
1401 /// Determines whether diagnostics should be delayed.
1402 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1403
1404 /// Returns the current delayed-diagnostics pool.
1405 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1406
1407 /// Enter a new scope. Access and deprecation diagnostics will be
1408 /// collected in this pool.
1411 state.SavedPool = CurPool;
1412 CurPool = &pool;
1413 return state;
1414 }
1415
1416 /// Leave a delayed-diagnostic state that was previously pushed.
1417 /// Do not emit any of the diagnostics. This is performed as part
1418 /// of the bookkeeping of popping a pool "properly".
1420 CurPool = state.SavedPool;
1421 }
1422
1423 /// Enter a new scope where access and deprecation diagnostics are
1424 /// not delayed.
1427 state.SavedPool = CurPool;
1428 CurPool = nullptr;
1429 return state;
1430 }
1431
1432 /// Undo a previous pushUndelayed().
1434 assert(CurPool == nullptr);
1435 CurPool = state.SavedPool;
1436 }
1438
1442
1443 /// Diagnostics that are emitted only if we discover that the given function
1444 /// must be codegen'ed. Because handling these correctly adds overhead to
1445 /// compilation, this is currently only used for offload languages like CUDA,
1446 /// OpenMP, and SYCL.
1447 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1448
1449 /// CurContext - This is the current declaration context of parsing.
1451
1453 assert(AMDGPUPtr);
1454 return *AMDGPUPtr;
1455 }
1456
1458 assert(ARMPtr);
1459 return *ARMPtr;
1460 }
1461
1463 assert(AVRPtr);
1464 return *AVRPtr;
1465 }
1466
1468 assert(BPFPtr);
1469 return *BPFPtr;
1470 }
1471
1473 assert(CodeCompletionPtr);
1474 return *CodeCompletionPtr;
1475 }
1476
1478 assert(CUDAPtr);
1479 return *CUDAPtr;
1480 }
1481
1483 assert(DirectXPtr);
1484 return *DirectXPtr;
1485 }
1486
1488 assert(HLSLPtr);
1489 return *HLSLPtr;
1490 }
1491
1493 assert(HexagonPtr);
1494 return *HexagonPtr;
1495 }
1496
1498 assert(LoongArchPtr);
1499 return *LoongArchPtr;
1500 }
1501
1503 assert(M68kPtr);
1504 return *M68kPtr;
1505 }
1506
1508 assert(MIPSPtr);
1509 return *MIPSPtr;
1510 }
1511
1513 assert(MSP430Ptr);
1514 return *MSP430Ptr;
1515 }
1516
1518 assert(NVPTXPtr);
1519 return *NVPTXPtr;
1520 }
1521
1523 assert(ObjCPtr);
1524 return *ObjCPtr;
1525 }
1526
1528 assert(OpenACCPtr);
1529 return *OpenACCPtr;
1530 }
1531
1533 assert(OpenCLPtr);
1534 return *OpenCLPtr;
1535 }
1536
1538 assert(OpenMPPtr && "SemaOpenMP is dead");
1539 return *OpenMPPtr;
1540 }
1541
1543 assert(PPCPtr);
1544 return *PPCPtr;
1545 }
1546
1548 assert(PseudoObjectPtr);
1549 return *PseudoObjectPtr;
1550 }
1551
1553 assert(RISCVPtr);
1554 return *RISCVPtr;
1555 }
1556
1558 assert(SPIRVPtr);
1559 return *SPIRVPtr;
1560 }
1561
1563 assert(SYCLPtr);
1564 return *SYCLPtr;
1565 }
1566
1568 assert(SwiftPtr);
1569 return *SwiftPtr;
1570 }
1571
1573 assert(SystemZPtr);
1574 return *SystemZPtr;
1575 }
1576
1578 assert(WasmPtr);
1579 return *WasmPtr;
1580 }
1581
1583 assert(X86Ptr);
1584 return *X86Ptr;
1585 }
1586
1587 /// Source of additional semantic information.
1589
1590protected:
1591 friend class Parser;
1593 friend class ASTReader;
1594 friend class ASTDeclReader;
1595 friend class ASTWriter;
1596
1597private:
1598 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1599 bool WarnedDarwinSDKInfoMissing = false;
1600
1601 StackExhaustionHandler StackHandler;
1602
1603 Sema(const Sema &) = delete;
1604 void operator=(const Sema &) = delete;
1605
1606 /// The handler for the FileChanged preprocessor events.
1607 ///
1608 /// Used for diagnostics that implement custom semantic analysis for #include
1609 /// directives, like -Wpragma-pack.
1610 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1611
1612 /// The parser's current scope.
1613 ///
1614 /// The parser maintains this state here.
1615 Scope *CurScope;
1616
1617 mutable IdentifierInfo *Ident_super;
1618
1619 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1620 std::unique_ptr<SemaARM> ARMPtr;
1621 std::unique_ptr<SemaAVR> AVRPtr;
1622 std::unique_ptr<SemaBPF> BPFPtr;
1623 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1624 std::unique_ptr<SemaCUDA> CUDAPtr;
1625 std::unique_ptr<SemaDirectX> DirectXPtr;
1626 std::unique_ptr<SemaHLSL> HLSLPtr;
1627 std::unique_ptr<SemaHexagon> HexagonPtr;
1628 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1629 std::unique_ptr<SemaM68k> M68kPtr;
1630 std::unique_ptr<SemaMIPS> MIPSPtr;
1631 std::unique_ptr<SemaMSP430> MSP430Ptr;
1632 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1633 std::unique_ptr<SemaObjC> ObjCPtr;
1634 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1635 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1636 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1637 std::unique_ptr<SemaPPC> PPCPtr;
1638 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1639 std::unique_ptr<SemaRISCV> RISCVPtr;
1640 std::unique_ptr<SemaSPIRV> SPIRVPtr;
1641 std::unique_ptr<SemaSYCL> SYCLPtr;
1642 std::unique_ptr<SemaSwift> SwiftPtr;
1643 std::unique_ptr<SemaSystemZ> SystemZPtr;
1644 std::unique_ptr<SemaWasm> WasmPtr;
1645 std::unique_ptr<SemaX86> X86Ptr;
1646
1647 ///@}
1648
1649 //
1650 //
1651 // -------------------------------------------------------------------------
1652 //
1653 //
1654
1655 /// \name API Notes
1656 /// Implementations are in SemaAPINotes.cpp
1657 ///@{
1658
1659public:
1660 /// Map any API notes provided for this declaration to attributes on the
1661 /// declaration.
1662 ///
1663 /// Triggered by declaration-attribute processing.
1664 void ProcessAPINotes(Decl *D);
1665 /// Apply the 'Nullability:' annotation to the specified declaration
1666 void ApplyNullability(Decl *D, NullabilityKind Nullability);
1667 /// Apply the 'Type:' annotation to the specified declaration
1668 void ApplyAPINotesType(Decl *D, StringRef TypeString);
1669
1670 /// Diagnose exact API notes selectors that were not matched by any
1671 /// declaration processed in this translation unit.
1673
1674 /// Whether APINotes should be gathered for all applicable Swift language
1675 /// versions, without being applied. Leaving clients of the current module
1676 /// to select and apply the correct version.
1678 return APINotes.captureVersionIndependentSwift();
1679 }
1680 ///@}
1681
1682 //
1683 //
1684 // -------------------------------------------------------------------------
1685 //
1686 //
1687
1688 /// \name C++ Access Control
1689 /// Implementations are in SemaAccess.cpp
1690 ///@{
1691
1692public:
1699
1700 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1701 /// Returns true on error (when the previous member decl access specifier
1702 /// is different from the new member decl access specifier).
1703 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1704 NamedDecl *PrevMemberDecl,
1705 AccessSpecifier LexicalAS);
1706
1707 /// Perform access-control checking on a previously-unresolved member
1708 /// access which has now been resolved to a member.
1710 DeclAccessPair FoundDecl);
1712 DeclAccessPair FoundDecl);
1713
1714 /// Checks access to an overloaded operator new or delete.
1716 SourceRange PlacementRange,
1717 CXXRecordDecl *NamingClass,
1718 DeclAccessPair FoundDecl,
1719 bool Diagnose = true);
1720
1721 /// Checks access to a constructor.
1723 DeclAccessPair FoundDecl,
1724 const InitializedEntity &Entity,
1725 bool IsCopyBindingRefToTemp = false);
1726
1727 /// Checks access to a constructor.
1729 DeclAccessPair FoundDecl,
1730 const InitializedEntity &Entity,
1731 const PartialDiagnostic &PDiag);
1733 CXXDestructorDecl *Dtor,
1734 const PartialDiagnostic &PDiag,
1735 QualType objectType = QualType());
1736
1737 /// Checks access to the target of a friend declaration.
1739
1740 /// Checks access to a member.
1742 CXXRecordDecl *NamingClass,
1744
1745 /// Checks implicit access to a member in a structured binding.
1748 CXXRecordDecl *DecomposedClass,
1749 DeclAccessPair Field);
1751 const SourceRange &,
1752 DeclAccessPair FoundDecl);
1753
1754 /// Checks access to an overloaded member operator, including
1755 /// conversion operators.
1757 Expr *ArgExpr,
1758 DeclAccessPair FoundDecl);
1760 ArrayRef<Expr *> ArgExprs,
1761 DeclAccessPair FoundDecl);
1763 DeclAccessPair FoundDecl);
1764
1765 /// Checks access for a hierarchy conversion.
1766 ///
1767 /// \param ForceCheck true if this check should be performed even if access
1768 /// control is disabled; some things rely on this for semantics
1769 /// \param ForceUnprivileged true if this check should proceed as if the
1770 /// context had no special privileges
1772 QualType Derived, const CXXBasePath &Path,
1773 unsigned DiagID, bool ForceCheck = false,
1774 bool ForceUnprivileged = false);
1775
1777 SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1778 const CXXBasePath &Path, unsigned DiagID,
1779 llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1780 bool ForceCheck = false, bool ForceUnprivileged = false);
1781
1782 /// Checks access to all the declarations in the given result set.
1783 void CheckLookupAccess(const LookupResult &R);
1784
1785 /// Checks access to Target from the given class. The check will take access
1786 /// specifiers into account, but no member access expressions and such.
1787 ///
1788 /// \param Target the declaration to check if it can be accessed
1789 /// \param NamingClass the class in which the lookup was started.
1790 /// \param BaseType type of the left side of member access expression.
1791 /// \p BaseType and \p NamingClass are used for C++ access control.
1792 /// Depending on the lookup case, they should be set to the following:
1793 /// - lhs.target (member access without a qualifier):
1794 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1795 /// - lhs.X::target (member access with a qualifier):
1796 /// BaseType is the type of 'lhs', NamingClass is 'X'
1797 /// - X::target (qualified lookup without member access):
1798 /// BaseType is null, NamingClass is 'X'.
1799 /// - target (unqualified lookup).
1800 /// BaseType is null, NamingClass is the parent class of 'target'.
1801 /// \return true if the Target is accessible from the Class, false otherwise.
1802 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1803 QualType BaseType);
1804
1805 /// Is the given member accessible for the purposes of deciding whether to
1806 /// define a special member function as deleted?
1808 DeclAccessPair Found, QualType ObjectType,
1809 SourceLocation Loc,
1810 const PartialDiagnostic &Diag);
1813 QualType ObjectType) {
1814 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1815 SourceLocation(), PDiag());
1816 }
1817
1819 const DependentDiagnostic &DD,
1820 const MultiLevelTemplateArgumentList &TemplateArgs);
1822
1823 ///@}
1824
1825 //
1826 //
1827 // -------------------------------------------------------------------------
1828 //
1829 //
1830
1831 /// \name Attributes
1832 /// Implementations are in SemaAttr.cpp
1833 ///@{
1834
1835public:
1836 /// Controls member pointer representation format under the MS ABI.
1839
1840 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1841
1842 /// Source location for newly created implicit MSInheritanceAttrs
1844
1850
1856
1858 PSK_Reset = 0x0, // #pragma ()
1859 PSK_Set = 0x1, // #pragma (value)
1860 PSK_Push = 0x2, // #pragma (push[, id])
1861 PSK_Pop = 0x4, // #pragma (pop[, id])
1862 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1863 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1864 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1865 };
1866
1872
1873 // #pragma pack and align.
1875 public:
1876 // `Native` represents default align mode, which may vary based on the
1877 // platform.
1878 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1879
1880 // #pragma pack info constructor
1881 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1882 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1883 assert(Num == PackNumber && "The pack number has been truncated.");
1884 }
1885
1886 // #pragma align info constructor
1888 : PackAttr(false), AlignMode(M),
1889 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1890
1891 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1892
1894
1895 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1896 // integer encoding for it. This should only be passed to
1897 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1899 std::uint32_t Encoding{};
1900 if (Info.IsXLStack())
1901 Encoding |= IsXLMask;
1902
1903 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1904
1905 if (Info.IsPackAttr())
1906 Encoding |= PackAttrMask;
1907
1908 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1909
1910 return Encoding;
1911 }
1912
1913 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1914 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1916 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1917 int PackNumber = (Encoding & PackNumMask) >> 4;
1918
1919 if (Encoding & PackAttrMask)
1920 return AlignPackInfo(M, PackNumber, IsXL);
1921
1922 return AlignPackInfo(M, IsXL);
1923 }
1924
1925 bool IsPackAttr() const { return PackAttr; }
1926
1927 bool IsAlignAttr() const { return !PackAttr; }
1928
1929 Mode getAlignMode() const { return AlignMode; }
1930
1931 unsigned getPackNumber() const { return PackNumber; }
1932
1933 bool IsPackSet() const {
1934 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1935 // attriute on a decl.
1936 return PackNumber != UninitPackVal && PackNumber != 0;
1937 }
1938
1939 bool IsXLStack() const { return XLStack; }
1940
1941 bool operator==(const AlignPackInfo &Info) const {
1942 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
1943 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
1944 Info.XLStack);
1945 }
1946
1947 bool operator!=(const AlignPackInfo &Info) const {
1948 return !(*this == Info);
1949 }
1950
1951 private:
1952 /// \brief True if this is a pragma pack attribute,
1953 /// not a pragma align attribute.
1954 bool PackAttr;
1955
1956 /// \brief The alignment mode that is in effect.
1957 Mode AlignMode;
1958
1959 /// \brief The pack number of the stack.
1960 unsigned char PackNumber;
1961
1962 /// \brief True if it is a XL #pragma align/pack stack.
1963 bool XLStack;
1964
1965 /// \brief Uninitialized pack value.
1966 static constexpr unsigned char UninitPackVal = -1;
1967
1968 // Masks to encode and decode an AlignPackInfo.
1969 static constexpr uint32_t IsXLMask{0x0000'0001};
1970 static constexpr uint32_t AlignModeMask{0x0000'0006};
1971 static constexpr uint32_t PackAttrMask{0x00000'0008};
1972 static constexpr uint32_t PackNumMask{0x0000'01F0};
1973 };
1974
1975 template <typename ValueType> struct PragmaStack {
1987
1988 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
1989 llvm::StringRef StackSlotLabel, ValueType Value) {
1990 if (Action == PSK_Reset) {
1992 CurrentPragmaLocation = PragmaLocation;
1993 return;
1994 }
1995 if (Action & PSK_Push)
1996 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
1997 PragmaLocation);
1998 else if (Action & PSK_Pop) {
1999 if (!StackSlotLabel.empty()) {
2000 // If we've got a label, try to find it and jump there.
2001 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
2002 return x.StackSlotLabel == StackSlotLabel;
2003 });
2004 // If we found the label so pop from there.
2005 if (I != Stack.rend()) {
2006 CurrentValue = I->Value;
2007 CurrentPragmaLocation = I->PragmaLocation;
2008 Stack.erase(std::prev(I.base()), Stack.end());
2009 }
2010 } else if (!Stack.empty()) {
2011 // We do not have a label, just pop the last entry.
2012 CurrentValue = Stack.back().Value;
2013 CurrentPragmaLocation = Stack.back().PragmaLocation;
2014 Stack.pop_back();
2015 }
2016 }
2017 if (Action & PSK_Set) {
2019 CurrentPragmaLocation = PragmaLocation;
2020 }
2021 }
2022
2023 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
2024 // method body to restore the stacks on exit, so it works like this:
2025 //
2026 // struct S {
2027 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
2028 // void Method {}
2029 // #pragma <name>(pop, InternalPragmaSlot)
2030 // };
2031 //
2032 // It works even with #pragma vtordisp, although MSVC doesn't support
2033 // #pragma vtordisp(push [, id], n)
2034 // syntax.
2035 //
2036 // Push / pop a named sentinel slot.
2037 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
2038 assert((Action == PSK_Push || Action == PSK_Pop) &&
2039 "Can only push / pop #pragma stack sentinels!");
2040 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
2041 }
2042
2043 // Constructors.
2044 explicit PragmaStack(const ValueType &Default)
2046
2047 bool hasValue() const { return CurrentValue != DefaultValue; }
2048
2050 ValueType DefaultValue; // Value used for PSK_Reset action.
2051 ValueType CurrentValue;
2053 };
2054 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2055 // we shouldn't do so if they're in a module).
2056
2057 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2058 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
2059 ///
2060 /// 0: Suppress all vtordisps
2061 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2062 /// structors
2063 /// 2: Always insert vtordisps to support RTTI on partially constructed
2064 /// objects
2067 // The current #pragma align/pack values and locations at each #include.
2074 // Segment #pragmas.
2079
2080 // #pragma strict_gs_check.
2082
2083 // This stack tracks the current state of Sema.CurFPFeatures.
2086 FPOptionsOverride result;
2087 if (!FpPragmaStack.hasValue()) {
2088 result = FPOptionsOverride();
2089 } else {
2090 result = FpPragmaStack.CurrentValue;
2091 }
2092 return result;
2093 }
2094
2101
2102 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2103 // Actions should be performed only if we enter / exit a C++ method body.
2105 public:
2106 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2111
2112 private:
2113 Sema &S;
2114 StringRef SlotLabel;
2115 bool ShouldAct;
2116 };
2117
2118 /// Last section used with #pragma init_seg.
2121
2122 /// Sections used with #pragma alloc_text.
2123 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2124
2125 /// VisContext - Manages the stack for \#pragma GCC visibility.
2126 void *VisContext; // Really a "PragmaVisStack*"
2127
2128 /// This an attribute introduced by \#pragma clang attribute.
2135
2136 /// A push'd group of PragmaAttributeEntries.
2138 /// The location of the push attribute.
2140 /// The namespace of this push group.
2143 };
2144
2146
2147 /// The declaration that is currently receiving an attribute from the
2148 /// #pragma attribute stack.
2150
2151 /// This represents the last location of a "#pragma clang optimize off"
2152 /// directive if such a directive has not been closed by an "on" yet. If
2153 /// optimizations are currently "on", this is set to an invalid location.
2155
2156 /// Get the location for the currently active "\#pragma clang optimize
2157 /// off". If this location is invalid, then the state of the pragma is "on".
2161
2162 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2163 /// whether the optimizations in the list passed to the pragma should be
2164 /// turned off or on. This boolean is true by default because command line
2165 /// options are honored when `#pragma optimize("", on)`.
2166 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2168
2169 /// Set of no-builtin functions listed by \#pragma function.
2171
2172 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2173 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2175
2176 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2178
2179 /// Add gsl::Pointer attribute to std::container::iterator
2180 /// \param ND The declaration that introduces the name
2181 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2182 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2183
2184 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2186
2187 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2189
2190 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2192
2193 /// Add [[gsl::Pointer]] attributes for std:: types.
2195
2196 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2197 StringRef ParamName);
2198 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2199 // can be the name of a function parameter, we need to parse the function
2200 // declaration and rest of the parameters before processesing 'X'. Therefore
2201 // do this lazily instead of processing while parsing the annotation itself.
2203
2204 /// Add _Nullable attributes for std:: types.
2206
2207 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2210 PragmaClangSectionKind SecKind,
2211 StringRef SecName);
2212
2213 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2215 SourceLocation PragmaLoc);
2216
2217 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2218 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2219 StringRef SlotLabel, Expr *Alignment);
2220
2221 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2222 /// (unless they are value dependent or type dependent). Returns false
2223 /// and emits a diagnostic if one or more of the arguments could not be
2224 /// folded into a constant.
2227
2232
2234 SourceLocation IncludeLoc);
2236
2237 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2239
2240 /// ActOnPragmaMSComment - Called on well formed
2241 /// \#pragma comment(kind, "arg").
2243 StringRef Arg);
2244
2245 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2246 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2247 StringRef Value);
2248
2249 /// Are precise floating point semantics currently enabled?
2251 return !CurFPFeatures.getAllowFPReassociate() &&
2252 !CurFPFeatures.getNoSignedZero() &&
2253 !CurFPFeatures.getAllowReciprocal() &&
2254 !CurFPFeatures.getAllowApproxFunc();
2255 }
2256
2259
2260 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2261 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2263
2264 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2265 /// pointers_to_members(representation method[, general purpose
2266 /// representation]).
2269 SourceLocation PragmaLoc);
2270
2271 /// Called on well formed \#pragma vtordisp().
2272 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2274
2275 bool UnifySection(StringRef SectionName, int SectionFlags,
2276 NamedDecl *TheDecl);
2277 bool UnifySection(StringRef SectionName, int SectionFlags,
2278 SourceLocation PragmaSectionLocation);
2279
2280 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2281 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2282 PragmaMsStackAction Action,
2283 llvm::StringRef StackSlotLabel,
2284 StringLiteral *SegmentName, llvm::StringRef PragmaName);
2285
2286 /// Called on well formed \#pragma section().
2287 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2288 StringLiteral *SegmentName);
2289
2290 /// Called on well-formed \#pragma init_seg().
2291 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2292 StringLiteral *SegmentName);
2293
2294 /// Called on well-formed \#pragma alloc_text().
2296 SourceLocation PragmaLocation, StringRef Section,
2297 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2298 &Functions);
2299
2300 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2301 /// strict_gs_check.
2303 PragmaMsStackAction Action,
2304 bool Value);
2305
2306 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2307 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2308 SourceLocation PragmaLoc);
2309
2311 SourceLocation PragmaLoc,
2314 const IdentifierInfo *Namespace);
2315
2316 /// Called on well-formed '\#pragma clang attribute pop'.
2318 const IdentifierInfo *Namespace);
2319
2320 /// Adds the attributes that have been specified using the
2321 /// '\#pragma clang attribute push' directives to the given declaration.
2322 void AddPragmaAttributes(Scope *S, Decl *D);
2323
2325 llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
2327 return [this](SourceLocation Loc, PartialDiagnostic PD) {
2328 // This bypasses a lot of the filters in the diag engine, as it's
2329 // to be used to attach notes to diagnostics which have already
2330 // been filtered through.
2331 DiagnosticBuilder Builder(Diags.Report(Loc, PD.getDiagID()));
2332 PD.Emit(Builder);
2333 };
2334 }
2335
2341
2343
2344 /// Called on well formed \#pragma clang optimize.
2345 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2346
2347 /// #pragma optimize("[optimization-list]", on | off).
2348 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2349
2350 /// Call on well formed \#pragma function.
2351 void
2353 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2354
2356 SourceLocation NameLoc,
2357 Scope *curScope);
2358
2359 /// Information from a C++ #pragma export, for a symbol that we
2360 /// haven't seen the declaration for yet.
2365
2366 llvm::DenseMap<IdentifierInfo *, PendingPragmaInfo> PendingExportedNames;
2367
2368 /// ActonPragmaExport - called on well-formed '\#pragma export'.
2369 void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc,
2370 Scope *curScope);
2371
2372 /// Only called on function definitions; if there is a pragma in scope
2373 /// with the effect of a range-based optnone, consider marking the function
2374 /// with attribute optnone.
2376
2377 /// Only called on function definitions; if there is a `#pragma alloc_text`
2378 /// that decides which code section the function should be in, add
2379 /// attribute section to the function.
2381
2382 /// Adds the 'optnone' attribute to the function declaration if there
2383 /// are no conflicts; Loc represents the location causing the 'optnone'
2384 /// attribute to be added (usually because of a pragma).
2386
2387 /// Only called on function definitions; if there is a MSVC #pragma optimize
2388 /// in scope, consider changing the function's attributes based on the
2389 /// optimization list passed to the pragma.
2391
2392 /// Only called on function definitions; if there is a pragma in scope
2393 /// with the effect of a range-based no_builtin, consider marking the function
2394 /// with attribute no_builtin.
2396
2397 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2398 /// add an appropriate visibility attribute.
2400
2401 /// FreeVisContext - Deallocate and null out VisContext.
2402 void FreeVisContext();
2403
2404 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2405 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2406 SourceLocation PragmaLoc);
2407
2408 /// ActOnPragmaFPContract - Called on well formed
2409 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2410 /// \#pragma clang fp contract
2412
2413 /// Called on well formed
2414 /// \#pragma clang fp reassociate
2415 /// or
2416 /// \#pragma clang fp reciprocal
2418 bool IsEnabled);
2419
2420 /// ActOnPragmaFenvAccess - Called on well formed
2421 /// \#pragma STDC FENV_ACCESS
2422 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2423
2424 /// ActOnPragmaCXLimitedRange - Called on well formed
2425 /// \#pragma STDC CX_LIMITED_RANGE
2428
2429 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2432
2433 /// Called to set constant rounding mode for floating point operations.
2434 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2435
2436 /// Called to set exception behavior for floating point operations.
2438
2439 /// PushNamespaceVisibilityAttr - Note that we've entered a
2440 /// namespace with a visibility attribute.
2441 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2442 SourceLocation Loc);
2443
2444 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2445 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2446 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2447
2448 /// Handles semantic checking for features that are common to all attributes,
2449 /// such as checking whether a parameter was properly specified, or the
2450 /// correct number of arguments were passed, etc. Returns true if the
2451 /// attribute has been diagnosed.
2452 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2453 bool SkipArgCountCheck = false);
2454 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2455 bool SkipArgCountCheck = false);
2456
2457 ///@}
2458
2459 //
2460 //
2461 // -------------------------------------------------------------------------
2462 //
2463 //
2464
2465 /// \name Availability Attribute Handling
2466 /// Implementations are in SemaAvailability.cpp
2467 ///@{
2468
2469public:
2470 /// Issue any -Wunguarded-availability warnings in \c FD
2472
2474
2475 /// Retrieve the current function, if any, that should be analyzed for
2476 /// potential availability violations.
2478
2480 const ObjCInterfaceDecl *UnknownObjCClass,
2481 bool ObjCPropertyAccess,
2482 bool AvoidPartialAvailabilityChecks,
2483 ObjCInterfaceDecl *ClassReceiver);
2484
2486
2487 std::pair<AvailabilityResult, const NamedDecl *>
2488 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2489 ObjCInterfaceDecl *ClassReceiver);
2490 ///@}
2491
2492 //
2493 //
2494 // -------------------------------------------------------------------------
2495 //
2496 //
2497
2498 /// \name Bounds Safety
2499 /// Implementations are in SemaBoundsSafety.cpp
2500 ///@{
2501public:
2502 /// Check if applying the specified attribute variant from the "counted by"
2503 /// family of attributes to FieldDecl \p FD is semantically valid. If
2504 /// semantically invalid diagnostics will be emitted explaining the problems.
2505 ///
2506 /// \param FD The FieldDecl to apply the attribute to
2507 /// \param E The count expression on the attribute
2508 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2509 /// attributes. If the false the attribute is from
2510 /// "counted_by" family of attributes.
2511 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2512 /// of attributes. If false the attribute does not have the
2513 /// suffix.
2514 ///
2515 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2516 /// \p CountInBytes and \p OrNull both being true indicates the
2517 /// `counted_by_or_null` attribute.
2518 ///
2519 /// \returns false iff semantically valid.
2520 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2521 bool OrNull);
2522
2523 /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2524 /// `__counted_by_or_null` pointer type \param LHSTy.
2525 ///
2526 /// \param LHSTy The type being assigned to. Checks will only be performed if
2527 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2528 /// \param RHSExpr The expression being assigned from.
2529 /// \param Action The type assignment being performed
2530 /// \param Loc The SourceLocation to use for error diagnostics
2531 /// \param Assignee The ValueDecl being assigned. This is used to compute
2532 /// the name of the assignee. If the assignee isn't known this can
2533 /// be set to nullptr.
2534 /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2535 /// Assignee to compute the name of the assignee use the fully
2536 /// qualified name, otherwise use the unqualified name.
2537 ///
2538 /// \returns True iff no diagnostic where emitted, false otherwise.
2540 QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2541 SourceLocation Loc, const ValueDecl *Assignee,
2542 bool ShowFullyQualifiedAssigneeName);
2543
2544 /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2545 /// pointer.
2546 ///
2547 /// \param Entity The entity being initialized
2548 /// \param Kind The kind of initialization being performed
2549 /// \param Action The type assignment being performed
2550 /// \param LHSTy The type being assigned to. Checks will only be performed if
2551 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2552 /// \param RHSExpr The expression being used for initialization.
2553 ///
2554 /// \returns True iff no diagnostic where emitted, false otherwise.
2556 const InitializationKind &Kind,
2557 AssignmentAction Action,
2558 QualType LHSType, Expr *RHSExpr);
2559
2560 /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2561 /// or counted_by_or_null pointers in \param E.
2562 ///
2563 /// \param E the expression to check
2564 ///
2565 /// \returns True iff no diagnostic where emitted, false otherwise.
2567 ///@}
2568
2569 //
2570 //
2571 // -------------------------------------------------------------------------
2572 //
2573 //
2574
2575 /// \name Casts
2576 /// Implementations are in SemaCast.cpp
2577 ///@{
2578
2579public:
2585
2586 /// ActOnCXXNamedCast - Parse
2587 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2589 SourceLocation LAngleBracketLoc, Declarator &D,
2590 SourceLocation RAngleBracketLoc,
2591 SourceLocation LParenLoc, Expr *E,
2592 SourceLocation RParenLoc);
2593
2595 TypeSourceInfo *Ty, Expr *E,
2596 SourceRange AngleBrackets, SourceRange Parens);
2597
2599 ExprResult Operand,
2600 SourceLocation RParenLoc);
2601
2603 Expr *Operand, SourceLocation RParenLoc);
2604
2605 // Checks that reinterpret casts don't have undefined behavior.
2606 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2607 bool IsDereference, SourceRange Range);
2608
2609 // Checks that the vector type should be initialized from a scalar
2610 // by splatting the value rather than populating a single element.
2611 // This is the case for AltiVecVector types as well as with
2612 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2613 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2614
2615 // Checks if the -faltivec-src-compat=gcc option is specified.
2616 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2617 // treated the same way as they are when trying to initialize
2618 // these vectors on gcc (an error is emitted).
2620 QualType SrcTy);
2621
2623 SourceLocation RParenLoc, Expr *Op);
2624
2626 SourceLocation LParenLoc,
2627 Expr *CastExpr,
2628 SourceLocation RParenLoc);
2629
2630 ///@}
2631
2632 //
2633 //
2634 // -------------------------------------------------------------------------
2635 //
2636 //
2637
2638 /// \name Extra Semantic Checking
2639 /// Implementations are in SemaChecking.cpp
2640 ///@{
2641
2642public:
2643 /// Used to change context to isConstantEvaluated without pushing a heavy
2644 /// ExpressionEvaluationContextRecord object.
2646
2651
2653 unsigned ByteNo) const;
2654
2656 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2657 FAPK_Variadic, // values to format are passed as variadic arguments
2658 FAPK_VAList, // values to format are passed in a va_list
2659 FAPK_Elsewhere, // values to format are not passed to this function
2660 };
2661
2662 // Used to grab the relevant information from a FormatAttr and a
2663 // FunctionDeclaration.
2669
2670 /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2671 /// populate the FormatStringInfo parameter with the attribute's correct
2672 /// format_idx and firstDataArg. Returns true when the format fits the
2673 /// function and the FormatStringInfo has been populated.
2674 static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2675 unsigned FirstArg, FormatStringInfo *FSI);
2676 static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2677 bool HasImplicitThisParam, bool IsVariadic,
2678 FormatStringInfo *FSI);
2679
2680 // Used by C++ template instantiation.
2682
2683 /// ConvertVectorExpr - Handle __builtin_convertvector
2685 SourceLocation BuiltinLoc,
2686 SourceLocation RParenLoc);
2687
2688 static StringRef GetFormatStringTypeName(FormatStringType FST);
2689 static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2690 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2691 static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2692
2693 bool FormatStringHasSArg(const StringLiteral *FExpr);
2694
2695 /// Check for comparisons of floating-point values using == and !=. Issue a
2696 /// warning if the comparison is not likely to do what the programmer
2697 /// intended.
2698 void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2699 const Expr *RHS, BinaryOperatorKind Opcode);
2700
2701 /// Register a magic integral constant to be used as a type tag.
2702 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2703 uint64_t MagicValue, QualType Type,
2704 bool LayoutCompatible, bool MustBeNull);
2705
2708
2712
2714
2715 /// If true, \c Type should be compared with other expression's types for
2716 /// layout-compatibility.
2717 LLVM_PREFERRED_TYPE(bool)
2719 LLVM_PREFERRED_TYPE(bool)
2720 unsigned MustBeNull : 1;
2721 };
2722
2723 /// A pair of ArgumentKind identifier and magic value. This uniquely
2724 /// identifies the magic value.
2725 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2726
2727 /// Diagnoses the current set of gathered accesses. This happens at the end of
2728 /// each expression evaluation context. Diagnostics are emitted only for
2729 /// accesses gathered in the current evaluation context.
2731
2732 /// This function checks if the expression is in the sef of potentially
2733 /// misaligned members and it is converted to some pointer type T with lower
2734 /// or equal alignment requirements. If so it removes it. This is used when
2735 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2736 /// void*).
2737 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2738
2739 /// Returns true if `From` is a function or pointer to a function with the
2740 /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2741 /// function without this attribute.
2742 bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2743
2744 /// This function calls Action when it determines that E designates a
2745 /// misaligned member due to the packed attribute. This is used to emit
2746 /// local diagnostics like in reference binding.
2748 Expr *E,
2749 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2750 Action);
2751
2752 enum class AtomicArgumentOrder { API, AST };
2754 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2755 SourceLocation RParenLoc, MultiExprArg Args,
2758
2759 /// Check to see if a given expression could have '.c_str()' called on it.
2760 bool hasCStrMethod(const Expr *E);
2761
2762 /// Diagnose pointers that are always non-null.
2763 /// \param E the expression containing the pointer
2764 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2765 /// compared to a null pointer
2766 /// \param IsEqual True when the comparison is equal to a null pointer
2767 /// \param Range Extra SourceRange to highlight in the diagnostic
2770 bool IsEqual, SourceRange Range);
2771
2772 /// CheckParmsForFunctionDef - Check that the parameters of the given
2773 /// function are appropriate for the definition of a function. This
2774 /// takes care of any checks that cannot be performed on the
2775 /// declaration itself, e.g., that the types of each of the function
2776 /// parameters are complete.
2778 bool CheckParameterNames);
2779
2780 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2781 /// pointer cast increases the alignment requirements.
2782 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2783
2784 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2785 /// to weak/__unsafe_unretained type.
2786 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2787
2788 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2789 /// to weak/__unsafe_unretained expression.
2790 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2791
2792 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2793 /// statement as a \p Body, and it is located on the same line.
2794 ///
2795 /// This helps prevent bugs due to typos, such as:
2796 /// if (condition);
2797 /// do_stuff();
2798 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2799 unsigned DiagID);
2800
2801 /// Warn if a for/while loop statement \p S, which is followed by
2802 /// \p PossibleBody, has a suspicious null statement as a body.
2803 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2804
2805 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2806 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2807 SourceLocation OpLoc);
2808
2809 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2811 const TypeSourceInfo *Derived);
2812
2813 /// CheckFunctionCall - Check a direct function call for various correctness
2814 /// and safety properties not strictly enforced by the C type system.
2815 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2816 const FunctionProtoType *Proto);
2817
2824
2825 /// \param FPOnly restricts the arguments to floating-point types.
2826 std::optional<QualType>
2827 BuiltinVectorMath(CallExpr *TheCall,
2830 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2831
2832 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2833 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2834
2835 /// Handles the checks for format strings, non-POD arguments to vararg
2836 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2837 /// attributes and AArch64 SME attributes.
2838 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2839 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2840 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2841 VariadicCallType CallType);
2842
2843 /// Verify that two format strings (as understood by attribute(format) and
2844 /// attribute(format_matches) are compatible. If they are incompatible,
2845 /// diagnostics are emitted with the assumption that \c
2846 /// AuthoritativeFormatString is correct and
2847 /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2848 /// diagnostics will point to it and a note will refer to \c
2849 /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2850 bool
2852 const StringLiteral *AuthoritativeFormatString,
2853 const StringLiteral *TestedFormatString,
2854 const Expr *FunctionCallArg = nullptr);
2855
2856 /// Verify that one format string (as understood by attribute(format)) is
2857 /// self-consistent; for instance, that it doesn't have multiple positional
2858 /// arguments referring to the same argument in incompatible ways. Diagnose
2859 /// if it isn't.
2861
2862 /// \brief Enforce the bounds of a TCB
2863 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2864 /// directly calls other functions in the same TCB as marked by the
2865 /// enforce_tcb and enforce_tcb_leaf attributes.
2866 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2867 const NamedDecl *Callee);
2868
2869 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2870
2871 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2872 /// TheCall is a constant expression.
2873 bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
2874 llvm::APSInt &Result);
2875
2876 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2877 /// TheCall is a constant expression in the range [Low, High].
2878 bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
2879 int High, bool RangeIsError = true);
2880
2881 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2882 /// TheCall is a constant expression is a multiple of Num..
2883 bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
2884 unsigned Multiple);
2885
2886 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2887 /// constant expression representing a power of 2.
2888 bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum);
2889
2890 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2891 /// a constant expression representing an arbitrary byte value shifted left by
2892 /// a multiple of 8 bits.
2893 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
2894 unsigned ArgBits);
2895
2896 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2897 /// TheCall is a constant expression representing either a shifted byte value,
2898 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2899 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2900 /// Arm MVE intrinsics.
2901 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum,
2902 unsigned ArgBits);
2903
2904 /// Checks that a call expression's argument count is at least the desired
2905 /// number. This is useful when doing custom type-checking on a variadic
2906 /// function. Returns true on error.
2907 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2908
2909 /// Checks that a call expression's argument count is at most the desired
2910 /// number. This is useful when doing custom type-checking on a variadic
2911 /// function. Returns true on error.
2912 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
2913
2914 /// Checks that a call expression's argument count is in the desired range.
2915 /// This is useful when doing custom type-checking on a variadic function.
2916 /// Returns true on error.
2917 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
2918 unsigned MaxArgCount);
2919
2920 /// Checks that a call expression's argument count is the desired number.
2921 /// This is useful when doing custom type-checking. Returns true on error.
2922 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
2923
2924 /// Returns true if the argument consists of one contiguous run of 1s with any
2925 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
2926 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
2927 /// since all 1s are not contiguous.
2928 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2929
2931 bool *ICContext = nullptr,
2932 bool IsListInit = false);
2933
2934 /// Check for overflow behavior type related implicit conversion diagnostics.
2935 /// Returns true if OBT-related diagnostic was issued, false otherwise.
2937 SourceLocation CC);
2938
2939 bool
2944 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
2946
2947private:
2948 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2949 const ArraySubscriptExpr *ASE = nullptr,
2950 bool AllowOnePastEnd = true, bool IndexNegated = false);
2951 void CheckArrayAccess(const Expr *E);
2952
2953 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2954 const FunctionProtoType *Proto);
2955
2956 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2957 /// such as function pointers returned from functions.
2958 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
2959
2960 /// CheckConstructorCall - Check a constructor call for correctness and safety
2961 /// properties not enforced by the C type system.
2962 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
2964 const FunctionProtoType *Proto, SourceLocation Loc);
2965
2966 /// Warn if a pointer or reference argument passed to a function points to an
2967 /// object that is less aligned than the parameter. This can happen when
2968 /// creating a typedef with a lower alignment than the original type and then
2969 /// calling functions defined in terms of the original type.
2970 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
2971 StringRef ParamName, QualType ArgTy, QualType ParamTy);
2972
2973 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
2974
2975 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2976 CallExpr *TheCall);
2977
2978 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2979 CallExpr *TheCall);
2980
2981 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
2982
2983 /// Argument-value fortify checks for libc functions that are not builtins,
2984 /// dispatched by name (e.g. umask). Diagnostics belong to -Wfortify-source.
2985 void checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall);
2986
2987 /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
2988 /// or '__builtin_c23_va_start' for validity. Emit an error and return true
2989 /// on failure; return false on success.
2990 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
2991 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
2992
2993 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2994 /// friends. This is declared to take (...), so we have to check everything.
2995 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
2996
2997 /// BuiltinSemaBuiltinFPClassification - Handle functions like
2998 /// __builtin_isnan and friends. This is declared to take (...), so we have
2999 /// to check everything.
3000 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
3001 unsigned BuiltinID);
3002
3003 /// Perform semantic analysis for a call to __builtin_complex.
3004 bool BuiltinComplex(CallExpr *TheCall);
3005 bool BuiltinOSLogFormat(CallExpr *TheCall);
3006
3007 /// BuiltinPrefetch - Handle __builtin_prefetch.
3008 /// This is declared to take (const void*, ...) and can take two
3009 /// optional constant int args.
3010 bool BuiltinPrefetch(CallExpr *TheCall);
3011
3012 /// Handle __builtin_alloca_with_align. This is declared
3013 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3014 /// than 8.
3015 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
3016
3017 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
3018 bool BuiltinArithmeticFence(CallExpr *TheCall);
3019
3020 /// BuiltinAssume - Handle __assume (MS Extension).
3021 /// __assume does not evaluate its arguments, and should warn if its argument
3022 /// has side effects.
3023 bool BuiltinAssume(CallExpr *TheCall);
3024
3025 /// Handle __builtin_assume_aligned. This is declared
3026 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3027 bool BuiltinAssumeAligned(CallExpr *TheCall);
3028
3029 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3030 /// This checks that the target supports __builtin_longjmp and
3031 /// that val is a constant 1.
3032 bool BuiltinLongjmp(CallExpr *TheCall);
3033
3034 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3035 /// This checks that the target supports __builtin_setjmp.
3036 bool BuiltinSetjmp(CallExpr *TheCall);
3037
3038 /// We have a call to a function like __sync_fetch_and_add, which is an
3039 /// overloaded function based on the pointer type of its first argument.
3040 /// The main BuildCallExpr routines have already promoted the types of
3041 /// arguments because all of these calls are prototyped as void(...).
3042 ///
3043 /// This function goes through and does final semantic checking for these
3044 /// builtins, as well as generating any warnings.
3045 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
3046
3047 /// BuiltinNontemporalOverloaded - We have a call to
3048 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3049 /// overloaded function based on the pointer type of its last argument.
3050 ///
3051 /// This function goes through and does final semantic checking for these
3052 /// builtins.
3053 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
3054 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
3056
3057 /// \param FPOnly restricts the arguments to floating-point types.
3058 bool BuiltinElementwiseMath(CallExpr *TheCall,
3061 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
3062
3063 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
3064
3065 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
3067 bool BuiltinCountedByRef(CallExpr *TheCall);
3068
3069 // Matrix builtin handling.
3070 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
3071 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
3072 ExprResult CallResult);
3073 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
3074 ExprResult CallResult);
3075
3076 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3077 /// functions) for correct use of format strings.
3078 /// Returns true if a format string has been fully checked.
3079 bool CheckFormatArguments(const FormatAttr *Format,
3080 ArrayRef<const Expr *> Args, bool IsCXXMember,
3081 VariadicCallType CallType, SourceLocation Loc,
3082 SourceRange Range,
3083 llvm::SmallBitVector &CheckedVarArgs);
3084 bool CheckFormatString(const FormatMatchesAttr *Format,
3085 ArrayRef<const Expr *> Args, bool IsCXXMember,
3086 VariadicCallType CallType, SourceLocation Loc,
3087 SourceRange Range,
3088 llvm::SmallBitVector &CheckedVarArgs);
3089 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3090 FormatArgumentPassingKind FAPK,
3091 StringLiteral *ReferenceFormatString,
3092 unsigned format_idx, unsigned firstDataArg,
3094 SourceLocation Loc, SourceRange range,
3095 llvm::SmallBitVector &CheckedVarArgs);
3096
3097 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3098
3099 /// Warn when using the wrong abs() function.
3100 void CheckAbsoluteValueFunction(const CallExpr *Call,
3101 const FunctionDecl *FDecl);
3102
3103 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3104
3105 /// Check for dangerous or invalid arguments to memset().
3106 ///
3107 /// This issues warnings on known problematic, dangerous or unspecified
3108 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3109 /// function calls.
3110 ///
3111 /// \param Call The call expression to diagnose.
3112 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3113 IdentifierInfo *FnName);
3114
3115 bool CheckSizeofMemaccessArgument(const Expr *SizeOfArg, const Expr *Dest,
3116 IdentifierInfo *FnName);
3117 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3118 // be the size of the source, instead of the destination.
3119 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3120
3121 // Warn on anti-patterns as the 'size' argument to strncat.
3122 // The correct size argument should look like following:
3123 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3124 void CheckStrncatArguments(const CallExpr *Call,
3125 const IdentifierInfo *FnName);
3126
3127 /// Alerts the user that they are attempting to free a non-malloc'd object.
3128 void CheckFreeArguments(const CallExpr *E);
3129
3130 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3131 SourceLocation ReturnLoc, bool isObjCMethod = false,
3132 const AttrVec *Attrs = nullptr,
3133 const FunctionDecl *FD = nullptr);
3134
3135 /// Diagnoses "dangerous" implicit conversions within the given
3136 /// expression (which is a full expression). Implements -Wconversion
3137 /// and -Wsign-compare.
3138 ///
3139 /// \param CC the "context" location of the implicit conversion, i.e.
3140 /// the most location of the syntactic entity requiring the implicit
3141 /// conversion
3142 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3143
3144 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3145 /// Input argument E is a logical expression.
3147
3148 /// Diagnose when expression is an integer constant expression and its
3149 /// evaluation results in integer overflow
3150 void CheckForIntOverflow(const Expr *E);
3151 void CheckUnsequencedOperations(const Expr *E);
3152
3153 /// Perform semantic checks on a completed expression. This will either
3154 /// be a full-expression or a default argument expression.
3155 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3156 bool IsConstexpr = false);
3157
3158 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3159 Expr *Init);
3160
3161 /// A map from magic value to type information.
3162 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3163 TypeTagForDatatypeMagicValues;
3164
3165 /// Peform checks on a call of a function with argument_with_type_tag
3166 /// or pointer_with_type_tag attributes.
3167 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3168 const ArrayRef<const Expr *> ExprArgs,
3169 SourceLocation CallSiteLoc);
3170
3171 /// Check if we are taking the address of a packed field
3172 /// as this may be a problem if the pointer value is dereferenced.
3173 void CheckAddressOfPackedMember(Expr *rhs);
3174
3175 /// Helper class that collects misaligned member designations and
3176 /// their location info for delayed diagnostics.
3177 struct MisalignedMember {
3178 Expr *E;
3179 RecordDecl *RD;
3180 ValueDecl *MD;
3181 CharUnits Alignment;
3182
3183 MisalignedMember() : E(), RD(), MD() {}
3184 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3185 CharUnits Alignment)
3186 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
3187 explicit MisalignedMember(Expr *E)
3188 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3189
3190 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3191 };
3192
3193 /// Adds an expression to the set of gathered misaligned members.
3194 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3195 CharUnits Alignment);
3196 ///@}
3197
3198 //
3199 //
3200 // -------------------------------------------------------------------------
3201 //
3202 //
3203
3204 /// \name C++ Coroutines
3205 /// Implementations are in SemaCoroutine.cpp
3206 ///@{
3207
3208public:
3209 /// The C++ "std::coroutine_traits" template, which is defined in
3210 /// <coroutine_traits>
3212
3214 StringRef Keyword);
3218
3221 UnresolvedLookupExpr *Lookup);
3223 Expr *Awaiter, bool IsImplicit = false);
3225 UnresolvedLookupExpr *Lookup);
3228 bool IsImplicit = false);
3233
3234 // As a clang extension, enforces that a non-coroutine function must be marked
3235 // with [[clang::coro_wrapper]] if it returns a type marked with
3236 // [[clang::coro_return_type]].
3237 // Expects that FD is not a coroutine.
3239 /// Lookup 'coroutine_traits' in std namespace and std::experimental
3240 /// namespace. The namespace found is recorded in Namespace.
3242 SourceLocation FuncLoc);
3243 /// Check that the expression co_await promise.final_suspend() shall not be
3244 /// potentially-throwing.
3245 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3246
3247 ///@}
3248
3249 //
3250 //
3251 // -------------------------------------------------------------------------
3252 //
3253 //
3254
3255 /// \name C++ Scope Specifiers
3256 /// Implementations are in SemaCXXScopeSpec.cpp
3257 ///@{
3258
3259public:
3260 // Marks SS invalid if it represents an incomplete type.
3262 // Complete an enum decl, maybe without a scope spec.
3264 CXXScopeSpec *SS = nullptr);
3265
3266 /// Compute the DeclContext that is associated with the given type.
3267 ///
3268 /// \param T the type for which we are attempting to find a DeclContext.
3269 ///
3270 /// \returns the declaration context represented by the type T,
3271 /// or NULL if the declaration context cannot be computed (e.g., because it is
3272 /// dependent and not the current instantiation).
3274
3275 /// Compute the DeclContext that is associated with the given
3276 /// scope specifier.
3277 ///
3278 /// \param SS the C++ scope specifier as it appears in the source
3279 ///
3280 /// \param EnteringContext when true, we will be entering the context of
3281 /// this scope specifier, so we can retrieve the declaration context of a
3282 /// class template or class template partial specialization even if it is
3283 /// not the current instantiation.
3284 ///
3285 /// \returns the declaration context represented by the scope specifier @p SS,
3286 /// or NULL if the declaration context cannot be computed (e.g., because it is
3287 /// dependent and not the current instantiation).
3289 bool EnteringContext = false);
3291
3292 /// If the given nested name specifier refers to the current
3293 /// instantiation, return the declaration that corresponds to that
3294 /// current instantiation (C++0x [temp.dep.type]p1).
3295 ///
3296 /// \param NNS a dependent nested name specifier.
3298
3299 /// The parser has parsed a global nested-name-specifier '::'.
3300 ///
3301 /// \param CCLoc The location of the '::'.
3302 ///
3303 /// \param SS The nested-name-specifier, which will be updated in-place
3304 /// to reflect the parsed nested-name-specifier.
3305 ///
3306 /// \returns true if an error occurred, false otherwise.
3308
3309 /// The parser has parsed a '__super' nested-name-specifier.
3310 ///
3311 /// \param SuperLoc The location of the '__super' keyword.
3312 ///
3313 /// \param ColonColonLoc The location of the '::'.
3314 ///
3315 /// \param SS The nested-name-specifier, which will be updated in-place
3316 /// to reflect the parsed nested-name-specifier.
3317 ///
3318 /// \returns true if an error occurred, false otherwise.
3320 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3321
3322 /// Determines whether the given declaration is an valid acceptable
3323 /// result for name lookup of a nested-name-specifier.
3324 /// \param SD Declaration checked for nested-name-specifier.
3325 /// \param IsExtension If not null and the declaration is accepted as an
3326 /// extension, the pointed variable is assigned true.
3328 bool *CanCorrect = nullptr);
3329
3330 /// If the given nested-name-specifier begins with a bare identifier
3331 /// (e.g., Base::), perform name lookup for that identifier as a
3332 /// nested-name-specifier within the given scope, and return the result of
3333 /// that name lookup.
3335
3336 /// Keeps information about an identifier in a nested-name-spec.
3337 ///
3339 /// The type of the object, if we're parsing nested-name-specifier in
3340 /// a member access expression.
3342
3343 /// The identifier preceding the '::'.
3345
3346 /// The location of the identifier.
3348
3349 /// The location of the '::'.
3351
3352 /// Creates info object for the most typical case.
3354 SourceLocation ColonColonLoc,
3357 CCLoc(ColonColonLoc) {}
3358
3360 SourceLocation ColonColonLoc, QualType ObjectType)
3362 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3363 };
3364
3365 /// Build a new nested-name-specifier for "identifier::", as described
3366 /// by ActOnCXXNestedNameSpecifier.
3367 ///
3368 /// \param S Scope in which the nested-name-specifier occurs.
3369 /// \param IdInfo Parser information about an identifier in the
3370 /// nested-name-spec.
3371 /// \param EnteringContext If true, enter the context specified by the
3372 /// nested-name-specifier.
3373 /// \param SS Optional nested name specifier preceding the identifier.
3374 /// \param ScopeLookupResult Provides the result of name lookup within the
3375 /// scope of the nested-name-specifier that was computed at template
3376 /// definition time.
3377 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3378 /// error recovery and what kind of recovery is performed.
3379 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3380 /// are allowed. The bool value pointed by this parameter is set to
3381 /// 'true' if the identifier is treated as if it was followed by ':',
3382 /// not '::'.
3383 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3384 ///
3385 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3386 /// that it contains an extra parameter \p ScopeLookupResult, which provides
3387 /// the result of name lookup within the scope of the nested-name-specifier
3388 /// that was computed at template definition time.
3389 ///
3390 /// If ErrorRecoveryLookup is true, then this call is used to improve error
3391 /// recovery. This means that it should not emit diagnostics, it should
3392 /// just return true on failure. It also means it should only return a valid
3393 /// scope if it *knows* that the result is correct. It should not return in a
3394 /// dependent context, for example. Nor will it extend \p SS with the scope
3395 /// specifier.
3396 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3397 bool EnteringContext, CXXScopeSpec &SS,
3398 NamedDecl *ScopeLookupResult,
3399 bool ErrorRecoveryLookup,
3400 bool *IsCorrectedToColon = nullptr,
3401 bool OnlyNamespace = false);
3402
3403 /// The parser has parsed a nested-name-specifier 'identifier::'.
3404 ///
3405 /// \param S The scope in which this nested-name-specifier occurs.
3406 ///
3407 /// \param IdInfo Parser information about an identifier in the
3408 /// nested-name-spec.
3409 ///
3410 /// \param EnteringContext Whether we're entering the context nominated by
3411 /// this nested-name-specifier.
3412 ///
3413 /// \param SS The nested-name-specifier, which is both an input
3414 /// parameter (the nested-name-specifier before this type) and an
3415 /// output parameter (containing the full nested-name-specifier,
3416 /// including this new type).
3417 ///
3418 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3419 /// are allowed. The bool value pointed by this parameter is set to 'true'
3420 /// if the identifier is treated as if it was followed by ':', not '::'.
3421 ///
3422 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3423 ///
3424 /// \returns true if an error occurred, false otherwise.
3425 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3426 bool EnteringContext, CXXScopeSpec &SS,
3427 bool *IsCorrectedToColon = nullptr,
3428 bool OnlyNamespace = false);
3429
3430 /// The parser has parsed a nested-name-specifier
3431 /// 'template[opt] template-name < template-args >::'.
3432 ///
3433 /// \param S The scope in which this nested-name-specifier occurs.
3434 ///
3435 /// \param SS The nested-name-specifier, which is both an input
3436 /// parameter (the nested-name-specifier before this type) and an
3437 /// output parameter (containing the full nested-name-specifier,
3438 /// including this new type).
3439 ///
3440 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3441 /// \param TemplateName the template name.
3442 /// \param TemplateNameLoc The location of the template name.
3443 /// \param LAngleLoc The location of the opening angle bracket ('<').
3444 /// \param TemplateArgs The template arguments.
3445 /// \param RAngleLoc The location of the closing angle bracket ('>').
3446 /// \param CCLoc The location of the '::'.
3447 ///
3448 /// \param EnteringContext Whether we're entering the context of the
3449 /// nested-name-specifier.
3450 ///
3451 ///
3452 /// \returns true if an error occurred, false otherwise.
3454 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3455 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3456 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3457 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3458
3460 SourceLocation ColonColonLoc);
3461
3463 const DeclSpec &DS,
3464 SourceLocation ColonColonLoc,
3465 QualType Type);
3466
3467 /// IsInvalidUnlessNestedName - This method is used for error recovery
3468 /// purposes to determine whether the specified identifier is only valid as
3469 /// a nested name specifier, for example a namespace name. It is
3470 /// conservatively correct to always return false from this method.
3471 ///
3472 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3474 NestedNameSpecInfo &IdInfo,
3475 bool EnteringContext);
3476
3477 /// Given a C++ nested-name-specifier, produce an annotation value
3478 /// that the parser can use later to reconstruct the given
3479 /// nested-name-specifier.
3480 ///
3481 /// \param SS A nested-name-specifier.
3482 ///
3483 /// \returns A pointer containing all of the information in the
3484 /// nested-name-specifier \p SS.
3486
3487 /// Given an annotation pointer for a nested-name-specifier, restore
3488 /// the nested-name-specifier structure.
3489 ///
3490 /// \param Annotation The annotation pointer, produced by
3491 /// \c SaveNestedNameSpecifierAnnotation().
3492 ///
3493 /// \param AnnotationRange The source range corresponding to the annotation.
3494 ///
3495 /// \param SS The nested-name-specifier that will be updated with the contents
3496 /// of the annotation pointer.
3497 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3498 SourceRange AnnotationRange,
3499 CXXScopeSpec &SS);
3500
3501 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3502
3503 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3504 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3505 /// After this method is called, according to [C++ 3.4.3p3], names should be
3506 /// looked up in the declarator-id's scope, until the declarator is parsed and
3507 /// ActOnCXXExitDeclaratorScope is called.
3508 /// The 'SS' should be a non-empty valid CXXScopeSpec.
3510
3511 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3512 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3513 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3514 /// Used to indicate that names should revert to being looked up in the
3515 /// defining scope.
3517
3518 ///@}
3519
3520 //
3521 //
3522 // -------------------------------------------------------------------------
3523 //
3524 //
3525
3526 /// \name Declarations
3527 /// Implementations are in SemaDecl.cpp
3528 ///@{
3529
3530public:
3532
3533 /// The index of the first InventedParameterInfo that refers to the current
3534 /// context.
3536
3537 /// A RAII object to temporarily push a declaration context.
3539 private:
3540 Sema &S;
3541 DeclContext *SavedContext;
3542 ProcessingContextState SavedContextState;
3543 QualType SavedCXXThisTypeOverride;
3544 unsigned SavedFunctionScopesStart;
3545 unsigned SavedInventedParameterInfosStart;
3546
3547 public:
3548 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3549 : S(S), SavedContext(S.CurContext),
3550 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3551 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3552 SavedFunctionScopesStart(S.FunctionScopesStart),
3553 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3554 assert(ContextToPush && "pushing null context");
3555 S.CurContext = ContextToPush;
3556 if (NewThisContext)
3557 S.CXXThisTypeOverride = QualType();
3558 // Any saved FunctionScopes do not refer to this context.
3559 S.FunctionScopesStart = S.FunctionScopes.size();
3560 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3561 }
3562
3563 void pop() {
3564 if (!SavedContext)
3565 return;
3566 S.CurContext = SavedContext;
3567 S.DelayedDiagnostics.popUndelayed(SavedContextState);
3568 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3569 S.FunctionScopesStart = SavedFunctionScopesStart;
3570 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3571 SavedContext = nullptr;
3572 }
3573
3575 ContextRAII(const ContextRAII &) = delete;
3577 };
3578
3579 void DiagnoseInvalidJumps(Stmt *Body);
3580
3581 /// The function definitions which were renamed as part of typo-correction
3582 /// to match their respective declarations. We want to keep track of them
3583 /// to ensure that we don't emit a "redefinition" error if we encounter a
3584 /// correctly named definition after the renamed definition.
3586
3587 /// A cache of the flags available in enumerations with the flag_enum
3588 /// attribute.
3589 llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3590
3591 /// A cache of enumerator values for enums checked by -Wassign-enum.
3592 llvm::DenseMap<const EnumDecl *, llvm::SmallVector<llvm::APSInt>>
3594
3595 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3596 /// declared. Rare. May alias another identifier, declared or undeclared.
3597 ///
3598 /// For aliases, the target identifier is used as a key for eventual
3599 /// processing when the target is declared. For the single-identifier form,
3600 /// the sole identifier is used as the key. Each entry is a `SetVector`
3601 /// (ordered by parse order) of aliases (identified by the alias name) in case
3602 /// of multiple aliases to the same undeclared identifier.
3603 llvm::MapVector<
3605 llvm::SetVector<
3607 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3609
3610 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3611 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3612 /// to define functions that occur in multiple standards to call the version
3613 /// in the currently selected standard.
3614 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>
3616
3617 /// Set containing all typedefs that are likely unused.
3620
3621 /// Store UnusedLocalTypedefNameCandidates in \p Sorted in a deterministic
3622 /// order.
3625
3629
3630 /// The set of file scoped decls seen so far that have not been used
3631 /// and must warn if not used. Only contains the first declaration.
3633
3637
3638 /// All the tentative definitions encountered in the TU.
3640
3641 /// All the external declarations encoutered and used in the TU.
3643
3644 /// Generally null except when we temporarily switch decl contexts,
3645 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3647
3648 /// Is the module scope we are in a C++ Header Unit?
3650 return ModuleScopes.empty() ? false
3651 : ModuleScopes.back().Module->isHeaderUnit();
3652 }
3653
3654 /// Get the module owning an entity.
3655 Module *getOwningModule(const Decl *Entity) {
3656 return Entity->getOwningModule();
3657 }
3658
3659 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3660
3662 /// Returns the TypeDeclType for the given type declaration,
3663 /// as ASTContext::getTypeDeclType would, but
3664 /// performs the required semantic checks for name lookup of said entity.
3665 void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD,
3666 SourceLocation NameLoc);
3667
3668 /// If the identifier refers to a type name within this scope,
3669 /// return the declaration of that type.
3670 ///
3671 /// This routine performs ordinary name lookup of the identifier II
3672 /// within the given scope, with optional C++ scope specifier SS, to
3673 /// determine whether the name refers to a type. If so, returns an
3674 /// opaque pointer (actually a QualType) corresponding to that
3675 /// type. Otherwise, returns NULL.
3677 Scope *S, CXXScopeSpec *SS = nullptr,
3678 bool isClassName = false, bool HasTrailingDot = false,
3679 ParsedType ObjectType = nullptr,
3680 bool IsCtorOrDtorName = false,
3681 bool WantNontrivialTypeSourceInfo = false,
3682 bool IsClassTemplateDeductionContext = true,
3683 ImplicitTypenameContext AllowImplicitTypename =
3685 IdentifierInfo **CorrectedII = nullptr);
3686
3687 /// isTagName() - This method is called *for error recovery purposes only*
3688 /// to determine if the specified name is a valid tag name ("struct foo"). If
3689 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3690 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3691 /// diagnose cases in C where the user forgot to specify the tag.
3693
3694 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3695 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3696 /// then downgrade the missing typename error to a warning.
3697 /// This is needed for MSVC compatibility; Example:
3698 /// @code
3699 /// template<class T> class A {
3700 /// public:
3701 /// typedef int TYPE;
3702 /// };
3703 /// template<class T> class B : public A<T> {
3704 /// public:
3705 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3706 /// };
3707 /// @endcode
3708 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3710 Scope *S, CXXScopeSpec *SS,
3711 ParsedType &SuggestedType,
3712 bool IsTemplateName = false);
3713
3714 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3715 /// type name has failed in a dependent context. In these situations, we
3716 /// automatically form a DependentTypeName that will retry lookup in a related
3717 /// scope during instantiation.
3719 SourceLocation NameLoc,
3720 bool IsTemplateTypeArg);
3721
3722 class NameClassification {
3724 union {
3729 };
3730
3731 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3732
3733 public:
3736
3739
3740 static NameClassification Error() {
3741 return NameClassification(NameClassificationKind::Error);
3742 }
3743
3744 static NameClassification Unknown() {
3745 return NameClassification(NameClassificationKind::Unknown);
3746 }
3747
3748 static NameClassification OverloadSet(ExprResult E) {
3749 NameClassification Result(NameClassificationKind::OverloadSet);
3750 Result.Expr = E;
3751 return Result;
3752 }
3753
3754 static NameClassification NonType(NamedDecl *D) {
3755 NameClassification Result(NameClassificationKind::NonType);
3756 Result.NonTypeDecl = D;
3757 return Result;
3758 }
3759
3760 static NameClassification UndeclaredNonType() {
3761 return NameClassification(NameClassificationKind::UndeclaredNonType);
3762 }
3763
3764 static NameClassification DependentNonType() {
3765 return NameClassification(NameClassificationKind::DependentNonType);
3766 }
3767
3768 static NameClassification TypeTemplate(TemplateName Name) {
3769 NameClassification Result(NameClassificationKind::TypeTemplate);
3770 Result.Template = Name;
3771 return Result;
3772 }
3773
3774 static NameClassification VarTemplate(TemplateName Name) {
3775 NameClassification Result(NameClassificationKind::VarTemplate);
3776 Result.Template = Name;
3777 return Result;
3778 }
3779
3780 static NameClassification FunctionTemplate(TemplateName Name) {
3782 Result.Template = Name;
3783 return Result;
3784 }
3785
3786 static NameClassification Concept(TemplateName Name) {
3787 NameClassification Result(NameClassificationKind::Concept);
3788 Result.Template = Name;
3789 return Result;
3790 }
3791
3792 static NameClassification UndeclaredTemplate(TemplateName Name) {
3794 Result.Template = Name;
3795 return Result;
3796 }
3797
3798 NameClassificationKind getKind() const { return Kind; }
3799
3802 return Expr;
3803 }
3804
3806 assert(Kind == NameClassificationKind::Type);
3807 return Type;
3808 }
3809
3811 assert(Kind == NameClassificationKind::NonType);
3812 return NonTypeDecl;
3813 }
3814
3823
3825 switch (Kind) {
3827 return TNK_Type_template;
3829 return TNK_Function_template;
3831 return TNK_Var_template;
3833 return TNK_Concept_template;
3836 default:
3837 llvm_unreachable("unsupported name classification.");
3838 }
3839 }
3840 };
3841
3842 /// Perform name lookup on the given name, classifying it based on
3843 /// the results of name lookup and the following token.
3844 ///
3845 /// This routine is used by the parser to resolve identifiers and help direct
3846 /// parsing. When the identifier cannot be found, this routine will attempt
3847 /// to correct the typo and classify based on the resulting name.
3848 ///
3849 /// \param S The scope in which we're performing name lookup.
3850 ///
3851 /// \param SS The nested-name-specifier that precedes the name.
3852 ///
3853 /// \param Name The identifier. If typo correction finds an alternative name,
3854 /// this pointer parameter will be updated accordingly.
3855 ///
3856 /// \param NameLoc The location of the identifier.
3857 ///
3858 /// \param NextToken The token following the identifier. Used to help
3859 /// disambiguate the name.
3860 ///
3861 /// \param CCC The correction callback, if typo correction is desired.
3862 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3863 IdentifierInfo *&Name, SourceLocation NameLoc,
3864 const Token &NextToken,
3865 CorrectionCandidateCallback *CCC = nullptr);
3866
3867 /// Act on the result of classifying a name as an undeclared (ADL-only)
3868 /// non-type declaration.
3870 SourceLocation NameLoc);
3871 /// Act on the result of classifying a name as an undeclared member of a
3872 /// dependent base class.
3874 IdentifierInfo *Name,
3875 SourceLocation NameLoc,
3876 bool IsAddressOfOperand);
3877 /// Act on the result of classifying a name as a specific non-type
3878 /// declaration.
3881 SourceLocation NameLoc,
3882 const Token &NextToken);
3883 /// Act on the result of classifying a name as an overload set.
3885
3886 /// Describes the detailed kind of a template name. Used in diagnostics.
3898
3899 /// Determine whether it's plausible that E was intended to be a
3900 /// template-name.
3902 if (!getLangOpts().CPlusPlus || E.isInvalid())
3903 return false;
3904 Dependent = false;
3905 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
3906 return !DRE->hasExplicitTemplateArgs();
3907 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
3908 return !ME->hasExplicitTemplateArgs();
3909 Dependent = true;
3910 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
3911 return !DSDRE->hasExplicitTemplateArgs();
3912 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
3913 return !DSME->hasExplicitTemplateArgs();
3914 // Any additional cases recognized here should also be handled by
3915 // diagnoseExprIntendedAsTemplateName.
3916 return false;
3917 }
3918
3919 void warnOnReservedIdentifier(const NamedDecl *D);
3921
3922 void ProcessPragmaExport(DeclaratorDecl *newDecl);
3923
3925
3927 MultiTemplateParamsArg TemplateParameterLists);
3928
3929 /// Attempt to fold a variable-sized type to a constant-sized type, returning
3930 /// true if we were successful.
3932 SourceLocation Loc,
3933 unsigned FailedFoldDiagID);
3934
3935 /// Register the given locally-scoped extern "C" declaration so
3936 /// that it can be found later for redeclarations. We include any extern "C"
3937 /// declaration that is not visible in the translation unit here, not just
3938 /// function-scope declarations.
3940
3941 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3942 /// If T is the name of a class, then each of the following shall have a
3943 /// name different from T:
3944 /// - every static data member of class T;
3945 /// - every member function of class T
3946 /// - every member of class T that is itself a type;
3947 /// \returns true if the declaration name violates these rules.
3949
3950 /// Diagnose a declaration whose declarator-id has the given
3951 /// nested-name-specifier.
3952 ///
3953 /// \param SS The nested-name-specifier of the declarator-id.
3954 ///
3955 /// \param DC The declaration context to which the nested-name-specifier
3956 /// resolves.
3957 ///
3958 /// \param Name The name of the entity being declared.
3959 ///
3960 /// \param Loc The location of the name of the entity being declared.
3961 ///
3962 /// \param IsMemberSpecialization Whether we are declaring a member
3963 /// specialization.
3964 ///
3965 /// \param TemplateId The template-id, if any.
3966 ///
3967 /// \returns true if we cannot safely recover from this error, false
3968 /// otherwise.
3971 TemplateIdAnnotation *TemplateId,
3972 bool IsMemberSpecialization);
3973
3975
3976 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
3977
3979 unsigned &IntVal);
3980
3981 /// Diagnose function specifiers on a declaration of an identifier that
3982 /// does not identify a function.
3983 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
3984
3985 /// Return the declaration shadowed by the given typedef \p D, or null
3986 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3988 const LookupResult &R);
3989
3990 /// Return the declaration shadowed by the given variable \p D, or null
3991 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3993
3994 /// Return the declaration shadowed by the given variable \p D, or null
3995 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3997 const LookupResult &R);
3998 /// Diagnose variable or built-in function shadowing. Implements
3999 /// -Wshadow.
4000 ///
4001 /// This method is called whenever a VarDecl is added to a "useful"
4002 /// scope.
4003 ///
4004 /// \param ShadowedDecl the declaration that is shadowed by the given variable
4005 /// \param R the lookup of the name
4006 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
4007 const LookupResult &R);
4008
4009 /// Check -Wshadow without the advantage of a previous lookup.
4010 void CheckShadow(Scope *S, VarDecl *D);
4011
4012 /// Warn if 'E', which is an expression that is about to be modified, refers
4013 /// to a shadowing declaration.
4015
4016 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
4017 /// when these variables are captured by the lambda.
4019
4020 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
4021 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4022 TypedefNameDecl *NewTD);
4025 TypeSourceInfo *TInfo,
4027
4028 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4029 /// declares a typedef-name, either using the 'typedef' type specifier or via
4030 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4034 TypeSourceInfo *TInfo,
4036 MultiTemplateParamsArg TemplateParamLists,
4037 bool &AddToScope,
4039
4040private:
4041 // Perform a check on an AsmLabel to verify its consistency and emit
4042 // diagnostics in case of an error.
4043 void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
4044 TypeSourceInfo *TInfo, VarDecl *);
4045
4046public:
4047 /// Perform semantic checking on a newly-created variable
4048 /// declaration.
4049 ///
4050 /// This routine performs all of the type-checking required for a
4051 /// variable declaration once it has been built. It is used both to
4052 /// check variables after they have been parsed and their declarators
4053 /// have been translated into a declaration, and to check variables
4054 /// that have been instantiated from a template.
4055 ///
4056 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4057 ///
4058 /// Returns true if the variable declaration is a redeclaration.
4059 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
4060 void CheckVariableDeclarationType(VarDecl *NewVD);
4061 void CheckCompleteVariableDeclaration(VarDecl *VD);
4062
4063 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4064 TypeSourceInfo *TInfo,
4065 LookupResult &Previous,
4066 MultiTemplateParamsArg TemplateParamLists,
4067 bool &AddToScope);
4068
4069 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4070 /// and if so, check that it's a valid override and remember it.
4071 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
4072
4073 /// Perform semantic checking of a new function declaration.
4074 ///
4075 /// Performs semantic analysis of the new function declaration
4076 /// NewFD. This routine performs all semantic checking that does not
4077 /// require the actual declarator involved in the declaration, and is
4078 /// used both for the declaration of functions as they are parsed
4079 /// (called via ActOnDeclarator) and for the declaration of functions
4080 /// that have been instantiated via C++ template instantiation (called
4081 /// via InstantiateDecl).
4082 ///
4083 /// \param IsMemberSpecialization whether this new function declaration is
4084 /// a member specialization (that replaces any definition provided by the
4085 /// previous declaration).
4086 ///
4087 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4088 ///
4089 /// \returns true if the function declaration is a redeclaration.
4090 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4091 LookupResult &Previous,
4092 bool IsMemberSpecialization, bool DeclIsDefn);
4093
4094 /// Checks if the new declaration declared in dependent context must be
4095 /// put in the same redeclaration chain as the specified declaration.
4096 ///
4097 /// \param D Declaration that is checked.
4098 /// \param PrevDecl Previous declaration found with proper lookup method for
4099 /// the same declaration name.
4100 /// \returns True if D must be added to the redeclaration chain which PrevDecl
4101 /// belongs to.
4102 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4103
4104 /// Determines if we can perform a correct type check for \p D as a
4105 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4106 /// best-effort check.
4107 ///
4108 /// \param NewD The new declaration.
4109 /// \param OldD The old declaration.
4110 /// \param NewT The portion of the type of the new declaration to check.
4111 /// \param OldT The portion of the type of the old declaration to check.
4112 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4113 QualType NewT, QualType OldT);
4114 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4115 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4116
4117 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4118 /// containing class. Otherwise it will return implicit SectionAttr if the
4119 /// function is a definition and there is an active value on CodeSegStack
4120 /// (from the current #pragma code-seg value).
4121 ///
4122 /// \param FD Function being declared.
4123 /// \param IsDefinition Whether it is a definition or just a declaration.
4124 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4125 /// nullptr if no attribute should be added.
4126 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4127 bool IsDefinition);
4128
4129 /// Common checks for a parameter-declaration that should apply to both
4130 /// function parameters and non-type template parameters.
4131 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4132
4133 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4134 /// to introduce parameters into function prototype scope.
4135 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4136 SourceLocation ExplicitThisLoc = {});
4137
4138 /// Synthesizes a variable for a parameter arising from a
4139 /// typedef.
4140 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4141 QualType T);
4142 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4143 SourceLocation NameLoc,
4144 const IdentifierInfo *Name, QualType T,
4145 TypeSourceInfo *TSInfo, StorageClass SC);
4146
4147 /// Emit diagnostics if the initializer or any of its explicit or
4148 /// implicitly-generated subexpressions require copying or
4149 /// default-initializing a type that is or contains a C union type that is
4150 /// non-trivial to copy or default-initialize.
4151 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4152
4153 // These flags are passed to checkNonTrivialCUnion.
4159
4160 /// Emit diagnostics if a non-trivial C union type or a struct that contains
4161 /// a non-trivial C union is used in an invalid context.
4163 NonTrivialCUnionContext UseContext,
4164 unsigned NonTrivialKind);
4165
4166 /// Certain globally-unique variables might be accidentally duplicated if
4167 /// built into multiple shared libraries with hidden visibility. This can
4168 /// cause problems if the variable is mutable, its initialization is
4169 /// effectful, or its address is taken.
4172
4173 /// AddInitializerToDecl - Adds the initializer Init to the
4174 /// declaration dcl. If DirectInit is true, this is C++ direct
4175 /// initialization rather than copy initialization.
4176 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4177 void ActOnUninitializedDecl(Decl *dcl);
4178
4179 /// ActOnInitializerError - Given that there was an error parsing an
4180 /// initializer for the given declaration, try to at least re-establish
4181 /// invariants such as whether a variable's type is either dependent or
4182 /// complete.
4183 void ActOnInitializerError(Decl *Dcl);
4184
4185 void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt);
4187 IdentifierInfo *Ident,
4188 ParsedAttributes &Attrs);
4189
4190 /// Check if VD needs to be dllexport/dllimport due to being in a
4191 /// dllexport/import function.
4194
4195 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4196 /// any semantic actions necessary after any initializer has been attached.
4197 void FinalizeDeclaration(Decl *D);
4199 ArrayRef<Decl *> Group);
4200
4201 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4202 /// group, performing any necessary semantic checking.
4204
4205 /// Should be called on all declarations that might have attached
4206 /// documentation comments.
4207 void ActOnDocumentableDecl(Decl *D);
4209
4210 enum class FnBodyKind {
4211 /// C++26 [dcl.fct.def.general]p1
4212 /// function-body:
4213 /// ctor-initializer[opt] compound-statement
4214 /// function-try-block
4216 /// = default ;
4218 /// deleted-function-body
4219 ///
4220 /// deleted-function-body:
4221 /// = delete ;
4222 /// = delete ( unevaluated-string ) ;
4224 };
4225
4227 SourceLocation LocAfterDecls);
4229 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4230 SkipBodyInfo *SkipBody = nullptr);
4232 MultiTemplateParamsArg TemplateParamLists,
4233 SkipBodyInfo *SkipBody = nullptr,
4234 FnBodyKind BodyKind = FnBodyKind::Other);
4236 SkipBodyInfo *SkipBody = nullptr,
4237 FnBodyKind BodyKind = FnBodyKind::Other);
4239
4240 /// Determine whether we can delay parsing the body of a function or
4241 /// function template until it is used, assuming we don't care about emitting
4242 /// code for that function.
4243 ///
4244 /// This will be \c false if we may need the body of the function in the
4245 /// middle of parsing an expression (where it's impractical to switch to
4246 /// parsing a different function), for instance, if it's constexpr in C++11
4247 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4248 bool canDelayFunctionBody(const Declarator &D);
4249
4250 /// Determine whether we can skip parsing the body of a function
4251 /// definition, assuming we don't care about analyzing its body or emitting
4252 /// code for that function.
4253 ///
4254 /// This will be \c false only if we may need the body of the function in
4255 /// order to parse the rest of the program (for instance, if it is
4256 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4257 bool canSkipFunctionBody(Decl *D);
4258
4259 /// Given the set of return statements within a function body,
4260 /// compute the variables that are subject to the named return value
4261 /// optimization.
4262 ///
4263 /// Each of the variables that is subject to the named return value
4264 /// optimization will be marked as NRVO variables in the AST, and any
4265 /// return statement that has a marked NRVO variable as its NRVO candidate can
4266 /// use the named return value optimization.
4267 ///
4268 /// This function applies a very simplistic algorithm for NRVO: if every
4269 /// return statement in the scope of a variable has the same NRVO candidate,
4270 /// that candidate is an NRVO variable.
4272
4273 /// Performs semantic analysis at the end of a function body.
4274 ///
4275 /// \param RetainFunctionScopeInfo If \c true, the client is responsible for
4276 /// releasing the associated \p FunctionScopeInfo. This is useful when
4277 /// building e.g. LambdaExprs.
4279 bool IsInstantiation = false,
4280 bool RetainFunctionScopeInfo = false);
4283
4284 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4285 /// attribute for which parsing is delayed.
4287
4288 /// Diagnose any unused parameters in the given sequence of
4289 /// ParmVarDecl pointers.
4291
4292 /// Diagnose whether the size of parameters or return value of a
4293 /// function or obj-c method definition is pass-by-value and larger than a
4294 /// specified threshold.
4295 void
4297 QualType ReturnTy, NamedDecl *D);
4298
4300 SourceLocation RParenLoc);
4301
4304
4305 void ActOnPopScope(SourceLocation Loc, Scope *S);
4306
4307 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4308 /// no declarator (e.g. "struct foo;") is parsed.
4310 const ParsedAttributesView &DeclAttrs,
4311 RecordDecl *&AnonRecord);
4312
4313 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4314 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4315 /// parameters to cope with template friend declarations.
4317 const ParsedAttributesView &DeclAttrs,
4318 MultiTemplateParamsArg TemplateParams,
4319 bool IsExplicitInstantiation,
4320 RecordDecl *&AnonRecord,
4321 SourceLocation EllipsisLoc = {});
4322
4323 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4324 /// anonymous structure or union. Anonymous unions are a C++ feature
4325 /// (C++ [class.union]) and a C11 feature; anonymous structures
4326 /// are a C11 feature and GNU C++ extension.
4327 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4328 RecordDecl *Record,
4329 const PrintingPolicy &Policy);
4330
4331 /// Called once it is known whether
4332 /// a tag declaration is an anonymous union or struct.
4334
4335 /// Emit diagnostic warnings for placeholder members.
4336 /// We can only do that after the class is fully constructed,
4337 /// as anonymous union/structs can insert placeholders
4338 /// in their parent scope (which might be a Record).
4340
4341 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4342 /// Microsoft C anonymous structure.
4343 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4344 /// Example:
4345 ///
4346 /// struct A { int a; };
4347 /// struct B { struct A; int b; };
4348 ///
4349 /// void foo() {
4350 /// B var;
4351 /// var.a = 3;
4352 /// }
4353 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4354 RecordDecl *Record);
4355
4356 /// Given a non-tag type declaration, returns an enum useful for indicating
4357 /// what kind of non-tag type this is.
4358 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4359
4360 /// Determine whether a tag with a given kind is acceptable
4361 /// as a redeclaration of the given tag declaration.
4362 ///
4363 /// \returns true if the new tag kind is acceptable, false otherwise.
4365 bool isDefinition, SourceLocation NewTagLoc,
4366 const IdentifierInfo *Name);
4367
4368 /// This is invoked when we see 'struct foo' or 'struct {'. In the
4369 /// former case, Name will be non-null. In the later case, Name will be null.
4370 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4371 /// a reference/declaration/definition of a tag.
4372 ///
4373 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4374 /// trailing-type-specifier) other than one in an alias-declaration.
4375 ///
4376 /// \param SkipBody If non-null, will be set to indicate if the caller should
4377 /// skip the definition of this tag and treat it as if it were a declaration.
4378 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4379 SourceLocation KWLoc, CXXScopeSpec &SS,
4380 IdentifierInfo *Name, SourceLocation NameLoc,
4381 const ParsedAttributesView &Attr, AccessSpecifier AS,
4382 SourceLocation ModulePrivateLoc,
4383 MultiTemplateParamsArg TemplateParameterLists,
4384 bool &OwnedDecl, bool &IsDependent,
4385 SourceLocation ScopedEnumKWLoc,
4386 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4387 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4388 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4389
4390 /// ActOnField - Each field of a C struct/union is passed into this in order
4391 /// to create a FieldDecl object for it.
4392 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4393 Declarator &D, Expr *BitfieldWidth);
4394
4395 /// HandleField - Analyze a field of a C struct or a C++ data member.
4396 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4397 Declarator &D, Expr *BitfieldWidth,
4398 InClassInitStyle InitStyle, AccessSpecifier AS);
4399
4400 /// Build a new FieldDecl and check its well-formedness.
4401 ///
4402 /// This routine builds a new FieldDecl given the fields name, type,
4403 /// record, etc. \p PrevDecl should refer to any previous declaration
4404 /// with the same name and in the same scope as the field to be
4405 /// created.
4406 ///
4407 /// \returns a new FieldDecl.
4408 ///
4409 /// \todo The Declarator argument is a hack. It will be removed once
4410 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4411 TypeSourceInfo *TInfo, RecordDecl *Record,
4412 SourceLocation Loc, bool Mutable,
4413 Expr *BitfieldWidth, InClassInitStyle InitStyle,
4414 SourceLocation TSSL, AccessSpecifier AS,
4415 NamedDecl *PrevDecl, Declarator *D = nullptr);
4416
4418
4419 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4420 /// class and class extensions. For every class \@interface and class
4421 /// extension \@interface, if the last ivar is a bitfield of any type,
4422 /// then add an implicit `char :0` ivar to the end of that interface.
4423 void ActOnLastBitfield(SourceLocation DeclStart,
4424 SmallVectorImpl<Decl *> &AllIvarDecls);
4425
4426 // This is used for both record definitions and ObjC interface declarations.
4427 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4428 ArrayRef<Decl *> Fields, SourceLocation LBrac,
4429 SourceLocation RBrac, const ParsedAttributesView &AttrList);
4430
4431 /// ActOnTagStartDefinition - Invoked when we have entered the
4432 /// scope of a tag's definition (e.g., for an enumeration, class,
4433 /// struct, or union).
4434 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4435
4436 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4437 /// Differently from C++, actually parse the body and reject / error out
4438 /// in case of a structural mismatch.
4439 bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4440
4442
4443 /// Invoked when we enter a tag definition that we're skipping.
4445
4446 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4447 /// C++ record definition's base-specifiers clause and are starting its
4448 /// member declarations.
4450 SourceLocation FinalLoc,
4451 bool IsFinalSpelledSealed,
4452 bool IsAbstract,
4453 SourceLocation LBraceLoc);
4454
4455 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4456 /// the definition of a tag (enumeration, class, struct, or union).
4458 SourceRange BraceRange);
4459
4462
4464
4465 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4466 /// error parsing the definition of a tag.
4468
4470 EnumConstantDecl *LastEnumConst,
4471 SourceLocation IdLoc, IdentifierInfo *Id,
4472 Expr *val);
4473
4474 /// Check that this is a valid underlying type for an enum declaration.
4476
4477 /// Check whether this is a valid redeclaration of a previous enumeration.
4478 /// \return true if the redeclaration was invalid.
4479 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4480 QualType EnumUnderlyingTy, bool IsFixed,
4481 const EnumDecl *Prev);
4482
4483 /// Determine whether the body of an anonymous enumeration should be skipped.
4484 /// \param II The name of the first enumerator.
4486 SourceLocation IILoc);
4487
4488 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4489 SourceLocation IdLoc, IdentifierInfo *Id,
4490 const ParsedAttributesView &Attrs,
4491 SourceLocation EqualLoc, Expr *Val,
4492 SkipBodyInfo *SkipBody = nullptr);
4493 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4494 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4495 const ParsedAttributesView &Attr);
4496
4497 /// Set the current declaration context until it gets popped.
4498 void PushDeclContext(Scope *S, DeclContext *DC);
4499 void PopDeclContext();
4500
4501 /// EnterDeclaratorContext - Used when we must lookup names in the context
4502 /// of a declarator's nested name specifier.
4505
4506 /// Enter a template parameter scope, after it's been associated with a
4507 /// particular DeclContext. Causes lookup within the scope to chain through
4508 /// enclosing contexts in the correct order.
4510
4511 /// Push the parameters of D, which must be a function, into scope.
4514
4515 /// Add this decl to the scope shadowed decl chains.
4516 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4517
4518 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4519 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4520 /// true if 'D' belongs to the given declaration context.
4521 ///
4522 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4523 /// enclosing namespace set of the context, rather than contained
4524 /// directly within it.
4525 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4526 bool AllowInlineNamespace = false) const;
4527
4528 /// Finds the scope corresponding to the given decl context, if it
4529 /// happens to be an enclosing scope. Otherwise return NULL.
4531
4532 /// Subroutines of ActOnDeclarator().
4534 TypeSourceInfo *TInfo);
4536
4537 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4539 NamedDecl *New, Decl *Old,
4541
4542 /// CheckAttributesOnDeducedType - Calls Sema functions for attributes that
4543 /// requires the type to be deduced.
4545
4546 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4547 /// same name and scope as a previous declaration 'Old'. Figure out
4548 /// how to resolve this situation, merging decls or emitting
4549 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4551 LookupResult &OldDecls);
4552
4553 /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4554 /// definition visible.
4555 /// This method performs any necessary cleanup on the parser state to discard
4556 /// child nodes from newly parsed decl we are retiring.
4557 void CleanupMergedEnum(Scope *S, Decl *New);
4558
4559 /// MergeFunctionDecl - We just parsed a function 'New' from
4560 /// declarator D which has the same name and scope as a previous
4561 /// declaration 'Old'. Figure out how to resolve this situation,
4562 /// merging decls or emitting diagnostics as appropriate.
4563 ///
4564 /// In C++, New and Old must be declarations that are not
4565 /// overloaded. Use IsOverload to determine whether New and Old are
4566 /// overloaded, and to select the Old declaration that New should be
4567 /// merged with.
4568 ///
4569 /// Returns true if there was an error, false otherwise.
4571 bool MergeTypeWithOld, bool NewDeclIsDefn);
4572
4573 /// Completes the merge of two function declarations that are
4574 /// known to be compatible.
4575 ///
4576 /// This routine handles the merging of attributes and other
4577 /// properties of function declarations from the old declaration to
4578 /// the new declaration, once we know that New is in fact a
4579 /// redeclaration of Old.
4580 ///
4581 /// \returns false
4583 Scope *S, bool MergeTypeWithOld);
4585
4586 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4587 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4588 /// situation, merging decls or emitting diagnostics as appropriate.
4589 ///
4590 /// Tentative definition rules (C99 6.9.2p2) are checked by
4591 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4592 /// definitions here, since the initializer hasn't been attached.
4594
4595 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4596 /// scope as a previous declaration 'Old'. Figure out how to merge their
4597 /// types, emitting diagnostics as appropriate.
4598 ///
4599 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4600 /// back to here in AddInitializerToDecl. We can't check them before the
4601 /// initializer is attached.
4602 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4603
4604 /// We've just determined that \p Old and \p New both appear to be definitions
4605 /// of the same variable. Either diagnose or fix the problem.
4606 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4608
4609 /// Filters out lookup results that don't fall within the given scope
4610 /// as determined by isDeclInScope.
4612 bool ConsiderLinkage, bool AllowInlineNamespace);
4613
4614 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4615 /// have compatible owning modules.
4617
4618 /// [module.interface]p6:
4619 /// A redeclaration of an entity X is implicitly exported if X was introduced
4620 /// by an exported declaration; otherwise it shall not be exported.
4622
4623 /// A wrapper function for checking the semantic restrictions of
4624 /// a redeclaration within a module.
4626
4627 /// Check the redefinition in C++20 Modules.
4628 ///
4629 /// [basic.def.odr]p14:
4630 /// For any definable item D with definitions in multiple translation units,
4631 /// - if D is a non-inline non-templated function or variable, or
4632 /// - if the definitions in different translation units do not satisfy the
4633 /// following requirements,
4634 /// the program is ill-formed; a diagnostic is required only if the
4635 /// definable item is attached to a named module and a prior definition is
4636 /// reachable at the point where a later definition occurs.
4637 /// - Each such definition shall not be attached to a named module
4638 /// ([module.unit]).
4639 /// - Each such definition shall consist of the same sequence of tokens, ...
4640 /// ...
4641 ///
4642 /// Return true if the redefinition is not allowed. Return false otherwise.
4643 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4644
4646
4647 /// If it's a file scoped decl that must warn if not used, keep track
4648 /// of it.
4650
4651 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4653
4656 DiagReceiverTy DiagReceiver);
4657 void DiagnoseUnusedDecl(const NamedDecl *ND);
4658
4659 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4660 /// unless they are marked attr(unused).
4661 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4662
4663 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4664 /// variable.
4665 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4666
4667 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4668 /// from S, where a non-field would be declared. This routine copes
4669 /// with the difference between C and C++ scoping rules in structs and
4670 /// unions. For example, the following code is well-formed in C but
4671 /// ill-formed in C++:
4672 /// @code
4673 /// struct S6 {
4674 /// enum { BAR } e;
4675 /// };
4676 ///
4677 /// void test_S6() {
4678 /// struct S6 a;
4679 /// a.e = BAR;
4680 /// }
4681 /// @endcode
4682 /// For the declaration of BAR, this routine will return a different
4683 /// scope. The scope S will be the scope of the unnamed enumeration
4684 /// within S6. In C++, this routine will return the scope associated
4685 /// with S6, because the enumeration's scope is a transparent
4686 /// context but structures can contain non-field names. In C, this
4687 /// routine will return the translation unit scope, since the
4688 /// enumeration's scope is a transparent context and structures cannot
4689 /// contain non-field names.
4691
4693 SourceLocation Loc);
4694
4695 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4696 /// file scope. lazily create a decl for it. ForRedeclaration is true
4697 /// if we're creating this built-in in anticipation of redeclaring the
4698 /// built-in.
4699 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4700 bool ForRedeclaration, SourceLocation Loc);
4701
4702 /// Get the outermost AttributedType node that sets a calling convention.
4703 /// Valid types should not have multiple attributes with different CCs.
4704 const AttributedType *getCallingConvAttributedType(QualType T) const;
4705
4706 /// GetNameForDeclarator - Determine the full declaration name for the
4707 /// given Declarator.
4709
4710 /// Retrieves the declaration name from a parsed unqualified-id.
4712
4713 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4714 /// we are currently parsing the initializer.
4716
4717 /// Look for a locally scoped extern "C" declaration by the given name.
4719
4722
4723 /// Adjust the \c DeclContext for a function or variable that might be a
4724 /// function-local external declaration.
4726
4728
4729 /// Checks if the variant/multiversion functions are compatible.
4731 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4732 const PartialDiagnostic &NoProtoDiagID,
4733 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4734 const PartialDiagnosticAt &NoSupportDiagIDAt,
4735 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4736 bool ConstexprSupported, bool CLinkageMayDiffer);
4737
4738 /// type checking declaration initializers (C99 6.7.8)
4740 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4741
4744 SourceRange Range, bool DirectInit,
4745 Expr *Init);
4746
4748 Expr *Init);
4749
4751
4752 // Heuristically tells if the function is `get_return_object` member of a
4753 // coroutine promise_type by matching the function name.
4754 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4755 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4756
4757 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4758 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4760 Scope *S);
4761
4762 /// If this function is a C++ replaceable global allocation function
4763 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4764 /// adds any function attributes that we know a priori based on the standard.
4765 ///
4766 /// We need to check for duplicate attributes both here and where user-written
4767 /// attributes are applied to declarations.
4769 FunctionDecl *FD);
4770
4771 /// Adds any function attributes that we know a priori based on
4772 /// the declaration of this function.
4773 ///
4774 /// These attributes can apply both to implicitly-declared builtins
4775 /// (like __builtin___printf_chk) or to library-declared functions
4776 /// like NSLog or printf.
4777 ///
4778 /// We need to check for duplicate attributes both here and where user-written
4779 /// attributes are applied to declarations.
4781
4782 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4783 /// the correct width, and that the field type is valid.
4784 /// Returns false on success.
4786 const IdentifierInfo *FieldName, QualType FieldTy,
4787 bool IsMsStruct, Expr *BitWidth);
4788
4789 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4790 /// enum. If AllowMask is true, then we also allow the complement of a valid
4791 /// value, to be used as a mask.
4792 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4793 bool AllowMask) const;
4794
4795 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4796 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4797 SourceLocation WeakNameLoc);
4798
4799 /// ActOnPragmaRedefineExtname - Called on well formed
4800 /// \#pragma redefine_extname oldname newname.
4802 IdentifierInfo *AliasName,
4803 SourceLocation PragmaLoc,
4804 SourceLocation WeakNameLoc,
4805 SourceLocation AliasNameLoc);
4806
4807 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4808 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4809 SourceLocation PragmaLoc,
4810 SourceLocation WeakNameLoc,
4811 SourceLocation AliasNameLoc);
4812
4813 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4816 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4817 OMPDiscarded, // Discarded due to OpenMP hostness
4818 TemplateDiscarded, // Discarded due to uninstantiated templates
4820 };
4821 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4822 bool Final = false);
4823
4824 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4826
4827 /// Function or variable declarations to be checked for whether the deferred
4828 /// diagnostics should be emitted.
4830
4831private:
4832 /// Map of current shadowing declarations to shadowed declarations. Warn if
4833 /// it looks like the user is trying to modify the shadowing declaration.
4834 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4835
4836 // We need this to handle
4837 //
4838 // typedef struct {
4839 // void *foo() { return 0; }
4840 // } A;
4841 //
4842 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4843 // for example. If 'A', foo will have external linkage. If we have '*A',
4844 // foo will have no linkage. Since we can't know until we get to the end
4845 // of the typedef, this function finds out if D might have non-external
4846 // linkage. Callers should verify at the end of the TU if it D has external
4847 // linkage or not.
4848 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4849
4850#include "clang/Sema/AttrIsTypeDependent.inc"
4851
4852 ///@}
4853
4854 //
4855 //
4856 // -------------------------------------------------------------------------
4857 //
4858 //
4859
4860 /// \name Declaration Attribute Handling
4861 /// Implementations are in SemaDeclAttr.cpp
4862 ///@{
4863
4864public:
4865 /// Describes the kind of priority given to an availability attribute.
4866 ///
4867 /// The sum of priorities deteremines the final priority of the attribute.
4868 /// The final priority determines how the attribute will be merged.
4869 /// An attribute with a lower priority will always remove higher priority
4870 /// attributes for the specified platform when it is being applied. An
4871 /// attribute with a higher priority will not be applied if the declaration
4872 /// already has an availability attribute with a lower priority for the
4873 /// specified platform. The final prirority values are not expected to match
4874 /// the values in this enumeration, but instead should be treated as a plain
4875 /// integer value. This enumeration just names the priority weights that are
4876 /// used to calculate that final vaue.
4878 /// The availability attribute was specified explicitly next to the
4879 /// declaration.
4881
4882 /// The availability attribute was applied using '#pragma clang attribute'.
4884
4885 /// The availability attribute for a specific platform was inferred from
4886 /// an availability attribute for another platform.
4888
4889 /// The availability attribute was inferred from an 'anyAppleOS'
4890 /// availability attribute.
4892
4893 /// The availability attribute was inferred from an 'anyAppleOS'
4894 /// availability attribute that was applied using '#pragma clang attribute'.
4895 /// This has the lowest priority.
4897 };
4898
4899 /// Describes the reason a calling convention specification was ignored, used
4900 /// for diagnostics.
4907
4908 /// A helper function to provide Attribute Location for the Attr types
4909 /// AND the ParsedAttr.
4910 template <typename AttrInfo>
4911 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
4912 getAttrLoc(const AttrInfo &AL) {
4913 return AL.getLocation();
4914 }
4916
4917 /// If Expr is a valid integer constant, get the value of the integer
4918 /// expression and return success or failure. May output an error.
4919 ///
4920 /// Negative argument is implicitly converted to unsigned, unless
4921 /// \p StrictlyUnsigned is true.
4922 template <typename AttrInfo>
4923 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
4924 unsigned Idx = UINT_MAX,
4925 bool StrictlyUnsigned = false) {
4926 std::optional<llvm::APSInt> I = llvm::APSInt(32);
4927 if (Expr->isTypeDependent() ||
4929 if (Idx != UINT_MAX)
4930 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
4931 << &AI << Idx << AANT_ArgumentIntegerConstant
4932 << Expr->getSourceRange();
4933 else
4934 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
4936 return false;
4937 }
4938
4939 if (!I->isIntN(32)) {
4940 Diag(Expr->getExprLoc(), diag::err_ice_too_large)
4941 << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
4942 return false;
4943 }
4944
4945 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
4946 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
4947 << &AI << /*non-negative*/ 1;
4948 return false;
4949 }
4950
4951 Val = (uint32_t)I->getZExtValue();
4952 return true;
4953 }
4954
4955 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
4956 /// \#pragma weak during processing of other Decls.
4957 /// I couldn't figure out a clean way to generate these in-line, so
4958 /// we store them here and handle separately -- which is a hack.
4959 /// It would be best to refactor this.
4961
4962 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
4964
4968
4969 /// ExtVectorDecls - This is a list all the extended vector types. This allows
4970 /// us to associate a raw vector type with one of the ext_vector type names.
4971 /// This is only necessary for issuing pretty diagnostics.
4973
4974 /// Check if the argument \p E is a ASCII string literal. If not emit an error
4975 /// and return false, otherwise set \p Str to the value of the string literal
4976 /// and return true.
4978 const Expr *E, StringRef &Str,
4979 SourceLocation *ArgLocation = nullptr);
4980
4981 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
4982 /// If not emit an error and return false. If the argument is an identifier it
4983 /// will emit an error with a fixit hint and treat it as if it was a string
4984 /// literal.
4985 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4986 StringRef &Str,
4987 SourceLocation *ArgLocation = nullptr);
4988
4989 /// Determine if type T is a valid subject for a nonnull and similar
4990 /// attributes. Dependent types are considered valid so they can be checked
4991 /// during instantiation time. By default, we look through references (the
4992 /// behavior used by nonnull), but if the second parameter is true, then we
4993 /// treat a reference type as valid.
4994 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4995
4996 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
4997 /// declaration.
4998 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4999 Expr *OE);
5000
5001 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
5002 /// declaration.
5003 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
5004 Expr *ParamExpr);
5005
5006 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
5007 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
5008
5009 AvailabilityAttr *
5011 const IdentifierInfo *Platform, bool Implicit,
5012 VersionTuple Introduced, VersionTuple Deprecated,
5013 VersionTuple Obsoleted, bool IsUnavailable,
5014 StringRef Message, bool IsStrict, StringRef Replacement,
5015 AvailabilityMergeKind AMK, int Priority,
5016 const IdentifierInfo *IIEnvironment,
5017 const IdentifierInfo *InferredPlatformII = nullptr);
5018
5019 AvailabilityAttr *mergeAndInferAvailabilityAttr(
5020 NamedDecl *D, const AttributeCommonInfo &CI,
5021 const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced,
5022 VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable,
5023 StringRef Message, bool IsStrict, StringRef Replacement,
5024 AvailabilityMergeKind AMK, int Priority,
5025 const IdentifierInfo *IIEnvironment,
5026 const IdentifierInfo *InferredPlatformII);
5027
5028 TypeVisibilityAttr *
5030 TypeVisibilityAttr::VisibilityType Vis);
5031 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5032 VisibilityAttr::VisibilityType Vis);
5034 VisibilityAttr::VisibilityType Type);
5035 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
5036 StringRef Name);
5037
5038 /// Used to implement to perform semantic checking on
5039 /// attribute((section("foo"))) specifiers.
5040 ///
5041 /// In this case, "foo" is passed in to be checked. If the section
5042 /// specifier is invalid, return an Error that indicates the problem.
5043 ///
5044 /// This is a simple quality of implementation feature to catch errors
5045 /// and give good diagnostics in cases when the assembler or code generator
5046 /// would otherwise reject the section specifier.
5047 llvm::Error isValidSectionSpecifier(StringRef Str);
5048 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
5049 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
5050 StringRef Name);
5051
5052 // Check for things we'd like to warn about. Multiversioning issues are
5053 // handled later in the process, once we know how many exist.
5054 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
5055
5056 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
5057 StringRef NewUserDiagnostic);
5058 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
5059 const IdentifierInfo *Format, int FormatIdx,
5060 int FirstArg);
5061 FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
5062 const AttributeCommonInfo &CI,
5063 const IdentifierInfo *Format,
5064 int FormatIdx,
5065 StringLiteral *FormatStr);
5066 ModularFormatAttr *mergeModularFormatAttr(Decl *D,
5067 const AttributeCommonInfo &CI,
5068 const IdentifierInfo *ModularImplFn,
5069 StringRef ImplName,
5071
5072 PersonalityAttr *mergePersonalityAttr(Decl *D, FunctionDecl *Routine,
5073 const AttributeCommonInfo &CI);
5074
5075 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5076 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5077 bool IsPackExpansion);
5079 bool IsPackExpansion);
5080
5081 /// AddAlignValueAttr - Adds an align_value attribute to a particular
5082 /// declaration.
5083 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
5084
5085 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
5086 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
5089
5091 bool BestCase,
5092 MSInheritanceModel SemanticSpelling);
5093
5095
5096 /// AddModeAttr - Adds a mode attribute to a particular declaration.
5097 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
5098 const IdentifierInfo *Name, bool InInstantiation = false);
5099 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
5100 const AttributeCommonInfo &CI,
5101 const IdentifierInfo *Ident);
5102 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
5103 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
5104 const AttributeCommonInfo &CI);
5105 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
5106 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
5107 const InternalLinkageAttr &AL);
5108
5109 /// Check validaty of calling convention attribute \p attr. If \p FD
5110 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
5111 /// target. Otherwise, it is specified by \p CFT.
5113 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
5115
5116 /// Checks a regparm attribute, returning true if it is ill-formed and
5117 /// otherwise setting numParams to the appropriate value.
5118 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
5119
5120 /// Create a CUDALaunchBoundsAttr attribute. By default, the function only
5121 /// supports nvptx target architectures and skips MaxBlocks if it is previous
5122 /// to sm_90. Use \p IgnoreArch to skip the architecture check.
5123 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
5124 Expr *MaxThreads,
5125 Expr *MinBlocks, Expr *MaxBlocks,
5126 bool IgnoreArch = false);
5127
5128 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
5129 /// declaration.
5130 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5131 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
5132
5133 /// Add a cluster_dims attribute to a particular declaration.
5134 CUDAClusterDimsAttr *createClusterDimsAttr(const AttributeCommonInfo &CI,
5135 Expr *X, Expr *Y, Expr *Z);
5136 void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
5137 Expr *Y, Expr *Z);
5138 /// Add a no_cluster attribute to a particular declaration.
5139 void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI);
5140
5141 enum class RetainOwnershipKind { NS, CF, OS };
5142
5143 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5144 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5145
5146 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5147
5148 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5149 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5150 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5151 const AttributeCommonInfo &CI,
5152 bool BestCase,
5153 MSInheritanceModel Model);
5154
5155 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5156 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5157 const EnforceTCBLeafAttr &AL);
5158
5159 /// Helper for delayed processing TransparentUnion or
5160 /// BPFPreserveAccessIndexAttr attribute.
5162 const ParsedAttributesView &AttrList);
5163
5164 // Options for ProcessDeclAttributeList().
5168
5171 Result.IncludeCXX11Attributes = Val;
5172 return Result;
5173 }
5174
5177 Result.IgnoreTypeAttributes = Val;
5178 return Result;
5179 }
5180
5181 // Should C++11 attributes be processed?
5183
5184 // Should any type attributes encountered be ignored?
5185 // If this option is false, a diagnostic will be emitted for any type
5186 // attributes of a kind that does not "slide" from the declaration to
5187 // the decl-specifier-seq.
5189 };
5190
5191 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5192 /// attribute list to the specified decl, ignoring any type attributes.
5194 const ParsedAttributesView &AttrList,
5195 const ProcessDeclAttributeOptions &Options =
5197
5198 /// Annotation attributes are the only attributes allowed after an access
5199 /// specifier.
5201 const ParsedAttributesView &AttrList);
5202
5203 /// checkUnusedDeclAttributes - Given a declarator which is not being
5204 /// used to build a declaration, complain about any decl attributes
5205 /// which might be lying around on it.
5207
5208 void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5209
5210 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5211 /// \#pragma weak needs a non-definition decl and source may not have one.
5213 SourceLocation Loc);
5214
5215 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5216 /// applied to it, possibly with an alias.
5217 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5218
5219 void ProcessPragmaWeak(Scope *S, Decl *D);
5220 // Decl attributes - this routine is the top level dispatcher.
5221 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5222
5224
5225 /// Given a set of delayed diagnostics, re-emit them as if they had
5226 /// been delayed in the current context instead of in the given pool.
5227 /// Essentially, this just moves them to the current pool.
5229
5230 /// Check that the type is a plain record with one field being a pointer
5231 /// type and the other field being an integer. This matches the common
5232 /// implementation of std::span or sized_allocation_t in P0901R11.
5233 bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty);
5234
5235 /// Check if IdxExpr is a valid parameter index for a function or
5236 /// instance method D. May output an error.
5237 ///
5238 /// \returns true if IdxExpr is a valid index.
5239 template <typename AttrInfo>
5241 const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5242 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5243 bool CanIndexVariadicArguments = false) {
5245
5246 // In C++ the implicit 'this' function parameter also counts.
5247 // Parameters are counted from one.
5248 bool HP = hasFunctionProto(D);
5249 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
5250 bool IV = HP && isFunctionOrMethodVariadic(D);
5251 unsigned NumParams =
5252 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
5253
5254 std::optional<llvm::APSInt> IdxInt;
5255 if (IdxExpr->isTypeDependent() ||
5256 !(IdxInt = IdxExpr->getIntegerConstantExpr(Context))) {
5257 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5258 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5259 << IdxExpr->getSourceRange();
5260 return false;
5261 }
5262
5263 constexpr unsigned Limit = 1 << ParamIdx::IdxBitWidth;
5264 unsigned IdxSource = IdxInt->getLimitedValue(Limit);
5265 if (IdxSource < 1 || IdxSource == Limit ||
5266 ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5267 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5268 << &AI << AttrArgNum << IdxExpr->getSourceRange();
5269 return false;
5270 }
5271 if (HasImplicitThisParam && !CanIndexImplicitThis) {
5272 if (IdxSource == 1) {
5273 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5274 << &AI << IdxExpr->getSourceRange();
5275 return false;
5276 }
5277 }
5278
5279 Idx = ParamIdx(IdxSource, D);
5280 return true;
5281 }
5282
5283 ///@}
5284
5285 //
5286 //
5287 // -------------------------------------------------------------------------
5288 //
5289 //
5290
5291 /// \name C++ Declarations
5292 /// Implementations are in SemaDeclCXX.cpp
5293 ///@{
5294
5295public:
5297
5298 /// Called before parsing a function declarator belonging to a function
5299 /// declaration.
5301 unsigned TemplateParameterDepth);
5302
5303 /// Called after parsing a function declarator belonging to a function
5304 /// declaration.
5306
5307 // Act on C++ namespaces
5309 SourceLocation NamespaceLoc,
5310 SourceLocation IdentLoc, IdentifierInfo *Ident,
5311 SourceLocation LBrace,
5312 const ParsedAttributesView &AttrList,
5313 UsingDirectiveDecl *&UsingDecl, bool IsNested);
5314
5315 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5316 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5317 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5318
5320
5321 /// Retrieve the special "std" namespace, which may require us to
5322 /// implicitly define the namespace.
5324
5326 EnumDecl *getStdAlignValT() const;
5327
5330 QualType AllocType, SourceLocation);
5331
5333 const IdentifierInfo *MemberOrBase);
5334
5336 /// The '<=>' operator was used in an expression and a builtin operator
5337 /// was selected.
5339 /// A defaulted 'operator<=>' needed the comparison category. This
5340 /// typically only applies to 'std::strong_ordering', due to the implicit
5341 /// fallback return value.
5343 };
5344
5345 /// Lookup the specified comparison category types in the standard
5346 /// library, an check the VarDecls possibly returned by the operator<=>
5347 /// builtins for that type.
5348 ///
5349 /// \return The type of the comparison category type corresponding to the
5350 /// specified Kind, or a null type if an error occurs
5352 SourceLocation Loc,
5354
5355 /// Tests whether Ty is an instance of std::initializer_list and, if
5356 /// it is and Element is not NULL, assigns the element type to Element.
5357 bool isStdInitializerList(QualType Ty, QualType *Element);
5358
5359 /// Tests whether Ty is an instance of std::type_identity and, if
5360 /// it is and TypeArgument is not NULL, assigns the element type to Element.
5361 /// If MalformedDecl is not null, and type_identity was ruled out due to being
5362 /// incorrectly structured despite having the correct name, the faulty Decl
5363 /// will be assigned to MalformedDecl.
5364 bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5365 const Decl **MalformedDecl = nullptr);
5366
5367 /// Looks for the std::initializer_list template and instantiates it
5368 /// with Element, or emits an error if it's not found.
5369 ///
5370 /// \returns The instantiated template, or null on error.
5372
5373 /// Looks for the std::type_identity template and instantiates it
5374 /// with Type, or returns a null type if type_identity has not been declared
5375 ///
5376 /// \returns The instantiated template, or null if std::type_identity is not
5377 /// declared
5379
5380 /// Determine whether Ctor is an initializer-list constructor, as
5381 /// defined in [dcl.init.list]p2.
5382 bool isInitListConstructor(const FunctionDecl *Ctor);
5383
5384 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5385 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5386 SourceLocation IdentLoc,
5387 IdentifierInfo *NamespcName,
5388 const ParsedAttributesView &AttrList);
5389
5391
5392 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5393 SourceLocation AliasLoc, IdentifierInfo *Alias,
5394 CXXScopeSpec &SS, SourceLocation IdentLoc,
5395 IdentifierInfo *Ident);
5396
5397 /// Remove decls we can't actually see from a lookup being used to declare
5398 /// shadow using decls.
5399 ///
5400 /// \param S - The scope of the potential shadow decl
5401 /// \param Previous - The lookup of a potential shadow decl's name.
5402 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5403
5404 /// Hides a using shadow declaration. This is required by the current
5405 /// using-decl implementation when a resolvable using declaration in a
5406 /// class is followed by a declaration which would hide or override
5407 /// one or more of the using decl's targets; for example:
5408 ///
5409 /// struct Base { void foo(int); };
5410 /// struct Derived : Base {
5411 /// using Base::foo;
5412 /// void foo(int);
5413 /// };
5414 ///
5415 /// The governing language is C++03 [namespace.udecl]p12:
5416 ///
5417 /// When a using-declaration brings names from a base class into a
5418 /// derived class scope, member functions in the derived class
5419 /// override and/or hide member functions with the same name and
5420 /// parameter types in a base class (rather than conflicting).
5421 ///
5422 /// There are two ways to implement this:
5423 /// (1) optimistically create shadow decls when they're not hidden
5424 /// by existing declarations, or
5425 /// (2) don't create any shadow decls (or at least don't make them
5426 /// visible) until we've fully parsed/instantiated the class.
5427 /// The problem with (1) is that we might have to retroactively remove
5428 /// a shadow decl, which requires several O(n) operations because the
5429 /// decl structures are (very reasonably) not designed for removal.
5430 /// (2) avoids this but is very fiddly and phase-dependent.
5431 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5432
5433 /// Determines whether to create a using shadow decl for a particular
5434 /// decl, given the set of decls existing prior to this using lookup.
5436 const LookupResult &PreviousDecls,
5437 UsingShadowDecl *&PrevShadow);
5438
5439 /// Builds a shadow declaration corresponding to a 'using' declaration.
5442 UsingShadowDecl *PrevDecl);
5443
5444 /// Checks that the given using declaration is not an invalid
5445 /// redeclaration. Note that this is checking only for the using decl
5446 /// itself, not for any ill-formedness among the UsingShadowDecls.
5448 bool HasTypenameKeyword,
5449 const CXXScopeSpec &SS,
5450 SourceLocation NameLoc,
5451 const LookupResult &Previous);
5452
5453 /// Checks that the given nested-name qualifier used in a using decl
5454 /// in the current context is appropriately related to the current
5455 /// scope. If an error is found, diagnoses it and returns true.
5456 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5457 /// the result of that lookup. UD is likewise nullptr, except when we have an
5458 /// already-populated UsingDecl whose shadow decls contain the same
5459 /// information (i.e. we're instantiating a UsingDecl with non-dependent
5460 /// scope).
5461 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5462 const CXXScopeSpec &SS,
5463 const DeclarationNameInfo &NameInfo,
5464 SourceLocation NameLoc,
5465 const LookupResult *R = nullptr,
5466 const UsingDecl *UD = nullptr);
5467
5468 /// Builds a using declaration.
5469 ///
5470 /// \param IsInstantiation - Whether this call arises from an
5471 /// instantiation of an unresolved using declaration. We treat
5472 /// the lookup differently for these declarations.
5474 SourceLocation UsingLoc,
5475 bool HasTypenameKeyword,
5476 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5477 DeclarationNameInfo NameInfo,
5478 SourceLocation EllipsisLoc,
5479 const ParsedAttributesView &AttrList,
5480 bool IsInstantiation, bool IsUsingIfExists);
5482 SourceLocation UsingLoc,
5483 SourceLocation EnumLoc,
5484 SourceLocation NameLoc,
5485 TypeSourceInfo *EnumType, EnumDecl *ED);
5486 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5487 ArrayRef<NamedDecl *> Expansions);
5488
5489 /// Additional checks for a using declaration referring to a constructor name.
5491
5492 /// Given a derived-class using shadow declaration for a constructor and the
5493 /// correspnding base class constructor, find or create the implicit
5494 /// synthesized derived class constructor to use for this initialization.
5497 ConstructorUsingShadowDecl *DerivedShadow);
5498
5500 SourceLocation UsingLoc,
5501 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5502 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5503 const ParsedAttributesView &AttrList);
5505 SourceLocation UsingLoc,
5506 SourceLocation EnumLoc, SourceRange TyLoc,
5507 const IdentifierInfo &II, ParsedType Ty,
5508 const CXXScopeSpec &SS);
5510 MultiTemplateParamsArg TemplateParams,
5511 SourceLocation UsingLoc, UnqualifiedId &Name,
5512 const ParsedAttributesView &AttrList,
5513 TypeResult Type, Decl *DeclFromDeclSpec);
5514
5515 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5516 /// including handling of its default argument expressions.
5517 ///
5518 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5520 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5522 bool HadMultipleCandidates, bool IsListInitialization,
5523 bool IsStdInitListInitialization, bool RequiresZeroInit,
5524 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5525
5526 /// Build a CXXConstructExpr whose constructor has already been resolved if
5527 /// it denotes an inherited constructor.
5529 SourceLocation ConstructLoc, QualType DeclInitType,
5530 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5531 bool HadMultipleCandidates, bool IsListInitialization,
5532 bool IsStdInitListInitialization, bool RequiresZeroInit,
5533 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5534
5535 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5536 // the constructor can be elidable?
5538 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5539 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5540 bool HadMultipleCandidates, bool IsListInitialization,
5541 bool IsStdInitListInitialization, bool RequiresZeroInit,
5542 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5543
5545 SourceLocation InitLoc);
5546
5547 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5548 /// constructed variable.
5549 void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit);
5550
5551 /// Helper class that collects exception specifications for
5552 /// implicitly-declared special member functions.
5554 // Pointer to allow copying
5555 Sema *Self;
5556 // We order exception specifications thus:
5557 // noexcept is the most restrictive, but is only used in C++11.
5558 // throw() comes next.
5559 // Then a throw(collected exceptions)
5560 // Finally no specification, which is expressed as noexcept(false).
5561 // throw(...) is used instead if any called function uses it.
5562 ExceptionSpecificationType ComputedEST;
5563 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5564 SmallVector<QualType, 4> Exceptions;
5565
5566 void ClearExceptions() {
5567 ExceptionsSeen.clear();
5568 Exceptions.clear();
5569 }
5570
5571 public:
5573 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5574 if (!Self.getLangOpts().CPlusPlus11)
5575 ComputedEST = EST_DynamicNone;
5576 }
5577
5578 /// Get the computed exception specification type.
5580 assert(!isComputedNoexcept(ComputedEST) &&
5581 "noexcept(expr) should not be a possible result");
5582 return ComputedEST;
5583 }
5584
5585 /// The number of exceptions in the exception specification.
5586 unsigned size() const { return Exceptions.size(); }
5587
5588 /// The set of exceptions in the exception specification.
5589 const QualType *data() const { return Exceptions.data(); }
5590
5591 /// Integrate another called method into the collected data.
5592 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5593
5594 /// Integrate an invoked expression into the collected data.
5595 void CalledExpr(Expr *E) { CalledStmt(E); }
5596
5597 /// Integrate an invoked statement into the collected data.
5598 void CalledStmt(Stmt *S);
5599
5600 /// Overwrite an EPI's exception specification with this
5601 /// computed exception specification.
5604 ESI.Type = getExceptionSpecType();
5605 if (ESI.Type == EST_Dynamic) {
5606 ESI.Exceptions = Exceptions;
5607 } else if (ESI.Type == EST_None) {
5608 /// C++11 [except.spec]p14:
5609 /// The exception-specification is noexcept(false) if the set of
5610 /// potential exceptions of the special member function contains "any"
5611 ESI.Type = EST_NoexceptFalse;
5612 ESI.NoexceptExpr =
5613 Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get();
5614 }
5615 return ESI;
5616 }
5617 };
5618
5619 /// Evaluate the implicit exception specification for a defaulted
5620 /// special member function.
5622
5623 /// Check the given exception-specification and update the
5624 /// exception specification information with the results.
5625 void checkExceptionSpecification(bool IsTopLevel,
5627 ArrayRef<ParsedType> DynamicExceptions,
5628 ArrayRef<SourceRange> DynamicExceptionRanges,
5629 Expr *NoexceptExpr,
5630 SmallVectorImpl<QualType> &Exceptions,
5632
5633 /// Add an exception-specification to the given member or friend function
5634 /// (or function template). The exception-specification was parsed
5635 /// after the function itself was declared.
5637 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5638 ArrayRef<ParsedType> DynamicExceptions,
5639 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5640
5641 class InheritedConstructorInfo;
5642
5643 /// Determine if a special member function should have a deleted
5644 /// definition when it is defaulted.
5646 InheritedConstructorInfo *ICI = nullptr,
5647 bool Diagnose = false);
5648
5649 /// Produce notes explaining why a defaulted function was defined as deleted.
5651
5652 /// Declare the implicit default constructor for the given class.
5653 ///
5654 /// \param ClassDecl The class declaration into which the implicit
5655 /// default constructor will be added.
5656 ///
5657 /// \returns The implicitly-declared default constructor.
5660
5661 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5662 /// defining this constructor as the default constructor.
5665
5666 /// Declare the implicit destructor for the given class.
5667 ///
5668 /// \param ClassDecl The class declaration into which the implicit
5669 /// destructor will be added.
5670 ///
5671 /// \returns The implicitly-declared destructor.
5673
5674 /// DefineImplicitDestructor - Checks for feasibility of
5675 /// defining this destructor as the default destructor.
5676 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5678
5679 /// Build an exception spec for destructors that don't have one.
5680 ///
5681 /// C++11 says that user-defined destructors with no exception spec get one
5682 /// that looks as if the destructor was implicitly declared.
5684
5685 /// Define the specified inheriting constructor.
5688
5689 /// Declare the implicit copy constructor for the given class.
5690 ///
5691 /// \param ClassDecl The class declaration into which the implicit
5692 /// copy constructor will be added.
5693 ///
5694 /// \returns The implicitly-declared copy constructor.
5696
5697 /// DefineImplicitCopyConstructor - Checks for feasibility of
5698 /// defining this constructor as the copy constructor.
5699 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5701
5702 /// Declare the implicit move constructor for the given class.
5703 ///
5704 /// \param ClassDecl The Class declaration into which the implicit
5705 /// move constructor will be added.
5706 ///
5707 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5708 /// declared.
5710
5711 /// DefineImplicitMoveConstructor - Checks for feasibility of
5712 /// defining this constructor as the move constructor.
5713 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5715
5716 /// Declare the implicit copy assignment operator for the given class.
5717 ///
5718 /// \param ClassDecl The class declaration into which the implicit
5719 /// copy assignment operator will be added.
5720 ///
5721 /// \returns The implicitly-declared copy assignment operator.
5723
5724 /// Defines an implicitly-declared copy assignment operator.
5725 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5726 CXXMethodDecl *MethodDecl);
5727
5728 /// Declare the implicit move assignment operator for the given class.
5729 ///
5730 /// \param ClassDecl The Class declaration into which the implicit
5731 /// move assignment operator will be added.
5732 ///
5733 /// \returns The implicitly-declared move assignment operator, or NULL if it
5734 /// wasn't declared.
5736
5737 /// Defines an implicitly-declared move assignment operator.
5738 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5739 CXXMethodDecl *MethodDecl);
5740
5741 /// Check a completed declaration of an implicit special member.
5743
5744 /// Determine whether the given function is an implicitly-deleted
5745 /// special member function.
5747
5748 /// Check whether 'this' shows up in the type of a static member
5749 /// function after the (naturally empty) cv-qualifier-seq would be.
5750 ///
5751 /// \returns true if an error occurred.
5753
5754 /// Whether this' shows up in the exception specification of a static
5755 /// member function.
5757
5758 /// Check whether 'this' shows up in the attributes of the given
5759 /// static member function.
5760 ///
5761 /// \returns true if an error occurred.
5763
5765 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5766
5768
5769 /// Given a constructor and the set of arguments provided for the
5770 /// constructor, convert the arguments and add any required default arguments
5771 /// to form a proper call to this constructor.
5772 ///
5773 /// \returns true if an error occurred, false otherwise.
5775 QualType DeclInitType, MultiExprArg ArgsPtr,
5776 SourceLocation Loc,
5777 SmallVectorImpl<Expr *> &ConvertedArgs,
5778 bool AllowExplicit = false,
5779 bool IsListInitialization = false);
5780
5781 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5782 /// initializer for the declaration 'Dcl'.
5783 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5784 /// static data member of class X, names should be looked up in the scope of
5785 /// class X.
5787
5788 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5789 /// initializer for the declaration 'Dcl'.
5790 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5791
5792 /// Define the "body" of the conversion from a lambda object to a
5793 /// function pointer.
5794 ///
5795 /// This routine doesn't actually define a sensible body; rather, it fills
5796 /// in the initialization expression needed to copy the lambda object into
5797 /// the block, and IR generation actually generates the real body of the
5798 /// block pointer conversion.
5799 void
5801 CXXConversionDecl *Conv);
5802
5803 /// Define the "body" of the conversion from a lambda object to a
5804 /// block pointer.
5805 ///
5806 /// This routine doesn't actually define a sensible body; rather, it fills
5807 /// in the initialization expression needed to copy the lambda object into
5808 /// the block, and IR generation actually generates the real body of the
5809 /// block pointer conversion.
5811 CXXConversionDecl *Conv);
5812
5813 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5814 /// linkage specification, including the language and (if present)
5815 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5816 /// language string literal. LBraceLoc, if valid, provides the location of
5817 /// the '{' brace. Otherwise, this linkage specification does not
5818 /// have any braces.
5820 Expr *LangStr, SourceLocation LBraceLoc);
5821
5822 /// ActOnFinishLinkageSpecification - Complete the definition of
5823 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5824 /// valid, it's the position of the closing '}' brace in a linkage
5825 /// specification that uses braces.
5827 SourceLocation RBraceLoc);
5828
5829 //===--------------------------------------------------------------------===//
5830 // C++ Classes
5831 //
5832
5833 /// Get the class that is directly named by the current context. This is the
5834 /// class for which an unqualified-id in this scope could name a constructor
5835 /// or destructor.
5836 ///
5837 /// If the scope specifier denotes a class, this will be that class.
5838 /// If the scope specifier is empty, this will be the class whose
5839 /// member-specification we are currently within. Otherwise, there
5840 /// is no such class.
5842
5843 /// isCurrentClassName - Determine whether the identifier II is the
5844 /// name of the class type currently being defined. In the case of
5845 /// nested classes, this will only return true if II is the name of
5846 /// the innermost class.
5847 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5848 const CXXScopeSpec *SS = nullptr);
5849
5850 /// Determine whether the identifier II is a typo for the name of
5851 /// the class type currently being defined. If so, update it to the identifier
5852 /// that should have been used.
5854
5855 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5857 SourceLocation ColonLoc,
5858 const ParsedAttributesView &Attrs);
5859
5860 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5861 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5862 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
5863 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
5864 /// present (but parsing it has been deferred).
5865 NamedDecl *
5867 MultiTemplateParamsArg TemplateParameterLists,
5868 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5869 InClassInitStyle InitStyle);
5870
5871 /// Enter a new C++ default initializer scope. After calling this, the
5872 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
5873 /// parsing or instantiating the initializer failed.
5875
5876 /// This is invoked after parsing an in-class initializer for a
5877 /// non-static C++ class member, and after instantiating an in-class
5878 /// initializer in a class template. Such actions are deferred until the class
5879 /// is complete.
5881 SourceLocation EqualLoc,
5883
5884 /// Handle a C++ member initializer using parentheses syntax.
5886 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
5887 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
5888 const DeclSpec &DS, SourceLocation IdLoc,
5889 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
5890 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
5891
5892 /// Handle a C++ member initializer using braced-init-list syntax.
5893 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
5894 CXXScopeSpec &SS,
5895 IdentifierInfo *MemberOrBase,
5896 ParsedType TemplateTypeTy,
5897 const DeclSpec &DS, SourceLocation IdLoc,
5898 Expr *InitList, SourceLocation EllipsisLoc);
5899
5900 /// Handle a C++ member initializer.
5901 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
5902 CXXScopeSpec &SS,
5903 IdentifierInfo *MemberOrBase,
5904 ParsedType TemplateTypeTy,
5905 const DeclSpec &DS, SourceLocation IdLoc,
5906 Expr *Init, SourceLocation EllipsisLoc);
5907
5909 SourceLocation IdLoc);
5910
5912 TypeSourceInfo *BaseTInfo, Expr *Init,
5913 CXXRecordDecl *ClassDecl,
5914 SourceLocation EllipsisLoc);
5915
5917 CXXRecordDecl *ClassDecl);
5918
5921
5923 ArrayRef<CXXCtorInitializer *> Initializers = {});
5924
5925 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5926 /// mark all the non-trivial destructors of its members and bases as
5927 /// referenced.
5928 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5929 CXXRecordDecl *Record);
5930
5931 /// Mark destructors of virtual bases of this class referenced. In the Itanium
5932 /// C++ ABI, this is done when emitting a destructor for any non-abstract
5933 /// class. In the Microsoft C++ ABI, this is done any time a class's
5934 /// destructor is referenced.
5936 SourceLocation Location, CXXRecordDecl *ClassDecl,
5937 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
5938 nullptr);
5939
5940 /// Do semantic checks to allow the complete destructor variant to be emitted
5941 /// when the destructor is defined in another translation unit. In the Itanium
5942 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
5943 /// can be emitted in separate TUs. To emit the complete variant, run a subset
5944 /// of the checks performed when emitting a regular destructor.
5945 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
5946 CXXDestructorDecl *Dtor);
5947
5948 /// The list of classes whose vtables have been used within
5949 /// this translation unit, and the source locations at which the
5950 /// first use occurred.
5951 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
5952
5953 /// The list of vtables that are required but have not yet been
5954 /// materialized.
5956
5957 /// The set of classes whose vtables have been used within
5958 /// this translation unit, and a bit that will be true if the vtable is
5959 /// required to be emitted (otherwise, it should be emitted only if needed
5960 /// by code generation).
5961 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5962
5963 /// Load any externally-stored vtable uses.
5965
5966 /// Note that the vtable for the given class was used at the
5967 /// given location.
5969 bool DefinitionRequired = false);
5970
5971 /// Mark the exception specifications of all virtual member functions
5972 /// in the given class as needed.
5974 const CXXRecordDecl *RD);
5975
5976 /// MarkVirtualMembersReferenced - Will mark all members of the given
5977 /// CXXRecordDecl referenced.
5979 bool ConstexprOnly = false);
5980
5981 /// Define all of the vtables that have been used in this
5982 /// translation unit and reference any virtual members used by those
5983 /// vtables.
5984 ///
5985 /// \returns true if any work was done, false otherwise.
5986 bool DefineUsedVTables();
5987
5988 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5989 /// special functions, such as the default constructor, copy
5990 /// constructor, or destructor, to the given C++ class (C++
5991 /// [special]p1). This routine can only be executed just before the
5992 /// definition of the class is complete.
5994
5995 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5996 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
5998 bool AnyErrors);
5999
6000 /// Check class-level dllimport/dllexport attribute. The caller must
6001 /// ensure that referenceDLLExportedClassMethods is called some point later
6002 /// when all outer classes of Class are complete.
6005
6007
6008 /// Perform propagation of DLL attributes from a derived class to a
6009 /// templated base class for MS compatibility.
6011 CXXRecordDecl *Class, Attr *ClassAttr,
6012 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6013 SourceLocation BaseLoc);
6014
6015 /// Perform semantic checks on a class definition that has been
6016 /// completing, introducing implicitly-declared members, checking for
6017 /// abstract types, etc.
6018 ///
6019 /// \param S The scope in which the class was parsed. Null if we didn't just
6020 /// parse a class definition.
6021 /// \param Record The completed class.
6023
6024 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6025 /// conditions that are needed for the attribute to have an effect.
6027
6028 /// Check that VTable Pointer authentication is only being set on the first
6029 /// first instantiation of the vtable
6031
6033 Decl *TagDecl, SourceLocation LBrac,
6034 SourceLocation RBrac,
6035 const ParsedAttributesView &AttrList);
6036
6037 /// Perform any semantic analysis which needs to be delayed until all
6038 /// pending class member declarations have been parsed.
6041
6042 /// This is used to implement the constant expression evaluation part of the
6043 /// attribute enable_if extension. There is nothing in standard C++ which
6044 /// would require reentering parameters.
6047 llvm::function_ref<Scope *()> EnterScope);
6049
6050 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6051 /// parsing a top-level (non-nested) C++ class, and we are now
6052 /// parsing those parts of the given Method declaration that could
6053 /// not be parsed earlier (C++ [class.mem]p2), such as default
6054 /// arguments. This action should enter the scope of the given
6055 /// Method declaration as if we had just parsed the qualified method
6056 /// name. However, it should not bring the parameters into scope;
6057 /// that will be performed by ActOnDelayedCXXMethodParameter.
6059 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6061
6062 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6063 /// processing the delayed method declaration for Method. The method
6064 /// declaration is now considered finished. There may be a separate
6065 /// ActOnStartOfFunctionDef action later (not necessarily
6066 /// immediately!) for this method, if it was also defined inside the
6067 /// class body.
6070
6072
6073 bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
6074 StringEvaluationContext EvalContext,
6075 bool ErrorOnInvalidMessage);
6076 bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
6077 StringEvaluationContext EvalContext,
6078 bool ErrorOnInvalidMessage);
6079
6081 Expr *AssertExpr, Expr *AssertMessageExpr,
6082 SourceLocation RParenLoc);
6084 Expr *AssertExpr, Expr *AssertMessageExpr,
6085 SourceLocation RParenLoc, bool Failed);
6086
6087 /// Try to print more useful information about a failed static_assert
6088 /// with expression \E
6089 void DiagnoseStaticAssertDetails(const Expr *E);
6090
6091 /// If E represents a built-in type trait, or a known standard type trait,
6092 /// try to print more information about why the type type-trait failed.
6093 /// This assumes we already evaluated the expression to a false boolean value.
6094 void DiagnoseTypeTraitDetails(const Expr *E);
6095
6096 /// Handle a friend type declaration. This works in tandem with
6097 /// ActOnTag.
6098 ///
6099 /// Notes on friend class templates:
6100 ///
6101 /// We generally treat friend class declarations as if they were
6102 /// declaring a class. So, for example, the elaborated type specifier
6103 /// in a friend declaration is required to obey the restrictions of a
6104 /// class-head (i.e. no typedefs in the scope chain), template
6105 /// parameters are required to match up with simple template-ids, &c.
6106 /// However, unlike when declaring a template specialization, it's
6107 /// okay to refer to a template specialization without an empty
6108 /// template parameter declaration, e.g.
6109 /// friend class A<T>::B<unsigned>;
6110 /// We permit this as a special case; if there are any template
6111 /// parameters present at all, require proper matching, i.e.
6112 /// template <> template <class T> friend class A<int>::B;
6113 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6114 MultiTemplateParamsArg TemplateParams,
6115 SourceLocation EllipsisLoc);
6117 MultiTemplateParamsArg TemplateParams);
6118
6119 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6120 /// the well-formedness of the constructor declarator @p D with type @p
6121 /// R. If there are any errors in the declarator, this routine will
6122 /// emit diagnostics and set the invalid bit to true. In any case, the type
6123 /// will be updated to reflect a well-formed type for the constructor and
6124 /// returned.
6126 StorageClass &SC);
6127
6128 /// CheckConstructor - Checks a fully-formed constructor for
6129 /// well-formedness, issuing any diagnostics required. Returns true if
6130 /// the constructor declarator is invalid.
6132
6133 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6134 /// the well-formednes of the destructor declarator @p D with type @p
6135 /// R. If there are any errors in the declarator, this routine will
6136 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6137 /// will be updated to reflect a well-formed type for the destructor and
6138 /// returned.
6140 StorageClass &SC);
6141
6142 /// CheckDestructor - Checks a fully-formed destructor definition for
6143 /// well-formedness, issuing any diagnostics required. Returns true
6144 /// on error.
6146
6147 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6148 /// well-formednes of the conversion function declarator @p D with
6149 /// type @p R. If there are any errors in the declarator, this routine
6150 /// will emit diagnostics and return true. Otherwise, it will return
6151 /// false. Either way, the type @p R will be updated to reflect a
6152 /// well-formed type for the conversion operator.
6154
6155 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6156 /// the declaration of the given C++ conversion function. This routine
6157 /// is responsible for recording the conversion function in the C++
6158 /// class, if possible.
6160
6161 /// Check the validity of a declarator that we parsed for a deduction-guide.
6162 /// These aren't actually declarators in the grammar, so we need to check that
6163 /// the user didn't specify any pieces that are not part of the
6164 /// deduction-guide grammar. Return true on invalid deduction-guide.
6166 StorageClass &SC);
6167
6169
6172 SourceLocation DefaultLoc);
6174
6175 /// Kinds of defaulted comparison operator functions.
6176 enum class DefaultedComparisonKind : unsigned char {
6177 /// This is not a defaultable comparison operator.
6179 /// This is an operator== that should be implemented as a series of
6180 /// subobject comparisons.
6182 /// This is an operator<=> that should be implemented as a series of
6183 /// subobject comparisons.
6185 /// This is an operator!= that should be implemented as a rewrite in terms
6186 /// of a == comparison.
6188 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
6189 /// terms of a <=> comparison.
6191 };
6192
6196 FunctionDecl *Spaceship);
6199
6201 QualType R, bool IsLambda,
6202 DeclContext *DC = nullptr);
6204 DeclarationName Name, QualType R);
6206
6207 //===--------------------------------------------------------------------===//
6208 // C++ Derived Classes
6209 //
6210
6211 /// Check the validity of a C++ base class specifier.
6212 ///
6213 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6214 /// and returns NULL otherwise.
6216 SourceRange SpecifierRange, bool Virtual,
6217 AccessSpecifier Access,
6218 TypeSourceInfo *TInfo,
6219 SourceLocation EllipsisLoc);
6220
6221 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6222 /// one entry in the base class list of a class specifier, for
6223 /// example:
6224 /// class foo : public bar, virtual private baz {
6225 /// 'public bar' and 'virtual private baz' are each base-specifiers.
6226 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6227 const ParsedAttributesView &Attrs, bool Virtual,
6228 AccessSpecifier Access, ParsedType basetype,
6229 SourceLocation BaseLoc,
6230 SourceLocation EllipsisLoc);
6231
6232 /// Performs the actual work of attaching the given base class
6233 /// specifiers to a C++ class.
6236
6237 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6238 /// class, after checking whether there are any duplicate base
6239 /// classes.
6240 void ActOnBaseSpecifiers(Decl *ClassDecl,
6242
6243 /// Determine whether the type \p Derived is a C++ class that is
6244 /// derived from the type \p Base.
6245 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6247 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6251 CXXBasePaths &Paths);
6252
6253 // FIXME: I don't like this name.
6254 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6255
6257 SourceLocation Loc, SourceRange Range,
6258 CXXCastPath *BasePath = nullptr,
6259 bool IgnoreAccess = false);
6260
6261 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6262 /// conversion (where Derived and Base are class types) is
6263 /// well-formed, meaning that the conversion is unambiguous (and
6264 /// that all of the base classes are accessible). Returns true
6265 /// and emits a diagnostic if the code is ill-formed, returns false
6266 /// otherwise. Loc is the location where this routine should point to
6267 /// if there is an error, and Range is the source range to highlight
6268 /// if there is an error.
6269 ///
6270 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6271 /// diagnostic for the respective type of error will be suppressed, but the
6272 /// check for ill-formed code will still be performed.
6274 unsigned InaccessibleBaseID,
6275 unsigned AmbiguousBaseConvID,
6276 SourceLocation Loc, SourceRange Range,
6277 DeclarationName Name, CXXCastPath *BasePath,
6278 bool IgnoreAccess = false);
6279
6280 /// Builds a string representing ambiguous paths from a
6281 /// specific derived class to different subobjects of the same base
6282 /// class.
6283 ///
6284 /// This function builds a string that can be used in error messages
6285 /// to show the different paths that one can take through the
6286 /// inheritance hierarchy to go from the derived class to different
6287 /// subobjects of a base class. The result looks something like this:
6288 /// @code
6289 /// struct D -> struct B -> struct A
6290 /// struct D -> struct C -> struct A
6291 /// @endcode
6292 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6293
6295 const CXXMethodDecl *Old);
6296
6297 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6298 /// covariant, according to C++ [class.virtual]p5.
6300 const CXXMethodDecl *Old);
6301
6302 // Check that the overriding method has no explicit object parameter.
6304 const CXXMethodDecl *Old);
6305
6306 /// Mark the given method pure.
6307 ///
6308 /// \param Method the method to be marked pure.
6309 ///
6310 /// \param InitRange the source range that covers the "0" initializer.
6312
6313 /// CheckOverrideControl - Check C++11 override control semantics.
6315
6316 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6317 /// not used in the declaration of an overriding method.
6319
6320 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6321 /// function overrides a virtual member function marked 'final', according to
6322 /// C++11 [class.virtual]p4.
6324 const CXXMethodDecl *Old);
6325
6336
6337 struct TypeDiagnoser;
6338
6341 TypeDiagnoser &Diagnoser);
6342 template <typename... Ts>
6344 const Ts &...Args) {
6345 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6346 return RequireNonAbstractType(Loc, T, Diagnoser);
6347 }
6348
6349 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6350
6351 //===--------------------------------------------------------------------===//
6352 // C++ Overloaded Operators [C++ 13.5]
6353 //
6354
6355 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6356 /// of this overloaded operator is well-formed. If so, returns false;
6357 /// otherwise, emits appropriate diagnostics and returns true.
6359
6360 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6361 /// of this literal operator function is well-formed. If so, returns
6362 /// false; otherwise, emits appropriate diagnostics and returns true.
6364
6365 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6366 /// found in an explicit(bool) specifier.
6368
6369 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6370 /// Returns true if the explicit specifier is now resolved.
6372
6373 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6374 /// C++ if/switch/while/for statement.
6375 /// e.g: "if (int x = f()) {...}"
6377
6378 // Emitting members of dllexported classes is delayed until the class
6379 // (including field initializers) is fully parsed.
6382
6383 /// Merge the exception specifications of two variable declarations.
6384 ///
6385 /// This is called when there's a redeclaration of a VarDecl. The function
6386 /// checks if the redeclaration might have an exception specification and
6387 /// validates compatibility and merges the specs if necessary.
6389
6390 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6391 /// function, once we already know that they have the same
6392 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6393 /// error, false otherwise.
6395
6396 /// Helpers for dealing with blocks and functions.
6398
6399 /// CheckExtraCXXDefaultArguments - Check for any extra default
6400 /// arguments in the declarator, which is not a function declaration
6401 /// or definition and therefore is not permitted to have default
6402 /// arguments. This routine should be invoked for every declarator
6403 /// that is not a function declaration or definition.
6405
6409
6410 /// Perform semantic analysis for the variable declaration that
6411 /// occurs within a C++ catch clause, returning the newly-created
6412 /// variable.
6414 SourceLocation StartLoc,
6415 SourceLocation IdLoc,
6416 const IdentifierInfo *Id);
6417
6418 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6419 /// handler.
6421
6423
6424 /// Handle a friend tag declaration where the scope specifier was
6425 /// templated.
6427 unsigned TagSpec, SourceLocation TagLoc,
6428 CXXScopeSpec &SS, IdentifierInfo *Name,
6429 SourceLocation NameLoc,
6430 SourceLocation EllipsisLoc,
6432 MultiTemplateParamsArg TempParamLists);
6433
6435 SourceLocation DeclStart, Declarator &D,
6436 Expr *BitfieldWidth,
6437 InClassInitStyle InitStyle,
6438 AccessSpecifier AS,
6439 const ParsedAttr &MSPropertyAttr);
6440
6441 /// Diagnose why the specified class does not have a trivial special member of
6442 /// the given kind.
6445
6446 /// Determine whether a defaulted or deleted special member function is
6447 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6448 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6452 bool Diagnose = false);
6453
6454 /// For a defaulted function, the kind of defaulted function that it is.
6456 LLVM_PREFERRED_TYPE(CXXSpecialMemberKind)
6457 unsigned SpecialMember : 8;
6458 unsigned Comparison : 8;
6459
6460 public:
6462 : SpecialMember(llvm::to_underlying(CXXSpecialMemberKind::Invalid)),
6463 Comparison(llvm::to_underlying(DefaultedComparisonKind::None)) {}
6465 : SpecialMember(llvm::to_underlying(CSM)),
6466 Comparison(llvm::to_underlying(DefaultedComparisonKind::None)) {}
6468 : SpecialMember(llvm::to_underlying(CXXSpecialMemberKind::Invalid)),
6469 Comparison(llvm::to_underlying(Comp)) {}
6470
6471 bool isSpecialMember() const {
6472 return static_cast<CXXSpecialMemberKind>(SpecialMember) !=
6474 }
6475 bool isComparison() const {
6476 return static_cast<DefaultedComparisonKind>(Comparison) !=
6478 }
6479
6480 explicit operator bool() const {
6481 return isSpecialMember() || isComparison();
6482 }
6483
6485 return static_cast<CXXSpecialMemberKind>(SpecialMember);
6486 }
6488 return static_cast<DefaultedComparisonKind>(Comparison);
6489 }
6490
6491 /// Get the index of this function kind for use in diagnostics.
6492 unsigned getDiagnosticIndex() const {
6493 static_assert(llvm::to_underlying(CXXSpecialMemberKind::Invalid) >
6494 llvm::to_underlying(CXXSpecialMemberKind::Destructor),
6495 "invalid should have highest index");
6496 static_assert((unsigned)DefaultedComparisonKind::None == 0,
6497 "none should be equal to zero");
6498 return SpecialMember + Comparison;
6499 }
6500 };
6501
6502 /// Determine the kind of defaulting that would be done for a given function.
6503 ///
6504 /// If the function is both a default constructor and a copy / move
6505 /// constructor (due to having a default argument for the first parameter),
6506 /// this picks CXXSpecialMemberKind::DefaultConstructor.
6507 ///
6508 /// FIXME: Check that case is properly handled by all callers.
6509 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
6510
6511 /// Handle a C++11 empty-declaration and attribute-declaration.
6513 SourceLocation SemiLoc);
6514
6516 /// Diagnose issues that are non-constant or that are extensions.
6518 /// Identify whether this function satisfies the formal rules for constexpr
6519 /// functions in the current lanugage mode (with no extensions).
6521 };
6522
6523 // Check whether a function declaration satisfies the requirements of a
6524 // constexpr function definition or a constexpr constructor definition. If so,
6525 // return true. If not, produce appropriate diagnostics (unless asked not to
6526 // by Kind) and return false.
6527 //
6528 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6530 CheckConstexprKind Kind);
6531
6532 /// Diagnose methods which overload virtual methods in a base class
6533 /// without overriding any.
6535
6536 /// Check if a method overloads virtual methods in a base class without
6537 /// overriding any.
6538 void
6540 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6541 void
6543 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6544
6545 /// ActOnParamDefaultArgument - Check whether the default argument
6546 /// provided for a function parameter is well-formed. If so, attach it
6547 /// to the parameter declaration.
6548 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6549 Expr *defarg);
6550
6551 /// ActOnParamUnparsedDefaultArgument - We've seen a default
6552 /// argument for a function parameter, but we can't parse it yet
6553 /// because we're inside a class definition. Note that this default
6554 /// argument will be parsed later.
6556 SourceLocation ArgLoc);
6557
6558 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6559 /// the default argument for the parameter param failed.
6561 Expr *DefaultArg);
6563 SourceLocation EqualLoc);
6564 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6565 SourceLocation EqualLoc);
6566
6567 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6568 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6569 StringLiteral *Message = nullptr);
6570 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
6571
6572 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6573 StringLiteral *DeletedMessage = nullptr);
6577
6578 NamedDecl *
6580 MultiTemplateParamsArg TemplateParamLists);
6583 RecordDecl *ClassDecl,
6584 const IdentifierInfo *Name);
6585
6587 SourceLocation Loc);
6589
6590 /// Stack containing information needed when in C++2a an 'auto' is encountered
6591 /// in a function declaration parameter type specifier in order to invent a
6592 /// corresponding template parameter in the enclosing abbreviated function
6593 /// template. This information is also present in LambdaScopeInfo, stored in
6594 /// the FunctionScopes stack.
6596
6597 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6598 std::unique_ptr<CXXFieldCollector> FieldCollector;
6599
6601 /// Set containing all declared private fields that are not used.
6603
6605
6606 /// PureVirtualClassDiagSet - a set of class declarations which we have
6607 /// emitted a list of pure virtual functions. Used to prevent emitting the
6608 /// same list more than once.
6609 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6610
6614
6615 /// All the delegating constructors seen so far in the file, used for
6616 /// cycle detection at the end of the TU.
6618
6619 /// The C++ "std" namespace, where the standard library resides.
6621
6622 /// The C++ "std::initializer_list" template, which is defined in
6623 /// <initializer_list>.
6625
6626 /// The C++ "std::type_identity" template, which is defined in
6627 /// <type_traits>.
6629
6630 // Contains the locations of the beginning of unparsed default
6631 // argument locations.
6632 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6633
6634 /// UndefinedInternals - all the used, undefined objects which require a
6635 /// definition in this translation unit.
6636 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6637
6638 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6640
6641 /// The C++ special members which we are currently in the process of
6642 /// declaring. If this process recursively triggers the declaration of the
6643 /// same special member, we should act as if it is not yet declared.
6645
6647
6648 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6649
6652 ParsingClassDepth++;
6654 }
6656 ParsingClassDepth--;
6658 }
6659
6661 CXXScopeSpec &SS,
6662 ParsedType TemplateTypeTy,
6663 IdentifierInfo *MemberOrBase);
6664
6665private:
6666 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6667 QualType ResultTy,
6668 ArrayRef<QualType> Args);
6669 // Helper for ActOnFields to check for all function pointer members.
6670 bool EntirelyFunctionPointers(const RecordDecl *Record);
6671
6672 // A cache representing if we've fully checked the various comparison category
6673 // types stored in ASTContext. The bit-index corresponds to the integer value
6674 // of a ComparisonCategoryType enumerator.
6675 llvm::SmallBitVector FullyCheckedComparisonCategories;
6676
6677 /// Check if there is a field shadowing.
6678 void CheckShadowInheritedFields(const SourceLocation &Loc,
6679 DeclarationName FieldName,
6680 const CXXRecordDecl *RD,
6681 bool DeclIsField = true);
6682
6683 ///@}
6684
6685 //
6686 //
6687 // -------------------------------------------------------------------------
6688 //
6689 //
6690
6691 /// \name C++ Exception Specifications
6692 /// Implementations are in SemaExceptionSpec.cpp
6693 ///@{
6694
6695public:
6696 /// All the overriding functions seen during a class definition
6697 /// that had their exception spec checks delayed, plus the overridden
6698 /// function.
6701
6702 /// All the function redeclarations seen during a class definition that had
6703 /// their exception spec checks delayed, plus the prior declaration they
6704 /// should be checked against. Except during error recovery, the new decl
6705 /// should always be a friend declaration, as that's the only valid way to
6706 /// redeclare a special member before its class is complete.
6709
6710 /// Determine if we're in a case where we need to (incorrectly) eagerly
6711 /// parse an exception specification to work around a libstdc++ bug.
6713
6714 /// Check the given noexcept-specifier, convert its expression, and compute
6715 /// the appropriate ExceptionSpecificationType.
6716 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6718
6719 CanThrowResult canThrow(const Stmt *E);
6720 /// Determine whether the callee of a particular function call can throw.
6721 /// E, D and Loc are all optional.
6722 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6725 const FunctionProtoType *FPT);
6728
6729 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6730 /// exception specification. Incomplete types, or pointers to incomplete types
6731 /// other than void are not allowed.
6732 ///
6733 /// \param[in,out] T The exception type. This will be decayed to a pointer
6734 /// type
6735 /// when the input is an array or a function type.
6737
6738 /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6739 /// pointer to member to a function with an exception specification. This
6740 /// means that it is invalid to add another level of indirection.
6743
6744 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6745 /// exception specifications. Exception specifications are equivalent if
6746 /// they allow exactly the same set of exception types. It does not matter how
6747 /// that is achieved. See C++ [except.spec]p2.
6749 SourceLocation OldLoc,
6750 const FunctionProtoType *New,
6751 SourceLocation NewLoc);
6753 const PartialDiagnostic &NoteID,
6754 const FunctionProtoType *Old,
6755 SourceLocation OldLoc,
6756 const FunctionProtoType *New,
6757 SourceLocation NewLoc);
6758 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6759
6760 /// CheckExceptionSpecSubset - Check whether the second function type's
6761 /// exception specification is a subset (or equivalent) of the first function
6762 /// type. This is used by override and pointer assignment checks.
6764 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6765 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6766 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6767 SourceLocation SuperLoc, const FunctionProtoType *Subset,
6768 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6769
6770 /// CheckParamExceptionSpec - Check if the parameter and return types of the
6771 /// two functions have equivalent exception specs. This is part of the
6772 /// assignment and override compatibility check. We do not check the
6773 /// parameters of parameter function pointers recursively, as no sane
6774 /// programmer would even be able to write such a function type.
6776 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6777 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6778 SourceLocation TargetLoc, const FunctionProtoType *Source,
6779 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6780
6781 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6782
6783 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6784 /// spec is a subset of base spec.
6786 const CXXMethodDecl *Old);
6787
6788 ///@}
6789
6790 //
6791 //
6792 // -------------------------------------------------------------------------
6793 //
6794 //
6795
6796 /// \name Expressions
6797 /// Implementations are in SemaExpr.cpp
6798 ///@{
6799
6800public:
6801 /// Describes how the expressions currently being parsed are
6802 /// evaluated at run-time, if at all.
6804 /// The current expression and its subexpressions occur within an
6805 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6806 /// \c sizeof, where the type of the expression may be significant but
6807 /// no code will be generated to evaluate the value of the expression at
6808 /// run time.
6810
6811 /// The current expression occurs within a braced-init-list within
6812 /// an unevaluated operand. This is mostly like a regular unevaluated
6813 /// context, except that we still instantiate constexpr functions that are
6814 /// referenced here so that we can perform narrowing checks correctly.
6816
6817 /// The current expression occurs within a discarded statement.
6818 /// This behaves largely similarly to an unevaluated operand in preventing
6819 /// definitions from being required, but not in other ways.
6821
6822 /// The current expression occurs within an unevaluated
6823 /// operand that unconditionally permits abstract references to
6824 /// fields, such as a SIZE operator in MS-style inline assembly.
6826
6827 /// The current context is "potentially evaluated" in C++11 terms,
6828 /// but the expression is evaluated at compile-time (like the values of
6829 /// cases in a switch statement).
6831
6832 /// In addition of being constant evaluated, the current expression
6833 /// occurs in an immediate function context - either a consteval function
6834 /// or a consteval if statement.
6836
6837 /// The current expression is potentially evaluated at run time,
6838 /// which means that code may be generated to evaluate the value of the
6839 /// expression at run time.
6841
6842 /// The current expression is potentially evaluated, but any
6843 /// declarations referenced inside that expression are only used if
6844 /// in fact the current expression is used.
6845 ///
6846 /// This value is used when parsing default function arguments, for which
6847 /// we would like to provide diagnostics (e.g., passing non-POD arguments
6848 /// through varargs) but do not want to mark declarations as "referenced"
6849 /// until the default argument is used.
6851 };
6852
6853 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6854 /// to a variable (constant) that may or may not be odr-used in this Expr, and
6855 /// we won't know until all lvalue-to-rvalue and discarded value conversions
6856 /// have been applied to all subexpressions of the enclosing full expression.
6857 /// This is cleared at the end of each full expression.
6860
6861 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6862
6863 /// Data structure used to record current or nested
6864 /// expression evaluation contexts.
6866 /// The expression evaluation context.
6868
6869 /// Whether the enclosing context needed a cleanup.
6871
6872 /// The number of active cleanup objects when we entered
6873 /// this expression evaluation context.
6875
6877
6878 /// The lambdas that are present within this context, if it
6879 /// is indeed an unevaluated context.
6881
6882 /// The declaration that provides context for lambda expressions
6883 /// and block literals if the normal declaration context does not
6884 /// suffice, e.g., in a default function argument.
6886
6887 /// Declaration for initializer if one is currently being
6888 /// parsed. Used when an expression has a possibly unreachable
6889 /// diagnostic to reference the declaration as a whole.
6891
6892 /// If we are processing a decltype type, a set of call expressions
6893 /// for which we have deferred checking the completeness of the return type.
6895
6896 /// If we are processing a decltype type, a set of temporary binding
6897 /// expressions for which we have deferred checking the destructor.
6899
6901
6902 /// Expressions appearing as the LHS of a volatile assignment in this
6903 /// context. We produce a warning for these when popping the context if
6904 /// they are not discarded-value expressions nor unevaluated operands.
6906
6907 /// Set of candidates for starting an immediate invocation.
6910
6911 /// Set of DeclRefExprs referencing a consteval function when used in a
6912 /// context not already known to be immediately invoked.
6914
6915 /// P2718R0 - Lifetime extension in range-based for loops.
6916 /// MaterializeTemporaryExprs in for-range-init expressions which need to
6917 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
6918 /// InLifetimeExtendingContext is true.
6920
6921 /// Small set of gathered accesses to potentially misaligned members
6922 /// due to the packed attribute.
6924
6925 /// \brief Describes whether we are in an expression constext which we have
6926 /// to handle differently.
6934
6935 // A context can be nested in both a discarded statement context and
6936 // an immediate function context, so they need to be tracked independently.
6940
6942
6943 // We are in a constant context, but we also allow
6944 // non constant expressions, for example for array bounds (which may be
6945 // VLAs).
6947
6948 /// Whether we are currently in a context in which all temporaries must be
6949 /// lifetime-extended, even if they're not bound to a reference (for
6950 /// example, in a for-range initializer).
6952
6953 /// Whether evaluating an expression for a switch case label.
6954 bool IsCaseExpr = false;
6955
6956 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
6958
6959 // When evaluating immediate functions in the initializer of a default
6960 // argument or default member initializer, this is the declaration whose
6961 // default initializer is being evaluated and the location of the call
6962 // or constructor definition.
6966 : Loc(Loc), Decl(Decl), Context(Context) {
6967 assert(Decl && Context && "invalid initialization context");
6968 }
6969
6971 ValueDecl *Decl = nullptr;
6973 };
6974 std::optional<InitializationContext> DelayedDefaultInitializationContext;
6975
6986
6992
6999
7004
7009 // C++23 [expr.const]p14:
7010 // An expression or conversion is in an immediate function
7011 // context if it is potentially evaluated and either:
7012 // * its innermost enclosing non-block scope is a function
7013 // parameter scope of an immediate function, or
7014 // * its enclosing statement is enclosed by the compound-
7015 // statement of a consteval if statement.
7018 }
7019
7027 };
7028
7030 assert(!ExprEvalContexts.empty() &&
7031 "Must be in an expression evaluation context");
7032 return ExprEvalContexts.back();
7033 }
7034
7036 assert(!ExprEvalContexts.empty() &&
7037 "Must be in an expression evaluation context");
7038 return ExprEvalContexts.back();
7039 }
7040
7042 assert(ExprEvalContexts.size() >= 2 &&
7043 "Must be in an expression evaluation context");
7044 return ExprEvalContexts[ExprEvalContexts.size() - 2];
7045 }
7046
7048 return const_cast<Sema *>(this)->parentEvaluationContext();
7049 }
7050
7055
7056 /// Increment when we find a reference; decrement when we find an ignored
7057 /// assignment. Ultimately the value is 0 if every reference is an ignored
7058 /// assignment.
7059 ///
7060 /// Uses canonical VarDecl as key so in-class decls and out-of-class defs of
7061 /// static data members get tracked as a single entry.
7062 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
7063
7064 /// Used to control the generation of ExprWithCleanups.
7066
7067 /// ExprCleanupObjects - This is the stack of objects requiring
7068 /// cleanup that are created by the current full expression.
7070
7071 /// Determine whether the use of this declaration is valid, without
7072 /// emitting diagnostics.
7073 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
7074 // A version of DiagnoseUseOfDecl that should be used if overload resolution
7075 // has been used to find this declaration, which means we don't have to bother
7076 // checking the trailing requires clause.
7078 return DiagnoseUseOfDecl(
7079 D, Loc, /*UnknownObjCClass=*/nullptr, /*ObjCPropertyAccess=*/false,
7080 /*AvoidPartialAvailabilityChecks=*/false, /*ClassReceiver=*/nullptr,
7081 /*SkipTrailingRequiresClause=*/true);
7082 }
7083
7084 /// Determine whether the use of this declaration is valid, and
7085 /// emit any corresponding diagnostics.
7086 ///
7087 /// This routine diagnoses various problems with referencing
7088 /// declarations that can occur when using a declaration. For example,
7089 /// it might warn if a deprecated or unavailable declaration is being
7090 /// used, or produce an error (and return true) if a C++0x deleted
7091 /// function is being used.
7092 ///
7093 /// \returns true if there was an error (this declaration cannot be
7094 /// referenced), false otherwise.
7096 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
7097 bool ObjCPropertyAccess = false,
7098 bool AvoidPartialAvailabilityChecks = false,
7099 ObjCInterfaceDecl *ClassReceiver = nullptr,
7100 bool SkipTrailingRequiresClause = false);
7101
7102 /// Emit a note explaining that this function is deleted.
7104
7105 /// DiagnoseSentinelCalls - This routine checks whether a call or
7106 /// message-send is to a declaration with the sentinel attribute, and
7107 /// if so, it checks that the requirements of the sentinel are
7108 /// satisfied.
7110 ArrayRef<Expr *> Args);
7111
7113 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
7116
7118 ExpressionEvaluationContext NewContext, FunctionDecl *FD);
7119
7122 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
7126
7128
7132
7133 /// Check whether E, which is either a discarded-value expression or an
7134 /// unevaluated operand, is a simple-assignment to a volatlie-qualified
7135 /// lvalue, and if so, remove it from the list of volatile-qualified
7136 /// assignments that we are going to warn are deprecated.
7138
7140
7141 // Functions for marking a declaration referenced. These functions also
7142 // contain the relevant logic for marking if a reference to a function or
7143 // variable is an odr-use (in the C++11 sense). There are separate variants
7144 // for expressions referring to a decl; these exist because odr-use marking
7145 // needs to be delayed for some constant variables when we build one of the
7146 // named expressions.
7147 //
7148 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
7149 // should usually be true. This only needs to be set to false if the lack of
7150 // odr-use cannot be determined from the current context (for instance,
7151 // because the name denotes a virtual function and was written without an
7152 // explicit nested-name-specifier).
7153 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
7154
7155 /// Mark a function referenced, and check whether it is odr-used
7156 /// (C++ [basic.def.odr]p2, C99 6.9p3)
7158 bool MightBeOdrUse = true);
7159
7160 /// Mark a variable referenced, and check whether it is odr-used
7161 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
7162 /// used directly for normal expressions referring to VarDecl.
7164
7165 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7166 ///
7167 /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7168 /// be handled with care if the DeclRefExpr is not newly-created.
7169 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7170
7171 /// Perform reference-marking and odr-use handling for a MemberExpr.
7173
7174 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7177 unsigned CapturingScopeIndex);
7178
7180 void CleanupVarDeclMarking();
7181
7182 /// Try to capture the given variable.
7183 ///
7184 /// \param Var The variable to capture.
7185 ///
7186 /// \param Loc The location at which the capture occurs.
7187 ///
7188 /// \param Kind The kind of capture, which may be implicit (for either a
7189 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7190 ///
7191 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7192 /// an explicit lambda capture.
7193 ///
7194 /// \param BuildAndDiagnose Whether we are actually supposed to add the
7195 /// captures or diagnose errors. If false, this routine merely check whether
7196 /// the capture can occur without performing the capture itself or complaining
7197 /// if the variable cannot be captured.
7198 ///
7199 /// \param CaptureType Will be set to the type of the field used to capture
7200 /// this variable in the innermost block or lambda. Only valid when the
7201 /// variable can be captured.
7202 ///
7203 /// \param DeclRefType Will be set to the type of a reference to the capture
7204 /// from within the current scope. Only valid when the variable can be
7205 /// captured.
7206 ///
7207 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7208 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7209 /// This is useful when enclosing lambdas must speculatively capture
7210 /// variables that may or may not be used in certain specializations of
7211 /// a nested generic lambda.
7212 ///
7213 /// \returns true if an error occurred (i.e., the variable cannot be
7214 /// captured) and false if the capture succeeded.
7216 TryCaptureKind Kind, SourceLocation EllipsisLoc,
7217 bool BuildAndDiagnose, QualType &CaptureType,
7218 QualType &DeclRefType,
7219 const unsigned *const FunctionScopeIndexToStopAt);
7220
7221 /// Try to capture the given variable.
7224 SourceLocation EllipsisLoc = SourceLocation());
7225
7226 /// Checks if the variable must be captured.
7228
7229 /// Given a variable, determine the type that a reference to that
7230 /// variable will have in the given scope.
7232
7233 /// Mark all of the declarations referenced within a particular AST node as
7234 /// referenced. Used when template instantiation instantiates a non-dependent
7235 /// type -- entities referenced by the type are now referenced.
7237
7238 /// Mark any declarations that appear within this expression or any
7239 /// potentially-evaluated subexpressions as "referenced".
7240 ///
7241 /// \param SkipLocalVariables If true, don't mark local variables as
7242 /// 'referenced'.
7243 /// \param StopAt Subexpressions that we shouldn't recurse into.
7245 bool SkipLocalVariables = false,
7246 ArrayRef<const Expr *> StopAt = {});
7247
7248 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7249 /// conversion.
7250 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7251
7252 /// Conditionally issue a diagnostic based on the statements's reachability
7253 /// analysis.
7254 ///
7255 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7256 /// the function body is parsed, and then do a basic reachability analysis to
7257 /// determine if the statement is reachable. If it is unreachable, the
7258 /// diagnostic will not be emitted.
7259 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7260 const PartialDiagnostic &PD);
7261
7262 /// Conditionally issue a diagnostic based on the current
7263 /// evaluation context.
7264 ///
7265 /// \param Statement If Statement is non-null, delay reporting the
7266 /// diagnostic until the function body is parsed, and then do a basic
7267 /// reachability analysis to determine if the statement is reachable.
7268 /// If it is unreachable, the diagnostic will not be emitted.
7269 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7270 const PartialDiagnostic &PD);
7271 /// Similar, but diagnostic is only produced if all the specified statements
7272 /// are reachable.
7273 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7274 const PartialDiagnostic &PD);
7275
7276 // Primary Expressions.
7277 SourceRange getExprRange(Expr *E) const;
7278
7279 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7280 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7281 bool HasTrailingLParen, bool IsAddressOfOperand,
7282 CorrectionCandidateCallback *CCC = nullptr,
7283 bool IsInlineAsmIdentifier = false);
7284
7285 /// Decomposes the given name into a DeclarationNameInfo, its location, and
7286 /// possibly a list of template arguments.
7287 ///
7288 /// If this produces template arguments, it is permitted to call
7289 /// DecomposeTemplateName.
7290 ///
7291 /// This actually loses a lot of source location information for
7292 /// non-standard name kinds; we should consider preserving that in
7293 /// some way.
7294 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7295 TemplateArgumentListInfo &Buffer,
7296 DeclarationNameInfo &NameInfo,
7297 const TemplateArgumentListInfo *&TemplateArgs);
7298
7299 /// Diagnose a lookup that found results in an enclosing class during error
7300 /// recovery. This usually indicates that the results were found in a
7301 /// dependent base class that could not be searched as part of a template
7302 /// definition. Always issues a diagnostic (though this may be only a warning
7303 /// in MS compatibility mode).
7304 ///
7305 /// Return \c true if the error is unrecoverable, or \c false if the caller
7306 /// should attempt to recover using these lookup results.
7307 bool DiagnoseDependentMemberLookup(const LookupResult &R);
7308
7309 /// Diagnose an empty lookup.
7310 ///
7311 /// \return false if new lookup candidates were found
7312 bool
7313 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7314 CorrectionCandidateCallback &CCC,
7315 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7316 ArrayRef<Expr *> Args = {},
7317 DeclContext *LookupCtx = nullptr);
7318
7319 /// If \p D cannot be odr-used in the current expression evaluation context,
7320 /// return a reason explaining why. Otherwise, return NOUR_None.
7322
7323 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7324 SourceLocation Loc,
7325 const CXXScopeSpec *SS = nullptr);
7326 DeclRefExpr *
7327 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7328 const DeclarationNameInfo &NameInfo,
7329 const CXXScopeSpec *SS = nullptr,
7330 NamedDecl *FoundD = nullptr,
7331 SourceLocation TemplateKWLoc = SourceLocation(),
7332 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7333
7334 /// BuildDeclRefExpr - Build an expression that references a
7335 /// declaration that does not require a closure capture.
7336 DeclRefExpr *
7337 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7338 const DeclarationNameInfo &NameInfo,
7339 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7340 SourceLocation TemplateKWLoc = SourceLocation(),
7341 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7342
7343 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7344 bool HasTrailingLParen);
7345
7346 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7347 /// declaration name, generally during template instantiation.
7348 /// There's a large number of things which don't need to be done along
7349 /// this path.
7351 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7352 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7353
7354 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7355 bool NeedsADL,
7356 bool AcceptInvalidDecl = false);
7357
7358 /// Complete semantic analysis for a reference to the given declaration.
7360 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7361 NamedDecl *FoundD = nullptr,
7362 const TemplateArgumentListInfo *TemplateArgs = nullptr,
7363 bool AcceptInvalidDecl = false);
7364
7365 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7366 // where Tokens representing function local predefined macros (such as
7367 // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7368 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7369
7370 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7371 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7372 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7373
7374 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7375
7376 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7378 Scope *UDLScope = nullptr);
7379 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7380 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7381 MultiExprArg Val);
7382 ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7383 unsigned NumUserSpecifiedExprs,
7384 SourceLocation InitLoc,
7385 SourceLocation LParenLoc,
7386 SourceLocation RParenLoc);
7387
7388 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7389 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle
7390 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7391 /// from multiple tokens. However, the common case is that StringToks points
7392 /// to one string.
7393 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7394 Scope *UDLScope = nullptr);
7395
7396 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7397
7398 /// ControllingExprOrType is either an opaque pointer coming out of a
7399 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7400 /// into two so we don't take a void *, but that's awkward because one of
7401 /// the operands is either a ParsedType or an Expr *, which doesn't lend
7402 /// itself to generic code very well.
7403 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7404 SourceLocation DefaultLoc,
7405 SourceLocation RParenLoc,
7406 bool PredicateIsExpr,
7407 void *ControllingExprOrType,
7408 ArrayRef<ParsedType> ArgTypes,
7409 ArrayRef<Expr *> ArgExprs);
7410 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7411 /// it'd be better to split this interface into two so we don't take a
7412 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7413 /// isn't a trivial change.
7414 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7415 SourceLocation DefaultLoc,
7416 SourceLocation RParenLoc,
7417 bool PredicateIsExpr,
7418 void *ControllingExprOrType,
7419 ArrayRef<TypeSourceInfo *> Types,
7420 ArrayRef<Expr *> Exprs);
7421
7422 // Binary/Unary Operators. 'Tok' is the token for the operator.
7423 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7424 Expr *InputExpr, bool IsAfterAmp = false);
7425 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7426 Expr *Input, bool IsAfterAmp = false);
7427
7428 /// Unary Operators. 'Tok' is the token for the operator.
7429 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7430 Expr *Input, bool IsAfterAmp = false);
7431
7432 /// Determine whether the given expression is a qualified member
7433 /// access expression, of a form that could be turned into a pointer to member
7434 /// with the address-of operator.
7435 bool isQualifiedMemberAccess(Expr *E);
7436 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7437 const Expr *Op,
7438 const CXXMethodDecl *MD);
7439
7440 /// CheckAddressOfOperand - The operand of & must be either a function
7441 /// designator or an lvalue designating an object. If it is an lvalue, the
7442 /// object cannot be declared with storage class register or be a bit field.
7443 /// Note: The usual conversions are *not* applied to the operand of the &
7444 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7445 /// In C++, the operand might be an overloaded function name, in which case
7446 /// we allow the '&' but retain the overloaded-function type.
7447 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7448
7449 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7450 /// _Alignas(type-name) .
7451 /// [dcl.align] An alignment-specifier of the form
7452 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7453 ///
7454 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7455 /// _Alignas(_Alignof(type-name)).
7456 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7457 SourceLocation OpLoc, SourceRange R);
7458 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7459 SourceLocation OpLoc, SourceRange R);
7460
7461 /// Build a sizeof or alignof expression given a type operand.
7462 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7463 SourceLocation OpLoc,
7464 UnaryExprOrTypeTrait ExprKind,
7465 SourceRange R);
7466
7467 /// Build a sizeof or alignof expression given an expression
7468 /// operand.
7469 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7470 UnaryExprOrTypeTrait ExprKind);
7471
7472 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7473 /// expr and the same for @c alignof and @c __alignof
7474 /// Note that the ArgRange is invalid if isType is false.
7475 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7476 UnaryExprOrTypeTrait ExprKind,
7477 bool IsType, void *TyOrEx,
7478 SourceRange ArgRange);
7479
7480 /// Check for operands with placeholder types and complain if found.
7481 /// Returns ExprError() if there was an error and no recovery was possible.
7483 bool CheckVecStepExpr(Expr *E);
7484
7485 /// Check the constraints on expression operands to unary type expression
7486 /// and type traits.
7487 ///
7488 /// Completes any types necessary and validates the constraints on the operand
7489 /// expression. The logic mostly mirrors the type-based overload, but may
7490 /// modify the expression as it completes the type for that expression through
7491 /// template instantiation, etc.
7492 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
7493
7494 /// Check the constraints on operands to unary expression and type
7495 /// traits.
7496 ///
7497 /// This will complete any types necessary, and validate the various
7498 /// constraints on those operands.
7499 ///
7500 /// The UsualUnaryConversions() function is *not* called by this routine.
7501 /// C99 6.3.2.1p[2-4] all state:
7502 /// Except when it is the operand of the sizeof operator ...
7503 ///
7504 /// C++ [expr.sizeof]p4
7505 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7506 /// standard conversions are not applied to the operand of sizeof.
7507 ///
7508 /// This policy is followed for all of the unary trait expressions.
7509 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7510 SourceRange ExprRange,
7511 UnaryExprOrTypeTrait ExprKind,
7512 StringRef KWName);
7513
7514 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7515 tok::TokenKind Kind, Expr *Input);
7516
7517 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7518 MultiExprArg ArgExprs,
7519 SourceLocation RLoc);
7520 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7521 Expr *Idx, SourceLocation RLoc);
7522
7523 ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx,
7524 SourceLocation RBLoc);
7525
7526 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7527 Expr *ColumnIdx,
7528 SourceLocation RBLoc);
7529
7530 /// ConvertArgumentsForCall - Converts the arguments specified in
7531 /// Args/NumArgs to the parameter types of the function FDecl with
7532 /// function prototype Proto. Call is the call expression itself, and
7533 /// Fn is the function expression. For a C++ member function, this
7534 /// routine does not attempt to convert the object argument. Returns
7535 /// true if the call is ill-formed.
7536 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7537 const FunctionProtoType *Proto,
7538 ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7539 bool ExecConfig = false);
7540
7541 /// CheckStaticArrayArgument - If the given argument corresponds to a static
7542 /// array parameter, check that it is non-null, and that if it is formed by
7543 /// array-to-pointer decay, the underlying array is sufficiently large.
7544 ///
7545 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7546 /// the array type derivation, then for each call to the function, the value
7547 /// of the corresponding actual argument shall provide access to the first
7548 /// element of an array with at least as many elements as specified by the
7549 /// size expression.
7550 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7551 const Expr *ArgExpr);
7552
7553 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7554 /// This provides the location of the left/right parens and a list of comma
7555 /// locations.
7556 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7557 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7558 Expr *ExecConfig = nullptr);
7559
7560 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7561 /// This provides the location of the left/right parens and a list of comma
7562 /// locations.
7563 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7564 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7565 Expr *ExecConfig = nullptr,
7566 bool IsExecConfig = false,
7567 bool AllowRecovery = false);
7568
7569 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7570 // with the specified CallArgs
7571 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7572 MultiExprArg CallArgs);
7573
7575
7576 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7577 /// i.e. an expression not of \p OverloadTy. The expression should
7578 /// unary-convert to an expression of function-pointer or
7579 /// block-pointer type.
7580 ///
7581 /// \param NDecl the declaration being called, if available
7583 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7584 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7585 Expr *Config = nullptr, bool IsExecConfig = false,
7586 ADLCallKind UsesADL = ADLCallKind::NotADL);
7587
7589 ParsedType &Ty, SourceLocation RParenLoc,
7590 Expr *CastExpr);
7591
7592 /// Prepares for a scalar cast, performing all the necessary stages
7593 /// except the final cast and returning the kind required.
7595
7596 /// Build an altivec or OpenCL literal.
7598 SourceLocation RParenLoc, Expr *E,
7599 TypeSourceInfo *TInfo);
7600
7601 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7602 /// the ParenListExpr into a sequence of comma binary operators.
7604
7606 SourceLocation RParenLoc, Expr *InitExpr);
7607
7609 TypeSourceInfo *TInfo,
7610 SourceLocation RParenLoc,
7611 Expr *LiteralExpr);
7612
7613 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7614 SourceLocation RBraceLoc);
7615
7616 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7617 SourceLocation RBraceLoc, bool IsExplicit);
7618
7619 /// Binary Operators. 'Tok' is the token for the operator.
7621 Expr *LHSExpr, Expr *RHSExpr);
7623 Expr *LHSExpr, Expr *RHSExpr,
7624 bool ForFoldExpression = false);
7625
7626 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7627 /// operator @p Opc at location @c TokLoc. This routine only supports
7628 /// built-in operations; ActOnBinOp handles overloaded operators.
7630 Expr *LHSExpr, Expr *RHSExpr,
7631 bool ForFoldExpression = false);
7633 UnresolvedSetImpl &Functions);
7634
7635 /// Look for instances where it is likely the comma operator is confused with
7636 /// another operator. There is an explicit list of acceptable expressions for
7637 /// the left hand side of the comma operator, otherwise emit a warning.
7638 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7639
7640 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7641 /// in the case of a the GNU conditional expr extension.
7643 SourceLocation ColonLoc, Expr *CondExpr,
7644 Expr *LHSExpr, Expr *RHSExpr);
7645
7646 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7648 LabelDecl *TheDecl);
7649
7650 void ActOnStartStmtExpr();
7651 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7652 SourceLocation RPLoc);
7654 SourceLocation RPLoc, unsigned TemplateDepth);
7655 // Handle the final expression in a statement expression.
7657 void ActOnStmtExprError();
7658
7659 /// __builtin_offsetof(type, a.b[123][456].c)
7661 TypeSourceInfo *TInfo,
7662 const Designation &Desig,
7663 SourceLocation RParenLoc);
7666 ParsedType ParsedArgTy,
7667 const Designation &Desig,
7668 SourceLocation RParenLoc);
7669
7670 // __builtin_choose_expr(constExpr, expr1, expr2)
7671 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7672 Expr *LHSExpr, Expr *RHSExpr,
7673 SourceLocation RPLoc);
7674
7675 // __builtin_va_arg(expr, type)
7677 SourceLocation RPLoc);
7679 TypeSourceInfo *TInfo, SourceLocation RPLoc);
7680
7681 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7682 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7684 SourceLocation BuiltinLoc,
7685 SourceLocation RPLoc);
7686
7687 // #embed
7689 StringLiteral *BinaryData, StringRef FileName);
7690
7691 // Build a potentially resolved SourceLocExpr.
7693 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7694 DeclContext *ParentContext);
7695
7696 // __null
7698
7699 bool CheckCaseExpression(Expr *E);
7700
7701 //===------------------------- "Block" Extension ------------------------===//
7702
7703 /// ActOnBlockStart - This callback is invoked when a block literal is
7704 /// started.
7705 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7706
7707 /// ActOnBlockArguments - This callback allows processing of block arguments.
7708 /// If there are no arguments, this is still invoked.
7709 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7710 Scope *CurScope);
7711
7712 /// ActOnBlockError - If there is an error parsing a block, this callback
7713 /// is invoked to pop the information about the block from the action impl.
7714 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7715
7716 /// ActOnBlockStmtExpr - This is called when the body of a block statement
7717 /// literal was successfully completed. ^(int x){...}
7719 Scope *CurScope);
7720
7721 //===---------------------------- Clang Extensions ----------------------===//
7722
7723 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7724 /// provided arguments.
7725 ///
7726 /// __builtin_convertvector( value, dst type )
7727 ///
7729 SourceLocation BuiltinLoc,
7730 SourceLocation RParenLoc);
7731
7732 //===---------------------------- OpenCL Features -----------------------===//
7733
7734 /// Parse a __builtin_astype expression.
7735 ///
7736 /// __builtin_astype( value, dst type )
7737 ///
7738 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7739 SourceLocation BuiltinLoc,
7740 SourceLocation RParenLoc);
7741
7742 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7744 SourceLocation BuiltinLoc,
7745 SourceLocation RParenLoc);
7746
7747 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7749 ArrayRef<Expr *> SubExprs,
7750 QualType T = QualType());
7751
7752 /// Cast a base object to a member's actual type.
7753 ///
7754 /// There are two relevant checks:
7755 ///
7756 /// C++ [class.access.base]p7:
7757 ///
7758 /// If a class member access operator [...] is used to access a non-static
7759 /// data member or non-static member function, the reference is ill-formed
7760 /// if the left operand [...] cannot be implicitly converted to a pointer to
7761 /// the naming class of the right operand.
7762 ///
7763 /// C++ [expr.ref]p7:
7764 ///
7765 /// If E2 is a non-static data member or a non-static member function, the
7766 /// program is ill-formed if the class of which E2 is directly a member is
7767 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7768 ///
7769 /// Note that the latter check does not consider access; the access of the
7770 /// "real" base class is checked as appropriate when checking the access of
7771 /// the member name.
7773 NestedNameSpecifier Qualifier,
7774 NamedDecl *FoundDecl,
7775 NamedDecl *Member);
7776
7777 /// CheckCallReturnType - Checks that a call expression's return type is
7778 /// complete. Returns true on failure. The location passed in is the location
7779 /// that best represents the call.
7780 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7781 CallExpr *CE, FunctionDecl *FD);
7782
7783 /// Emit a warning for all pending noderef expressions that we recorded.
7785
7787
7788 /// Instantiate or parse a C++ default argument expression as necessary.
7789 /// Return true on error.
7791 ParmVarDecl *Param, Expr *Init = nullptr,
7792 bool SkipImmediateInvocations = true);
7793
7794 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7795 /// the default expr if needed.
7797 ParmVarDecl *Param, Expr *Init = nullptr);
7798
7799 /// Wrap the expression in a ConstantExpr if it is a potential immediate
7800 /// invocation.
7802
7804
7805 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7806 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7807
7808 /// Abstract base class used for diagnosing integer constant
7809 /// expression violations.
7811 public:
7813
7815
7816 virtual SemaDiagnosticBuilder
7817 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7819 SourceLocation Loc) = 0;
7822 };
7823
7824 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7825 /// and reports the appropriate diagnostics. Returns false on success.
7826 /// Can optionally return the value of the expression.
7829 VerifyICEDiagnoser &Diagnoser,
7833 unsigned DiagID,
7836 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7840 AllowFoldKind CanFold = AllowFoldKind::No) {
7841 return VerifyIntegerConstantExpression(E, nullptr, CanFold);
7842 }
7843
7844 /// DiagnoseAssignmentAsCondition - Given that an expression is
7845 /// being used as a boolean condition, warn if it's an assignment.
7847
7848 /// Redundant parentheses over an equality comparison can indicate
7849 /// that the user intended an assignment used as condition.
7851
7853 public:
7855 FullExprArg(Sema &actions) : E(nullptr) {}
7856
7857 ExprResult release() { return E; }
7858
7859 Expr *get() const { return E; }
7860
7861 Expr *operator->() { return E; }
7862
7863 private:
7864 // FIXME: No need to make the entire Sema class a friend when it's just
7865 // Sema::MakeFullExpr that needs access to the constructor below.
7866 friend class Sema;
7867
7868 explicit FullExprArg(Expr *expr) : E(expr) {}
7869
7870 Expr *E;
7871 };
7872
7874 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
7875 }
7877 return FullExprArg(
7878 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
7879 }
7881 ExprResult FE =
7882 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
7883 /*DiscardedValue*/ true);
7884 return FullExprArg(FE.get());
7885 }
7886
7887 class ConditionResult {
7888 Decl *ConditionVar;
7889 ExprResult Condition;
7890 bool Invalid;
7891 std::optional<bool> KnownValue;
7892
7893 friend class Sema;
7894 ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
7895 bool IsConstexpr)
7896 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
7897 if (IsConstexpr && Condition.get()) {
7898 if (std::optional<llvm::APSInt> Val =
7899 Condition.get()->getIntegerConstantExpr(S.Context)) {
7900 KnownValue = !!(*Val);
7901 }
7902 }
7903 }
7904 explicit ConditionResult(bool Invalid)
7905 : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
7906 KnownValue(std::nullopt) {}
7907
7908 public:
7909 ConditionResult() : ConditionResult(false) {}
7910 bool isInvalid() const { return Invalid; }
7911 std::pair<VarDecl *, Expr *> get() const {
7912 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
7913 Condition.get());
7914 }
7915 std::optional<bool> getKnownValue() const { return KnownValue; }
7916 };
7918
7919 /// CheckBooleanCondition - Diagnose problems involving the use of
7920 /// the given expression as a boolean condition (e.g. in an if
7921 /// statement). Also performs the standard function and array
7922 /// decays, possibly changing the input variable.
7923 ///
7924 /// \param Loc - A location associated with the condition, e.g. the
7925 /// 'if' keyword.
7926 /// \return true iff there were any errors
7928 bool IsConstexpr = false);
7929
7930 enum class ConditionKind {
7931 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
7932 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
7933 Switch ///< An integral condition for a 'switch' statement.
7934 };
7935
7936 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
7937 ConditionKind CK, bool MissingOK = false);
7938
7939 QualType CheckConditionalOperands( // C99 6.5.15
7941 ExprObjectKind &OK, SourceLocation QuestionLoc);
7942
7943 /// Emit a specialized diagnostic when one expression is a null pointer
7944 /// constant and the other is not a pointer. Returns true if a diagnostic is
7945 /// emitted.
7946 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7947 SourceLocation QuestionLoc);
7948
7949 /// type checking for vector binary operators.
7951 SourceLocation Loc, bool IsCompAssign,
7952 bool AllowBothBool, bool AllowBoolConversion,
7953 bool AllowBoolOperation, bool ReportInvalid);
7954
7955 /// Return a signed ext_vector_type that is of identical size and number of
7956 /// elements. For floating point vectors, return an integer type of identical
7957 /// size and number of elements. In the non ext_vector_type case, search from
7958 /// the largest type to the smallest type to avoid cases where long long ==
7959 /// long, where long gets picked over long long.
7962
7963 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7964 /// operates on extended vector types. Instead of producing an IntTy result,
7965 /// like a scalar comparison, a vector comparison produces a vector of integer
7966 /// types.
7968 SourceLocation Loc,
7969 BinaryOperatorKind Opc);
7971 SourceLocation Loc,
7972 BinaryOperatorKind Opc);
7974 SourceLocation Loc,
7975 BinaryOperatorKind Opc);
7977 SourceLocation Loc,
7978 BinaryOperatorKind Opc);
7979 // type checking for sizeless vector binary operators.
7981 SourceLocation Loc, bool IsCompAssign,
7982 ArithConvKind OperationKind);
7983
7984 /// Type checking for matrix binary operators.
7986 SourceLocation Loc,
7987 bool IsCompAssign);
7989 SourceLocation Loc, bool IsCompAssign);
7990
7991 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
7992 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
7993 /// VLST) allowed?
7994 ///
7995 /// This will also return false if the two given types do not make sense from
7996 /// the perspective of SVE bitcasts.
7997 bool isValidSveBitcast(QualType srcType, QualType destType);
7998
7999 /// Are the two types matrix types and do they have the same dimensions i.e.
8000 /// do they have the same number of rows and the same number of columns?
8002
8003 bool areVectorTypesSameSize(QualType srcType, QualType destType);
8004
8005 /// Are the two types lax-compatible vector types? That is, given
8006 /// that one of them is a vector, do they have equal storage sizes,
8007 /// where the storage size is the number of elements times the element
8008 /// size?
8009 ///
8010 /// This will also return false if either of the types is neither a
8011 /// vector nor a real type.
8012 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
8013
8014 /// Is this a legal conversion between two types, one of which is
8015 /// known to be a vector type?
8016 bool isLaxVectorConversion(QualType srcType, QualType destType);
8017
8018 // This returns true if at least one of the types is an altivec vector.
8019 bool anyAltivecTypes(QualType srcType, QualType destType);
8020
8021 // type checking C++ declaration initializers (C++ [dcl.init]).
8022
8023 /// Check a cast of an unknown-any type. We intentionally only
8024 /// trigger this for C-style casts.
8027 ExprValueKind &VK, CXXCastPath &Path);
8028
8029 /// Force an expression with unknown-type to an expression of the
8030 /// given type.
8032
8033 /// Type-check an expression that's being passed to an
8034 /// __unknown_anytype parameter.
8036 QualType &paramType);
8037
8038 // CheckMatrixCast - Check type constraints for matrix casts.
8039 // We allow casting between matrixes of the same dimensions i.e. when they
8040 // have the same number of rows and column. Returns true if the cast is
8041 // invalid.
8042 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8043 CastKind &Kind);
8044
8045 // CheckVectorCast - check type constraints for vectors.
8046 // Since vectors are an extension, there are no C standard reference for this.
8047 // We allow casting between vectors and integer datatypes of the same size.
8048 // returns true if the cast is invalid
8049 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8050 CastKind &Kind);
8051
8052 /// Prepare `SplattedExpr` for a vector splat operation, adding
8053 /// implicit casts if necessary.
8054 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8055
8056 /// Prepare `SplattedExpr` for a matrix splat operation, adding
8057 /// implicit casts if necessary.
8058 ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr);
8059
8060 // CheckExtVectorCast - check type constraints for extended vectors.
8061 // Since vectors are an extension, there are no C standard reference for this.
8062 // We allow casting between vectors and integer datatypes of the same size,
8063 // or vectors and the element type of that vector.
8064 // returns the cast expr
8066 CastKind &Kind);
8067
8069 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
8070 }
8071
8072 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
8073 // functions and arrays to their respective pointers (C99 6.3.2.1), and
8074 // promotes floating-piont types according to the language semantics.
8076
8077 // UsualUnaryFPConversions - promotes floating-point types according to the
8078 // current language semantics.
8080
8081 /// CallExprUnaryConversions - a special case of an unary conversion
8082 /// performed on a function designator of a call expression.
8084
8085 // DefaultFunctionArrayConversion - converts functions and arrays
8086 // to their respective pointers (C99 6.3.2.1).
8088
8089 // DefaultFunctionArrayLvalueConversion - converts functions and
8090 // arrays to their respective pointers and performs the
8091 // lvalue-to-rvalue conversion.
8093 bool Diagnose = true);
8094
8095 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8096 // the operand. This function is a no-op if the operand has a function type
8097 // or an array type.
8099
8100 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8101 // do not have a prototype. Integer promotions are performed on each
8102 // argument, and arguments that have type float are promoted to double.
8104
8106 const FunctionProtoType *Proto,
8107 Expr *Fn);
8108
8109 /// Determine the degree of POD-ness for an expression.
8110 /// Incomplete types are considered POD, since this check can be performed
8111 /// when we're in an unevaluated context.
8113
8114 /// Check to see if the given expression is a valid argument to a variadic
8115 /// function, issuing a diagnostic if not.
8116 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8117
8118 /// GatherArgumentsForCall - Collector argument expressions for various
8119 /// form of call prototypes.
8121 SourceLocation CallLoc, FunctionDecl *FDecl,
8122 const FunctionProtoType *Proto, unsigned FirstParam,
8125 bool AllowExplicit = false, bool IsListInitialization = false);
8126
8127 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8128 // will create a runtime trap if the resulting type is not a POD type.
8130 FunctionDecl *FDecl);
8131
8132 // Check that the usual arithmetic conversions can be performed on this pair
8133 // of expressions that might be of enumeration type.
8135 ArithConvKind ACK);
8136
8137 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8138 // operands and then handles various conversions that are common to binary
8139 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8140 // routine returns the first non-arithmetic type found. The client is
8141 // responsible for emitting appropriate error diagnostics.
8143 SourceLocation Loc, ArithConvKind ACK);
8144
8146 switch (ConvTy) {
8147 default:
8148 return false;
8152 return true;
8153 }
8154 llvm_unreachable("impossible");
8155 }
8156
8157 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8158 /// assignment conversion type specified by ConvTy. This returns true if the
8159 /// conversion was invalid or false if the conversion was accepted.
8161 QualType DstType, QualType SrcType,
8162 Expr *SrcExpr, AssignmentAction Action,
8163 bool *Complained = nullptr);
8164
8165 /// CheckAssignmentConstraints - Perform type checking for assignment,
8166 /// argument passing, variable initialization, and function return values.
8167 /// C99 6.5.16.
8169 QualType LHSType,
8170 QualType RHSType);
8171
8172 /// Check assignment constraints and optionally prepare for a conversion of
8173 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8174 /// is true.
8176 ExprResult &RHS, CastKind &Kind,
8177 bool ConvertRHS = true);
8178
8179 /// Check assignment constraints for an assignment of RHS to LHSType.
8180 ///
8181 /// \param LHSType The destination type for the assignment.
8182 /// \param RHS The source expression for the assignment.
8183 /// \param Diagnose If \c true, diagnostics may be produced when checking
8184 /// for assignability. If a diagnostic is produced, \p RHS will be
8185 /// set to ExprError(). Note that this function may still return
8186 /// without producing a diagnostic, even for an invalid assignment.
8187 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8188 /// in an audited Core Foundation API and does not need to be checked
8189 /// for ARC retain issues.
8190 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8191 /// conversions necessary to perform the assignment. If \c false,
8192 /// \p Diagnose must also be \c false.
8194 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8195 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8196
8197 // If the lhs type is a transparent union, check whether we
8198 // can initialize the transparent union with the given expression.
8200 ExprResult &RHS);
8201
8202 /// the following "Check" methods will return a valid/converted QualType
8203 /// or a null QualType (indicating an error diagnostic was issued).
8204
8205 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8207 ExprResult &RHS);
8208
8209 /// Diagnose cases where a scalar was implicitly converted to a vector and
8210 /// diagnose the underlying types. Otherwise, diagnose the error
8211 /// as invalid vector logical operands for non-C++ cases.
8213 ExprResult &RHS);
8214
8216 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8217 BinaryOperatorKind Opc);
8218 QualType CheckRemainderOperands( // C99 6.5.5
8219 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8220 bool IsCompAssign = false);
8221 QualType CheckAdditionOperands( // C99 6.5.6
8222 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8223 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8225 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8226 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8227 QualType CheckShiftOperands( // C99 6.5.7
8228 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8229 BinaryOperatorKind Opc, bool IsCompAssign = false);
8231 QualType CheckCompareOperands( // C99 6.5.8/9
8232 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8233 BinaryOperatorKind Opc);
8234 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8235 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8236 BinaryOperatorKind Opc);
8237 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8238 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8239 BinaryOperatorKind Opc);
8240 // CheckAssignmentOperands is used for both simple and compound assignment.
8241 // For simple assignment, pass both expressions and a null converted type.
8242 // For compound assignment, pass both expressions and the converted type.
8243 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8244 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8245 BinaryOperatorKind Opc);
8246
8247 /// To be used for checking whether the arguments being passed to
8248 /// function exceeds the number of parameters expected for it.
8249 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8250 bool PartialOverloading = false) {
8251 // We check whether we're just after a comma in code-completion.
8252 if (NumArgs > 0 && PartialOverloading)
8253 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8254 return NumArgs > NumParams;
8255 }
8256
8257 /// Whether the AST is currently being rebuilt to correct immediate
8258 /// invocations. Immediate invocation candidates and references to consteval
8259 /// functions aren't tracked when this is set.
8261
8267
8268 /// Determines whether we are currently in a context that
8269 /// is not evaluated as per C++ [expr] p5.
8272 }
8273
8277
8281
8285
8292
8293 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8295 assert(!ExprEvalContexts.empty() &&
8296 "Must be in an expression evaluation context");
8297 for (const auto &Ctx : llvm::reverse(ExprEvalContexts)) {
8299 Ctx.DelayedDefaultInitializationContext)
8300 return Ctx.DelayedDefaultInitializationContext;
8301 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8302 Ctx.isUnevaluated())
8303 break;
8304 }
8305 return std::nullopt;
8306 }
8307
8308 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8310 assert(!ExprEvalContexts.empty() &&
8311 "Must be in an expression evaluation context");
8312 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8313 for (auto &Ctx : llvm::reverse(ExprEvalContexts)) {
8315 !Ctx.DelayedDefaultInitializationContext && Res)
8316 break;
8317 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8318 Ctx.isUnevaluated())
8319 break;
8320 Res = Ctx.DelayedDefaultInitializationContext;
8321 }
8322 return Res;
8323 }
8324
8328
8329 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8330 /// SelfAssigned when inside a CXXMethodDecl.
8331 const FieldDecl *
8333
8335
8336 template <typename... Ts>
8338 const Ts &...Args) {
8339 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8340 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8341 }
8342
8343 template <typename... Ts>
8344 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8345 const Ts &...Args) {
8346 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8348 }
8349
8350 /// Abstract class used to diagnose incomplete types.
8353
8354 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
8355 virtual ~TypeDiagnoser() {}
8356 };
8357
8358 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8359 protected:
8360 unsigned DiagID;
8361 std::tuple<const Ts &...> Args;
8362
8363 template <std::size_t... Is>
8365 std::index_sequence<Is...>) const {
8366 // Apply all tuple elements to the builder in order.
8367 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8368 (void)Dummy;
8369 }
8370
8371 public:
8372 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8373 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8374 assert(DiagID != 0 && "no diagnostic for type diagnoser");
8375 }
8376
8377 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8378 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8379 emit(DB, std::index_sequence_for<Ts...>());
8380 DB << T;
8381 }
8382 };
8383
8384 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8385 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8386 /// For example, a diagnostic with no other parameters would generally have
8387 /// the form "...%select{incomplete|sizeless}0 type %1...".
8388 template <typename... Ts>
8390 public:
8391 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8392 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8393
8394 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8395 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8396 this->emit(DB, std::index_sequence_for<Ts...>());
8397 DB << T->isSizelessType() << T;
8398 }
8399 };
8400
8401 /// Check an argument list for placeholders that we won't try to
8402 /// handle later.
8404
8405 /// The C++ "std::source_location::__impl" struct, defined in
8406 /// <source_location>.
8408
8409 /// A stack of expression evaluation contexts.
8411
8412 // Set of failed immediate invocations to avoid double diagnosing.
8414
8415 /// List of SourceLocations where 'self' is implicitly retained inside a
8416 /// block.
8419
8420 /// Do an explicit extend of the given block pointer if we're in ARC.
8422
8423 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8426
8427private:
8428 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8429
8430 /// Methods for marking which expressions involve dereferencing a pointer
8431 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8432 /// they are parsed, meaning that a noderef pointer may not be accessed. For
8433 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8434 /// `*p`, but need to check that `address of` is called on it. This requires
8435 /// keeping a container of all pending expressions and checking if the address
8436 /// of them are eventually taken.
8437 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8438 void CheckAddressOfNoDeref(const Expr *E);
8439
8440 ///@}
8441
8442 //
8443 //
8444 // -------------------------------------------------------------------------
8445 //
8446 //
8447
8448 /// \name C++ Expressions
8449 /// Implementations are in SemaExprCXX.cpp
8450 ///@{
8451
8452public:
8453 /// The C++ "std::bad_alloc" class, which is defined by the C++
8454 /// standard library.
8456
8457 /// The C++ "std::align_val_t" enum class, which is defined by the C++
8458 /// standard library.
8460
8461 /// The C++ "type_info" declaration, which is defined in <typeinfo>.
8463
8464 /// A flag to remember whether the implicit forms of operator new and delete
8465 /// have been declared.
8467
8468 /// Delete-expressions to be analyzed at the end of translation unit
8469 ///
8470 /// This list contains class members, and locations of delete-expressions
8471 /// that could not be proven as to whether they mismatch with new-expression
8472 /// used in initializer of the field.
8473 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8474
8475 /// Handle the result of the special case name lookup for inheriting
8476 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8477 /// constructor names in member using declarations, even if 'X' is not the
8478 /// name of the corresponding type.
8480 SourceLocation NameLoc,
8481 const IdentifierInfo &Name);
8482
8484 SourceLocation NameLoc, Scope *S,
8485 CXXScopeSpec &SS, bool EnteringContext);
8487 Scope *S, CXXScopeSpec &SS,
8488 ParsedType ObjectType, bool EnteringContext);
8489
8491 ParsedType ObjectType);
8492
8493 /// Build a C++ typeid expression with a type operand.
8494 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8495 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8496
8497 /// Build a C++ typeid expression with an expression operand.
8498 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8499 Expr *Operand, SourceLocation RParenLoc);
8500
8501 /// ActOnCXXTypeid - Parse typeid( something ).
8503 bool isType, void *TyOrExpr,
8504 SourceLocation RParenLoc);
8505
8506 /// Build a Microsoft __uuidof expression with a type operand.
8507 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8508 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8509
8510 /// Build a Microsoft __uuidof expression with an expression operand.
8511 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8512 Expr *Operand, SourceLocation RParenLoc);
8513
8514 /// ActOnCXXUuidof - Parse __uuidof( something ).
8516 bool isType, void *TyOrExpr,
8517 SourceLocation RParenLoc);
8518
8519 //// ActOnCXXThis - Parse 'this' pointer.
8521
8522 /// Check whether the type of 'this' is valid in the current context.
8524
8525 /// Build a CXXThisExpr and mark it referenced in the current context.
8526 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8528
8529 /// Try to retrieve the type of the 'this' pointer.
8530 ///
8531 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8533
8534 /// When non-NULL, the C++ 'this' expression is allowed despite the
8535 /// current context not being a non-static member function. In such cases,
8536 /// this provides the type used for 'this'.
8538
8539 /// RAII object used to temporarily allow the C++ 'this' expression
8540 /// to be used, with the given qualifiers on the current class type.
8542 Sema &S;
8543 QualType OldCXXThisTypeOverride;
8544 bool Enabled;
8545
8546 public:
8547 /// Introduce a new scope where 'this' may be allowed (when enabled),
8548 /// using the given declaration (which is either a class template or a
8549 /// class) along with the given qualifiers.
8550 /// along with the qualifiers placed on '*this'.
8551 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8552 bool Enabled = true);
8553
8557 };
8558
8559 /// Make sure the value of 'this' is actually available in the current
8560 /// context, if it is a potentially evaluated context.
8561 ///
8562 /// \param Loc The location at which the capture of 'this' occurs.
8563 ///
8564 /// \param Explicit Whether 'this' is explicitly captured in a lambda
8565 /// capture list.
8566 ///
8567 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8568 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8569 /// This is useful when enclosing lambdas must speculatively capture
8570 /// 'this' that may or may not be used in certain specializations of
8571 /// a nested generic lambda (depending on whether the name resolves to
8572 /// a non-static member function or a static function).
8573 /// \return returns 'true' if failed, 'false' if success.
8575 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8576 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8577 bool ByCopy = false);
8578
8579 /// Determine whether the given type is the type of *this that is used
8580 /// outside of the body of a member function for a type that is currently
8581 /// being defined.
8583
8584 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8586
8587 /// Build a boolean-typed literal expression.
8589
8590 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8592
8593 //// ActOnCXXThrow - Parse throw expressions.
8596 bool IsThrownVarInScope);
8597
8598 /// CheckCXXThrowOperand - Validate the operand of a throw.
8599 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8600
8601 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8602 /// Can be interpreted either as function-style casting ("int(x)")
8603 /// or class type construction ("ClassType(x,y,z)")
8604 /// or creation of a value-initialized type ("int()").
8606 SourceLocation LParenOrBraceLoc,
8607 MultiExprArg Exprs,
8608 SourceLocation RParenOrBraceLoc,
8609 bool ListInitialization);
8610
8612 SourceLocation LParenLoc,
8613 MultiExprArg Exprs,
8614 SourceLocation RParenLoc,
8615 bool ListInitialization);
8616
8617 /// Parsed a C++ 'new' expression (C++ 5.3.4).
8618 ///
8619 /// E.g.:
8620 /// @code new (memory) int[size][4] @endcode
8621 /// or
8622 /// @code ::new Foo(23, "hello") @endcode
8623 ///
8624 /// \param StartLoc The first location of the expression.
8625 /// \param UseGlobal True if 'new' was prefixed with '::'.
8626 /// \param PlacementLParen Opening paren of the placement arguments.
8627 /// \param PlacementArgs Placement new arguments.
8628 /// \param PlacementRParen Closing paren of the placement arguments.
8629 /// \param TypeIdParens If the type is in parens, the source range.
8630 /// \param D The type to be allocated, as well as array dimensions.
8631 /// \param Initializer The initializing expression or initializer-list, or
8632 /// null if there is none.
8633 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8634 SourceLocation PlacementLParen,
8635 MultiExprArg PlacementArgs,
8636 SourceLocation PlacementRParen,
8637 SourceRange TypeIdParens, Declarator &D,
8638 Expr *Initializer);
8640 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8641 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8642 SourceRange TypeIdParens, QualType AllocType,
8643 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8644 SourceRange DirectInitRange, Expr *Initializer);
8645
8646 /// Determine whether \p FD is an aligned allocation or deallocation
8647 /// function that is unavailable.
8649
8650 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8651 /// function that is unavailable.
8653 SourceLocation Loc);
8654
8655 /// Checks that a type is suitable as the allocated type
8656 /// in a new-expression.
8657 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8658 SourceRange R);
8659
8660 /// Finds the overloads of operator new and delete that are appropriate
8661 /// for the allocation.
8663 SourceLocation StartLoc, SourceRange Range,
8665 QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP,
8666 MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew,
8667 FunctionDecl *&OperatorDelete, bool Diagnose = true);
8668
8669 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8670 /// delete. These are:
8671 /// @code
8672 /// // C++03:
8673 /// void* operator new(std::size_t) throw(std::bad_alloc);
8674 /// void* operator new[](std::size_t) throw(std::bad_alloc);
8675 /// void operator delete(void *) throw();
8676 /// void operator delete[](void *) throw();
8677 /// // C++11:
8678 /// void* operator new(std::size_t);
8679 /// void* operator new[](std::size_t);
8680 /// void operator delete(void *) noexcept;
8681 /// void operator delete[](void *) noexcept;
8682 /// // C++1y:
8683 /// void* operator new(std::size_t);
8684 /// void* operator new[](std::size_t);
8685 /// void operator delete(void *) noexcept;
8686 /// void operator delete[](void *) noexcept;
8687 /// void operator delete(void *, std::size_t) noexcept;
8688 /// void operator delete[](void *, std::size_t) noexcept;
8689 /// @endcode
8690 /// Note that the placement and nothrow forms of new are *not* implicitly
8691 /// declared. Their use requires including <new>.
8694 ArrayRef<QualType> Params);
8695
8697 DeclarationName Name, FunctionDecl *&Operator,
8699 bool Diagnose = true);
8702 DeclarationName Name,
8703 bool Diagnose = true);
8705 CXXRecordDecl *RD,
8706 bool Diagnose,
8707 bool LookForGlobal,
8708 DeclarationName Name);
8709
8710 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8711 /// @code ::delete ptr; @endcode
8712 /// or
8713 /// @code delete [] ptr; @endcode
8714 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8715 bool ArrayForm, Expr *Operand);
8717 bool IsDelete, bool CallCanBeVirtual,
8718 bool WarnOnNonAbstractTypes,
8719 SourceLocation DtorLoc);
8720
8722 Expr *Operand, SourceLocation RParen);
8724 SourceLocation RParen);
8725
8727 SourceLocation OpLoc,
8728 tok::TokenKind OpKind,
8729 ParsedType &ObjectType,
8730 bool &MayBePseudoDestructor);
8731
8733 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8734 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8735 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8736
8738 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8739 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8740 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8741
8743 SourceLocation OpLoc,
8744 tok::TokenKind OpKind,
8745 SourceLocation TildeLoc,
8746 const DeclSpec &DS);
8747
8748 /// MaybeCreateExprWithCleanups - If the current full-expression
8749 /// requires any cleanups, surround it with a ExprWithCleanups node.
8750 /// Otherwise, just returns the passed-in expression.
8754
8755 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8756 return ActOnFinishFullExpr(
8757 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8758 }
8760 bool DiscardedValue, bool IsConstexpr = false,
8761 bool IsTemplateArgument = false);
8763
8764 /// Process the expression contained within a decltype. For such expressions,
8765 /// certain semantic checks on temporaries are delayed until this point, and
8766 /// are omitted for the 'topmost' call in the decltype expression. If the
8767 /// topmost call bound a temporary, strip that temporary off the expression.
8769
8770 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8771 bool IsUDSuffix);
8772
8774
8775 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8776 SourceLocation StmtLoc,
8777 ConditionKind CK);
8778
8779 /// Check the use of the given variable as a C++ condition in an if,
8780 /// while, do-while, or switch statement.
8782 SourceLocation StmtLoc, ConditionKind CK);
8783
8784 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8785 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8786
8787 /// Helper function to determine whether this is the (deprecated) C++
8788 /// conversion from a string literal to a pointer to non-const char or
8789 /// non-const wchar_t (for narrow and wide string literals,
8790 /// respectively).
8792
8793 /// PerformImplicitConversion - Perform an implicit conversion of the
8794 /// expression From to the type ToType using the pre-computed implicit
8795 /// conversion sequence ICS. Returns the converted
8796 /// expression. Action is the kind of conversion we're performing,
8797 /// used in the error message.
8799 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8800 AssignmentAction Action,
8802
8803 /// PerformImplicitConversion - Perform an implicit conversion of the
8804 /// expression From to the type ToType by following the standard
8805 /// conversion sequence SCS. Returns the converted
8806 /// expression. Flavor is the context in which we're performing this
8807 /// conversion, for use in error messages.
8809 const StandardConversionSequence &SCS,
8810 AssignmentAction Action,
8812
8813 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8814
8815 /// Parsed one of the type trait support pseudo-functions.
8816 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8818 SourceLocation RParenLoc);
8819 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8821 SourceLocation RParenLoc);
8822
8823 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8824 /// pseudo-functions.
8825 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8826 ParsedType LhsTy, Expr *DimExpr,
8827 SourceLocation RParen);
8828
8829 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8830 TypeSourceInfo *TSInfo, Expr *DimExpr,
8831 SourceLocation RParen);
8832
8833 /// ActOnExpressionTrait - Parsed one of the unary type trait support
8834 /// pseudo-functions.
8835 ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8836 Expr *Queried, SourceLocation RParen);
8837
8838 ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8839 Expr *Queried, SourceLocation RParen);
8840
8843 bool isIndirect);
8845 ExprResult &RHS,
8846 SourceLocation QuestionLoc);
8847
8848 //// Determines if a type is trivially relocatable
8849 /// according to the C++26 rules.
8850 // FIXME: This is in Sema because it requires
8851 // overload resolution, can we move to ASTContext?
8854
8855 /// Check the operands of ?: under C++ semantics.
8856 ///
8857 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8858 /// extension. In this case, LHS == Cond. (But they're not aliases.)
8859 ///
8860 /// This function also implements GCC's vector extension and the
8861 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8862 /// permit the use of a?b:c where the type of a is that of a integer vector
8863 /// with the same number of elements and size as the vectors of b and c. If
8864 /// one of either b or c is a scalar it is implicitly converted to match the
8865 /// type of the vector. Otherwise the expression is ill-formed. If both b and
8866 /// c are scalars, then b and c are checked and converted to the type of a if
8867 /// possible.
8868 ///
8869 /// The expressions are evaluated differently for GCC's and OpenCL's
8870 /// extensions. For the GCC extension, the ?: operator is evaluated as
8871 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8872 /// For the OpenCL extensions, the ?: operator is evaluated as
8873 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
8874 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
8876 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8877 ExprObjectKind &OK, SourceLocation questionLoc);
8878
8879 /// Find a merged pointer type and convert the two expressions to it.
8880 ///
8881 /// This finds the composite pointer type for \p E1 and \p E2 according to
8882 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8883 /// it. It does not emit diagnostics (FIXME: that's not true if \p
8884 /// ConvertArgs is \c true).
8885 ///
8886 /// \param Loc The location of the operator requiring these two expressions to
8887 /// be converted to the composite pointer type.
8888 ///
8889 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
8890 /// type.
8892 bool ConvertArgs = true);
8894 ExprResult &E2, bool ConvertArgs = true) {
8895 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8896 QualType Composite =
8897 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
8898 E1 = E1Tmp;
8899 E2 = E2Tmp;
8900 return Composite;
8901 }
8902
8903 /// MaybeBindToTemporary - If the passed in expression has a record type with
8904 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
8905 /// it simply returns the passed in expression.
8907
8908 /// IgnoredValueConversions - Given that an expression's result is
8909 /// syntactically ignored, perform any conversions that are
8910 /// required.
8912
8914
8917 const DeclarationNameInfo &TargetNameInfo);
8918
8920 SourceLocation KeywordLoc,
8921 bool IsIfExists, CXXScopeSpec &SS,
8922 UnqualifiedId &Name);
8923
8926 ArrayRef<ParmVarDecl *> LocalParameters,
8927 Scope *BodyScope);
8931 CXXScopeSpec &SS,
8932 SourceLocation NameLoc,
8933 const IdentifierInfo *TypeName,
8934 TemplateIdAnnotation *TemplateId);
8936 SourceLocation NoexceptLoc);
8938 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8939 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8942 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8946 bool IsSatisfied, SourceLocation NoexceptLoc,
8953 BuildNestedRequirement(StringRef InvalidConstraintEntity,
8954 const ASTConstraintSatisfaction &Satisfaction);
8957 SourceLocation LParenLoc,
8958 ArrayRef<ParmVarDecl *> LocalParameters,
8959 SourceLocation RParenLoc,
8961 SourceLocation ClosingBraceLoc);
8962
8963private:
8964 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
8965 bool IsDelete);
8966
8967 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8968 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8969 bool DeleteWasArrayForm);
8970
8971 ///@}
8972
8973 //
8974 //
8975 // -------------------------------------------------------------------------
8976 //
8977 //
8978
8979 /// \name Member Access Expressions
8980 /// Implementations are in SemaExprMember.cpp
8981 ///@{
8982
8983public:
8984 /// Check whether an expression might be an implicit class member access.
8986 bool IsAddressOfOperand);
8987
8988 /// Builds an expression which might be an implicit member expression.
8990 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
8991 const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
8992
8993 /// Builds an implicit member access expression. The current context
8994 /// is known to be an instance method, and the given unqualified lookup
8995 /// set is known to contain only instance members, at least one of which
8996 /// is from an appropriate type.
8998 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8999 LookupResult &R,
9000 const TemplateArgumentListInfo *TemplateArgs,
9001 bool IsDefiniteInstance, const Scope *S);
9002
9004 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
9005 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9006 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9007 const TemplateArgumentListInfo *TemplateArgs);
9008
9009 /// The main callback when the parser finds something like
9010 /// expression . [nested-name-specifier] identifier
9011 /// expression -> [nested-name-specifier] identifier
9012 /// where 'identifier' encompasses a fairly broad spectrum of
9013 /// possibilities, including destructor and operator references.
9014 ///
9015 /// \param OpKind either tok::arrow or tok::period
9016 /// \param ObjCImpDecl the current Objective-C \@implementation
9017 /// decl; this is an ugly hack around the fact that Objective-C
9018 /// \@implementations aren't properly put in the context chain
9020 tok::TokenKind OpKind, CXXScopeSpec &SS,
9021 SourceLocation TemplateKWLoc,
9022 UnqualifiedId &Member, Decl *ObjCImpDecl);
9023
9024 MemberExpr *
9025 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
9026 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
9027 ValueDecl *Member, DeclAccessPair FoundDecl,
9028 bool HadMultipleCandidates,
9029 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
9031 const TemplateArgumentListInfo *TemplateArgs = nullptr);
9032
9033 // Check whether the declarations we found through a nested-name
9034 // specifier in a member expression are actually members of the base
9035 // type. The restriction here is:
9036 //
9037 // C++ [expr.ref]p2:
9038 // ... In these cases, the id-expression shall name a
9039 // member of the class or of one of its base classes.
9040 //
9041 // So it's perfectly legitimate for the nested-name specifier to name
9042 // an unrelated class, and for us to find an overload set including
9043 // decls from classes which are not superclasses, as long as the decl
9044 // we actually pick through overload resolution is from a superclass.
9045 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
9046 const CXXScopeSpec &SS,
9047 const LookupResult &R);
9048
9049 // This struct is for use by ActOnMemberAccess to allow
9050 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
9051 // changing the access operator from a '.' to a '->' (to see if that is the
9052 // change needed to fix an error about an unknown member, e.g. when the class
9053 // defines a custom operator->).
9059
9061 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
9062 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9063 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9064 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
9065 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9066
9069 bool IsArrow, const CXXScopeSpec &SS,
9070 SourceLocation TemplateKWLoc,
9071 NamedDecl *FirstQualifierInScope, LookupResult &R,
9072 const TemplateArgumentListInfo *TemplateArgs,
9073 const Scope *S, bool SuppressQualifierCheck = false,
9074 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9075
9076 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
9077 SourceLocation OpLoc,
9078 const CXXScopeSpec &SS, FieldDecl *Field,
9079 DeclAccessPair FoundDecl,
9080 const DeclarationNameInfo &MemberNameInfo);
9081
9082 /// Perform conversions on the LHS of a member access expression.
9084
9086 const CXXScopeSpec &SS, SourceLocation nameLoc,
9087 IndirectFieldDecl *indirectField,
9088 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
9089 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
9090
9091private:
9092 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
9093
9094 ///@}
9095
9096 //
9097 //
9098 // -------------------------------------------------------------------------
9099 //
9100 //
9101
9102 /// \name Initializers
9103 /// Implementations are in SemaInit.cpp
9104 ///@{
9105
9106public:
9107 /// Stack of types that correspond to the parameter entities that are
9108 /// currently being copy-initialized. Can be empty.
9110
9111 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
9113
9114 bool IsStringInit(Expr *Init, const ArrayType *AT);
9115
9116 /// Determine whether we can perform aggregate initialization for the purposes
9117 /// of overload resolution.
9119 const InitializedEntity &Entity, InitListExpr *From);
9120
9122 SourceLocation EqualOrColonLoc,
9123 bool GNUSyntax, ExprResult Init);
9124
9125 /// Check that the lifetime of the initializer (and its subobjects) is
9126 /// sufficient for initializing the entity, and perform lifetime extension
9127 /// (when permitted) if not.
9129
9132 bool BoundToLvalueReference);
9133
9134 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9135 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9136 /// we don't have xvalues there.
9138
9142
9146 SourceLocation EqualLoc, ExprResult Init,
9147 bool TopLevelOfInitList = false,
9148 bool AllowExplicit = false);
9149
9151 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9152 const InitializationKind &Kind, MultiExprArg Init);
9153
9154 ///@}
9155
9156 //
9157 //
9158 // -------------------------------------------------------------------------
9159 //
9160 //
9161
9162 /// \name C++ Lambda Expressions
9163 /// Implementations are in SemaLambda.cpp
9164 ///@{
9165
9166public:
9167 /// Create a new lambda closure type.
9169 TypeSourceInfo *Info,
9170 unsigned LambdaDependencyKind,
9171 LambdaCaptureDefault CaptureDefault);
9172
9173 /// Number lambda for linkage purposes if necessary.
9175 std::optional<CXXRecordDecl::LambdaNumbering>
9176 NumberingOverride = std::nullopt);
9177
9178 /// Endow the lambda scope info with the relevant properties.
9179 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9180 SourceRange IntroducerRange,
9181 LambdaCaptureDefault CaptureDefault,
9182 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9183 bool Mutable);
9184
9187
9189 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9190 TemplateParameterList *TemplateParams);
9191
9192 void
9194 SourceLocation CallOperatorLoc,
9195 const AssociatedConstraint &TrailingRequiresClause,
9196 TypeSourceInfo *MethodTyInfo,
9197 ConstexprSpecKind ConstexprKind, StorageClass SC,
9199 bool HasExplicitResultType);
9200
9201 /// Returns true if the explicit object parameter was invalid.
9203 SourceLocation CallLoc);
9204
9205 /// Perform initialization analysis of the init-capture and perform
9206 /// any implicit conversions such as an lvalue-to-rvalue conversion if
9207 /// not being used to initialize a reference.
9209 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9210 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9212 Loc, ByRef, EllipsisLoc, std::nullopt, Id,
9214 }
9216 SourceLocation EllipsisLoc,
9217 UnsignedOrNone NumExpansions,
9218 IdentifierInfo *Id,
9219 bool DirectInit, Expr *&Init);
9220
9221 /// Create a dummy variable within the declcontext of the lambda's
9222 /// call operator, for name lookup purposes for a lambda init capture.
9223 ///
9224 /// CodeGen handles emission of lambda captures, ignoring these dummy
9225 /// variables appropriately.
9227 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9228 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9229
9230 /// Add an init-capture to a lambda scope.
9231 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9232
9233 /// Note that we have finished the explicit captures for the
9234 /// given lambda.
9236
9237 /// Deduce a block or lambda's return type based on the return
9238 /// statements present in the body.
9240
9241 /// Once the Lambdas capture are known, we can start to create the closure,
9242 /// call operator method, and keep track of the captures.
9243 /// We do the capture lookup here, but they are not actually captured until
9244 /// after we know what the qualifiers of the call operator are.
9246 Scope *CurContext);
9247
9248 /// This is called after parsing the explicit template parameter list
9249 /// on a lambda (if it exists) in C++2a.
9251 SourceLocation LAngleLoc,
9252 ArrayRef<NamedDecl *> TParams,
9253 SourceLocation RAngleLoc,
9254 ExprResult RequiresClause);
9255
9257 SourceLocation MutableLoc);
9258
9260 Scope *LambdaScope,
9262
9263 /// ActOnStartOfLambdaDefinition - This is called just before we start
9264 /// parsing the body of a lambda; it analyzes the explicit captures and
9265 /// arguments, and sets up various data-structures for the body of the
9266 /// lambda.
9268 Declarator &ParamInfo, const DeclSpec &DS);
9269
9270 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9271 /// is invoked to pop the information about the lambda.
9272 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9273 bool IsInstantiation = false);
9274
9275 /// ActOnLambdaExpr - This is called when the body of a lambda expression
9276 /// was successfully completed.
9278
9279 /// Does copying/destroying the captured variable have side effects?
9280 bool CaptureHasSideEffects(const sema::Capture &From);
9281
9282 /// Diagnose if an explicit lambda capture is unused. Returns true if a
9283 /// diagnostic is emitted.
9284 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9285 SourceRange FixItRange,
9286 const sema::Capture &From);
9287
9288 /// Build a FieldDecl suitable to hold the given capture.
9290
9291 /// Initialize the given capture with a suitable expression.
9293 SourceLocation ImplicitCaptureLoc,
9294 bool IsOpenMPMapping = false);
9295
9296 /// Complete a lambda-expression having processed and attached the
9297 /// lambda body.
9299
9300 /// Get the return type to use for a lambda's conversion function(s) to
9301 /// function pointer type, given the type of the call operator.
9302 QualType
9304 CallingConv CC);
9305
9307 SourceLocation ConvLocation,
9308 CXXConversionDecl *Conv, Expr *Src);
9309
9311 : private FunctionScopeRAII {
9312 public:
9314 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9316 bool ShouldAddDeclsFromParentScope = true);
9317 };
9318
9319 /// Compute the mangling number context for a lambda expression or
9320 /// block literal. Also return the extra mangling decl if any.
9321 ///
9322 /// \param DC - The DeclContext containing the lambda expression or
9323 /// block literal.
9324 std::tuple<MangleNumberingContext *, Decl *>
9326
9327 ///@}
9328
9329 //
9330 //
9331 // -------------------------------------------------------------------------
9332 //
9333 //
9334
9335 /// \name Name Lookup
9336 ///
9337 /// These routines provide name lookup that is used during semantic
9338 /// analysis to resolve the various kinds of names (identifiers,
9339 /// overloaded operator names, constructor names, etc.) into zero or
9340 /// more declarations within a particular scope. The major entry
9341 /// points are LookupName, which performs unqualified name lookup,
9342 /// and LookupQualifiedName, which performs qualified name lookup.
9343 ///
9344 /// All name lookup is performed based on some specific criteria,
9345 /// which specify what names will be visible to name lookup and how
9346 /// far name lookup should work. These criteria are important both
9347 /// for capturing language semantics (certain lookups will ignore
9348 /// certain names, for example) and for performance, since name
9349 /// lookup is often a bottleneck in the compilation of C++. Name
9350 /// lookup criteria is specified via the LookupCriteria enumeration.
9351 ///
9352 /// The results of name lookup can vary based on the kind of name
9353 /// lookup performed, the current language, and the translation
9354 /// unit. In C, for example, name lookup will either return nothing
9355 /// (no entity found) or a single declaration. In C++, name lookup
9356 /// can additionally refer to a set of overloaded functions or
9357 /// result in an ambiguity. All of the possible results of name
9358 /// lookup are captured by the LookupResult class, which provides
9359 /// the ability to distinguish among them.
9360 ///
9361 /// Implementations are in SemaLookup.cpp
9362 ///@{
9363
9364public:
9365 /// Tracks whether we are in a context where typo correction is
9366 /// disabled.
9368
9369 /// The number of typos corrected by CorrectTypo.
9371
9372 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9373 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9374
9375 /// A cache containing identifiers for which typo correction failed and
9376 /// their locations, so that repeated attempts to correct an identifier in a
9377 /// given location are ignored if typo correction already failed for it.
9379
9380 /// SpecialMemberOverloadResult - The overloading result for a special member
9381 /// function.
9382 ///
9383 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9384 /// integer are used to determine whether overload resolution succeeded.
9386 public:
9388
9389 private:
9390 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9391
9392 public:
9395 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9396
9397 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
9398 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9399
9400 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
9401 void setKind(Kind K) { Pair.setInt(K); }
9402 };
9403
9404 class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode,
9406 public:
9407 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
9408 : FastFoldingSetNode(ID) {}
9409 };
9410
9411 /// A cache of special member function overload resolution results
9412 /// for C++ records.
9413 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
9414
9416
9417 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9418 // TODO: make this is a typesafe union.
9421
9422 /// Describes the kind of name lookup to perform.
9424 /// Ordinary name lookup, which finds ordinary names (functions,
9425 /// variables, typedefs, etc.) in C and most kinds of names
9426 /// (functions, variables, members, types, etc.) in C++.
9428 /// Tag name lookup, which finds the names of enums, classes,
9429 /// structs, and unions.
9431 /// Label name lookup.
9433 /// Member name lookup, which finds the names of
9434 /// class/struct/union members.
9436 /// Look up of an operator name (e.g., operator+) for use with
9437 /// operator overloading. This lookup is similar to ordinary name
9438 /// lookup, but will ignore any declarations that are class members.
9440 /// Look up a name following ~ in a destructor name. This is an ordinary
9441 /// lookup, but prefers tags to typedefs.
9443 /// Look up of a name that precedes the '::' scope resolution
9444 /// operator in C++. This lookup completely ignores operator, object,
9445 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9447 /// Look up a namespace name within a C++ using directive or
9448 /// namespace alias definition, ignoring non-namespace names (C++
9449 /// [basic.lookup.udir]p1).
9451 /// Look up all declarations in a scope with the given name,
9452 /// including resolved using declarations. This is appropriate
9453 /// for checking redeclarations for a using declaration.
9455 /// Look up an ordinary name that is going to be redeclared as a
9456 /// name with linkage. This lookup ignores any declarations that
9457 /// are outside of the current scope unless they have linkage. See
9458 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9460 /// Look up a friend of a local class. This lookup does not look
9461 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9463 /// Look up the name of an Objective-C protocol.
9465 /// Look up implicit 'self' parameter of an objective-c method.
9467 /// Look up the name of an OpenMP user-defined reduction operation.
9469 /// Look up the name of an OpenMP user-defined mapper.
9471 /// Look up any declaration with any name.
9473 };
9474
9475 /// The possible outcomes of name lookup for a literal operator.
9477 /// The lookup resulted in an error.
9479 /// The lookup found no match but no diagnostic was issued.
9481 /// The lookup found a single 'cooked' literal operator, which
9482 /// expects a normal literal to be built and passed to it.
9484 /// The lookup found a single 'raw' literal operator, which expects
9485 /// a string literal containing the spelling of the literal token.
9487 /// The lookup found an overload set of literal operator templates,
9488 /// which expect the characters of the spelling of the literal token to be
9489 /// passed as a non-type template argument pack.
9491 /// The lookup found an overload set of literal operator templates,
9492 /// which expect the character type and characters of the spelling of the
9493 /// string literal token to be passed as template arguments.
9495 };
9496
9497 SpecialMemberOverloadResult
9499 bool VolatileArg, bool RValueThis, bool ConstThis,
9500 bool VolatileThis);
9501
9503
9504 /// Look up a name, looking for a single declaration. Return
9505 /// null if the results were absent, ambiguous, or overloaded.
9506 ///
9507 /// It is preferable to use the elaborated form and explicitly handle
9508 /// ambiguity and overloaded.
9510 Scope *S, DeclarationName Name, SourceLocation Loc,
9511 LookupNameKind NameKind,
9513
9514 /// Lookup a builtin function, when name lookup would otherwise
9515 /// fail.
9516 bool LookupBuiltin(LookupResult &R);
9517 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9518
9519 /// Perform unqualified name lookup starting from a given
9520 /// scope.
9521 ///
9522 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9523 /// used to find names within the current scope. For example, 'x' in
9524 /// @code
9525 /// int x;
9526 /// int f() {
9527 /// return x; // unqualified name look finds 'x' in the global scope
9528 /// }
9529 /// @endcode
9530 ///
9531 /// Different lookup criteria can find different names. For example, a
9532 /// particular scope can have both a struct and a function of the same
9533 /// name, and each can be found by certain lookup criteria. For more
9534 /// information about lookup criteria, see the documentation for the
9535 /// class LookupCriteria.
9536 ///
9537 /// @param S The scope from which unqualified name lookup will
9538 /// begin. If the lookup criteria permits, name lookup may also search
9539 /// in the parent scopes.
9540 ///
9541 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9542 /// look up and the lookup kind), and is updated with the results of lookup
9543 /// including zero or more declarations and possibly additional information
9544 /// used to diagnose ambiguities.
9545 ///
9546 /// @returns \c true if lookup succeeded and false otherwise.
9547 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9548 bool ForceNoCPlusPlus = false);
9549
9550 /// Perform qualified name lookup into a given context.
9551 ///
9552 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9553 /// names when the context of those names is explicit specified, e.g.,
9554 /// "std::vector" or "x->member", or as part of unqualified name lookup.
9555 ///
9556 /// Different lookup criteria can find different names. For example, a
9557 /// particular scope can have both a struct and a function of the same
9558 /// name, and each can be found by certain lookup criteria. For more
9559 /// information about lookup criteria, see the documentation for the
9560 /// class LookupCriteria.
9561 ///
9562 /// \param R captures both the lookup criteria and any lookup results found.
9563 ///
9564 /// \param LookupCtx The context in which qualified name lookup will
9565 /// search. If the lookup criteria permits, name lookup may also search
9566 /// in the parent contexts or (for C++ classes) base classes.
9567 ///
9568 /// \param InUnqualifiedLookup true if this is qualified name lookup that
9569 /// occurs as part of unqualified name lookup.
9570 ///
9571 /// \returns true if lookup succeeded, false if it failed.
9572 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9573 bool InUnqualifiedLookup = false);
9574
9575 /// Performs qualified name lookup or special type of lookup for
9576 /// "__super::" scope specifier.
9577 ///
9578 /// This routine is a convenience overload meant to be called from contexts
9579 /// that need to perform a qualified name lookup with an optional C++ scope
9580 /// specifier that might require special kind of lookup.
9581 ///
9582 /// \param R captures both the lookup criteria and any lookup results found.
9583 ///
9584 /// \param LookupCtx The context in which qualified name lookup will
9585 /// search.
9586 ///
9587 /// \param SS An optional C++ scope-specifier.
9588 ///
9589 /// \returns true if lookup succeeded, false if it failed.
9590 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9591 CXXScopeSpec &SS);
9592
9593 /// Performs name lookup for a name that was parsed in the
9594 /// source code, and may contain a C++ scope specifier.
9595 ///
9596 /// This routine is a convenience routine meant to be called from
9597 /// contexts that receive a name and an optional C++ scope specifier
9598 /// (e.g., "N::M::x"). It will then perform either qualified or
9599 /// unqualified name lookup (with LookupQualifiedName or LookupName,
9600 /// respectively) on the given name and return those results. It will
9601 /// perform a special type of lookup for "__super::" scope specifier.
9602 ///
9603 /// @param S The scope from which unqualified name lookup will
9604 /// begin.
9605 ///
9606 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
9607 ///
9608 /// @param EnteringContext Indicates whether we are going to enter the
9609 /// context of the scope-specifier SS (if present).
9610 ///
9611 /// @returns True if any decls were found (but possibly ambiguous)
9613 QualType ObjectType, bool AllowBuiltinCreation = false,
9614 bool EnteringContext = false);
9615
9616 /// Perform qualified name lookup into all base classes of the given
9617 /// class.
9618 ///
9619 /// \param R captures both the lookup criteria and any lookup results found.
9620 ///
9621 /// \param Class The context in which qualified name lookup will
9622 /// search. Name lookup will search in all base classes merging the results.
9623 ///
9624 /// @returns True if any decls were found (but possibly ambiguous)
9626
9628 UnresolvedSetImpl &Functions);
9629
9630 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9631 /// If GnuLabelLoc is a valid source location, then this is a definition
9632 /// of an __label__ label name, otherwise it is a normal label definition
9633 /// or use. If IsLabelStmt is true, then this is the label of a
9634 /// labeled-statement.
9636 SourceLocation GnuLabelLoc = SourceLocation(),
9637 bool IsLabelStmt = false);
9638
9639 /// Perform a name lookup for a label with the specified name; this does not
9640 /// create a new label if the lookup fails.
9642
9643 /// Look up the constructors for the given class.
9645
9646 /// Look up the default constructor for the given class.
9648
9649 /// Look up the copying constructor for the given class.
9651 unsigned Quals);
9652
9653 /// Look up the copying assignment operator for the given class.
9655 bool RValueThis, unsigned ThisQuals);
9656
9657 /// Look up the moving constructor for the given class.
9659 unsigned Quals);
9660
9661 /// Look up the moving assignment operator for the given class.
9663 bool RValueThis, unsigned ThisQuals);
9664
9665 /// Look for the destructor of the given class.
9666 ///
9667 /// During semantic analysis, this routine should be used in lieu of
9668 /// CXXRecordDecl::getDestructor().
9669 ///
9670 /// \returns The destructor for this class.
9672
9673 /// Force the declaration of any implicitly-declared members of this
9674 /// class.
9676
9677 /// Make a merged definition of an existing hidden definition \p ND
9678 /// visible at the specified location.
9680
9681 /// Check ODR hashes for C/ObjC when merging types from modules.
9682 /// Differently from C++, actually parse the body and reject in case
9683 /// of a mismatch.
9684 template <typename T,
9685 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
9687 if (Duplicate->getODRHash() != Previous->getODRHash())
9688 return false;
9689
9690 // Make the previous decl visible.
9692 return true;
9693 }
9694
9695 /// Get the set of additional modules that should be checked during
9696 /// name lookup. A module and its imports become visible when instanting a
9697 /// template defined within it.
9698 llvm::DenseSet<Module *> &getLookupModules();
9699
9700 bool hasVisibleMergedDefinition(const NamedDecl *Def);
9702
9703 /// Determine if the template parameter \p D has a visible default argument.
9704 bool
9706 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9707 /// Determine if the template parameter \p D has a reachable default argument.
9709 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9710 /// Determine if the template parameter \p D has a reachable default argument.
9714
9715 /// Determine if there is a visible declaration of \p D that is an explicit
9716 /// specialization declaration for a specialization of a template. (For a
9717 /// member specialization, use hasVisibleMemberSpecialization.)
9719 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9720 /// Determine if there is a reachable declaration of \p D that is an explicit
9721 /// specialization declaration for a specialization of a template. (For a
9722 /// member specialization, use hasReachableMemberSpecialization.)
9724 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9725
9726 /// Determine if there is a visible declaration of \p D that is a member
9727 /// specialization declaration (as opposed to an instantiated declaration).
9729 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9730 /// Determine if there is a reachable declaration of \p D that is a member
9731 /// specialization declaration (as opposed to an instantiated declaration).
9733 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9734
9735 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9736
9737 /// Determine whether any declaration of an entity is visible.
9738 bool
9740 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9741 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9742 }
9743
9746 /// Determine whether any declaration of an entity is reachable.
9747 bool
9749 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9750 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9751 }
9753 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9754
9755 void diagnoseTypo(const TypoCorrection &Correction,
9756 const PartialDiagnostic &TypoDiag,
9757 bool ErrorRecovery = true);
9758
9759 /// Diagnose a successfully-corrected typo. Separated from the correction
9760 /// itself to allow external validation of the result, etc.
9761 ///
9762 /// \param Correction The result of performing typo correction.
9763 /// \param TypoDiag The diagnostic to produce. This will have the corrected
9764 /// string added to it (and usually also a fixit).
9765 /// \param PrevNote A note to use when indicating the location of the entity
9766 /// to which we are correcting. Will have the correction string added
9767 /// to it.
9768 /// \param ErrorRecovery If \c true (the default), the caller is going to
9769 /// recover from the typo as if the corrected string had been typed.
9770 /// In this case, \c PDiag must be an error, and we will attach a fixit
9771 /// to it.
9772 void diagnoseTypo(const TypoCorrection &Correction,
9773 const PartialDiagnostic &TypoDiag,
9774 const PartialDiagnostic &PrevNote,
9775 bool ErrorRecovery = true);
9776
9777 /// Find the associated classes and namespaces for
9778 /// argument-dependent lookup for a call with the given set of
9779 /// arguments.
9780 ///
9781 /// This routine computes the sets of associated classes and associated
9782 /// namespaces searched by argument-dependent lookup
9783 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9785 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9786 AssociatedNamespaceSet &AssociatedNamespaces,
9787 AssociatedClassSet &AssociatedClasses);
9788
9789 /// Produce a diagnostic describing the ambiguity that resulted
9790 /// from name lookup.
9791 ///
9792 /// \param Result The result of the ambiguous lookup to be diagnosed.
9794
9795 /// LookupLiteralOperator - Determine which literal operator should be used
9796 /// for a user-defined literal, per C++11 [lex.ext].
9797 ///
9798 /// Normal overload resolution is not used to select which literal operator to
9799 /// call for a user-defined literal. Look up the provided literal operator
9800 /// name, and filter the results to the appropriate set for the given argument
9801 /// types.
9804 bool AllowRaw, bool AllowTemplate,
9805 bool AllowStringTemplate, bool DiagnoseMissing,
9806 StringLiteral *StringLit = nullptr);
9807
9809 ArrayRef<Expr *> Args, ADLResult &Functions);
9810
9811 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9813 bool IncludeGlobalScope = true,
9814 bool LoadExternal = true);
9815 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9817 bool IncludeGlobalScope = true,
9818 bool IncludeDependentBases = false,
9819 bool LoadExternal = true);
9820
9821 /// Try to "correct" a typo in the source code by finding
9822 /// visible declarations whose names are similar to the name that was
9823 /// present in the source code.
9824 ///
9825 /// \param TypoName the \c DeclarationNameInfo structure that contains
9826 /// the name that was present in the source code along with its location.
9827 ///
9828 /// \param LookupKind the name-lookup criteria used to search for the name.
9829 ///
9830 /// \param S the scope in which name lookup occurs.
9831 ///
9832 /// \param SS the nested-name-specifier that precedes the name we're
9833 /// looking for, if present.
9834 ///
9835 /// \param CCC A CorrectionCandidateCallback object that provides further
9836 /// validation of typo correction candidates. It also provides flags for
9837 /// determining the set of keywords permitted.
9838 ///
9839 /// \param MemberContext if non-NULL, the context in which to look for
9840 /// a member access expression.
9841 ///
9842 /// \param EnteringContext whether we're entering the context described by
9843 /// the nested-name-specifier SS.
9844 ///
9845 /// \param OPT when non-NULL, the search for visible declarations will
9846 /// also walk the protocols in the qualified interfaces of \p OPT.
9847 ///
9848 /// \returns a \c TypoCorrection containing the corrected name if the typo
9849 /// along with information such as the \c NamedDecl where the corrected name
9850 /// was declared, and any additional \c NestedNameSpecifier needed to access
9851 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9853 Sema::LookupNameKind LookupKind, Scope *S,
9855 CorrectTypoKind Mode,
9856 DeclContext *MemberContext = nullptr,
9857 bool EnteringContext = false,
9858 const ObjCObjectPointerType *OPT = nullptr,
9859 bool RecordFailure = true);
9860
9861 /// Kinds of missing import. Note, the values of these enumerators correspond
9862 /// to %select values in diagnostics.
9870
9871 /// Diagnose that the specified declaration needs to be visible but
9872 /// isn't, and suggest a module import that would resolve the problem.
9874 MissingImportKind MIK, bool Recover = true);
9876 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
9877 MissingImportKind MIK, bool Recover);
9878
9879 /// Called on #pragma clang __debug dump II
9881
9882 /// Called on #pragma clang __debug dump E
9883 void ActOnPragmaDump(Expr *E);
9884
9885private:
9886 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
9887 //
9888 // The boolean value will be true to indicate that the namespace was loaded
9889 // from an AST/PCH file, or false otherwise.
9890 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
9891
9892 /// Whether we have already loaded known namespaces from an extenal
9893 /// source.
9894 bool LoadedExternalKnownNamespaces;
9895
9896 bool CppLookupName(LookupResult &R, Scope *S);
9897
9898 /// Determine if we could use all the declarations in the module.
9899 bool isUsableModule(const Module *M);
9900
9901 /// Helper for CorrectTypo used to create and populate a new
9902 /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
9903 /// skipped entirely.
9904 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
9905 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
9907 DeclContext *MemberContext, bool EnteringContext,
9908 const ObjCObjectPointerType *OPT, bool ErrorRecovery);
9909
9910 /// Cache for module units which is usable for current module.
9911 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
9912
9913 /// Record the typo correction failure and return an empty correction.
9914 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
9915 bool RecordFailure = true) {
9916 if (RecordFailure)
9917 TypoCorrectionFailures[Typo].insert(TypoLoc);
9918 return TypoCorrection();
9919 }
9920
9921 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
9922
9923 /// Determine whether two declarations should be linked together, given that
9924 /// the old declaration might not be visible and the new declaration might
9925 /// not have external linkage.
9926 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
9927 const NamedDecl *New) {
9928 if (isVisible(Old))
9929 return true;
9930 // See comment in below overload for why it's safe to compute the linkage
9931 // of the new declaration here.
9932 if (New->isExternallyDeclarable()) {
9933 assert(Old->isExternallyDeclarable() &&
9934 "should not have found a non-externally-declarable previous decl");
9935 return true;
9936 }
9937 return false;
9938 }
9939 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
9940
9941 ///@}
9942
9943 //
9944 //
9945 // -------------------------------------------------------------------------
9946 //
9947 //
9948
9949 /// \name Modules
9950 /// Implementations are in SemaModule.cpp
9951 ///@{
9952
9953public:
9954 /// Get the module unit whose scope we are currently within.
9956 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
9957 }
9958
9959 /// Is the module scope we are an implementation unit?
9961 if (ModuleScopes.empty())
9962 return false;
9963 const Module *M = ModuleScopes.back().Module;
9965 }
9966
9967 // When loading a non-modular PCH files, this is used to restore module
9968 // visibility.
9970 VisibleModules.setVisible(Mod, ImportLoc);
9971 }
9972
9973 enum class ModuleDeclKind {
9974 Interface, ///< 'export module X;'
9975 Implementation, ///< 'module X;'
9976 PartitionInterface, ///< 'export module X:Y;'
9977 PartitionImplementation, ///< 'module X:Y;'
9978 };
9979
9980 /// An enumeration to represent the transition of states in parsing module
9981 /// fragments and imports. If we are not parsing a C++20 TU, or we find
9982 /// an error in state transition, the state is set to NotACXX20Module.
9984 FirstDecl, ///< Parsing the first decl in a TU.
9985 GlobalFragment, ///< after 'module;' but before 'module X;'
9986 ImportAllowed, ///< after 'module X;' but before any non-import decl.
9987 ImportFinished, ///< after any non-import decl.
9988 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
9989 ///< non-import decl.
9990 PrivateFragmentImportFinished, ///< after 'module :private;' but a
9991 ///< non-import decl has already been seen.
9992 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
9993 };
9994
9995 /// The parser has processed a module-declaration that begins the definition
9996 /// of a module interface or implementation.
9998 SourceLocation ModuleLoc, ModuleDeclKind MDK,
9999 ModuleIdPath Path, ModuleIdPath Partition,
10000 ModuleImportState &ImportState,
10001 bool SeenNoTrivialPPDirective);
10002
10003 /// The parser has processed a global-module-fragment declaration that begins
10004 /// the definition of the global module fragment of the current module unit.
10005 /// \param ModuleLoc The location of the 'module' keyword.
10007
10008 /// The parser has processed a private-module-fragment declaration that begins
10009 /// the definition of the private module fragment of the current module unit.
10010 /// \param ModuleLoc The location of the 'module' keyword.
10011 /// \param PrivateLoc The location of the 'private' keyword.
10013 SourceLocation PrivateLoc);
10014
10015 /// The parser has processed a module import declaration.
10016 ///
10017 /// \param StartLoc The location of the first token in the declaration. This
10018 /// could be the location of an '@', 'export', or 'import'.
10019 /// \param ExportLoc The location of the 'export' keyword, if any.
10020 /// \param ImportLoc The location of the 'import' keyword.
10021 /// \param Path The module toplevel name as an access path.
10022 /// \param IsPartition If the name is for a partition.
10024 SourceLocation ExportLoc,
10025 SourceLocation ImportLoc, ModuleIdPath Path,
10026 bool IsPartition = false);
10028 SourceLocation ExportLoc,
10029 SourceLocation ImportLoc, Module *M,
10030 ModuleIdPath Path = {});
10031
10032 /// The parser has processed a module import translated from a
10033 /// #include or similar preprocessing directive.
10034 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10035 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10036
10037 /// The parsed has entered a submodule.
10038 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
10039 /// The parser has left a submodule.
10040 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
10041
10042 /// Create an implicit import of the given module at the given
10043 /// source location, for error recovery, if possible.
10044 ///
10045 /// This routine is typically used when an entity found by name lookup
10046 /// is actually hidden within a module that we know about but the user
10047 /// has forgotten to import.
10048 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
10049 Module *Mod);
10050
10051 /// We have parsed the start of an export declaration, including the '{'
10052 /// (if present).
10053 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
10054 SourceLocation LBraceLoc);
10055
10056 /// Complete the definition of an export declaration.
10057 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
10058 SourceLocation RBraceLoc);
10059
10060private:
10061 /// The parser has begun a translation unit to be compiled as a C++20
10062 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
10063 void HandleStartOfHeaderUnit();
10064
10065 struct ModuleScope {
10066 SourceLocation BeginLoc;
10067 clang::Module *Module = nullptr;
10068 VisibleModuleSet OuterVisibleModules;
10069 };
10070 /// The modules we're currently parsing.
10071 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
10072
10073 /// For an interface unit, this is the implicitly imported interface unit.
10074 clang::Module *ThePrimaryInterface = nullptr;
10075
10076 /// The explicit global module fragment of the current translation unit.
10077 /// The explicit Global Module Fragment, as specified in C++
10078 /// [module.global.frag].
10079 clang::Module *TheGlobalModuleFragment = nullptr;
10080
10081 /// The implicit global module fragments of the current translation unit.
10082 ///
10083 /// The contents in the implicit global module fragment can't be discarded.
10084 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
10085
10086 /// Namespace definitions that we will export when they finish.
10087 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
10088
10089 /// In a C++ standard module, inline declarations require a definition to be
10090 /// present at the end of a definition domain. This set holds the decls to
10091 /// be checked at the end of the TU.
10092 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
10093
10094 /// Helper function to judge if we are in module purview.
10095 /// Return false if we are not in a module.
10096 bool isCurrentModulePurview() const;
10097
10098 /// Enter the scope of the explicit global module fragment.
10099 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
10100 /// Leave the scope of the explicit global module fragment.
10101 void PopGlobalModuleFragment();
10102
10103 /// Enter the scope of an implicit global module fragment.
10104 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
10105 /// Leave the scope of an implicit global module fragment.
10106 void PopImplicitGlobalModuleFragment();
10107
10108 VisibleModuleSet VisibleModules;
10109
10110 /// Whether we had imported any named modules.
10111 bool HadImportedNamedModules = false;
10112 /// The set of instantiations we need to check if they references TU-local
10113 /// entity from TUs. This only makes sense if we imported any named modules.
10114 llvm::SmallVector<std::pair<FunctionDecl *, SourceLocation>>
10115 PendingCheckReferenceForTULocal;
10116 /// Implement [basic.link]p18, which requires that we can't use TU-local
10117 /// entities from other TUs (ignoring header units).
10118 void checkReferenceToTULocalFromOtherTU(FunctionDecl *FD,
10119 SourceLocation PointOfInstantiation);
10120 /// Implement [basic.link]p17, which diagnose for non TU local exposure in
10121 /// module interface or module partition.
10122 void checkExposure(const TranslationUnitDecl *TU);
10123
10124 ///@}
10125
10126 //
10127 //
10128 // -------------------------------------------------------------------------
10129 //
10130 //
10131
10132 /// \name C++ Overloading
10133 /// Implementations are in SemaOverload.cpp
10134 ///@{
10135
10136public:
10137 /// Whether deferrable diagnostics should be deferred.
10138 bool DeferDiags = false;
10139
10140 /// RAII class to control scope of DeferDiags.
10142 Sema &S;
10143 bool SavedDeferDiags = false;
10144
10145 public:
10147 : S(S), SavedDeferDiags(S.DeferDiags) {
10148 S.DeferDiags = SavedDeferDiags || DeferDiags;
10149 }
10150 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
10153 };
10154
10155 /// Flag indicating if Sema is building a recovery call expression.
10156 ///
10157 /// This flag is used to avoid building recovery call expressions
10158 /// if Sema is already doing so, which would cause infinite recursions.
10160
10161 /// Determine whether the given New declaration is an overload of the
10162 /// declarations in Old. This routine returns OverloadKind::Match or
10163 /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
10164 /// New has the same signature as some function in Old (C++ 1.3.10) or if the
10165 /// Old declarations aren't functions (or function templates) at all. When it
10166 /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
10167 /// will point to the decl that New cannot be overloaded with. This decl may
10168 /// be a UsingShadowDecl on top of the underlying declaration.
10169 ///
10170 /// Example: Given the following input:
10171 ///
10172 /// void f(int, float); // #1
10173 /// void f(int, int); // #2
10174 /// int f(int, int); // #3
10175 ///
10176 /// When we process #1, there is no previous declaration of "f", so IsOverload
10177 /// will not be used.
10178 ///
10179 /// When we process #2, Old contains only the FunctionDecl for #1. By
10180 /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10181 /// they have different signatures), so this routine returns
10182 /// OverloadKind::Overload; MatchedDecl is unchanged.
10183 ///
10184 /// When we process #3, Old is an overload set containing #1 and #2. We
10185 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10186 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10187 /// types of functions are not part of the signature), IsOverload returns
10188 /// OverloadKind::Match and MatchedDecl will be set to point to the
10189 /// FunctionDecl for #2.
10190 ///
10191 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10192 /// class by a using declaration. The rules for whether to hide shadow
10193 /// declarations ignore some properties which otherwise figure into a function
10194 /// template's signature.
10196 const LookupResult &OldDecls, NamedDecl *&OldDecl,
10197 bool UseMemberUsingDeclRules);
10199 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10200
10201 // Checks whether MD constitutes an override the base class method BaseMD.
10202 // When checking for overrides, the object object members are ignored.
10203 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10204 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10205
10206 enum class AllowedExplicit {
10207 /// Allow no explicit functions to be used.
10209 /// Allow explicit conversion functions but not explicit constructors.
10211 /// Allow both explicit conversion functions and explicit constructors.
10213 };
10214
10216 Expr *From, QualType ToType, bool SuppressUserConversions,
10217 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10218 bool AllowObjCWritebackConversion);
10219
10220 /// PerformImplicitConversion - Perform an implicit conversion of the
10221 /// expression From to the type ToType. Returns the
10222 /// converted expression. Flavor is the kind of conversion we're
10223 /// performing, used in the error message. If @p AllowExplicit,
10224 /// explicit user-defined conversions are permitted.
10226 AssignmentAction Action,
10227 bool AllowExplicit = false);
10228
10229 /// IsIntegralPromotion - Determines whether the conversion from the
10230 /// expression From (whose potentially-adjusted type is FromType) to
10231 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10232 /// sets PromotedType to the promoted type.
10233 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10234
10235 /// IsFloatingPointPromotion - Determines whether the conversion from
10236 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10237 /// returns true and sets PromotedType to the promoted type.
10238 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10239
10240 /// Determine if a conversion is a complex promotion.
10241 ///
10242 /// A complex promotion is defined as a complex -> complex conversion
10243 /// where the conversion between the underlying real types is a
10244 /// floating-point or integral promotion.
10245 bool IsComplexPromotion(QualType FromType, QualType ToType);
10246
10247 /// IsOverflowBehaviorTypePromotion - Determines whether the conversion from
10248 /// FromType to ToType involves an OverflowBehaviorType FromType being
10249 /// promoted to an OverflowBehaviorType ToType which has a larger bitwidth.
10250 /// If so, returns true and sets FromType to ToType.
10251 bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType);
10252
10253 /// IsOverflowBehaviorTypeConversion - Determines whether the conversion from
10254 /// FromType to ToType necessarily involves both an OverflowBehaviorType and
10255 /// a non-OverflowBehaviorType. If so, returns true and sets FromType to
10256 /// ToType.
10257 bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType);
10258
10259 /// IsPointerConversion - Determines whether the conversion of the
10260 /// expression From, which has the (possibly adjusted) type FromType,
10261 /// can be converted to the type ToType via a pointer conversion (C++
10262 /// 4.10). If so, returns true and places the converted type (that
10263 /// might differ from ToType in its cv-qualifiers at some level) into
10264 /// ConvertedType.
10265 ///
10266 /// This routine also supports conversions to and from block pointers
10267 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10268 /// pointers to interfaces. FIXME: Once we've determined the
10269 /// appropriate overloading rules for Objective-C, we may want to
10270 /// split the Objective-C checks into a different routine; however,
10271 /// GCC seems to consider all of these conversions to be pointer
10272 /// conversions, so for now they live here. IncompatibleObjC will be
10273 /// set if the conversion is an allowed Objective-C conversion that
10274 /// should result in a warning.
10275 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10276 bool InOverloadResolution, QualType &ConvertedType,
10277 bool &IncompatibleObjC);
10278
10279 /// isObjCPointerConversion - Determines whether this is an
10280 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10281 /// with the same arguments and return values.
10282 bool isObjCPointerConversion(QualType FromType, QualType ToType,
10283 QualType &ConvertedType, bool &IncompatibleObjC);
10284 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10285 QualType &ConvertedType);
10286
10287 /// FunctionParamTypesAreEqual - This routine checks two function proto types
10288 /// for equality of their parameter types. Caller has already checked that
10289 /// they have same number of parameters. If the parameters are different,
10290 /// ArgPos will have the parameter index of the first different parameter.
10291 /// If `Reversed` is true, the parameters of `NewType` will be compared in
10292 /// reverse order. That's useful if one of the functions is being used as a
10293 /// C++20 synthesized operator overload with a reversed parameter order.
10296 unsigned *ArgPos = nullptr,
10297 bool Reversed = false);
10298
10300 const FunctionProtoType *NewType,
10301 unsigned *ArgPos = nullptr,
10302 bool Reversed = false);
10303
10304 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10305 const FunctionDecl *NewFunction,
10306 unsigned *ArgPos = nullptr,
10307 bool Reversed = false);
10308
10309 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10310 /// function types. Catches different number of parameter, mismatch in
10311 /// parameter types, and different return types.
10313 QualType ToType);
10314
10315 /// CheckPointerConversion - Check the pointer conversion from the
10316 /// expression From to the type ToType. This routine checks for
10317 /// ambiguous or inaccessible derived-to-base pointer
10318 /// conversions for which IsPointerConversion has already returned
10319 /// true. It returns true and produces a diagnostic if there was an
10320 /// error, or returns false otherwise.
10321 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10322 CXXCastPath &BasePath, bool IgnoreBaseAccess,
10323 bool Diagnose = true);
10324
10325 /// IsMemberPointerConversion - Determines whether the conversion of the
10326 /// expression From, which has the (possibly adjusted) type FromType, can be
10327 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10328 /// If so, returns true and places the converted type (that might differ from
10329 /// ToType in its cv-qualifiers at some level) into ConvertedType.
10330 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10331 bool InOverloadResolution,
10332 QualType &ConvertedType);
10333
10343 /// CheckMemberPointerConversion - Check the member pointer conversion from
10344 /// the expression From to the type ToType. This routine checks for ambiguous
10345 /// or virtual or inaccessible base-to-derived member pointer conversions for
10346 /// which IsMemberPointerConversion has already returned true. It produces a
10347 // diagnostic if there was an error.
10349 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10350 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10351 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10352
10353 /// IsQualificationConversion - Determines whether the conversion from
10354 /// an rvalue of type FromType to ToType is a qualification conversion
10355 /// (C++ 4.4).
10356 ///
10357 /// \param ObjCLifetimeConversion Output parameter that will be set to
10358 /// indicate when the qualification conversion involves a change in the
10359 /// Objective-C object lifetime.
10360 bool IsQualificationConversion(QualType FromType, QualType ToType,
10361 bool CStyle, bool &ObjCLifetimeConversion);
10362
10363 /// Determine whether the conversion from FromType to ToType is a valid
10364 /// conversion of ExtInfo/ExtProtoInfo on the nested function type.
10365 /// More precisely, this method checks whether FromType can be transformed
10366 /// into an exact match for ToType, by transforming its extended function
10367 /// type information in legal manner (e.g. by strictly stripping "noreturn"
10368 /// or "noexcept", or by stripping "noescape" for arguments).
10369 bool IsFunctionConversion(QualType FromType, QualType ToType) const;
10370
10371 /// Same as `IsFunctionConversion`, but if this would return true, it sets
10372 /// `ResultTy` to `ToType`.
10373 bool TryFunctionConversion(QualType FromType, QualType ToType,
10374 QualType &ResultTy) const;
10375
10378 DeclarationName Name,
10379 OverloadCandidateSet &CandidateSet,
10380 FunctionDecl *Fn, MultiExprArg Args,
10381 bool IsMember = false);
10382
10384 FunctionDecl *Fun);
10386 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
10388
10389 /// PerformContextuallyConvertToBool - Perform a contextual conversion
10390 /// of the expression From to bool (C++0x [conv]p3).
10392
10393 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10394 /// conversion of the expression From to an Objective-C pointer type.
10395 /// Returns a valid but null ExprResult if no conversion sequence exists.
10397
10399 CCEKind CCE,
10400 NamedDecl *Dest = nullptr);
10401
10403 llvm::APSInt &Value, CCEKind CCE);
10405 APValue &Value, CCEKind CCE,
10406 NamedDecl *Dest = nullptr);
10407
10408 /// EvaluateConvertedConstantExpression - Evaluate an Expression
10409 /// That is a converted constant expression
10410 /// (which was built with BuildConvertedConstantExpression)
10413 CCEKind CCE, bool RequireInt,
10414 const APValue &PreNarrowingValue);
10415
10416 /// Abstract base class used to perform a contextual implicit
10417 /// conversion from an expression to any type passing a filter.
10419 public:
10422
10426
10427 /// Determine whether the specified type is a valid destination type
10428 /// for this conversion.
10429 virtual bool match(QualType T) = 0;
10430
10431 /// Emits a diagnostic complaining that the expression does not have
10432 /// integral or enumeration type.
10434 QualType T) = 0;
10435
10436 /// Emits a diagnostic when the expression has incomplete class type.
10437 virtual SemaDiagnosticBuilder
10439
10440 /// Emits a diagnostic when the only matching conversion function
10441 /// is explicit.
10443 SourceLocation Loc,
10444 QualType T,
10445 QualType ConvTy) = 0;
10446
10447 /// Emits a note for the explicit conversion function.
10448 virtual SemaDiagnosticBuilder
10450
10451 /// Emits a diagnostic when there are multiple possible conversion
10452 /// functions.
10454 QualType T) = 0;
10455
10456 /// Emits a note for one of the candidate conversions.
10457 virtual SemaDiagnosticBuilder
10459
10460 /// Emits a diagnostic when we picked a conversion function
10461 /// (for cases when we are not allowed to pick a conversion function).
10463 SourceLocation Loc,
10464 QualType T,
10465 QualType ConvTy) = 0;
10466
10468 };
10469
10471 bool AllowScopedEnumerations;
10472
10473 public:
10474 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10475 bool SuppressConversion)
10477 AllowScopedEnumerations(AllowScopedEnumerations) {}
10478
10479 /// Match an integral or (possibly scoped) enumeration type.
10480 bool match(QualType T) override;
10481
10483 QualType T) override {
10484 return diagnoseNotInt(S, Loc, T);
10485 }
10486
10487 /// Emits a diagnostic complaining that the expression does not have
10488 /// integral or enumeration type.
10490 QualType T) = 0;
10491 };
10492
10493 /// Perform a contextual implicit conversion.
10496 ContextualImplicitConverter &Converter);
10497
10498 /// ReferenceCompareResult - Expresses the result of comparing two
10499 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10500 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10502 /// Ref_Incompatible - The two types are incompatible, so direct
10503 /// reference binding is not possible.
10505 /// Ref_Related - The two types are reference-related, which means
10506 /// that their unqualified forms (T1 and T2) are either the same
10507 /// or T1 is a base class of T2.
10509 /// Ref_Compatible - The two types are reference-compatible.
10511 };
10512
10513 // Fake up a scoped enumeration that still contextually converts to bool.
10515 /// The conversions that would be performed on an lvalue of type T2 when
10516 /// binding a reference of type T1 to it, as determined when evaluating
10517 /// whether T1 is reference-compatible with T2.
10528 };
10530
10531 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10532 /// determine whether they are reference-compatible,
10533 /// reference-related, or incompatible, for use in C++ initialization by
10534 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10535 /// type, and the first type (T1) is the pointee type of the reference
10536 /// type being initialized.
10539 ReferenceConversions *Conv = nullptr);
10540
10541 /// AddOverloadCandidate - Adds the given function to the set of
10542 /// candidate functions, using the given function call arguments. If
10543 /// @p SuppressUserConversions, then don't allow user-defined
10544 /// conversions via constructors or conversion operators.
10545 ///
10546 /// \param PartialOverloading true if we are performing "partial" overloading
10547 /// based on an incomplete set of function arguments. This feature is used by
10548 /// code completion.
10551 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10552 bool PartialOverloading = false, bool AllowExplicit = true,
10553 bool AllowExplicitConversion = false,
10554 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10555 ConversionSequenceList EarlyConversions = {},
10557 bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10558
10559 /// Add all of the function declarations in the given function set to
10560 /// the overload candidate set.
10562 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10563 OverloadCandidateSet &CandidateSet,
10564 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10565 bool SuppressUserConversions = false, bool PartialOverloading = false,
10566 bool FirstArgumentIsBase = false);
10567
10568 /// AddMethodCandidate - Adds a named decl (which is some kind of
10569 /// method) as a method candidate to the given overload set.
10570 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10571 Expr::Classification ObjectClassification,
10572 ArrayRef<Expr *> Args,
10573 OverloadCandidateSet &CandidateSet,
10574 bool SuppressUserConversion = false,
10575 OverloadCandidateParamOrder PO = {});
10576
10577 /// AddMethodCandidate - Adds the given C++ member function to the set
10578 /// of candidate functions, using the given function call arguments
10579 /// and the object argument (@c Object). For example, in a call
10580 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10581 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10582 /// allow user-defined conversions via constructors or conversion
10583 /// operators.
10584 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10585 CXXRecordDecl *ActingContext, QualType ObjectType,
10586 Expr::Classification ObjectClassification,
10587 ArrayRef<Expr *> Args,
10588 OverloadCandidateSet &CandidateSet,
10589 bool SuppressUserConversions = false,
10590 bool PartialOverloading = false,
10591 ConversionSequenceList EarlyConversions = {},
10593 bool StrictPackMatch = false);
10594
10595 /// Add a C++ member function template as a candidate to the candidate
10596 /// set, using template argument deduction to produce an appropriate member
10597 /// function template specialization.
10599 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10600 CXXRecordDecl *ActingContext,
10601 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10602 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10603 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10604 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10605
10606 /// Add a C++ function template specialization as a candidate
10607 /// in the candidate set, using template argument deduction to produce
10608 /// an appropriate function template specialization.
10610 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10611 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10612 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10613 bool PartialOverloading = false, bool AllowExplicit = true,
10614 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10616 bool AggregateCandidateDeduction = false);
10617
10619 /// Do not consider any user-defined conversions when constructing the
10620 /// initializing sequence.
10622
10623 /// Before constructing the initializing sequence, we check whether the
10624 /// parameter type and argument type contain any user defined conversions.
10625 /// If so, do not initialize them. This effectively bypasses some undesired
10626 /// instantiation before checking constaints, which might otherwise result
10627 /// in non-SFINAE errors e.g. recursive constraints.
10629
10636 };
10637
10638 /// Check that implicit conversion sequences can be formed for each argument
10639 /// whose corresponding parameter has a non-dependent type, per DR1391's
10640 /// [temp.deduct.call]p10.
10643 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10645 CheckNonDependentConversionsFlag UserConversionFlag,
10646 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10647 Expr::Classification ObjectClassification = {},
10648 OverloadCandidateParamOrder PO = {});
10649
10650 /// AddConversionCandidate - Add a C++ conversion function as a
10651 /// candidate in the candidate set (C++ [over.match.conv],
10652 /// C++ [over.match.copy]). From is the expression we're converting from,
10653 /// and ToType is the type that we're eventually trying to convert to
10654 /// (which may or may not be the same type as the type that the
10655 /// conversion function produces).
10657 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10658 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10659 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10660 bool AllowExplicit, bool AllowResultConversion = true,
10661 bool StrictPackMatch = false);
10662
10663 /// Adds a conversion function template specialization
10664 /// candidate to the overload set, using template argument deduction
10665 /// to deduce the template arguments of the conversion function
10666 /// template from the type that we are converting to (C++
10667 /// [temp.deduct.conv]).
10669 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10670 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10671 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10672 bool AllowExplicit, bool AllowResultConversion = true);
10673
10674 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10675 /// converts the given @c Object to a function pointer via the
10676 /// conversion function @c Conversion, and then attempts to call it
10677 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10678 /// the type of function that we'll eventually be calling.
10679 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10680 DeclAccessPair FoundDecl,
10681 CXXRecordDecl *ActingContext,
10682 const FunctionProtoType *Proto, Expr *Object,
10683 ArrayRef<Expr *> Args,
10684 OverloadCandidateSet &CandidateSet);
10685
10686 /// Add all of the non-member operator function declarations in the given
10687 /// function set to the overload candidate set.
10689 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10690 OverloadCandidateSet &CandidateSet,
10691 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10692
10693 /// Add overload candidates for overloaded operators that are
10694 /// member functions.
10695 ///
10696 /// Add the overloaded operator candidates that are member functions
10697 /// for the operator Op that was used in an operator expression such
10698 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10699 /// CandidateSet will store the added overload candidates. (C++
10700 /// [over.match.oper]).
10702 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10703 OverloadCandidateSet &CandidateSet,
10705
10706 /// AddBuiltinCandidate - Add a candidate for a built-in
10707 /// operator. ResultTy and ParamTys are the result and parameter types
10708 /// of the built-in candidate, respectively. Args and NumArgs are the
10709 /// arguments being passed to the candidate. IsAssignmentOperator
10710 /// should be true when this built-in candidate is an assignment
10711 /// operator. NumContextualBoolArguments is the number of arguments
10712 /// (at the beginning of the argument list) that will be contextually
10713 /// converted to bool.
10714 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10715 OverloadCandidateSet &CandidateSet,
10716 bool IsAssignmentOperator = false,
10717 unsigned NumContextualBoolArguments = 0);
10718
10719 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10720 /// operator overloads to the candidate set (C++ [over.built]), based
10721 /// on the operator @p Op and the arguments given. For example, if the
10722 /// operator is a binary '+', this routine might add "int
10723 /// operator+(int, int)" to cover integer addition.
10725 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10726 OverloadCandidateSet &CandidateSet);
10727
10728 /// Add function candidates found via argument-dependent lookup
10729 /// to the set of overloading candidates.
10730 ///
10731 /// This routine performs argument-dependent name lookup based on the
10732 /// given function name (which may also be an operator name) and adds
10733 /// all of the overload candidates found by ADL to the overload
10734 /// candidate set (C++ [basic.lookup.argdep]).
10736 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10737 TemplateArgumentListInfo *ExplicitTemplateArgs,
10738 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10739
10740 /// Check the enable_if expressions on the given function. Returns the first
10741 /// failing attribute, or NULL if they were all successful.
10742 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10743 ArrayRef<Expr *> Args,
10744 bool MissingImplicitThis = false);
10745
10746 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10747 /// non-ArgDependent DiagnoseIfAttrs.
10748 ///
10749 /// Argument-dependent diagnose_if attributes should be checked each time a
10750 /// function is used as a direct callee of a function call.
10751 ///
10752 /// Returns true if any errors were emitted.
10753 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10754 const Expr *ThisArg,
10755 ArrayRef<const Expr *> Args,
10756 SourceLocation Loc);
10757
10758 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10759 /// ArgDependent DiagnoseIfAttrs.
10760 ///
10761 /// Argument-independent diagnose_if attributes should be checked on every use
10762 /// of a function.
10763 ///
10764 /// Returns true if any errors were emitted.
10765 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10766 SourceLocation Loc);
10767
10768 /// Determine if \p A and \p B are equivalent internal linkage declarations
10769 /// from different modules, and thus an ambiguity error can be downgraded to
10770 /// an extension warning.
10771 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10772 const NamedDecl *B);
10774 SourceLocation Loc, const NamedDecl *D,
10775 ArrayRef<const NamedDecl *> Equiv);
10776
10777 // Emit as a 'note' the specific overload candidate
10779 const NamedDecl *Found, const FunctionDecl *Fn,
10781 QualType DestType = QualType(), bool TakingAddress = false);
10782
10783 // Emit as a series of 'note's all template and non-templates identified by
10784 // the expression Expr
10785 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10786 bool TakingAddress = false);
10787
10788 /// Returns whether the given function's address can be taken or not,
10789 /// optionally emitting a diagnostic if the address can't be taken.
10790 ///
10791 /// Returns false if taking the address of the function is illegal.
10792 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10793 bool Complain = false,
10794 SourceLocation Loc = SourceLocation());
10795
10796 // [PossiblyAFunctionType] --> [Return]
10797 // NonFunctionType --> NonFunctionType
10798 // R (A) --> R(A)
10799 // R (*)(A) --> R (A)
10800 // R (&)(A) --> R (A)
10801 // R (S::*)(A) --> R (A)
10802 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10803
10804 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10805 /// an overloaded function (C++ [over.over]), where @p From is an
10806 /// expression with overloaded function type and @p ToType is the type
10807 /// we're trying to resolve to. For example:
10808 ///
10809 /// @code
10810 /// int f(double);
10811 /// int f(int);
10812 ///
10813 /// int (*pfd)(double) = f; // selects f(double)
10814 /// @endcode
10815 ///
10816 /// This routine returns the resulting FunctionDecl if it could be
10817 /// resolved, and NULL otherwise. When @p Complain is true, this
10818 /// routine will emit diagnostics if there is an error.
10819 FunctionDecl *
10820 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10821 bool Complain, DeclAccessPair &Found,
10822 bool *pHadMultipleCandidates = nullptr);
10823
10824 /// Given an expression that refers to an overloaded function, try to
10825 /// resolve that function to a single function that can have its address
10826 /// taken. This will modify `Pair` iff it returns non-null.
10827 ///
10828 /// This routine can only succeed if from all of the candidates in the
10829 /// overload set for SrcExpr that can have their addresses taken, there is one
10830 /// candidate that is more constrained than the rest.
10831 FunctionDecl *
10832 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10833
10834 /// Given an overloaded function, tries to turn it into a non-overloaded
10835 /// function reference using resolveAddressOfSingleOverloadCandidate. This
10836 /// will perform access checks, diagnose the use of the resultant decl, and,
10837 /// if requested, potentially perform a function-to-pointer decay.
10838 ///
10839 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10840 /// Otherwise, returns true. This may emit diagnostics and return true.
10842 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10843
10844 /// Given an expression that refers to an overloaded function, try to
10845 /// resolve that overloaded function expression down to a single function.
10846 ///
10847 /// This routine can only resolve template-ids that refer to a single function
10848 /// template, where that template-id refers to a single template whose
10849 /// template arguments are either provided by the template-id or have
10850 /// defaults, as described in C++0x [temp.arg.explicit]p3.
10851 ///
10852 /// If no template-ids are found, no diagnostics are emitted and NULL is
10853 /// returned.
10855 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10856 TemplateSpecCandidateSet *FailedTSC = nullptr,
10857 bool ForTypeDeduction = false);
10858
10859 // Resolve and fix an overloaded expression that can be resolved
10860 // because it identifies a single function template specialization.
10861 //
10862 // Last three arguments should only be supplied if Complain = true
10863 //
10864 // Return true if it was logically possible to so resolve the
10865 // expression, regardless of whether or not it succeeded. Always
10866 // returns true if 'complain' is set.
10868 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10869 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10870 QualType DestTypeForComplaining = QualType(),
10871 unsigned DiagIDForComplaining = 0);
10872
10873 /// Add the overload candidates named by callee and/or found by argument
10874 /// dependent lookup to the given overload set.
10875 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10876 ArrayRef<Expr *> Args,
10877 OverloadCandidateSet &CandidateSet,
10878 bool PartialOverloading = false);
10879
10880 /// Add the call candidates from the given set of lookup results to the given
10881 /// overload set. Non-function lookup results are ignored.
10883 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
10884 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
10885
10886 // An enum used to represent the different possible results of building a
10887 // range-based for loop.
10893
10894 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
10895 /// given LookupResult is non-empty, it is assumed to describe a member which
10896 /// will be invoked. Otherwise, the function will be found via argument
10897 /// dependent lookup.
10898 /// CallExpr is set to a valid expression and FRS_Success returned on success,
10899 /// otherwise CallExpr is set to ExprError() and some non-success value
10900 /// is returned.
10902 SourceLocation RangeLoc,
10903 const DeclarationNameInfo &NameInfo,
10904 LookupResult &MemberLookup,
10905 OverloadCandidateSet *CandidateSet,
10906 Expr *Range, ExprResult *CallExpr);
10907
10908 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10909 /// (which eventually refers to the declaration Func) and the call
10910 /// arguments Args/NumArgs, attempt to resolve the function call down
10911 /// to a specific function. If overload resolution succeeds, returns
10912 /// the call expression produced by overload resolution.
10913 /// Otherwise, emits diagnostics and returns ExprError.
10915 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
10916 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
10917 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
10918
10919 /// Constructs and populates an OverloadedCandidateSet from
10920 /// the given function.
10921 /// \returns true when an the ExprResult output parameter has been set.
10923 MultiExprArg Args, SourceLocation RParenLoc,
10924 OverloadCandidateSet *CandidateSet,
10926
10930 const UnresolvedSetImpl &Fns,
10931 bool PerformADL = true);
10932
10933 /// Perform lookup for an overloaded unary operator.
10936 const UnresolvedSetImpl &Fns,
10937 ArrayRef<Expr *> Args, bool RequiresADL = true);
10938
10939 /// Create a unary operation that may resolve to an overloaded
10940 /// operator.
10941 ///
10942 /// \param OpLoc The location of the operator itself (e.g., '*').
10943 ///
10944 /// \param Opc The UnaryOperatorKind that describes this operator.
10945 ///
10946 /// \param Fns The set of non-member functions that will be
10947 /// considered by overload resolution. The caller needs to build this
10948 /// set based on the context using, e.g.,
10949 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10950 /// set should not contain any member functions; those will be added
10951 /// by CreateOverloadedUnaryOp().
10952 ///
10953 /// \param Input The input argument.
10956 const UnresolvedSetImpl &Fns, Expr *input,
10957 bool RequiresADL = true);
10958
10959 /// Perform lookup for an overloaded binary operator.
10962 const UnresolvedSetImpl &Fns,
10963 ArrayRef<Expr *> Args, bool RequiresADL = true);
10964
10965 /// Create a binary operation that may resolve to an overloaded
10966 /// operator.
10967 ///
10968 /// \param OpLoc The location of the operator itself (e.g., '+').
10969 ///
10970 /// \param Opc The BinaryOperatorKind that describes this operator.
10971 ///
10972 /// \param Fns The set of non-member functions that will be
10973 /// considered by overload resolution. The caller needs to build this
10974 /// set based on the context using, e.g.,
10975 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10976 /// set should not contain any member functions; those will be added
10977 /// by CreateOverloadedBinOp().
10978 ///
10979 /// \param LHS Left-hand argument.
10980 /// \param RHS Right-hand argument.
10981 /// \param PerformADL Whether to consider operator candidates found by ADL.
10982 /// \param AllowRewrittenCandidates Whether to consider candidates found by
10983 /// C++20 operator rewrites.
10984 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
10985 /// the function in question. Such a function is never a candidate in
10986 /// our overload resolution. This also enables synthesizing a three-way
10987 /// comparison from < and == as described in C++20 [class.spaceship]p1.
10989 const UnresolvedSetImpl &Fns, Expr *LHS,
10990 Expr *RHS, bool RequiresADL = true,
10991 bool AllowRewrittenCandidates = true,
10992 FunctionDecl *DefaultedFn = nullptr);
10994 const UnresolvedSetImpl &Fns,
10995 Expr *LHS, Expr *RHS,
10996 FunctionDecl *DefaultedFn);
10997
10999 SourceLocation RLoc, Expr *Base,
11000 MultiExprArg Args);
11001
11002 /// BuildCallToMemberFunction - Build a call to a member
11003 /// function. MemExpr is the expression that refers to the member
11004 /// function (and includes the object parameter), Args/NumArgs are the
11005 /// arguments to the function call (not including the object
11006 /// parameter). The caller needs to validate that the member
11007 /// expression refers to a non-static member function or an overloaded
11008 /// member function.
11010 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
11011 SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
11012 bool IsExecConfig = false, bool AllowRecovery = false);
11013
11014 /// BuildCallToObjectOfClassType - Build a call to an object of class
11015 /// type (C++ [over.call.object]), which can end up invoking an
11016 /// overloaded function call operator (@c operator()) or performing a
11017 /// user-defined conversion on the object argument.
11019 SourceLocation LParenLoc,
11020 MultiExprArg Args,
11021 SourceLocation RParenLoc);
11022
11023 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11024 /// (if one exists), where @c Base is an expression of class type and
11025 /// @c Member is the name of the member we're trying to find.
11027 SourceLocation OpLoc,
11028 bool *NoArrowOperatorFound = nullptr);
11029
11032 bool HadMultipleCandidates);
11033
11034 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
11035 /// to a literal operator described by the provided lookup results.
11038 SourceLocation LitEndLoc,
11039 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
11040
11041 /// FixOverloadedFunctionReference - E is an expression that refers to
11042 /// a C++ overloaded function (possibly with some parentheses and
11043 /// perhaps a '&' around it). We have resolved the overloaded function
11044 /// to the function declaration Fn, so patch up the expression E to
11045 /// refer (possibly indirectly) to Fn. Returns the new expr.
11047 FunctionDecl *Fn);
11049 DeclAccessPair FoundDecl,
11050 FunctionDecl *Fn);
11051
11052 /// - Returns a selector which best matches given argument list or
11053 /// nullptr if none could be found
11055 bool IsInstance,
11057
11058 ///@}
11059
11060 //
11061 //
11062 // -------------------------------------------------------------------------
11063 //
11064 //
11065
11066 /// \name Statements
11067 /// Implementations are in SemaStmt.cpp
11068 ///@{
11069
11070public:
11071 /// Stack of active SEH __finally scopes. Can be empty.
11073
11074 /// Stack of '_Defer' statements that are currently being parsed, as well
11075 /// as the locations of their '_Defer' keywords. Can be empty.
11077
11078 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
11080
11082 bool HasLeadingEmptyMacro = false);
11083
11085 SourceLocation EndLoc);
11087
11088 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
11089 /// whose result is unused, warn.
11090 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
11091
11092 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
11096 ArrayRef<Stmt *> Elts, bool isStmtExpr);
11097
11099
11102 SourceLocation DotDotDotLoc, ExprResult RHS,
11103 SourceLocation ColonLoc);
11104
11105 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
11106 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
11107
11109 SourceLocation ColonLoc, Stmt *SubStmt,
11110 Scope *CurScope);
11112 SourceLocation ColonLoc, Stmt *SubStmt);
11113
11115 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
11117 Stmt *SubStmt);
11118
11119 /// Check whether the given statement can have musttail applied to it,
11120 /// issuing a diagnostic and returning false if not. In the success case,
11121 /// the statement is rewritten to remove implicit nodes from the return
11122 /// value.
11123 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11124
11126 SourceLocation LParenLoc, Stmt *InitStmt,
11128 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11130 SourceLocation LParenLoc, Stmt *InitStmt,
11132 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11133
11135
11137 SourceLocation LParenLoc, Stmt *InitStmt,
11139 SourceLocation RParenLoc);
11141 Stmt *Body);
11142
11143 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11144 /// integer not in the range of enum values.
11145 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11146 Expr *SrcExpr);
11147
11150 Stmt *Body);
11152 SourceLocation WhileLoc, SourceLocation CondLParen,
11153 Expr *Cond, SourceLocation CondRParen);
11154
11156 Stmt *First, ConditionResult Second,
11157 FullExprArg Third, SourceLocation RParenLoc,
11158 Stmt *Body);
11159
11160 /// In an Objective C collection iteration statement:
11161 /// for (x in y)
11162 /// x can be an arbitrary l-value expression. Bind it up as a
11163 /// full-expression.
11165
11167 /// Initial building of a for-range statement.
11169 /// Instantiation or recovery rebuild of a for-range statement. Don't
11170 /// attempt any typo-correction.
11172 /// Determining whether a for-range statement could be built. Avoid any
11173 /// unnecessary or irreversible actions.
11175 };
11176
11177 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
11178 ///
11179 /// C++11 [stmt.ranged]:
11180 /// A range-based for statement is equivalent to
11181 ///
11182 /// {
11183 /// auto && __range = range-init;
11184 /// for ( auto __begin = begin-expr,
11185 /// __end = end-expr;
11186 /// __begin != __end;
11187 /// ++__begin ) {
11188 /// for-range-declaration = *__begin;
11189 /// statement
11190 /// }
11191 /// }
11192 ///
11193 /// The body of the loop is not available yet, since it cannot be analysed
11194 /// until we have determined the type of the for-range-declaration.
11196 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11197 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11198 SourceLocation RParenLoc, BuildForRangeKind Kind,
11199 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11200
11201 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11202 StmtResult BuildCXXForRangeStmt(
11203 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11204 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11205 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11206 BuildForRangeKind Kind,
11207 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11208
11209 /// Set the type of a for-range declaration whose for-range or expansion
11210 /// initialiser is dependent.
11211 void ActOnDependentForRangeInitializer(VarDecl *LoopVar,
11212 BuildForRangeKind BFRK);
11213
11214 /// Holds the 'begin' and 'end' variables of a range-based for loop or
11215 /// expansion statement; begin-expr and end-expr are also provided; the
11216 /// latter are used in some diagnostics.
11218 VarDecl *BeginVar = nullptr;
11219 VarDecl *EndVar = nullptr;
11220 Expr *BeginExpr = nullptr;
11221 Expr *EndExpr = nullptr;
11222 bool isValid() const { return BeginVar != nullptr && EndVar != nullptr; }
11223 };
11224
11225 /// Determine begin-expr and end-expr and build variable declarations for
11226 /// them as per [stmt.ranged].
11227 ForRangeBeginEndInfo BuildCXXForRangeBeginEndVars(
11228 Scope *S, VarDecl *RangeVar, SourceLocation ColonLoc,
11229 SourceLocation CoawaitLoc,
11230 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps,
11231 BuildForRangeKind Kind, bool IsConstexpr,
11232 StmtResult *RebuildResult = nullptr,
11233 llvm::function_ref<StmtResult()> RebuildWithDereference = {},
11234 IdentifierInfo *BeginName = nullptr, IdentifierInfo *EndName = nullptr);
11235
11236 /// Helper used by the expansion statements and for-range code to build
11237 /// a variable declaration for e.g. 'begin' and 'end'.
11238 VarDecl *BuildForRangeVarDecl(SourceLocation Loc, QualType Type,
11239 IdentifierInfo *Name, bool IsConstexpr);
11240
11241 /// Build the range variable of a range-based for loop or iterating
11242 /// expansion statement and return its DeclStmt.
11243 StmtResult BuildCXXForRangeRangeVar(Scope *S, Expr *Range, QualType Type,
11244 bool IsConstexpr = false);
11245
11246 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11247 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11248 /// body cannot be performed until after the type of the range variable is
11249 /// determined.
11250 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11251
11252 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11253 LabelDecl *TheDecl);
11254 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11255 SourceLocation StarLoc, Expr *DestExp);
11256 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
11257 LabelDecl *Label, SourceLocation LabelLoc);
11258 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
11259 LabelDecl *Label, SourceLocation LabelLoc);
11260
11261 void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope);
11262 void ActOnDeferStmtError(Scope *CurScope);
11263 StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope);
11264
11267
11270
11271 bool isMoveEligible() const { return S != None; };
11273 };
11275
11276 /// Determine whether the given expression might be move-eligible or
11277 /// copy-elidable in either a (co_)return statement or throw expression,
11278 /// without considering function return type, if applicable.
11279 ///
11280 /// \param E The expression being returned from the function or block,
11281 /// being thrown, or being co_returned from a coroutine. This expression
11282 /// might be modified by the implementation.
11283 ///
11284 /// \param Mode Overrides detection of current language mode
11285 /// and uses the rules for C++23.
11286 ///
11287 /// \returns An aggregate which contains the Candidate and isMoveEligible
11288 /// and isCopyElidable methods. If Candidate is non-null, it means
11289 /// isMoveEligible() would be true under the most permissive language
11290 /// standard.
11291 NamedReturnInfo getNamedReturnInfo(
11293
11294 /// Determine whether the given NRVO candidate variable is move-eligible or
11295 /// copy-elidable, without considering function return type.
11296 ///
11297 /// \param VD The NRVO candidate variable.
11298 ///
11299 /// \returns An aggregate which contains the Candidate and isMoveEligible
11300 /// and isCopyElidable methods. If Candidate is non-null, it means
11301 /// isMoveEligible() would be true under the most permissive language
11302 /// standard.
11303 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11304
11305 /// Updates given NamedReturnInfo's move-eligible and
11306 /// copy-elidable statuses, considering the function
11307 /// return type criteria as applicable to return statements.
11308 ///
11309 /// \param Info The NamedReturnInfo object to update.
11310 ///
11311 /// \param ReturnType This is the return type of the function.
11312 /// \returns The copy elision candidate, in case the initial return expression
11313 /// was copy elidable, or nullptr otherwise.
11314 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11315 QualType ReturnType);
11316
11317 /// Perform the initialization of a potentially-movable value, which
11318 /// is the result of return value.
11319 ///
11320 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11321 /// treat returned lvalues as rvalues in certain cases (to prefer move
11322 /// construction), then falls back to treating them as lvalues if that failed.
11325 const NamedReturnInfo &NRInfo, Expr *Value,
11326 bool SupressSimplerImplicitMoves = false);
11327
11329
11330 /// Deduce the return type for a function from a returned expression, per
11331 /// C++1y [dcl.spec.auto]p6.
11333 SourceLocation ReturnLoc, Expr *RetExpr,
11334 const AutoType *AT);
11335
11336 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11337 Scope *CurScope);
11338 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11339 bool AllowRecovery = false);
11340
11341 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11342 /// for capturing scopes.
11344 NamedReturnInfo &NRInfo,
11345 bool SupressSimplerImplicitMoves);
11346
11347 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11348 /// and creates a proper catch handler from them.
11350 Stmt *HandlerBlock);
11351
11352 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11353 /// handlers and creates a try statement from them.
11355 ArrayRef<Stmt *> Handlers);
11356
11357 void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11358
11359 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11360 SourceLocation TryLoc, Stmt *TryBlock,
11361 Stmt *Handler);
11363 Stmt *Block);
11368
11370 bool IsIfExists,
11371 NestedNameSpecifierLoc QualifierLoc,
11372 DeclarationNameInfo NameInfo,
11373 Stmt *Nested);
11375 bool IsIfExists, CXXScopeSpec &SS,
11376 UnqualifiedId &Name, Stmt *Nested);
11377
11378 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11379 CapturedRegionKind Kind, unsigned NumParams);
11380 typedef std::pair<StringRef, QualType> CapturedParamNameType;
11381 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11382 CapturedRegionKind Kind,
11384 unsigned OpenMPCaptureLevel = 0);
11388 SourceLocation Loc,
11389 unsigned NumParams);
11390
11392 VarDecl *RangeVar, ArrayRef<MaterializeTemporaryExpr *> Temporaries);
11393
11394private:
11395 /// Check whether the given statement can have musttail applied to it,
11396 /// issuing a diagnostic and returning false if not.
11397 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11398
11399 ///@}
11400
11401 //
11402 //
11403 // -------------------------------------------------------------------------
11404 //
11405 //
11406
11407 /// \name `inline asm` Statement
11408 /// Implementations are in SemaStmtAsm.cpp
11409 ///@{
11410
11411public:
11412 ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel);
11413 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11414 bool IsVolatile, unsigned NumOutputs,
11415 unsigned NumInputs, IdentifierInfo **Names,
11416 MultiExprArg Constraints, MultiExprArg Exprs,
11417 Expr *AsmString, MultiExprArg Clobbers,
11418 unsigned NumLabels, SourceLocation RParenLoc);
11419
11421 llvm::InlineAsmIdentifierInfo &Info);
11423 SourceLocation TemplateKWLoc,
11424 UnqualifiedId &Id,
11425 bool IsUnevaluatedContext);
11426 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11427 SourceLocation AsmLoc);
11429 SourceLocation AsmLoc);
11431 ArrayRef<Token> AsmToks, StringRef AsmString,
11432 unsigned NumOutputs, unsigned NumInputs,
11433 ArrayRef<StringRef> Constraints,
11434 ArrayRef<StringRef> Clobbers,
11435 ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11436 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11437 SourceLocation Location, bool AlwaysCreate);
11438
11439 ///@}
11440
11441 //
11442 //
11443 // -------------------------------------------------------------------------
11444 //
11445 //
11446
11447 /// \name Statement Attribute Handling
11448 /// Implementations are in SemaStmtAttr.cpp
11449 ///@{
11450
11451public:
11452 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11453 const AttributeCommonInfo &A);
11454 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11455 const AttributeCommonInfo &A);
11456
11457 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11459
11460 /// Process the attributes before creating an attributed statement. Returns
11461 /// the semantic attributes that have been processed.
11462 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11464
11466 SourceRange Range);
11468 const IdentifierInfo *AttrName,
11469 SourceRange Range);
11470
11471 ///@}
11472
11473 //
11474 //
11475 // -------------------------------------------------------------------------
11476 //
11477 //
11478
11479 /// \name C++ Templates
11480 /// Implementations are in SemaTemplate.cpp
11481 ///@{
11482
11483public:
11484 // Saves the current floating-point pragma stack and clear it in this Sema.
11486 public:
11488 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11489 S.FpPragmaStack.Stack.clear();
11490 }
11491 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11494
11495 private:
11496 Sema &S;
11498 };
11499
11501 CurFPFeatures = FPO;
11502 FpPragmaStack.CurrentValue = FPO.getChangesFrom(FPOptions(LangOpts));
11503 }
11504
11510
11515
11516 typedef llvm::MapVector<const FunctionDecl *,
11517 std::unique_ptr<LateParsedTemplate>>
11520
11521 /// Determine the number of levels of enclosing template parameters. This is
11522 /// only usable while parsing. Note that this does not include dependent
11523 /// contexts in which no template parameters have yet been declared, such as
11524 /// in a terse function template or generic lambda before the first 'auto' is
11525 /// encountered.
11526 unsigned getTemplateDepth(Scope *S) const;
11527
11529 bool AllowFunctionTemplates = true,
11530 bool AllowDependent = true);
11532 bool AllowFunctionTemplates = true,
11533 bool AllowDependent = true,
11534 bool AllowNonTemplateFunctions = false);
11535 /// Try to interpret the lookup result D as a template-name.
11536 ///
11537 /// \param D A declaration found by name lookup.
11538 /// \param AllowFunctionTemplates Whether function templates should be
11539 /// considered valid results.
11540 /// \param AllowDependent Whether unresolved using declarations (that might
11541 /// name templates) should be considered valid results.
11543 bool AllowFunctionTemplates = true,
11544 bool AllowDependent = true);
11545
11547 /// Whether and why a template name is required in this lookup.
11549 public:
11550 /// Template name is required if TemplateKWLoc is valid.
11552 : TemplateKW(TemplateKWLoc) {}
11553 /// Template name is unconditionally required.
11555
11557 return TemplateKW.value_or(SourceLocation());
11558 }
11559 bool hasTemplateKeyword() const {
11560 return getTemplateKeywordLoc().isValid();
11561 }
11562 bool isRequired() const { return TemplateKW != SourceLocation(); }
11563 explicit operator bool() const { return isRequired(); }
11564
11565 private:
11566 std::optional<SourceLocation> TemplateKW;
11567 };
11568
11570 /// This is not assumed to be a template name.
11572 /// This is assumed to be a template name because lookup found nothing.
11574 /// This is assumed to be a template name because lookup found one or more
11575 /// functions (but no function templates).
11577 };
11578
11579 bool
11581 QualType ObjectType, bool EnteringContext,
11582 RequiredTemplateKind RequiredTemplate = SourceLocation(),
11583 AssumedTemplateKind *ATK = nullptr,
11584 bool AllowTypoCorrection = true);
11585
11587 bool hasTemplateKeyword,
11588 const UnqualifiedId &Name,
11589 ParsedType ObjectType, bool EnteringContext,
11591 bool &MemberOfUnknownSpecialization,
11592 bool AllowTypoCorrection = true);
11593
11594 /// Try to resolve an undeclared template name as a type template.
11595 ///
11596 /// Sets II to the identifier corresponding to the template name, and updates
11597 /// Name to a corresponding (typo-corrected) type template name and TNK to
11598 /// the corresponding kind, if possible.
11600 TemplateNameKind &TNK,
11601 SourceLocation NameLoc,
11602 IdentifierInfo *&II);
11603
11604 /// Determine whether a particular identifier might be the name in a C++1z
11605 /// deduction-guide declaration.
11606 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11607 SourceLocation NameLoc, CXXScopeSpec &SS,
11608 ParsedTemplateTy *Template = nullptr);
11609
11611 SourceLocation IILoc, Scope *S,
11612 const CXXScopeSpec *SS,
11613 TemplateTy &SuggestedTemplate,
11614 TemplateNameKind &SuggestedKind);
11615
11616 /// Determine whether we would be unable to instantiate this template (because
11617 /// it either has no definition, or is in the process of being instantiated).
11619 SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11620 bool InstantiatedFromMember, const NamedDecl *Pattern,
11621 const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11622 bool Complain = true, bool *Unreachable = nullptr);
11623
11624 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11625 /// that the template parameter 'PrevDecl' is being shadowed by a new
11626 /// declaration at location Loc. Returns true to indicate that this is
11627 /// an error, and false otherwise.
11628 ///
11629 /// \param Loc The location of the declaration that shadows a template
11630 /// parameter.
11631 ///
11632 /// \param PrevDecl The template parameter that the declaration shadows.
11633 ///
11634 /// \param SupportedForCompatibility Whether to issue the diagnostic as
11635 /// a warning for compatibility with older versions of clang.
11636 /// Ignored when MSVC compatibility is enabled.
11638 bool SupportedForCompatibility = false);
11639
11640 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11641 /// the parameter D to reference the templated declaration and return a
11642 /// pointer to the template declaration. Otherwise, do nothing to D and return
11643 /// null.
11645
11646 /// ActOnTypeParameter - Called when a C++ template type parameter
11647 /// (e.g., "typename T") has been parsed. Typename specifies whether
11648 /// the keyword "typename" was used to declare the type parameter
11649 /// (otherwise, "class" was used), and KeyLoc is the location of the
11650 /// "class" or "typename" keyword. ParamName is the name of the
11651 /// parameter (NULL indicates an unnamed template parameter) and
11652 /// ParamNameLoc is the location of the parameter name (if any).
11653 /// If the type parameter has a default argument, it will be added
11654 /// later via ActOnTypeParameterDefault.
11656 SourceLocation EllipsisLoc,
11657 SourceLocation KeyLoc,
11658 IdentifierInfo *ParamName,
11659 SourceLocation ParamNameLoc, unsigned Depth,
11660 unsigned Position, SourceLocation EqualLoc,
11661 ParsedType DefaultArg, bool HasTypeConstraint);
11662
11664
11665 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11667 TemplateTypeParmDecl *ConstrainedParameter,
11668 SourceLocation EllipsisLoc);
11669 bool BuildTypeConstraint(const CXXScopeSpec &SS,
11671 TemplateTypeParmDecl *ConstrainedParameter,
11672 SourceLocation EllipsisLoc,
11673 bool AllowUnexpandedPack);
11674
11675 /// Attach a type-constraint to a template parameter.
11676 /// \returns true if an error occurred. This can happen if the
11677 /// immediately-declared constraint could not be formed (e.g. incorrect number
11678 /// of arguments for the named concept).
11680 DeclarationNameInfo NameInfo,
11681 TemplateDecl *NamedConcept, NamedDecl *FoundDecl,
11682 const TemplateArgumentListInfo *TemplateArgs,
11683 TemplateTypeParmDecl *ConstrainedParameter,
11684 SourceLocation EllipsisLoc);
11685
11687 NonTypeTemplateParmDecl *NewConstrainedParm,
11688 NonTypeTemplateParmDecl *OrigConstrainedParm,
11689 SourceLocation EllipsisLoc);
11690
11691 /// Require the given type to be a structural type, and diagnose if it is not.
11692 ///
11693 /// \return \c true if an error was produced.
11695
11696 /// Check that the type of a non-type template parameter is
11697 /// well-formed.
11698 ///
11699 /// \returns the (possibly-promoted) parameter type if valid;
11700 /// otherwise, produces a diagnostic and returns a NULL type.
11702 SourceLocation Loc);
11704
11706 unsigned Depth, unsigned Position,
11707 SourceLocation EqualLoc,
11708 Expr *DefaultArg);
11709
11710 /// ActOnTemplateTemplateParameter - Called when a C++ template template
11711 /// parameter (e.g. T in template <template <typename> class T> class array)
11712 /// has been parsed. S is the current scope.
11714 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind,
11715 bool TypenameKeyword, TemplateParameterList *Params,
11716 SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11717 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11718 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11719
11720 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11721 /// constrained by RequiresClause, that contains the template parameters in
11722 /// Params.
11724 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11725 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11726 SourceLocation RAngleLoc, Expr *RequiresClause);
11727
11728 /// The context in which we are checking a template parameter list.
11730 // For this context, Class, Variable, TypeAlias, and non-pack Template
11731 // Template Parameters are treated uniformly.
11733
11740 };
11741
11742 /// Checks the validity of a template parameter list, possibly
11743 /// considering the template parameter list from a previous
11744 /// declaration.
11745 ///
11746 /// If an "old" template parameter list is provided, it must be
11747 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11748 /// template parameter list.
11749 ///
11750 /// \param NewParams Template parameter list for a new template
11751 /// declaration. This template parameter list will be updated with any
11752 /// default arguments that are carried through from the previous
11753 /// template parameter list.
11754 ///
11755 /// \param OldParams If provided, template parameter list from a
11756 /// previous declaration of the same template. Default template
11757 /// arguments will be merged from the old template parameter list to
11758 /// the new template parameter list.
11759 ///
11760 /// \param TPC Describes the context in which we are checking the given
11761 /// template parameter list.
11762 ///
11763 /// \param SkipBody If we might have already made a prior merged definition
11764 /// of this template visible, the corresponding body-skipping information.
11765 /// Default argument redefinition is not an error when skipping such a body,
11766 /// because (under the ODR) we can assume the default arguments are the same
11767 /// as the prior merged definition.
11768 ///
11769 /// \returns true if an error occurred, false otherwise.
11771 TemplateParameterList *OldParams,
11773 SkipBodyInfo *SkipBody = nullptr);
11774
11775 /// Match the given template parameter lists to the given scope
11776 /// specifier, returning the template parameter list that applies to the
11777 /// name.
11778 ///
11779 /// \param DeclStartLoc the start of the declaration that has a scope
11780 /// specifier or a template parameter list.
11781 ///
11782 /// \param DeclLoc The location of the declaration itself.
11783 ///
11784 /// \param SS the scope specifier that will be matched to the given template
11785 /// parameter lists. This scope specifier precedes a qualified name that is
11786 /// being declared.
11787 ///
11788 /// \param TemplateId The template-id following the scope specifier, if there
11789 /// is one. Used to check for a missing 'template<>'.
11790 ///
11791 /// \param ParamLists the template parameter lists, from the outermost to the
11792 /// innermost template parameter lists.
11793 ///
11794 /// \param IsFriend Whether to apply the slightly different rules for
11795 /// matching template parameters to scope specifiers in friend
11796 /// declarations.
11797 ///
11798 /// \param IsMemberSpecialization will be set true if the scope specifier
11799 /// denotes a fully-specialized type, and therefore this is a declaration of
11800 /// a member specialization.
11801 ///
11802 /// \returns the template parameter list, if any, that corresponds to the
11803 /// name that is preceded by the scope specifier @p SS. This template
11804 /// parameter list may have template parameters (if we're declaring a
11805 /// template) or may have no template parameters (if we're declaring a
11806 /// template specialization), or may be NULL (if what we're declaring isn't
11807 /// itself a template).
11809 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11810 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11811 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11812 bool &IsMemberSpecialization, bool &Invalid,
11813 bool SuppressDiagnostic = false);
11814
11815 /// Returns the template parameter list with all default template argument
11816 /// information.
11818
11820 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11821 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11822 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11823 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11824 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11825 TemplateParameterList **OuterTemplateParamLists,
11826 bool IsMemberSpecialization, SkipBodyInfo *SkipBody = nullptr);
11827
11828 /// Translates template arguments as provided by the parser
11829 /// into template arguments used by semantic analysis.
11832
11833 /// Convert a parsed type into a parsed template argument. This is mostly
11834 /// trivial, except that we may have parsed a C++17 deduced class template
11835 /// specialization type, in which case we should form a template template
11836 /// argument instead of a type template argument.
11838
11840
11843 SourceLocation TemplateLoc,
11844 TemplateArgumentListInfo &TemplateArgs,
11845 Scope *Scope, bool ForNestedNameSpecifier);
11846
11848 ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
11849 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
11850 SourceLocation TemplateKWLoc, TemplateTy Template,
11851 const IdentifierInfo *TemplateII,
11852 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11853 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11854 bool IsCtorOrDtorName = false, bool IsClassName = false,
11855 ImplicitTypenameContext AllowImplicitTypename =
11857
11858 /// Parsed an elaborated-type-specifier that refers to a template-id,
11859 /// such as \c class T::template apply<U>.
11861 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11862 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11863 SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11864 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11865
11868 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11870
11871 /// Get the specialization of the given variable template corresponding to
11872 /// the specified argument list, or a null-but-valid result if the arguments
11873 /// are dependent.
11875 SourceLocation TemplateLoc,
11876 SourceLocation TemplateNameLoc,
11877 const TemplateArgumentListInfo &TemplateArgs,
11878 bool SetWrittenArgs);
11879
11880 /// Form a reference to the specialization of the given variable template
11881 /// corresponding to the specified argument list, or a null-but-valid result
11882 /// if the arguments are dependent.
11884 const DeclarationNameInfo &NameInfo,
11886 SourceLocation TemplateLoc,
11887 const TemplateArgumentListInfo *TemplateArgs);
11888
11890 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
11892 const TemplateArgumentListInfo *TemplateArgs);
11893
11895 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11896 const DeclarationNameInfo &ConceptNameInfo,
11897 NamedDecl *FoundDecl, TemplateDecl *NamedConcept,
11898 const TemplateArgumentListInfo *TemplateArgs,
11899 bool DoCheckConstraintSatisfaction = true);
11900
11903 bool TemplateKeyword, TemplateDecl *TD,
11904 SourceLocation Loc);
11905
11907 SourceLocation TemplateKWLoc, LookupResult &R,
11908 bool RequiresADL,
11909 const TemplateArgumentListInfo *TemplateArgs);
11910
11911 // We actually only call this from template instantiation.
11914 const DeclarationNameInfo &NameInfo,
11915 const TemplateArgumentListInfo *TemplateArgs,
11916 bool IsAddressOfOperand);
11917
11919 return Pack.pack_size() - 1 - *ArgPackSubstIndex;
11920 }
11921
11924 Arg = Arg.pack_elements()[*ArgPackSubstIndex];
11925 if (Arg.isPackExpansion())
11926 Arg = Arg.getPackExpansionPattern();
11927 return Arg;
11928 }
11929
11931 BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
11932 QualType ParamType, SourceLocation loc,
11933 TemplateArgument Replacement,
11934 UnsignedOrNone PackIndex, bool Final);
11935
11936 /// Form a template name from a name that is syntactically required to name a
11937 /// template, either due to use of the 'template' keyword or because a name in
11938 /// this syntactic context is assumed to name a template (C++
11939 /// [temp.names]p2-4).
11940 ///
11941 /// This action forms a template name given the name of the template and its
11942 /// optional scope specifier. This is used when the 'template' keyword is used
11943 /// or when the parsing context unambiguously treats a following '<' as
11944 /// introducing a template argument list. Note that this may produce a
11945 /// non-dependent template name if we can perform the lookup now and identify
11946 /// the named template.
11947 ///
11948 /// For example, given "x.MetaFun::template apply", the scope specifier
11949 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
11950 /// of the "template" keyword, and "apply" is the \p Name.
11952 SourceLocation TemplateKWLoc,
11953 const UnqualifiedId &Name,
11954 ParsedType ObjectType,
11955 bool EnteringContext, TemplateTy &Template,
11956 bool AllowInjectedClassName = false);
11957
11959 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11960 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
11962 MultiTemplateParamsArg TemplateParameterLists,
11963 SkipBodyInfo *SkipBody = nullptr);
11964
11965 /// Check the non-type template arguments of a class template
11966 /// partial specialization according to C++ [temp.class.spec]p9.
11967 ///
11968 /// \param TemplateNameLoc the location of the template name.
11969 /// \param PrimaryTemplate the template parameters of the primary class
11970 /// template.
11971 /// \param NumExplicit the number of explicitly-specified template arguments.
11972 /// \param TemplateArgs the template arguments of the class template
11973 /// partial specialization.
11974 ///
11975 /// \returns \c true if there was an error, \c false otherwise.
11977 TemplateDecl *PrimaryTemplate,
11978 unsigned NumExplicitArgs,
11984
11986 MultiTemplateParamsArg TemplateParameterLists,
11987 Declarator &D);
11988
11989 /// Diagnose cases where we have an explicit template specialization
11990 /// before/after an explicit template instantiation, producing diagnostics
11991 /// for those cases where they are required and determining whether the
11992 /// new specialization/instantiation will have any effect.
11993 ///
11994 /// \param NewLoc the location of the new explicit specialization or
11995 /// instantiation.
11996 ///
11997 /// \param NewTSK the kind of the new explicit specialization or
11998 /// instantiation.
11999 ///
12000 /// \param PrevDecl the previous declaration of the entity.
12001 ///
12002 /// \param PrevTSK the kind of the old explicit specialization or
12003 /// instantiatin.
12004 ///
12005 /// \param PrevPointOfInstantiation if valid, indicates where the previous
12006 /// declaration was instantiated (either implicitly or explicitly).
12007 ///
12008 /// \param HasNoEffect will be set to true to indicate that the new
12009 /// specialization or instantiation has no effect and should be ignored.
12010 ///
12011 /// \returns true if there was an error that should prevent the introduction
12012 /// of the new declaration into the AST, false otherwise.
12014 SourceLocation NewLoc,
12015 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
12016 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
12017 SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
12018
12019 /// Perform semantic analysis for the given dependent function
12020 /// template specialization.
12021 ///
12022 /// The only possible way to get a dependent function template specialization
12023 /// is with a friend declaration, like so:
12024 ///
12025 /// \code
12026 /// template <class T> void foo(T);
12027 /// template <class T> class A {
12028 /// friend void foo<>(T);
12029 /// };
12030 /// \endcode
12031 ///
12032 /// There really isn't any useful analysis we can do here, so we
12033 /// just store the information.
12035 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
12037
12038 /// Perform semantic analysis for the given function template
12039 /// specialization.
12040 ///
12041 /// This routine performs all of the semantic analysis required for an
12042 /// explicit function template specialization. On successful completion,
12043 /// the function declaration \p FD will become a function template
12044 /// specialization.
12045 ///
12046 /// \param FD the function declaration, which will be updated to become a
12047 /// function template specialization.
12048 ///
12049 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
12050 /// if any. Note that this may be valid info even when 0 arguments are
12051 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
12052 /// as it anyway contains info on the angle brackets locations.
12053 ///
12054 /// \param Previous the set of declarations that may be specialized by
12055 /// this function specialization.
12056 ///
12057 /// \param QualifiedFriend whether this is a lookup for a qualified friend
12058 /// declaration with no explicit template argument list that might be
12059 /// befriending a function template specialization.
12061 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
12062 LookupResult &Previous, bool QualifiedFriend = false);
12063
12064 /// Perform semantic analysis for the given non-template member
12065 /// specialization.
12066 ///
12067 /// This routine performs all of the semantic analysis required for an
12068 /// explicit member function specialization. On successful completion,
12069 /// the function declaration \p FD will become a member function
12070 /// specialization.
12071 ///
12072 /// \param Member the member declaration, which will be updated to become a
12073 /// specialization.
12074 ///
12075 /// \param Previous the set of declarations, one of which may be specialized
12076 /// by this function specialization; the set will be modified to contain the
12077 /// redeclared member.
12080
12081 // Explicit instantiation of a class template specialization
12083 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
12084 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
12085 TemplateTy Template, SourceLocation TemplateNameLoc,
12086 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
12087 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
12088
12089 // Explicit instantiation of a member class of a class template.
12091 SourceLocation TemplateLoc,
12092 unsigned TagSpec, SourceLocation KWLoc,
12093 CXXScopeSpec &SS, IdentifierInfo *Name,
12094 SourceLocation NameLoc,
12095 const ParsedAttributesView &Attr);
12096
12098 SourceLocation TemplateLoc,
12099 Declarator &D);
12100
12101 /// If the given template parameter has a default template
12102 /// argument, substitute into that default template argument and
12103 /// return the corresponding template argument.
12105 TemplateDecl *Template, SourceLocation TemplateKWLoc,
12106 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
12107 ArrayRef<TemplateArgument> SugaredConverted,
12108 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
12109
12110 /// Returns the top most location responsible for the definition of \p N.
12111 /// If \p N is a a template specialization, this is the location
12112 /// of the top of the instantiation stack.
12113 /// Otherwise, the location of \p N is returned.
12115
12116 /// Specifies the context in which a particular template
12117 /// argument is being checked.
12119 /// The template argument was specified in the code or was
12120 /// instantiated with some deduced template arguments.
12122
12123 /// The template argument was deduced via template argument
12124 /// deduction.
12126
12127 /// The template argument was deduced from an array bound
12128 /// via template argument deduction.
12130 };
12131
12139
12140 /// The checked, converted argument will be added to the
12141 /// end of these vectors.
12143
12144 /// The check is being performed in the context of partial ordering.
12146
12147 /// If true, assume these template arguments are
12148 /// the injected template arguments for a template template parameter.
12149 /// This will relax the requirement that all its possible uses are valid:
12150 /// TTP checking is loose, and assumes that invalid uses will be diagnosed
12151 /// during instantiation.
12153
12154 /// Is set to true when, in the context of TTP matching, a pack parameter
12155 /// matches non-pack arguments.
12156 bool StrictPackMatch = false;
12157 };
12158
12159 /// Check that the given template argument corresponds to the given
12160 /// template parameter.
12161 ///
12162 /// \param Param The template parameter against which the argument will be
12163 /// checked.
12164 ///
12165 /// \param Arg The template argument, which may be updated due to conversions.
12166 ///
12167 /// \param Template The template in which the template argument resides.
12168 ///
12169 /// \param TemplateLoc The location of the template name for the template
12170 /// whose argument list we're matching.
12171 ///
12172 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
12173 /// the template argument list.
12174 ///
12175 /// \param ArgumentPackIndex The index into the argument pack where this
12176 /// argument will be placed. Only valid if the parameter is a parameter pack.
12177 ///
12178 /// \param CTAK Describes how we arrived at this particular template argument:
12179 /// explicitly written, deduced, etc.
12180 ///
12181 /// \returns true on error, false otherwise.
12183 NamedDecl *Template, SourceLocation TemplateLoc,
12184 SourceLocation RAngleLoc,
12185 unsigned ArgumentPackIndex,
12188
12189 /// Check that the given template arguments can be provided to
12190 /// the given template, converting the arguments along the way.
12191 ///
12192 /// \param Template The template to which the template arguments are being
12193 /// provided.
12194 ///
12195 /// \param TemplateLoc The location of the template name in the source.
12196 ///
12197 /// \param TemplateArgs The list of template arguments. If the template is
12198 /// a template template parameter, this function may extend the set of
12199 /// template arguments to also include substituted, defaulted template
12200 /// arguments.
12201 ///
12202 /// \param PartialTemplateArgs True if the list of template arguments is
12203 /// intentionally partial, e.g., because we're checking just the initial
12204 /// set of template arguments.
12205 ///
12206 /// \param Converted Will receive the converted, canonicalized template
12207 /// arguments.
12208 ///
12209 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
12210 /// contain the converted forms of the template arguments as written.
12211 /// Otherwise, \p TemplateArgs will not be modified.
12212 ///
12213 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
12214 /// receive true if the cause for the error is the associated constraints of
12215 /// the template not being satisfied by the template arguments.
12216 ///
12217 /// \param DefaultArgs any default arguments from template specialization
12218 /// deduction.
12219 ///
12220 /// \returns true if an error occurred, false otherwise.
12222 SourceLocation TemplateLoc,
12223 TemplateArgumentListInfo &TemplateArgs,
12224 const DefaultArguments &DefaultArgs,
12225 bool PartialTemplateArgs,
12227 bool UpdateArgsWithConversions = true,
12228 bool *ConstraintsNotSatisfied = nullptr);
12229
12232 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
12233 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
12234 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions = true,
12235 bool *ConstraintsNotSatisfied = nullptr);
12236
12239 SmallVectorImpl<TemplateArgument> &SugaredConverted,
12240 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
12241
12242 /// Check a template argument against its corresponding
12243 /// template type parameter.
12244 ///
12245 /// This routine implements the semantics of C++ [temp.arg.type]. It
12246 /// returns true if an error occurred, and false otherwise.
12248
12249 /// Check a template argument against its corresponding
12250 /// non-type template parameter.
12251 ///
12252 /// This routine implements the semantics of C++ [temp.arg.nontype].
12253 /// If an error occurred, it returns ExprError(); otherwise, it
12254 /// returns the converted template argument. \p ParamType is the
12255 /// type of the non-type template parameter after it has been instantiated.
12257 QualType InstantiatedParamType, Expr *Arg,
12258 TemplateArgument &SugaredConverted,
12259 TemplateArgument &CanonicalConverted,
12260 bool StrictCheck,
12262
12263 /// Check a template argument against its corresponding
12264 /// template template parameter.
12265 ///
12266 /// This routine implements the semantics of C++ [temp.arg.template].
12267 /// It returns true if an error occurred, and false otherwise.
12269 TemplateParameterList *Params,
12271 bool PartialOrdering,
12272 bool *StrictPackMatch);
12273
12276 const TemplateArgumentLoc &Arg);
12277
12279 std::optional<SourceRange> ParamRange = {});
12281
12282 /// Given a non-type template argument that refers to a
12283 /// declaration and the type of its corresponding non-type template
12284 /// parameter, produce an expression that properly refers to that
12285 /// declaration.
12286 /// FIXME: This is used in some contexts where the resulting expression
12287 /// doesn't need to live too long. It would be useful if this function
12288 /// could return a temporary expression.
12290 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc);
12293 SourceLocation Loc);
12294
12295 /// Enumeration describing how template parameter lists are compared
12296 /// for equality.
12298 /// We are matching the template parameter lists of two templates
12299 /// that might be redeclarations.
12300 ///
12301 /// \code
12302 /// template<typename T> struct X;
12303 /// template<typename T> struct X;
12304 /// \endcode
12306
12307 /// We are matching the template parameter lists of two template
12308 /// template parameters as part of matching the template parameter lists
12309 /// of two templates that might be redeclarations.
12310 ///
12311 /// \code
12312 /// template<template<int I> class TT> struct X;
12313 /// template<template<int Value> class Other> struct X;
12314 /// \endcode
12316
12317 /// We are determining whether the template-parameters are equivalent
12318 /// according to C++ [temp.over.link]/6. This comparison does not consider
12319 /// constraints.
12320 ///
12321 /// \code
12322 /// template<C1 T> void f(T);
12323 /// template<C2 T> void f(T);
12324 /// \endcode
12326 };
12327
12328 // A struct to represent the 'new' declaration, which is either itself just
12329 // the named decl, or the important information we need about it in order to
12330 // do constraint comparisons.
12332 const NamedDecl *ND = nullptr;
12333 const DeclContext *DC = nullptr;
12334 const DeclContext *LexicalDC = nullptr;
12335 SourceLocation Loc;
12336
12337 public:
12340 const DeclContext *LexicalDeclCtx,
12341 SourceLocation Loc)
12342
12343 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12344 assert(DC && LexicalDC &&
12345 "Constructor only for cases where we have the information to put "
12346 "in here");
12347 }
12348
12349 // If this was constructed with no information, we cannot do substitution
12350 // for constraint comparison, so make sure we can check that.
12351 bool isInvalid() const { return !ND && !DC; }
12352
12353 const NamedDecl *getDecl() const { return ND; }
12354
12355 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12356
12358 return ND ? ND->getLexicalDeclContext() : LexicalDC;
12359 }
12360
12362 return ND ? ND->getDeclContext() : DC;
12363 }
12364
12365 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12366 };
12367
12368 /// Determine whether the given template parameter lists are
12369 /// equivalent.
12370 ///
12371 /// \param New The new template parameter list, typically written in the
12372 /// source code as part of a new template declaration.
12373 ///
12374 /// \param Old The old template parameter list, typically found via
12375 /// name lookup of the template declared with this template parameter
12376 /// list.
12377 ///
12378 /// \param Complain If true, this routine will produce a diagnostic if
12379 /// the template parameter lists are not equivalent.
12380 ///
12381 /// \param Kind describes how we are to match the template parameter lists.
12382 ///
12383 /// \param TemplateArgLoc If this source location is valid, then we
12384 /// are actually checking the template parameter list of a template
12385 /// argument (New) against the template parameter list of its
12386 /// corresponding template template parameter (Old). We produce
12387 /// slightly different diagnostics in this scenario.
12388 ///
12389 /// \returns True if the template parameter lists are equal, false
12390 /// otherwise.
12392 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12393 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12395 SourceLocation TemplateArgLoc = SourceLocation());
12396
12398 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12400 SourceLocation TemplateArgLoc = SourceLocation()) {
12401 return TemplateParameterListsAreEqual(nullptr, New, nullptr, Old, Complain,
12402 Kind, TemplateArgLoc);
12403 }
12404
12405 /// Check whether a template can be declared within this scope.
12406 ///
12407 /// If the template declaration is valid in this scope, returns
12408 /// false. Otherwise, issues a diagnostic and returns true.
12409 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12410
12411 /// Called when the parser has parsed a C++ typename
12412 /// specifier, e.g., "typename T::type".
12413 ///
12414 /// \param S The scope in which this typename type occurs.
12415 /// \param TypenameLoc the location of the 'typename' keyword
12416 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12417 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12418 /// \param IdLoc the location of the identifier.
12419 /// \param IsImplicitTypename context where T::type refers to a type.
12421 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12422 const IdentifierInfo &II, SourceLocation IdLoc,
12424
12425 /// Called when the parser has parsed a C++ typename
12426 /// specifier that ends in a template-id, e.g.,
12427 /// "typename MetaFun::template apply<T1, T2>".
12428 ///
12429 /// \param S The scope in which this typename type occurs.
12430 /// \param TypenameLoc the location of the 'typename' keyword
12431 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12432 /// \param TemplateLoc the location of the 'template' keyword, if any.
12433 /// \param TemplateName The template name.
12434 /// \param TemplateII The identifier used to name the template.
12435 /// \param TemplateIILoc The location of the template name.
12436 /// \param LAngleLoc The location of the opening angle bracket ('<').
12437 /// \param TemplateArgs The template arguments.
12438 /// \param RAngleLoc The location of the closing angle bracket ('>').
12440 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12441 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12442 TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12443 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12444 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12445
12447 SourceLocation KeywordLoc,
12448 NestedNameSpecifierLoc QualifierLoc,
12449 const IdentifierInfo &II, SourceLocation IILoc,
12450 TypeSourceInfo **TSI, bool DeducedTSTContext);
12451
12453 SourceLocation KeywordLoc,
12454 NestedNameSpecifierLoc QualifierLoc,
12455 const IdentifierInfo &II, SourceLocation IILoc,
12456 bool DeducedTSTContext = true);
12457
12458 /// Rebuilds a type within the context of the current instantiation.
12459 ///
12460 /// The type \p T is part of the type of an out-of-line member definition of
12461 /// a class template (or class template partial specialization) that was
12462 /// parsed and constructed before we entered the scope of the class template
12463 /// (or partial specialization thereof). This routine will rebuild that type
12464 /// now that we have entered the declarator's scope, which may produce
12465 /// different canonical types, e.g.,
12466 ///
12467 /// \code
12468 /// template<typename T>
12469 /// struct X {
12470 /// typedef T* pointer;
12471 /// pointer data();
12472 /// };
12473 ///
12474 /// template<typename T>
12475 /// typename X<T>::pointer X<T>::data() { ... }
12476 /// \endcode
12477 ///
12478 /// Here, the type "typename X<T>::pointer" will be created as a
12479 /// DependentNameType, since we do not know that we can look into X<T> when we
12480 /// parsed the type. This function will rebuild the type, performing the
12481 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12482 /// canonical type is the same as the canonical type of T*, allowing the
12483 /// return types of the out-of-line definition and the declaration to match.
12485 SourceLocation Loc,
12486 DeclarationName Name);
12488
12490
12491 /// Rebuild the template parameters now that we know we're in a current
12492 /// instantiation.
12493 bool
12495
12496 /// Produces a formatted string that describes the binding of
12497 /// template parameters to template arguments.
12498 std::string
12500 const TemplateArgumentList &Args);
12501
12502 std::string
12504 const TemplateArgument *Args,
12505 unsigned NumArgs);
12506
12510
12511 /// ActOnDependentIdExpression - Handle a dependent id-expression that
12512 /// was just parsed. This is only possible with an explicit scope
12513 /// specifier naming a dependent type.
12515 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12516 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12517 const TemplateArgumentListInfo *TemplateArgs);
12518
12521 SourceLocation TemplateKWLoc,
12522 const DeclarationNameInfo &NameInfo,
12523 const TemplateArgumentListInfo *TemplateArgs);
12524
12525 // Calculates whether the expression Constraint depends on an enclosing
12526 // template, for the purposes of [temp.friend] p9.
12527 // TemplateDepth is the 'depth' of the friend function, which is used to
12528 // compare whether a declaration reference is referring to a containing
12529 // template, or just the current friend function. A 'lower' TemplateDepth in
12530 // the AST refers to a 'containing' template. As the constraint is
12531 // uninstantiated, this is relative to the 'top' of the TU.
12532 bool
12534 unsigned TemplateDepth,
12535 const Expr *Constraint);
12536
12537 /// Find the failed Boolean condition within a given Boolean
12538 /// constant expression, and describe it with a string.
12539 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12540
12542
12544 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12545 const IdentifierInfo *Name, SourceLocation NameLoc);
12546
12548 Expr *ConstraintExpr,
12549 const ParsedAttributesView &Attrs);
12550
12552 bool &AddToScope);
12554
12555 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12556 const CXXScopeSpec &SS,
12557 const IdentifierInfo *Name,
12558 SourceLocation TagLoc, SourceLocation NameLoc);
12559
12561 CachedTokens &Toks);
12564
12565 /// We've found a use of a templated declaration that would trigger an
12566 /// implicit instantiation. Check that any relevant explicit specializations
12567 /// and partial specializations are visible/reachable, and diagnose if not.
12570
12571 ///@}
12572
12573 //
12574 //
12575 // -------------------------------------------------------------------------
12576 //
12577 //
12578
12579 /// \name C++ Template Argument Deduction
12580 /// Implementations are in SemaTemplateDeduction.cpp
12581 ///@{
12582
12583public:
12584 class SFINAETrap;
12585
12588 : S(S), Prev(std::exchange(S.CurrentSFINAEContext, Cur)) {}
12589
12590 protected:
12592 ~SFINAEContextBase() { S.CurrentSFINAEContext = Prev; }
12595
12596 private:
12597 SFINAETrap *Prev;
12598 };
12599
12603
12604 /// RAII class used to determine whether SFINAE has
12605 /// trapped any errors that occur during template argument
12606 /// deduction.
12607 class SFINAETrap : SFINAEContextBase {
12608 bool HasErrorOcurred = false;
12609 bool WithAccessChecking = false;
12610 bool PrevLastDiagnosticIgnored =
12611 S.getDiagnostics().isLastDiagnosticIgnored();
12612 sema::TemplateDeductionInfo *DeductionInfo = nullptr;
12613
12614 SFINAETrap(Sema &S, sema::TemplateDeductionInfo *Info,
12615 bool WithAccessChecking)
12616 : SFINAEContextBase(S, this), WithAccessChecking(WithAccessChecking),
12617 DeductionInfo(Info) {}
12618
12619 public:
12620 /// \param WithAccessChecking If true, discard all diagnostics (from the
12621 /// immediate context) instead of adding them to the currently active
12622 /// \ref TemplateDeductionInfo.
12623 explicit SFINAETrap(Sema &S, bool WithAccessChecking = false)
12624 : SFINAETrap(S, /*Info=*/nullptr, WithAccessChecking) {}
12625
12627 : SFINAETrap(S, &Info, /*WithAccessChecking=*/false) {}
12628
12630 S.getDiagnostics().setLastDiagnosticIgnored(PrevLastDiagnosticIgnored);
12631 }
12632
12633 SFINAETrap(const SFINAETrap &) = delete;
12634 SFINAETrap &operator=(const SFINAETrap &) = delete;
12635
12637 return DeductionInfo;
12638 }
12639
12640 /// Determine whether any SFINAE errors have been trapped.
12641 bool hasErrorOccurred() const { return HasErrorOcurred; }
12642 void setErrorOccurred() { HasErrorOcurred = true; }
12643
12644 bool withAccessChecking() const { return WithAccessChecking; }
12645 };
12646
12647 /// RAII class used to indicate that we are performing provisional
12648 /// semantic analysis to determine the validity of a construct, so
12649 /// typo-correction and diagnostics in the immediate context (not within
12650 /// implicitly-instantiated templates) should be suppressed.
12652 Sema &SemaRef;
12653 // FIXME: Using a SFINAETrap for this is a hack.
12654 SFINAETrap Trap;
12655 bool PrevDisableTypoCorrection;
12656
12657 public:
12658 explicit TentativeAnalysisScope(Sema &SemaRef)
12659 : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12660 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12661 SemaRef.DisableTypoCorrection = true;
12662 }
12664 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12665 }
12666
12669 };
12670
12671 /// For each declaration that involved template argument deduction, the
12672 /// set of diagnostics that were suppressed during that template argument
12673 /// deduction.
12674 ///
12675 /// FIXME: Serialize this structure to the AST file.
12676 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12679
12680 /// Compare types for equality with respect to possibly compatible
12681 /// function types (noreturn adjustment, implicit calling conventions). If any
12682 /// of parameter and argument is not a function, just perform type comparison.
12683 ///
12684 /// \param P the template parameter type.
12685 ///
12686 /// \param A the argument type.
12688
12689 /// Allocate a TemplateArgumentLoc where all locations have
12690 /// been initialized to the given location.
12691 ///
12692 /// \param Arg The template argument we are producing template argument
12693 /// location information for.
12694 ///
12695 /// \param NTTPType For a declaration template argument, the type of
12696 /// the non-type template parameter that corresponds to this template
12697 /// argument. Can be null if no type sugar is available to add to the
12698 /// type from the template argument.
12699 ///
12700 /// \param Loc The source location to use for the resulting template
12701 /// argument.
12703 QualType NTTPType,
12704 SourceLocation Loc);
12705
12706 /// Get a template argument mapping the given template parameter to itself,
12707 /// e.g. for X in \c template<int X>, this would return an expression template
12708 /// argument referencing X.
12710 SourceLocation Location);
12711
12712 /// Adjust the type \p ArgFunctionType to match the calling convention,
12713 /// noreturn, and optionally the exception specification of \p FunctionType.
12714 /// Deduction often wants to ignore these properties when matching function
12715 /// types.
12717 bool AdjustExceptionSpec = false);
12718
12721 ArrayRef<TemplateArgument> TemplateArgs,
12723
12726 ArrayRef<TemplateArgument> TemplateArgs,
12728
12729 /// Deduce the template arguments of the given template from \p FromType.
12730 /// Used to implement the IsDeducible constraint for alias CTAD per C++
12731 /// [over.match.class.deduct]p4.
12732 ///
12733 /// It only supports class or type alias templates.
12737
12742 bool NumberOfArgumentsMustMatch);
12743
12744 /// Substitute the explicitly-provided template arguments into the
12745 /// given function template according to C++ [temp.arg.explicit].
12746 ///
12747 /// \param FunctionTemplate the function template into which the explicit
12748 /// template arguments will be substituted.
12749 ///
12750 /// \param ExplicitTemplateArgs the explicitly-specified template
12751 /// arguments.
12752 ///
12753 /// \param Deduced the deduced template arguments, which will be populated
12754 /// with the converted and checked explicit template arguments.
12755 ///
12756 /// \param ParamTypes will be populated with the instantiated function
12757 /// parameters.
12758 ///
12759 /// \param FunctionType if non-NULL, the result type of the function template
12760 /// will also be instantiated and the pointed-to value will be updated with
12761 /// the instantiated function type.
12762 ///
12763 /// \param Info if substitution fails for any reason, this object will be
12764 /// populated with more information about the failure.
12765 ///
12766 /// \returns TemplateDeductionResult::Success if substitution was successful,
12767 /// or some failure condition.
12770 TemplateArgumentListInfo &ExplicitTemplateArgs,
12774
12775 /// brief A function argument from which we performed template argument
12776 // deduction for a call.
12789
12790 /// Finish template argument deduction for a function template,
12791 /// checking the deduced template arguments for completeness and forming
12792 /// the function template specialization.
12793 ///
12794 /// \param OriginalCallArgs If non-NULL, the original call arguments against
12795 /// which the deduced argument types should be compared.
12796 /// \param CheckNonDependent Callback before substituting into the declaration
12797 /// with the deduced template arguments.
12798 /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12799 /// some breakages introduced by CWG2369, where non-user-defined conversions
12800 /// are checked first before the constraints.
12804 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12806 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12807 bool PartialOverloading, bool PartialOrdering,
12808 bool ForOverloadSetAddressResolution,
12809 llvm::function_ref<bool(bool)> CheckNonDependent =
12810 [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12811 return false;
12812 });
12813
12814 /// Perform template argument deduction from a function call
12815 /// (C++ [temp.deduct.call]).
12816 ///
12817 /// \param FunctionTemplate the function template for which we are performing
12818 /// template argument deduction.
12819 ///
12820 /// \param ExplicitTemplateArgs the explicit template arguments provided
12821 /// for this call.
12822 ///
12823 /// \param Args the function call arguments
12824 ///
12825 /// \param Specialization if template argument deduction was successful,
12826 /// this will be set to the function template specialization produced by
12827 /// template argument deduction.
12828 ///
12829 /// \param Info the argument will be updated to provide additional information
12830 /// about template argument deduction.
12831 ///
12832 /// \param CheckNonDependent A callback to invoke to check conversions for
12833 /// non-dependent parameters, between deduction and substitution, per DR1391.
12834 /// If this returns true, substitution will be skipped and we return
12835 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12836 /// passed the parameter types (after substituting explicit template
12837 /// arguments).
12838 ///
12839 /// \returns the result of template argument deduction.
12842 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12844 bool PartialOverloading, bool AggregateDeductionCandidate,
12845 bool PartialOrdering, QualType ObjectType,
12846 Expr::Classification ObjectClassification,
12847 bool ForOverloadSetAddressResolution,
12848 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12849
12850 /// Deduce template arguments when taking the address of a function
12851 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12852 /// a template.
12853 ///
12854 /// \param FunctionTemplate the function template for which we are performing
12855 /// template argument deduction.
12856 ///
12857 /// \param ExplicitTemplateArgs the explicitly-specified template
12858 /// arguments.
12859 ///
12860 /// \param ArgFunctionType the function type that will be used as the
12861 /// "argument" type (A) when performing template argument deduction from the
12862 /// function template's function type. This type may be NULL, if there is no
12863 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
12864 ///
12865 /// \param Specialization if template argument deduction was successful,
12866 /// this will be set to the function template specialization produced by
12867 /// template argument deduction.
12868 ///
12869 /// \param Info the argument will be updated to provide additional information
12870 /// about template argument deduction.
12871 ///
12872 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12873 /// the address of a function template per [temp.deduct.funcaddr] and
12874 /// [over.over]. If \c false, we are looking up a function template
12875 /// specialization based on its signature, per [temp.deduct.decl].
12876 ///
12877 /// \returns the result of template argument deduction.
12880 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
12882 bool IsAddressOfFunction = false);
12883
12884 /// Deduce template arguments for a templated conversion
12885 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
12886 /// conversion function template specialization.
12889 Expr::Classification ObjectClassification, QualType ToType,
12891
12892 /// Deduce template arguments for a function template when there is
12893 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
12894 ///
12895 /// \param FunctionTemplate the function template for which we are performing
12896 /// template argument deduction.
12897 ///
12898 /// \param ExplicitTemplateArgs the explicitly-specified template
12899 /// arguments.
12900 ///
12901 /// \param Specialization if template argument deduction was successful,
12902 /// this will be set to the function template specialization produced by
12903 /// template argument deduction.
12904 ///
12905 /// \param Info the argument will be updated to provide additional information
12906 /// about template argument deduction.
12907 ///
12908 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12909 /// the address of a function template in a context where we do not have a
12910 /// target type, per [over.over]. If \c false, we are looking up a function
12911 /// template specialization based on its signature, which only happens when
12912 /// deducing a function parameter type from an argument that is a template-id
12913 /// naming a function template specialization.
12914 ///
12915 /// \returns the result of template argument deduction.
12918 TemplateArgumentListInfo *ExplicitTemplateArgs,
12921 bool IsAddressOfFunction = false);
12922
12923 /// Substitute Replacement for \p auto in \p TypeWithAuto
12924 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
12925 /// Substitute Replacement for auto in TypeWithAuto
12927 QualType Replacement);
12928
12929 // Substitute auto in TypeWithAuto for a Dependent auto type
12931
12932 // Substitute auto in TypeWithAuto for a Dependent auto type
12935
12936 /// Completely replace the \c auto in \p TypeWithAuto by
12937 /// \p Replacement. This does not retain any \c auto type sugar.
12938 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
12940 QualType Replacement);
12941
12942 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
12943 ///
12944 /// Note that this is done even if the initializer is dependent. (This is
12945 /// necessary to support partial ordering of templates using 'auto'.)
12946 /// A dependent type will be produced when deducing from a dependent type.
12947 ///
12948 /// \param Type the type pattern using the auto type-specifier.
12949 /// \param Init the initializer for the variable whose type is to be deduced.
12950 /// \param Result if type deduction was successful, this will be set to the
12951 /// deduced type.
12952 /// \param Info the argument will be updated to provide additional information
12953 /// about template argument deduction.
12954 /// \param DependentDeduction Set if we should permit deduction in
12955 /// dependent cases. This is necessary for template partial ordering
12956 /// with 'auto' template parameters. The template parameter depth to be
12957 /// used should be specified in the 'Info' parameter.
12958 /// \param IgnoreConstraints Set if we should not fail if the deduced type
12959 /// does not satisfy the type-constraint in the auto
12960 /// type.
12964 bool DependentDeduction = false,
12965 bool IgnoreConstraints = false,
12966 TemplateSpecCandidateSet *FailedTSC = nullptr);
12967 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
12969 bool Diagnose = true);
12970
12972 SourceLocation Loc);
12973
12974 /// Returns the more specialized class template partial specialization
12975 /// according to the rules of partial ordering of class template partial
12976 /// specializations (C++ [temp.class.order]).
12977 ///
12978 /// \param PS1 the first class template partial specialization
12979 ///
12980 /// \param PS2 the second class template partial specialization
12981 ///
12982 /// \returns the more specialized class template partial specialization. If
12983 /// neither partial specialization is more specialized, returns NULL.
12988
12991
12995
12998
13000 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
13001 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
13002 bool PartialOrdering, bool *StrictPackMatch);
13003
13004 /// Mark which template parameters are used in a given expression.
13005 ///
13006 /// \param E the expression from which template parameters will be deduced.
13007 ///
13008 /// \param Used a bit vector whose elements will be set to \c true
13009 /// to indicate when the corresponding template parameter will be
13010 /// deduced.
13011 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
13012 unsigned Depth, llvm::SmallBitVector &Used);
13013
13014 /// Mark which template parameters are named in a given expression.
13015 ///
13016 /// Unlike MarkUsedTemplateParameters, this excludes parameter that
13017 /// are used but not directly named by an expression - i.e. it excludes
13018 /// any template parameter that denotes the type of a referenced NTTP.
13019 ///
13020 /// \param Used a bit vector whose elements will be set to \c true
13021 /// to indicate when the corresponding template parameter will be
13022 /// deduced.
13024 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used);
13025
13026 /// Mark which template parameters can be deduced from a given
13027 /// template argument list.
13028 ///
13029 /// \param TemplateArgs the template argument list from which template
13030 /// parameters will be deduced.
13031 ///
13032 /// \param Used a bit vector whose elements will be set to \c true
13033 /// to indicate when the corresponding template parameter will be
13034 /// deduced.
13035 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
13036 bool OnlyDeduced, unsigned Depth,
13037 llvm::SmallBitVector &Used);
13038
13040 unsigned Depth, llvm::SmallBitVector &Used);
13041
13043 unsigned Depth, llvm::SmallBitVector &Used);
13044
13045 void
13050
13051 /// Marks all of the template parameters that will be deduced by a
13052 /// call to the given function template.
13053 static void
13056 llvm::SmallBitVector &Deduced);
13057
13058 /// Returns the more specialized function template according
13059 /// to the rules of function template partial ordering (C++
13060 /// [temp.func.order]).
13061 ///
13062 /// \param FT1 the first function template
13063 ///
13064 /// \param FT2 the second function template
13065 ///
13066 /// \param TPOC the context in which we are performing partial ordering of
13067 /// function templates.
13068 ///
13069 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
13070 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
13071 /// when calling a member function.
13072 ///
13073 /// \param RawObj1Ty The type of the object parameter of FT1 if a member
13074 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
13075 /// template from a member function
13076 ///
13077 /// \param RawObj2Ty The type of the object parameter of FT2 if a member
13078 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
13079 /// template from a member function
13080 ///
13081 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
13082 /// candidate with a reversed parameter order. In this case, the corresponding
13083 /// P/A pairs between FT1 and FT2 are reversed.
13084 ///
13085 /// \returns the more specialized function template. If neither
13086 /// template is more specialized, returns NULL.
13089 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
13090 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
13091 bool PartialOverloading = false);
13092
13093 /// Retrieve the most specialized of the given function template
13094 /// specializations.
13095 ///
13096 /// \param SpecBegin the start iterator of the function template
13097 /// specializations that we will be comparing.
13098 ///
13099 /// \param SpecEnd the end iterator of the function template
13100 /// specializations, paired with \p SpecBegin.
13101 ///
13102 /// \param Loc the location where the ambiguity or no-specializations
13103 /// diagnostic should occur.
13104 ///
13105 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
13106 /// no matching candidates.
13107 ///
13108 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
13109 /// occurs.
13110 ///
13111 /// \param CandidateDiag partial diagnostic used for each function template
13112 /// specialization that is a candidate in the ambiguous ordering. One
13113 /// parameter in this diagnostic should be unbound, which will correspond to
13114 /// the string describing the template arguments for the function template
13115 /// specialization.
13116 ///
13117 /// \returns the most specialized function template specialization, if
13118 /// found. Otherwise, returns SpecEnd.
13119 UnresolvedSetIterator
13120 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
13121 TemplateSpecCandidateSet &FailedCandidates,
13122 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
13123 const PartialDiagnostic &AmbigDiag,
13124 const PartialDiagnostic &CandidateDiag,
13125 bool Complain = true, QualType TargetType = QualType());
13126
13127 /// Returns the more constrained function according to the rules of
13128 /// partial ordering by constraints (C++ [temp.constr.order]).
13129 ///
13130 /// \param FD1 the first function
13131 ///
13132 /// \param FD2 the second function
13133 ///
13134 /// \returns the more constrained function. If neither function is
13135 /// more constrained, returns NULL.
13136 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
13137 FunctionDecl *FD2);
13138
13139 ///@}
13140
13141 //
13142 //
13143 // -------------------------------------------------------------------------
13144 //
13145 //
13146
13147 /// \name C++ Template Deduction Guide
13148 /// Implementations are in SemaTemplateDeductionGuide.cpp
13149 ///@{
13150
13151 /// Declare implicit deduction guides for a class template if we've
13152 /// not already done so.
13153 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
13154 SourceLocation Loc);
13155
13156 CXXDeductionGuideDecl *DeclareAggregateDeductionGuideFromInitList(
13157 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
13158 SourceLocation Loc);
13159
13160 ///@}
13161
13162 //
13163 //
13164 // -------------------------------------------------------------------------
13165 //
13166 //
13167
13168 /// \name C++ Template Instantiation
13169 /// Implementations are in SemaTemplateInstantiate.cpp
13170 ///@{
13171
13172public:
13173 /// A helper class for building up ExtParameterInfos.
13176 bool HasInteresting = false;
13177
13178 public:
13179 /// Set the ExtParameterInfo for the parameter at the given index,
13180 ///
13182 assert(Infos.size() <= index);
13183 Infos.resize(index);
13184 Infos.push_back(info);
13185
13186 if (!HasInteresting)
13187 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
13188 }
13189
13190 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
13191 /// ExtParameterInfo array we've built up.
13193 getPointerOrNull(unsigned numParams) {
13194 if (!HasInteresting)
13195 return nullptr;
13196 Infos.resize(numParams);
13197 return Infos.data();
13198 }
13199 };
13200
13201 /// The current instantiation scope used to store local
13202 /// variables.
13204
13205 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
13207
13208 /// A mapping from parameters with unparsed default arguments to the
13209 /// set of instantiations of each parameter.
13210 ///
13211 /// This mapping is a temporary data structure used when parsing
13212 /// nested class templates or nested classes of class templates,
13213 /// where we might end up instantiating an inner class before the
13214 /// default arguments of its methods have been parsed.
13216
13217 using InstantiatingSpecializationsKey = llvm::PointerIntPair<Decl *, 2>;
13218
13225
13227 : S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
13228 auto [_, Created] = S.InstantiatingSpecializations.insert(Key);
13229 if (!Created)
13230 Key = {};
13231 }
13232
13234 if (Key.getOpaqueValue()) {
13235 [[maybe_unused]] bool Erased =
13236 S.InstantiatingSpecializations.erase(Key);
13237 assert(Erased);
13238 }
13239 }
13240
13243
13244 operator bool() const { return Key.getOpaqueValue() == nullptr; }
13245
13246 private:
13247 Sema &S;
13249 };
13250
13251 /// A context in which code is being synthesized (where a source location
13252 /// alone is not sufficient to identify the context). This covers template
13253 /// instantiation and various forms of implicitly-generated functions.
13255 /// The kind of template instantiation we are performing
13257 /// We are instantiating a template declaration. The entity is
13258 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
13260
13261 /// We are instantiating a default argument for a template
13262 /// parameter. The Entity is the template parameter whose argument is
13263 /// being instantiated, the Template is the template, and the
13264 /// TemplateArgs/NumTemplateArguments provide the template arguments as
13265 /// specified.
13267
13268 /// We are instantiating a default argument for a function.
13269 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
13270 /// provides the template arguments as specified.
13272
13273 /// We are substituting explicit template arguments provided for
13274 /// a function template. The entity is a FunctionTemplateDecl.
13276
13277 /// We are substituting template argument determined as part of
13278 /// template argument deduction for either a class template
13279 /// partial specialization or a function template. The
13280 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
13281 /// a TemplateDecl.
13283
13284 /// We are substituting into a lambda expression.
13286
13287 /// We are substituting prior template arguments into a new
13288 /// template parameter. The template parameter itself is either a
13289 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
13291
13292 /// We are checking the validity of a default template argument that
13293 /// has been used when naming a template-id.
13295
13296 /// We are computing the exception specification for a defaulted special
13297 /// member function.
13299
13300 /// We are instantiating the exception specification for a function
13301 /// template which was deferred until it was needed.
13303
13304 /// We are instantiating a requirement of a requires expression.
13306
13307 /// We are checking the satisfaction of a nested requirement of a requires
13308 /// expression.
13310
13311 /// We are declaring an implicit special member function.
13313
13314 /// We are declaring an implicit 'operator==' for a defaulted
13315 /// 'operator<=>'.
13317
13318 /// We are defining a synthesized function (such as a defaulted special
13319 /// member).
13321
13322 // We are checking the constraints associated with a constrained entity or
13323 // the constraint expression of a concept. This includes the checks that
13324 // atomic constraints have the type 'bool' and that they can be constant
13325 // evaluated.
13327
13328 // We are substituting template arguments into a constraint expression.
13330
13331 // Instantiating a Requires Expression parameter clause.
13333
13334 // We are substituting into the parameter mapping of an atomic constraint
13335 // during normalization.
13337
13338 /// We are rewriting a comparison operator in terms of an operator<=>.
13340
13341 /// We are initializing a structured binding.
13343
13344 /// We are marking a class as __dllexport.
13346
13347 /// We are building an implied call from __builtin_dump_struct. The
13348 /// arguments are in CallArgs.
13350
13351 /// Added for Template instantiation observation.
13352 /// Memoization means we are _not_ instantiating a template because
13353 /// it is already instantiated (but we entered a context where we
13354 /// would have had to if it was not already instantiated).
13356
13357 /// We are building deduction guides for a class.
13359
13360 /// We are instantiating a type alias template declaration.
13362
13363 /// We are performing partial ordering for template template parameters.
13365
13366 /// We are performing name lookup for a function template or variable
13367 /// template named 'sycl_kernel_launch'.
13369
13370 /// We are performing overload resolution for a call to a function
13371 /// template or variable template named 'sycl_kernel_launch'.
13373
13374 /// We are instantiating an expansion statement.
13376 } Kind;
13377
13378 /// Whether we're substituting into constraints.
13380
13381 /// Whether we're substituting into the parameter mapping of a constraint.
13383
13384 /// The point of instantiation or synthesis within the source code.
13386
13387 /// The entity that is being synthesized.
13389
13390 /// The template (or partial specialization) in which we are
13391 /// performing the instantiation, for substitutions of prior template
13392 /// arguments.
13394
13395 union {
13396 /// The list of template arguments we are substituting, if they
13397 /// are not part of the entity.
13399
13400 /// The list of argument expressions in a synthesized call.
13401 const Expr *const *CallArgs;
13402 };
13403
13404 // FIXME: Wrap this union around more members, or perhaps store the
13405 // kind-specific members in the RAII object owning the context.
13406 union {
13407 /// The number of template arguments in TemplateArgs.
13409
13410 /// The number of expressions in CallArgs.
13411 unsigned NumCallArgs;
13412
13413 /// The special member being declared or defined.
13415 };
13416
13421
13422 /// The source range that covers the construct that cause
13423 /// the instantiation, e.g., the template-id that causes a class
13424 /// template instantiation.
13426
13431
13432 /// Determines whether this template is an actual instantiation
13433 /// that should be counted toward the maximum instantiation depth.
13434 bool isInstantiationRecord() const;
13435 };
13436
13437 /// A stack object to be created when performing template
13438 /// instantiation.
13439 ///
13440 /// Construction of an object of type \c InstantiatingTemplate
13441 /// pushes the current instantiation onto the stack of active
13442 /// instantiations. If the size of this stack exceeds the maximum
13443 /// number of recursive template instantiations, construction
13444 /// produces an error and evaluates true.
13445 ///
13446 /// Destruction of this object will pop the named instantiation off
13447 /// the stack.
13449 /// Note that we are instantiating a class template,
13450 /// function template, variable template, alias template,
13451 /// or a member thereof.
13452 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13453 Decl *Entity,
13454 SourceRange InstantiationRange = SourceRange());
13455
13457 /// Note that we are instantiating an exception specification
13458 /// of a function template.
13459 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13461 SourceRange InstantiationRange = SourceRange());
13462
13463 /// Note that we are instantiating a type alias template declaration.
13464 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13465 TypeAliasTemplateDecl *Entity,
13466 ArrayRef<TemplateArgument> TemplateArgs,
13467 SourceRange InstantiationRange = SourceRange());
13468
13469 /// Note that we are instantiating a default argument in a
13470 /// template-id.
13471 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13473 ArrayRef<TemplateArgument> TemplateArgs,
13474 SourceRange InstantiationRange = SourceRange());
13475
13476 /// Note that we are substituting either explicitly-specified or
13477 /// deduced template arguments during function template argument deduction.
13478 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13480 ArrayRef<TemplateArgument> TemplateArgs,
13482 SourceRange InstantiationRange = SourceRange());
13483
13484 /// Note that we are instantiating as part of template
13485 /// argument deduction for a class template declaration.
13486 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13488 ArrayRef<TemplateArgument> TemplateArgs,
13489 SourceRange InstantiationRange = SourceRange());
13490
13491 /// Note that we are instantiating as part of template
13492 /// argument deduction for a class template partial
13493 /// specialization.
13494 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13496 ArrayRef<TemplateArgument> TemplateArgs,
13497 SourceRange InstantiationRange = SourceRange());
13498
13499 /// Note that we are instantiating as part of template
13500 /// argument deduction for a variable template partial
13501 /// specialization.
13502 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13504 ArrayRef<TemplateArgument> TemplateArgs,
13505 SourceRange InstantiationRange = SourceRange());
13506
13507 /// Note that we are instantiating a default argument for a function
13508 /// parameter.
13509 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13510 ParmVarDecl *Param,
13511 ArrayRef<TemplateArgument> TemplateArgs,
13512 SourceRange InstantiationRange = SourceRange());
13513
13514 /// Note that we are substituting prior template arguments into a
13515 /// non-type parameter.
13516 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13518 ArrayRef<TemplateArgument> TemplateArgs,
13519 SourceRange InstantiationRange);
13520
13521 /// Note that we are substituting prior template arguments into a
13522 /// template template parameter.
13523 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13525 ArrayRef<TemplateArgument> TemplateArgs,
13526 SourceRange InstantiationRange);
13527
13528 /// Note that we are checking the default template argument
13529 /// against the template parameter for a given template-id.
13530 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13532 ArrayRef<TemplateArgument> TemplateArgs,
13533 SourceRange InstantiationRange);
13534
13536 /// \brief Note that we are checking the constraints associated with some
13537 /// constrained entity (a concept declaration or a template with associated
13538 /// constraints).
13539 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13541 ArrayRef<TemplateArgument> TemplateArgs,
13542 SourceRange InstantiationRange);
13543
13545 /// \brief Note that we are checking a constraint expression associated
13546 /// with a template declaration or as part of the satisfaction check of a
13547 /// concept.
13548 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13550 SourceRange InstantiationRange);
13551
13553 /// \brief Note that we are subtituting into the parameter mapping of an
13554 /// atomic constraint during constraint normalization.
13555 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13557 SourceRange InstantiationRange);
13558
13559 /// \brief Note that we are substituting template arguments into a part of
13560 /// a requirement of a requires expression.
13561 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13563 SourceRange InstantiationRange = SourceRange());
13564
13565 /// \brief Note that we are substituting the body of an expansion statement.
13566 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13567 CXXExpansionStmtPattern *ExpansionStmt,
13569 SourceRange InstantiationRange);
13570
13571 /// \brief Note that we are checking the satisfaction of the constraint
13572 /// expression inside of a nested requirement.
13573 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13575 SourceRange InstantiationRange = SourceRange());
13576
13577 /// \brief Note that we are checking a requires clause.
13578 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13579 const RequiresExpr *E,
13580 SourceRange InstantiationRange);
13581
13583 /// \brief Note that we are building deduction guides.
13584 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13586 SourceRange InstantiationRange = SourceRange());
13587
13589 /// \brief Note that we are partial ordering template template parameters.
13590 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13592 SourceRange InstantiationRange = SourceRange());
13593
13594 /// Note that we have finished instantiating this template.
13595 void Clear();
13596
13598
13599 /// Determines whether we have exceeded the maximum
13600 /// recursive template instantiations.
13601 bool isInvalid() const { return Invalid; }
13602
13603 private:
13604 Sema &SemaRef;
13605 bool Invalid;
13606
13609 SourceLocation PointOfInstantiation,
13610 SourceRange InstantiationRange, Decl *Entity,
13611 NamedDecl *Template = nullptr,
13612 ArrayRef<TemplateArgument> TemplateArgs = {});
13613
13615
13616 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13617 };
13618
13619 bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13620 const MultiLevelTemplateArgumentList &TemplateArgs,
13621 TemplateArgumentLoc &Output,
13622 SourceLocation Loc = {},
13623 const DeclarationName &Entity = {});
13624 bool
13625 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13626 const MultiLevelTemplateArgumentList &TemplateArgs,
13627 TemplateArgumentListInfo &Outputs);
13628
13629 /// Substitute concept template arguments in the constraint expression
13630 /// of a concept-id. This is used to implement [temp.constr.normal].
13632 SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE,
13633 const Expr *ConstraintExpr,
13634 const MultiLevelTemplateArgumentList &MLTAL);
13635
13637 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
13638 const MultiLevelTemplateArgumentList &TemplateArgs,
13639 TemplateArgumentListInfo &Out);
13640
13641 /// Retrieve the template argument list(s) that should be used to
13642 /// instantiate the definition of the given declaration.
13643 ///
13644 /// \param ND the declaration for which we are computing template
13645 /// instantiation arguments.
13646 ///
13647 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13648 /// the decl context where it will be created. In this case, the `Innermost`
13649 /// should likely be provided. If ND is non-null, this is ignored.
13650 ///
13651 /// \param Innermost if non-NULL, specifies a template argument list for the
13652 /// template declaration passed as ND.
13653 ///
13654 /// \param RelativeToPrimary true if we should get the template
13655 /// arguments relative to the primary template, even when we're
13656 /// dealing with a specialization. This is only relevant for function
13657 /// template specializations.
13658 ///
13659 /// \param Pattern If non-NULL, indicates the pattern from which we will be
13660 /// instantiating the definition of the given declaration, \p ND. This is
13661 /// used to determine the proper set of template instantiation arguments for
13662 /// friend function template specializations.
13663 ///
13664 /// \param ForConstraintInstantiation when collecting arguments,
13665 /// ForConstraintInstantiation indicates we should continue looking when
13666 /// encountering a lambda generic call operator, and continue looking for
13667 /// arguments on an enclosing class template.
13668 ///
13669 /// \param SkipForSpecialization when specified, any template specializations
13670 /// in a traversal would be ignored.
13671 ///
13672 /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13673 /// when encountering a specialized member function template, rather than
13674 /// returning immediately.
13675 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13676 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13677 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13678 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13679 bool ForConstraintInstantiation = false,
13680 bool SkipForSpecialization = false,
13681 bool ForDefaultArgumentSubstitution = false);
13682
13683 /// RAII object to handle the state changes required to synthesize
13684 /// a function body.
13686 Sema &S;
13687 Sema::ContextRAII SavedContext;
13688 bool PushedCodeSynthesisContext = false;
13689
13690 public:
13692 : S(S), SavedContext(S, DC) {
13693 auto *FD = dyn_cast<FunctionDecl>(DC);
13694 S.PushFunctionScope();
13695 S.PushExpressionEvaluationContextForFunction(
13697 if (FD)
13698 FD->setWillHaveBody(true);
13699 else
13700 assert(isa<ObjCMethodDecl>(DC));
13701 }
13702
13704 assert(!PushedCodeSynthesisContext);
13705
13708 Ctx.PointOfInstantiation = UseLoc;
13709 Ctx.Entity = cast<Decl>(S.CurContext);
13710 S.pushCodeSynthesisContext(Ctx);
13711
13712 PushedCodeSynthesisContext = true;
13713 }
13714
13716 if (PushedCodeSynthesisContext)
13717 S.popCodeSynthesisContext();
13718 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
13719 FD->setWillHaveBody(false);
13720 S.CheckImmediateEscalatingFunctionDefinition(FD, S.getCurFunction());
13721 }
13722 S.PopExpressionEvaluationContext();
13723 S.PopFunctionScopeInfo();
13724 }
13725
13729 };
13730
13731 /// RAII object to ensure that a code synthesis context is popped on scope
13732 /// exit.
13734 Sema &S;
13735
13736 public:
13738 : S(S) {
13739 S.pushCodeSynthesisContext(Ctx);
13740 }
13741
13742 ~ScopedCodeSynthesisContext() { S.popCodeSynthesisContext(); }
13746 };
13747
13748 /// List of active code synthesis contexts.
13749 ///
13750 /// This vector is treated as a stack. As synthesis of one entity requires
13751 /// synthesis of another, additional contexts are pushed onto the stack.
13753
13754 /// Specializations whose definitions are currently being instantiated.
13755 llvm::DenseSet<InstantiatingSpecializationsKey> InstantiatingSpecializations;
13756
13757 /// Non-dependent types used in templates that have already been instantiated
13758 /// by some template instantiation.
13759 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13760
13761 /// Extra modules inspected when performing a lookup during a template
13762 /// instantiation. Computed lazily.
13764
13765 /// Cache of additional modules that should be used for name lookup
13766 /// within the current template instantiation. Computed lazily; use
13767 /// getLookupModules() to get a complete set.
13768 llvm::DenseSet<Module *> LookupModulesCache;
13769
13770 /// Map from the most recent declaration of a namespace to the most
13771 /// recent visible declaration of that namespace.
13772 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13773
13775
13776 /// The number of \p CodeSynthesisContexts that are not template
13777 /// instantiations and, therefore, should not be counted as part of the
13778 /// instantiation depth.
13779 ///
13780 /// When the instantiation depth reaches the user-configurable limit
13781 /// \p LangOptions::InstantiationDepth we will abort instantiation.
13782 // FIXME: Should we have a similar limit for other forms of synthesis?
13784
13785 /// The depth of the context stack at the point when the most recent
13786 /// error or warning was produced.
13787 ///
13788 /// This value is used to suppress printing of redundant context stacks
13789 /// when there are multiple errors or warnings in the same instantiation.
13790 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13792
13793 /// The current index into pack expansion arguments that will be
13794 /// used for substitution of parameter packs.
13795 ///
13796 /// The pack expansion index will be none to indicate that parameter packs
13797 /// should be instantiated as themselves. Otherwise, the index specifies
13798 /// which argument within the parameter pack will be used for substitution.
13800
13801 /// RAII object used to change the argument pack substitution index
13802 /// within a \c Sema object.
13803 ///
13804 /// See \c ArgPackSubstIndex for more information.
13806 Sema &Self;
13807 UnsignedOrNone OldSubstIndex;
13808
13809 public:
13811 : Self(Self),
13812 OldSubstIndex(std::exchange(Self.ArgPackSubstIndex, NewSubstIndex)) {}
13813
13814 ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13817 };
13818
13821
13832 /// Prints the current instantiation stack through a series of
13833 /// notes.
13838
13839 /// Returns a pointer to the current SFINAE context, if any.
13840 [[nodiscard]] SFINAETrap *getSFINAEContext() const {
13841 return CurrentSFINAEContext;
13842 }
13843 [[nodiscard]] bool isSFINAEContext() const {
13844 return CurrentSFINAEContext != nullptr;
13845 }
13846
13847 /// Perform substitution on the type T with a given set of template
13848 /// arguments.
13849 ///
13850 /// This routine substitutes the given template arguments into the
13851 /// type T and produces the instantiated type.
13852 ///
13853 /// \param T the type into which the template arguments will be
13854 /// substituted. If this type is not dependent, it will be returned
13855 /// immediately.
13856 ///
13857 /// \param Args the template arguments that will be
13858 /// substituted for the top-level template parameters within T.
13859 ///
13860 /// \param Loc the location in the source code where this substitution
13861 /// is being performed. It will typically be the location of the
13862 /// declarator (if we're instantiating the type of some declaration)
13863 /// or the location of the type in the source code (if, e.g., we're
13864 /// instantiating the type of a cast expression).
13865 ///
13866 /// \param Entity the name of the entity associated with a declaration
13867 /// being instantiated (if any). May be empty to indicate that there
13868 /// is no such entity (if, e.g., this is a type that occurs as part of
13869 /// a cast expression) or that the entity has no name (e.g., an
13870 /// unnamed function parameter).
13871 ///
13872 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
13873 /// acceptable as the top level type of the result.
13874 ///
13875 /// \param IsIncompleteSubstitution If provided, the pointee will be set
13876 /// whenever substitution would perform a replacement with a null or
13877 /// non-existent template argument.
13878 ///
13879 /// \returns If the instantiation succeeds, the instantiated
13880 /// type. Otherwise, produces diagnostics and returns a NULL type.
13882 const MultiLevelTemplateArgumentList &TemplateArgs,
13883 SourceLocation Loc, DeclarationName Entity,
13884 bool AllowDeducedTST = false);
13885
13887 const MultiLevelTemplateArgumentList &TemplateArgs,
13888 SourceLocation Loc, DeclarationName Entity,
13889 bool *IsIncompleteSubstitution = nullptr);
13890
13892 const MultiLevelTemplateArgumentList &TemplateArgs,
13893 SourceLocation Loc, DeclarationName Entity);
13894
13895 /// A form of SubstType intended specifically for instantiating the
13896 /// type of a FunctionDecl. Its purpose is solely to force the
13897 /// instantiation of default-argument expressions and to avoid
13898 /// instantiating an exception-specification.
13900 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
13901 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
13902 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
13904 const MultiLevelTemplateArgumentList &Args);
13907 SmallVectorImpl<QualType> &ExceptionStorage,
13908 const MultiLevelTemplateArgumentList &Args);
13909 ParmVarDecl *
13911 const MultiLevelTemplateArgumentList &TemplateArgs,
13912 int indexAdjustment, UnsignedOrNone NumExpansions,
13913 bool ExpectParameterPack, bool EvaluateConstraints = true);
13914
13915 /// Substitute the given template arguments into the given set of
13916 /// parameters, producing the set of parameter types that would be generated
13917 /// from such a substitution.
13919 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
13920 const MultiLevelTemplateArgumentList &TemplateArgs,
13921 SmallVectorImpl<QualType> &ParamTypes,
13923 ExtParameterInfoBuilder &ParamInfos);
13924
13925 /// Substitute the given template arguments into the default argument.
13927 const MultiLevelTemplateArgumentList &TemplateArgs,
13928 bool ForCallExpr = false);
13930 const MultiLevelTemplateArgumentList &TemplateArgs);
13931 /// Substitute an expression as if it is a address-of-operand, which makes it
13932 /// act like a CXXIdExpression rather than an attempt to call.
13934 const MultiLevelTemplateArgumentList &TemplateArgs);
13935
13936 // Must be used instead of SubstExpr at 'constraint checking' time.
13939 const MultiLevelTemplateArgumentList &TemplateArgs);
13940 // Unlike the above, this does not evaluate constraints.
13942 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
13943
13944 /// Substitute the given template arguments into a list of
13945 /// expressions, expanding pack expansions if required.
13946 ///
13947 /// \param Exprs The list of expressions to substitute into.
13948 ///
13949 /// \param IsCall Whether this is some form of call, in which case
13950 /// default arguments will be dropped.
13951 ///
13952 /// \param TemplateArgs The set of template arguments to substitute.
13953 ///
13954 /// \param Outputs Will receive all of the substituted arguments.
13955 ///
13956 /// \returns true if an error occurred, false otherwise.
13957 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
13958 const MultiLevelTemplateArgumentList &TemplateArgs,
13959 SmallVectorImpl<Expr *> &Outputs);
13960
13962 const MultiLevelTemplateArgumentList &TemplateArgs);
13963
13966 bool CXXDirectInit);
13967
13968 /// Perform substitution on the base class specifiers of the
13969 /// given class template specialization.
13970 ///
13971 /// Produces a diagnostic and returns true on error, returns false and
13972 /// attaches the instantiated base classes to the class template
13973 /// specialization if successful.
13974 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13975 const MultiLevelTemplateArgumentList &TemplateArgs);
13976
13977 /// Instantiate the definition of a class from a given pattern.
13978 ///
13979 /// \param PointOfInstantiation The point of instantiation within the
13980 /// source code.
13981 ///
13982 /// \param Instantiation is the declaration whose definition is being
13983 /// instantiated. This will be either a class template specialization
13984 /// or a member class of a class template specialization.
13985 ///
13986 /// \param Pattern is the pattern from which the instantiation
13987 /// occurs. This will be either the declaration of a class template or
13988 /// the declaration of a member class of a class template.
13989 ///
13990 /// \param TemplateArgs The template arguments to be substituted into
13991 /// the pattern.
13992 ///
13993 /// \param TSK the kind of implicit or explicit instantiation to perform.
13994 ///
13995 /// \param Complain whether to complain if the class cannot be instantiated
13996 /// due to the lack of a definition.
13997 ///
13998 /// \returns true if an error occurred, false otherwise.
13999 bool InstantiateClass(SourceLocation PointOfInstantiation,
14000 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
14001 const MultiLevelTemplateArgumentList &TemplateArgs,
14002 TemplateSpecializationKind TSK, bool Complain = true);
14003
14004private:
14005 bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
14006 CXXRecordDecl *Instantiation,
14007 CXXRecordDecl *Pattern,
14008 const MultiLevelTemplateArgumentList &TemplateArgs,
14009 TemplateSpecializationKind TSK, bool Complain);
14010
14011public:
14012 /// Instantiate the definition of an enum from a given pattern.
14013 ///
14014 /// \param PointOfInstantiation The point of instantiation within the
14015 /// source code.
14016 /// \param Instantiation is the declaration whose definition is being
14017 /// instantiated. This will be a member enumeration of a class
14018 /// temploid specialization, or a local enumeration within a
14019 /// function temploid specialization.
14020 /// \param Pattern The templated declaration from which the instantiation
14021 /// occurs.
14022 /// \param TemplateArgs The template arguments to be substituted into
14023 /// the pattern.
14024 /// \param TSK The kind of implicit or explicit instantiation to perform.
14025 ///
14026 /// \return \c true if an error occurred, \c false otherwise.
14027 bool InstantiateEnum(SourceLocation PointOfInstantiation,
14028 EnumDecl *Instantiation, EnumDecl *Pattern,
14029 const MultiLevelTemplateArgumentList &TemplateArgs,
14031
14032 /// Instantiate the definition of a field from the given pattern.
14033 ///
14034 /// \param PointOfInstantiation The point of instantiation within the
14035 /// source code.
14036 /// \param Instantiation is the declaration whose definition is being
14037 /// instantiated. This will be a class of a class temploid
14038 /// specialization, or a local enumeration within a function temploid
14039 /// specialization.
14040 /// \param Pattern The templated declaration from which the instantiation
14041 /// occurs.
14042 /// \param TemplateArgs The template arguments to be substituted into
14043 /// the pattern.
14044 ///
14045 /// \return \c true if an error occurred, \c false otherwise.
14047 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
14048 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
14049
14051 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
14052
14054 SourceLocation PointOfInstantiation,
14055 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14056 TemplateSpecializationKind TSK, bool Complain,
14057 bool PrimaryStrictPackMatch);
14058
14059 /// Instantiates the definitions of all of the member
14060 /// of the given class, which is an instantiation of a class template
14061 /// or a member class of a template.
14062 void
14063 InstantiateClassMembers(SourceLocation PointOfInstantiation,
14064 CXXRecordDecl *Instantiation,
14065 const MultiLevelTemplateArgumentList &TemplateArgs,
14067
14068 /// Instantiate the definitions of all of the members of the
14069 /// given class template specialization, which was named as part of an
14070 /// explicit instantiation.
14072 SourceLocation PointOfInstantiation,
14073 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14075
14078 const MultiLevelTemplateArgumentList &TemplateArgs);
14079
14080 /// Do template substitution on declaration name info.
14083 const MultiLevelTemplateArgumentList &TemplateArgs);
14085 SubstTemplateName(SourceLocation TemplateKWLoc,
14086 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
14087 SourceLocation NameLoc,
14088 const MultiLevelTemplateArgumentList &TemplateArgs);
14089
14091 const MultiLevelTemplateArgumentList &TemplateArgs,
14092 bool EvaluateConstraint);
14093
14094 /// Determine whether we are currently performing template instantiation.
14097 }
14098
14099 /// Determine whether we are currently performing constraint substitution.
14101 return !CodeSynthesisContexts.empty() &&
14102 CodeSynthesisContexts.back().InConstraintSubstitution;
14103 }
14104
14106 return !CodeSynthesisContexts.empty() &&
14107 CodeSynthesisContexts.back().InParameterMappingSubstitution &&
14109 }
14110
14111 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
14112
14113 /// \brief create a Requirement::SubstitutionDiagnostic with only a
14114 /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
14117
14118 ///@}
14119
14120 //
14121 //
14122 // -------------------------------------------------------------------------
14123 //
14124 //
14125
14126 /// \name C++ Template Declaration Instantiation
14127 /// Implementations are in SemaTemplateInstantiateDecl.cpp
14128 ///@{
14129
14130public:
14131 /// An entity for which implicit template instantiation is required.
14132 ///
14133 /// The source location associated with the declaration is the first place in
14134 /// the source code where the declaration was "used". It is not necessarily
14135 /// the point of instantiation (which will be either before or after the
14136 /// namespace-scope declaration that triggered this implicit instantiation),
14137 /// However, it is the location that diagnostics should generally refer to,
14138 /// because users will need to know what code triggered the instantiation.
14139 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
14140
14141 /// The queue of implicit template instantiations that are required
14142 /// but have not yet been performed.
14143 std::deque<PendingImplicitInstantiation> PendingInstantiations;
14144
14145 /// Queue of implicit template instantiations that cannot be performed
14146 /// eagerly.
14148
14152
14153 /// The queue of implicit template instantiations that are required
14154 /// and must be performed within the current local scope.
14155 ///
14156 /// This queue is only used for member functions of local classes in
14157 /// templates, which must be instantiated in the same scope as their
14158 /// enclosing function, so that they can reference function-local
14159 /// types, static variables, enumerators, etc.
14160 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
14161
14163 public:
14165 : S(S), AtEndOfTU(AtEndOfTU) {
14166 SavedPendingLocalImplicitInstantiations.swap(
14167 S.PendingLocalImplicitInstantiations);
14168 }
14169
14170 void perform() {
14171 S.PerformPendingInstantiations(/*LocalOnly=*/true,
14172 /*AtEndOfTU=*/AtEndOfTU);
14173 }
14174
14176 assert(S.PendingLocalImplicitInstantiations.empty() &&
14177 "there shouldn't be any pending local implicit instantiations");
14178 SavedPendingLocalImplicitInstantiations.swap(
14179 S.PendingLocalImplicitInstantiations);
14180 }
14181
14185
14186 private:
14187 Sema &S;
14188 bool AtEndOfTU;
14189 std::deque<PendingImplicitInstantiation>
14190 SavedPendingLocalImplicitInstantiations;
14191 };
14192
14193 /// Records and restores the CurFPFeatures state on entry/exit of compound
14194 /// statements.
14196 public:
14201 FPOptionsOverride getOverrides() { return OldOverrides; }
14202
14203 private:
14204 Sema &S;
14205 FPOptions OldFPFeaturesState;
14206 FPOptionsOverride OldOverrides;
14207 LangOptions::FPEvalMethodKind OldEvalMethod;
14208 SourceLocation OldFPPragmaLocation;
14209 };
14210
14212 public:
14213 GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
14214 : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
14215 if (!Enabled)
14216 return;
14217
14218 S.SavedPendingInstantiations.emplace_back();
14219 S.SavedPendingInstantiations.back().swap(S.PendingInstantiations);
14220
14221 S.SavedVTableUses.emplace_back();
14222 S.SavedVTableUses.back().swap(S.VTableUses);
14223 }
14224
14225 void perform() {
14226 if (Enabled) {
14227 S.DefineUsedVTables();
14228 S.PerformPendingInstantiations(/*LocalOnly=*/false,
14229 /*AtEndOfTU=*/AtEndOfTU);
14230 }
14231 }
14232
14234 if (!Enabled)
14235 return;
14236
14237 // Restore the set of pending vtables.
14238 assert(S.VTableUses.empty() &&
14239 "VTableUses should be empty before it is discarded.");
14240 S.VTableUses.swap(S.SavedVTableUses.back());
14241 S.SavedVTableUses.pop_back();
14242
14243 // Restore the set of pending implicit instantiations.
14244 if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
14245 AtEndOfTU) {
14246 assert(S.PendingInstantiations.empty() &&
14247 "PendingInstantiations should be empty before it is discarded.");
14248 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
14249 S.SavedPendingInstantiations.pop_back();
14250 } else {
14251 // Template instantiations in the PCH may be delayed until the TU.
14252 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
14253 S.PendingInstantiations.insert(
14254 S.PendingInstantiations.end(),
14255 S.SavedPendingInstantiations.back().begin(),
14256 S.SavedPendingInstantiations.back().end());
14257 S.SavedPendingInstantiations.pop_back();
14258 }
14259 }
14260
14262 delete;
14265
14266 private:
14267 Sema &S;
14268 bool Enabled;
14269 bool AtEndOfTU;
14270 };
14271
14273 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
14274
14285
14286 /// Recheck instantiated thread-safety attributes that could not be validated
14287 /// on the dependent pattern declaration.
14288 bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A);
14289
14290 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14291 const Decl *Pattern, Decl *Inst,
14292 LateInstantiatedAttrVec *LateAttrs = nullptr,
14293 LocalInstantiationScope *OuterMostScope = nullptr);
14294
14295 /// Update instantiation attributes after template was late parsed.
14296 ///
14297 /// Some attributes are evaluated based on the body of template. If it is
14298 /// late parsed, such attributes cannot be evaluated when declaration is
14299 /// instantiated. This function is used to update instantiation attributes
14300 /// when template definition is ready.
14301 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
14302
14303 void
14305 const Decl *Pattern, Decl *Inst,
14306 LateInstantiatedAttrVec *LateAttrs = nullptr,
14307 LocalInstantiationScope *OuterMostScope = nullptr);
14308
14310 bool IsCopy = false);
14311
14313 ParmVarDecl *Param);
14314 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
14316
14317 /// Instantiate (or find existing instantiation of) a function template with a
14318 /// given set of template arguments.
14319 ///
14320 /// Usually this should not be used, and template argument deduction should be
14321 /// used in its place.
14324 SourceLocation Loc,
14327
14328 /// Instantiate the definition of the given function from its
14329 /// template.
14330 ///
14331 /// \param PointOfInstantiation the point at which the instantiation was
14332 /// required. Note that this is not precisely a "point of instantiation"
14333 /// for the function, but it's close.
14334 ///
14335 /// \param Function the already-instantiated declaration of a
14336 /// function template specialization or member function of a class template
14337 /// specialization.
14338 ///
14339 /// \param Recursive if true, recursively instantiates any functions that
14340 /// are required by this instantiation.
14341 ///
14342 /// \param DefinitionRequired if true, then we are performing an explicit
14343 /// instantiation where the body of the function is required. Complain if
14344 /// there is no such body.
14345 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
14347 bool Recursive = false,
14348 bool DefinitionRequired = false,
14349 bool AtEndOfTU = false);
14352 const TemplateArgumentList *PartialSpecArgs,
14354 SourceLocation PointOfInstantiation,
14355 LateInstantiatedAttrVec *LateAttrs = nullptr,
14356 LocalInstantiationScope *StartingScope = nullptr);
14357
14358 /// Instantiates a variable template specialization by completing it
14359 /// with appropriate type information and initializer.
14361 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14362 const MultiLevelTemplateArgumentList &TemplateArgs);
14363
14364 /// BuildVariableInstantiation - Used after a new variable has been created.
14365 /// Sets basic variable data and decides whether to postpone the
14366 /// variable instantiation.
14367 void
14369 const MultiLevelTemplateArgumentList &TemplateArgs,
14370 LateInstantiatedAttrVec *LateAttrs,
14371 DeclContext *Owner,
14372 LocalInstantiationScope *StartingScope,
14373 bool InstantiatingVarTemplate = false,
14374 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14375
14376 /// Instantiate the initializer of a variable.
14378 VarDecl *Var, VarDecl *OldVar,
14379 const MultiLevelTemplateArgumentList &TemplateArgs);
14380
14381 /// Instantiate the definition of the given variable from its
14382 /// template.
14383 ///
14384 /// \param PointOfInstantiation the point at which the instantiation was
14385 /// required. Note that this is not precisely a "point of instantiation"
14386 /// for the variable, but it's close.
14387 ///
14388 /// \param Var the already-instantiated declaration of a templated variable.
14389 ///
14390 /// \param Recursive if true, recursively instantiates any functions that
14391 /// are required by this instantiation.
14392 ///
14393 /// \param DefinitionRequired if true, then we are performing an explicit
14394 /// instantiation where a definition of the variable is required. Complain
14395 /// if there is no such definition.
14396 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14397 VarDecl *Var, bool Recursive = false,
14398 bool DefinitionRequired = false,
14399 bool AtEndOfTU = false);
14400
14403 const MultiLevelTemplateArgumentList &TemplateArgs);
14404
14405 /// Find the instantiation of the given declaration within the
14406 /// current instantiation.
14407 ///
14408 /// This routine is intended to be used when \p D is a declaration
14409 /// referenced from within a template, that needs to mapped into the
14410 /// corresponding declaration within an instantiation. For example,
14411 /// given:
14412 ///
14413 /// \code
14414 /// template<typename T>
14415 /// struct X {
14416 /// enum Kind {
14417 /// KnownValue = sizeof(T)
14418 /// };
14419 ///
14420 /// bool getKind() const { return KnownValue; }
14421 /// };
14422 ///
14423 /// template struct X<int>;
14424 /// \endcode
14425 ///
14426 /// In the instantiation of X<int>::getKind(), we need to map the \p
14427 /// EnumConstantDecl for \p KnownValue (which refers to
14428 /// X<T>::<Kind>::KnownValue) to its instantiation
14429 /// (X<int>::<Kind>::KnownValue).
14430 /// \p FindInstantiatedDecl performs this mapping from within the
14431 /// instantiation of X<int>.
14432 NamedDecl *
14434 const MultiLevelTemplateArgumentList &TemplateArgs,
14435 bool FindingInstantiatedContext = false);
14436
14437 /// Finds the instantiation of the given declaration context
14438 /// within the current instantiation.
14439 ///
14440 /// \returns NULL if there was an error
14441 DeclContext *
14443 const MultiLevelTemplateArgumentList &TemplateArgs);
14444
14445 Decl *SubstDecl(Decl *D, DeclContext *Owner,
14446 const MultiLevelTemplateArgumentList &TemplateArgs);
14447
14448 /// Substitute the name and return type of a defaulted 'operator<=>' to form
14449 /// an implicit 'operator=='.
14451 FunctionDecl *Spaceship);
14452
14453 /// Performs template instantiation for all implicit template
14454 /// instantiations we have seen until this point.
14455 void PerformPendingInstantiations(bool LocalOnly = false,
14456 bool AtEndOfTU = true);
14457
14460 const MultiLevelTemplateArgumentList &TemplateArgs,
14461 bool EvaluateConstraints = true);
14462
14464 const DeclContext *Pattern,
14465 const MultiLevelTemplateArgumentList &TemplateArgs);
14466
14467private:
14468 /// Introduce the instantiated local variables into the local
14469 /// instantiation scope.
14470 void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14471 const FunctionDecl *PatternDecl,
14473 /// Introduce the instantiated function parameters into the local
14474 /// instantiation scope, and set the parameter names to those used
14475 /// in the template.
14476 bool addInstantiatedParametersToScope(
14477 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14479 const MultiLevelTemplateArgumentList &TemplateArgs);
14480
14481 /// Introduce the instantiated captures of the lambda into the local
14482 /// instantiation scope.
14483 bool addInstantiatedCapturesToScope(
14484 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14486 const MultiLevelTemplateArgumentList &TemplateArgs);
14487
14488 int ParsingClassDepth = 0;
14489
14490 class SavePendingParsedClassStateRAII {
14491 public:
14492 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14493
14494 ~SavePendingParsedClassStateRAII() {
14495 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14496 "there shouldn't be any pending delayed exception spec checks");
14497 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14498 "there shouldn't be any pending delayed exception spec checks");
14499 swapSavedState();
14500 }
14501
14502 SavePendingParsedClassStateRAII(const SavePendingParsedClassStateRAII &) =
14503 delete;
14504 SavePendingParsedClassStateRAII &
14505 operator=(const SavePendingParsedClassStateRAII &) = delete;
14506
14507 private:
14508 Sema &S;
14510 SavedOverridingExceptionSpecChecks;
14512 SavedEquivalentExceptionSpecChecks;
14513
14514 void swapSavedState() {
14515 SavedOverridingExceptionSpecChecks.swap(
14516 S.DelayedOverridingExceptionSpecChecks);
14517 SavedEquivalentExceptionSpecChecks.swap(
14518 S.DelayedEquivalentExceptionSpecChecks);
14519 }
14520 };
14521
14522 ///@}
14523
14524 //
14525 //
14526 // -------------------------------------------------------------------------
14527 //
14528 //
14529
14530 /// \name C++ Variadic Templates
14531 /// Implementations are in SemaTemplateVariadic.cpp
14532 ///@{
14533
14534public:
14535 /// Determine whether an unexpanded parameter pack might be permitted in this
14536 /// location. Useful for error recovery.
14538
14539 /// The context in which an unexpanded parameter pack is
14540 /// being diagnosed.
14541 ///
14542 /// Note that the values of this enumeration line up with the first
14543 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14545 /// An arbitrary expression.
14547
14548 /// The base type of a class type.
14550
14551 /// The type of an arbitrary declaration.
14553
14554 /// The type of a data member.
14556
14557 /// The size of a bit-field.
14559
14560 /// The expression in a static assertion.
14562
14563 /// The fixed underlying type of an enumeration.
14565
14566 /// The enumerator value.
14568
14569 /// A using declaration.
14571
14572 /// A friend declaration.
14574
14575 /// A declaration qualifier.
14577
14578 /// An initializer.
14580
14581 /// A default argument.
14583
14584 /// The type of a non-type template parameter.
14586
14587 /// The type of an exception.
14589
14590 /// Explicit specialization.
14592
14593 /// Partial specialization.
14595
14596 /// Microsoft __if_exists.
14598
14599 /// Microsoft __if_not_exists.
14601
14602 /// Lambda expression.
14604
14605 /// Block expression.
14607
14608 /// A type constraint.
14610
14611 // A requirement in a requires-expression.
14613
14614 // A requires-clause.
14616 };
14617
14618 /// Diagnose unexpanded parameter packs.
14619 ///
14620 /// \param Loc The location at which we should emit the diagnostic.
14621 ///
14622 /// \param UPPC The context in which we are diagnosing unexpanded
14623 /// parameter packs.
14624 ///
14625 /// \param Unexpanded the set of unexpanded parameter packs.
14626 ///
14627 /// \returns true if an error occurred, false otherwise.
14631
14632 /// If the given type contains an unexpanded parameter pack,
14633 /// diagnose the error.
14634 ///
14635 /// \param Loc The source location where a diagnostc should be emitted.
14636 ///
14637 /// \param T The type that is being checked for unexpanded parameter
14638 /// packs.
14639 ///
14640 /// \returns true if an error occurred, false otherwise.
14643
14644 /// If the given expression contains an unexpanded parameter
14645 /// pack, diagnose the error.
14646 ///
14647 /// \param E The expression that is being checked for unexpanded
14648 /// parameter packs.
14649 ///
14650 /// \returns true if an error occurred, false otherwise.
14653
14654 /// If the given requirees-expression contains an unexpanded reference to one
14655 /// of its own parameter packs, diagnose the error.
14656 ///
14657 /// \param RE The requiress-expression that is being checked for unexpanded
14658 /// parameter packs.
14659 ///
14660 /// \returns true if an error occurred, false otherwise.
14662
14663 /// If the given nested-name-specifier contains an unexpanded
14664 /// parameter pack, diagnose the error.
14665 ///
14666 /// \param SS The nested-name-specifier that is being checked for
14667 /// unexpanded parameter packs.
14668 ///
14669 /// \returns true if an error occurred, false otherwise.
14672
14673 /// If the given name contains an unexpanded parameter pack,
14674 /// diagnose the error.
14675 ///
14676 /// \param NameInfo The name (with source location information) that
14677 /// is being checked for unexpanded parameter packs.
14678 ///
14679 /// \returns true if an error occurred, false otherwise.
14682
14683 /// If the given template name contains an unexpanded parameter pack,
14684 /// diagnose the error.
14685 ///
14686 /// \param Loc The location of the template name.
14687 ///
14688 /// \param Template The template name that is being checked for unexpanded
14689 /// parameter packs.
14690 ///
14691 /// \returns true if an error occurred, false otherwise.
14695
14696 /// If the given template argument contains an unexpanded parameter
14697 /// pack, diagnose the error.
14698 ///
14699 /// \param Arg The template argument that is being checked for unexpanded
14700 /// parameter packs.
14701 ///
14702 /// \returns true if an error occurred, false otherwise.
14705
14706 /// Collect the set of unexpanded parameter packs within the given
14707 /// template argument.
14708 ///
14709 /// \param Arg The template argument that will be traversed to find
14710 /// unexpanded parameter packs.
14712 TemplateArgument Arg,
14714
14715 /// Collect the set of unexpanded parameter packs within the given
14716 /// template argument.
14717 ///
14718 /// \param Arg The template argument that will be traversed to find
14719 /// unexpanded parameter packs.
14723
14724 /// Collect the set of unexpanded parameter packs within the given
14725 /// type.
14726 ///
14727 /// \param T The type that will be traversed to find
14728 /// unexpanded parameter packs.
14731
14732 /// Collect the set of unexpanded parameter packs within the given
14733 /// type.
14734 ///
14735 /// \param TL The type that will be traversed to find
14736 /// unexpanded parameter packs.
14739
14740 /// Collect the set of unexpanded parameter packs within the given
14741 /// nested-name-specifier.
14742 ///
14743 /// \param NNS The nested-name-specifier that will be traversed to find
14744 /// unexpanded parameter packs.
14748
14749 /// Collect the set of unexpanded parameter packs within the given
14750 /// name.
14751 ///
14752 /// \param NameInfo The name that will be traversed to find
14753 /// unexpanded parameter packs.
14755 const DeclarationNameInfo &NameInfo,
14757
14758 /// Collect the set of unexpanded parameter packs within the given
14759 /// expression.
14762
14763 /// Invoked when parsing a template argument.
14764 ///
14765 /// \param Arg the template argument, which may already be invalid.
14766 ///
14767 /// If it is followed by ellipsis, this function is called before
14768 /// `ActOnPackExpansion`.
14771
14772 /// Invoked when parsing a template argument followed by an
14773 /// ellipsis, which creates a pack expansion.
14774 ///
14775 /// \param Arg The template argument preceding the ellipsis, which
14776 /// may already be invalid.
14777 ///
14778 /// \param EllipsisLoc The location of the ellipsis.
14780 SourceLocation EllipsisLoc);
14781
14782 /// Invoked when parsing a type followed by an ellipsis, which
14783 /// creates a pack expansion.
14784 ///
14785 /// \param Type The type preceding the ellipsis, which will become
14786 /// the pattern of the pack expansion.
14787 ///
14788 /// \param EllipsisLoc The location of the ellipsis.
14790
14791 /// Construct a pack expansion type from the pattern of the pack
14792 /// expansion.
14794 SourceLocation EllipsisLoc,
14795 UnsignedOrNone NumExpansions);
14796
14797 /// Construct a pack expansion type from the pattern of the pack
14798 /// expansion.
14799 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14800 SourceLocation EllipsisLoc,
14801 UnsignedOrNone NumExpansions);
14802
14803 /// Invoked when parsing an expression followed by an ellipsis, which
14804 /// creates a pack expansion.
14805 ///
14806 /// \param Pattern The expression preceding the ellipsis, which will become
14807 /// the pattern of the pack expansion.
14808 ///
14809 /// \param EllipsisLoc The location of the ellipsis.
14810 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14811
14812 /// Invoked when parsing an expression followed by an ellipsis, which
14813 /// creates a pack expansion.
14814 ///
14815 /// \param Pattern The expression preceding the ellipsis, which will become
14816 /// the pattern of the pack expansion.
14817 ///
14818 /// \param EllipsisLoc The location of the ellipsis.
14819 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14820 UnsignedOrNone NumExpansions);
14821
14822 /// Determine whether we could expand a pack expansion with the
14823 /// given set of parameter packs into separate arguments by repeatedly
14824 /// transforming the pattern.
14825 ///
14826 /// \param EllipsisLoc The location of the ellipsis that identifies the
14827 /// pack expansion.
14828 ///
14829 /// \param PatternRange The source range that covers the entire pattern of
14830 /// the pack expansion.
14831 ///
14832 /// \param Unexpanded The set of unexpanded parameter packs within the
14833 /// pattern.
14834 ///
14835 /// \param ShouldExpand Will be set to \c true if the transformer should
14836 /// expand the corresponding pack expansions into separate arguments. When
14837 /// set, \c NumExpansions must also be set.
14838 ///
14839 /// \param RetainExpansion Whether the caller should add an unexpanded
14840 /// pack expansion after all of the expanded arguments. This is used
14841 /// when extending explicitly-specified template argument packs per
14842 /// C++0x [temp.arg.explicit]p9.
14843 ///
14844 /// \param NumExpansions The number of separate arguments that will be in
14845 /// the expanded form of the corresponding pack expansion. This is both an
14846 /// input and an output parameter, which can be set by the caller if the
14847 /// number of expansions is known a priori (e.g., due to a prior substitution)
14848 /// and will be set by the callee when the number of expansions is known.
14849 /// The callee must set this value when \c ShouldExpand is \c true; it may
14850 /// set this value in other cases.
14851 ///
14852 /// \returns true if an error occurred (e.g., because the parameter packs
14853 /// are to be instantiated with arguments of different lengths), false
14854 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
14855 /// must be set.
14857 SourceLocation EllipsisLoc, SourceRange PatternRange,
14859 const MultiLevelTemplateArgumentList &TemplateArgs,
14860 bool FailOnPackProducingTemplates, bool &ShouldExpand,
14861 bool &RetainExpansion, UnsignedOrNone &NumExpansions,
14862 bool Diagnose = true);
14863
14864 /// Determine the number of arguments in the given pack expansion
14865 /// type.
14866 ///
14867 /// This routine assumes that the number of arguments in the expansion is
14868 /// consistent across all of the unexpanded parameter packs in its pattern.
14869 ///
14870 /// Returns an empty Optional if the type can't be expanded.
14872 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
14873
14876 const MultiLevelTemplateArgumentList &TemplateArgs);
14877
14878 /// Determine whether the given declarator contains any unexpanded
14879 /// parameter packs.
14880 ///
14881 /// This routine is used by the parser to disambiguate function declarators
14882 /// with an ellipsis prior to the ')', e.g.,
14883 ///
14884 /// \code
14885 /// void f(T...);
14886 /// \endcode
14887 ///
14888 /// To determine whether we have an (unnamed) function parameter pack or
14889 /// a variadic function.
14890 ///
14891 /// \returns true if the declarator contains any unexpanded parameter packs,
14892 /// false otherwise.
14894
14895 /// Returns the pattern of the pack expansion for a template argument.
14896 ///
14897 /// \param OrigLoc The template argument to expand.
14898 ///
14899 /// \param Ellipsis Will be set to the location of the ellipsis.
14900 ///
14901 /// \param NumExpansions Will be set to the number of expansions that will
14902 /// be generated from this pack expansion, if known a priori.
14905 SourceLocation &Ellipsis,
14906 UnsignedOrNone &NumExpansions) const;
14907
14908 /// Given a template argument that contains an unexpanded parameter pack, but
14909 /// which has already been substituted, attempt to determine the number of
14910 /// elements that will be produced once this argument is fully-expanded.
14911 ///
14912 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
14913 /// avoid actually expanding the pack where possible.
14915
14916 /// Called when an expression computing the size of a parameter pack
14917 /// is parsed.
14918 ///
14919 /// \code
14920 /// template<typename ...Types> struct count {
14921 /// static const unsigned value = sizeof...(Types);
14922 /// };
14923 /// \endcode
14924 ///
14925 //
14926 /// \param OpLoc The location of the "sizeof" keyword.
14927 /// \param Name The name of the parameter pack whose size will be determined.
14928 /// \param NameLoc The source location of the name of the parameter pack.
14929 /// \param RParenLoc The location of the closing parentheses.
14931 IdentifierInfo &Name,
14932 SourceLocation NameLoc,
14933 SourceLocation RParenLoc);
14934
14935 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
14936 SourceLocation EllipsisLoc,
14937 SourceLocation LSquareLoc, Expr *IndexExpr,
14938 SourceLocation RSquareLoc);
14939
14940 ExprResult BuildPackIndexingExpr(Expr *PackExpression,
14941 SourceLocation EllipsisLoc, Expr *IndexExpr,
14942 SourceLocation RSquareLoc,
14943 ArrayRef<Expr *> ExpandedExprs = {},
14944 bool FullySubstituted = false);
14945
14946 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
14947 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
14948 tok::TokenKind Operator,
14949 SourceLocation EllipsisLoc, Expr *RHS,
14950 SourceLocation RParenLoc);
14951 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
14952 SourceLocation LParenLoc, Expr *LHS,
14953 BinaryOperatorKind Operator,
14954 SourceLocation EllipsisLoc, Expr *RHS,
14955 SourceLocation RParenLoc,
14956 UnsignedOrNone NumExpansions);
14957 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
14958 BinaryOperatorKind Operator);
14959
14960 ///@}
14961
14962 //
14963 //
14964 // -------------------------------------------------------------------------
14965 //
14966 //
14967
14968 /// \name Constraints and Concepts
14969 /// Implementations are in SemaConcept.cpp
14970 ///@{
14971
14972public:
14973 ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI);
14974
14975 ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc,
14976 TypeSourceInfo *TSI);
14977
14978public:
14980 const llvm::FoldingSetNodeID &ID) {
14981 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
14982 SatisfactionStack.emplace_back(Can, ID);
14983 }
14984
14985 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
14986
14988 const llvm::FoldingSetNodeID &ID) const {
14989 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
14990 return llvm::is_contained(SatisfactionStack,
14991 SatisfactionStackEntryTy{Can, ID});
14992 }
14993
14995 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
14996
14997 // Resets the current SatisfactionStack for cases where we are instantiating
14998 // constraints as a 'side effect' of normal instantiation in a way that is not
14999 // indicative of recursive definition.
15002 Sema &SemaRef;
15003
15004 public:
15006 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
15007 }
15008
15010 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
15011 }
15012
15016 };
15017
15020 SatisfactionStack.swap(NewSS);
15021 }
15022
15024 llvm::PointerUnion<const NamedDecl *,
15026
15027 /// Check whether the given expression is a valid constraint expression.
15028 /// A diagnostic is emitted if it is not, false is returned, and
15029 /// PossibleNonPrimary will be set to true if the failure might be due to a
15030 /// non-primary expression being used as an atomic constraint.
15031 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
15032 bool *PossibleNonPrimary = nullptr,
15033 bool IsTrailingRequiresClause = false);
15034
15035 /// \brief Check whether the given list of constraint expressions are
15036 /// satisfied (as if in a 'conjunction') given template arguments.
15037 /// \param Template the template-like entity that triggered the constraints
15038 /// check (either a concept or a constrained entity).
15039 /// \param ConstraintExprs a list of constraint expressions, treated as if
15040 /// they were 'AND'ed together.
15041 /// \param TemplateArgLists the list of template arguments to substitute into
15042 /// the constraint expression.
15043 /// \param TemplateIDRange The source range of the template id that
15044 /// caused the constraints check.
15045 /// \param Satisfaction if true is returned, will contain details of the
15046 /// satisfaction, with enough information to diagnose an unsatisfied
15047 /// expression.
15048 /// \returns true if an error occurred and satisfaction could not be checked,
15049 /// false otherwise.
15052 ArrayRef<AssociatedConstraint> AssociatedConstraints,
15053 const MultiLevelTemplateArgumentList &TemplateArgLists,
15054 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
15055 const ConceptReference *TopLevelConceptId = nullptr,
15056 Expr **ConvertedExpr = nullptr);
15057
15058 /// Check whether the given function decl's trailing requires clause is
15059 /// satisfied, if any. Returns false and updates Satisfaction with the
15060 /// satisfaction verdict if successful, emits a diagnostic and returns true if
15061 /// an error occurred and satisfaction could not be determined.
15062 ///
15063 /// \returns true if an error occurred, false otherwise.
15065 ConstraintSatisfaction &Satisfaction,
15066 SourceLocation UsageLoc = SourceLocation(),
15067 bool ForOverloadResolution = false);
15068
15069 // Calculates whether two constraint expressions are equal irrespective of a
15070 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
15071 // 'New', which are the "source" of the constraint, since this is necessary
15072 // for figuring out the relative 'depth' of the constraint. The depth of the
15073 // 'primary template' and the 'instantiated from' templates aren't necessarily
15074 // the same, such as a case when one is a 'friend' defined in a class.
15076 const Expr *OldConstr,
15078 const Expr *NewConstr);
15079
15080 // Calculates whether the friend function depends on an enclosing template for
15081 // the purposes of [temp.friend] p9.
15083
15084 /// \brief Ensure that the given template arguments satisfy the constraints
15085 /// associated with the given template, emitting a diagnostic if they do not.
15086 ///
15087 /// \param Template The template to which the template arguments are being
15088 /// provided.
15089 ///
15090 /// \param TemplateArgs The converted, canonicalized template arguments.
15091 ///
15092 /// \param TemplateIDRange The source range of the template id that
15093 /// caused the constraints check.
15094 ///
15095 /// \returns true if the constrains are not satisfied or could not be checked
15096 /// for satisfaction, false if the constraints are satisfied.
15099 const MultiLevelTemplateArgumentList &TemplateArgs,
15100 SourceRange TemplateIDRange);
15101
15102 bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
15104 ArrayRef<TemplateArgument> TemplateArgs,
15105 ConstraintSatisfaction &Satisfaction);
15106
15107 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15108 /// unsatisfied.
15109 /// \param First whether this is the first time an unsatisfied constraint is
15110 /// diagnosed for this error.
15112 SourceLocation Loc = {},
15113 bool First = true);
15114
15115 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15116 /// unsatisfied.
15117 void
15119 bool First = true);
15120
15123 ArrayRef<AssociatedConstraint> AssociatedConstraints);
15124
15125 /// \brief Check whether the given declaration's associated constraints are
15126 /// at least as constrained than another declaration's according to the
15127 /// partial ordering of constraints.
15128 ///
15129 /// \param Result If no error occurred, receives the result of true if D1 is
15130 /// at least constrained than D2, and false otherwise.
15131 ///
15132 /// \returns true if an error occurred, false otherwise.
15133 bool IsAtLeastAsConstrained(const NamedDecl *D1,
15135 const NamedDecl *D2,
15137 bool &Result);
15138
15139 /// If D1 was not at least as constrained as D2, but would've been if a pair
15140 /// of atomic constraints involved had been declared in a concept and not
15141 /// repeated in two separate places in code.
15142 /// \returns true if such a diagnostic was emitted, false otherwise.
15146
15147 /// Cache the satisfaction of an atomic constraint.
15148 /// The key is based on the unsubstituted expression and the parameter
15149 /// mapping. This lets us not substituting the mapping more than once,
15150 /// which is (very!) expensive.
15151 /// FIXME: this should be private.
15152 llvm::DenseMap<llvm::FoldingSetNodeID,
15155
15156 /// Cache the instantiation results of template parameter mappings within
15157 /// concepts. Substituting into normalized concepts can be extremely expensive
15158 /// due to the redundancy of template parameters. This cache is intended for
15159 /// use by TemplateInstantiator to avoid redundant semantic checking.
15160 llvm::DenseMap<llvm::FoldingSetNodeID, TemplateArgumentLoc>
15162
15163private:
15164 /// Caches pairs of template-like decls whose associated constraints were
15165 /// checked for subsumption and whether or not the first's constraints did in
15166 /// fact subsume the second's.
15167 llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
15168 SubsumptionCache;
15169 /// Caches the normalized associated constraints of declarations (concepts or
15170 /// constrained declarations). If an error occurred while normalizing the
15171 /// associated constraints of the template or concept, nullptr will be cached
15172 /// here.
15173 llvm::DenseMap<ConstrainedDeclOrNestedRequirement, NormalizedConstraint *>
15174 NormalizationCache;
15175
15176 /// Cache whether the associated constraint of a declaration
15177 /// is satisfied.
15178 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
15179 SatisfactionCache;
15180
15181 // The current stack of constraint satisfactions, so we can exit-early.
15183
15184 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
15185 /// LocalInstantiationScope of the current non-lambda function. For lambdas,
15186 /// use LambdaScopeForCallOperatorInstantiationRAII.
15187 bool
15188 SetupConstraintScope(FunctionDecl *FD,
15189 std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15190 const MultiLevelTemplateArgumentList &MLTAL,
15192
15193 /// Used during constraint checking, sets up the constraint template argument
15194 /// lists, and calls SetupConstraintScope to set up the
15195 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
15196 std::optional<MultiLevelTemplateArgumentList>
15197 SetupConstraintCheckingTemplateArgumentsAndScope(
15198 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15200
15201 ///@}
15202
15203 //
15204 //
15205 // -------------------------------------------------------------------------
15206 //
15207 //
15208
15209 /// \name Types
15210 /// Implementations are in SemaType.cpp
15211 ///@{
15212
15213public:
15214 /// A mapping that describes the nullability we've seen in each header file.
15216
15217 static int getPrintable(int I) { return I; }
15218 static unsigned getPrintable(unsigned I) { return I; }
15219 static bool getPrintable(bool B) { return B; }
15220 static const char *getPrintable(const char *S) { return S; }
15221 static StringRef getPrintable(StringRef S) { return S; }
15222 static const std::string &getPrintable(const std::string &S) { return S; }
15223 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
15224 return II;
15225 }
15227 static QualType getPrintable(QualType T) { return T; }
15228 static SourceRange getPrintable(SourceRange R) { return R; }
15230 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
15232
15233 enum class CompleteTypeKind {
15234 /// Apply the normal rules for complete types. In particular,
15235 /// treat all sizeless types as incomplete.
15237
15238 /// Relax the normal rules for complete types so that they include
15239 /// sizeless built-in types.
15241
15242 // FIXME: Eventually we should flip the default to Normal and opt in
15243 // to AcceptSizeless rather than opt out of it.
15245 };
15246
15248 const DeclSpec *DS = nullptr);
15250 const DeclSpec *DS = nullptr);
15251
15252 /// Build a pointer type.
15253 ///
15254 /// \param T The type to which we'll be building a pointer.
15255 ///
15256 /// \param Loc The location of the entity whose type involves this
15257 /// pointer type or, if there is no such entity, the location of the
15258 /// type that will have pointer type.
15259 ///
15260 /// \param Entity The name of the entity that involves the pointer
15261 /// type, if known.
15262 ///
15263 /// \returns A suitable pointer type, if there are no
15264 /// errors. Otherwise, returns a NULL type.
15266 DeclarationName Entity);
15267
15268 /// Build a reference type.
15269 ///
15270 /// \param T The type to which we'll be building a reference.
15271 ///
15272 /// \param Loc The location of the entity whose type involves this
15273 /// reference type or, if there is no such entity, the location of the
15274 /// type that will have reference type.
15275 ///
15276 /// \param Entity The name of the entity that involves the reference
15277 /// type, if known.
15278 ///
15279 /// \returns A suitable reference type, if there are no
15280 /// errors. Otherwise, returns a NULL type.
15282 DeclarationName Entity);
15283
15284 /// Build an array type.
15285 ///
15286 /// \param T The type of each element in the array.
15287 ///
15288 /// \param ASM C99 array size modifier (e.g., '*', 'static').
15289 ///
15290 /// \param ArraySize Expression describing the size of the array.
15291 ///
15292 /// \param Brackets The range from the opening '[' to the closing ']'.
15293 ///
15294 /// \param Entity The name of the entity that involves the array
15295 /// type, if known.
15296 ///
15297 /// \returns A suitable array type, if there are no errors. Otherwise,
15298 /// returns a NULL type.
15300 unsigned Quals, SourceRange Brackets,
15301 DeclarationName Entity);
15303
15304 /// Build an ext-vector type.
15305 ///
15306 /// Run the required checks for the extended vector type.
15308 SourceLocation AttrLoc);
15309 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
15310 SourceLocation AttrLoc);
15311
15313 Expr *CountExpr,
15314 bool CountInBytes,
15315 bool OrNull);
15316
15317 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
15318 /// expression is uninstantiated. If instantiated it will apply the
15319 /// appropriate address space to the type. This function allows dependent
15320 /// template variables to be used in conjunction with the address_space
15321 /// attribute
15322 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
15323 SourceLocation AttrLoc);
15324
15325 /// Same as above, but constructs the AddressSpace index if not provided.
15327 SourceLocation AttrLoc);
15328
15330
15332
15333 /// Build a function type.
15334 ///
15335 /// This routine checks the function type according to C++ rules and
15336 /// under the assumption that the result type and parameter types have
15337 /// just been instantiated from a template. It therefore duplicates
15338 /// some of the behavior of GetTypeForDeclarator, but in a much
15339 /// simpler form that is only suitable for this narrow use case.
15340 ///
15341 /// \param T The return type of the function.
15342 ///
15343 /// \param ParamTypes The parameter types of the function. This array
15344 /// will be modified to account for adjustments to the types of the
15345 /// function parameters.
15346 ///
15347 /// \param Loc The location of the entity whose type involves this
15348 /// function type or, if there is no such entity, the location of the
15349 /// type that will have function type.
15350 ///
15351 /// \param Entity The name of the entity that involves the function
15352 /// type, if known.
15353 ///
15354 /// \param EPI Extra information about the function type. Usually this will
15355 /// be taken from an existing function with the same prototype.
15356 ///
15357 /// \returns A suitable function type, if there are no errors. The
15358 /// unqualified type will always be a FunctionProtoType.
15359 /// Otherwise, returns a NULL type.
15361 SourceLocation Loc, DeclarationName Entity,
15363
15364 /// Build a member pointer type \c T Class::*.
15365 ///
15366 /// \param T the type to which the member pointer refers.
15367 /// \param Class the class type into which the member pointer points.
15368 /// \param Loc the location where this type begins
15369 /// \param Entity the name of the entity that will have this member pointer
15370 /// type
15371 ///
15372 /// \returns a member pointer type, if successful, or a NULL type if there was
15373 /// an error.
15375 CXXRecordDecl *Cls, SourceLocation Loc,
15376 DeclarationName Entity);
15377
15378 /// Build a block pointer type.
15379 ///
15380 /// \param T The type to which we'll be building a block pointer.
15381 ///
15382 /// \param Loc The source location, used for diagnostics.
15383 ///
15384 /// \param Entity The name of the entity that involves the block pointer
15385 /// type, if known.
15386 ///
15387 /// \returns A suitable block pointer type, if there are no
15388 /// errors. Otherwise, returns a NULL type.
15390 DeclarationName Entity);
15391
15392 /// Build a paren type including \p T.
15395
15396 /// Build a Read-only Pipe type.
15397 ///
15398 /// \param T The type to which we'll be building a Pipe.
15399 ///
15400 /// \param Loc We do not use it for now.
15401 ///
15402 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15403 /// a NULL type.
15405
15406 /// Build a Write-only Pipe type.
15407 ///
15408 /// \param T The type to which we'll be building a Pipe.
15409 ///
15410 /// \param Loc We do not use it for now.
15411 ///
15412 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15413 /// a NULL type.
15415
15416 /// Build a bit-precise integer type.
15417 ///
15418 /// \param IsUnsigned Boolean representing the signedness of the type.
15419 ///
15420 /// \param BitWidth Size of this int type in bits, or an expression
15421 /// representing that.
15422 ///
15423 /// \param Loc Location of the keyword.
15424 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15425
15426 /// GetTypeForDeclarator - Convert the type for the specified
15427 /// declarator to Type instances.
15428 ///
15429 /// The result of this call will never be null, but the associated
15430 /// type may be a null type if there's an unrecoverable error.
15433
15434 /// Package the given type and TSI into a ParsedType.
15437 TypeSourceInfo **TInfo = nullptr);
15438
15440
15441 // Check whether the size of array element of type \p EltTy is a multiple of
15442 // its alignment and return false if it isn't.
15444
15445 void
15446 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15447 SourceLocation FallbackLoc,
15448 SourceLocation ConstQualLoc = SourceLocation(),
15449 SourceLocation VolatileQualLoc = SourceLocation(),
15450 SourceLocation RestrictQualLoc = SourceLocation(),
15451 SourceLocation AtomicQualLoc = SourceLocation(),
15452 SourceLocation UnalignedQualLoc = SourceLocation());
15453
15454 /// Retrieve the keyword associated
15456
15457 /// Adjust the calling convention of a method to be the ABI default if it
15458 /// wasn't specified explicitly. This handles method types formed from
15459 /// function type typedefs and typename template arguments.
15460 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15461 bool IsCtorOrDtor, SourceLocation Loc);
15462
15463 // Check if there is an explicit attribute, but only look through parens.
15464 // The intent is to look for an attribute on the current declarator, but not
15465 // one that came from a typedef.
15467
15468 /// Check whether a nullability type specifier can be added to the given
15469 /// type through some means not written in source (e.g. API notes).
15470 ///
15471 /// \param Type The type to which the nullability specifier will be
15472 /// added. On success, this type will be updated appropriately.
15473 ///
15474 /// \param Nullability The nullability specifier to add.
15475 ///
15476 /// \param DiagLoc The location to use for diagnostics.
15477 ///
15478 /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15479 /// array type (e.g., because it will decay to a pointer).
15480 ///
15481 /// \param OverrideExisting Whether to override an existing, locally-specified
15482 /// nullability specifier rather than complaining about the conflict.
15483 ///
15484 /// \returns true if nullability cannot be applied, false otherwise.
15486 NullabilityKind Nullability,
15487 SourceLocation DiagLoc,
15488 bool AllowArrayTypes,
15489 bool OverrideExisting);
15490
15491 /// Check whether the given variable declaration has a size that fits within
15492 /// the address space it is declared in. This issues a diagnostic if not.
15493 ///
15494 /// \param VD The variable declaration to check the size of.
15495 ///
15496 /// \param AS The address space to check the size of \p VD against.
15497 ///
15498 /// \returns true if the variable's size fits within the address space, false
15499 /// otherwise.
15500 bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS);
15501
15502 /// Get the type of expression E, triggering instantiation to complete the
15503 /// type if necessary -- that is, if the expression refers to a templated
15504 /// static data member of incomplete array type.
15505 ///
15506 /// May still return an incomplete type if instantiation was not possible or
15507 /// if the type is incomplete for a different reason. Use
15508 /// RequireCompleteExprType instead if a diagnostic is expected for an
15509 /// incomplete expression type.
15511
15513
15514 /// Ensure that the type of the given expression is complete.
15515 ///
15516 /// This routine checks whether the expression \p E has a complete type. If
15517 /// the expression refers to an instantiable construct, that instantiation is
15518 /// performed as needed to complete its type. Furthermore
15519 /// Sema::RequireCompleteType is called for the expression's type (or in the
15520 /// case of a reference type, the referred-to type).
15521 ///
15522 /// \param E The expression whose type is required to be complete.
15523 /// \param Kind Selects which completeness rules should be applied.
15524 /// \param Diagnoser The object that will emit a diagnostic if the type is
15525 /// incomplete.
15526 ///
15527 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15528 /// otherwise.
15530 TypeDiagnoser &Diagnoser);
15531 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15532
15533 template <typename... Ts>
15534 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15535 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15537 }
15538
15539 // Returns the underlying type of a decltype with the given expression.
15541
15543 /// If AsUnevaluated is false, E is treated as though it were an evaluated
15544 /// context, such as when building a type for decltype(auto).
15545 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15546
15547 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15548 SourceLocation Loc,
15549 SourceLocation EllipsisLoc);
15550 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15551 SourceLocation Loc, SourceLocation EllipsisLoc,
15552 bool FullySubstituted = false,
15553 ArrayRef<QualType> Expansions = {});
15554
15555 using UTTKind = UnaryTransformType::UTTKind;
15557 SourceLocation Loc);
15563 SourceLocation Loc);
15565 SourceLocation Loc);
15567 SourceLocation Loc);
15568
15570 return BuiltinRemoveReference(BaseType, UTTKind::RemoveCVRef, Loc);
15571 }
15572
15574 SourceLocation Loc);
15576 SourceLocation Loc);
15577
15578 bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15579
15580 /// Ensure that the type T is a literal type.
15581 ///
15582 /// This routine checks whether the type @p T is a literal type. If @p T is an
15583 /// incomplete type, an attempt is made to complete it. If @p T is a literal
15584 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15585 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15586 /// it the type @p T), along with notes explaining why the type is not a
15587 /// literal type, and returns true.
15588 ///
15589 /// @param Loc The location in the source that the non-literal type
15590 /// diagnostic should refer to.
15591 ///
15592 /// @param T The type that this routine is examining for literalness.
15593 ///
15594 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15595 ///
15596 /// @returns @c true if @p T is not a literal type and a diagnostic was
15597 /// emitted, @c false otherwise.
15599 TypeDiagnoser &Diagnoser);
15600 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15601
15602 template <typename... Ts>
15603 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15604 const Ts &...Args) {
15605 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15606 return RequireLiteralType(Loc, T, Diagnoser);
15607 }
15608
15611 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
15612 }
15613
15614 /// Ensure that the type T is a complete type.
15615 ///
15616 /// This routine checks whether the type @p T is complete in any
15617 /// context where a complete type is required. If @p T is a complete
15618 /// type, returns false. If @p T is a class template specialization,
15619 /// this routine then attempts to perform class template
15620 /// instantiation. If instantiation fails, or if @p T is incomplete
15621 /// and cannot be completed, issues the diagnostic @p diag (giving it
15622 /// the type @p T) and returns true.
15623 ///
15624 /// @param Loc The location in the source that the incomplete type
15625 /// diagnostic should refer to.
15626 ///
15627 /// @param T The type that this routine is examining for completeness.
15628 ///
15629 /// @param Kind Selects which completeness rules should be applied.
15630 ///
15631 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15632 /// @c false otherwise.
15634 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15636 CompleteTypeKind Kind, unsigned DiagID);
15637
15639 TypeDiagnoser &Diagnoser) {
15640 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
15641 }
15642 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15643 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
15644 }
15645
15646 template <typename... Ts>
15647 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15648 const Ts &...Args) {
15649 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15650 return RequireCompleteType(Loc, T, Diagnoser);
15651 }
15652
15653 /// Determine whether a declaration is visible to name lookup.
15654 bool isVisible(const NamedDecl *D) {
15655 return D->isUnconditionallyVisible() ||
15656 isAcceptableSlow(D, AcceptableKind::Visible);
15657 }
15658
15659 /// Determine whether a declaration is reachable.
15660 bool isReachable(const NamedDecl *D) {
15661 // All visible declarations are reachable.
15662 return D->isUnconditionallyVisible() ||
15663 isAcceptableSlow(D, AcceptableKind::Reachable);
15664 }
15665
15666 /// Determine whether a declaration is acceptable (visible/reachable).
15668 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15669 }
15670
15671 /// Determine if \p D and \p Suggested have a structurally compatible
15672 /// layout as described in C11 6.2.7/1.
15673 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15674
15675 /// Determine if \p D has a visible definition. If not, suggest a declaration
15676 /// that should be made visible to expose the definition.
15677 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15678 bool OnlyNeedComplete = false);
15680 NamedDecl *Hidden;
15681 return hasVisibleDefinition(const_cast<NamedDecl *>(D), &Hidden);
15682 }
15683 /// Determine if \p D has a definition which allows we redefine it in current
15684 /// TU. \p Suggested is the definition that should be made visible to expose
15685 /// the definition.
15686 bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
15687 bool &Visible);
15689 NamedDecl *Hidden;
15690 return isRedefinitionAllowedFor(const_cast<NamedDecl *>(D), &Hidden,
15691 Visible);
15692 }
15693
15694 /// Determine if \p D has a reachable definition. If not, suggest a
15695 /// declaration that should be made reachable to expose the definition.
15696 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15697 bool OnlyNeedComplete = false);
15699 NamedDecl *Hidden;
15700 return hasReachableDefinition(D, &Hidden);
15701 }
15702
15703 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15704 AcceptableKind Kind,
15705 bool OnlyNeedComplete = false);
15707 NamedDecl *Hidden;
15708 return hasAcceptableDefinition(D, &Hidden, Kind);
15709 }
15710
15711 /// Try to parse the conditional expression attached to an effect attribute
15712 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15713 /// optional on error.
15714 std::optional<FunctionEffectMode>
15715 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15716
15717 void ActOnCleanupAttr(Decl *D, const Attr *A);
15718 void ActOnInitPriorityAttr(Decl *D, const Attr *A);
15719
15720private:
15721 /// The implementation of RequireCompleteType
15722 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15723 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15724
15725 /// Nullability type specifiers.
15726 IdentifierInfo *Ident__Nonnull = nullptr;
15727 IdentifierInfo *Ident__Nullable = nullptr;
15728 IdentifierInfo *Ident__Nullable_result = nullptr;
15729 IdentifierInfo *Ident__Null_unspecified = nullptr;
15730
15731 ///@}
15732
15733 //
15734 //
15735 // -------------------------------------------------------------------------
15736 //
15737 //
15738
15739 /// \name FixIt Helpers
15740 /// Implementations are in SemaFixItUtils.cpp
15741 ///@{
15742
15743public:
15744 /// Get a string to suggest for zero-initialization of a type.
15746 SourceLocation Loc) const;
15747 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15748
15749 ///@}
15750
15751 //
15752 //
15753 // -------------------------------------------------------------------------
15754 //
15755 //
15756
15757 /// \name Function Effects
15758 /// Implementations are in SemaFunctionEffects.cpp
15759 ///@{
15760public:
15763
15766 std::optional<FunctionEffectWithCondition>
15767 Old; // Invalid when 'Kind' is 'Added'.
15768 std::optional<FunctionEffectWithCondition>
15769 New; // Invalid when 'Kind' is 'Removed'.
15770
15771 StringRef effectName() const {
15772 if (Old)
15773 return Old.value().Effect.name();
15774 return New.value().Effect.name();
15775 }
15776
15777 /// Describes the result of effects differing between a base class's virtual
15778 /// method and an overriding method in a subclass.
15779 enum class OverrideResult {
15782 Merge // Merge missing effect from base to derived.
15783 };
15784
15785 /// Return true if adding or removing the effect as part of a type
15786 /// conversion should generate a diagnostic.
15788 const FunctionEffectsRef &SrcFX,
15789 QualType DstType,
15790 const FunctionEffectsRef &DstFX) const;
15791
15792 /// Return true if adding or removing the effect in a redeclaration should
15793 /// generate a diagnostic.
15794 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
15795 const FunctionEffectsRef &OldFX,
15796 const FunctionDecl &NewFunction,
15797 const FunctionEffectsRef &NewFX) const;
15798
15799 /// Return true if adding or removing the effect in a C++ virtual method
15800 /// override should generate a diagnostic.
15802 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
15803 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
15804 };
15805
15806 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
15807 /// Caller should short-circuit by checking for equality first.
15809 const FunctionEffectsRef &New);
15810 };
15811
15812 /// All functions/lambdas/blocks which have bodies and which have a non-empty
15813 /// FunctionEffectsRef to be verified.
15815
15816 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
15817 /// are all null.
15819
15820public:
15821 /// Warn and return true if adding a function effect to a set would create a
15822 /// conflict.
15825 SourceLocation NewAttrLoc);
15826
15827 // Report a failure to merge function effects between declarations due to a
15828 // conflict.
15829 void
15831 SourceLocation NewLoc,
15832 SourceLocation OldLoc);
15833
15834 /// Inline checks from the start of maybeAddDeclWithEffects, to
15835 /// minimize performance impact on code not using effects.
15836 template <class FuncOrBlockDecl>
15837 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
15838 if (Context.hasAnyFunctionEffects())
15839 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
15841 }
15842
15843 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
15844 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15845
15846 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
15847 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15848
15850
15851 ///@}
15852
15853 //
15854 //
15855 // -------------------------------------------------------------------------
15856 //
15857 //
15858
15859 /// \name Expansion Statements
15860 /// Implementations are in SemaExpand.cpp
15861 ///@{
15862public:
15863 CXXExpansionStmtDecl *ActOnCXXExpansionStmtDecl(unsigned TemplateDepth,
15864 SourceLocation TemplateKWLoc);
15865
15869
15871 SourceLocation LBraceLoc,
15872 SourceLocation RBraceLoc);
15873
15875 CXXExpansionStmtDecl *ESD, Stmt *Init, Stmt *ExpansionVarStmt,
15876 Expr *ExpansionInitializer, SourceLocation LParenLoc,
15877 SourceLocation ColonLoc, SourceLocation RParenLoc,
15878 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps);
15879
15880 StmtResult FinishCXXExpansionStmt(Stmt *Expansion, Stmt *Body);
15881
15883 Stmt *ExpansionVar,
15884 SourceLocation LParenLoc,
15885 SourceLocation ColonLoc,
15886 SourceLocation RParenLoc);
15887
15889 CXXExpansionStmtDecl *ESD, Stmt *Init, DeclStmt *ExpansionVarStmt,
15890 Expr *ExpansionInitializer, SourceLocation LParenLoc,
15891 SourceLocation ColonLoc, SourceLocation RParenLoc,
15892 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
15893
15894 ExprResult BuildCXXExpansionSelectExpr(InitListExpr *Range, Expr *Idx);
15895
15896 std::optional<uint64_t>
15897 ComputeExpansionSize(CXXExpansionStmtPattern *Expansion);
15898 ///@}
15899};
15900
15904
15905/// Contains a late templated function.
15906/// Will be parsed at the end of the translation unit, used by Sema & Parser.
15909 /// The template function declaration to be late parsed.
15911 /// Floating-point options in the point of definition.
15913};
15914
15915template <>
15917 PragmaMsStackAction Action,
15918 llvm::StringRef StackSlotLabel,
15920
15921} // end namespace clang
15922
15923#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 enumerations for traits support.
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.
Token Tok
The Token.
FormatToken * Previous
The previous token in the unwrapped line.
static const Decl * getCanonicalDecl(const Decl *D)
Result
Implement __builtin_bit_cast and related operations.
#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.
llvm::json::Object Object
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:50
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
This file declares semantic analysis functions specific to RISC-V.
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.
TypePropertyCache< Private > Cache
Definition Type.cpp:4922
C Language Family Type Representation.
Represents a member of a struct/union/class.
Definition Decl.h:3204
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:35
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
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:427
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:2727
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3821
Attr - This represents one attribute.
Definition Attr.h:46
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3517
A binding in a decomposition declaration.
Definition DeclCXX.h:4206
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4716
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:2633
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2968
Represents a C++ base or member initializer.
Definition DeclCXX.h:2398
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2629
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
Represents a C++26 expansion statement declaration.
CXXExpansionStmtPattern - Represents an unexpanded C++ expansion statement.
Definition StmtCXX.h:675
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:2145
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
Represents the this expression in C++.
Definition ExprCXX.h:1157
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:70
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition Decl.h:4988
CaseStmt - Represent a case statement.
Definition Stmt.h:1929
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3682
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:3698
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:1399
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1640
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:871
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
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:2001
A decomposition declaration.
Definition DeclCXX.h:4270
Captures a template argument whose value has been deduced via c++ template argument deduction.
Definition Template.h:339
A dependently-generated diagnostic.
Designation - Represent a full designation, which is a sequence of designators.
Definition Designator.h:221
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3467
Represents an enum.
Definition Decl.h:4055
Store information needed for an explicit specifier.
Definition DeclCXX.h:1944
The return type of classify().
Definition Expr.h:339
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:808
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
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:3204
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:260
FileNullability & operator[](FileID file)
Definition Sema.h:271
FileNullability Nullability
Definition Sema.h:267
Represents a function declaration or definition.
Definition Decl.h:2029
A mutable set of FunctionEffect::Kind.
Definition TypeBase.h:5260
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5374
Kind
Identifies the particular effect.
Definition TypeBase.h:5022
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5206
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4840
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5406
Declaration of a template function.
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4628
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4602
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:622
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3511
Describes an C or C++ initializer list.
Definition Expr.h:5314
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:377
Represents the results of name lookup.
Definition Lookup.h:147
A global _GUID constant.
Definition DeclCXX.h:4424
An instance of this class represents the declaration of a property member.
Definition DeclCXX.h:4370
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:4919
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3752
Abstract interface for a module loader.
Describes a module or submodule.
Definition Module.h:340
bool isModulePartitionImplementation() const
Is this a module partition implementation unit.
Definition Module.h:877
Module(ModuleConstructorTag, StringRef Name, SourceLocation DefinitionLoc, Module *Parent, bool IsFramework, bool IsExplicit, unsigned VisibilityID)
Construct a new module or submodule.
Definition Module.cpp:36
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:882
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:8107
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:1160
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
static constexpr unsigned IdxBitWidth
Definition Attr.h:281
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2188
Represents a parameter to a function.
Definition Decl.h:1819
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:294
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:330
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:2697
A (possibly-)qualified type.
Definition TypeBase.h:938
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
Represents a struct/union/class.
Definition Decl.h:4369
Represents the body of a requires-expression.
Definition DeclCXX.h:2114
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:1881
bool operator==(const AlignPackInfo &Info) const
Definition Sema.h:1941
static AlignPackInfo getFromRawEncoding(unsigned Encoding)
Definition Sema.h:1913
unsigned getPackNumber() const
Definition Sema.h:1931
bool IsXLStack() const
Definition Sema.h:1939
bool IsPackSet() const
Definition Sema.h:1933
AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
Definition Sema.h:1887
bool IsAlignAttr() const
Definition Sema.h:1927
bool IsPackAttr() const
Definition Sema.h:1925
bool operator!=(const AlignPackInfo &Info) const
Definition Sema.h:1947
AlignPackInfo(bool IsXL)
Definition Sema.h:1891
static uint32_t getRawEncoding(const AlignPackInfo &Info)
Definition Sema.h:1898
Mode getAlignMode() const
Definition Sema.h:1929
ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
Definition Sema.h:13810
ArgPackSubstIndexRAII & operator=(const ArgPackSubstIndexRAII &)=delete
ArgPackSubstIndexRAII(const ArgPackSubstIndexRAII &)=delete
BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
Definition Sema.h:8372
void diagnose(Sema &S, SourceLocation Loc, QualType T) override
Definition Sema.h:8377
void emit(const SemaDiagnosticBuilder &DB, std::index_sequence< Is... >) const
Definition Sema.h:8364
std::tuple< const Ts &... > Args
Definition Sema.h:8361
CXXThisScopeRAII(const CXXThisScopeRAII &)=delete
CXXThisScopeRAII & operator=(const CXXThisScopeRAII &)=delete
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 & operator=(const CompoundScopeRAII &)=delete
CompoundScopeRAII(Sema &S, bool IsStmtExpr=false)
Definition Sema.h:1321
CompoundScopeRAII(const CompoundScopeRAII &)=delete
std::pair< VarDecl *, Expr * > get() const
Definition Sema.h:7911
std::optional< bool > getKnownValue() const
Definition Sema.h:7915
A RAII object to temporarily push a declaration context.
Definition Sema.h:3538
ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext=true)
Definition Sema.h:3548
ContextRAII & operator=(const ContextRAII &)=delete
ContextRAII(const ContextRAII &)=delete
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10418
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:10423
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:6487
DefaultedFunctionKind(CXXSpecialMemberKind CSM)
Definition Sema.h:6464
unsigned getDiagnosticIndex() const
Get the index of this function kind for use in diagnostics.
Definition Sema.h:6492
DefaultedFunctionKind(DefaultedComparisonKind Comp)
Definition Sema.h:6467
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6484
DeferDiagsRAII(Sema &S, bool DeferDiags)
Definition Sema.h:10146
DeferDiagsRAII & operator=(const DeferDiagsRAII &)=delete
DeferDiagsRAII(const DeferDiagsRAII &)=delete
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1390
DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool)
Enter a new scope.
Definition Sema.h:1409
void popUndelayed(DelayedDiagnosticsState state)
Undo a previous pushUndelayed().
Definition Sema.h:1433
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1402
sema::DelayedDiagnosticPool * getCurrentPool() const
Returns the current delayed-diagnostics pool.
Definition Sema.h:1405
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:1419
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1425
A helper class for building up ExtParameterInfos.
Definition Sema.h:13174
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:13193
void set(unsigned index, FunctionProtoType::ExtParameterInfo info)
Set the ExtParameterInfo for the parameter at the given index,.
Definition Sema.h:13181
FPFeaturesStateRAII(const FPFeaturesStateRAII &)=delete
FPOptionsOverride getOverrides()
Definition Sema.h:14201
FPFeaturesStateRAII & operator=(const FPFeaturesStateRAII &)=delete
FpPragmaStackSaveRAII(const FpPragmaStackSaveRAII &)=delete
FpPragmaStackSaveRAII & operator=(const FpPragmaStackSaveRAII &)=delete
FullExprArg(Sema &actions)
Definition Sema.h:7855
ExprResult release()
Definition Sema.h:7857
friend class Sema
Definition Sema.h:7866
Expr * get() const
Definition Sema.h:7859
GlobalEagerInstantiationScope(const GlobalEagerInstantiationScope &)=delete
GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
Definition Sema.h:14213
GlobalEagerInstantiationScope & operator=(const GlobalEagerInstantiationScope &)=delete
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:10482
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:10474
unsigned size() const
The number of exceptions in the exception specification.
Definition Sema.h:5586
ExceptionSpecificationType getExceptionSpecType() const
Get the computed exception specification type.
Definition Sema.h:5579
const QualType * data() const
The set of exceptions in the exception specification.
Definition Sema.h:5589
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:5595
FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const
Overwrite an EPI's exception specification with this computed exception specification.
Definition Sema.h:5602
LambdaScopeForCallOperatorInstantiationRAII(Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope=true)
LocalEagerInstantiationScope & operator=(const LocalEagerInstantiationScope &)=delete
LocalEagerInstantiationScope(Sema &S, bool AtEndOfTU)
Definition Sema.h:14164
LocalEagerInstantiationScope(const LocalEagerInstantiationScope &)=delete
static NameClassification DependentNonType()
Definition Sema.h:3764
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3774
ExprResult getExpression() const
Definition Sema.h:3800
NameClassification(const IdentifierInfo *Keyword)
Definition Sema.h:3737
static NameClassification Unknown()
Definition Sema.h:3744
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3748
NameClassificationKind getKind() const
Definition Sema.h:3798
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3792
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3780
NamedDecl * getNonTypeDecl() const
Definition Sema.h:3810
NameClassification(ParsedType Type)
Definition Sema.h:3734
TemplateName getTemplateName() const
Definition Sema.h:3815
ParsedType getType() const
Definition Sema.h:3805
TemplateNameKind getTemplateNameKind() const
Definition Sema.h:3824
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3754
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3786
static NameClassification UndeclaredNonType()
Definition Sema.h:3760
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3768
static NameClassification Error()
Definition Sema.h:3740
void operator()(sema::FunctionScopeInfo *Scope) const
Definition Sema.cpp:2615
PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct)
Definition SemaAttr.cpp:29
PragmaStackSentinelRAII(const PragmaStackSentinelRAII &)=delete
PragmaStackSentinelRAII & operator=(const PragmaStackSentinelRAII &)=delete
RequiredTemplateKind(TemplateNameIsRequiredTag)
Template name is unconditionally required.
Definition Sema.h:11554
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11556
RequiredTemplateKind(SourceLocation TemplateKWLoc=SourceLocation())
Template name is required if TemplateKWLoc is valid.
Definition Sema.h:11551
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12607
SFINAETrap & operator=(const SFINAETrap &)=delete
SFINAETrap(const SFINAETrap &)=delete
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12641
SFINAETrap(Sema &S, bool WithAccessChecking=false)
Definition Sema.h:12623
bool withAccessChecking() const
Definition Sema.h:12644
sema::TemplateDeductionInfo * getDeductionInfo() const
Definition Sema.h:12636
SFINAETrap(Sema &S, sema::TemplateDeductionInfo &Info)
Definition Sema.h:12626
SatisfactionStackResetRAII(const SatisfactionStackResetRAII &)=delete
SatisfactionStackResetRAII & operator=(const SatisfactionStackResetRAII &)=delete
ScopedCodeSynthesisContext(Sema &S, const CodeSynthesisContext &Ctx)
Definition Sema.h:13737
ScopedCodeSynthesisContext & operator=(const ScopedCodeSynthesisContext &)=delete
ScopedCodeSynthesisContext(const ScopedCodeSynthesisContext &)=delete
A derivative of BoundTypeDiagnoser for which the diagnostic's type parameter is preceded by a 0/1 enu...
Definition Sema.h:8389
void diagnose(Sema &S, SourceLocation Loc, QualType T) override
Definition Sema.h:8394
SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
Definition Sema.h:8391
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
Definition Sema.h:9407
SpecialMemberOverloadResult(CXXMethodDecl *MD)
Definition Sema.h:9394
CXXMethodDecl * getMethod() const
Definition Sema.h:9397
void setMethod(CXXMethodDecl *MD)
Definition Sema.h:9398
void addContextNote(SourceLocation UseLoc)
Definition Sema.h:13703
SynthesizedFunctionScope(const SynthesizedFunctionScope &)=delete
SynthesizedFunctionScope(Sema &S, DeclContext *DC)
Definition Sema.h:13691
SynthesizedFunctionScope & operator=(const SynthesizedFunctionScope &)=delete
SourceLocation getLocation() const
Definition Sema.h:12365
bool ContainsDecl(const NamedDecl *ND) const
Definition Sema.h:12355
const DeclContext * getDeclContext() const
Definition Sema.h:12361
TemplateCompareNewDeclInfo(const DeclContext *DeclCtx, const DeclContext *LexicalDeclCtx, SourceLocation Loc)
Definition Sema.h:12339
const NamedDecl * getDecl() const
Definition Sema.h:12353
TemplateCompareNewDeclInfo(const NamedDecl *ND)
Definition Sema.h:12338
const DeclContext * getLexicalDeclContext() const
Definition Sema.h:12357
TentativeAnalysisScope(Sema &SemaRef)
Definition Sema.h:12658
TentativeAnalysisScope & operator=(const TentativeAnalysisScope &)=delete
TentativeAnalysisScope(const TentativeAnalysisScope &)=delete
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
VerifyICEDiagnoser(bool Suppress=false)
Definition Sema.h:7814
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:869
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)
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:1452
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:3642
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:13768
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:8294
bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs (unless they are value dependent ...
Definition SemaAttr.cpp:546
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13752
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:11072
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13203
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2688
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1143
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:1595
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:14149
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
void PopParsingClass(ParsingClassState state)
Definition Sema.h:6655
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:10159
void LoadExternalWeakUndeclaredIdentifiers()
Load weak undeclared identifiers from the external source.
Definition Sema.cpp:1103
bool containsUnexpandedParameterPacks(Declarator &D)
Determine whether the given declarator contains any unexpanded parameter packs.
std::optional< QualType > BuiltinVectorMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
std::optional< uint64_t > ComputeExpansionSize(CXXExpansionStmtPattern *Expansion)
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:6644
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)
void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc, Scope *curScope)
ActonPragmaExport - called on well-formed '#pragma export'.
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:8344
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:8262
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:971
bool isAttrContext() const
Definition Sema.h:7051
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 BuildBoolLiteral(SourceLocation Loc, bool Value)
Build a boolean-typed literal expression.
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:8337
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition Sema.cpp:2788
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6406
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9423
@ LookupLabel
Label name lookup.
Definition Sema.h:9432
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9427
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9454
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9446
@ LookupOMPReductionName
Look up the name of an OpenMP user-defined reduction operation.
Definition Sema.h:9468
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9462
@ LookupObjCProtocolName
Look up the name of an Objective-C protocol.
Definition Sema.h:9464
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9459
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9439
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9466
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9450
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9435
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition Sema.h:9442
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9430
@ LookupOMPMapperName
Look up the name of an OpenMP user-defined mapper.
Definition Sema.h:9470
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9472
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:417
llvm::DenseMap< IdentifierInfo *, SrcLocSet > IdentifierSourceLocations
Definition Sema.h:9373
LazyVector< TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2 > ExtVectorDeclsType
Definition Sema.h:4967
UnaryTransformType::UTTKind UTTKind
Definition Sema.h:15555
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.
ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx, SourceLocation RBLoc)
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:671
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:6343
SemaM68k & M68k()
Definition Sema.h:1502
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:13822
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:1385
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)
void deduceOpenCLAddressSpace(VarDecl *decl)
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:2149
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:9863
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:4912
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:5141
OpaquePtr< QualType > TypeTy
Definition Sema.h:1303
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:170
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:370
void PrintContextStack()
Definition Sema.h:13831
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:657
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
SemaOpenMP & OpenMP()
Definition Sema.h:1537
void CheckDelegatingCtorCycles()
llvm::SmallSet< SourceLocation, 2 > SrcLocSet
Definition Sema.h:9372
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:2324
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6381
bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is visible.
Definition Sema.h:9739
bool FormatStringHasSArg(const StringLiteral *FExpr)
StmtResult BuildCXXForRangeRangeVar(Scope *S, Expr *Range, QualType Type, bool IsConstexpr=false)
Build the range variable of a range-based for loop or iterating expansion statement and return its De...
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:1373
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.
llvm::DenseMap< const EnumDecl *, llvm::SmallVector< llvm::APSInt > > AssignEnumCache
A cache of enumerator values for enums checked by -Wassign-enum.
Definition Sema.h:3593
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:15223
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:1264
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:4814
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1853
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:15679
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, const IdentifierInfo *IIEnvironment, const IdentifierInfo *InferredPlatformII=nullptr)
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:6617
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:5240
void emitAndClearUnusedLocalTypedefWarnings()
Definition Sema.cpp:1216
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:6598
void ActOnForEachDeclStmt(DeclGroupPtrTy Decl)
Definition SemaStmt.cpp:86
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:1253
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:1477
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:376
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:7931
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7933
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7932
void LateTemplateParserCB(void *P, LateParsedTemplate &LPT)
Callback to the parser to parse templated functions when needed.
Definition Sema.h:1354
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:15638
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
static SourceRange getPrintable(SourceLocation L)
Definition Sema.h:15229
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)
bool needsRebuildOfDefaultArgOrInit() const
Definition Sema.h:8282
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:9977
@ Interface
'export module X;'
Definition Sema.h:9974
@ Implementation
'module X;'
Definition Sema.h:9975
@ PartitionInterface
'export module X:Y;'
Definition Sema.h:9976
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition Sema.h:8424
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1246
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:9686
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition Sema.h:10501
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10504
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10510
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10508
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:lifetime_capture_by(this)]] to STL container methods.
Definition SemaAttr.cpp:318
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:1811
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
@ AR_dependent
Definition Sema.h:1696
@ AR_accessible
Definition Sema.h:1694
@ AR_inaccessible
Definition Sema.h:1695
@ AR_delayed
Definition Sema.h:1697
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:15236
@ AcceptSizeless
Relax the normal rules for complete types so that they include sizeless built-in types.
Definition Sema.h:15240
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:686
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:940
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7029
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2460
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,...
ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc)
Definition SemaCast.cpp:439
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:8413
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl)
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2084
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:8325
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr)
static SourceRange getPrintable(const Expr *E)
Definition Sema.h:15230
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2078
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:15818
void setFunctionHasBranchIntoScope()
Definition Sema.cpp:2641
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:4972
ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val)
Definition SemaStmt.cpp:486
SourceLocation getOptimizeOffPragmaLocation() const
Get the location for the currently active "\#pragma clang optimizeoff". If this location is invalid,...
Definition Sema.h:2158
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:6858
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:663
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.
StmtResult BuildNonEnumeratingCXXExpansionStmtPattern(CXXExpansionStmtDecl *ESD, Stmt *Init, DeclStmt *ExpansionVarStmt, Expr *ExpansionInitializer, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation RParenLoc, ArrayRef< MaterializeTemporaryExpr * > LifetimeExtendTemps={})
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
SmallVector< AlignPackIncludeState, 8 > AlignPackIncludeStack
Definition Sema.h:2073
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:11274
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:2740
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:4215
@ Default
= default ;
Definition Sema.h:4217
@ Delete
deleted-function-body
Definition Sema.h:4223
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)
bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T, SourceLocation CC)
Check for overflow behavior type related implicit conversion diagnostics.
llvm::function_ref< void(llvm::raw_ostream &)> EntityPrinter
Definition Sema.h:14111
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue=true)
Definition SemaStmt.cpp:49
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.
bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS)
Check whether the given variable declaration has a size that fits within the address space it is decl...
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:1297
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:2085
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:1492
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:888
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...
PersonalityAttr * mergePersonalityAttr(Decl *D, FunctionDecl *Routine, const AttributeCommonInfo &CI)
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:15154
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
void ActOnTranslationUnitScope(Scope *S)
Scope actions.
Definition Sema.cpp:173
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD, bool Diagnose, bool LookForGlobal, DeclarationName Name)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt)
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)
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, const Designation &Desig, SourceLocation RParenLoc)
SemaSYCL & SYCL()
Definition Sema.h:1562
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:3015
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:7041
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:1758
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:706
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:842
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
LateParsedTemplateMapT LateParsedTemplateMap
Definition Sema.h:11519
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:12118
@ CTAK_DeducedFromArrayBound
The template argument was deduced from an array bound via template argument deduction.
Definition Sema.h:12129
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12121
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12125
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:689
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:760
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:9367
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:
AvailabilityAttr * mergeAndInferAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, const IdentifierInfo *IIEnvironment, const IdentifierInfo *InferredPlatformII)
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
SemaX86 & X86()
Definition Sema.h:1582
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.
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:13772
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:1310
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:8249
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:702
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:9378
FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC)
Definition Sema.h:7876
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:227
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:976
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.
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2366
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:938
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:4441
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:15603
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
bool CheckCaseExpression(Expr *E)
void resetFPOptions(FPOptions FPO)
Definition Sema.h:11500
bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind)
Definition Sema.h:15706
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool FailOnPackProducingTemplates, bool &ShouldExpand, bool &RetainExpansion, UnsignedOrNone &NumExpansions, bool Diagnose=true)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
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:9960
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:15219
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1522
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1377
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:2970
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:1447
void CheckDelayedMemberExceptionSpecs()
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:81
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:940
ClassTemplateDecl * StdCoroutineTraitsCache
The C++ "std::coroutine_traits" template, which is defined in <coroutine_traits>
Definition Sema.h:3211
bool captureSwiftVersionIndependentAPINotes()
Whether APINotes should be gathered for all applicable Swift language versions, without being applied...
Definition Sema.h:1677
void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Name, bool InInstantiation=false)
AddModeAttr - Adds a mode attribute to a particular declaration.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2081
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void PrintInstantiationStack()
Definition Sema.h:13835
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:3632
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:763
bool isImmediateFunctionContext() const
Definition Sema.h:8274
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:941
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1083
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:677
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:773
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:6624
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)
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD)
ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool)
Definition Sema.h:1439
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:6708
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:2077
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:778
void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc)
ActOnPragmaOptionsAlign - Called on well formed #pragma options align.
Definition SemaAttr.cpp:377
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:892
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.
void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded unary operator.
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:713
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2645
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:6651
@ FRS_Success
Definition Sema.h:10889
@ FRS_DiagnosticIssued
Definition Sema.h:10891
@ FRS_NoViableFunction
Definition Sema.h:10890
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:14284
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:991
void mergeVisibilityType(Decl *D, SourceLocation Loc, VisibilityAttr::VisibilityType Type)
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9420
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:9370
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:6176
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
Definition Sema.h:6190
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
Definition Sema.h:6187
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
Definition Sema.h:6184
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6178
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
Definition Sema.h:6181
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:9109
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:15814
@ Conversions
Allow explicit conversion functions but not explicit constructors.
Definition Sema.h:10210
@ All
Allow both explicit conversion functions and explicit constructors.
Definition Sema.h:10212
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:1236
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition Sema.h:6639
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)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, const Designation &Desig, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
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:1214
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:15023
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:679
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition Sema.h:3655
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:1763
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:2731
unsigned InventedParameterInfosStart
The index of the first InventedParameterInfo that refers to the current context.
Definition Sema.h:3535
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 CheckAttributesOnDeducedType(Decl *D)
CheckAttributesOnDeducedType - Calls Sema functions for attributes that requires the type to be deduc...
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)
void setFunctionHasIndirectGoto()
Definition Sema.cpp:2651
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:12297
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12315
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12305
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12325
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:4963
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:1777
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:8455
void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName)
ActOnPragmaClangSection - Called on well formed #pragma clang section.
Definition SemaAttr.cpp:432
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:11569
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11576
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11573
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:838
StmtResult ActOnCXXExpansionStmtPattern(CXXExpansionStmtDecl *ESD, Stmt *Init, Stmt *ExpansionVarStmt, Expr *ExpansionInitializer, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation RParenLoc, ArrayRef< MaterializeTemporaryExpr * > LifetimeExtendTemps)
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:2752
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2479
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:427
SourceRange getExprRange(Expr *E) const
Definition SemaExpr.cpp:514
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:11505
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:170
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:3628
std::optional< ExpressionEvaluationContextRecord::InitializationContext > OutermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8309
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:15226
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition Sema.h:4652
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:1593
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:406
FPOptions & getCurFPFeatures()
Definition Sema.h:936
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8407
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:277
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:84
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2497
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:2630
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:15647
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:14544
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition Sema.h:14564
@ UPPC_RequiresClause
Definition Sema.h:14615
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14570
@ UPPC_IfExists
Microsoft __if_exists.
Definition Sema.h:14597
@ UPPC_Requirement
Definition Sema.h:14612
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14588
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14567
@ UPPC_Lambda
Lambda expression.
Definition Sema.h:14603
@ UPPC_IfNotExists
Microsoft __if_not_exists.
Definition Sema.h:14600
@ UPPC_PartialSpecialization
Partial specialization.
Definition Sema.h:14594
@ UPPC_Initializer
An initializer.
Definition Sema.h:14579
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14549
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14573
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14582
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14552
@ UPPC_Expression
An arbitrary expression.
Definition Sema.h:14546
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14591
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14576
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14555
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14561
@ UPPC_Block
Block expression.
Definition Sema.h:14606
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14558
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14585
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14609
api_notes::APINotesManager APINotes
Definition Sema.h:1314
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:12677
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:934
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:13217
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:5955
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2591
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:2120
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:767
SemaCodeCompletion & CodeCompletion()
Definition Sema.h:1472
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:238
ModularFormatAttr * mergeModularFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *ModularImplFn, StringRef ImplName, MutableArrayRef< StringRef > Aspects)
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition Sema.h:3649
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:1527
void SwapSatisfactionStack(llvm::SmallVectorImpl< SatisfactionStackEntryTy > &NewSS)
Definition Sema.h:15018
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:7120
@ ReuseLambdaContextDecl
Definition Sema.h:7120
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:942
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:1467
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:1356
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false)
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:1309
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:2167
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool SubstTemplateArgumentsInParameterMapping(ArrayRef< TemplateArgumentLoc > Args, SourceLocation BaseLoc, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Out)
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:1351
SmallVector< PragmaAttributeGroup, 2 > PragmaAttributeStack
Definition Sema.h:2145
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor, bool IsCopy=false)
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:2269
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:3636
SemaDirectX & DirectX()
Definition Sema.h:1482
llvm::SmallSetVector< const NamedDecl *, 16 > NamedDeclSetType
Definition Sema.h:6600
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:1512
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:1594
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:1308
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,...
std::unique_ptr< sema::FunctionScopeInfo > CachedFunctionScope
Definition Sema.h:1242
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2706
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:1237
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
llvm::DenseMap< unsigned, CXXDeductionGuideDecl * > AggregateDeductionCandidates
Definition Sema.h:9112
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:961
void ActOnStartOfCompoundStmt(bool IsStmtExpr)
Definition SemaStmt.cpp:417
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15660
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:6602
SemaHLSL & HLSL()
Definition Sema.h:1487
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:11518
bool CollectStats
Flag indicating whether or not to collect detailed statistics.
Definition Sema.h:1240
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9419
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:1237
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:7035
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:1854
void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1507
IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName, unsigned Index)
Invent a new identifier for parameters of abbreviated templates.
Definition Sema.cpp:140
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:1552
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:15837
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition Sema.h:1843
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:5961
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....
ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr)
Prepare SplattedExpr for a matrix splat operation, adding implicit casts if necessary.
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:216
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:5335
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
Definition Sema.h:5338
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5342
MemberPointerConversionDirection
Definition Sema.h:10342
SmallVector< PendingImplicitInstantiation, 1 > LateParsedInstantiations
Queue of implicit template instantiations that cannot be performed eagerly.
Definition Sema.h:14147
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6595
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc, TypeSourceInfo *TSI)
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:78
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:2818
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:15221
SemaSwift & Swift()
Definition Sema.h:1567
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:2066
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:6700
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7065
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6632
StmtResult ActOnExprStmtError()
Definition SemaStmt.cpp:66
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2076
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.
StmtResult BuildCXXEnumeratingExpansionStmtPattern(Decl *ESD, Stmt *Init, Stmt *ExpansionVar, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation RParenLoc)
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
void completeExprArrayBound(Expr *E)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1147
std::function< TypeResult(StringRef, StringRef, SourceLocation)> ParseTypeFromStringCallback
Callback to the parser to parse a type expressed as a string.
Definition Sema.h:1365
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:2123
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:1770
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:912
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro=false)
Definition SemaStmt.cpp:71
OpenCLOptions OpenCLFeatures
Definition Sema.h:1305
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:11923
ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand, UnresolvedLookupExpr *Lookup)
SmallVector< std::deque< PendingImplicitInstantiation >, 8 > SavedPendingInstantiations
Definition Sema.h:14151
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:2170
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:885
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:4829
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:10529
FileNullabilityMap NullabilityMap
A mapping that describes the nullability we've seen in each header file.
Definition Sema.h:15215
ProcessingContextState ParsingClassState
Definition Sema.h:6650
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:1345
NamedDecl * lookupExternCFunctionOrVariable(IdentifierInfo *IdentId, SourceLocation NameLoc, Scope *curScope)
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:2625
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 ActOnCXXExpansionInitList(MultiExprArg SubExprs, SourceLocation LBraceLoc, SourceLocation RBraceLoc)
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:3059
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:3901
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition Sema.h:2725
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:15569
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
llvm::DenseMap< llvm::FoldingSetNodeID, TemplateArgumentLoc > * CurrentCachedTemplateArgs
Cache the instantiation results of template parameter mappings within concepts.
Definition Sema.h:15161
bool CheckNontrivialField(FieldDecl *FD)
void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList)
Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr attribute.
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
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:7062
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...
bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypeConversion - Determines whether the conversion from FromType to ToType necessar...
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope)
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
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)
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:2443
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:11918
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:13215
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:4923
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:5951
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:647
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:15654
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition Sema.h:8278
llvm::MapVector< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3615
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2119
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9955
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:2580
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...
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:8145
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:2661
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:7077
void ApplyForRangeOrExpansionStatementLifetimeExtension(VarDecl *RangeVar, ArrayRef< MaterializeTemporaryExpr * > Temporaries)
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:6609
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:1450
auto getDefaultDiagFunc()
Definition Sema.h:2326
void ActOnInitPriorityAttr(Decl *D, const Attr *A)
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.
bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypePromotion - Determines whether the conversion from FromType to ToType involves ...
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:315
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:12678
ClassTemplateDecl * StdTypeIdentity
The C++ "std::type_identity" template, which is defined in <type_traits>.
Definition Sema.h:6628
SemaOpenCL & OpenCL()
Definition Sema.h:1532
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:14160
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:659
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool isPreciseFPEnabled()
Are precise floating point semantics currently enabled?
Definition Sema.h:2250
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:931
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:15231
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...
void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope)
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:2655
@ FAPK_Elsewhere
Definition Sema.h:2659
@ FAPK_Fixed
Definition Sema.h:2656
@ FAPK_Variadic
Definition Sema.h:2657
@ FAPK_VAList
Definition Sema.h:2658
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:8270
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
llvm::DenseMap< ParmVarDecl *, llvm::TinyPtrVector< ParmVarDecl * > > UnparsedDefaultArgInstantiationsMap
Definition Sema.h:13206
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1737
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)
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:15667
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:14994
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:8466
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:3646
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition Sema.h:6861
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index, QualType ParamType, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
bool MSStructPragmaOn
Definition Sema.h:1840
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:13783
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:14095
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID)
Definition Sema.h:15642
SourceManager & getSourceManager() const
Definition Sema.h:939
void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
QualType BuiltinAddReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
void ActOnCleanupAttr(Decl *D, const Attr *A)
QualType CXXThisTypeOverride
When non-NULL, the C++ 'this' expression is allowed despite the current context not being a non-stati...
Definition Sema.h:8537
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:4901
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:652
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_enum attribute.
Definition Sema.h:3589
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:988
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:718
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:12397
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:2338
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:9413
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:593
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:14100
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,...
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:6071
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.
CXXExpansionStmtDecl * ActOnCXXExpansionStmtDecl(unsigned TemplateDepth, SourceLocation TemplateKWLoc)
bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc)
PragmaClangSection PragmaClangTextSection
Definition Sema.h:1855
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:7574
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.
NonTrivialCUnionKind
Definition Sema.h:4154
@ NTCUK_Destruct
Definition Sema.h:4156
@ NTCUK_Init
Definition Sema.h:4155
@ NTCUK_Copy
Definition Sema.h:4157
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
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:1386
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:8423
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1852
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:9208
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...
CXXExpansionStmtDecl * BuildCXXExpansionStmtDecl(DeclContext *Ctx, SourceLocation TemplateKWLoc, NonTypeTemplateParmDecl *NTTP)
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:2491
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:2065
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:6859
void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro, SourceLocation MutableLoc)
ExternalSemaSource * getExternalSource() const
Definition Sema.h:944
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:1250
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
Definition Sema.h:2126
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
bool isSFINAEContext() const
Definition Sema.h:13843
FunctionDecl * BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl, QualType AllocType, SourceLocation)
QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs=true)
Definition Sema.h:8893
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...
static SourceRange getPrintable(SourceRange R)
Definition Sema.h:15228
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:13799
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:14979
ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI)
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:15609
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, const PartialDiagnostic &PD, const FunctionDecl *FD=nullptr)
Definition Sema.h:1153
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:3021
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)
void ProcessPragmaExport(DeclaratorDecl *newDecl)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void emitDeferredDiags()
Definition Sema.cpp:2134
void setFunctionHasMustTail()
Definition Sema.cpp:2656
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...
LabelDecl * LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc=SourceLocation(), bool IsLabelStmt=false)
LookupOrCreateLabel - Do a name lookup of a label with the specified name.
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:8462
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:14985
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:2646
RedeclarationKind forRedeclarationInCurContext() const
bool hasReachableDefinition(NamedDecl *D)
Definition Sema.h:15698
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:2647
bool CheckAttrTarget(const ParsedAttr &CurrAttr)
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6620
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:641
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:1231
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:1591
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:11380
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.
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:276
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:1588
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
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:1311
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:4715
bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
PragmaAlignPackDiagnoseKind
Definition Sema.h:2228
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:7069
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:126
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1350
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:1884
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14143
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:9983
@ PrivateFragmentImportFinished
after 'module :private;' but a non-import decl has already been seen.
Definition Sema.h:9990
@ ImportFinished
after any non-import decl.
Definition Sema.h:9987
@ PrivateFragmentImportAllowed
after 'module :private;' but before any non-import decl.
Definition Sema.h:9988
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9984
@ GlobalFragment
after 'module;' but before 'module X;'
Definition Sema.h:9985
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
Definition Sema.h:9992
@ ImportAllowed
after 'module X;' but before any non-import decl.
Definition Sema.h:9986
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:15227
bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A)
Recheck instantiated thread-safety attributes that could not be validated on the dependent pattern de...
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
CUDALaunchBoundsAttr * CreateLaunchBoundsAttr(const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks, bool IgnoreArch=false)
Create a CUDALaunchBoundsAttr attribute.
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:110
VarDecl * BuildForRangeVarDecl(SourceLocation Loc, QualType Type, IdentifierInfo *Name, bool IsConstexpr)
Helper used by the expansion statements and for-range code to build a variable declaration for e....
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested)
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl)
void incrementMSManglingNumber() const
Definition Sema.h:1271
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:6803
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6825
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6815
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6830
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6820
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6840
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6809
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6835
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6850
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:13791
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:4877
@ AP_InferredFromAnyAppleOS
The availability attribute was inferred from an 'anyAppleOS' availability attribute.
Definition Sema.h:4891
@ AP_PragmaClangAttribute
The availability attribute was applied using 'pragma clang attribute'.
Definition Sema.h:4883
@ AP_InferredFromOtherPlatform
The availability attribute for a specific platform was inferred from an availability attribute for an...
Definition Sema.h:4887
@ AP_PragmaClangAttribute_InferredFromAnyAppleOS
The availability attribute was inferred from an 'anyAppleOS' availability attribute that was applied ...
Definition Sema.h:4896
@ AP_Explicit
The availability attribute was specified explicitly next to the declaration.
Definition Sema.h:4880
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:990
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:14105
SemaPPC & PPC()
Definition Sema.h:1542
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:2504
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:421
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition SemaStmt.cpp:76
SmallVector< Decl *, 2 > WeakTopLevelDecl
WeakTopLevelDecl - Translation-unit scoped declarations generated by #pragma weak during processing o...
Definition Sema.h:4960
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:1269
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:14987
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...
ASTContext::CXXRecordDeclRelocationInfo CheckCXX2CRelocatable(const clang::CXXRecordDecl *D)
LateTemplateParserCB * LateTemplateParser
Definition Sema.h:1355
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:8473
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:3639
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:10138
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:8260
SemaSystemZ & SystemZ()
Definition Sema.h:1572
DarwinSDKInfo * getDarwinSDKInfoForAvailabilityChecking()
Definition Sema.cpp:124
bool isRedefinitionAllowedFor(const NamedDecl *D, bool &Visible)
Definition Sema.h:15688
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:3043
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.
llvm::SmallPtrSet< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3619
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8410
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:10334
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:9969
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:674
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:1313
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:11546
@ TemplateNameIsRequired
Definition Sema.h:11546
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:792
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:481
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:6613
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:1312
CXXMethodDecl * CreateLambdaCallOperator(SourceRange IntroducerRange, CXXRecordDecl *Class)
void DiagnoseUnterminatedPragmaAlignPack()
Definition SemaAttr.cpp:632
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:7880
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:935
FPOptions CurFPFeatures
Definition Sema.h:1306
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:1358
QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc)
llvm::SmallPtrSet< const CXXRecordDecl *, 8 > RecordDeclSetTy
Definition Sema.h:6604
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.
ExprResult BuildCXXExpansionSelectExpr(InitListExpr *Range, Expr *Idx)
void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD)
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)
void LoadExternalExtnameUndeclaredIdentifiers()
Load pragma redefine_extname'd undeclared identifiers from the external source.
Definition Sema.cpp:1113
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:523
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2075
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:3082
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc, bool IsExplicit)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
std::unique_ptr< APINotesSelectorDiagnosticState > APINotesSelectorDiagnostics
Definition Sema.h:1316
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< ParsedType > Args, SourceLocation RParenLoc)
Parsed one of the type trait support pseudo-functions.
StmtResult FinishCXXExpansionStmt(Stmt *Expansion, Stmt *Body)
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition Sema.h:11729
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11739
@ TPC_FriendFunctionTemplate
Definition Sema.h:11737
@ TPC_ClassTemplateMember
Definition Sema.h:11735
@ TPC_FunctionTemplate
Definition Sema.h:11734
@ TPC_FriendClassTemplate
Definition Sema.h:11736
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11738
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:1462
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:1592
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:2154
bool isMainFileLoc(SourceLocation Loc) const
Determines whether the given source location is in the main file and we're in a context where we shou...
Definition Sema.cpp:980
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:7839
void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init)
CXXDeductionGuideDecl * DeclareAggregateDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
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.
void ActOnDeferStmtError(Scope *CurScope)
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:6636
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition Sema.h:13763
void PrintStats() const
Print out statistics about the semantic analysis.
Definition Sema.cpp:692
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:15218
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:1838
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:1255
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:89
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:11166
@ BFRK_Check
Determining whether a for-range statement could be built.
Definition Sema.h:11174
@ BFRK_Build
Initial building of a for-range statement.
Definition Sema.h:11168
@ BFRK_Rebuild
Instantiation or recovery rebuild of a for-range statement.
Definition Sema.h:11171
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
SemaNVPTX & NVPTX()
Definition Sema.h:1517
void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD)
Check that VTable Pointer authentication is only being set on the first first instantiation of the vt...
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool AllowTypoCorrection=true)
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:915
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:586
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:2095
@ PSK_ConstSeg
Definition Sema.h:2098
@ PSK_DataSeg
Definition Sema.h:2096
@ PSK_CodeSeg
Definition Sema.h:2099
@ PSK_BSSSeg
Definition Sema.h:2097
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:647
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty)
Check that the type is a plain record with one field being a pointer type and the other field being a...
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition SemaCast.cpp:338
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:6380
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,...
CodeAlignAttr * BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E)
ExprResult ActOnStmtExprResult(ExprResult E)
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...
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:3608
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2252
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)
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, bool IsMemberSpecialization, SkipBodyInfo *SkipBody=nullptr)
PragmaClangSection PragmaClangBSSSection
Definition Sema.h:1851
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:1369
QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel)
AbstractDiagSelID
Definition Sema.h:6326
@ AbstractSynthesizedIvarType
Definition Sema.h:6333
@ AbstractVariableType
Definition Sema.h:6330
@ AbstractReturnType
Definition Sema.h:6328
@ AbstractNone
Definition Sema.h:6327
@ AbstractFieldType
Definition Sema.h:6331
@ AbstractArrayType
Definition Sema.h:6334
@ AbstractParamType
Definition Sema.h:6329
@ AbstractIvarType
Definition Sema.h:6332
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition SemaStmt.cpp:976
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 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:1557
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:8459
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...
void getSortedUnusedLocalTypedefNameCandidates(SmallVectorImpl< const TypedefNameDecl * > &Sorted) const
Store UnusedLocalTypedefNameCandidates in Sorted in a deterministic order.
Definition Sema.cpp:1203
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.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
void DiagnoseUnusedAPINotesSelectors()
Diagnose exact API notes selectors that were not matched by any declaration processed in this transla...
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:8068
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:9476
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9480
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9486
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9478
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9483
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9494
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9490
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:2676
const ExpressionEvaluationContextRecord & parentEvaluationContext() const
Definition Sema.h:7047
SemaLoongArch & LoongArch()
Definition Sema.h:1497
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:6515
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6520
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6517
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:14139
void CheckVariableDeclarationType(VarDecl *NewVD)
sema::CompoundScopeInfo & getCurCompoundScope() const
Definition SemaStmt.cpp:433
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:3035
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1302
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
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:730
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:3585
void ActOnFinishOfCompoundStmt()
Definition SemaStmt.cpp:429
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:1783
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:15534
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:7917
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition SemaStmt.cpp:437
void NoteTemplateParameterLocation(const NamedDecl &Decl)
SemaWasm & Wasm()
Definition Sema.h:1577
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)
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, int FirstArg)
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:3531
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:13759
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 ...
SemaPseudoObject & PseudoObject()
Definition Sema.h:1547
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:2637
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt)
Definition SemaStmt.cpp:614
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11511
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:7873
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:732
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:149
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:8418
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1301
static int getPrintable(int I)
Definition Sema.h:15217
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:926
void ActOnDependentForRangeInitializer(VarDecl *LoopVar, BuildForRangeKind BFRK)
Set the type of a for-range declaration whose for-range or expansion initialiser is dependent.
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition Sema.h:9748
bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling)
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:13046
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope)
Definition SemaStmt.cpp:591
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:3887
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:15222
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:552
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:8286
ForRangeBeginEndInfo BuildCXXForRangeBeginEndVars(Scope *S, VarDecl *RangeVar, SourceLocation ColonLoc, SourceLocation CoawaitLoc, ArrayRef< MaterializeTemporaryExpr * > LifetimeExtendTemps, BuildForRangeKind Kind, bool IsConstexpr, StmtResult *RebuildResult=nullptr, llvm::function_ref< StmtResult()> RebuildWithDereference={}, IdentifierInfo *BeginName=nullptr, IdentifierInfo *EndName=nullptr)
Determine begin-expr and end-expr and build variable declarations for them as per [stmt....
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
SFINAETrap * CurrentSFINAEContext
Definition Sema.h:13774
SemaARM & ARM()
Definition Sema.h:1457
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:13755
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:365
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.
static const char * getPrintable(const char *S)
Definition Sema.h:15220
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.
SmallVector< std::pair< Scope *, SourceLocation >, 2 > CurrentDefer
Stack of '_Defer' statements that are currently being parsed, as well as the locations of their '_Def...
Definition Sema.h:11076
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:673
QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a block pointer type.
PragmaMsStackAction
Definition Sema.h:1857
@ PSK_Push_Set
Definition Sema.h:1863
@ PSK_Reset
Definition Sema.h:1858
@ PSK_Pop_Set
Definition Sema.h:1864
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:8755
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.
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13840
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:298
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:343
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3761
Exposes information about the current target.
Definition TargetInfo.h:227
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.).
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:4679
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:3557
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:8460
The base class of the type hierarchy.
Definition TypeBase.h:1876
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3711
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3606
Simple class containing the result of Sema::CorrectTypo.
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1088
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3389
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4125
A set of unresolved declarations.
The iterator over UnresolvedSets.
Represents a C++ using-declaration.
Definition DeclCXX.h:3612
Represents C++ using-directive.
Definition DeclCXX.h:3117
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3420
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:932
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:4274
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2881
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:791
Retains information about a captured region.
Definition ScopeInfo.h:817
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 UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
Enums for the diagnostics of target, target_version and target_clones.
Definition Sema.h:855
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
llvm::DenseMap< int, SourceRange > ParsedSubjectMatchRuleSet
bool operator==(const ValueType &a, const ValueType &b)
void threadSafetyCleanup(BeforeSet *Cache)
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
The JSON file list parser is used to communicate input to InstallAPI.
PragmaClangSectionAction
Definition Sema.h:476
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
ImplicitTypenameContext
Definition DeclSpec.h:1984
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
OverloadKind
Definition Sema.h:823
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:834
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:826
bool isa(CodeGen::Address addr)
Definition Address.h:330
OpaquePtr< TemplateName > ParsedTemplateTy
Definition Ownership.h:256
@ CPlusPlus
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
VariadicCallType
Definition Sema.h:513
FunctionEffectMode
Used with attributes/effects with a boolean condition, e.g. nonblocking.
Definition Sema.h:459
CUDAFunctionTarget
Definition Cuda.h:63
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:791
@ Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition Sema.h:799
PragmaMSCommentKind
Definition PragmaKinds.h:14
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:36
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
TryCaptureKind
Definition Sema.h:653
IfStatementKind
In an if statement, this denotes whether the statement is a constexpr or consteval if statement.
Definition Specifiers.h:40
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition Sema.h:661
@ BitwiseOp
A bitwise operation.
Definition Sema.h:665
@ Arithmetic
An arithmetic operation.
Definition Sema.h:663
@ Conditional
A conditional (?:) operator.
Definition Sema.h:669
@ CompAssign
A compound assignment expression.
Definition Sema.h:671
@ Comparison
A comparison.
Definition Sema.h:667
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:349
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:272
@ Success
Annotation was successful.
Definition Parser.h:65
CXXConstructionKind
Definition ExprCXX.h:1543
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:150
PointerAuthDiscArgKind
Definition Sema.h:594
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:604
@ TemplateTemplateArgument
Definition Sema.h:613
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
NonTrivialCUnionContext
Definition Sema.h:532
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:628
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:636
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:642
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:633
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:639
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:238
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:919
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:128
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:249
void inferNoReturnAttr(Sema &S, Decl *D)
Expr * Cond
};
llvm::MutableArrayRef< ImplicitConversionSequence > ConversionSequenceList
A list of implicit conversion sequences for the arguments of an OverloadCandidate.
Definition Overload.h:929
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
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:2925
@ CopyInit
[a = b], [a = {b}]
Definition DeclSpec.h:2927
@ 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:478
@ Undefined
Keep undefined.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:616
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3818
CorrectTypoKind
Definition Sema.h:818
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
OptionalUnsigned< unsigned > UnsignedOrNone
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:689
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:712
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:787
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition Sema.h:704
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition Sema.h:759
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition Sema.h:749
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition Sema.h:776
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition Sema.h:763
@ CompatibleOBTDiscards
CompatibleOBTDiscards - Assignment discards overflow behavior.
Definition Sema.h:783
@ IncompatibleOBTKinds
IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType kinds, e....
Definition Sema.h:780
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
Definition Sema.h:696
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition Sema.h:738
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:733
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition Sema.h:772
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition Sema.h:723
@ IncompatiblePointerDiscardsOverflowBehavior
IncompatiblePointerDiscardsOverflowBehavior - The assignment discards overflow behavior annotations b...
Definition Sema.h:743
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition Sema.h:700
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition Sema.h:708
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition Sema.h:755
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition Sema.h:717
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:729
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition Sema.h:767
TagUseKind
Definition Sema.h:451
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:467
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6030
TUFragmentKind
Definition Sema.h:487
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...
@ On
Always emit colors regardless of the output stream.
NameClassificationKind
Describes the result of the name lookup and resolution performed by Sema::ClassifyName().
Definition Sema.h:555
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:587
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
@ DependentNonType
The name denotes a member of a dependent type that could not be resolved.
Definition Sema.h:576
@ UndeclaredTemplate
The name was classified as an ADL-only function template name.
Definition Sema.h:589
@ NonType
The name was classified as a specific non-type, non-template declaration.
Definition Sema.h:568
@ Unknown
This name is not a type or template in this context, but might be something else.
Definition Sema.h:558
@ Error
Classification failed; an error has been produced.
Definition Sema.h:560
@ Type
The name was classified as a type.
Definition Sema.h:564
@ TypeTemplate
The name was classified as a template whose specializations are types.
Definition Sema.h:583
@ Concept
The name was classified as a concept name.
Definition Sema.h:591
@ OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
Definition Sema.h:581
@ UndeclaredNonType
The name was classified as an ADL-only function name.
Definition Sema.h:572
@ VarTemplate
The name was classified as a variable template name.
Definition Sema.h:585
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:499
CastKind
CastKind - The kind of operation required for a conversion.
AllowFoldKind
Definition Sema.h:655
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:676
PragmaMSStructKind
Definition PragmaKinds.h:24
AssignmentAction
Definition Sema.h:216
@ Deduced
The normal deduced case.
Definition TypeBase.h:1815
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
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:521
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:29
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
TypeAwareAllocationMode
Definition ExprCXX.h:2254
IfExistsResult
Describes the result of an "if-exists" condition check.
Definition Sema.h:803
@ Exists
The symbol exists.
Definition Sema.h:805
@ DoesNotExist
The symbol does not exist.
Definition Sema.h:808
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition Specifiers.h:413
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:310
TrivialABIHandling
Definition Sema.h:645
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:650
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:647
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:419
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:414
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:417
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:390
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:376
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:412
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:421
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:409
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:393
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:382
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:396
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:385
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:406
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:400
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:403
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
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:1305
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:838
@ CaseValue
Expression in a case label.
Definition Sema.h:839
@ StaticAssertMessageData
Call to data() in a static assert message.
Definition Sema.h:849
@ Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:840
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:847
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:846
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:842
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:851
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:845
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
SourceLocIdentKind
Definition Expr.h:5019
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:6005
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6016
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6019
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6023
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2248
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:1995
CheckedConversionKind
The kind of conversion being performed.
Definition Sema.h:438
@ Implicit
An implicit conversion.
Definition Sema.h:440
@ CStyleCast
A C-style cast.
Definition Sema.h:442
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:448
@ OtherCast
A cast other than a C-style cast.
Definition Sema.h:446
@ FunctionalCast
A functional-style cast.
Definition Sema.h:444
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition Specifiers.h:174
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
int const char * function
Definition c++config.h:31
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
Selector diagnostic state for all API notes readers used by one Sema.
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:242
SourceLocation PointerEndLoc
The end location for the first pointer declarator in the file.
Definition Sema.h:249
SourceLocation PointerLoc
The first pointer declarator (of any pointer kind) in the file that does not have a corresponding nul...
Definition Sema.h:245
bool SawTypeNullability
Whether we saw any type nullability annotations in the given file.
Definition Sema.h:255
uint8_t PointerKind
Which kind of pointer declarator we saw.
Definition Sema.h:252
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition TypeBase.h:5143
Holds information about the various types of exception specification.
Definition TypeBase.h:5463
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5465
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5468
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5471
Extra information about a function prototype.
Definition TypeBase.h:5491
Represents a complete lambda introducer.
Definition DeclSpec.h:2933
Contains a late templated function.
Definition Sema.h:15907
FPOptions FPO
Floating-point options in the point of definition.
Definition Sema.h:15912
Decl * D
The template function declaration to be late parsed.
Definition Sema.h:15910
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:933
Describes how types, statements, expressions, and declarations should be printed.
SourceLocation CurrentPragmaLocation
Definition Sema.h:2070
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10621
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10628
CheckNonDependentConversionsFlag(bool SuppressUserConversions, bool OnlyInitializeNonUserDefinedConversions)
Definition Sema.h:10630
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12156
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12152
CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &)=delete
CheckTemplateArgumentInfo(bool PartialOrdering=false, bool MatchingTTP=false)
Definition Sema.h:12133
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12145
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12142
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12142
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:13254
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition Sema.h:13425
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool InParameterMappingSubstitution
Whether we're substituting into the parameter mapping of a constraint.
Definition Sema.h:13382
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition Sema.h:13398
ArrayRef< TemplateArgument > template_arguments() const
Definition Sema.h:13417
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation,...
Definition Sema.h:13393
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13385
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13411
bool InConstraintSubstitution
Whether we're substituting into constraints.
Definition Sema.h:13379
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13401
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition Sema.h:13408
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:13256
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13345
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition Sema.h:13266
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13275
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition Sema.h:13294
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13342
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition Sema.h:13302
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition Sema.h:13309
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13349
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition Sema.h:13320
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13355
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition Sema.h:13285
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition Sema.h:13361
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13358
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition Sema.h:13364
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13282
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition Sema.h:13290
@ SYCLKernelLaunchOverloadResolution
We are performing overload resolution for a call to a function template or variable template named 's...
Definition Sema.h:13372
@ ExpansionStmtInstantiation
We are instantiating an expansion statement.
Definition Sema.h:13375
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13298
@ TemplateInstantiation
We are instantiating a template declaration.
Definition Sema.h:13259
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition Sema.h:13312
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13316
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13271
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13339
@ SYCLKernelLaunchLookup
We are performing name lookup for a function template or variable template named 'sycl_kernel_launch'...
Definition Sema.h:13368
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition Sema.h:13305
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13388
CXXSpecialMemberKind SpecialMember
The special member being declared or defined.
Definition Sema.h:13414
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:6964
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6865
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:6898
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6900
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6951
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6885
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:6894
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6905
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:6913
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6909
bool IsCaseExpr
Whether evaluating an expression for a switch case label.
Definition Sema.h:6954
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6919
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:6880
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6927
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition Sema.h:6957
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6923
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6870
VarDecl * DeclForInitializer
Declaration for initializer if one is currently being parsed.
Definition Sema.h:6890
std::optional< InitializationContext > DelayedDefaultInitializationContext
Definition Sema.h:6974
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext)
Definition Sema.h:6976
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6867
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6874
Holds the 'begin' and 'end' variables of a range-based for loop or expansion statement; begin-expr an...
Definition Sema.h:11217
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2667
FunctionEffectDiffVector(const FunctionEffectsRef &Old, const FunctionEffectsRef &New)
Caller should short-circuit by checking for equality first.
std::optional< FunctionEffectWithCondition > Old
Definition Sema.h:15767
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:15771
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:15779
std::optional< FunctionEffectWithCondition > New
Definition Sema.h:15769
FunctionEffect::Kind EffectKind
Definition Sema.h:15764
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13601
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:14277
LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D)
Definition Sema.h:14280
bool isMoveEligible() const
Definition Sema.h:11271
bool isCopyElidable() const
Definition Sema.h:11272
const VarDecl * Candidate
Definition Sema.h:11266
IdentifierInfo * Identifier
The identifier preceding the '::'.
Definition Sema.h:3344
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType=ParsedType())
Creates info object for the most typical case.
Definition Sema.h:3353
SourceLocation IdentifierLoc
The location of the identifier.
Definition Sema.h:3347
SourceLocation CCLoc
The location of the '::'.
Definition Sema.h:3350
ParsedType ObjectType
The type of the object, if we're parsing nested-name-specifier in a member access expression.
Definition Sema.h:3341
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType)
Definition Sema.h:3359
OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType)
Definition Sema.h:12778
Information from a C++ pragma export, for a symbol that we haven't seen the declaration for yet.
Definition Sema.h:2361
This an attribute introduced by #pragma clang attribute.
Definition Sema.h:2129
SmallVector< attr::SubjectMatchRule, 4 > MatchRules
Definition Sema.h:2132
A push'd group of PragmaAttributeEntries.
Definition Sema.h:2137
SourceLocation Loc
The location of the push attribute.
Definition Sema.h:2139
SmallVector< PragmaAttributeEntry, 2 > Entries
Definition Sema.h:2142
const IdentifierInfo * Namespace
The namespace of this push group.
Definition Sema.h:2141
SourceLocation PragmaLocation
Definition Sema.h:1848
PragmaMsStackAction Action
Definition Sema.h:1868
Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
Definition Sema.h:1981
llvm::StringRef StackSlotLabel
Definition Sema.h:1977
SourceLocation PragmaLocation
Definition Sema.h:1979
SourceLocation PragmaPushLocation
Definition Sema.h:1980
ValueType CurrentValue
Definition Sema.h:2051
void SentinelAction(PragmaMsStackAction Action, StringRef Label)
Definition Sema.h:2037
bool hasValue() const
Definition Sema.h:2047
SmallVector< Slot, 2 > Stack
Definition Sema.h:2049
ValueType DefaultValue
Definition Sema.h:2050
SourceLocation CurrentPragmaLocation
Definition Sema.h:2052
PragmaStack(const ValueType &Default)
Definition Sema.h:2044
void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value)
Definition Sema.h:1988
ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val)
Definition Sema.h:5175
ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val)
Definition Sema.h:5169
RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
Definition Sema.h:13226
RecursiveInstGuard(const RecursiveInstGuard &)=delete
RecursiveInstGuard & operator=(const RecursiveInstGuard &)=delete
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition Sema.h:10518
SFINAEContextBase & operator=(const SFINAEContextBase &)=delete
SFINAEContextBase(Sema &S, SFINAETrap *Cur)
Definition Sema.h:12587
SFINAEContextBase(const SFINAEContextBase &)=delete
Abstract class used to diagnose incomplete types.
Definition Sema.h:8351
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
Definition Sema.h:2709
unsigned LayoutCompatible
If true, Type should be compared with other expression's types for layout-compatibility.
Definition Sema.h:2718
bool CheckSameAsPrevious
Definition Sema.h:355
NamedDecl * Previous
Definition Sema.h:356
SkipBodyInfo()=default
NamedDecl * New
Definition Sema.h:357
Information about a template-id annotation token.