1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the Sema class, which performs semantic analysis and
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_SEMA_SEMA_H
15 #define LLVM_CLANG_SEMA_SEMA_H
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/Availability.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/DeclarationName.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExternalASTSource.h"
26 #include "clang/AST/LocInfoType.h"
27 #include "clang/AST/MangleNumberingContext.h"
28 #include "clang/AST/NSAPI.h"
29 #include "clang/AST/PrettyPrinter.h"
30 #include "clang/AST/StmtCXX.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/AST/TypeOrdering.h"
33 #include "clang/Basic/ExpressionTraits.h"
34 #include "clang/Basic/Module.h"
35 #include "clang/Basic/OpenMPKinds.h"
36 #include "clang/Basic/PragmaKinds.h"
37 #include "clang/Basic/Specifiers.h"
38 #include "clang/Basic/TemplateKinds.h"
39 #include "clang/Basic/TypeTraits.h"
40 #include "clang/Sema/AnalysisBasedWarnings.h"
41 #include "clang/Sema/CleanupInfo.h"
42 #include "clang/Sema/DeclSpec.h"
43 #include "clang/Sema/ExternalSemaSource.h"
44 #include "clang/Sema/IdentifierResolver.h"
45 #include "clang/Sema/ObjCMethodList.h"
46 #include "clang/Sema/Ownership.h"
47 #include "clang/Sema/Scope.h"
48 #include "clang/Sema/TypoCorrection.h"
49 #include "clang/Sema/Weak.h"
50 #include "llvm/ADT/ArrayRef.h"
51 #include "llvm/ADT/Optional.h"
52 #include "llvm/ADT/SetVector.h"
53 #include "llvm/ADT/SmallBitVector.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/TinyPtrVector.h"
65 template <typename ValueT> struct DenseMapInfo;
66 template <typename ValueT, typename ValueInfoT> class DenseSet;
68 struct InlineAsmIdentifierInfo;
75 class ASTMutationListener;
85 class CXXBindTemporaryExpr;
86 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
87 class CXXConstructorDecl;
88 class CXXConversionDecl;
90 class CXXDestructorDecl;
91 class CXXFieldCollector;
92 class CXXMemberCallExpr;
98 class ClassTemplateDecl;
99 class ClassTemplatePartialSpecializationDecl;
100 class ClassTemplateSpecializationDecl;
101 class VarTemplatePartialSpecializationDecl;
102 class CodeCompleteConsumer;
103 class CodeCompletionAllocator;
104 class CodeCompletionTUInfo;
105 class CodeCompletionResult;
106 class CoroutineBodyStmt;
108 class DeclAccessPair;
111 class DeclaratorDecl;
112 class DeducedTemplateArgument;
113 class DependentDiagnostic;
114 class DesignatedInitExpr;
117 class EnumConstantDecl;
123 class FunctionProtoType;
124 class FunctionTemplateDecl;
125 class ImplicitConversionSequence;
126 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
128 class InitializationKind;
129 class InitializationSequence;
130 class InitializedEntity;
131 class IntegerLiteral;
135 class LocalInstantiationScope;
138 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
140 class MultiLevelTemplateArgumentList;
142 class ObjCCategoryDecl;
143 class ObjCCategoryImplDecl;
144 class ObjCCompatibleAliasDecl;
145 class ObjCContainerDecl;
147 class ObjCImplementationDecl;
148 class ObjCInterfaceDecl;
150 template <class T> class ObjCList;
151 class ObjCMessageExpr;
152 class ObjCMethodDecl;
153 class ObjCPropertyDecl;
154 class ObjCProtocolDecl;
155 class OMPThreadPrivateDecl;
156 class OMPRequiresDecl;
157 class OMPDeclareReductionDecl;
158 class OMPDeclareSimdDecl;
160 struct OMPVarListLocTy;
161 struct OverloadCandidate;
162 enum class OverloadCandidateParamOrder : char;
163 enum OverloadCandidateRewriteKind : unsigned;
164 class OverloadCandidateSet;
169 class PseudoDestructorTypeStorage;
170 class PseudoObjectExpr;
172 class StandardConversionSequence;
176 class TemplateArgument;
177 class TemplateArgumentList;
178 class TemplateArgumentLoc;
180 class TemplateInstantiationCallback;
181 class TemplateParameterList;
182 class TemplatePartialOrderingContext;
183 class TemplateTemplateParmDecl;
187 class TypedefNameDecl;
189 class TypoCorrectionConsumer;
191 class UnresolvedLookupExpr;
192 class UnresolvedMemberExpr;
193 class UnresolvedSetImpl;
194 class UnresolvedSetIterator;
196 class UsingShadowDecl;
199 class VarTemplateSpecializationDecl;
200 class VisibilityAttr;
201 class VisibleDeclConsumer;
202 class IndirectFieldDecl;
203 struct DeductionFailureInfo;
204 class TemplateSpecCandidateSet;
207 class AccessedEntity;
208 class BlockScopeInfo;
210 class CapturedRegionScopeInfo;
211 class CapturingScopeInfo;
212 class CompoundScopeInfo;
213 class DelayedDiagnostic;
214 class DelayedDiagnosticPool;
215 class FunctionScopeInfo;
216 class LambdaScopeInfo;
217 class PossiblyUnreachableDiag;
218 class SemaPPCallbacks;
219 class TemplateDeductionInfo;
222 namespace threadSafety {
224 void threadSafetyCleanup(BeforeSet* Cache);
227 // FIXME: No way to easily map from TemplateTypeParmTypes to
228 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
229 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
230 SourceLocation> UnexpandedParameterPack;
232 /// Describes whether we've seen any nullability information for the given
234 struct FileNullability {
235 /// The first pointer declarator (of any pointer kind) in the file that does
236 /// not have a corresponding nullability annotation.
237 SourceLocation PointerLoc;
239 /// The end location for the first pointer declarator in the file. Used for
241 SourceLocation PointerEndLoc;
243 /// Which kind of pointer declarator we saw.
246 /// Whether we saw any type nullability annotations in the given file.
247 bool SawTypeNullability = false;
250 /// A mapping from file IDs to a record of whether we've seen nullability
251 /// information in that file.
252 class FileNullabilityMap {
253 /// A mapping from file IDs to the nullability information for each file ID.
254 llvm::DenseMap<FileID, FileNullability> Map;
256 /// A single-element cache based on the file ID.
259 FileNullability Nullability;
263 FileNullability &operator[](FileID file) {
264 // Check the single-element cache.
265 if (file == Cache.File)
266 return Cache.Nullability;
268 // It's not in the single-element cache; flush the cache if we have one.
269 if (!Cache.File.isInvalid()) {
270 Map[Cache.File] = Cache.Nullability;
273 // Pull this entry into the cache.
275 Cache.Nullability = Map[file];
276 return Cache.Nullability;
280 /// Keeps track of expected type during expression parsing. The type is tied to
281 /// a particular token, all functions that update or consume the type take a
282 /// start location of the token they are looking at as a parameter. This allows
283 /// to avoid updating the type on hot paths in the parser.
284 class PreferredTypeBuilder {
286 PreferredTypeBuilder() = default;
287 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
289 void enterCondition(Sema &S, SourceLocation Tok);
290 void enterReturn(Sema &S, SourceLocation Tok);
291 void enterVariableInit(SourceLocation Tok, Decl *D);
292 /// Computing a type for the function argument may require running
293 /// overloading, so we postpone its computation until it is actually needed.
295 /// Clients should be very careful when using this funciton, as it stores a
296 /// function_ref, clients should make sure all calls to get() with the same
297 /// location happen while function_ref is alive.
298 void enterFunctionArgument(SourceLocation Tok,
299 llvm::function_ref<QualType()> ComputeType);
301 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
302 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
303 SourceLocation OpLoc);
304 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
305 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
306 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
307 /// Handles all type casts, including C-style cast, C++ casts, etc.
308 void enterTypeCast(SourceLocation Tok, QualType CastType);
310 QualType get(SourceLocation Tok) const {
311 if (Tok != ExpectedLoc)
316 return ComputeType();
321 /// Start position of a token for which we store expected type.
322 SourceLocation ExpectedLoc;
323 /// Expected type for a token starting at ExpectedLoc.
325 /// A function to compute expected type at ExpectedLoc. It is only considered
327 llvm::function_ref<QualType()> ComputeType;
330 /// Sema - This implements semantic analysis and AST building for C.
332 Sema(const Sema &) = delete;
333 void operator=(const Sema &) = delete;
335 /// A key method to reduce duplicate debug info from Sema.
336 virtual void anchor();
338 ///Source of additional semantic information.
339 ExternalSemaSource *ExternalSource;
341 ///Whether Sema has generated a multiplexer and has to delete it.
342 bool isMultiplexExternalSource;
344 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
346 bool isVisibleSlow(const NamedDecl *D);
348 /// Determine whether two declarations should be linked together, given that
349 /// the old declaration might not be visible and the new declaration might
350 /// not have external linkage.
351 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
352 const NamedDecl *New) {
355 // See comment in below overload for why it's safe to compute the linkage
356 // of the new declaration here.
357 if (New->isExternallyDeclarable()) {
358 assert(Old->isExternallyDeclarable() &&
359 "should not have found a non-externally-declarable previous decl");
364 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
366 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
368 ArrayRef<QualType> Args);
371 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
372 typedef OpaquePtr<TemplateName> TemplateTy;
373 typedef OpaquePtr<QualType> TypeTy;
375 OpenCLOptions OpenCLFeatures;
376 FPOptions FPFeatures;
378 const LangOptions &LangOpts;
381 ASTConsumer &Consumer;
382 DiagnosticsEngine &Diags;
383 SourceManager &SourceMgr;
385 /// Flag indicating whether or not to collect detailed statistics.
388 /// Code-completion consumer.
389 CodeCompleteConsumer *CodeCompleter;
391 /// CurContext - This is the current declaration context of parsing.
392 DeclContext *CurContext;
394 /// Generally null except when we temporarily switch decl contexts,
395 /// like in \see ActOnObjCTemporaryExitContainerContext.
396 DeclContext *OriginalLexicalContext;
398 /// VAListTagName - The declaration name corresponding to __va_list_tag.
399 /// This is used as part of a hack to omit that class from ADL results.
400 DeclarationName VAListTagName;
402 bool MSStructPragmaOn; // True when \#pragma ms_struct on
404 /// Controls member pointer representation format under the MS ABI.
405 LangOptions::PragmaMSPointersToMembersKind
406 MSPointerToMemberRepresentationMethod;
408 /// Stack of active SEH __finally scopes. Can be empty.
409 SmallVector<Scope*, 2> CurrentSEHFinally;
411 /// Source location for newly created implicit MSInheritanceAttrs
412 SourceLocation ImplicitMSInheritanceAttrLoc;
414 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
415 /// `TransformTypos` in order to keep track of any TypoExprs that are created
416 /// recursively during typo correction and wipe them away if the correction
418 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
420 /// pragma clang section kind
421 enum PragmaClangSectionKind {
430 enum PragmaClangSectionAction {
435 struct PragmaClangSection {
436 std::string SectionName;
438 SourceLocation PragmaLocation;
440 void Act(SourceLocation PragmaLocation,
441 PragmaClangSectionAction Action,
442 StringLiteral* Name);
445 PragmaClangSection PragmaClangBSSSection;
446 PragmaClangSection PragmaClangDataSection;
447 PragmaClangSection PragmaClangRodataSection;
448 PragmaClangSection PragmaClangRelroSection;
449 PragmaClangSection PragmaClangTextSection;
451 enum PragmaMsStackAction {
452 PSK_Reset = 0x0, // #pragma ()
453 PSK_Set = 0x1, // #pragma (value)
454 PSK_Push = 0x2, // #pragma (push[, id])
455 PSK_Pop = 0x4, // #pragma (pop[, id])
456 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
457 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
458 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
461 template<typename ValueType>
464 llvm::StringRef StackSlotLabel;
466 SourceLocation PragmaLocation;
467 SourceLocation PragmaPushLocation;
468 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
469 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
470 : StackSlotLabel(StackSlotLabel), Value(Value),
471 PragmaLocation(PragmaLocation),
472 PragmaPushLocation(PragmaPushLocation) {}
474 void Act(SourceLocation PragmaLocation,
475 PragmaMsStackAction Action,
476 llvm::StringRef StackSlotLabel,
479 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
480 // method body to restore the stacks on exit, so it works like this:
483 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
485 // #pragma <name>(pop, InternalPragmaSlot)
488 // It works even with #pragma vtordisp, although MSVC doesn't support
489 // #pragma vtordisp(push [, id], n)
492 // Push / pop a named sentinel slot.
493 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
494 assert((Action == PSK_Push || Action == PSK_Pop) &&
495 "Can only push / pop #pragma stack sentinels!");
496 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
500 explicit PragmaStack(const ValueType &Default)
501 : DefaultValue(Default), CurrentValue(Default) {}
503 bool hasValue() const { return CurrentValue != DefaultValue; }
505 SmallVector<Slot, 2> Stack;
506 ValueType DefaultValue; // Value used for PSK_Reset action.
507 ValueType CurrentValue;
508 SourceLocation CurrentPragmaLocation;
510 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
511 // we shouldn't do so if they're in a module).
513 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
514 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
516 /// 0: Suppress all vtordisps
517 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
519 /// 2: Always insert vtordisps to support RTTI on partially constructed
521 PragmaStack<MSVtorDispMode> VtorDispStack;
523 // Sentinel to represent when the stack is set to mac68k alignment.
524 static const unsigned kMac68kAlignmentSentinel = ~0U;
525 PragmaStack<unsigned> PackStack;
526 // The current #pragma pack values and locations at each #include.
527 struct PackIncludeState {
528 unsigned CurrentValue;
529 SourceLocation CurrentPragmaLocation;
530 bool HasNonDefaultValue, ShouldWarnOnInclude;
532 SmallVector<PackIncludeState, 8> PackIncludeStack;
534 PragmaStack<StringLiteral *> DataSegStack;
535 PragmaStack<StringLiteral *> BSSSegStack;
536 PragmaStack<StringLiteral *> ConstSegStack;
537 PragmaStack<StringLiteral *> CodeSegStack;
539 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
540 // Actions should be performed only if we enter / exit a C++ method body.
541 class PragmaStackSentinelRAII {
543 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
544 ~PragmaStackSentinelRAII();
552 /// A mapping that describes the nullability we've seen in each header file.
553 FileNullabilityMap NullabilityMap;
555 /// Last section used with #pragma init_seg.
556 StringLiteral *CurInitSeg;
557 SourceLocation CurInitSegLoc;
559 /// VisContext - Manages the stack for \#pragma GCC visibility.
560 void *VisContext; // Really a "PragmaVisStack*"
562 /// This an attribute introduced by \#pragma clang attribute.
563 struct PragmaAttributeEntry {
565 ParsedAttr *Attribute;
566 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
570 /// A push'd group of PragmaAttributeEntries.
571 struct PragmaAttributeGroup {
572 /// The location of the push attribute.
574 /// The namespace of this push group.
575 const IdentifierInfo *Namespace;
576 SmallVector<PragmaAttributeEntry, 2> Entries;
579 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
581 /// The declaration that is currently receiving an attribute from the
582 /// #pragma attribute stack.
583 const Decl *PragmaAttributeCurrentTargetDecl;
585 /// This represents the last location of a "#pragma clang optimize off"
586 /// directive if such a directive has not been closed by an "on" yet. If
587 /// optimizations are currently "on", this is set to an invalid location.
588 SourceLocation OptimizeOffPragmaLocation;
590 /// Flag indicating if Sema is building a recovery call expression.
592 /// This flag is used to avoid building recovery call expressions
593 /// if Sema is already doing so, which would cause infinite recursions.
594 bool IsBuildingRecoveryCallExpr;
596 /// Used to control the generation of ExprWithCleanups.
599 /// ExprCleanupObjects - This is the stack of objects requiring
600 /// cleanup that are created by the current full expression. The
601 /// element type here is ExprWithCleanups::Object.
602 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
604 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
605 /// to a variable (constant) that may or may not be odr-used in this Expr, and
606 /// we won't know until all lvalue-to-rvalue and discarded value conversions
607 /// have been applied to all subexpressions of the enclosing full expression.
608 /// This is cleared at the end of each full expression.
609 using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
610 MaybeODRUseExprSet MaybeODRUseExprs;
612 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
614 /// Stack containing information about each of the nested
615 /// function, block, and method scopes that are currently active.
616 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
618 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
619 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
622 /// ExtVectorDecls - This is a list all the extended vector types. This allows
623 /// us to associate a raw vector type with one of the ext_vector type names.
624 /// This is only necessary for issuing pretty diagnostics.
625 ExtVectorDeclsType ExtVectorDecls;
627 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
628 std::unique_ptr<CXXFieldCollector> FieldCollector;
630 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
632 /// Set containing all declared private fields that are not used.
633 NamedDeclSetType UnusedPrivateFields;
635 /// Set containing all typedefs that are likely unused.
636 llvm::SmallSetVector<const TypedefNameDecl *, 4>
637 UnusedLocalTypedefNameCandidates;
639 /// Delete-expressions to be analyzed at the end of translation unit
641 /// This list contains class members, and locations of delete-expressions
642 /// that could not be proven as to whether they mismatch with new-expression
643 /// used in initializer of the field.
644 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
645 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
646 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
648 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
650 /// PureVirtualClassDiagSet - a set of class declarations which we have
651 /// emitted a list of pure virtual functions. Used to prevent emitting the
652 /// same list more than once.
653 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
655 /// ParsingInitForAutoVars - a set of declarations with auto types for which
656 /// we are currently parsing the initializer.
657 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
659 /// Look for a locally scoped extern "C" declaration by the given name.
660 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
662 typedef LazyVector<VarDecl *, ExternalSemaSource,
663 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
664 TentativeDefinitionsType;
666 /// All the tentative definitions encountered in the TU.
667 TentativeDefinitionsType TentativeDefinitions;
669 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
670 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
671 UnusedFileScopedDeclsType;
673 /// The set of file scoped decls seen so far that have not been used
674 /// and must warn if not used. Only contains the first declaration.
675 UnusedFileScopedDeclsType UnusedFileScopedDecls;
677 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
678 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
679 DelegatingCtorDeclsType;
681 /// All the delegating constructors seen so far in the file, used for
682 /// cycle detection at the end of the TU.
683 DelegatingCtorDeclsType DelegatingCtorDecls;
685 /// All the overriding functions seen during a class definition
686 /// that had their exception spec checks delayed, plus the overridden
688 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
689 DelayedOverridingExceptionSpecChecks;
691 /// All the function redeclarations seen during a class definition that had
692 /// their exception spec checks delayed, plus the prior declaration they
693 /// should be checked against. Except during error recovery, the new decl
694 /// should always be a friend declaration, as that's the only valid way to
695 /// redeclare a special member before its class is complete.
696 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
697 DelayedEquivalentExceptionSpecChecks;
699 typedef llvm::MapVector<const FunctionDecl *,
700 std::unique_ptr<LateParsedTemplate>>
701 LateParsedTemplateMapT;
702 LateParsedTemplateMapT LateParsedTemplateMap;
704 /// Callback to the parser to parse templated functions when needed.
705 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
706 typedef void LateTemplateParserCleanupCB(void *P);
707 LateTemplateParserCB *LateTemplateParser;
708 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
711 void SetLateTemplateParser(LateTemplateParserCB *LTP,
712 LateTemplateParserCleanupCB *LTPCleanup,
714 LateTemplateParser = LTP;
715 LateTemplateParserCleanup = LTPCleanup;
719 class DelayedDiagnostics;
721 class DelayedDiagnosticsState {
722 sema::DelayedDiagnosticPool *SavedPool;
723 friend class Sema::DelayedDiagnostics;
725 typedef DelayedDiagnosticsState ParsingDeclState;
726 typedef DelayedDiagnosticsState ProcessingContextState;
728 /// A class which encapsulates the logic for delaying diagnostics
729 /// during parsing and other processing.
730 class DelayedDiagnostics {
731 /// The current pool of diagnostics into which delayed
732 /// diagnostics should go.
733 sema::DelayedDiagnosticPool *CurPool;
736 DelayedDiagnostics() : CurPool(nullptr) {}
738 /// Adds a delayed diagnostic.
739 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
741 /// Determines whether diagnostics should be delayed.
742 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
744 /// Returns the current delayed-diagnostics pool.
745 sema::DelayedDiagnosticPool *getCurrentPool() const {
749 /// Enter a new scope. Access and deprecation diagnostics will be
750 /// collected in this pool.
751 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
752 DelayedDiagnosticsState state;
753 state.SavedPool = CurPool;
758 /// Leave a delayed-diagnostic state that was previously pushed.
759 /// Do not emit any of the diagnostics. This is performed as part
760 /// of the bookkeeping of popping a pool "properly".
761 void popWithoutEmitting(DelayedDiagnosticsState state) {
762 CurPool = state.SavedPool;
765 /// Enter a new scope where access and deprecation diagnostics are
767 DelayedDiagnosticsState pushUndelayed() {
768 DelayedDiagnosticsState state;
769 state.SavedPool = CurPool;
774 /// Undo a previous pushUndelayed().
775 void popUndelayed(DelayedDiagnosticsState state) {
776 assert(CurPool == nullptr);
777 CurPool = state.SavedPool;
779 } DelayedDiagnostics;
781 /// A RAII object to temporarily push a declaration context.
785 DeclContext *SavedContext;
786 ProcessingContextState SavedContextState;
787 QualType SavedCXXThisTypeOverride;
790 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
791 : S(S), SavedContext(S.CurContext),
792 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
793 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
795 assert(ContextToPush && "pushing null context");
796 S.CurContext = ContextToPush;
798 S.CXXThisTypeOverride = QualType();
802 if (!SavedContext) return;
803 S.CurContext = SavedContext;
804 S.DelayedDiagnostics.popUndelayed(SavedContextState);
805 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
806 SavedContext = nullptr;
814 /// Used to change context to isConstantEvaluated without pushing a heavy
815 /// ExpressionEvaluationContextRecord object.
816 bool isConstantEvaluatedOverride;
818 bool isConstantEvaluated() {
819 return ExprEvalContexts.back().isConstantEvaluated() ||
820 isConstantEvaluatedOverride;
823 /// RAII object to handle the state changes required to synthesize
825 class SynthesizedFunctionScope {
827 Sema::ContextRAII SavedContext;
828 bool PushedCodeSynthesisContext = false;
831 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
832 : S(S), SavedContext(S, DC) {
833 S.PushFunctionScope();
834 S.PushExpressionEvaluationContext(
835 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
836 if (auto *FD = dyn_cast<FunctionDecl>(DC))
837 FD->setWillHaveBody(true);
839 assert(isa<ObjCMethodDecl>(DC));
842 void addContextNote(SourceLocation UseLoc) {
843 assert(!PushedCodeSynthesisContext);
845 Sema::CodeSynthesisContext Ctx;
846 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
847 Ctx.PointOfInstantiation = UseLoc;
848 Ctx.Entity = cast<Decl>(S.CurContext);
849 S.pushCodeSynthesisContext(Ctx);
851 PushedCodeSynthesisContext = true;
854 ~SynthesizedFunctionScope() {
855 if (PushedCodeSynthesisContext)
856 S.popCodeSynthesisContext();
857 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
858 FD->setWillHaveBody(false);
859 S.PopExpressionEvaluationContext();
860 S.PopFunctionScopeInfo();
864 /// WeakUndeclaredIdentifiers - Identifiers contained in
865 /// \#pragma weak before declared. rare. may alias another
866 /// identifier, declared or undeclared
867 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
869 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
870 /// \#pragma redefine_extname before declared. Used in Solaris system headers
871 /// to define functions that occur in multiple standards to call the version
872 /// in the currently selected standard.
873 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
876 /// Load weak undeclared identifiers from the external source.
877 void LoadExternalWeakUndeclaredIdentifiers();
879 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
880 /// \#pragma weak during processing of other Decls.
881 /// I couldn't figure out a clean way to generate these in-line, so
882 /// we store them here and handle separately -- which is a hack.
883 /// It would be best to refactor this.
884 SmallVector<Decl*,2> WeakTopLevelDecl;
886 IdentifierResolver IdResolver;
888 /// Translation Unit Scope - useful to Objective-C actions that need
889 /// to lookup file scope declarations in the "ordinary" C decl namespace.
890 /// For example, user-defined classes, built-in "id" type, etc.
893 /// The C++ "std" namespace, where the standard library resides.
894 LazyDeclPtr StdNamespace;
896 /// The C++ "std::bad_alloc" class, which is defined by the C++
897 /// standard library.
898 LazyDeclPtr StdBadAlloc;
900 /// The C++ "std::align_val_t" enum class, which is defined by the C++
901 /// standard library.
902 LazyDeclPtr StdAlignValT;
904 /// The C++ "std::experimental" namespace, where the experimental parts
905 /// of the standard library resides.
906 NamespaceDecl *StdExperimentalNamespaceCache;
908 /// The C++ "std::initializer_list" template, which is defined in
909 /// \<initializer_list>.
910 ClassTemplateDecl *StdInitializerList;
912 /// The C++ "std::coroutine_traits" template, which is defined in
913 /// \<coroutine_traits>
914 ClassTemplateDecl *StdCoroutineTraitsCache;
916 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
917 RecordDecl *CXXTypeInfoDecl;
919 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
920 RecordDecl *MSVCGuidDecl;
922 /// Caches identifiers/selectors for NSFoundation APIs.
923 std::unique_ptr<NSAPI> NSAPIObj;
925 /// The declaration of the Objective-C NSNumber class.
926 ObjCInterfaceDecl *NSNumberDecl;
928 /// The declaration of the Objective-C NSValue class.
929 ObjCInterfaceDecl *NSValueDecl;
931 /// Pointer to NSNumber type (NSNumber *).
932 QualType NSNumberPointer;
934 /// Pointer to NSValue type (NSValue *).
935 QualType NSValuePointer;
937 /// The Objective-C NSNumber methods used to create NSNumber literals.
938 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
940 /// The declaration of the Objective-C NSString class.
941 ObjCInterfaceDecl *NSStringDecl;
943 /// Pointer to NSString type (NSString *).
944 QualType NSStringPointer;
946 /// The declaration of the stringWithUTF8String: method.
947 ObjCMethodDecl *StringWithUTF8StringMethod;
949 /// The declaration of the valueWithBytes:objCType: method.
950 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
952 /// The declaration of the Objective-C NSArray class.
953 ObjCInterfaceDecl *NSArrayDecl;
955 /// The declaration of the arrayWithObjects:count: method.
956 ObjCMethodDecl *ArrayWithObjectsMethod;
958 /// The declaration of the Objective-C NSDictionary class.
959 ObjCInterfaceDecl *NSDictionaryDecl;
961 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
962 ObjCMethodDecl *DictionaryWithObjectsMethod;
964 /// id<NSCopying> type.
965 QualType QIDNSCopying;
967 /// will hold 'respondsToSelector:'
968 Selector RespondsToSelectorSel;
970 /// A flag to remember whether the implicit forms of operator new and delete
971 /// have been declared.
972 bool GlobalNewDeleteDeclared;
974 /// A flag to indicate that we're in a context that permits abstract
975 /// references to fields. This is really a
976 bool AllowAbstractFieldReference;
978 /// Describes how the expressions currently being parsed are
979 /// evaluated at run-time, if at all.
980 enum class ExpressionEvaluationContext {
981 /// The current expression and its subexpressions occur within an
982 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
983 /// \c sizeof, where the type of the expression may be significant but
984 /// no code will be generated to evaluate the value of the expression at
988 /// The current expression occurs within a braced-init-list within
989 /// an unevaluated operand. This is mostly like a regular unevaluated
990 /// context, except that we still instantiate constexpr functions that are
991 /// referenced here so that we can perform narrowing checks correctly.
994 /// The current expression occurs within a discarded statement.
995 /// This behaves largely similarly to an unevaluated operand in preventing
996 /// definitions from being required, but not in other ways.
999 /// The current expression occurs within an unevaluated
1000 /// operand that unconditionally permits abstract references to
1001 /// fields, such as a SIZE operator in MS-style inline assembly.
1002 UnevaluatedAbstract,
1004 /// The current context is "potentially evaluated" in C++11 terms,
1005 /// but the expression is evaluated at compile-time (like the values of
1006 /// cases in a switch statement).
1009 /// The current expression is potentially evaluated at run time,
1010 /// which means that code may be generated to evaluate the value of the
1011 /// expression at run time.
1012 PotentiallyEvaluated,
1014 /// The current expression is potentially evaluated, but any
1015 /// declarations referenced inside that expression are only used if
1016 /// in fact the current expression is used.
1018 /// This value is used when parsing default function arguments, for which
1019 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1020 /// through varargs) but do not want to mark declarations as "referenced"
1021 /// until the default argument is used.
1022 PotentiallyEvaluatedIfUsed
1025 /// Data structure used to record current or nested
1026 /// expression evaluation contexts.
1027 struct ExpressionEvaluationContextRecord {
1028 /// The expression evaluation context.
1029 ExpressionEvaluationContext Context;
1031 /// Whether the enclosing context needed a cleanup.
1032 CleanupInfo ParentCleanup;
1034 /// Whether we are in a decltype expression.
1037 /// The number of active cleanup objects when we entered
1038 /// this expression evaluation context.
1039 unsigned NumCleanupObjects;
1041 /// The number of typos encountered during this expression evaluation
1042 /// context (i.e. the number of TypoExprs created).
1045 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1047 /// The lambdas that are present within this context, if it
1048 /// is indeed an unevaluated context.
1049 SmallVector<LambdaExpr *, 2> Lambdas;
1051 /// The declaration that provides context for lambda expressions
1052 /// and block literals if the normal declaration context does not
1053 /// suffice, e.g., in a default function argument.
1054 Decl *ManglingContextDecl;
1056 /// If we are processing a decltype type, a set of call expressions
1057 /// for which we have deferred checking the completeness of the return type.
1058 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1060 /// If we are processing a decltype type, a set of temporary binding
1061 /// expressions for which we have deferred checking the destructor.
1062 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1064 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1066 /// Expressions appearing as the LHS of a volatile assignment in this
1067 /// context. We produce a warning for these when popping the context if
1068 /// they are not discarded-value expressions nor unevaluated operands.
1069 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1071 /// \brief Describes whether we are in an expression constext which we have
1072 /// to handle differently.
1073 enum ExpressionKind {
1074 EK_Decltype, EK_TemplateArgument, EK_Other
1077 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1078 unsigned NumCleanupObjects,
1079 CleanupInfo ParentCleanup,
1080 Decl *ManglingContextDecl,
1081 ExpressionKind ExprContext)
1082 : Context(Context), ParentCleanup(ParentCleanup),
1083 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1084 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1086 bool isUnevaluated() const {
1087 return Context == ExpressionEvaluationContext::Unevaluated ||
1088 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1089 Context == ExpressionEvaluationContext::UnevaluatedList;
1091 bool isConstantEvaluated() const {
1092 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1096 /// A stack of expression evaluation contexts.
1097 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1099 /// Emit a warning for all pending noderef expressions that we recorded.
1100 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1102 /// Compute the mangling number context for a lambda expression or
1103 /// block literal. Also return the extra mangling decl if any.
1105 /// \param DC - The DeclContext containing the lambda expression or
1107 std::tuple<MangleNumberingContext *, Decl *>
1108 getCurrentMangleNumberContext(const DeclContext *DC);
1111 /// SpecialMemberOverloadResult - The overloading result for a special member
1114 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1115 /// integer are used to determine whether overload resolution succeeded.
1116 class SpecialMemberOverloadResult {
1125 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1128 SpecialMemberOverloadResult() : Pair() {}
1129 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1130 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1132 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1133 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1135 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1136 void setKind(Kind K) { Pair.setInt(K); }
1139 class SpecialMemberOverloadResultEntry
1140 : public llvm::FastFoldingSetNode,
1141 public SpecialMemberOverloadResult {
1143 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1144 : FastFoldingSetNode(ID)
1148 /// A cache of special member function overload resolution results
1149 /// for C++ records.
1150 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1152 /// A cache of the flags available in enumerations with the flag_bits
1154 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1156 /// The kind of translation unit we are processing.
1158 /// When we're processing a complete translation unit, Sema will perform
1159 /// end-of-translation-unit semantic tasks (such as creating
1160 /// initializers for tentative definitions in C) once parsing has
1161 /// completed. Modules and precompiled headers perform different kinds of
1163 TranslationUnitKind TUKind;
1165 llvm::BumpPtrAllocator BumpAlloc;
1167 /// The number of SFINAE diagnostics that have been trapped.
1168 unsigned NumSFINAEErrors;
1170 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1171 UnparsedDefaultArgInstantiationsMap;
1173 /// A mapping from parameters with unparsed default arguments to the
1174 /// set of instantiations of each parameter.
1176 /// This mapping is a temporary data structure used when parsing
1177 /// nested class templates or nested classes of class templates,
1178 /// where we might end up instantiating an inner class before the
1179 /// default arguments of its methods have been parsed.
1180 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1182 // Contains the locations of the beginning of unparsed default
1183 // argument locations.
1184 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1186 /// UndefinedInternals - all the used, undefined objects which require a
1187 /// definition in this translation unit.
1188 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1190 /// Determine if VD, which must be a variable or function, is an external
1191 /// symbol that nonetheless can't be referenced from outside this translation
1192 /// unit because its type has no linkage and it's not extern "C".
1193 bool isExternalWithNoLinkageType(ValueDecl *VD);
1195 /// Obtain a sorted list of functions that are undefined but ODR-used.
1196 void getUndefinedButUsed(
1197 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1199 /// Retrieves list of suspicious delete-expressions that will be checked at
1200 /// the end of translation unit.
1201 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1202 getMismatchingDeleteExpressions() const;
1204 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1205 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1207 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1208 /// We need to maintain a list, since selectors can have differing signatures
1209 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1210 /// of selectors are "overloaded").
1211 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1212 /// methods inside categories with a particular selector.
1213 GlobalMethodPool MethodPool;
1215 /// Method selectors used in a \@selector expression. Used for implementation
1217 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1219 /// List of SourceLocations where 'self' is implicitly retained inside a
1221 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1222 ImplicitlyRetainedSelfLocs;
1224 /// Kinds of C++ special members.
1225 enum CXXSpecialMember {
1226 CXXDefaultConstructor,
1235 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1238 /// The C++ special members which we are currently in the process of
1239 /// declaring. If this process recursively triggers the declaration of the
1240 /// same special member, we should act as if it is not yet declared.
1241 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1243 /// Kinds of defaulted comparison operator functions.
1244 enum class DefaultedComparisonKind : unsigned char {
1245 /// This is not a defaultable comparison operator.
1247 /// This is an operator== that should be implemented as a series of
1248 /// subobject comparisons.
1250 /// This is an operator<=> that should be implemented as a series of
1251 /// subobject comparisons.
1253 /// This is an operator!= that should be implemented as a rewrite in terms
1254 /// of a == comparison.
1256 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1257 /// terms of a <=> comparison.
1261 /// The function definitions which were renamed as part of typo-correction
1262 /// to match their respective declarations. We want to keep track of them
1263 /// to ensure that we don't emit a "redefinition" error if we encounter a
1264 /// correctly named definition after the renamed definition.
1265 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1267 /// Stack of types that correspond to the parameter entities that are
1268 /// currently being copy-initialized. Can be empty.
1269 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1271 void ReadMethodPool(Selector Sel);
1272 void updateOutOfDateSelector(Selector Sel);
1274 /// Private Helper predicate to check for 'self'.
1275 bool isSelfExpr(Expr *RExpr);
1276 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1278 /// Cause the active diagnostic on the DiagosticsEngine to be
1279 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1280 /// should not be used elsewhere.
1281 void EmitCurrentDiagnostic(unsigned DiagID);
1283 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1285 class FPContractStateRAII {
1287 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1288 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1292 FPOptions OldFPFeaturesState;
1295 void addImplicitTypedef(StringRef Name, QualType T);
1297 bool WarnedStackExhausted = false;
1300 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1301 TranslationUnitKind TUKind = TU_Complete,
1302 CodeCompleteConsumer *CompletionConsumer = nullptr);
1305 /// Perform initialization that occurs after the parser has been
1306 /// initialized but before it parses anything.
1309 const LangOptions &getLangOpts() const { return LangOpts; }
1310 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1311 FPOptions &getFPOptions() { return FPFeatures; }
1313 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1314 SourceManager &getSourceManager() const { return SourceMgr; }
1315 Preprocessor &getPreprocessor() const { return PP; }
1316 ASTContext &getASTContext() const { return Context; }
1317 ASTConsumer &getASTConsumer() const { return Consumer; }
1318 ASTMutationListener *getASTMutationListener() const;
1319 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1321 ///Registers an external source. If an external source already exists,
1322 /// creates a multiplex external source and appends to it.
1324 ///\param[in] E - A non-null external sema source.
1326 void addExternalSource(ExternalSemaSource *E);
1328 void PrintStats() const;
1330 /// Warn that the stack is nearly exhausted.
1331 void warnStackExhausted(SourceLocation Loc);
1333 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1334 /// guaranteed). Produces a warning if we're low on stack space and allocates
1335 /// more in that case. Use this in code that may recurse deeply (for example,
1336 /// in template instantiation) to avoid stack overflow.
1337 void runWithSufficientStackSpace(SourceLocation Loc,
1338 llvm::function_ref<void()> Fn);
1340 /// Helper class that creates diagnostics with optional
1341 /// template instantiation stacks.
1343 /// This class provides a wrapper around the basic DiagnosticBuilder
1344 /// class that emits diagnostics. SemaDiagnosticBuilder is
1345 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1346 /// does) and, if the diagnostic comes from inside a template
1347 /// instantiation, printing the template instantiation stack as
1349 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1354 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1355 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1357 // This is a cunning lie. DiagnosticBuilder actually performs move
1358 // construction in its copy constructor (but due to varied uses, it's not
1359 // possible to conveniently express this as actual move construction). So
1360 // the default copy ctor here is fine, because the base class disables the
1361 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1362 // in that case anwyay.
1363 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1365 ~SemaDiagnosticBuilder() {
1366 // If we aren't active, there is nothing to do.
1367 if (!isActive()) return;
1369 // Otherwise, we need to emit the diagnostic. First flush the underlying
1370 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1371 // won't emit the diagnostic in its own destructor.
1373 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1374 // do its own needless checks to see if the diagnostic needs to be
1375 // emitted. However, because we take care to ensure that the builder
1376 // objects never escape, a sufficiently smart compiler will be able to
1377 // eliminate that code.
1381 // Dispatch to Sema to emit the diagnostic.
1382 SemaRef.EmitCurrentDiagnostic(DiagID);
1385 /// Teach operator<< to produce an object of the correct type.
1386 template<typename T>
1387 friend const SemaDiagnosticBuilder &operator<<(
1388 const SemaDiagnosticBuilder &Diag, const T &Value) {
1389 const DiagnosticBuilder &BaseDiag = Diag;
1395 /// Emit a diagnostic.
1396 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1397 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1398 return SemaDiagnosticBuilder(DB, *this, DiagID);
1401 /// Emit a partial diagnostic.
1402 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1404 /// Build a partial diagnostic.
1405 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1407 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1409 /// Get a string to suggest for zero-initialization of a type.
1411 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1412 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1414 /// Calls \c Lexer::getLocForEndOfToken()
1415 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1417 /// Retrieve the module loader associated with the preprocessor.
1418 ModuleLoader &getModuleLoader() const;
1420 void emitAndClearUnusedLocalTypedefWarnings();
1422 enum TUFragmentKind {
1423 /// The global module fragment, between 'module;' and a module-declaration.
1425 /// A normal translation unit fragment. For a non-module unit, this is the
1426 /// entire translation unit. Otherwise, it runs from the module-declaration
1427 /// to the private-module-fragment (if any) or the end of the TU (if not).
1429 /// The private module fragment, between 'module :private;' and the end of
1430 /// the translation unit.
1434 void ActOnStartOfTranslationUnit();
1435 void ActOnEndOfTranslationUnit();
1436 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1438 void CheckDelegatingCtorCycles();
1440 Scope *getScopeForContext(DeclContext *Ctx);
1442 void PushFunctionScope();
1443 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1444 sema::LambdaScopeInfo *PushLambdaScope();
1446 /// This is used to inform Sema what the current TemplateParameterDepth
1447 /// is during Parsing. Currently it is used to pass on the depth
1448 /// when parsing generic lambda 'auto' parameters.
1449 void RecordParsingTemplateParameterDepth(unsigned Depth);
1451 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1452 RecordDecl *RD, CapturedRegionKind K,
1453 unsigned OpenMPCaptureLevel = 0);
1455 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1456 /// time after they've been popped.
1457 class PoppedFunctionScopeDeleter {
1461 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1462 void operator()(sema::FunctionScopeInfo *Scope) const;
1465 using PoppedFunctionScopePtr =
1466 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1468 PoppedFunctionScopePtr
1469 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1470 const Decl *D = nullptr,
1471 QualType BlockType = QualType());
1473 sema::FunctionScopeInfo *getCurFunction() const {
1474 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1477 sema::FunctionScopeInfo *getEnclosingFunction() const;
1479 void setFunctionHasBranchIntoScope();
1480 void setFunctionHasBranchProtectedScope();
1481 void setFunctionHasIndirectGoto();
1483 void PushCompoundScope(bool IsStmtExpr);
1484 void PopCompoundScope();
1486 sema::CompoundScopeInfo &getCurCompoundScope() const;
1488 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1490 /// Retrieve the current block, if any.
1491 sema::BlockScopeInfo *getCurBlock();
1493 /// Get the innermost lambda enclosing the current location, if any. This
1494 /// looks through intervening non-lambda scopes such as local functions and
1496 sema::LambdaScopeInfo *getEnclosingLambda() const;
1498 /// Retrieve the current lambda scope info, if any.
1499 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1500 /// lambda scope info ignoring all inner capturing scopes that are not
1502 sema::LambdaScopeInfo *
1503 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1505 /// Retrieve the current generic lambda info, if any.
1506 sema::LambdaScopeInfo *getCurGenericLambda();
1508 /// Retrieve the current captured region, if any.
1509 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1511 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1512 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1514 void ActOnComment(SourceRange Comment);
1516 //===--------------------------------------------------------------------===//
1517 // Type Analysis / Processing: SemaType.cpp.
1520 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1521 const DeclSpec *DS = nullptr);
1522 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1523 const DeclSpec *DS = nullptr);
1524 QualType BuildPointerType(QualType T,
1525 SourceLocation Loc, DeclarationName Entity);
1526 QualType BuildReferenceType(QualType T, bool LValueRef,
1527 SourceLocation Loc, DeclarationName Entity);
1528 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1529 Expr *ArraySize, unsigned Quals,
1530 SourceRange Brackets, DeclarationName Entity);
1531 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1532 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1533 SourceLocation AttrLoc);
1534 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1535 SourceLocation AttrLoc);
1537 /// Same as above, but constructs the AddressSpace index if not provided.
1538 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1539 SourceLocation AttrLoc);
1541 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1543 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1545 /// Build a function type.
1547 /// This routine checks the function type according to C++ rules and
1548 /// under the assumption that the result type and parameter types have
1549 /// just been instantiated from a template. It therefore duplicates
1550 /// some of the behavior of GetTypeForDeclarator, but in a much
1551 /// simpler form that is only suitable for this narrow use case.
1553 /// \param T The return type of the function.
1555 /// \param ParamTypes The parameter types of the function. This array
1556 /// will be modified to account for adjustments to the types of the
1557 /// function parameters.
1559 /// \param Loc The location of the entity whose type involves this
1560 /// function type or, if there is no such entity, the location of the
1561 /// type that will have function type.
1563 /// \param Entity The name of the entity that involves the function
1566 /// \param EPI Extra information about the function type. Usually this will
1567 /// be taken from an existing function with the same prototype.
1569 /// \returns A suitable function type, if there are no errors. The
1570 /// unqualified type will always be a FunctionProtoType.
1571 /// Otherwise, returns a NULL type.
1572 QualType BuildFunctionType(QualType T,
1573 MutableArrayRef<QualType> ParamTypes,
1574 SourceLocation Loc, DeclarationName Entity,
1575 const FunctionProtoType::ExtProtoInfo &EPI);
1577 QualType BuildMemberPointerType(QualType T, QualType Class,
1579 DeclarationName Entity);
1580 QualType BuildBlockPointerType(QualType T,
1581 SourceLocation Loc, DeclarationName Entity);
1582 QualType BuildParenType(QualType T);
1583 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1584 QualType BuildReadPipeType(QualType T,
1585 SourceLocation Loc);
1586 QualType BuildWritePipeType(QualType T,
1587 SourceLocation Loc);
1589 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1590 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1592 /// Package the given type and TSI into a ParsedType.
1593 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1594 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1595 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1596 static QualType GetTypeFromParser(ParsedType Ty,
1597 TypeSourceInfo **TInfo = nullptr);
1598 CanThrowResult canThrow(const Expr *E);
1599 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1600 const FunctionProtoType *FPT);
1601 void UpdateExceptionSpec(FunctionDecl *FD,
1602 const FunctionProtoType::ExceptionSpecInfo &ESI);
1603 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1604 bool CheckDistantExceptionSpec(QualType T);
1605 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1606 bool CheckEquivalentExceptionSpec(
1607 const FunctionProtoType *Old, SourceLocation OldLoc,
1608 const FunctionProtoType *New, SourceLocation NewLoc);
1609 bool CheckEquivalentExceptionSpec(
1610 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1611 const FunctionProtoType *Old, SourceLocation OldLoc,
1612 const FunctionProtoType *New, SourceLocation NewLoc);
1613 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1614 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1615 const PartialDiagnostic &NestedDiagID,
1616 const PartialDiagnostic &NoteID,
1617 const PartialDiagnostic &NoThrowDiagID,
1618 const FunctionProtoType *Superset,
1619 SourceLocation SuperLoc,
1620 const FunctionProtoType *Subset,
1621 SourceLocation SubLoc);
1622 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1623 const PartialDiagnostic &NoteID,
1624 const FunctionProtoType *Target,
1625 SourceLocation TargetLoc,
1626 const FunctionProtoType *Source,
1627 SourceLocation SourceLoc);
1629 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1631 /// The parser has parsed the context-sensitive type 'instancetype'
1632 /// in an Objective-C message declaration. Return the appropriate type.
1633 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1635 /// Abstract class used to diagnose incomplete types.
1636 struct TypeDiagnoser {
1639 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1640 virtual ~TypeDiagnoser() {}
1643 static int getPrintable(int I) { return I; }
1644 static unsigned getPrintable(unsigned I) { return I; }
1645 static bool getPrintable(bool B) { return B; }
1646 static const char * getPrintable(const char *S) { return S; }
1647 static StringRef getPrintable(StringRef S) { return S; }
1648 static const std::string &getPrintable(const std::string &S) { return S; }
1649 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1652 static DeclarationName getPrintable(DeclarationName N) { return N; }
1653 static QualType getPrintable(QualType T) { return T; }
1654 static SourceRange getPrintable(SourceRange R) { return R; }
1655 static SourceRange getPrintable(SourceLocation L) { return L; }
1656 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1657 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1659 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1661 std::tuple<const Ts &...> Args;
1663 template <std::size_t... Is>
1664 void emit(const SemaDiagnosticBuilder &DB,
1665 std::index_sequence<Is...>) const {
1666 // Apply all tuple elements to the builder in order.
1667 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1672 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1673 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1674 assert(DiagID != 0 && "no diagnostic for type diagnoser");
1677 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1678 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1679 emit(DB, std::index_sequence_for<Ts...>());
1685 /// Methods for marking which expressions involve dereferencing a pointer
1686 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1687 /// they are parsed, meaning that a noderef pointer may not be accessed. For
1688 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1689 /// `*p`, but need to check that `address of` is called on it. This requires
1690 /// keeping a container of all pending expressions and checking if the address
1691 /// of them are eventually taken.
1692 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1693 void CheckAddressOfNoDeref(const Expr *E);
1694 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1696 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1697 TypeDiagnoser *Diagnoser);
1699 struct ModuleScope {
1700 SourceLocation BeginLoc;
1701 clang::Module *Module = nullptr;
1702 bool ModuleInterface = false;
1703 bool ImplicitGlobalModuleFragment = false;
1704 VisibleModuleSet OuterVisibleModules;
1706 /// The modules we're currently parsing.
1707 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1709 /// Namespace definitions that we will export when they finish.
1710 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1712 /// Get the module whose scope we are currently within.
1713 Module *getCurrentModule() const {
1714 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1717 VisibleModuleSet VisibleModules;
1720 /// Get the module owning an entity.
1721 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1723 /// Make a merged definition of an existing hidden definition \p ND
1724 /// visible at the specified location.
1725 void makeMergedDefinitionVisible(NamedDecl *ND);
1727 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1729 /// Determine whether a declaration is visible to name lookup.
1730 bool isVisible(const NamedDecl *D) {
1731 return !D->isHidden() || isVisibleSlow(D);
1734 /// Determine whether any declaration of an entity is visible.
1736 hasVisibleDeclaration(const NamedDecl *D,
1737 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1738 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1740 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1741 llvm::SmallVectorImpl<Module *> *Modules);
1743 bool hasVisibleMergedDefinition(NamedDecl *Def);
1744 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1746 /// Determine if \p D and \p Suggested have a structurally compatible
1747 /// layout as described in C11 6.2.7/1.
1748 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1750 /// Determine if \p D has a visible definition. If not, suggest a declaration
1751 /// that should be made visible to expose the definition.
1752 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1753 bool OnlyNeedComplete = false);
1754 bool hasVisibleDefinition(const NamedDecl *D) {
1756 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1759 /// Determine if the template parameter \p D has a visible default argument.
1761 hasVisibleDefaultArgument(const NamedDecl *D,
1762 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1764 /// Determine if there is a visible declaration of \p D that is an explicit
1765 /// specialization declaration for a specialization of a template. (For a
1766 /// member specialization, use hasVisibleMemberSpecialization.)
1767 bool hasVisibleExplicitSpecialization(
1768 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1770 /// Determine if there is a visible declaration of \p D that is a member
1771 /// specialization declaration (as opposed to an instantiated declaration).
1772 bool hasVisibleMemberSpecialization(
1773 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1775 /// Determine if \p A and \p B are equivalent internal linkage declarations
1776 /// from different modules, and thus an ambiguity error can be downgraded to
1777 /// an extension warning.
1778 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1779 const NamedDecl *B);
1780 void diagnoseEquivalentInternalLinkageDeclarations(
1781 SourceLocation Loc, const NamedDecl *D,
1782 ArrayRef<const NamedDecl *> Equiv);
1784 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1786 bool isCompleteType(SourceLocation Loc, QualType T) {
1787 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1789 bool RequireCompleteType(SourceLocation Loc, QualType T,
1790 TypeDiagnoser &Diagnoser);
1791 bool RequireCompleteType(SourceLocation Loc, QualType T,
1794 template <typename... Ts>
1795 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1796 const Ts &...Args) {
1797 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1798 return RequireCompleteType(Loc, T, Diagnoser);
1801 void completeExprArrayBound(Expr *E);
1802 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1803 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1805 template <typename... Ts>
1806 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1807 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1808 return RequireCompleteExprType(E, Diagnoser);
1811 bool RequireLiteralType(SourceLocation Loc, QualType T,
1812 TypeDiagnoser &Diagnoser);
1813 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1815 template <typename... Ts>
1816 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1817 const Ts &...Args) {
1818 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1819 return RequireLiteralType(Loc, T, Diagnoser);
1822 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1823 const CXXScopeSpec &SS, QualType T,
1824 TagDecl *OwnedTagDecl = nullptr);
1826 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1827 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1828 /// context, such as when building a type for decltype(auto).
1829 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1830 bool AsUnevaluated = true);
1831 QualType BuildUnaryTransformType(QualType BaseType,
1832 UnaryTransformType::UTTKind UKind,
1833 SourceLocation Loc);
1835 //===--------------------------------------------------------------------===//
1836 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1839 struct SkipBodyInfo {
1841 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1844 bool CheckSameAsPrevious;
1845 NamedDecl *Previous;
1849 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1851 void DiagnoseUseOfUnimplementedSelectors();
1853 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1855 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1856 Scope *S, CXXScopeSpec *SS = nullptr,
1857 bool isClassName = false, bool HasTrailingDot = false,
1858 ParsedType ObjectType = nullptr,
1859 bool IsCtorOrDtorName = false,
1860 bool WantNontrivialTypeSourceInfo = false,
1861 bool IsClassTemplateDeductionContext = true,
1862 IdentifierInfo **CorrectedII = nullptr);
1863 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1864 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1865 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1866 SourceLocation IILoc,
1869 ParsedType &SuggestedType,
1870 bool IsTemplateName = false);
1872 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1873 /// type name has failed in a dependent context. In these situations, we
1874 /// automatically form a DependentTypeName that will retry lookup in a related
1875 /// scope during instantiation.
1876 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1877 SourceLocation NameLoc,
1878 bool IsTemplateTypeArg);
1880 /// Describes the result of the name lookup and resolution performed
1881 /// by \c ClassifyName().
1882 enum NameClassificationKind {
1883 /// This name is not a type or template in this context, but might be
1886 /// Classification failed; an error has been produced.
1888 /// The name has been typo-corrected to a keyword.
1890 /// The name was classified as a type.
1892 /// The name was classified as a specific non-type, non-template
1893 /// declaration. ActOnNameClassifiedAsNonType should be called to
1894 /// convert the declaration to an expression.
1896 /// The name was classified as an ADL-only function name.
1897 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
1898 /// result to an expression.
1899 NC_UndeclaredNonType,
1900 /// The name denotes a member of a dependent type that could not be
1901 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
1902 /// convert the result to an expression.
1903 NC_DependentNonType,
1904 /// The name was classified as a non-type, and an expression representing
1905 /// that name has been formed.
1906 NC_ContextIndependentExpr,
1907 /// The name was classified as a template whose specializations are types.
1909 /// The name was classified as a variable template name.
1911 /// The name was classified as a function template name.
1912 NC_FunctionTemplate,
1913 /// The name was classified as an ADL-only function template name.
1914 NC_UndeclaredTemplate,
1917 class NameClassification {
1918 NameClassificationKind Kind;
1921 NamedDecl *NonTypeDecl;
1922 TemplateName Template;
1926 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1929 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1931 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1933 static NameClassification Error() {
1934 return NameClassification(NC_Error);
1937 static NameClassification Unknown() {
1938 return NameClassification(NC_Unknown);
1941 static NameClassification ContextIndependentExpr(ExprResult E) {
1942 NameClassification Result(NC_ContextIndependentExpr);
1947 static NameClassification NonType(NamedDecl *D) {
1948 NameClassification Result(NC_NonType);
1949 Result.NonTypeDecl = D;
1953 static NameClassification UndeclaredNonType() {
1954 return NameClassification(NC_UndeclaredNonType);
1957 static NameClassification DependentNonType() {
1958 return NameClassification(NC_DependentNonType);
1961 static NameClassification TypeTemplate(TemplateName Name) {
1962 NameClassification Result(NC_TypeTemplate);
1963 Result.Template = Name;
1967 static NameClassification VarTemplate(TemplateName Name) {
1968 NameClassification Result(NC_VarTemplate);
1969 Result.Template = Name;
1973 static NameClassification FunctionTemplate(TemplateName Name) {
1974 NameClassification Result(NC_FunctionTemplate);
1975 Result.Template = Name;
1979 static NameClassification UndeclaredTemplate(TemplateName Name) {
1980 NameClassification Result(NC_UndeclaredTemplate);
1981 Result.Template = Name;
1985 NameClassificationKind getKind() const { return Kind; }
1987 ExprResult getExpression() const {
1988 assert(Kind == NC_ContextIndependentExpr);
1992 ParsedType getType() const {
1993 assert(Kind == NC_Type);
1997 NamedDecl *getNonTypeDecl() const {
1998 assert(Kind == NC_NonType);
2002 TemplateName getTemplateName() const {
2003 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2004 Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate);
2008 TemplateNameKind getTemplateNameKind() const {
2010 case NC_TypeTemplate:
2011 return TNK_Type_template;
2012 case NC_FunctionTemplate:
2013 return TNK_Function_template;
2014 case NC_VarTemplate:
2015 return TNK_Var_template;
2016 case NC_UndeclaredTemplate:
2017 return TNK_Undeclared_template;
2019 llvm_unreachable("unsupported name classification.");
2024 /// Perform name lookup on the given name, classifying it based on
2025 /// the results of name lookup and the following token.
2027 /// This routine is used by the parser to resolve identifiers and help direct
2028 /// parsing. When the identifier cannot be found, this routine will attempt
2029 /// to correct the typo and classify based on the resulting name.
2031 /// \param S The scope in which we're performing name lookup.
2033 /// \param SS The nested-name-specifier that precedes the name.
2035 /// \param Name The identifier. If typo correction finds an alternative name,
2036 /// this pointer parameter will be updated accordingly.
2038 /// \param NameLoc The location of the identifier.
2040 /// \param NextToken The token following the identifier. Used to help
2041 /// disambiguate the name.
2043 /// \param CCC The correction callback, if typo correction is desired.
2044 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2045 IdentifierInfo *&Name, SourceLocation NameLoc,
2046 const Token &NextToken,
2047 CorrectionCandidateCallback *CCC = nullptr);
2049 /// Act on the result of classifying a name as an undeclared (ADL-only)
2050 /// non-type declaration.
2051 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2052 SourceLocation NameLoc);
2053 /// Act on the result of classifying a name as an undeclared member of a
2054 /// dependent base class.
2055 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2056 IdentifierInfo *Name,
2057 SourceLocation NameLoc,
2058 bool IsAddressOfOperand);
2059 /// Act on the result of classifying a name as a specific non-type
2061 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2063 SourceLocation NameLoc,
2064 const Token &NextToken);
2066 /// Describes the detailed kind of a template name. Used in diagnostics.
2067 enum class TemplateNameKindForDiagnostics {
2072 TemplateTemplateParam,
2076 TemplateNameKindForDiagnostics
2077 getTemplateNameKindForDiagnostics(TemplateName Name);
2079 /// Determine whether it's plausible that E was intended to be a
2081 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2082 if (!getLangOpts().CPlusPlus || E.isInvalid())
2085 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2086 return !DRE->hasExplicitTemplateArgs();
2087 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2088 return !ME->hasExplicitTemplateArgs();
2090 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2091 return !DSDRE->hasExplicitTemplateArgs();
2092 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2093 return !DSME->hasExplicitTemplateArgs();
2094 // Any additional cases recognized here should also be handled by
2095 // diagnoseExprIntendedAsTemplateName.
2098 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2099 SourceLocation Less,
2100 SourceLocation Greater);
2102 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2104 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2105 MultiTemplateParamsArg TemplateParameterLists);
2106 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2107 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2108 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2109 DeclarationName Name, SourceLocation Loc,
2112 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2113 SourceLocation FallbackLoc,
2114 SourceLocation ConstQualLoc = SourceLocation(),
2115 SourceLocation VolatileQualLoc = SourceLocation(),
2116 SourceLocation RestrictQualLoc = SourceLocation(),
2117 SourceLocation AtomicQualLoc = SourceLocation(),
2118 SourceLocation UnalignedQualLoc = SourceLocation());
2120 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2121 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2122 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2123 const LookupResult &R);
2124 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2125 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2126 const LookupResult &R);
2127 void CheckShadow(Scope *S, VarDecl *D);
2129 /// Warn if 'E', which is an expression that is about to be modified, refers
2130 /// to a shadowing declaration.
2131 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2133 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2136 /// Map of current shadowing declarations to shadowed declarations. Warn if
2137 /// it looks like the user is trying to modify the shadowing declaration.
2138 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2141 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2142 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2143 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2144 TypedefNameDecl *NewTD);
2145 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2146 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2147 TypeSourceInfo *TInfo,
2148 LookupResult &Previous);
2149 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2150 LookupResult &Previous, bool &Redeclaration);
2151 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2152 TypeSourceInfo *TInfo,
2153 LookupResult &Previous,
2154 MultiTemplateParamsArg TemplateParamLists,
2156 ArrayRef<BindingDecl *> Bindings = None);
2158 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2159 MultiTemplateParamsArg TemplateParamLists);
2160 // Returns true if the variable declaration is a redeclaration
2161 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2162 void CheckVariableDeclarationType(VarDecl *NewVD);
2163 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2165 void CheckCompleteVariableDeclaration(VarDecl *VD);
2166 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2167 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2169 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2170 TypeSourceInfo *TInfo,
2171 LookupResult &Previous,
2172 MultiTemplateParamsArg TemplateParamLists,
2174 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2176 enum class CheckConstexprKind {
2177 /// Diagnose issues that are non-constant or that are extensions.
2179 /// Identify whether this function satisfies the formal rules for constexpr
2180 /// functions in the current lanugage mode (with no extensions).
2184 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2185 CheckConstexprKind Kind);
2187 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2188 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2189 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2190 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2191 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2192 // Returns true if the function declaration is a redeclaration
2193 bool CheckFunctionDeclaration(Scope *S,
2194 FunctionDecl *NewFD, LookupResult &Previous,
2195 bool IsMemberSpecialization);
2196 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2197 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2198 QualType NewT, QualType OldT);
2199 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2200 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2201 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2203 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2204 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2205 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2208 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2209 SourceLocation NameLoc, IdentifierInfo *Name,
2210 QualType T, TypeSourceInfo *TSInfo,
2212 void ActOnParamDefaultArgument(Decl *param,
2213 SourceLocation EqualLoc,
2215 void ActOnParamUnparsedDefaultArgument(Decl *param,
2216 SourceLocation EqualLoc,
2217 SourceLocation ArgLoc);
2218 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2219 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2220 SourceLocation EqualLoc);
2222 // Contexts where using non-trivial C union types can be disallowed. This is
2223 // passed to err_non_trivial_c_union_in_invalid_context.
2224 enum NonTrivialCUnionContext {
2225 // Function parameter.
2226 NTCUC_FunctionParam,
2228 NTCUC_FunctionReturn,
2229 // Default-initialized object.
2230 NTCUC_DefaultInitializedObject,
2231 // Variable with automatic storage duration.
2233 // Initializer expression that might copy from another object.
2237 // Compound literal.
2238 NTCUC_CompoundLiteral,
2241 // lvalue-to-rvalue conversion of volatile type.
2242 NTCUC_LValueToRValueVolatile,
2245 /// Emit diagnostics if the initializer or any of its explicit or
2246 /// implicitly-generated subexpressions require copying or
2247 /// default-initializing a type that is or contains a C union type that is
2248 /// non-trivial to copy or default-initialize.
2249 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2251 // These flags are passed to checkNonTrivialCUnion.
2252 enum NonTrivialCUnionKind {
2254 NTCUK_Destruct = 0x2,
2258 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2259 /// a non-trivial C union is used in an invalid context.
2260 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2261 NonTrivialCUnionContext UseContext,
2262 unsigned NonTrivialKind);
2264 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2265 void ActOnUninitializedDecl(Decl *dcl);
2266 void ActOnInitializerError(Decl *Dcl);
2268 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2269 void ActOnCXXForRangeDecl(Decl *D);
2270 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2271 IdentifierInfo *Ident,
2272 ParsedAttributes &Attrs,
2273 SourceLocation AttrEnd);
2274 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2275 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2276 void CheckStaticLocalForDllExport(VarDecl *VD);
2277 void FinalizeDeclaration(Decl *D);
2278 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2279 ArrayRef<Decl *> Group);
2280 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2282 /// Should be called on all declarations that might have attached
2283 /// documentation comments.
2284 void ActOnDocumentableDecl(Decl *D);
2285 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2287 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2288 SourceLocation LocAfterDecls);
2289 void CheckForFunctionRedefinition(
2290 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2291 SkipBodyInfo *SkipBody = nullptr);
2292 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2293 MultiTemplateParamsArg TemplateParamLists,
2294 SkipBodyInfo *SkipBody = nullptr);
2295 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2296 SkipBodyInfo *SkipBody = nullptr);
2297 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2298 bool isObjCMethodDecl(Decl *D) {
2299 return D && isa<ObjCMethodDecl>(D);
2302 /// Determine whether we can delay parsing the body of a function or
2303 /// function template until it is used, assuming we don't care about emitting
2304 /// code for that function.
2306 /// This will be \c false if we may need the body of the function in the
2307 /// middle of parsing an expression (where it's impractical to switch to
2308 /// parsing a different function), for instance, if it's constexpr in C++11
2309 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2310 bool canDelayFunctionBody(const Declarator &D);
2312 /// Determine whether we can skip parsing the body of a function
2313 /// definition, assuming we don't care about analyzing its body or emitting
2314 /// code for that function.
2316 /// This will be \c false only if we may need the body of the function in
2317 /// order to parse the rest of the program (for instance, if it is
2318 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2319 bool canSkipFunctionBody(Decl *D);
2321 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2322 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2323 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2324 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2325 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2327 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2328 /// attribute for which parsing is delayed.
2329 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2331 /// Diagnose any unused parameters in the given sequence of
2332 /// ParmVarDecl pointers.
2333 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2335 /// Diagnose whether the size of parameters or return value of a
2336 /// function or obj-c method definition is pass-by-value and larger than a
2337 /// specified threshold.
2339 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2340 QualType ReturnTy, NamedDecl *D);
2342 void DiagnoseInvalidJumps(Stmt *Body);
2343 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2344 SourceLocation AsmLoc,
2345 SourceLocation RParenLoc);
2347 /// Handle a C++11 empty-declaration and attribute-declaration.
2348 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2349 SourceLocation SemiLoc);
2351 enum class ModuleDeclKind {
2352 Interface, ///< 'export module X;'
2353 Implementation, ///< 'module X;'
2356 /// The parser has processed a module-declaration that begins the definition
2357 /// of a module interface or implementation.
2358 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2359 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2360 ModuleIdPath Path, bool IsFirstDecl);
2362 /// The parser has processed a global-module-fragment declaration that begins
2363 /// the definition of the global module fragment of the current module unit.
2364 /// \param ModuleLoc The location of the 'module' keyword.
2365 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2367 /// The parser has processed a private-module-fragment declaration that begins
2368 /// the definition of the private module fragment of the current module unit.
2369 /// \param ModuleLoc The location of the 'module' keyword.
2370 /// \param PrivateLoc The location of the 'private' keyword.
2371 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2372 SourceLocation PrivateLoc);
2374 /// The parser has processed a module import declaration.
2376 /// \param StartLoc The location of the first token in the declaration. This
2377 /// could be the location of an '@', 'export', or 'import'.
2378 /// \param ExportLoc The location of the 'export' keyword, if any.
2379 /// \param ImportLoc The location of the 'import' keyword.
2380 /// \param Path The module access path.
2381 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2382 SourceLocation ExportLoc,
2383 SourceLocation ImportLoc, ModuleIdPath Path);
2384 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2385 SourceLocation ExportLoc,
2386 SourceLocation ImportLoc, Module *M,
2387 ModuleIdPath Path = {});
2389 /// The parser has processed a module import translated from a
2390 /// #include or similar preprocessing directive.
2391 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2392 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2394 /// The parsed has entered a submodule.
2395 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2396 /// The parser has left a submodule.
2397 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2399 /// Create an implicit import of the given module at the given
2400 /// source location, for error recovery, if possible.
2402 /// This routine is typically used when an entity found by name lookup
2403 /// is actually hidden within a module that we know about but the user
2404 /// has forgotten to import.
2405 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2408 /// Kinds of missing import. Note, the values of these enumerators correspond
2409 /// to %select values in diagnostics.
2410 enum class MissingImportKind {
2414 ExplicitSpecialization,
2415 PartialSpecialization
2418 /// Diagnose that the specified declaration needs to be visible but
2419 /// isn't, and suggest a module import that would resolve the problem.
2420 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2421 MissingImportKind MIK, bool Recover = true);
2422 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2423 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2424 MissingImportKind MIK, bool Recover);
2426 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2427 SourceLocation LBraceLoc);
2428 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2429 SourceLocation RBraceLoc);
2431 /// We've found a use of a templated declaration that would trigger an
2432 /// implicit instantiation. Check that any relevant explicit specializations
2433 /// and partial specializations are visible, and diagnose if not.
2434 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2436 /// We've found a use of a template specialization that would select a
2437 /// partial specialization. Check that the partial specialization is visible,
2438 /// and diagnose if not.
2439 void checkPartialSpecializationVisibility(SourceLocation Loc,
2442 /// Retrieve a suitable printing policy for diagnostics.
2443 PrintingPolicy getPrintingPolicy() const {
2444 return getPrintingPolicy(Context, PP);
2447 /// Retrieve a suitable printing policy for diagnostics.
2448 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2449 const Preprocessor &PP);
2452 void ActOnPopScope(SourceLocation Loc, Scope *S);
2453 void ActOnTranslationUnitScope(Scope *S);
2455 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2456 RecordDecl *&AnonRecord);
2457 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2458 MultiTemplateParamsArg TemplateParams,
2459 bool IsExplicitInstantiation,
2460 RecordDecl *&AnonRecord);
2462 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2465 const PrintingPolicy &Policy);
2467 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2468 RecordDecl *Record);
2470 /// Common ways to introduce type names without a tag for use in diagnostics.
2471 /// Keep in sync with err_tag_reference_non_tag.
2480 NTK_TypeAliasTemplate,
2481 NTK_TemplateTemplateArgument,
2484 /// Given a non-tag type declaration, returns an enum useful for indicating
2485 /// what kind of non-tag type this is.
2486 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2488 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2489 TagTypeKind NewTag, bool isDefinition,
2490 SourceLocation NewTagLoc,
2491 const IdentifierInfo *Name);
2494 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2495 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2496 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2497 TUK_Friend // Friend declaration: 'friend struct foo;'
2500 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2501 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2502 SourceLocation NameLoc, const ParsedAttributesView &Attr,
2503 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2504 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2505 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2506 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2507 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2508 SkipBodyInfo *SkipBody = nullptr);
2510 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2511 unsigned TagSpec, SourceLocation TagLoc,
2512 CXXScopeSpec &SS, IdentifierInfo *Name,
2513 SourceLocation NameLoc,
2514 const ParsedAttributesView &Attr,
2515 MultiTemplateParamsArg TempParamLists);
2517 TypeResult ActOnDependentTag(Scope *S,
2520 const CXXScopeSpec &SS,
2521 IdentifierInfo *Name,
2522 SourceLocation TagLoc,
2523 SourceLocation NameLoc);
2525 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2526 IdentifierInfo *ClassName,
2527 SmallVectorImpl<Decl *> &Decls);
2528 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2529 Declarator &D, Expr *BitfieldWidth);
2531 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2532 Declarator &D, Expr *BitfieldWidth,
2533 InClassInitStyle InitStyle,
2534 AccessSpecifier AS);
2535 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2536 SourceLocation DeclStart, Declarator &D,
2537 Expr *BitfieldWidth,
2538 InClassInitStyle InitStyle,
2540 const ParsedAttr &MSPropertyAttr);
2542 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2543 TypeSourceInfo *TInfo,
2544 RecordDecl *Record, SourceLocation Loc,
2545 bool Mutable, Expr *BitfieldWidth,
2546 InClassInitStyle InitStyle,
2547 SourceLocation TSSL,
2548 AccessSpecifier AS, NamedDecl *PrevDecl,
2549 Declarator *D = nullptr);
2551 bool CheckNontrivialField(FieldDecl *FD);
2552 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2554 enum TrivialABIHandling {
2555 /// The triviality of a method unaffected by "trivial_abi".
2556 TAH_IgnoreTrivialABI,
2558 /// The triviality of a method affected by "trivial_abi".
2559 TAH_ConsiderTrivialABI
2562 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2563 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2564 bool Diagnose = false);
2566 /// For a defaulted function, the kind of defaulted function that it is.
2567 class DefaultedFunctionKind {
2568 CXXSpecialMember SpecialMember : 8;
2569 DefaultedComparisonKind Comparison : 8;
2572 DefaultedFunctionKind()
2573 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
2575 DefaultedFunctionKind(CXXSpecialMember CSM)
2576 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
2577 DefaultedFunctionKind(DefaultedComparisonKind Comp)
2578 : SpecialMember(CXXInvalid), Comparison(Comp) {}
2580 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
2581 bool isComparison() const {
2582 return Comparison != DefaultedComparisonKind::None;
2585 explicit operator bool() const {
2586 return isSpecialMember() || isComparison();
2589 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
2590 DefaultedComparisonKind asComparison() const { return Comparison; }
2592 /// Get the index of this function kind for use in diagnostics.
2593 unsigned getDiagnosticIndex() const {
2594 static_assert(CXXInvalid > CXXDestructor,
2595 "invalid should have highest index");
2596 static_assert((unsigned)DefaultedComparisonKind::None == 0,
2597 "none should be equal to zero");
2598 return SpecialMember + (unsigned)Comparison;
2602 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
2604 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
2605 return getDefaultedFunctionKind(MD).asSpecialMember();
2607 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
2608 return getDefaultedFunctionKind(FD).asComparison();
2611 void ActOnLastBitfield(SourceLocation DeclStart,
2612 SmallVectorImpl<Decl *> &AllIvarDecls);
2613 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2614 Declarator &D, Expr *BitfieldWidth,
2615 tok::ObjCKeywordKind visibility);
2617 // This is used for both record definitions and ObjC interface declarations.
2618 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2619 ArrayRef<Decl *> Fields, SourceLocation LBrac,
2620 SourceLocation RBrac, const ParsedAttributesView &AttrList);
2622 /// ActOnTagStartDefinition - Invoked when we have entered the
2623 /// scope of a tag's definition (e.g., for an enumeration, class,
2624 /// struct, or union).
2625 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2627 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2628 /// Differently from C++, actually parse the body and reject / error out
2629 /// in case of a structural mismatch.
2630 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2631 SkipBodyInfo &SkipBody);
2633 typedef void *SkippedDefinitionContext;
2635 /// Invoked when we enter a tag definition that we're skipping.
2636 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2638 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2640 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2641 /// C++ record definition's base-specifiers clause and are starting its
2642 /// member declarations.
2643 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2644 SourceLocation FinalLoc,
2645 bool IsFinalSpelledSealed,
2646 SourceLocation LBraceLoc);
2648 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2649 /// the definition of a tag (enumeration, class, struct, or union).
2650 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2651 SourceRange BraceRange);
2653 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2655 void ActOnObjCContainerFinishDefinition();
2657 /// Invoked when we must temporarily exit the objective-c container
2658 /// scope for parsing/looking-up C constructs.
2660 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2661 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2662 void ActOnObjCReenterContainerContext(DeclContext *DC);
2664 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2665 /// error parsing the definition of a tag.
2666 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2668 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2669 EnumConstantDecl *LastEnumConst,
2670 SourceLocation IdLoc,
2673 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2674 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2675 QualType EnumUnderlyingTy, bool IsFixed,
2676 const EnumDecl *Prev);
2678 /// Determine whether the body of an anonymous enumeration should be skipped.
2679 /// \param II The name of the first enumerator.
2680 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2681 SourceLocation IILoc);
2683 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2684 SourceLocation IdLoc, IdentifierInfo *Id,
2685 const ParsedAttributesView &Attrs,
2686 SourceLocation EqualLoc, Expr *Val);
2687 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2688 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2689 const ParsedAttributesView &Attr);
2691 DeclContext *getContainingDC(DeclContext *DC);
2693 /// Set the current declaration context until it gets popped.
2694 void PushDeclContext(Scope *S, DeclContext *DC);
2695 void PopDeclContext();
2697 /// EnterDeclaratorContext - Used when we must lookup names in the context
2698 /// of a declarator's nested name specifier.
2699 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2700 void ExitDeclaratorContext(Scope *S);
2702 /// Push the parameters of D, which must be a function, into scope.
2703 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2704 void ActOnExitFunctionContext();
2706 DeclContext *getFunctionLevelDeclContext();
2708 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2709 /// to the function decl for the function being parsed. If we're currently
2710 /// in a 'block', this returns the containing context.
2711 FunctionDecl *getCurFunctionDecl();
2713 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2714 /// the method decl for the method being parsed. If we're currently
2715 /// in a 'block', this returns the containing context.
2716 ObjCMethodDecl *getCurMethodDecl();
2718 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2719 /// or C function we're in, otherwise return null. If we're currently
2720 /// in a 'block', this returns the containing context.
2721 NamedDecl *getCurFunctionOrMethodDecl();
2723 /// Add this decl to the scope shadowed decl chains.
2724 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2726 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2727 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2728 /// true if 'D' belongs to the given declaration context.
2730 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2731 /// enclosing namespace set of the context, rather than contained
2732 /// directly within it.
2733 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2734 bool AllowInlineNamespace = false);
2736 /// Finds the scope corresponding to the given decl context, if it
2737 /// happens to be an enclosing scope. Otherwise return NULL.
2738 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2740 /// Subroutines of ActOnDeclarator().
2741 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2742 TypeSourceInfo *TInfo);
2743 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2745 /// Describes the kind of merge to perform for availability
2746 /// attributes (including "deprecated", "unavailable", and "availability").
2747 enum AvailabilityMergeKind {
2748 /// Don't merge availability attributes at all.
2750 /// Merge availability attributes for a redeclaration, which requires
2753 /// Merge availability attributes for an override, which requires
2754 /// an exact match or a weakening of constraints.
2756 /// Merge availability attributes for an implementation of
2757 /// a protocol requirement.
2758 AMK_ProtocolImplementation,
2761 /// Describes the kind of priority given to an availability attribute.
2763 /// The sum of priorities deteremines the final priority of the attribute.
2764 /// The final priority determines how the attribute will be merged.
2765 /// An attribute with a lower priority will always remove higher priority
2766 /// attributes for the specified platform when it is being applied. An
2767 /// attribute with a higher priority will not be applied if the declaration
2768 /// already has an availability attribute with a lower priority for the
2769 /// specified platform. The final prirority values are not expected to match
2770 /// the values in this enumeration, but instead should be treated as a plain
2771 /// integer value. This enumeration just names the priority weights that are
2772 /// used to calculate that final vaue.
2773 enum AvailabilityPriority : int {
2774 /// The availability attribute was specified explicitly next to the
2778 /// The availability attribute was applied using '#pragma clang attribute'.
2779 AP_PragmaClangAttribute = 1,
2781 /// The availability attribute for a specific platform was inferred from
2782 /// an availability attribute for another platform.
2783 AP_InferredFromOtherPlatform = 2
2786 /// Attribute merging methods. Return true if a new attribute was added.
2788 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
2789 IdentifierInfo *Platform, bool Implicit,
2790 VersionTuple Introduced, VersionTuple Deprecated,
2791 VersionTuple Obsoleted, bool IsUnavailable,
2792 StringRef Message, bool IsStrict, StringRef Replacement,
2793 AvailabilityMergeKind AMK, int Priority);
2794 TypeVisibilityAttr *
2795 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2796 TypeVisibilityAttr::VisibilityType Vis);
2797 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2798 VisibilityAttr::VisibilityType Vis);
2799 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
2801 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
2802 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
2804 mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase,
2805 MSInheritanceAttr::Spelling SemanticSpelling);
2806 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
2807 IdentifierInfo *Format, int FormatIdx,
2809 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
2811 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
2813 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
2814 const AttributeCommonInfo &CI,
2815 const IdentifierInfo *Ident);
2816 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
2817 NoSpeculativeLoadHardeningAttr *
2818 mergeNoSpeculativeLoadHardeningAttr(Decl *D,
2819 const NoSpeculativeLoadHardeningAttr &AL);
2820 SpeculativeLoadHardeningAttr *
2821 mergeSpeculativeLoadHardeningAttr(Decl *D,
2822 const SpeculativeLoadHardeningAttr &AL);
2823 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
2824 const AttributeCommonInfo &CI);
2825 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
2826 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
2827 const InternalLinkageAttr &AL);
2828 CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
2829 CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
2831 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2832 AvailabilityMergeKind AMK = AMK_Redeclaration);
2833 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2834 LookupResult &OldDecls);
2835 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2836 bool MergeTypeWithOld);
2837 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2838 Scope *S, bool MergeTypeWithOld);
2839 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2840 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2841 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2842 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2843 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2844 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2845 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2847 // AssignmentAction - This is used by all the assignment diagnostic functions
2848 // to represent what is actually causing the operation
2849 enum AssignmentAction {
2857 AA_Passing_CFAudited
2860 /// C++ Overloading.
2862 /// This is a legitimate overload: the existing declarations are
2863 /// functions or function templates with different signatures.
2866 /// This is not an overload because the signature exactly matches
2867 /// an existing declaration.
2870 /// This is not an overload because the lookup results contain a
2874 OverloadKind CheckOverload(Scope *S,
2876 const LookupResult &OldDecls,
2877 NamedDecl *&OldDecl,
2878 bool IsForUsingDecl);
2879 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2880 bool ConsiderCudaAttrs = true);
2882 ImplicitConversionSequence
2883 TryImplicitConversion(Expr *From, QualType ToType,
2884 bool SuppressUserConversions,
2886 bool InOverloadResolution,
2888 bool AllowObjCWritebackConversion);
2890 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2891 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2892 bool IsComplexPromotion(QualType FromType, QualType ToType);
2893 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2894 bool InOverloadResolution,
2895 QualType& ConvertedType, bool &IncompatibleObjC);
2896 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2897 QualType& ConvertedType, bool &IncompatibleObjC);
2898 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2899 QualType &ConvertedType);
2900 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2901 QualType& ConvertedType);
2902 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2903 const FunctionProtoType *NewType,
2904 unsigned *ArgPos = nullptr);
2905 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2906 QualType FromType, QualType ToType);
2908 void maybeExtendBlockObject(ExprResult &E);
2909 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2910 bool CheckPointerConversion(Expr *From, QualType ToType,
2912 CXXCastPath& BasePath,
2913 bool IgnoreBaseAccess,
2914 bool Diagnose = true);
2915 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2916 bool InOverloadResolution,
2917 QualType &ConvertedType);
2918 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2920 CXXCastPath &BasePath,
2921 bool IgnoreBaseAccess);
2922 bool IsQualificationConversion(QualType FromType, QualType ToType,
2923 bool CStyle, bool &ObjCLifetimeConversion);
2924 bool IsFunctionConversion(QualType FromType, QualType ToType,
2925 QualType &ResultTy);
2926 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2927 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2929 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2930 const VarDecl *NRVOCandidate,
2931 QualType ResultType,
2933 bool AllowNRVO = true);
2935 bool CanPerformAggregateInitializationForOverloadResolution(
2936 const InitializedEntity &Entity, InitListExpr *From);
2938 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2940 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2941 SourceLocation EqualLoc,
2943 bool TopLevelOfInitList = false,
2944 bool AllowExplicit = false);
2945 ExprResult PerformObjectArgumentInitialization(Expr *From,
2946 NestedNameSpecifier *Qualifier,
2947 NamedDecl *FoundDecl,
2948 CXXMethodDecl *Method);
2950 /// Check that the lifetime of the initializer (and its subobjects) is
2951 /// sufficient for initializing the entity, and perform lifetime extension
2952 /// (when permitted) if not.
2953 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
2955 ExprResult PerformContextuallyConvertToBool(Expr *From);
2956 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2958 /// Contexts in which a converted constant expression is required.
2960 CCEK_CaseValue, ///< Expression in a case label.
2961 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2962 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2963 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2964 CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
2965 CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
2967 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2968 llvm::APSInt &Value, CCEKind CCE);
2969 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2970 APValue &Value, CCEKind CCE);
2972 /// Abstract base class used to perform a contextual implicit
2973 /// conversion from an expression to any type passing a filter.
2974 class ContextualImplicitConverter {
2977 bool SuppressConversion;
2979 ContextualImplicitConverter(bool Suppress = false,
2980 bool SuppressConversion = false)
2981 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2983 /// Determine whether the specified type is a valid destination type
2984 /// for this conversion.
2985 virtual bool match(QualType T) = 0;
2987 /// Emits a diagnostic complaining that the expression does not have
2988 /// integral or enumeration type.
2989 virtual SemaDiagnosticBuilder
2990 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2992 /// Emits a diagnostic when the expression has incomplete class type.
2993 virtual SemaDiagnosticBuilder
2994 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2996 /// Emits a diagnostic when the only matching conversion function
2998 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2999 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3001 /// Emits a note for the explicit conversion function.
3002 virtual SemaDiagnosticBuilder
3003 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3005 /// Emits a diagnostic when there are multiple possible conversion
3007 virtual SemaDiagnosticBuilder
3008 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3010 /// Emits a note for one of the candidate conversions.
3011 virtual SemaDiagnosticBuilder
3012 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3014 /// Emits a diagnostic when we picked a conversion function
3015 /// (for cases when we are not allowed to pick a conversion function).
3016 virtual SemaDiagnosticBuilder diagnoseConversion(
3017 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3019 virtual ~ContextualImplicitConverter() {}
3022 class ICEConvertDiagnoser : public ContextualImplicitConverter {
3023 bool AllowScopedEnumerations;
3026 ICEConvertDiagnoser(bool AllowScopedEnumerations,
3027 bool Suppress, bool SuppressConversion)
3028 : ContextualImplicitConverter(Suppress, SuppressConversion),
3029 AllowScopedEnumerations(AllowScopedEnumerations) {}
3031 /// Match an integral or (possibly scoped) enumeration type.
3032 bool match(QualType T) override;
3034 SemaDiagnosticBuilder
3035 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3036 return diagnoseNotInt(S, Loc, T);
3039 /// Emits a diagnostic complaining that the expression does not have
3040 /// integral or enumeration type.
3041 virtual SemaDiagnosticBuilder
3042 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3045 /// Perform a contextual implicit conversion.
3046 ExprResult PerformContextualImplicitConversion(
3047 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3050 enum ObjCSubscriptKind {
3055 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3057 // Note that LK_String is intentionally after the other literals, as
3058 // this is used for diagnostics logic.
3059 enum ObjCLiteralKind {
3068 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3070 ExprResult PerformObjectMemberConversion(Expr *From,
3071 NestedNameSpecifier *Qualifier,
3072 NamedDecl *FoundDecl,
3075 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3076 // TODO: make this is a typesafe union.
3077 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
3078 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3080 using ADLCallKind = CallExpr::ADLCallKind;
3082 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3083 ArrayRef<Expr *> Args,
3084 OverloadCandidateSet &CandidateSet,
3085 bool SuppressUserConversions = false,
3086 bool PartialOverloading = false,
3087 bool AllowExplicit = true,
3088 bool AllowExplicitConversion = false,
3089 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3090 ConversionSequenceList EarlyConversions = None,
3091 OverloadCandidateParamOrder PO = {});
3092 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3093 ArrayRef<Expr *> Args,
3094 OverloadCandidateSet &CandidateSet,
3095 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3096 bool SuppressUserConversions = false,
3097 bool PartialOverloading = false,
3098 bool FirstArgumentIsBase = false);
3099 void AddMethodCandidate(DeclAccessPair FoundDecl,
3100 QualType ObjectType,
3101 Expr::Classification ObjectClassification,
3102 ArrayRef<Expr *> Args,
3103 OverloadCandidateSet& CandidateSet,
3104 bool SuppressUserConversion = false,
3105 OverloadCandidateParamOrder PO = {});
3106 void AddMethodCandidate(CXXMethodDecl *Method,
3107 DeclAccessPair FoundDecl,
3108 CXXRecordDecl *ActingContext, QualType ObjectType,
3109 Expr::Classification ObjectClassification,
3110 ArrayRef<Expr *> Args,
3111 OverloadCandidateSet& CandidateSet,
3112 bool SuppressUserConversions = false,
3113 bool PartialOverloading = false,
3114 ConversionSequenceList EarlyConversions = None,
3115 OverloadCandidateParamOrder PO = {});
3116 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3117 DeclAccessPair FoundDecl,
3118 CXXRecordDecl *ActingContext,
3119 TemplateArgumentListInfo *ExplicitTemplateArgs,
3120 QualType ObjectType,
3121 Expr::Classification ObjectClassification,
3122 ArrayRef<Expr *> Args,
3123 OverloadCandidateSet& CandidateSet,
3124 bool SuppressUserConversions = false,
3125 bool PartialOverloading = false,
3126 OverloadCandidateParamOrder PO = {});
3127 void AddTemplateOverloadCandidate(
3128 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3129 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3130 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3131 bool PartialOverloading = false, bool AllowExplicit = true,
3132 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3133 OverloadCandidateParamOrder PO = {});
3134 bool CheckNonDependentConversions(
3135 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3136 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3137 ConversionSequenceList &Conversions, bool SuppressUserConversions,
3138 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3139 Expr::Classification ObjectClassification = {},
3140 OverloadCandidateParamOrder PO = {});
3141 void AddConversionCandidate(
3142 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3143 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3144 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3145 bool AllowExplicit, bool AllowResultConversion = true);
3146 void AddTemplateConversionCandidate(
3147 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3148 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3149 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3150 bool AllowExplicit, bool AllowResultConversion = true);
3151 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3152 DeclAccessPair FoundDecl,
3153 CXXRecordDecl *ActingContext,
3154 const FunctionProtoType *Proto,
3155 Expr *Object, ArrayRef<Expr *> Args,
3156 OverloadCandidateSet& CandidateSet);
3157 void AddNonMemberOperatorCandidates(
3158 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3159 OverloadCandidateSet &CandidateSet,
3160 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3161 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3162 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3163 OverloadCandidateSet &CandidateSet,
3164 OverloadCandidateParamOrder PO = {});
3165 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3166 OverloadCandidateSet& CandidateSet,
3167 bool IsAssignmentOperator = false,
3168 unsigned NumContextualBoolArguments = 0);
3169 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3170 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3171 OverloadCandidateSet& CandidateSet);
3172 void AddArgumentDependentLookupCandidates(DeclarationName Name,
3174 ArrayRef<Expr *> Args,
3175 TemplateArgumentListInfo *ExplicitTemplateArgs,
3176 OverloadCandidateSet& CandidateSet,
3177 bool PartialOverloading = false);
3179 // Emit as a 'note' the specific overload candidate
3180 void NoteOverloadCandidate(
3181 NamedDecl *Found, FunctionDecl *Fn,
3182 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3183 QualType DestType = QualType(), bool TakingAddress = false);
3185 // Emit as a series of 'note's all template and non-templates identified by
3186 // the expression Expr
3187 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3188 bool TakingAddress = false);
3190 /// Check the enable_if expressions on the given function. Returns the first
3191 /// failing attribute, or NULL if they were all successful.
3192 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
3193 bool MissingImplicitThis = false);
3195 /// Find the failed Boolean condition within a given Boolean
3196 /// constant expression, and describe it with a string.
3197 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3199 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3200 /// non-ArgDependent DiagnoseIfAttrs.
3202 /// Argument-dependent diagnose_if attributes should be checked each time a
3203 /// function is used as a direct callee of a function call.
3205 /// Returns true if any errors were emitted.
3206 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3207 const Expr *ThisArg,
3208 ArrayRef<const Expr *> Args,
3209 SourceLocation Loc);
3211 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3212 /// ArgDependent DiagnoseIfAttrs.
3214 /// Argument-independent diagnose_if attributes should be checked on every use
3217 /// Returns true if any errors were emitted.
3218 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3219 SourceLocation Loc);
3221 /// Returns whether the given function's address can be taken or not,
3222 /// optionally emitting a diagnostic if the address can't be taken.
3224 /// Returns false if taking the address of the function is illegal.
3225 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3226 bool Complain = false,
3227 SourceLocation Loc = SourceLocation());
3229 // [PossiblyAFunctionType] --> [Return]
3230 // NonFunctionType --> NonFunctionType
3232 // R (*)(A) --> R (A)
3233 // R (&)(A) --> R (A)
3234 // R (S::*)(A) --> R (A)
3235 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3238 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3239 QualType TargetType,
3241 DeclAccessPair &Found,
3242 bool *pHadMultipleCandidates = nullptr);
3245 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
3246 DeclAccessPair &FoundResult);
3248 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
3249 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3252 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3253 bool Complain = false,
3254 DeclAccessPair *Found = nullptr);
3256 bool ResolveAndFixSingleFunctionTemplateSpecialization(
3257 ExprResult &SrcExpr,
3258 bool DoFunctionPointerConverion = false,
3259 bool Complain = false,
3260 SourceRange OpRangeForComplaining = SourceRange(),
3261 QualType DestTypeForComplaining = QualType(),
3262 unsigned DiagIDForComplaining = 0);
3265 Expr *FixOverloadedFunctionReference(Expr *E,
3266 DeclAccessPair FoundDecl,
3268 ExprResult FixOverloadedFunctionReference(ExprResult,
3269 DeclAccessPair FoundDecl,
3272 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3273 ArrayRef<Expr *> Args,
3274 OverloadCandidateSet &CandidateSet,
3275 bool PartialOverloading = false);
3277 // An enum used to represent the different possible results of building a
3278 // range-based for loop.
3279 enum ForRangeStatus {
3281 FRS_NoViableFunction,
3282 FRS_DiagnosticIssued
3285 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3286 SourceLocation RangeLoc,
3287 const DeclarationNameInfo &NameInfo,
3288 LookupResult &MemberLookup,
3289 OverloadCandidateSet *CandidateSet,
3290 Expr *Range, ExprResult *CallExpr);
3292 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3293 UnresolvedLookupExpr *ULE,
3294 SourceLocation LParenLoc,
3296 SourceLocation RParenLoc,
3298 bool AllowTypoCorrection=true,
3299 bool CalleesAddressIsTaken=false);
3301 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3302 MultiExprArg Args, SourceLocation RParenLoc,
3303 OverloadCandidateSet *CandidateSet,
3304 ExprResult *Result);
3306 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3307 UnaryOperatorKind Opc,
3308 const UnresolvedSetImpl &Fns,
3309 Expr *input, bool RequiresADL = true);
3311 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3312 BinaryOperatorKind Opc,
3313 const UnresolvedSetImpl &Fns,
3314 Expr *LHS, Expr *RHS,
3315 bool RequiresADL = true,
3316 bool AllowRewrittenCandidates = true);
3318 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3319 SourceLocation RLoc,
3320 Expr *Base,Expr *Idx);
3323 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3324 SourceLocation LParenLoc,
3326 SourceLocation RParenLoc);
3328 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3330 SourceLocation RParenLoc);
3332 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3333 SourceLocation OpLoc,
3334 bool *NoArrowOperatorFound = nullptr);
3336 /// CheckCallReturnType - Checks that a call expression's return type is
3337 /// complete. Returns true on failure. The location passed in is the location
3338 /// that best represents the call.
3339 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3340 CallExpr *CE, FunctionDecl *FD);
3342 /// Helpers for dealing with blocks and functions.
3343 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3344 bool CheckParameterNames);
3345 void CheckCXXDefaultArguments(FunctionDecl *FD);
3346 void CheckExtraCXXDefaultArguments(Declarator &D);
3347 Scope *getNonFieldDeclScope(Scope *S);
3349 /// \name Name lookup
3351 /// These routines provide name lookup that is used during semantic
3352 /// analysis to resolve the various kinds of names (identifiers,
3353 /// overloaded operator names, constructor names, etc.) into zero or
3354 /// more declarations within a particular scope. The major entry
3355 /// points are LookupName, which performs unqualified name lookup,
3356 /// and LookupQualifiedName, which performs qualified name lookup.
3358 /// All name lookup is performed based on some specific criteria,
3359 /// which specify what names will be visible to name lookup and how
3360 /// far name lookup should work. These criteria are important both
3361 /// for capturing language semantics (certain lookups will ignore
3362 /// certain names, for example) and for performance, since name
3363 /// lookup is often a bottleneck in the compilation of C++. Name
3364 /// lookup criteria is specified via the LookupCriteria enumeration.
3366 /// The results of name lookup can vary based on the kind of name
3367 /// lookup performed, the current language, and the translation
3368 /// unit. In C, for example, name lookup will either return nothing
3369 /// (no entity found) or a single declaration. In C++, name lookup
3370 /// can additionally refer to a set of overloaded functions or
3371 /// result in an ambiguity. All of the possible results of name
3372 /// lookup are captured by the LookupResult class, which provides
3373 /// the ability to distinguish among them.
3376 /// Describes the kind of name lookup to perform.
3377 enum LookupNameKind {
3378 /// Ordinary name lookup, which finds ordinary names (functions,
3379 /// variables, typedefs, etc.) in C and most kinds of names
3380 /// (functions, variables, members, types, etc.) in C++.
3381 LookupOrdinaryName = 0,
3382 /// Tag name lookup, which finds the names of enums, classes,
3383 /// structs, and unions.
3385 /// Label name lookup.
3387 /// Member name lookup, which finds the names of
3388 /// class/struct/union members.
3390 /// Look up of an operator name (e.g., operator+) for use with
3391 /// operator overloading. This lookup is similar to ordinary name
3392 /// lookup, but will ignore any declarations that are class members.
3394 /// Look up of a name that precedes the '::' scope resolution
3395 /// operator in C++. This lookup completely ignores operator, object,
3396 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3397 LookupNestedNameSpecifierName,
3398 /// Look up a namespace name within a C++ using directive or
3399 /// namespace alias definition, ignoring non-namespace names (C++
3400 /// [basic.lookup.udir]p1).
3401 LookupNamespaceName,
3402 /// Look up all declarations in a scope with the given name,
3403 /// including resolved using declarations. This is appropriate
3404 /// for checking redeclarations for a using declaration.
3405 LookupUsingDeclName,
3406 /// Look up an ordinary name that is going to be redeclared as a
3407 /// name with linkage. This lookup ignores any declarations that
3408 /// are outside of the current scope unless they have linkage. See
3409 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3410 LookupRedeclarationWithLinkage,
3411 /// Look up a friend of a local class. This lookup does not look
3412 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3413 LookupLocalFriendName,
3414 /// Look up the name of an Objective-C protocol.
3415 LookupObjCProtocolName,
3416 /// Look up implicit 'self' parameter of an objective-c method.
3417 LookupObjCImplicitSelfParam,
3418 /// Look up the name of an OpenMP user-defined reduction operation.
3419 LookupOMPReductionName,
3420 /// Look up the name of an OpenMP user-defined mapper.
3421 LookupOMPMapperName,
3422 /// Look up any declaration with any name.
3426 /// Specifies whether (or how) name