Path: blob/main/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp
35234 views
//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements semantic analysis for declarations.9//10//===----------------------------------------------------------------------===//1112#include "TypeLocBuilder.h"13#include "clang/AST/ASTConsumer.h"14#include "clang/AST/ASTContext.h"15#include "clang/AST/ASTLambda.h"16#include "clang/AST/CXXInheritance.h"17#include "clang/AST/CharUnits.h"18#include "clang/AST/CommentDiagnostic.h"19#include "clang/AST/Decl.h"20#include "clang/AST/DeclCXX.h"21#include "clang/AST/DeclObjC.h"22#include "clang/AST/DeclTemplate.h"23#include "clang/AST/EvaluatedExprVisitor.h"24#include "clang/AST/Expr.h"25#include "clang/AST/ExprCXX.h"26#include "clang/AST/NonTrivialTypeVisitor.h"27#include "clang/AST/Randstruct.h"28#include "clang/AST/StmtCXX.h"29#include "clang/AST/Type.h"30#include "clang/Basic/Builtins.h"31#include "clang/Basic/HLSLRuntime.h"32#include "clang/Basic/PartialDiagnostic.h"33#include "clang/Basic/SourceManager.h"34#include "clang/Basic/TargetInfo.h"35#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex36#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.37#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex38#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()39#include "clang/Sema/CXXFieldCollector.h"40#include "clang/Sema/DeclSpec.h"41#include "clang/Sema/DelayedDiagnostic.h"42#include "clang/Sema/Initialization.h"43#include "clang/Sema/Lookup.h"44#include "clang/Sema/ParsedTemplate.h"45#include "clang/Sema/Scope.h"46#include "clang/Sema/ScopeInfo.h"47#include "clang/Sema/SemaCUDA.h"48#include "clang/Sema/SemaHLSL.h"49#include "clang/Sema/SemaInternal.h"50#include "clang/Sema/SemaObjC.h"51#include "clang/Sema/SemaOpenMP.h"52#include "clang/Sema/SemaPPC.h"53#include "clang/Sema/SemaRISCV.h"54#include "clang/Sema/SemaSwift.h"55#include "clang/Sema/SemaWasm.h"56#include "clang/Sema/Template.h"57#include "llvm/ADT/STLForwardCompat.h"58#include "llvm/ADT/SmallString.h"59#include "llvm/ADT/StringExtras.h"60#include "llvm/TargetParser/Triple.h"61#include <algorithm>62#include <cstring>63#include <functional>64#include <optional>65#include <unordered_map>6667using namespace clang;68using namespace sema;6970Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {71if (OwnedType) {72Decl *Group[2] = { OwnedType, Ptr };73return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));74}7576return DeclGroupPtrTy::make(DeclGroupRef(Ptr));77}7879namespace {8081class TypeNameValidatorCCC final : public CorrectionCandidateCallback {82public:83TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,84bool AllowTemplates = false,85bool AllowNonTemplates = true)86: AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),87AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {88WantExpressionKeywords = false;89WantCXXNamedCasts = false;90WantRemainingKeywords = false;91}9293bool ValidateCandidate(const TypoCorrection &candidate) override {94if (NamedDecl *ND = candidate.getCorrectionDecl()) {95if (!AllowInvalidDecl && ND->isInvalidDecl())96return false;9798if (getAsTypeTemplateDecl(ND))99return AllowTemplates;100101bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);102if (!IsType)103return false;104105if (AllowNonTemplates)106return true;107108// An injected-class-name of a class template (specialization) is valid109// as a template or as a non-template.110if (AllowTemplates) {111auto *RD = dyn_cast<CXXRecordDecl>(ND);112if (!RD || !RD->isInjectedClassName())113return false;114RD = cast<CXXRecordDecl>(RD->getDeclContext());115return RD->getDescribedClassTemplate() ||116isa<ClassTemplateSpecializationDecl>(RD);117}118119return false;120}121122return !WantClassName && candidate.isKeyword();123}124125std::unique_ptr<CorrectionCandidateCallback> clone() override {126return std::make_unique<TypeNameValidatorCCC>(*this);127}128129private:130bool AllowInvalidDecl;131bool WantClassName;132bool AllowTemplates;133bool AllowNonTemplates;134};135136} // end anonymous namespace137138namespace {139enum class UnqualifiedTypeNameLookupResult {140NotFound,141FoundNonType,142FoundType143};144} // end anonymous namespace145146/// Tries to perform unqualified lookup of the type decls in bases for147/// dependent class.148/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a149/// type decl, \a FoundType if only type decls are found.150static UnqualifiedTypeNameLookupResult151lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,152SourceLocation NameLoc,153const CXXRecordDecl *RD) {154if (!RD->hasDefinition())155return UnqualifiedTypeNameLookupResult::NotFound;156// Look for type decls in base classes.157UnqualifiedTypeNameLookupResult FoundTypeDecl =158UnqualifiedTypeNameLookupResult::NotFound;159for (const auto &Base : RD->bases()) {160const CXXRecordDecl *BaseRD = nullptr;161if (auto *BaseTT = Base.getType()->getAs<TagType>())162BaseRD = BaseTT->getAsCXXRecordDecl();163else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {164// Look for type decls in dependent base classes that have known primary165// templates.166if (!TST || !TST->isDependentType())167continue;168auto *TD = TST->getTemplateName().getAsTemplateDecl();169if (!TD)170continue;171if (auto *BasePrimaryTemplate =172dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {173if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())174BaseRD = BasePrimaryTemplate;175else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {176if (const ClassTemplatePartialSpecializationDecl *PS =177CTD->findPartialSpecialization(Base.getType()))178if (PS->getCanonicalDecl() != RD->getCanonicalDecl())179BaseRD = PS;180}181}182}183if (BaseRD) {184for (NamedDecl *ND : BaseRD->lookup(&II)) {185if (!isa<TypeDecl>(ND))186return UnqualifiedTypeNameLookupResult::FoundNonType;187FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;188}189if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {190switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {191case UnqualifiedTypeNameLookupResult::FoundNonType:192return UnqualifiedTypeNameLookupResult::FoundNonType;193case UnqualifiedTypeNameLookupResult::FoundType:194FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;195break;196case UnqualifiedTypeNameLookupResult::NotFound:197break;198}199}200}201}202203return FoundTypeDecl;204}205206static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,207const IdentifierInfo &II,208SourceLocation NameLoc) {209// Lookup in the parent class template context, if any.210const CXXRecordDecl *RD = nullptr;211UnqualifiedTypeNameLookupResult FoundTypeDecl =212UnqualifiedTypeNameLookupResult::NotFound;213for (DeclContext *DC = S.CurContext;214DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;215DC = DC->getParent()) {216// Look for type decls in dependent base classes that have known primary217// templates.218RD = dyn_cast<CXXRecordDecl>(DC);219if (RD && RD->getDescribedClassTemplate())220FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);221}222if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)223return nullptr;224225// We found some types in dependent base classes. Recover as if the user226// wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the227// lookup during template instantiation.228S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;229230ASTContext &Context = S.Context;231auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,232cast<Type>(Context.getRecordType(RD)));233QualType T =234Context.getDependentNameType(ElaboratedTypeKeyword::Typename, NNS, &II);235236CXXScopeSpec SS;237SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));238239TypeLocBuilder Builder;240DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);241DepTL.setNameLoc(NameLoc);242DepTL.setElaboratedKeywordLoc(SourceLocation());243DepTL.setQualifierLoc(SS.getWithLocInContext(Context));244return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));245}246247/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.248static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,249SourceLocation NameLoc,250bool WantNontrivialTypeSourceInfo = true) {251switch (T->getTypeClass()) {252case Type::DeducedTemplateSpecialization:253case Type::Enum:254case Type::InjectedClassName:255case Type::Record:256case Type::Typedef:257case Type::UnresolvedUsing:258case Type::Using:259break;260// These can never be qualified so an ElaboratedType node261// would carry no additional meaning.262case Type::ObjCInterface:263case Type::ObjCTypeParam:264case Type::TemplateTypeParm:265return ParsedType::make(T);266default:267llvm_unreachable("Unexpected Type Class");268}269270if (!SS || SS->isEmpty())271return ParsedType::make(S.Context.getElaboratedType(272ElaboratedTypeKeyword::None, nullptr, T, nullptr));273274QualType ElTy = S.getElaboratedType(ElaboratedTypeKeyword::None, *SS, T);275if (!WantNontrivialTypeSourceInfo)276return ParsedType::make(ElTy);277278TypeLocBuilder Builder;279Builder.pushTypeSpec(T).setNameLoc(NameLoc);280ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);281ElabTL.setElaboratedKeywordLoc(SourceLocation());282ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));283return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));284}285286ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,287Scope *S, CXXScopeSpec *SS, bool isClassName,288bool HasTrailingDot, ParsedType ObjectTypePtr,289bool IsCtorOrDtorName,290bool WantNontrivialTypeSourceInfo,291bool IsClassTemplateDeductionContext,292ImplicitTypenameContext AllowImplicitTypename,293IdentifierInfo **CorrectedII) {294// FIXME: Consider allowing this outside C++1z mode as an extension.295bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&296getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&297!isClassName && !HasTrailingDot;298299// Determine where we will perform name lookup.300DeclContext *LookupCtx = nullptr;301if (ObjectTypePtr) {302QualType ObjectType = ObjectTypePtr.get();303if (ObjectType->isRecordType())304LookupCtx = computeDeclContext(ObjectType);305} else if (SS && SS->isNotEmpty()) {306LookupCtx = computeDeclContext(*SS, false);307308if (!LookupCtx) {309if (isDependentScopeSpecifier(*SS)) {310// C++ [temp.res]p3:311// A qualified-id that refers to a type and in which the312// nested-name-specifier depends on a template-parameter (14.6.2)313// shall be prefixed by the keyword typename to indicate that the314// qualified-id denotes a type, forming an315// elaborated-type-specifier (7.1.5.3).316//317// We therefore do not perform any name lookup if the result would318// refer to a member of an unknown specialization.319// In C++2a, in several contexts a 'typename' is not required. Also320// allow this as an extension.321if (AllowImplicitTypename == ImplicitTypenameContext::No &&322!isClassName && !IsCtorOrDtorName)323return nullptr;324bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;325if (IsImplicitTypename) {326SourceLocation QualifiedLoc = SS->getRange().getBegin();327if (getLangOpts().CPlusPlus20)328Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);329else330Diag(QualifiedLoc, diag::ext_implicit_typename)331<< SS->getScopeRep() << II.getName()332<< FixItHint::CreateInsertion(QualifiedLoc, "typename ");333}334335// We know from the grammar that this name refers to a type,336// so build a dependent node to describe the type.337if (WantNontrivialTypeSourceInfo)338return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,339(ImplicitTypenameContext)IsImplicitTypename)340.get();341342NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);343QualType T = CheckTypenameType(344IsImplicitTypename ? ElaboratedTypeKeyword::Typename345: ElaboratedTypeKeyword::None,346SourceLocation(), QualifierLoc, II, NameLoc);347return ParsedType::make(T);348}349350return nullptr;351}352353if (!LookupCtx->isDependentContext() &&354RequireCompleteDeclContext(*SS, LookupCtx))355return nullptr;356}357358// FIXME: LookupNestedNameSpecifierName isn't the right kind of359// lookup for class-names.360LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :361LookupOrdinaryName;362LookupResult Result(*this, &II, NameLoc, Kind);363if (LookupCtx) {364// Perform "qualified" name lookup into the declaration context we365// computed, which is either the type of the base of a member access366// expression or the declaration context associated with a prior367// nested-name-specifier.368LookupQualifiedName(Result, LookupCtx);369370if (ObjectTypePtr && Result.empty()) {371// C++ [basic.lookup.classref]p3:372// If the unqualified-id is ~type-name, the type-name is looked up373// in the context of the entire postfix-expression. If the type T of374// the object expression is of a class type C, the type-name is also375// looked up in the scope of class C. At least one of the lookups shall376// find a name that refers to (possibly cv-qualified) T.377LookupName(Result, S);378}379} else {380// Perform unqualified name lookup.381LookupName(Result, S);382383// For unqualified lookup in a class template in MSVC mode, look into384// dependent base classes where the primary class template is known.385if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {386if (ParsedType TypeInBase =387recoverFromTypeInKnownDependentBase(*this, II, NameLoc))388return TypeInBase;389}390}391392NamedDecl *IIDecl = nullptr;393UsingShadowDecl *FoundUsingShadow = nullptr;394switch (Result.getResultKind()) {395case LookupResult::NotFound:396if (CorrectedII) {397TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,398AllowDeducedTemplate);399TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,400S, SS, CCC, CTK_ErrorRecovery);401IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();402TemplateTy Template;403bool MemberOfUnknownSpecialization;404UnqualifiedId TemplateName;405TemplateName.setIdentifier(NewII, NameLoc);406NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();407CXXScopeSpec NewSS, *NewSSPtr = SS;408if (SS && NNS) {409NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));410NewSSPtr = &NewSS;411}412if (Correction && (NNS || NewII != &II) &&413// Ignore a correction to a template type as the to-be-corrected414// identifier is not a template (typo correction for template names415// is handled elsewhere).416!(getLangOpts().CPlusPlus && NewSSPtr &&417isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,418Template, MemberOfUnknownSpecialization))) {419ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,420isClassName, HasTrailingDot, ObjectTypePtr,421IsCtorOrDtorName,422WantNontrivialTypeSourceInfo,423IsClassTemplateDeductionContext);424if (Ty) {425diagnoseTypo(Correction,426PDiag(diag::err_unknown_type_or_class_name_suggest)427<< Result.getLookupName() << isClassName);428if (SS && NNS)429SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));430*CorrectedII = NewII;431return Ty;432}433}434}435Result.suppressDiagnostics();436return nullptr;437case LookupResult::NotFoundInCurrentInstantiation:438if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {439QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,440SS->getScopeRep(), &II);441TypeLocBuilder TLB;442DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);443TL.setElaboratedKeywordLoc(SourceLocation());444TL.setQualifierLoc(SS->getWithLocInContext(Context));445TL.setNameLoc(NameLoc);446return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));447}448[[fallthrough]];449case LookupResult::FoundOverloaded:450case LookupResult::FoundUnresolvedValue:451Result.suppressDiagnostics();452return nullptr;453454case LookupResult::Ambiguous:455// Recover from type-hiding ambiguities by hiding the type. We'll456// do the lookup again when looking for an object, and we can457// diagnose the error then. If we don't do this, then the error458// about hiding the type will be immediately followed by an error459// that only makes sense if the identifier was treated like a type.460if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {461Result.suppressDiagnostics();462return nullptr;463}464465// Look to see if we have a type anywhere in the list of results.466for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();467Res != ResEnd; ++Res) {468NamedDecl *RealRes = (*Res)->getUnderlyingDecl();469if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(470RealRes) ||471(AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {472if (!IIDecl ||473// Make the selection of the recovery decl deterministic.474RealRes->getLocation() < IIDecl->getLocation()) {475IIDecl = RealRes;476FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);477}478}479}480481if (!IIDecl) {482// None of the entities we found is a type, so there is no way483// to even assume that the result is a type. In this case, don't484// complain about the ambiguity. The parser will either try to485// perform this lookup again (e.g., as an object name), which486// will produce the ambiguity, or will complain that it expected487// a type name.488Result.suppressDiagnostics();489return nullptr;490}491492// We found a type within the ambiguous lookup; diagnose the493// ambiguity and then return that type. This might be the right494// answer, or it might not be, but it suppresses any attempt to495// perform the name lookup again.496break;497498case LookupResult::Found:499IIDecl = Result.getFoundDecl();500FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());501break;502}503504assert(IIDecl && "Didn't find decl");505506QualType T;507if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {508// C++ [class.qual]p2: A lookup that would find the injected-class-name509// instead names the constructors of the class, except when naming a class.510// This is ill-formed when we're not actually forming a ctor or dtor name.511auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);512auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);513if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&514FoundRD->isInjectedClassName() &&515declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))516Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)517<< &II << /*Type*/1;518519DiagnoseUseOfDecl(IIDecl, NameLoc);520521T = Context.getTypeDeclType(TD);522MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);523} else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {524(void)DiagnoseUseOfDecl(IDecl, NameLoc);525if (!HasTrailingDot)526T = Context.getObjCInterfaceType(IDecl);527FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.528} else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {529(void)DiagnoseUseOfDecl(UD, NameLoc);530// Recover with 'int'531return ParsedType::make(Context.IntTy);532} else if (AllowDeducedTemplate) {533if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {534assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);535TemplateName Template = Context.getQualifiedTemplateName(536SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false,537FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));538T = Context.getDeducedTemplateSpecializationType(Template, QualType(),539false);540// Don't wrap in a further UsingType.541FoundUsingShadow = nullptr;542}543}544545if (T.isNull()) {546// If it's not plausibly a type, suppress diagnostics.547Result.suppressDiagnostics();548return nullptr;549}550551if (FoundUsingShadow)552T = Context.getUsingType(FoundUsingShadow, T);553554return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);555}556557// Builds a fake NNS for the given decl context.558static NestedNameSpecifier *559synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {560for (;; DC = DC->getLookupParent()) {561DC = DC->getPrimaryContext();562auto *ND = dyn_cast<NamespaceDecl>(DC);563if (ND && !ND->isInline() && !ND->isAnonymousNamespace())564return NestedNameSpecifier::Create(Context, nullptr, ND);565else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))566return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),567RD->getTypeForDecl());568else if (isa<TranslationUnitDecl>(DC))569return NestedNameSpecifier::GlobalSpecifier(Context);570}571llvm_unreachable("something isn't in TU scope?");572}573574/// Find the parent class with dependent bases of the innermost enclosing method575/// context. Do not look for enclosing CXXRecordDecls directly, or we will end576/// up allowing unqualified dependent type names at class-level, which MSVC577/// correctly rejects.578static const CXXRecordDecl *579findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {580for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {581DC = DC->getPrimaryContext();582if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))583if (MD->getParent()->hasAnyDependentBases())584return MD->getParent();585}586return nullptr;587}588589ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,590SourceLocation NameLoc,591bool IsTemplateTypeArg) {592assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");593594NestedNameSpecifier *NNS = nullptr;595if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {596// If we weren't able to parse a default template argument, delay lookup597// until instantiation time by making a non-dependent DependentTypeName. We598// pretend we saw a NestedNameSpecifier referring to the current scope, and599// lookup is retried.600// FIXME: This hurts our diagnostic quality, since we get errors like "no601// type named 'Foo' in 'current_namespace'" when the user didn't write any602// name specifiers.603NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);604Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;605} else if (const CXXRecordDecl *RD =606findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {607// Build a DependentNameType that will perform lookup into RD at608// instantiation time.609NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),610RD->getTypeForDecl());611612// Diagnose that this identifier was undeclared, and retry the lookup during613// template instantiation.614Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II615<< RD;616} else {617// This is not a situation that we should recover from.618return ParsedType();619}620621QualType T =622Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);623624// Build type location information. We synthesized the qualifier, so we have625// to build a fake NestedNameSpecifierLoc.626NestedNameSpecifierLocBuilder NNSLocBuilder;627NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));628NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);629630TypeLocBuilder Builder;631DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);632DepTL.setNameLoc(NameLoc);633DepTL.setElaboratedKeywordLoc(SourceLocation());634DepTL.setQualifierLoc(QualifierLoc);635return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));636}637638DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {639// Do a tag name lookup in this scope.640LookupResult R(*this, &II, SourceLocation(), LookupTagName);641LookupName(R, S, false);642R.suppressDiagnostics();643if (R.getResultKind() == LookupResult::Found)644if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {645switch (TD->getTagKind()) {646case TagTypeKind::Struct:647return DeclSpec::TST_struct;648case TagTypeKind::Interface:649return DeclSpec::TST_interface;650case TagTypeKind::Union:651return DeclSpec::TST_union;652case TagTypeKind::Class:653return DeclSpec::TST_class;654case TagTypeKind::Enum:655return DeclSpec::TST_enum;656}657}658659return DeclSpec::TST_unspecified;660}661662bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {663if (CurContext->isRecord()) {664if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)665return true;666667const Type *Ty = SS->getScopeRep()->getAsType();668669CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);670for (const auto &Base : RD->bases())671if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))672return true;673return S->isFunctionPrototypeScope();674}675return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();676}677678void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,679SourceLocation IILoc,680Scope *S,681CXXScopeSpec *SS,682ParsedType &SuggestedType,683bool IsTemplateName) {684// Don't report typename errors for editor placeholders.685if (II->isEditorPlaceholder())686return;687// We don't have anything to suggest (yet).688SuggestedType = nullptr;689690// There may have been a typo in the name of the type. Look up typo691// results, in case we have something that we can suggest.692TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,693/*AllowTemplates=*/IsTemplateName,694/*AllowNonTemplates=*/!IsTemplateName);695if (TypoCorrection Corrected =696CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,697CCC, CTK_ErrorRecovery)) {698// FIXME: Support error recovery for the template-name case.699bool CanRecover = !IsTemplateName;700if (Corrected.isKeyword()) {701// We corrected to a keyword.702diagnoseTypo(Corrected,703PDiag(IsTemplateName ? diag::err_no_template_suggest704: diag::err_unknown_typename_suggest)705<< II);706II = Corrected.getCorrectionAsIdentifierInfo();707} else {708// We found a similarly-named type or interface; suggest that.709if (!SS || !SS->isSet()) {710diagnoseTypo(Corrected,711PDiag(IsTemplateName ? diag::err_no_template_suggest712: diag::err_unknown_typename_suggest)713<< II, CanRecover);714} else if (DeclContext *DC = computeDeclContext(*SS, false)) {715std::string CorrectedStr(Corrected.getAsString(getLangOpts()));716bool DroppedSpecifier =717Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;718diagnoseTypo(Corrected,719PDiag(IsTemplateName720? diag::err_no_member_template_suggest721: diag::err_unknown_nested_typename_suggest)722<< II << DC << DroppedSpecifier << SS->getRange(),723CanRecover);724} else {725llvm_unreachable("could not have corrected a typo here");726}727728if (!CanRecover)729return;730731CXXScopeSpec tmpSS;732if (Corrected.getCorrectionSpecifier())733tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),734SourceRange(IILoc));735// FIXME: Support class template argument deduction here.736SuggestedType =737getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,738tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,739/*IsCtorOrDtorName=*/false,740/*WantNontrivialTypeSourceInfo=*/true);741}742return;743}744745if (getLangOpts().CPlusPlus && !IsTemplateName) {746// See if II is a class template that the user forgot to pass arguments to.747UnqualifiedId Name;748Name.setIdentifier(II, IILoc);749CXXScopeSpec EmptySS;750TemplateTy TemplateResult;751bool MemberOfUnknownSpecialization;752if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,753Name, nullptr, true, TemplateResult,754MemberOfUnknownSpecialization) == TNK_Type_template) {755diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);756return;757}758}759760// FIXME: Should we move the logic that tries to recover from a missing tag761// (struct, union, enum) from Parser::ParseImplicitInt here, instead?762763if (!SS || (!SS->isSet() && !SS->isInvalid()))764Diag(IILoc, IsTemplateName ? diag::err_no_template765: diag::err_unknown_typename)766<< II;767else if (DeclContext *DC = computeDeclContext(*SS, false))768Diag(IILoc, IsTemplateName ? diag::err_no_member_template769: diag::err_typename_nested_not_found)770<< II << DC << SS->getRange();771else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {772SuggestedType =773ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();774} else if (isDependentScopeSpecifier(*SS)) {775unsigned DiagID = diag::err_typename_missing;776if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))777DiagID = diag::ext_typename_missing;778779Diag(SS->getRange().getBegin(), DiagID)780<< SS->getScopeRep() << II->getName()781<< SourceRange(SS->getRange().getBegin(), IILoc)782<< FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");783SuggestedType = ActOnTypenameType(S, SourceLocation(),784*SS, *II, IILoc).get();785} else {786assert(SS && SS->isInvalid() &&787"Invalid scope specifier has already been diagnosed");788}789}790791/// Determine whether the given result set contains either a type name792/// or793static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {794bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&795NextToken.is(tok::less);796797for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {798if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))799return true;800801if (CheckTemplate && isa<TemplateDecl>(*I))802return true;803}804805return false;806}807808static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,809Scope *S, CXXScopeSpec &SS,810IdentifierInfo *&Name,811SourceLocation NameLoc) {812LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);813SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());814if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {815StringRef FixItTagName;816switch (Tag->getTagKind()) {817case TagTypeKind::Class:818FixItTagName = "class ";819break;820821case TagTypeKind::Enum:822FixItTagName = "enum ";823break;824825case TagTypeKind::Struct:826FixItTagName = "struct ";827break;828829case TagTypeKind::Interface:830FixItTagName = "__interface ";831break;832833case TagTypeKind::Union:834FixItTagName = "union ";835break;836}837838StringRef TagName = FixItTagName.drop_back();839SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)840<< Name << TagName << SemaRef.getLangOpts().CPlusPlus841<< FixItHint::CreateInsertion(NameLoc, FixItTagName);842843for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();844I != IEnd; ++I)845SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)846<< Name << TagName;847848// Replace lookup results with just the tag decl.849Result.clear(Sema::LookupTagName);850SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());851return true;852}853854return false;855}856857Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,858IdentifierInfo *&Name,859SourceLocation NameLoc,860const Token &NextToken,861CorrectionCandidateCallback *CCC) {862DeclarationNameInfo NameInfo(Name, NameLoc);863ObjCMethodDecl *CurMethod = getCurMethodDecl();864865assert(NextToken.isNot(tok::coloncolon) &&866"parse nested name specifiers before calling ClassifyName");867if (getLangOpts().CPlusPlus && SS.isSet() &&868isCurrentClassName(*Name, S, &SS)) {869// Per [class.qual]p2, this names the constructors of SS, not the870// injected-class-name. We don't have a classification for that.871// There's not much point caching this result, since the parser872// will reject it later.873return NameClassification::Unknown();874}875876LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);877LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),878/*AllowBuiltinCreation=*/!CurMethod);879880if (SS.isInvalid())881return NameClassification::Error();882883// For unqualified lookup in a class template in MSVC mode, look into884// dependent base classes where the primary class template is known.885if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {886if (ParsedType TypeInBase =887recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))888return TypeInBase;889}890891// Perform lookup for Objective-C instance variables (including automatically892// synthesized instance variables), if we're in an Objective-C method.893// FIXME: This lookup really, really needs to be folded in to the normal894// unqualified lookup mechanism.895if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {896DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);897if (Ivar.isInvalid())898return NameClassification::Error();899if (Ivar.isUsable())900return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));901902// We defer builtin creation until after ivar lookup inside ObjC methods.903if (Result.empty())904LookupBuiltin(Result);905}906907bool SecondTry = false;908bool IsFilteredTemplateName = false;909910Corrected:911switch (Result.getResultKind()) {912case LookupResult::NotFound:913// If an unqualified-id is followed by a '(', then we have a function914// call.915if (SS.isEmpty() && NextToken.is(tok::l_paren)) {916// In C++, this is an ADL-only call.917// FIXME: Reference?918if (getLangOpts().CPlusPlus)919return NameClassification::UndeclaredNonType();920921// C90 6.3.2.2:922// If the expression that precedes the parenthesized argument list in a923// function call consists solely of an identifier, and if no924// declaration is visible for this identifier, the identifier is925// implicitly declared exactly as if, in the innermost block containing926// the function call, the declaration927//928// extern int identifier ();929//930// appeared.931//932// We also allow this in C99 as an extension. However, this is not933// allowed in all language modes as functions without prototypes may not934// be supported.935if (getLangOpts().implicitFunctionsAllowed()) {936if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))937return NameClassification::NonType(D);938}939}940941if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {942// In C++20 onwards, this could be an ADL-only call to a function943// template, and we're required to assume that this is a template name.944//945// FIXME: Find a way to still do typo correction in this case.946TemplateName Template =947Context.getAssumedTemplateName(NameInfo.getName());948return NameClassification::UndeclaredTemplate(Template);949}950951// In C, we first see whether there is a tag type by the same name, in952// which case it's likely that the user just forgot to write "enum",953// "struct", or "union".954if (!getLangOpts().CPlusPlus && !SecondTry &&955isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {956break;957}958959// Perform typo correction to determine if there is another name that is960// close to this name.961if (!SecondTry && CCC) {962SecondTry = true;963if (TypoCorrection Corrected =964CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,965&SS, *CCC, CTK_ErrorRecovery)) {966unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;967unsigned QualifiedDiag = diag::err_no_member_suggest;968969NamedDecl *FirstDecl = Corrected.getFoundDecl();970NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();971if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&972UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {973UnqualifiedDiag = diag::err_no_template_suggest;974QualifiedDiag = diag::err_no_member_template_suggest;975} else if (UnderlyingFirstDecl &&976(isa<TypeDecl>(UnderlyingFirstDecl) ||977isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||978isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {979UnqualifiedDiag = diag::err_unknown_typename_suggest;980QualifiedDiag = diag::err_unknown_nested_typename_suggest;981}982983if (SS.isEmpty()) {984diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);985} else {// FIXME: is this even reachable? Test it.986std::string CorrectedStr(Corrected.getAsString(getLangOpts()));987bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&988Name->getName() == CorrectedStr;989diagnoseTypo(Corrected, PDiag(QualifiedDiag)990<< Name << computeDeclContext(SS, false)991<< DroppedSpecifier << SS.getRange());992}993994// Update the name, so that the caller has the new name.995Name = Corrected.getCorrectionAsIdentifierInfo();996997// Typo correction corrected to a keyword.998if (Corrected.isKeyword())999return Name;10001001// Also update the LookupResult...1002// FIXME: This should probably go away at some point1003Result.clear();1004Result.setLookupName(Corrected.getCorrection());1005if (FirstDecl)1006Result.addDecl(FirstDecl);10071008// If we found an Objective-C instance variable, let1009// LookupInObjCMethod build the appropriate expression to1010// reference the ivar.1011// FIXME: This is a gross hack.1012if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {1013DeclResult R =1014ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());1015if (R.isInvalid())1016return NameClassification::Error();1017if (R.isUsable())1018return NameClassification::NonType(Ivar);1019}10201021goto Corrected;1022}1023}10241025// We failed to correct; just fall through and let the parser deal with it.1026Result.suppressDiagnostics();1027return NameClassification::Unknown();10281029case LookupResult::NotFoundInCurrentInstantiation: {1030// We performed name lookup into the current instantiation, and there were1031// dependent bases, so we treat this result the same way as any other1032// dependent nested-name-specifier.10331034// C++ [temp.res]p2:1035// A name used in a template declaration or definition and that is1036// dependent on a template-parameter is assumed not to name a type1037// unless the applicable name lookup finds a type name or the name is1038// qualified by the keyword typename.1039//1040// FIXME: If the next token is '<', we might want to ask the parser to1041// perform some heroics to see if we actually have a1042// template-argument-list, which would indicate a missing 'template'1043// keyword here.1044return NameClassification::DependentNonType();1045}10461047case LookupResult::Found:1048case LookupResult::FoundOverloaded:1049case LookupResult::FoundUnresolvedValue:1050break;10511052case LookupResult::Ambiguous:1053if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&1054hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,1055/*AllowDependent=*/false)) {1056// C++ [temp.local]p3:1057// A lookup that finds an injected-class-name (10.2) can result in an1058// ambiguity in certain cases (for example, if it is found in more than1059// one base class). If all of the injected-class-names that are found1060// refer to specializations of the same class template, and if the name1061// is followed by a template-argument-list, the reference refers to the1062// class template itself and not a specialization thereof, and is not1063// ambiguous.1064//1065// This filtering can make an ambiguous result into an unambiguous one,1066// so try again after filtering out template names.1067FilterAcceptableTemplateNames(Result);1068if (!Result.isAmbiguous()) {1069IsFilteredTemplateName = true;1070break;1071}1072}10731074// Diagnose the ambiguity and return an error.1075return NameClassification::Error();1076}10771078if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&1079(IsFilteredTemplateName ||1080hasAnyAcceptableTemplateNames(1081Result, /*AllowFunctionTemplates=*/true,1082/*AllowDependent=*/false,1083/*AllowNonTemplateFunctions*/ SS.isEmpty() &&1084getLangOpts().CPlusPlus20))) {1085// C++ [temp.names]p3:1086// After name lookup (3.4) finds that a name is a template-name or that1087// an operator-function-id or a literal- operator-id refers to a set of1088// overloaded functions any member of which is a function template if1089// this is followed by a <, the < is always taken as the delimiter of a1090// template-argument-list and never as the less-than operator.1091// C++2a [temp.names]p2:1092// A name is also considered to refer to a template if it is an1093// unqualified-id followed by a < and name lookup finds either one1094// or more functions or finds nothing.1095if (!IsFilteredTemplateName)1096FilterAcceptableTemplateNames(Result);10971098bool IsFunctionTemplate;1099bool IsVarTemplate;1100TemplateName Template;1101if (Result.end() - Result.begin() > 1) {1102IsFunctionTemplate = true;1103Template = Context.getOverloadedTemplateName(Result.begin(),1104Result.end());1105} else if (!Result.empty()) {1106auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(1107*Result.begin(), /*AllowFunctionTemplates=*/true,1108/*AllowDependent=*/false));1109IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);1110IsVarTemplate = isa<VarTemplateDecl>(TD);11111112UsingShadowDecl *FoundUsingShadow =1113dyn_cast<UsingShadowDecl>(*Result.begin());1114assert(!FoundUsingShadow ||1115TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));1116Template = Context.getQualifiedTemplateName(1117SS.getScopeRep(),1118/*TemplateKeyword=*/false,1119FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));1120} else {1121// All results were non-template functions. This is a function template1122// name.1123IsFunctionTemplate = true;1124Template = Context.getAssumedTemplateName(NameInfo.getName());1125}11261127if (IsFunctionTemplate) {1128// Function templates always go through overload resolution, at which1129// point we'll perform the various checks (e.g., accessibility) we need1130// to based on which function we selected.1131Result.suppressDiagnostics();11321133return NameClassification::FunctionTemplate(Template);1134}11351136return IsVarTemplate ? NameClassification::VarTemplate(Template)1137: NameClassification::TypeTemplate(Template);1138}11391140auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {1141QualType T = Context.getTypeDeclType(Type);1142if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))1143T = Context.getUsingType(USD, T);1144return buildNamedType(*this, &SS, T, NameLoc);1145};11461147NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();1148if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {1149DiagnoseUseOfDecl(Type, NameLoc);1150MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);1151return BuildTypeFor(Type, *Result.begin());1152}11531154ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);1155if (!Class) {1156// FIXME: It's unfortunate that we don't have a Type node for handling this.1157if (ObjCCompatibleAliasDecl *Alias =1158dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))1159Class = Alias->getClassInterface();1160}11611162if (Class) {1163DiagnoseUseOfDecl(Class, NameLoc);11641165if (NextToken.is(tok::period)) {1166// Interface. <something> is parsed as a property reference expression.1167// Just return "unknown" as a fall-through for now.1168Result.suppressDiagnostics();1169return NameClassification::Unknown();1170}11711172QualType T = Context.getObjCInterfaceType(Class);1173return ParsedType::make(T);1174}11751176if (isa<ConceptDecl>(FirstDecl)) {1177// We want to preserve the UsingShadowDecl for concepts.1178if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))1179return NameClassification::Concept(TemplateName(USD));1180return NameClassification::Concept(1181TemplateName(cast<TemplateDecl>(FirstDecl)));1182}11831184if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {1185(void)DiagnoseUseOfDecl(EmptyD, NameLoc);1186return NameClassification::Error();1187}11881189// We can have a type template here if we're classifying a template argument.1190if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&1191!isa<VarTemplateDecl>(FirstDecl))1192return NameClassification::TypeTemplate(1193TemplateName(cast<TemplateDecl>(FirstDecl)));11941195// Check for a tag type hidden by a non-type decl in a few cases where it1196// seems likely a type is wanted instead of the non-type that was found.1197bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);1198if ((NextToken.is(tok::identifier) ||1199(NextIsOp &&1200FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&1201isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {1202TypeDecl *Type = Result.getAsSingle<TypeDecl>();1203DiagnoseUseOfDecl(Type, NameLoc);1204return BuildTypeFor(Type, *Result.begin());1205}12061207// If we already know which single declaration is referenced, just annotate1208// that declaration directly. Defer resolving even non-overloaded class1209// member accesses, as we need to defer certain access checks until we know1210// the context.1211bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));1212if (Result.isSingleResult() && !ADL &&1213(!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))1214return NameClassification::NonType(Result.getRepresentativeDecl());12151216// Otherwise, this is an overload set that we will need to resolve later.1217Result.suppressDiagnostics();1218return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(1219Context, Result.getNamingClass(), SS.getWithLocInContext(Context),1220Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),1221/*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));1222}12231224ExprResult1225Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,1226SourceLocation NameLoc) {1227assert(getLangOpts().CPlusPlus && "ADL-only call in C?");1228CXXScopeSpec SS;1229LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);1230return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);1231}12321233ExprResult1234Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,1235IdentifierInfo *Name,1236SourceLocation NameLoc,1237bool IsAddressOfOperand) {1238DeclarationNameInfo NameInfo(Name, NameLoc);1239return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),1240NameInfo, IsAddressOfOperand,1241/*TemplateArgs=*/nullptr);1242}12431244ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,1245NamedDecl *Found,1246SourceLocation NameLoc,1247const Token &NextToken) {1248if (getCurMethodDecl() && SS.isEmpty())1249if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))1250return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);12511252// Reconstruct the lookup result.1253LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);1254Result.addDecl(Found);1255Result.resolveKind();12561257bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));1258return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);1259}12601261ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {1262// For an implicit class member access, transform the result into a member1263// access expression if necessary.1264auto *ULE = cast<UnresolvedLookupExpr>(E);1265if ((*ULE->decls_begin())->isCXXClassMember()) {1266CXXScopeSpec SS;1267SS.Adopt(ULE->getQualifierLoc());12681269// Reconstruct the lookup result.1270LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),1271LookupOrdinaryName);1272Result.setNamingClass(ULE->getNamingClass());1273for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)1274Result.addDecl(*I, I.getAccess());1275Result.resolveKind();1276return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,1277nullptr, S);1278}12791280// Otherwise, this is already in the form we needed, and no further checks1281// are necessary.1282return ULE;1283}12841285Sema::TemplateNameKindForDiagnostics1286Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {1287auto *TD = Name.getAsTemplateDecl();1288if (!TD)1289return TemplateNameKindForDiagnostics::DependentTemplate;1290if (isa<ClassTemplateDecl>(TD))1291return TemplateNameKindForDiagnostics::ClassTemplate;1292if (isa<FunctionTemplateDecl>(TD))1293return TemplateNameKindForDiagnostics::FunctionTemplate;1294if (isa<VarTemplateDecl>(TD))1295return TemplateNameKindForDiagnostics::VarTemplate;1296if (isa<TypeAliasTemplateDecl>(TD))1297return TemplateNameKindForDiagnostics::AliasTemplate;1298if (isa<TemplateTemplateParmDecl>(TD))1299return TemplateNameKindForDiagnostics::TemplateTemplateParam;1300if (isa<ConceptDecl>(TD))1301return TemplateNameKindForDiagnostics::Concept;1302return TemplateNameKindForDiagnostics::DependentTemplate;1303}13041305void Sema::PushDeclContext(Scope *S, DeclContext *DC) {1306assert(DC->getLexicalParent() == CurContext &&1307"The next DeclContext should be lexically contained in the current one.");1308CurContext = DC;1309S->setEntity(DC);1310}13111312void Sema::PopDeclContext() {1313assert(CurContext && "DeclContext imbalance!");13141315CurContext = CurContext->getLexicalParent();1316assert(CurContext && "Popped translation unit!");1317}13181319Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,1320Decl *D) {1321// Unlike PushDeclContext, the context to which we return is not necessarily1322// the containing DC of TD, because the new context will be some pre-existing1323// TagDecl definition instead of a fresh one.1324auto Result = static_cast<SkippedDefinitionContext>(CurContext);1325CurContext = cast<TagDecl>(D)->getDefinition();1326assert(CurContext && "skipping definition of undefined tag");1327// Start lookups from the parent of the current context; we don't want to look1328// into the pre-existing complete definition.1329S->setEntity(CurContext->getLookupParent());1330return Result;1331}13321333void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {1334CurContext = static_cast<decltype(CurContext)>(Context);1335}13361337void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {1338// C++0x [basic.lookup.unqual]p13:1339// A name used in the definition of a static data member of class1340// X (after the qualified-id of the static member) is looked up as1341// if the name was used in a member function of X.1342// C++0x [basic.lookup.unqual]p14:1343// If a variable member of a namespace is defined outside of the1344// scope of its namespace then any name used in the definition of1345// the variable member (after the declarator-id) is looked up as1346// if the definition of the variable member occurred in its1347// namespace.1348// Both of these imply that we should push a scope whose context1349// is the semantic context of the declaration. We can't use1350// PushDeclContext here because that context is not necessarily1351// lexically contained in the current context. Fortunately,1352// the containing scope should have the appropriate information.13531354assert(!S->getEntity() && "scope already has entity");13551356#ifndef NDEBUG1357Scope *Ancestor = S->getParent();1358while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();1359assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");1360#endif13611362CurContext = DC;1363S->setEntity(DC);13641365if (S->getParent()->isTemplateParamScope()) {1366// Also set the corresponding entities for all immediately-enclosing1367// template parameter scopes.1368EnterTemplatedContext(S->getParent(), DC);1369}1370}13711372void Sema::ExitDeclaratorContext(Scope *S) {1373assert(S->getEntity() == CurContext && "Context imbalance!");13741375// Switch back to the lexical context. The safety of this is1376// enforced by an assert in EnterDeclaratorContext.1377Scope *Ancestor = S->getParent();1378while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();1379CurContext = Ancestor->getEntity();13801381// We don't need to do anything with the scope, which is going to1382// disappear.1383}13841385void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {1386assert(S->isTemplateParamScope() &&1387"expected to be initializing a template parameter scope");13881389// C++20 [temp.local]p7:1390// In the definition of a member of a class template that appears outside1391// of the class template definition, the name of a member of the class1392// template hides the name of a template-parameter of any enclosing class1393// templates (but not a template-parameter of the member if the member is a1394// class or function template).1395// C++20 [temp.local]p9:1396// In the definition of a class template or in the definition of a member1397// of such a template that appears outside of the template definition, for1398// each non-dependent base class (13.8.2.1), if the name of the base class1399// or the name of a member of the base class is the same as the name of a1400// template-parameter, the base class name or member name hides the1401// template-parameter name (6.4.10).1402//1403// This means that a template parameter scope should be searched immediately1404// after searching the DeclContext for which it is a template parameter1405// scope. For example, for1406// template<typename T> template<typename U> template<typename V>1407// void N::A<T>::B<U>::f(...)1408// we search V then B<U> (and base classes) then U then A<T> (and base1409// classes) then T then N then ::.1410unsigned ScopeDepth = getTemplateDepth(S);1411for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {1412DeclContext *SearchDCAfterScope = DC;1413for (; DC; DC = DC->getLookupParent()) {1414if (const TemplateParameterList *TPL =1415cast<Decl>(DC)->getDescribedTemplateParams()) {1416unsigned DCDepth = TPL->getDepth() + 1;1417if (DCDepth > ScopeDepth)1418continue;1419if (ScopeDepth == DCDepth)1420SearchDCAfterScope = DC = DC->getLookupParent();1421break;1422}1423}1424S->setLookupEntity(SearchDCAfterScope);1425}1426}14271428void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {1429// We assume that the caller has already called1430// ActOnReenterTemplateScope so getTemplatedDecl() works.1431FunctionDecl *FD = D->getAsFunction();1432if (!FD)1433return;14341435// Same implementation as PushDeclContext, but enters the context1436// from the lexical parent, rather than the top-level class.1437assert(CurContext == FD->getLexicalParent() &&1438"The next DeclContext should be lexically contained in the current one.");1439CurContext = FD;1440S->setEntity(CurContext);14411442for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {1443ParmVarDecl *Param = FD->getParamDecl(P);1444// If the parameter has an identifier, then add it to the scope1445if (Param->getIdentifier()) {1446S->AddDecl(Param);1447IdResolver.AddDecl(Param);1448}1449}1450}14511452void Sema::ActOnExitFunctionContext() {1453// Same implementation as PopDeclContext, but returns to the lexical parent,1454// rather than the top-level class.1455assert(CurContext && "DeclContext imbalance!");1456CurContext = CurContext->getLexicalParent();1457assert(CurContext && "Popped translation unit!");1458}14591460/// Determine whether overloading is allowed for a new function1461/// declaration considering prior declarations of the same name.1462///1463/// This routine determines whether overloading is possible, not1464/// whether a new declaration actually overloads a previous one.1465/// It will return true in C++ (where overloads are always permitted)1466/// or, as a C extension, when either the new declaration or a1467/// previous one is declared with the 'overloadable' attribute.1468static bool AllowOverloadingOfFunction(const LookupResult &Previous,1469ASTContext &Context,1470const FunctionDecl *New) {1471if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())1472return true;14731474// Multiversion function declarations are not overloads in the1475// usual sense of that term, but lookup will report that an1476// overload set was found if more than one multiversion function1477// declaration is present for the same name. It is therefore1478// inadequate to assume that some prior declaration(s) had1479// the overloadable attribute; checking is required. Since one1480// declaration is permitted to omit the attribute, it is necessary1481// to check at least two; hence the 'any_of' check below. Note that1482// the overloadable attribute is implicitly added to declarations1483// that were required to have it but did not.1484if (Previous.getResultKind() == LookupResult::FoundOverloaded) {1485return llvm::any_of(Previous, [](const NamedDecl *ND) {1486return ND->hasAttr<OverloadableAttr>();1487});1488} else if (Previous.getResultKind() == LookupResult::Found)1489return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();14901491return false;1492}14931494void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {1495// Move up the scope chain until we find the nearest enclosing1496// non-transparent context. The declaration will be introduced into this1497// scope.1498while (S->getEntity() && S->getEntity()->isTransparentContext())1499S = S->getParent();15001501// Add scoped declarations into their context, so that they can be1502// found later. Declarations without a context won't be inserted1503// into any context.1504if (AddToContext)1505CurContext->addDecl(D);15061507// Out-of-line definitions shouldn't be pushed into scope in C++, unless they1508// are function-local declarations.1509if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())1510return;15111512// Template instantiations should also not be pushed into scope.1513if (isa<FunctionDecl>(D) &&1514cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())1515return;15161517if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {1518S->AddDecl(D);1519return;1520}1521// If this replaces anything in the current scope,1522IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),1523IEnd = IdResolver.end();1524for (; I != IEnd; ++I) {1525if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {1526S->RemoveDecl(*I);1527IdResolver.RemoveDecl(*I);15281529// Should only need to replace one decl.1530break;1531}1532}15331534S->AddDecl(D);15351536if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {1537// Implicitly-generated labels may end up getting generated in an order that1538// isn't strictly lexical, which breaks name lookup. Be careful to insert1539// the label at the appropriate place in the identifier chain.1540for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {1541DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();1542if (IDC == CurContext) {1543if (!S->isDeclScope(*I))1544continue;1545} else if (IDC->Encloses(CurContext))1546break;1547}15481549IdResolver.InsertDeclAfter(I, D);1550} else {1551IdResolver.AddDecl(D);1552}1553warnOnReservedIdentifier(D);1554}15551556bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,1557bool AllowInlineNamespace) const {1558return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);1559}15601561Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {1562DeclContext *TargetDC = DC->getPrimaryContext();1563do {1564if (DeclContext *ScopeDC = S->getEntity())1565if (ScopeDC->getPrimaryContext() == TargetDC)1566return S;1567} while ((S = S->getParent()));15681569return nullptr;1570}15711572static bool isOutOfScopePreviousDeclaration(NamedDecl *,1573DeclContext*,1574ASTContext&);15751576void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,1577bool ConsiderLinkage,1578bool AllowInlineNamespace) {1579LookupResult::Filter F = R.makeFilter();1580while (F.hasNext()) {1581NamedDecl *D = F.next();15821583if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))1584continue;15851586if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))1587continue;15881589F.erase();1590}15911592F.done();1593}15941595bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {1596// [module.interface]p7:1597// A declaration is attached to a module as follows:1598// - If the declaration is a non-dependent friend declaration that nominates a1599// function with a declarator-id that is a qualified-id or template-id or that1600// nominates a class other than with an elaborated-type-specifier with neither1601// a nested-name-specifier nor a simple-template-id, it is attached to the1602// module to which the friend is attached ([basic.link]).1603if (New->getFriendObjectKind() &&1604Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {1605New->setLocalOwningModule(Old->getOwningModule());1606makeMergedDefinitionVisible(New);1607return false;1608}16091610Module *NewM = New->getOwningModule();1611Module *OldM = Old->getOwningModule();16121613if (NewM && NewM->isPrivateModule())1614NewM = NewM->Parent;1615if (OldM && OldM->isPrivateModule())1616OldM = OldM->Parent;16171618if (NewM == OldM)1619return false;16201621if (NewM && OldM) {1622// A module implementation unit has visibility of the decls in its1623// implicitly imported interface.1624if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)1625return false;16261627// Partitions are part of the module, but a partition could import another1628// module, so verify that the PMIs agree.1629if ((NewM->isModulePartition() || OldM->isModulePartition()) &&1630getASTContext().isInSameModule(NewM, OldM))1631return false;1632}16331634bool NewIsModuleInterface = NewM && NewM->isNamedModule();1635bool OldIsModuleInterface = OldM && OldM->isNamedModule();1636if (NewIsModuleInterface || OldIsModuleInterface) {1637// C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:1638// if a declaration of D [...] appears in the purview of a module, all1639// other such declarations shall appear in the purview of the same module1640Diag(New->getLocation(), diag::err_mismatched_owning_module)1641<< New1642<< NewIsModuleInterface1643<< (NewIsModuleInterface ? NewM->getFullModuleName() : "")1644<< OldIsModuleInterface1645<< (OldIsModuleInterface ? OldM->getFullModuleName() : "");1646Diag(Old->getLocation(), diag::note_previous_declaration);1647New->setInvalidDecl();1648return true;1649}16501651return false;1652}16531654bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {1655// [module.interface]p1:1656// An export-declaration shall inhabit a namespace scope.1657//1658// So it is meaningless to talk about redeclaration which is not at namespace1659// scope.1660if (!New->getLexicalDeclContext()1661->getNonTransparentContext()1662->isFileContext() ||1663!Old->getLexicalDeclContext()1664->getNonTransparentContext()1665->isFileContext())1666return false;16671668bool IsNewExported = New->isInExportDeclContext();1669bool IsOldExported = Old->isInExportDeclContext();16701671// It should be irrevelant if both of them are not exported.1672if (!IsNewExported && !IsOldExported)1673return false;16741675if (IsOldExported)1676return false;16771678// If the Old declaration are not attached to named modules1679// and the New declaration are attached to global module.1680// It should be fine to allow the export since it doesn't change1681// the linkage of declarations. See1682// https://github.com/llvm/llvm-project/issues/98583 for details.1683if (!Old->isInNamedModule() && New->getOwningModule() &&1684New->getOwningModule()->isImplicitGlobalModule())1685return false;16861687assert(IsNewExported);16881689auto Lk = Old->getFormalLinkage();1690int S = 0;1691if (Lk == Linkage::Internal)1692S = 1;1693else if (Lk == Linkage::Module)1694S = 2;1695Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;1696Diag(Old->getLocation(), diag::note_previous_declaration);1697return true;1698}16991700bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {1701if (CheckRedeclarationModuleOwnership(New, Old))1702return true;17031704if (CheckRedeclarationExported(New, Old))1705return true;17061707return false;1708}17091710bool Sema::IsRedefinitionInModule(const NamedDecl *New,1711const NamedDecl *Old) const {1712assert(getASTContext().isSameEntity(New, Old) &&1713"New and Old are not the same definition, we should diagnostic it "1714"immediately instead of checking it.");1715assert(const_cast<Sema *>(this)->isReachable(New) &&1716const_cast<Sema *>(this)->isReachable(Old) &&1717"We shouldn't see unreachable definitions here.");17181719Module *NewM = New->getOwningModule();1720Module *OldM = Old->getOwningModule();17211722// We only checks for named modules here. The header like modules is skipped.1723// FIXME: This is not right if we import the header like modules in the module1724// purview.1725//1726// For example, assuming "header.h" provides definition for `D`.1727// ```C++1728// //--- M.cppm1729// export module M;1730// import "header.h"; // or #include "header.h" but import it by clang modules1731// actually.1732//1733// //--- Use.cpp1734// import M;1735// import "header.h"; // or uses clang modules.1736// ```1737//1738// In this case, `D` has multiple definitions in multiple TU (M.cppm and1739// Use.cpp) and `D` is attached to a named module `M`. The compiler should1740// reject it. But the current implementation couldn't detect the case since we1741// don't record the information about the importee modules.1742//1743// But this might not be painful in practice. Since the design of C++20 Named1744// Modules suggests us to use headers in global module fragment instead of1745// module purview.1746if (NewM && NewM->isHeaderLikeModule())1747NewM = nullptr;1748if (OldM && OldM->isHeaderLikeModule())1749OldM = nullptr;17501751if (!NewM && !OldM)1752return true;17531754// [basic.def.odr]p14.31755// Each such definition shall not be attached to a named module1756// ([module.unit]).1757if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))1758return true;17591760// Then New and Old lives in the same TU if their share one same module unit.1761if (NewM)1762NewM = NewM->getTopLevelModule();1763if (OldM)1764OldM = OldM->getTopLevelModule();1765return OldM == NewM;1766}17671768static bool isUsingDeclNotAtClassScope(NamedDecl *D) {1769if (D->getDeclContext()->isFileContext())1770return false;17711772return isa<UsingShadowDecl>(D) ||1773isa<UnresolvedUsingTypenameDecl>(D) ||1774isa<UnresolvedUsingValueDecl>(D);1775}17761777/// Removes using shadow declarations not at class scope from the lookup1778/// results.1779static void RemoveUsingDecls(LookupResult &R) {1780LookupResult::Filter F = R.makeFilter();1781while (F.hasNext())1782if (isUsingDeclNotAtClassScope(F.next()))1783F.erase();17841785F.done();1786}17871788/// Check for this common pattern:1789/// @code1790/// class S {1791/// S(const S&); // DO NOT IMPLEMENT1792/// void operator=(const S&); // DO NOT IMPLEMENT1793/// };1794/// @endcode1795static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {1796// FIXME: Should check for private access too but access is set after we get1797// the decl here.1798if (D->doesThisDeclarationHaveABody())1799return false;18001801if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))1802return CD->isCopyConstructor();1803return D->isCopyAssignmentOperator();1804}18051806bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {1807const DeclContext *DC = D->getDeclContext();1808while (!DC->isTranslationUnit()) {1809if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){1810if (!RD->hasNameForLinkage())1811return true;1812}1813DC = DC->getParent();1814}18151816return !D->isExternallyVisible();1817}18181819// FIXME: This needs to be refactored; some other isInMainFile users want1820// these semantics.1821static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {1822if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)1823return false;1824return S.SourceMgr.isInMainFile(Loc);1825}18261827bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {1828assert(D);18291830if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())1831return false;18321833// Ignore all entities declared within templates, and out-of-line definitions1834// of members of class templates.1835if (D->getDeclContext()->isDependentContext() ||1836D->getLexicalDeclContext()->isDependentContext())1837return false;18381839if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {1840if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)1841return false;1842// A non-out-of-line declaration of a member specialization was implicitly1843// instantiated; it's the out-of-line declaration that we're interested in.1844if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&1845FD->getMemberSpecializationInfo() && !FD->isOutOfLine())1846return false;18471848if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {1849if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))1850return false;1851} else {1852// 'static inline' functions are defined in headers; don't warn.1853if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))1854return false;1855}18561857if (FD->doesThisDeclarationHaveABody() &&1858Context.DeclMustBeEmitted(FD))1859return false;1860} else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {1861// Constants and utility variables are defined in headers with internal1862// linkage; don't warn. (Unlike functions, there isn't a convenient marker1863// like "inline".)1864if (!isMainFileLoc(*this, VD->getLocation()))1865return false;18661867if (Context.DeclMustBeEmitted(VD))1868return false;18691870if (VD->isStaticDataMember() &&1871VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)1872return false;1873if (VD->isStaticDataMember() &&1874VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&1875VD->getMemberSpecializationInfo() && !VD->isOutOfLine())1876return false;18771878if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))1879return false;1880} else {1881return false;1882}18831884// Only warn for unused decls internal to the translation unit.1885// FIXME: This seems like a bogus check; it suppresses -Wunused-function1886// for inline functions defined in the main source file, for instance.1887return mightHaveNonExternalLinkage(D);1888}18891890void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {1891if (!D)1892return;18931894if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {1895const FunctionDecl *First = FD->getFirstDecl();1896if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))1897return; // First should already be in the vector.1898}18991900if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {1901const VarDecl *First = VD->getFirstDecl();1902if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))1903return; // First should already be in the vector.1904}19051906if (ShouldWarnIfUnusedFileScopedDecl(D))1907UnusedFileScopedDecls.push_back(D);1908}19091910static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,1911const NamedDecl *D) {1912if (D->isInvalidDecl())1913return false;19141915if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {1916// For a decomposition declaration, warn if none of the bindings are1917// referenced, instead of if the variable itself is referenced (which1918// it is, by the bindings' expressions).1919bool IsAllPlaceholders = true;1920for (const auto *BD : DD->bindings()) {1921if (BD->isReferenced() || BD->hasAttr<UnusedAttr>())1922return false;1923IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);1924}1925if (IsAllPlaceholders)1926return false;1927} else if (!D->getDeclName()) {1928return false;1929} else if (D->isReferenced() || D->isUsed()) {1930return false;1931}19321933if (D->isPlaceholderVar(LangOpts))1934return false;19351936if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||1937D->hasAttr<CleanupAttr>())1938return false;19391940if (isa<LabelDecl>(D))1941return true;19421943// Except for labels, we only care about unused decls that are local to1944// functions.1945bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();1946if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))1947// For dependent types, the diagnostic is deferred.1948WithinFunction =1949WithinFunction || (R->isLocalClass() && !R->isDependentType());1950if (!WithinFunction)1951return false;19521953if (isa<TypedefNameDecl>(D))1954return true;19551956// White-list anything that isn't a local variable.1957if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))1958return false;19591960// Types of valid local variables should be complete, so this should succeed.1961if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {19621963const Expr *Init = VD->getInit();1964if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))1965Init = Cleanups->getSubExpr();19661967const auto *Ty = VD->getType().getTypePtr();19681969// Only look at the outermost level of typedef.1970if (const TypedefType *TT = Ty->getAs<TypedefType>()) {1971// Allow anything marked with __attribute__((unused)).1972if (TT->getDecl()->hasAttr<UnusedAttr>())1973return false;1974}19751976// Warn for reference variables whose initializtion performs lifetime1977// extension.1978if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);1979MTE && MTE->getExtendingDecl()) {1980Ty = VD->getType().getNonReferenceType().getTypePtr();1981Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();1982}19831984// If we failed to complete the type for some reason, or if the type is1985// dependent, don't diagnose the variable.1986if (Ty->isIncompleteType() || Ty->isDependentType())1987return false;19881989// Look at the element type to ensure that the warning behaviour is1990// consistent for both scalars and arrays.1991Ty = Ty->getBaseElementTypeUnsafe();19921993if (const TagType *TT = Ty->getAs<TagType>()) {1994const TagDecl *Tag = TT->getDecl();1995if (Tag->hasAttr<UnusedAttr>())1996return false;19971998if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {1999if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())2000return false;20012002if (Init) {2003const auto *Construct =2004dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());2005if (Construct && !Construct->isElidable()) {2006const CXXConstructorDecl *CD = Construct->getConstructor();2007if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&2008(VD->getInit()->isValueDependent() || !VD->evaluateValue()))2009return false;2010}20112012// Suppress the warning if we don't know how this is constructed, and2013// it could possibly be non-trivial constructor.2014if (Init->isTypeDependent()) {2015for (const CXXConstructorDecl *Ctor : RD->ctors())2016if (!Ctor->isTrivial())2017return false;2018}20192020// Suppress the warning if the constructor is unresolved because2021// its arguments are dependent.2022if (isa<CXXUnresolvedConstructExpr>(Init))2023return false;2024}2025}2026}20272028// TODO: __attribute__((unused)) templates?2029}20302031return true;2032}20332034static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,2035FixItHint &Hint) {2036if (isa<LabelDecl>(D)) {2037SourceLocation AfterColon = Lexer::findLocationAfterToken(2038D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),2039/*SkipTrailingWhitespaceAndNewline=*/false);2040if (AfterColon.isInvalid())2041return;2042Hint = FixItHint::CreateRemoval(2043CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));2044}2045}20462047void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {2048DiagnoseUnusedNestedTypedefs(2049D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });2050}20512052void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,2053DiagReceiverTy DiagReceiver) {2054if (D->getTypeForDecl()->isDependentType())2055return;20562057for (auto *TmpD : D->decls()) {2058if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))2059DiagnoseUnusedDecl(T, DiagReceiver);2060else if(const auto *R = dyn_cast<RecordDecl>(TmpD))2061DiagnoseUnusedNestedTypedefs(R, DiagReceiver);2062}2063}20642065void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {2066DiagnoseUnusedDecl(2067D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });2068}20692070void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {2071if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D))2072return;20732074if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {2075// typedefs can be referenced later on, so the diagnostics are emitted2076// at end-of-translation-unit.2077UnusedLocalTypedefNameCandidates.insert(TD);2078return;2079}20802081FixItHint Hint;2082GenerateFixForUnusedDecl(D, Context, Hint);20832084unsigned DiagID;2085if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())2086DiagID = diag::warn_unused_exception_param;2087else if (isa<LabelDecl>(D))2088DiagID = diag::warn_unused_label;2089else2090DiagID = diag::warn_unused_variable;20912092SourceLocation DiagLoc = D->getLocation();2093DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));2094}20952096void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,2097DiagReceiverTy DiagReceiver) {2098// If it's not referenced, it can't be set. If it has the Cleanup attribute,2099// it's not really unused.2100if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())2101return;21022103// In C++, `_` variables behave as if they were maybe_unused2104if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))2105return;21062107const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();21082109if (Ty->isReferenceType() || Ty->isDependentType())2110return;21112112if (const TagType *TT = Ty->getAs<TagType>()) {2113const TagDecl *Tag = TT->getDecl();2114if (Tag->hasAttr<UnusedAttr>())2115return;2116// In C++, don't warn for record types that don't have WarnUnusedAttr, to2117// mimic gcc's behavior.2118if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);2119RD && !RD->hasAttr<WarnUnusedAttr>())2120return;2121}21222123// Don't warn about __block Objective-C pointer variables, as they might2124// be assigned in the block but not used elsewhere for the purpose of lifetime2125// extension.2126if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())2127return;21282129// Don't warn about Objective-C pointer variables with precise lifetime2130// semantics; they can be used to ensure ARC releases the object at a known2131// time, which may mean assignment but no other references.2132if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())2133return;21342135auto iter = RefsMinusAssignments.find(VD);2136if (iter == RefsMinusAssignments.end())2137return;21382139assert(iter->getSecond() >= 0 &&2140"Found a negative number of references to a VarDecl");2141if (int RefCnt = iter->getSecond(); RefCnt > 0) {2142// Assume the given VarDecl is "used" if its ref count stored in2143// `RefMinusAssignments` is positive, with one exception.2144//2145// For a C++ variable whose decl (with initializer) entirely consist the2146// condition expression of a if/while/for construct,2147// Clang creates a DeclRefExpr for the condition expression rather than a2148// BinaryOperator of AssignmentOp. Thus, the C++ variable's ref2149// count stored in `RefMinusAssignment` equals 1 when the variable is never2150// used in the body of the if/while/for construct.2151bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);2152if (!UnusedCXXCondDecl)2153return;2154}21552156unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter2157: diag::warn_unused_but_set_variable;2158DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);2159}21602161static void CheckPoppedLabel(LabelDecl *L, Sema &S,2162Sema::DiagReceiverTy DiagReceiver) {2163// Verify that we have no forward references left. If so, there was a goto2164// or address of a label taken, but no definition of it. Label fwd2165// definitions are indicated with a null substmt which is also not a resolved2166// MS inline assembly label name.2167bool Diagnose = false;2168if (L->isMSAsmLabel())2169Diagnose = !L->isResolvedMSAsmLabel();2170else2171Diagnose = L->getStmt() == nullptr;2172if (Diagnose)2173DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)2174<< L);2175}21762177void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {2178S->applyNRVO();21792180if (S->decl_empty()) return;2181assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&2182"Scope shouldn't contain decls!");21832184/// We visit the decls in non-deterministic order, but we want diagnostics2185/// emitted in deterministic order. Collect any diagnostic that may be emitted2186/// and sort the diagnostics before emitting them, after we visited all decls.2187struct LocAndDiag {2188SourceLocation Loc;2189std::optional<SourceLocation> PreviousDeclLoc;2190PartialDiagnostic PD;2191};2192SmallVector<LocAndDiag, 16> DeclDiags;2193auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {2194DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});2195};2196auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,2197SourceLocation PreviousDeclLoc,2198PartialDiagnostic PD) {2199DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});2200};22012202for (auto *TmpD : S->decls()) {2203assert(TmpD && "This decl didn't get pushed??");22042205assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");2206NamedDecl *D = cast<NamedDecl>(TmpD);22072208// Diagnose unused variables in this scope.2209if (!S->hasUnrecoverableErrorOccurred()) {2210DiagnoseUnusedDecl(D, addDiag);2211if (const auto *RD = dyn_cast<RecordDecl>(D))2212DiagnoseUnusedNestedTypedefs(RD, addDiag);2213if (VarDecl *VD = dyn_cast<VarDecl>(D)) {2214DiagnoseUnusedButSetDecl(VD, addDiag);2215RefsMinusAssignments.erase(VD);2216}2217}22182219if (!D->getDeclName()) continue;22202221// If this was a forward reference to a label, verify it was defined.2222if (LabelDecl *LD = dyn_cast<LabelDecl>(D))2223CheckPoppedLabel(LD, *this, addDiag);22242225// Partial translation units that are created in incremental processing must2226// not clean up the IdResolver because PTUs should take into account the2227// declarations that came from previous PTUs.2228if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||2229getLangOpts().CPlusPlus)2230IdResolver.RemoveDecl(D);22312232// Warn on it if we are shadowing a declaration.2233auto ShadowI = ShadowingDecls.find(D);2234if (ShadowI != ShadowingDecls.end()) {2235if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {2236addDiagWithPrev(D->getLocation(), FD->getLocation(),2237PDiag(diag::warn_ctor_parm_shadows_field)2238<< D << FD << FD->getParent());2239}2240ShadowingDecls.erase(ShadowI);2241}2242}22432244llvm::sort(DeclDiags,2245[](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {2246// The particular order for diagnostics is not important, as long2247// as the order is deterministic. Using the raw location is going2248// to generally be in source order unless there are macro2249// expansions involved.2250return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();2251});2252for (const LocAndDiag &D : DeclDiags) {2253Diag(D.Loc, D.PD);2254if (D.PreviousDeclLoc)2255Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);2256}2257}22582259Scope *Sema::getNonFieldDeclScope(Scope *S) {2260while (((S->getFlags() & Scope::DeclScope) == 0) ||2261(S->getEntity() && S->getEntity()->isTransparentContext()) ||2262(S->isClassScope() && !getLangOpts().CPlusPlus))2263S = S->getParent();2264return S;2265}22662267static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,2268ASTContext::GetBuiltinTypeError Error) {2269switch (Error) {2270case ASTContext::GE_None:2271return "";2272case ASTContext::GE_Missing_type:2273return BuiltinInfo.getHeaderName(ID);2274case ASTContext::GE_Missing_stdio:2275return "stdio.h";2276case ASTContext::GE_Missing_setjmp:2277return "setjmp.h";2278case ASTContext::GE_Missing_ucontext:2279return "ucontext.h";2280}2281llvm_unreachable("unhandled error kind");2282}22832284FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,2285unsigned ID, SourceLocation Loc) {2286DeclContext *Parent = Context.getTranslationUnitDecl();22872288if (getLangOpts().CPlusPlus) {2289LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(2290Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);2291CLinkageDecl->setImplicit();2292Parent->addDecl(CLinkageDecl);2293Parent = CLinkageDecl;2294}22952296ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;2297if (Context.BuiltinInfo.isImmediate(ID)) {2298assert(getLangOpts().CPlusPlus20 &&2299"consteval builtins should only be available in C++20 mode");2300ConstexprKind = ConstexprSpecKind::Consteval;2301}23022303FunctionDecl *New = FunctionDecl::Create(2304Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,2305getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,2306Type->isFunctionProtoType(), ConstexprKind);2307New->setImplicit();2308New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));23092310// Create Decl objects for each parameter, adding them to the2311// FunctionDecl.2312if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {2313SmallVector<ParmVarDecl *, 16> Params;2314for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {2315ParmVarDecl *parm = ParmVarDecl::Create(2316Context, New, SourceLocation(), SourceLocation(), nullptr,2317FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);2318parm->setScopeInfo(0, i);2319Params.push_back(parm);2320}2321New->setParams(Params);2322}23232324AddKnownFunctionAttributes(New);2325return New;2326}23272328NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,2329Scope *S, bool ForRedeclaration,2330SourceLocation Loc) {2331LookupNecessaryTypesForBuiltin(S, ID);23322333ASTContext::GetBuiltinTypeError Error;2334QualType R = Context.GetBuiltinType(ID, Error);2335if (Error) {2336if (!ForRedeclaration)2337return nullptr;23382339// If we have a builtin without an associated type we should not emit a2340// warning when we were not able to find a type for it.2341if (Error == ASTContext::GE_Missing_type ||2342Context.BuiltinInfo.allowTypeMismatch(ID))2343return nullptr;23442345// If we could not find a type for setjmp it is because the jmp_buf type was2346// not defined prior to the setjmp declaration.2347if (Error == ASTContext::GE_Missing_setjmp) {2348Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)2349<< Context.BuiltinInfo.getName(ID);2350return nullptr;2351}23522353// Generally, we emit a warning that the declaration requires the2354// appropriate header.2355Diag(Loc, diag::warn_implicit_decl_requires_sysheader)2356<< getHeaderName(Context.BuiltinInfo, ID, Error)2357<< Context.BuiltinInfo.getName(ID);2358return nullptr;2359}23602361if (!ForRedeclaration &&2362(Context.BuiltinInfo.isPredefinedLibFunction(ID) ||2363Context.BuiltinInfo.isHeaderDependentFunction(ID))) {2364Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c992365: diag::ext_implicit_lib_function_decl)2366<< Context.BuiltinInfo.getName(ID) << R;2367if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))2368Diag(Loc, diag::note_include_header_or_declare)2369<< Header << Context.BuiltinInfo.getName(ID);2370}23712372if (R.isNull())2373return nullptr;23742375FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);2376RegisterLocallyScopedExternCDecl(New, S);23772378// TUScope is the translation-unit scope to insert this function into.2379// FIXME: This is hideous. We need to teach PushOnScopeChains to2380// relate Scopes to DeclContexts, and probably eliminate CurContext2381// entirely, but we're not there yet.2382DeclContext *SavedContext = CurContext;2383CurContext = New->getDeclContext();2384PushOnScopeChains(New, TUScope);2385CurContext = SavedContext;2386return New;2387}23882389/// Typedef declarations don't have linkage, but they still denote the same2390/// entity if their types are the same.2391/// FIXME: This is notionally doing the same thing as ASTReaderDecl's2392/// isSameEntity.2393static void2394filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,2395LookupResult &Previous) {2396// This is only interesting when modules are enabled.2397if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)2398return;23992400// Empty sets are uninteresting.2401if (Previous.empty())2402return;24032404LookupResult::Filter Filter = Previous.makeFilter();2405while (Filter.hasNext()) {2406NamedDecl *Old = Filter.next();24072408// Non-hidden declarations are never ignored.2409if (S.isVisible(Old))2410continue;24112412// Declarations of the same entity are not ignored, even if they have2413// different linkages.2414if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {2415if (S.Context.hasSameType(OldTD->getUnderlyingType(),2416Decl->getUnderlyingType()))2417continue;24182419// If both declarations give a tag declaration a typedef name for linkage2420// purposes, then they declare the same entity.2421if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&2422Decl->getAnonDeclWithTypedefName())2423continue;2424}24252426Filter.erase();2427}24282429Filter.done();2430}24312432bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {2433QualType OldType;2434if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))2435OldType = OldTypedef->getUnderlyingType();2436else2437OldType = Context.getTypeDeclType(Old);2438QualType NewType = New->getUnderlyingType();24392440if (NewType->isVariablyModifiedType()) {2441// Must not redefine a typedef with a variably-modified type.2442int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;2443Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)2444<< Kind << NewType;2445if (Old->getLocation().isValid())2446notePreviousDefinition(Old, New->getLocation());2447New->setInvalidDecl();2448return true;2449}24502451if (OldType != NewType &&2452!OldType->isDependentType() &&2453!NewType->isDependentType() &&2454!Context.hasSameType(OldType, NewType)) {2455int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;2456Diag(New->getLocation(), diag::err_redefinition_different_typedef)2457<< Kind << NewType << OldType;2458if (Old->getLocation().isValid())2459notePreviousDefinition(Old, New->getLocation());2460New->setInvalidDecl();2461return true;2462}2463return false;2464}24652466void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,2467LookupResult &OldDecls) {2468// If the new decl is known invalid already, don't bother doing any2469// merging checks.2470if (New->isInvalidDecl()) return;24712472// Allow multiple definitions for ObjC built-in typedefs.2473// FIXME: Verify the underlying types are equivalent!2474if (getLangOpts().ObjC) {2475const IdentifierInfo *TypeID = New->getIdentifier();2476switch (TypeID->getLength()) {2477default: break;2478case 2:2479{2480if (!TypeID->isStr("id"))2481break;2482QualType T = New->getUnderlyingType();2483if (!T->isPointerType())2484break;2485if (!T->isVoidPointerType()) {2486QualType PT = T->castAs<PointerType>()->getPointeeType();2487if (!PT->isStructureType())2488break;2489}2490Context.setObjCIdRedefinitionType(T);2491// Install the built-in type for 'id', ignoring the current definition.2492New->setTypeForDecl(Context.getObjCIdType().getTypePtr());2493return;2494}2495case 5:2496if (!TypeID->isStr("Class"))2497break;2498Context.setObjCClassRedefinitionType(New->getUnderlyingType());2499// Install the built-in type for 'Class', ignoring the current definition.2500New->setTypeForDecl(Context.getObjCClassType().getTypePtr());2501return;2502case 3:2503if (!TypeID->isStr("SEL"))2504break;2505Context.setObjCSelRedefinitionType(New->getUnderlyingType());2506// Install the built-in type for 'SEL', ignoring the current definition.2507New->setTypeForDecl(Context.getObjCSelType().getTypePtr());2508return;2509}2510// Fall through - the typedef name was not a builtin type.2511}25122513// Verify the old decl was also a type.2514TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();2515if (!Old) {2516Diag(New->getLocation(), diag::err_redefinition_different_kind)2517<< New->getDeclName();25182519NamedDecl *OldD = OldDecls.getRepresentativeDecl();2520if (OldD->getLocation().isValid())2521notePreviousDefinition(OldD, New->getLocation());25222523return New->setInvalidDecl();2524}25252526// If the old declaration is invalid, just give up here.2527if (Old->isInvalidDecl())2528return New->setInvalidDecl();25292530if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {2531auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);2532auto *NewTag = New->getAnonDeclWithTypedefName();2533NamedDecl *Hidden = nullptr;2534if (OldTag && NewTag &&2535OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&2536!hasVisibleDefinition(OldTag, &Hidden)) {2537// There is a definition of this tag, but it is not visible. Use it2538// instead of our tag.2539New->setTypeForDecl(OldTD->getTypeForDecl());2540if (OldTD->isModed())2541New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),2542OldTD->getUnderlyingType());2543else2544New->setTypeSourceInfo(OldTD->getTypeSourceInfo());25452546// Make the old tag definition visible.2547makeMergedDefinitionVisible(Hidden);25482549// If this was an unscoped enumeration, yank all of its enumerators2550// out of the scope.2551if (isa<EnumDecl>(NewTag)) {2552Scope *EnumScope = getNonFieldDeclScope(S);2553for (auto *D : NewTag->decls()) {2554auto *ED = cast<EnumConstantDecl>(D);2555assert(EnumScope->isDeclScope(ED));2556EnumScope->RemoveDecl(ED);2557IdResolver.RemoveDecl(ED);2558ED->getLexicalDeclContext()->removeDecl(ED);2559}2560}2561}2562}25632564// If the typedef types are not identical, reject them in all languages and2565// with any extensions enabled.2566if (isIncompatibleTypedef(Old, New))2567return;25682569// The types match. Link up the redeclaration chain and merge attributes if2570// the old declaration was a typedef.2571if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {2572New->setPreviousDecl(Typedef);2573mergeDeclAttributes(New, Old);2574}25752576if (getLangOpts().MicrosoftExt)2577return;25782579if (getLangOpts().CPlusPlus) {2580// C++ [dcl.typedef]p2:2581// In a given non-class scope, a typedef specifier can be used to2582// redefine the name of any type declared in that scope to refer2583// to the type to which it already refers.2584if (!isa<CXXRecordDecl>(CurContext))2585return;25862587// C++0x [dcl.typedef]p4:2588// In a given class scope, a typedef specifier can be used to redefine2589// any class-name declared in that scope that is not also a typedef-name2590// to refer to the type to which it already refers.2591//2592// This wording came in via DR424, which was a correction to the2593// wording in DR56, which accidentally banned code like:2594//2595// struct S {2596// typedef struct A { } A;2597// };2598//2599// in the C++03 standard. We implement the C++0x semantics, which2600// allow the above but disallow2601//2602// struct S {2603// typedef int I;2604// typedef int I;2605// };2606//2607// since that was the intent of DR56.2608if (!isa<TypedefNameDecl>(Old))2609return;26102611Diag(New->getLocation(), diag::err_redefinition)2612<< New->getDeclName();2613notePreviousDefinition(Old, New->getLocation());2614return New->setInvalidDecl();2615}26162617// Modules always permit redefinition of typedefs, as does C11.2618if (getLangOpts().Modules || getLangOpts().C11)2619return;26202621// If we have a redefinition of a typedef in C, emit a warning. This warning2622// is normally mapped to an error, but can be controlled with2623// -Wtypedef-redefinition. If either the original or the redefinition is2624// in a system header, don't emit this for compatibility with GCC.2625if (getDiagnostics().getSuppressSystemWarnings() &&2626// Some standard types are defined implicitly in Clang (e.g. OpenCL).2627(Old->isImplicit() ||2628Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||2629Context.getSourceManager().isInSystemHeader(New->getLocation())))2630return;26312632Diag(New->getLocation(), diag::ext_redefinition_of_typedef)2633<< New->getDeclName();2634notePreviousDefinition(Old, New->getLocation());2635}26362637/// DeclhasAttr - returns true if decl Declaration already has the target2638/// attribute.2639static bool DeclHasAttr(const Decl *D, const Attr *A) {2640const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);2641const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);2642for (const auto *i : D->attrs())2643if (i->getKind() == A->getKind()) {2644if (Ann) {2645if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())2646return true;2647continue;2648}2649// FIXME: Don't hardcode this check2650if (OA && isa<OwnershipAttr>(i))2651return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();2652return true;2653}26542655return false;2656}26572658static bool isAttributeTargetADefinition(Decl *D) {2659if (VarDecl *VD = dyn_cast<VarDecl>(D))2660return VD->isThisDeclarationADefinition();2661if (TagDecl *TD = dyn_cast<TagDecl>(D))2662return TD->isCompleteDefinition() || TD->isBeingDefined();2663return true;2664}26652666/// Merge alignment attributes from \p Old to \p New, taking into account the2667/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.2668///2669/// \return \c true if any attributes were added to \p New.2670static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {2671// Look for alignas attributes on Old, and pick out whichever attribute2672// specifies the strictest alignment requirement.2673AlignedAttr *OldAlignasAttr = nullptr;2674AlignedAttr *OldStrictestAlignAttr = nullptr;2675unsigned OldAlign = 0;2676for (auto *I : Old->specific_attrs<AlignedAttr>()) {2677// FIXME: We have no way of representing inherited dependent alignments2678// in a case like:2679// template<int A, int B> struct alignas(A) X;2680// template<int A, int B> struct alignas(B) X {};2681// For now, we just ignore any alignas attributes which are not on the2682// definition in such a case.2683if (I->isAlignmentDependent())2684return false;26852686if (I->isAlignas())2687OldAlignasAttr = I;26882689unsigned Align = I->getAlignment(S.Context);2690if (Align > OldAlign) {2691OldAlign = Align;2692OldStrictestAlignAttr = I;2693}2694}26952696// Look for alignas attributes on New.2697AlignedAttr *NewAlignasAttr = nullptr;2698unsigned NewAlign = 0;2699for (auto *I : New->specific_attrs<AlignedAttr>()) {2700if (I->isAlignmentDependent())2701return false;27022703if (I->isAlignas())2704NewAlignasAttr = I;27052706unsigned Align = I->getAlignment(S.Context);2707if (Align > NewAlign)2708NewAlign = Align;2709}27102711if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {2712// Both declarations have 'alignas' attributes. We require them to match.2713// C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but2714// fall short. (If two declarations both have alignas, they must both match2715// every definition, and so must match each other if there is a definition.)27162717// If either declaration only contains 'alignas(0)' specifiers, then it2718// specifies the natural alignment for the type.2719if (OldAlign == 0 || NewAlign == 0) {2720QualType Ty;2721if (ValueDecl *VD = dyn_cast<ValueDecl>(New))2722Ty = VD->getType();2723else2724Ty = S.Context.getTagDeclType(cast<TagDecl>(New));27252726if (OldAlign == 0)2727OldAlign = S.Context.getTypeAlign(Ty);2728if (NewAlign == 0)2729NewAlign = S.Context.getTypeAlign(Ty);2730}27312732if (OldAlign != NewAlign) {2733S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)2734<< (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()2735<< (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();2736S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);2737}2738}27392740if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {2741// C++11 [dcl.align]p6:2742// if any declaration of an entity has an alignment-specifier,2743// every defining declaration of that entity shall specify an2744// equivalent alignment.2745// C11 6.7.5/7:2746// If the definition of an object does not have an alignment2747// specifier, any other declaration of that object shall also2748// have no alignment specifier.2749S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)2750<< OldAlignasAttr;2751S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)2752<< OldAlignasAttr;2753}27542755bool AnyAdded = false;27562757// Ensure we have an attribute representing the strictest alignment.2758if (OldAlign > NewAlign) {2759AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);2760Clone->setInherited(true);2761New->addAttr(Clone);2762AnyAdded = true;2763}27642765// Ensure we have an alignas attribute if the old declaration had one.2766if (OldAlignasAttr && !NewAlignasAttr &&2767!(AnyAdded && OldStrictestAlignAttr->isAlignas())) {2768AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);2769Clone->setInherited(true);2770New->addAttr(Clone);2771AnyAdded = true;2772}27732774return AnyAdded;2775}27762777#define WANT_DECL_MERGE_LOGIC2778#include "clang/Sema/AttrParsedAttrImpl.inc"2779#undef WANT_DECL_MERGE_LOGIC27802781static bool mergeDeclAttribute(Sema &S, NamedDecl *D,2782const InheritableAttr *Attr,2783Sema::AvailabilityMergeKind AMK) {2784// Diagnose any mutual exclusions between the attribute that we want to add2785// and attributes that already exist on the declaration.2786if (!DiagnoseMutualExclusions(S, D, Attr))2787return false;27882789// This function copies an attribute Attr from a previous declaration to the2790// new declaration D if the new declaration doesn't itself have that attribute2791// yet or if that attribute allows duplicates.2792// If you're adding a new attribute that requires logic different from2793// "use explicit attribute on decl if present, else use attribute from2794// previous decl", for example if the attribute needs to be consistent2795// between redeclarations, you need to call a custom merge function here.2796InheritableAttr *NewAttr = nullptr;2797if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))2798NewAttr = S.mergeAvailabilityAttr(2799D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),2800AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),2801AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,2802AA->getPriority(), AA->getEnvironment());2803else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))2804NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());2805else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))2806NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());2807else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))2808NewAttr = S.mergeDLLImportAttr(D, *ImportA);2809else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))2810NewAttr = S.mergeDLLExportAttr(D, *ExportA);2811else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))2812NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());2813else if (const auto *FA = dyn_cast<FormatAttr>(Attr))2814NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),2815FA->getFirstArg());2816else if (const auto *SA = dyn_cast<SectionAttr>(Attr))2817NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());2818else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))2819NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());2820else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))2821NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),2822IA->getInheritanceModel());2823else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))2824NewAttr = S.mergeAlwaysInlineAttr(D, *AA,2825&S.Context.Idents.get(AA->getSpelling()));2826else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&2827(isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||2828isa<CUDAGlobalAttr>(Attr))) {2829// CUDA target attributes are part of function signature for2830// overloading purposes and must not be merged.2831return false;2832} else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))2833NewAttr = S.mergeMinSizeAttr(D, *MA);2834else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))2835NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());2836else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))2837NewAttr = S.mergeOptimizeNoneAttr(D, *OA);2838else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))2839NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);2840else if (isa<AlignedAttr>(Attr))2841// AlignedAttrs are handled separately, because we need to handle all2842// such attributes on a declaration at the same time.2843NewAttr = nullptr;2844else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&2845(AMK == Sema::AMK_Override ||2846AMK == Sema::AMK_ProtocolImplementation ||2847AMK == Sema::AMK_OptionalProtocolImplementation))2848NewAttr = nullptr;2849else if (const auto *UA = dyn_cast<UuidAttr>(Attr))2850NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());2851else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))2852NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);2853else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))2854NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);2855else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))2856NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);2857else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))2858NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);2859else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))2860NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);2861else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))2862NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),2863NT->getZ());2864else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))2865NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());2866else if (isa<SuppressAttr>(Attr))2867// Do nothing. Each redeclaration should be suppressed separately.2868NewAttr = nullptr;2869else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))2870NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));28712872if (NewAttr) {2873NewAttr->setInherited(true);2874D->addAttr(NewAttr);2875if (isa<MSInheritanceAttr>(NewAttr))2876S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));2877return true;2878}28792880return false;2881}28822883static const NamedDecl *getDefinition(const Decl *D) {2884if (const TagDecl *TD = dyn_cast<TagDecl>(D))2885return TD->getDefinition();2886if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {2887const VarDecl *Def = VD->getDefinition();2888if (Def)2889return Def;2890return VD->getActingDefinition();2891}2892if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {2893const FunctionDecl *Def = nullptr;2894if (FD->isDefined(Def, true))2895return Def;2896}2897return nullptr;2898}28992900static bool hasAttribute(const Decl *D, attr::Kind Kind) {2901for (const auto *Attribute : D->attrs())2902if (Attribute->getKind() == Kind)2903return true;2904return false;2905}29062907/// checkNewAttributesAfterDef - If we already have a definition, check that2908/// there are no new attributes in this declaration.2909static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {2910if (!New->hasAttrs())2911return;29122913const NamedDecl *Def = getDefinition(Old);2914if (!Def || Def == New)2915return;29162917AttrVec &NewAttributes = New->getAttrs();2918for (unsigned I = 0, E = NewAttributes.size(); I != E;) {2919const Attr *NewAttribute = NewAttributes[I];29202921if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {2922if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {2923SkipBodyInfo SkipBody;2924S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);29252926// If we're skipping this definition, drop the "alias" attribute.2927if (SkipBody.ShouldSkip) {2928NewAttributes.erase(NewAttributes.begin() + I);2929--E;2930continue;2931}2932} else {2933VarDecl *VD = cast<VarDecl>(New);2934unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==2935VarDecl::TentativeDefinition2936? diag::err_alias_after_tentative2937: diag::err_redefinition;2938S.Diag(VD->getLocation(), Diag) << VD->getDeclName();2939if (Diag == diag::err_redefinition)2940S.notePreviousDefinition(Def, VD->getLocation());2941else2942S.Diag(Def->getLocation(), diag::note_previous_definition);2943VD->setInvalidDecl();2944}2945++I;2946continue;2947}29482949if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {2950// Tentative definitions are only interesting for the alias check above.2951if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {2952++I;2953continue;2954}2955}29562957if (hasAttribute(Def, NewAttribute->getKind())) {2958++I;2959continue; // regular attr merging will take care of validating this.2960}29612962if (isa<C11NoReturnAttr>(NewAttribute)) {2963// C's _Noreturn is allowed to be added to a function after it is defined.2964++I;2965continue;2966} else if (isa<UuidAttr>(NewAttribute)) {2967// msvc will allow a subsequent definition to add an uuid to a class2968++I;2969continue;2970} else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {2971if (AA->isAlignas()) {2972// C++11 [dcl.align]p6:2973// if any declaration of an entity has an alignment-specifier,2974// every defining declaration of that entity shall specify an2975// equivalent alignment.2976// C11 6.7.5/7:2977// If the definition of an object does not have an alignment2978// specifier, any other declaration of that object shall also2979// have no alignment specifier.2980S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)2981<< AA;2982S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)2983<< AA;2984NewAttributes.erase(NewAttributes.begin() + I);2985--E;2986continue;2987}2988} else if (isa<LoaderUninitializedAttr>(NewAttribute)) {2989// If there is a C definition followed by a redeclaration with this2990// attribute then there are two different definitions. In C++, prefer the2991// standard diagnostics.2992if (!S.getLangOpts().CPlusPlus) {2993S.Diag(NewAttribute->getLocation(),2994diag::err_loader_uninitialized_redeclaration);2995S.Diag(Def->getLocation(), diag::note_previous_definition);2996NewAttributes.erase(NewAttributes.begin() + I);2997--E;2998continue;2999}3000} else if (isa<SelectAnyAttr>(NewAttribute) &&3001cast<VarDecl>(New)->isInline() &&3002!cast<VarDecl>(New)->isInlineSpecified()) {3003// Don't warn about applying selectany to implicitly inline variables.3004// Older compilers and language modes would require the use of selectany3005// to make such variables inline, and it would have no effect if we3006// honored it.3007++I;3008continue;3009} else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {3010// We allow to add OMP[Begin]DeclareVariantAttr to be added to3011// declarations after definitions.3012++I;3013continue;3014}30153016S.Diag(NewAttribute->getLocation(),3017diag::warn_attribute_precede_definition);3018S.Diag(Def->getLocation(), diag::note_previous_definition);3019NewAttributes.erase(NewAttributes.begin() + I);3020--E;3021}3022}30233024static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,3025const ConstInitAttr *CIAttr,3026bool AttrBeforeInit) {3027SourceLocation InsertLoc = InitDecl->getInnerLocStart();30283029// Figure out a good way to write this specifier on the old declaration.3030// FIXME: We should just use the spelling of CIAttr, but we don't preserve3031// enough of the attribute list spelling information to extract that without3032// heroics.3033std::string SuitableSpelling;3034if (S.getLangOpts().CPlusPlus20)3035SuitableSpelling = std::string(3036S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));3037if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)3038SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(3039InsertLoc, {tok::l_square, tok::l_square,3040S.PP.getIdentifierInfo("clang"), tok::coloncolon,3041S.PP.getIdentifierInfo("require_constant_initialization"),3042tok::r_square, tok::r_square}));3043if (SuitableSpelling.empty())3044SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(3045InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,3046S.PP.getIdentifierInfo("require_constant_initialization"),3047tok::r_paren, tok::r_paren}));3048if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)3049SuitableSpelling = "constinit";3050if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)3051SuitableSpelling = "[[clang::require_constant_initialization]]";3052if (SuitableSpelling.empty())3053SuitableSpelling = "__attribute__((require_constant_initialization))";3054SuitableSpelling += " ";30553056if (AttrBeforeInit) {3057// extern constinit int a;3058// int a = 0; // error (missing 'constinit'), accepted as extension3059assert(CIAttr->isConstinit() && "should not diagnose this for attribute");3060S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)3061<< InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);3062S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);3063} else {3064// int a = 0;3065// constinit extern int a; // error (missing 'constinit')3066S.Diag(CIAttr->getLocation(),3067CIAttr->isConstinit() ? diag::err_constinit_added_too_late3068: diag::warn_require_const_init_added_too_late)3069<< FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));3070S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)3071<< CIAttr->isConstinit()3072<< FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);3073}3074}30753076void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,3077AvailabilityMergeKind AMK) {3078if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {3079UsedAttr *NewAttr = OldAttr->clone(Context);3080NewAttr->setInherited(true);3081New->addAttr(NewAttr);3082}3083if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {3084RetainAttr *NewAttr = OldAttr->clone(Context);3085NewAttr->setInherited(true);3086New->addAttr(NewAttr);3087}30883089if (!Old->hasAttrs() && !New->hasAttrs())3090return;30913092// [dcl.constinit]p1:3093// If the [constinit] specifier is applied to any declaration of a3094// variable, it shall be applied to the initializing declaration.3095const auto *OldConstInit = Old->getAttr<ConstInitAttr>();3096const auto *NewConstInit = New->getAttr<ConstInitAttr>();3097if (bool(OldConstInit) != bool(NewConstInit)) {3098const auto *OldVD = cast<VarDecl>(Old);3099auto *NewVD = cast<VarDecl>(New);31003101// Find the initializing declaration. Note that we might not have linked3102// the new declaration into the redeclaration chain yet.3103const VarDecl *InitDecl = OldVD->getInitializingDeclaration();3104if (!InitDecl &&3105(NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))3106InitDecl = NewVD;31073108if (InitDecl == NewVD) {3109// This is the initializing declaration. If it would inherit 'constinit',3110// that's ill-formed. (Note that we do not apply this to the attribute3111// form).3112if (OldConstInit && OldConstInit->isConstinit())3113diagnoseMissingConstinit(*this, NewVD, OldConstInit,3114/*AttrBeforeInit=*/true);3115} else if (NewConstInit) {3116// This is the first time we've been told that this declaration should3117// have a constant initializer. If we already saw the initializing3118// declaration, this is too late.3119if (InitDecl && InitDecl != NewVD) {3120diagnoseMissingConstinit(*this, InitDecl, NewConstInit,3121/*AttrBeforeInit=*/false);3122NewVD->dropAttr<ConstInitAttr>();3123}3124}3125}31263127// Attributes declared post-definition are currently ignored.3128checkNewAttributesAfterDef(*this, New, Old);31293130if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {3131if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {3132if (!OldA->isEquivalent(NewA)) {3133// This redeclaration changes __asm__ label.3134Diag(New->getLocation(), diag::err_different_asm_label);3135Diag(OldA->getLocation(), diag::note_previous_declaration);3136}3137} else if (Old->isUsed()) {3138// This redeclaration adds an __asm__ label to a declaration that has3139// already been ODR-used.3140Diag(New->getLocation(), diag::err_late_asm_label_name)3141<< isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();3142}3143}31443145// Re-declaration cannot add abi_tag's.3146if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {3147if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {3148for (const auto &NewTag : NewAbiTagAttr->tags()) {3149if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {3150Diag(NewAbiTagAttr->getLocation(),3151diag::err_new_abi_tag_on_redeclaration)3152<< NewTag;3153Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);3154}3155}3156} else {3157Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);3158Diag(Old->getLocation(), diag::note_previous_declaration);3159}3160}31613162// This redeclaration adds a section attribute.3163if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {3164if (auto *VD = dyn_cast<VarDecl>(New)) {3165if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {3166Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);3167Diag(Old->getLocation(), diag::note_previous_declaration);3168}3169}3170}31713172// Redeclaration adds code-seg attribute.3173const auto *NewCSA = New->getAttr<CodeSegAttr>();3174if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&3175!NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {3176Diag(New->getLocation(), diag::warn_mismatched_section)3177<< 0 /*codeseg*/;3178Diag(Old->getLocation(), diag::note_previous_declaration);3179}31803181if (!Old->hasAttrs())3182return;31833184bool foundAny = New->hasAttrs();31853186// Ensure that any moving of objects within the allocated map is done before3187// we process them.3188if (!foundAny) New->setAttrs(AttrVec());31893190for (auto *I : Old->specific_attrs<InheritableAttr>()) {3191// Ignore deprecated/unavailable/availability attributes if requested.3192AvailabilityMergeKind LocalAMK = AMK_None;3193if (isa<DeprecatedAttr>(I) ||3194isa<UnavailableAttr>(I) ||3195isa<AvailabilityAttr>(I)) {3196switch (AMK) {3197case AMK_None:3198continue;31993200case AMK_Redeclaration:3201case AMK_Override:3202case AMK_ProtocolImplementation:3203case AMK_OptionalProtocolImplementation:3204LocalAMK = AMK;3205break;3206}3207}32083209// Already handled.3210if (isa<UsedAttr>(I) || isa<RetainAttr>(I))3211continue;32123213if (mergeDeclAttribute(*this, New, I, LocalAMK))3214foundAny = true;3215}32163217if (mergeAlignedAttrs(*this, New, Old))3218foundAny = true;32193220if (!foundAny) New->dropAttrs();3221}32223223/// mergeParamDeclAttributes - Copy attributes from the old parameter3224/// to the new one.3225static void mergeParamDeclAttributes(ParmVarDecl *newDecl,3226const ParmVarDecl *oldDecl,3227Sema &S) {3228// C++11 [dcl.attr.depend]p2:3229// The first declaration of a function shall specify the3230// carries_dependency attribute for its declarator-id if any declaration3231// of the function specifies the carries_dependency attribute.3232const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();3233if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {3234S.Diag(CDA->getLocation(),3235diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;3236// Find the first declaration of the parameter.3237// FIXME: Should we build redeclaration chains for function parameters?3238const FunctionDecl *FirstFD =3239cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();3240const ParmVarDecl *FirstVD =3241FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());3242S.Diag(FirstVD->getLocation(),3243diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;3244}32453246// HLSL parameter declarations for inout and out must match between3247// declarations. In HLSL inout and out are ambiguous at the call site, but3248// have different calling behavior, so you cannot overload a method based on a3249// difference between inout and out annotations.3250if (S.getLangOpts().HLSL) {3251const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();3252const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();3253// We don't need to cover the case where one declaration doesn't have an3254// attribute. The only possible case there is if one declaration has an `in`3255// attribute and the other declaration has no attribute. This case is3256// allowed since parameters are `in` by default.3257if (NDAttr && ODAttr &&3258NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {3259S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)3260<< NDAttr << newDecl;3261S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)3262<< ODAttr;3263}3264}32653266if (!oldDecl->hasAttrs())3267return;32683269bool foundAny = newDecl->hasAttrs();32703271// Ensure that any moving of objects within the allocated map is3272// done before we process them.3273if (!foundAny) newDecl->setAttrs(AttrVec());32743275for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {3276if (!DeclHasAttr(newDecl, I)) {3277InheritableAttr *newAttr =3278cast<InheritableParamAttr>(I->clone(S.Context));3279newAttr->setInherited(true);3280newDecl->addAttr(newAttr);3281foundAny = true;3282}3283}32843285if (!foundAny) newDecl->dropAttrs();3286}32873288static bool EquivalentArrayTypes(QualType Old, QualType New,3289const ASTContext &Ctx) {32903291auto NoSizeInfo = [&Ctx](QualType Ty) {3292if (Ty->isIncompleteArrayType() || Ty->isPointerType())3293return true;3294if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))3295return VAT->getSizeModifier() == ArraySizeModifier::Star;3296return false;3297};32983299// `type[]` is equivalent to `type *` and `type[*]`.3300if (NoSizeInfo(Old) && NoSizeInfo(New))3301return true;33023303// Don't try to compare VLA sizes, unless one of them has the star modifier.3304if (Old->isVariableArrayType() && New->isVariableArrayType()) {3305const auto *OldVAT = Ctx.getAsVariableArrayType(Old);3306const auto *NewVAT = Ctx.getAsVariableArrayType(New);3307if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^3308(NewVAT->getSizeModifier() == ArraySizeModifier::Star))3309return false;3310return true;3311}33123313// Only compare size, ignore Size modifiers and CVR.3314if (Old->isConstantArrayType() && New->isConstantArrayType()) {3315return Ctx.getAsConstantArrayType(Old)->getSize() ==3316Ctx.getAsConstantArrayType(New)->getSize();3317}33183319// Don't try to compare dependent sized array3320if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {3321return true;3322}33233324return Old == New;3325}33263327static void mergeParamDeclTypes(ParmVarDecl *NewParam,3328const ParmVarDecl *OldParam,3329Sema &S) {3330if (auto Oldnullability = OldParam->getType()->getNullability()) {3331if (auto Newnullability = NewParam->getType()->getNullability()) {3332if (*Oldnullability != *Newnullability) {3333S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)3334<< DiagNullabilityKind(3335*Newnullability,3336((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)3337!= 0))3338<< DiagNullabilityKind(3339*Oldnullability,3340((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)3341!= 0));3342S.Diag(OldParam->getLocation(), diag::note_previous_declaration);3343}3344} else {3345QualType NewT = NewParam->getType();3346NewT = S.Context.getAttributedType(3347AttributedType::getNullabilityAttrKind(*Oldnullability),3348NewT, NewT);3349NewParam->setType(NewT);3350}3351}3352const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());3353const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());3354if (OldParamDT && NewParamDT &&3355OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {3356QualType OldParamOT = OldParamDT->getOriginalType();3357QualType NewParamOT = NewParamDT->getOriginalType();3358if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {3359S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)3360<< NewParam << NewParamOT;3361S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)3362<< OldParamOT;3363}3364}3365}33663367namespace {33683369/// Used in MergeFunctionDecl to keep track of function parameters in3370/// C.3371struct GNUCompatibleParamWarning {3372ParmVarDecl *OldParm;3373ParmVarDecl *NewParm;3374QualType PromotedType;3375};33763377} // end anonymous namespace33783379// Determine whether the previous declaration was a definition, implicit3380// declaration, or a declaration.3381template <typename T>3382static std::pair<diag::kind, SourceLocation>3383getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {3384diag::kind PrevDiag;3385SourceLocation OldLocation = Old->getLocation();3386if (Old->isThisDeclarationADefinition())3387PrevDiag = diag::note_previous_definition;3388else if (Old->isImplicit()) {3389PrevDiag = diag::note_previous_implicit_declaration;3390if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {3391if (FD->getBuiltinID())3392PrevDiag = diag::note_previous_builtin_declaration;3393}3394if (OldLocation.isInvalid())3395OldLocation = New->getLocation();3396} else3397PrevDiag = diag::note_previous_declaration;3398return std::make_pair(PrevDiag, OldLocation);3399}34003401/// canRedefineFunction - checks if a function can be redefined. Currently,3402/// only extern inline functions can be redefined, and even then only in3403/// GNU89 mode.3404static bool canRedefineFunction(const FunctionDecl *FD,3405const LangOptions& LangOpts) {3406return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&3407!LangOpts.CPlusPlus &&3408FD->isInlineSpecified() &&3409FD->getStorageClass() == SC_Extern);3410}34113412const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {3413const AttributedType *AT = T->getAs<AttributedType>();3414while (AT && !AT->isCallingConv())3415AT = AT->getModifiedType()->getAs<AttributedType>();3416return AT;3417}34183419template <typename T>3420static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {3421const DeclContext *DC = Old->getDeclContext();3422if (DC->isRecord())3423return false;34243425LanguageLinkage OldLinkage = Old->getLanguageLinkage();3426if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())3427return true;3428if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())3429return true;3430return false;3431}34323433template<typename T> static bool isExternC(T *D) { return D->isExternC(); }3434static bool isExternC(VarTemplateDecl *) { return false; }3435static bool isExternC(FunctionTemplateDecl *) { return false; }34363437/// Check whether a redeclaration of an entity introduced by a3438/// using-declaration is valid, given that we know it's not an overload3439/// (nor a hidden tag declaration).3440template<typename ExpectedDecl>3441static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,3442ExpectedDecl *New) {3443// C++11 [basic.scope.declarative]p4:3444// Given a set of declarations in a single declarative region, each of3445// which specifies the same unqualified name,3446// -- they shall all refer to the same entity, or all refer to functions3447// and function templates; or3448// -- exactly one declaration shall declare a class name or enumeration3449// name that is not a typedef name and the other declarations shall all3450// refer to the same variable or enumerator, or all refer to functions3451// and function templates; in this case the class name or enumeration3452// name is hidden (3.3.10).34533454// C++11 [namespace.udecl]p14:3455// If a function declaration in namespace scope or block scope has the3456// same name and the same parameter-type-list as a function introduced3457// by a using-declaration, and the declarations do not declare the same3458// function, the program is ill-formed.34593460auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());3461if (Old &&3462!Old->getDeclContext()->getRedeclContext()->Equals(3463New->getDeclContext()->getRedeclContext()) &&3464!(isExternC(Old) && isExternC(New)))3465Old = nullptr;34663467if (!Old) {3468S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);3469S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);3470S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;3471return true;3472}3473return false;3474}34753476static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,3477const FunctionDecl *B) {3478assert(A->getNumParams() == B->getNumParams());34793480auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {3481const auto *AttrA = A->getAttr<PassObjectSizeAttr>();3482const auto *AttrB = B->getAttr<PassObjectSizeAttr>();3483if (AttrA == AttrB)3484return true;3485return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&3486AttrA->isDynamic() == AttrB->isDynamic();3487};34883489return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);3490}34913492/// If necessary, adjust the semantic declaration context for a qualified3493/// declaration to name the correct inline namespace within the qualifier.3494static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,3495DeclaratorDecl *OldD) {3496// The only case where we need to update the DeclContext is when3497// redeclaration lookup for a qualified name finds a declaration3498// in an inline namespace within the context named by the qualifier:3499//3500// inline namespace N { int f(); }3501// int ::f(); // Sema DC needs adjusting from :: to N::.3502//3503// For unqualified declarations, the semantic context *can* change3504// along the redeclaration chain (for local extern declarations,3505// extern "C" declarations, and friend declarations in particular).3506if (!NewD->getQualifier())3507return;35083509// NewD is probably already in the right context.3510auto *NamedDC = NewD->getDeclContext()->getRedeclContext();3511auto *SemaDC = OldD->getDeclContext()->getRedeclContext();3512if (NamedDC->Equals(SemaDC))3513return;35143515assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||3516NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&3517"unexpected context for redeclaration");35183519auto *LexDC = NewD->getLexicalDeclContext();3520auto FixSemaDC = [=](NamedDecl *D) {3521if (!D)3522return;3523D->setDeclContext(SemaDC);3524D->setLexicalDeclContext(LexDC);3525};35263527FixSemaDC(NewD);3528if (auto *FD = dyn_cast<FunctionDecl>(NewD))3529FixSemaDC(FD->getDescribedFunctionTemplate());3530else if (auto *VD = dyn_cast<VarDecl>(NewD))3531FixSemaDC(VD->getDescribedVarTemplate());3532}35333534bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,3535bool MergeTypeWithOld, bool NewDeclIsDefn) {3536// Verify the old decl was also a function.3537FunctionDecl *Old = OldD->getAsFunction();3538if (!Old) {3539if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {3540if (New->getFriendObjectKind()) {3541Diag(New->getLocation(), diag::err_using_decl_friend);3542Diag(Shadow->getTargetDecl()->getLocation(),3543diag::note_using_decl_target);3544Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)3545<< 0;3546return true;3547}35483549// Check whether the two declarations might declare the same function or3550// function template.3551if (FunctionTemplateDecl *NewTemplate =3552New->getDescribedFunctionTemplate()) {3553if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,3554NewTemplate))3555return true;3556OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())3557->getAsFunction();3558} else {3559if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))3560return true;3561OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());3562}3563} else {3564Diag(New->getLocation(), diag::err_redefinition_different_kind)3565<< New->getDeclName();3566notePreviousDefinition(OldD, New->getLocation());3567return true;3568}3569}35703571// If the old declaration was found in an inline namespace and the new3572// declaration was qualified, update the DeclContext to match.3573adjustDeclContextForDeclaratorDecl(New, Old);35743575// If the old declaration is invalid, just give up here.3576if (Old->isInvalidDecl())3577return true;35783579// Disallow redeclaration of some builtins.3580if (!getASTContext().canBuiltinBeRedeclared(Old)) {3581Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();3582Diag(Old->getLocation(), diag::note_previous_builtin_declaration)3583<< Old << Old->getType();3584return true;3585}35863587diag::kind PrevDiag;3588SourceLocation OldLocation;3589std::tie(PrevDiag, OldLocation) =3590getNoteDiagForInvalidRedeclaration(Old, New);35913592// Don't complain about this if we're in GNU89 mode and the old function3593// is an extern inline function.3594// Don't complain about specializations. They are not supposed to have3595// storage classes.3596if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&3597New->getStorageClass() == SC_Static &&3598Old->hasExternalFormalLinkage() &&3599!New->getTemplateSpecializationInfo() &&3600!canRedefineFunction(Old, getLangOpts())) {3601if (getLangOpts().MicrosoftExt) {3602Diag(New->getLocation(), diag::ext_static_non_static) << New;3603Diag(OldLocation, PrevDiag) << Old << Old->getType();3604} else {3605Diag(New->getLocation(), diag::err_static_non_static) << New;3606Diag(OldLocation, PrevDiag) << Old << Old->getType();3607return true;3608}3609}36103611if (const auto *ILA = New->getAttr<InternalLinkageAttr>())3612if (!Old->hasAttr<InternalLinkageAttr>()) {3613Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)3614<< ILA;3615Diag(Old->getLocation(), diag::note_previous_declaration);3616New->dropAttr<InternalLinkageAttr>();3617}36183619if (auto *EA = New->getAttr<ErrorAttr>()) {3620if (!Old->hasAttr<ErrorAttr>()) {3621Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;3622Diag(Old->getLocation(), diag::note_previous_declaration);3623New->dropAttr<ErrorAttr>();3624}3625}36263627if (CheckRedeclarationInModule(New, Old))3628return true;36293630if (!getLangOpts().CPlusPlus) {3631bool OldOvl = Old->hasAttr<OverloadableAttr>();3632if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {3633Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)3634<< New << OldOvl;36353636// Try our best to find a decl that actually has the overloadable3637// attribute for the note. In most cases (e.g. programs with only one3638// broken declaration/definition), this won't matter.3639//3640// FIXME: We could do this if we juggled some extra state in3641// OverloadableAttr, rather than just removing it.3642const Decl *DiagOld = Old;3643if (OldOvl) {3644auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {3645const auto *A = D->getAttr<OverloadableAttr>();3646return A && !A->isImplicit();3647});3648// If we've implicitly added *all* of the overloadable attrs to this3649// chain, emitting a "previous redecl" note is pointless.3650DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;3651}36523653if (DiagOld)3654Diag(DiagOld->getLocation(),3655diag::note_attribute_overloadable_prev_overload)3656<< OldOvl;36573658if (OldOvl)3659New->addAttr(OverloadableAttr::CreateImplicit(Context));3660else3661New->dropAttr<OverloadableAttr>();3662}3663}36643665// It is not permitted to redeclare an SME function with different SME3666// attributes.3667if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {3668Diag(New->getLocation(), diag::err_sme_attr_mismatch)3669<< New->getType() << Old->getType();3670Diag(OldLocation, diag::note_previous_declaration);3671return true;3672}36733674// If a function is first declared with a calling convention, but is later3675// declared or defined without one, all following decls assume the calling3676// convention of the first.3677//3678// It's OK if a function is first declared without a calling convention,3679// but is later declared or defined with the default calling convention.3680//3681// To test if either decl has an explicit calling convention, we look for3682// AttributedType sugar nodes on the type as written. If they are missing or3683// were canonicalized away, we assume the calling convention was implicit.3684//3685// Note also that we DO NOT return at this point, because we still have3686// other tests to run.3687QualType OldQType = Context.getCanonicalType(Old->getType());3688QualType NewQType = Context.getCanonicalType(New->getType());3689const FunctionType *OldType = cast<FunctionType>(OldQType);3690const FunctionType *NewType = cast<FunctionType>(NewQType);3691FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();3692FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();3693bool RequiresAdjustment = false;36943695if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {3696FunctionDecl *First = Old->getFirstDecl();3697const FunctionType *FT =3698First->getType().getCanonicalType()->castAs<FunctionType>();3699FunctionType::ExtInfo FI = FT->getExtInfo();3700bool NewCCExplicit = getCallingConvAttributedType(New->getType());3701if (!NewCCExplicit) {3702// Inherit the CC from the previous declaration if it was specified3703// there but not here.3704NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());3705RequiresAdjustment = true;3706} else if (Old->getBuiltinID()) {3707// Builtin attribute isn't propagated to the new one yet at this point,3708// so we check if the old one is a builtin.37093710// Calling Conventions on a Builtin aren't really useful and setting a3711// default calling convention and cdecl'ing some builtin redeclarations is3712// common, so warn and ignore the calling convention on the redeclaration.3713Diag(New->getLocation(), diag::warn_cconv_unsupported)3714<< FunctionType::getNameForCallConv(NewTypeInfo.getCC())3715<< (int)CallingConventionIgnoredReason::BuiltinFunction;3716NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());3717RequiresAdjustment = true;3718} else {3719// Calling conventions aren't compatible, so complain.3720bool FirstCCExplicit = getCallingConvAttributedType(First->getType());3721Diag(New->getLocation(), diag::err_cconv_change)3722<< FunctionType::getNameForCallConv(NewTypeInfo.getCC())3723<< !FirstCCExplicit3724<< (!FirstCCExplicit ? "" :3725FunctionType::getNameForCallConv(FI.getCC()));37263727// Put the note on the first decl, since it is the one that matters.3728Diag(First->getLocation(), diag::note_previous_declaration);3729return true;3730}3731}37323733// FIXME: diagnose the other way around?3734if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {3735NewTypeInfo = NewTypeInfo.withNoReturn(true);3736RequiresAdjustment = true;3737}37383739// Merge regparm attribute.3740if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||3741OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {3742if (NewTypeInfo.getHasRegParm()) {3743Diag(New->getLocation(), diag::err_regparm_mismatch)3744<< NewType->getRegParmType()3745<< OldType->getRegParmType();3746Diag(OldLocation, diag::note_previous_declaration);3747return true;3748}37493750NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());3751RequiresAdjustment = true;3752}37533754// Merge ns_returns_retained attribute.3755if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {3756if (NewTypeInfo.getProducesResult()) {3757Diag(New->getLocation(), diag::err_function_attribute_mismatch)3758<< "'ns_returns_retained'";3759Diag(OldLocation, diag::note_previous_declaration);3760return true;3761}37623763NewTypeInfo = NewTypeInfo.withProducesResult(true);3764RequiresAdjustment = true;3765}37663767if (OldTypeInfo.getNoCallerSavedRegs() !=3768NewTypeInfo.getNoCallerSavedRegs()) {3769if (NewTypeInfo.getNoCallerSavedRegs()) {3770AnyX86NoCallerSavedRegistersAttr *Attr =3771New->getAttr<AnyX86NoCallerSavedRegistersAttr>();3772Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;3773Diag(OldLocation, diag::note_previous_declaration);3774return true;3775}37763777NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);3778RequiresAdjustment = true;3779}37803781if (RequiresAdjustment) {3782const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();3783AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);3784New->setType(QualType(AdjustedType, 0));3785NewQType = Context.getCanonicalType(New->getType());3786}37873788// If this redeclaration makes the function inline, we may need to add it to3789// UndefinedButUsed.3790if (!Old->isInlined() && New->isInlined() &&3791!New->hasAttr<GNUInlineAttr>() &&3792!getLangOpts().GNUInline &&3793Old->isUsed(false) &&3794!Old->isDefined() && !New->isThisDeclarationADefinition())3795UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),3796SourceLocation()));37973798// If this redeclaration makes it newly gnu_inline, we don't want to warn3799// about it.3800if (New->hasAttr<GNUInlineAttr>() &&3801Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {3802UndefinedButUsed.erase(Old->getCanonicalDecl());3803}38043805// If pass_object_size params don't match up perfectly, this isn't a valid3806// redeclaration.3807if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&3808!hasIdenticalPassObjectSizeAttrs(Old, New)) {3809Diag(New->getLocation(), diag::err_different_pass_object_size_params)3810<< New->getDeclName();3811Diag(OldLocation, PrevDiag) << Old << Old->getType();3812return true;3813}38143815QualType OldQTypeForComparison = OldQType;3816if (Context.hasAnyFunctionEffects()) {3817const auto OldFX = Old->getFunctionEffects();3818const auto NewFX = New->getFunctionEffects();3819if (OldFX != NewFX) {3820const auto Diffs = FunctionEffectDifferences(OldFX, NewFX);3821for (const auto &Diff : Diffs) {3822if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {3823Diag(New->getLocation(),3824diag::warn_mismatched_func_effect_redeclaration)3825<< Diff.effectName();3826Diag(Old->getLocation(), diag::note_previous_declaration);3827}3828}3829// Following a warning, we could skip merging effects from the previous3830// declaration, but that would trigger an additional "conflicting types"3831// error.3832if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {3833FunctionEffectSet::Conflicts MergeErrs;3834FunctionEffectSet MergedFX =3835FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);3836if (!MergeErrs.empty())3837diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),3838Old->getLocation());38393840FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();3841EPI.FunctionEffects = FunctionEffectsRef(MergedFX);3842QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),3843NewFPT->getParamTypes(), EPI);38443845New->setType(ModQT);3846NewQType = New->getType();38473848// Revise OldQTForComparison to include the merged effects,3849// so as not to fail due to differences later.3850if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {3851EPI = OldFPT->getExtProtoInfo();3852EPI.FunctionEffects = FunctionEffectsRef(MergedFX);3853OldQTypeForComparison = Context.getFunctionType(3854OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);3855}3856}3857}3858}38593860if (getLangOpts().CPlusPlus) {3861OldQType = Context.getCanonicalType(Old->getType());3862NewQType = Context.getCanonicalType(New->getType());38633864// Go back to the type source info to compare the declared return types,3865// per C++1y [dcl.type.auto]p13:3866// Redeclarations or specializations of a function or function template3867// with a declared return type that uses a placeholder type shall also3868// use that placeholder, not a deduced type.3869QualType OldDeclaredReturnType = Old->getDeclaredReturnType();3870QualType NewDeclaredReturnType = New->getDeclaredReturnType();3871if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&3872canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,3873OldDeclaredReturnType)) {3874QualType ResQT;3875if (NewDeclaredReturnType->isObjCObjectPointerType() &&3876OldDeclaredReturnType->isObjCObjectPointerType())3877// FIXME: This does the wrong thing for a deduced return type.3878ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);3879if (ResQT.isNull()) {3880if (New->isCXXClassMember() && New->isOutOfLine())3881Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)3882<< New << New->getReturnTypeSourceRange();3883else3884Diag(New->getLocation(), diag::err_ovl_diff_return_type)3885<< New->getReturnTypeSourceRange();3886Diag(OldLocation, PrevDiag) << Old << Old->getType()3887<< Old->getReturnTypeSourceRange();3888return true;3889}3890else3891NewQType = ResQT;3892}38933894QualType OldReturnType = OldType->getReturnType();3895QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();3896if (OldReturnType != NewReturnType) {3897// If this function has a deduced return type and has already been3898// defined, copy the deduced value from the old declaration.3899AutoType *OldAT = Old->getReturnType()->getContainedAutoType();3900if (OldAT && OldAT->isDeduced()) {3901QualType DT = OldAT->getDeducedType();3902if (DT.isNull()) {3903New->setType(SubstAutoTypeDependent(New->getType()));3904NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));3905} else {3906New->setType(SubstAutoType(New->getType(), DT));3907NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));3908}3909}3910}39113912const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);3913CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);3914if (OldMethod && NewMethod) {3915// Preserve triviality.3916NewMethod->setTrivial(OldMethod->isTrivial());39173918// MSVC allows explicit template specialization at class scope:3919// 2 CXXMethodDecls referring to the same function will be injected.3920// We don't want a redeclaration error.3921bool IsClassScopeExplicitSpecialization =3922OldMethod->isFunctionTemplateSpecialization() &&3923NewMethod->isFunctionTemplateSpecialization();3924bool isFriend = NewMethod->getFriendObjectKind();39253926if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&3927!IsClassScopeExplicitSpecialization) {3928// -- Member function declarations with the same name and the3929// same parameter types cannot be overloaded if any of them3930// is a static member function declaration.3931if (OldMethod->isStatic() != NewMethod->isStatic()) {3932Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);3933Diag(OldLocation, PrevDiag) << Old << Old->getType();3934return true;3935}39363937// C++ [class.mem]p1:3938// [...] A member shall not be declared twice in the3939// member-specification, except that a nested class or member3940// class template can be declared and then later defined.3941if (!inTemplateInstantiation()) {3942unsigned NewDiag;3943if (isa<CXXConstructorDecl>(OldMethod))3944NewDiag = diag::err_constructor_redeclared;3945else if (isa<CXXDestructorDecl>(NewMethod))3946NewDiag = diag::err_destructor_redeclared;3947else if (isa<CXXConversionDecl>(NewMethod))3948NewDiag = diag::err_conv_function_redeclared;3949else3950NewDiag = diag::err_member_redeclared;39513952Diag(New->getLocation(), NewDiag);3953} else {3954Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)3955<< New << New->getType();3956}3957Diag(OldLocation, PrevDiag) << Old << Old->getType();3958return true;39593960// Complain if this is an explicit declaration of a special3961// member that was initially declared implicitly.3962//3963// As an exception, it's okay to befriend such methods in order3964// to permit the implicit constructor/destructor/operator calls.3965} else if (OldMethod->isImplicit()) {3966if (isFriend) {3967NewMethod->setImplicit();3968} else {3969Diag(NewMethod->getLocation(),3970diag::err_definition_of_implicitly_declared_member)3971<< New << llvm::to_underlying(getSpecialMember(OldMethod));3972return true;3973}3974} else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {3975Diag(NewMethod->getLocation(),3976diag::err_definition_of_explicitly_defaulted_member)3977<< llvm::to_underlying(getSpecialMember(OldMethod));3978return true;3979}3980}39813982// C++1z [over.load]p23983// Certain function declarations cannot be overloaded:3984// -- Function declarations that differ only in the return type,3985// the exception specification, or both cannot be overloaded.39863987// Check the exception specifications match. This may recompute the type of3988// both Old and New if it resolved exception specifications, so grab the3989// types again after this. Because this updates the type, we do this before3990// any of the other checks below, which may update the "de facto" NewQType3991// but do not necessarily update the type of New.3992if (CheckEquivalentExceptionSpec(Old, New))3993return true;39943995// C++11 [dcl.attr.noreturn]p1:3996// The first declaration of a function shall specify the noreturn3997// attribute if any declaration of that function specifies the noreturn3998// attribute.3999if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())4000if (!Old->hasAttr<CXX11NoReturnAttr>()) {4001Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)4002<< NRA;4003Diag(Old->getLocation(), diag::note_previous_declaration);4004}40054006// C++11 [dcl.attr.depend]p2:4007// The first declaration of a function shall specify the4008// carries_dependency attribute for its declarator-id if any declaration4009// of the function specifies the carries_dependency attribute.4010const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();4011if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {4012Diag(CDA->getLocation(),4013diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;4014Diag(Old->getFirstDecl()->getLocation(),4015diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;4016}40174018// (C++98 8.3.5p3):4019// All declarations for a function shall agree exactly in both the4020// return type and the parameter-type-list.4021// We also want to respect all the extended bits except noreturn.40224023// noreturn should now match unless the old type info didn't have it.4024if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {4025auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();4026const FunctionType *OldTypeForComparison4027= Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));4028OldQTypeForComparison = QualType(OldTypeForComparison, 0);4029assert(OldQTypeForComparison.isCanonical());4030}40314032if (haveIncompatibleLanguageLinkages(Old, New)) {4033// As a special case, retain the language linkage from previous4034// declarations of a friend function as an extension.4035//4036// This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC4037// and is useful because there's otherwise no way to specify language4038// linkage within class scope.4039//4040// Check cautiously as the friend object kind isn't yet complete.4041if (New->getFriendObjectKind() != Decl::FOK_None) {4042Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;4043Diag(OldLocation, PrevDiag);4044} else {4045Diag(New->getLocation(), diag::err_different_language_linkage) << New;4046Diag(OldLocation, PrevDiag);4047return true;4048}4049}40504051// If the function types are compatible, merge the declarations. Ignore the4052// exception specifier because it was already checked above in4053// CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics4054// about incompatible types under -fms-compatibility.4055if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,4056NewQType))4057return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);40584059// If the types are imprecise (due to dependent constructs in friends or4060// local extern declarations), it's OK if they differ. We'll check again4061// during instantiation.4062if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))4063return false;40644065// Fall through for conflicting redeclarations and redefinitions.4066}40674068// C: Function types need to be compatible, not identical. This handles4069// duplicate function decls like "void f(int); void f(enum X);" properly.4070if (!getLangOpts().CPlusPlus) {4071// C99 6.7.5.3p15: ...If one type has a parameter type list and the other4072// type is specified by a function definition that contains a (possibly4073// empty) identifier list, both shall agree in the number of parameters4074// and the type of each parameter shall be compatible with the type that4075// results from the application of default argument promotions to the4076// type of the corresponding identifier. ...4077// This cannot be handled by ASTContext::typesAreCompatible() because that4078// doesn't know whether the function type is for a definition or not when4079// eventually calling ASTContext::mergeFunctionTypes(). The only situation4080// we need to cover here is that the number of arguments agree as the4081// default argument promotion rules were already checked by4082// ASTContext::typesAreCompatible().4083if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&4084Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {4085if (Old->hasInheritedPrototype())4086Old = Old->getCanonicalDecl();4087Diag(New->getLocation(), diag::err_conflicting_types) << New;4088Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();4089return true;4090}40914092// If we are merging two functions where only one of them has a prototype,4093// we may have enough information to decide to issue a diagnostic that the4094// function without a prototype will change behavior in C23. This handles4095// cases like:4096// void i(); void i(int j);4097// void i(int j); void i();4098// void i(); void i(int j) {}4099// See ActOnFinishFunctionBody() for other cases of the behavior change4100// diagnostic. See GetFullTypeForDeclarator() for handling of a function4101// type without a prototype.4102if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&4103!New->isImplicit() && !Old->isImplicit()) {4104const FunctionDecl *WithProto, *WithoutProto;4105if (New->hasWrittenPrototype()) {4106WithProto = New;4107WithoutProto = Old;4108} else {4109WithProto = Old;4110WithoutProto = New;4111}41124113if (WithProto->getNumParams() != 0) {4114if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {4115// The one without the prototype will be changing behavior in C23, so4116// warn about that one so long as it's a user-visible declaration.4117bool IsWithoutProtoADef = false, IsWithProtoADef = false;4118if (WithoutProto == New)4119IsWithoutProtoADef = NewDeclIsDefn;4120else4121IsWithProtoADef = NewDeclIsDefn;4122Diag(WithoutProto->getLocation(),4123diag::warn_non_prototype_changes_behavior)4124<< IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)4125<< (WithoutProto == Old) << IsWithProtoADef;41264127// The reason the one without the prototype will be changing behavior4128// is because of the one with the prototype, so note that so long as4129// it's a user-visible declaration. There is one exception to this:4130// when the new declaration is a definition without a prototype, the4131// old declaration with a prototype is not the cause of the issue,4132// and that does not need to be noted because the one with a4133// prototype will not change behavior in C23.4134if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&4135!IsWithoutProtoADef)4136Diag(WithProto->getLocation(), diag::note_conflicting_prototype);4137}4138}4139}41404141if (Context.typesAreCompatible(OldQType, NewQType)) {4142const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();4143const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();4144const FunctionProtoType *OldProto = nullptr;4145if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&4146(OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {4147// The old declaration provided a function prototype, but the4148// new declaration does not. Merge in the prototype.4149assert(!OldProto->hasExceptionSpec() && "Exception spec in C");4150NewQType = Context.getFunctionType(NewFuncType->getReturnType(),4151OldProto->getParamTypes(),4152OldProto->getExtProtoInfo());4153New->setType(NewQType);4154New->setHasInheritedPrototype();41554156// Synthesize parameters with the same types.4157SmallVector<ParmVarDecl *, 16> Params;4158for (const auto &ParamType : OldProto->param_types()) {4159ParmVarDecl *Param = ParmVarDecl::Create(4160Context, New, SourceLocation(), SourceLocation(), nullptr,4161ParamType, /*TInfo=*/nullptr, SC_None, nullptr);4162Param->setScopeInfo(0, Params.size());4163Param->setImplicit();4164Params.push_back(Param);4165}41664167New->setParams(Params);4168}41694170return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);4171}4172}41734174// Check if the function types are compatible when pointer size address4175// spaces are ignored.4176if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))4177return false;41784179// GNU C permits a K&R definition to follow a prototype declaration4180// if the declared types of the parameters in the K&R definition4181// match the types in the prototype declaration, even when the4182// promoted types of the parameters from the K&R definition differ4183// from the types in the prototype. GCC then keeps the types from4184// the prototype.4185//4186// If a variadic prototype is followed by a non-variadic K&R definition,4187// the K&R definition becomes variadic. This is sort of an edge case, but4188// it's legal per the standard depending on how you read C99 6.7.5.3p15 and4189// C99 6.9.1p8.4190if (!getLangOpts().CPlusPlus &&4191Old->hasPrototype() && !New->hasPrototype() &&4192New->getType()->getAs<FunctionProtoType>() &&4193Old->getNumParams() == New->getNumParams()) {4194SmallVector<QualType, 16> ArgTypes;4195SmallVector<GNUCompatibleParamWarning, 16> Warnings;4196const FunctionProtoType *OldProto4197= Old->getType()->getAs<FunctionProtoType>();4198const FunctionProtoType *NewProto4199= New->getType()->getAs<FunctionProtoType>();42004201// Determine whether this is the GNU C extension.4202QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),4203NewProto->getReturnType());4204bool LooseCompatible = !MergedReturn.isNull();4205for (unsigned Idx = 0, End = Old->getNumParams();4206LooseCompatible && Idx != End; ++Idx) {4207ParmVarDecl *OldParm = Old->getParamDecl(Idx);4208ParmVarDecl *NewParm = New->getParamDecl(Idx);4209if (Context.typesAreCompatible(OldParm->getType(),4210NewProto->getParamType(Idx))) {4211ArgTypes.push_back(NewParm->getType());4212} else if (Context.typesAreCompatible(OldParm->getType(),4213NewParm->getType(),4214/*CompareUnqualified=*/true)) {4215GNUCompatibleParamWarning Warn = { OldParm, NewParm,4216NewProto->getParamType(Idx) };4217Warnings.push_back(Warn);4218ArgTypes.push_back(NewParm->getType());4219} else4220LooseCompatible = false;4221}42224223if (LooseCompatible) {4224for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {4225Diag(Warnings[Warn].NewParm->getLocation(),4226diag::ext_param_promoted_not_compatible_with_prototype)4227<< Warnings[Warn].PromotedType4228<< Warnings[Warn].OldParm->getType();4229if (Warnings[Warn].OldParm->getLocation().isValid())4230Diag(Warnings[Warn].OldParm->getLocation(),4231diag::note_previous_declaration);4232}42334234if (MergeTypeWithOld)4235New->setType(Context.getFunctionType(MergedReturn, ArgTypes,4236OldProto->getExtProtoInfo()));4237return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);4238}42394240// Fall through to diagnose conflicting types.4241}42424243// A function that has already been declared has been redeclared or4244// defined with a different type; show an appropriate diagnostic.42454246// If the previous declaration was an implicitly-generated builtin4247// declaration, then at the very least we should use a specialized note.4248unsigned BuiltinID;4249if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {4250// If it's actually a library-defined builtin function like 'malloc'4251// or 'printf', just warn about the incompatible redeclaration.4252if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {4253Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;4254Diag(OldLocation, diag::note_previous_builtin_declaration)4255<< Old << Old->getType();4256return false;4257}42584259PrevDiag = diag::note_previous_builtin_declaration;4260}42614262Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();4263Diag(OldLocation, PrevDiag) << Old << Old->getType();4264return true;4265}42664267bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,4268Scope *S, bool MergeTypeWithOld) {4269// Merge the attributes4270mergeDeclAttributes(New, Old);42714272// Merge "pure" flag.4273if (Old->isPureVirtual())4274New->setIsPureVirtual();42754276// Merge "used" flag.4277if (Old->getMostRecentDecl()->isUsed(false))4278New->setIsUsed();42794280// Merge attributes from the parameters. These can mismatch with K&R4281// declarations.4282if (New->getNumParams() == Old->getNumParams())4283for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {4284ParmVarDecl *NewParam = New->getParamDecl(i);4285ParmVarDecl *OldParam = Old->getParamDecl(i);4286mergeParamDeclAttributes(NewParam, OldParam, *this);4287mergeParamDeclTypes(NewParam, OldParam, *this);4288}42894290if (getLangOpts().CPlusPlus)4291return MergeCXXFunctionDecl(New, Old, S);42924293// Merge the function types so the we get the composite types for the return4294// and argument types. Per C11 6.2.7/4, only update the type if the old decl4295// was visible.4296QualType Merged = Context.mergeTypes(Old->getType(), New->getType());4297if (!Merged.isNull() && MergeTypeWithOld)4298New->setType(Merged);42994300return false;4301}43024303void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,4304ObjCMethodDecl *oldMethod) {4305// Merge the attributes, including deprecated/unavailable4306AvailabilityMergeKind MergeKind =4307isa<ObjCProtocolDecl>(oldMethod->getDeclContext())4308? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation4309: AMK_ProtocolImplementation)4310: isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration4311: AMK_Override;43124313mergeDeclAttributes(newMethod, oldMethod, MergeKind);43144315// Merge attributes from the parameters.4316ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),4317oe = oldMethod->param_end();4318for (ObjCMethodDecl::param_iterator4319ni = newMethod->param_begin(), ne = newMethod->param_end();4320ni != ne && oi != oe; ++ni, ++oi)4321mergeParamDeclAttributes(*ni, *oi, *this);43224323ObjC().CheckObjCMethodOverride(newMethod, oldMethod);4324}43254326static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {4327assert(!S.Context.hasSameType(New->getType(), Old->getType()));43284329S.Diag(New->getLocation(), New->isThisDeclarationADefinition()4330? diag::err_redefinition_different_type4331: diag::err_redeclaration_different_type)4332<< New->getDeclName() << New->getType() << Old->getType();43334334diag::kind PrevDiag;4335SourceLocation OldLocation;4336std::tie(PrevDiag, OldLocation)4337= getNoteDiagForInvalidRedeclaration(Old, New);4338S.Diag(OldLocation, PrevDiag) << Old << Old->getType();4339New->setInvalidDecl();4340}43414342void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,4343bool MergeTypeWithOld) {4344if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())4345return;43464347QualType MergedT;4348if (getLangOpts().CPlusPlus) {4349if (New->getType()->isUndeducedType()) {4350// We don't know what the new type is until the initializer is attached.4351return;4352} else if (Context.hasSameType(New->getType(), Old->getType())) {4353// These could still be something that needs exception specs checked.4354return MergeVarDeclExceptionSpecs(New, Old);4355}4356// C++ [basic.link]p10:4357// [...] the types specified by all declarations referring to a given4358// object or function shall be identical, except that declarations for an4359// array object can specify array types that differ by the presence or4360// absence of a major array bound (8.3.4).4361else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {4362const ArrayType *OldArray = Context.getAsArrayType(Old->getType());4363const ArrayType *NewArray = Context.getAsArrayType(New->getType());43644365// We are merging a variable declaration New into Old. If it has an array4366// bound, and that bound differs from Old's bound, we should diagnose the4367// mismatch.4368if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {4369for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;4370PrevVD = PrevVD->getPreviousDecl()) {4371QualType PrevVDTy = PrevVD->getType();4372if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())4373continue;43744375if (!Context.hasSameType(New->getType(), PrevVDTy))4376return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);4377}4378}43794380if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {4381if (Context.hasSameType(OldArray->getElementType(),4382NewArray->getElementType()))4383MergedT = New->getType();4384}4385// FIXME: Check visibility. New is hidden but has a complete type. If New4386// has no array bound, it should not inherit one from Old, if Old is not4387// visible.4388else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {4389if (Context.hasSameType(OldArray->getElementType(),4390NewArray->getElementType()))4391MergedT = Old->getType();4392}4393}4394else if (New->getType()->isObjCObjectPointerType() &&4395Old->getType()->isObjCObjectPointerType()) {4396MergedT = Context.mergeObjCGCQualifiers(New->getType(),4397Old->getType());4398}4399} else {4400// C 6.2.7p2:4401// All declarations that refer to the same object or function shall have4402// compatible type.4403MergedT = Context.mergeTypes(New->getType(), Old->getType());4404}4405if (MergedT.isNull()) {4406// It's OK if we couldn't merge types if either type is dependent, for a4407// block-scope variable. In other cases (static data members of class4408// templates, variable templates, ...), we require the types to be4409// equivalent.4410// FIXME: The C++ standard doesn't say anything about this.4411if ((New->getType()->isDependentType() ||4412Old->getType()->isDependentType()) && New->isLocalVarDecl()) {4413// If the old type was dependent, we can't merge with it, so the new type4414// becomes dependent for now. We'll reproduce the original type when we4415// instantiate the TypeSourceInfo for the variable.4416if (!New->getType()->isDependentType() && MergeTypeWithOld)4417New->setType(Context.DependentTy);4418return;4419}4420return diagnoseVarDeclTypeMismatch(*this, New, Old);4421}44224423// Don't actually update the type on the new declaration if the old4424// declaration was an extern declaration in a different scope.4425if (MergeTypeWithOld)4426New->setType(MergedT);4427}44284429static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,4430LookupResult &Previous) {4431// C11 6.2.7p4:4432// For an identifier with internal or external linkage declared4433// in a scope in which a prior declaration of that identifier is4434// visible, if the prior declaration specifies internal or4435// external linkage, the type of the identifier at the later4436// declaration becomes the composite type.4437//4438// If the variable isn't visible, we do not merge with its type.4439if (Previous.isShadowed())4440return false;44414442if (S.getLangOpts().CPlusPlus) {4443// C++11 [dcl.array]p3:4444// If there is a preceding declaration of the entity in the same4445// scope in which the bound was specified, an omitted array bound4446// is taken to be the same as in that earlier declaration.4447return NewVD->isPreviousDeclInSameBlockScope() ||4448(!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&4449!NewVD->getLexicalDeclContext()->isFunctionOrMethod());4450} else {4451// If the old declaration was function-local, don't merge with its4452// type unless we're in the same function.4453return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||4454OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();4455}4456}44574458void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {4459// If the new decl is already invalid, don't do any other checking.4460if (New->isInvalidDecl())4461return;44624463if (!shouldLinkPossiblyHiddenDecl(Previous, New))4464return;44654466VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();44674468// Verify the old decl was also a variable or variable template.4469VarDecl *Old = nullptr;4470VarTemplateDecl *OldTemplate = nullptr;4471if (Previous.isSingleResult()) {4472if (NewTemplate) {4473OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());4474Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;44754476if (auto *Shadow =4477dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))4478if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))4479return New->setInvalidDecl();4480} else {4481Old = dyn_cast<VarDecl>(Previous.getFoundDecl());44824483if (auto *Shadow =4484dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))4485if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))4486return New->setInvalidDecl();4487}4488}4489if (!Old) {4490Diag(New->getLocation(), diag::err_redefinition_different_kind)4491<< New->getDeclName();4492notePreviousDefinition(Previous.getRepresentativeDecl(),4493New->getLocation());4494return New->setInvalidDecl();4495}44964497// If the old declaration was found in an inline namespace and the new4498// declaration was qualified, update the DeclContext to match.4499adjustDeclContextForDeclaratorDecl(New, Old);45004501// Ensure the template parameters are compatible.4502if (NewTemplate &&4503!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),4504OldTemplate->getTemplateParameters(),4505/*Complain=*/true, TPL_TemplateMatch))4506return New->setInvalidDecl();45074508// C++ [class.mem]p1:4509// A member shall not be declared twice in the member-specification [...]4510//4511// Here, we need only consider static data members.4512if (Old->isStaticDataMember() && !New->isOutOfLine()) {4513Diag(New->getLocation(), diag::err_duplicate_member)4514<< New->getIdentifier();4515Diag(Old->getLocation(), diag::note_previous_declaration);4516New->setInvalidDecl();4517}45184519mergeDeclAttributes(New, Old);4520// Warn if an already-defined variable is made a weak_import in a subsequent4521// declaration4522if (New->hasAttr<WeakImportAttr>())4523for (auto *D = Old; D; D = D->getPreviousDecl()) {4524if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {4525Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();4526Diag(D->getLocation(), diag::note_previous_definition);4527// Remove weak_import attribute on new declaration.4528New->dropAttr<WeakImportAttr>();4529break;4530}4531}45324533if (const auto *ILA = New->getAttr<InternalLinkageAttr>())4534if (!Old->hasAttr<InternalLinkageAttr>()) {4535Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)4536<< ILA;4537Diag(Old->getLocation(), diag::note_previous_declaration);4538New->dropAttr<InternalLinkageAttr>();4539}45404541// Merge the types.4542VarDecl *MostRecent = Old->getMostRecentDecl();4543if (MostRecent != Old) {4544MergeVarDeclTypes(New, MostRecent,4545mergeTypeWithPrevious(*this, New, MostRecent, Previous));4546if (New->isInvalidDecl())4547return;4548}45494550MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));4551if (New->isInvalidDecl())4552return;45534554diag::kind PrevDiag;4555SourceLocation OldLocation;4556std::tie(PrevDiag, OldLocation) =4557getNoteDiagForInvalidRedeclaration(Old, New);45584559// [dcl.stc]p8: Check if we have a non-static decl followed by a static.4560if (New->getStorageClass() == SC_Static &&4561!New->isStaticDataMember() &&4562Old->hasExternalFormalLinkage()) {4563if (getLangOpts().MicrosoftExt) {4564Diag(New->getLocation(), diag::ext_static_non_static)4565<< New->getDeclName();4566Diag(OldLocation, PrevDiag);4567} else {4568Diag(New->getLocation(), diag::err_static_non_static)4569<< New->getDeclName();4570Diag(OldLocation, PrevDiag);4571return New->setInvalidDecl();4572}4573}4574// C99 6.2.2p4:4575// For an identifier declared with the storage-class specifier4576// extern in a scope in which a prior declaration of that4577// identifier is visible,23) if the prior declaration specifies4578// internal or external linkage, the linkage of the identifier at4579// the later declaration is the same as the linkage specified at4580// the prior declaration. If no prior declaration is visible, or4581// if the prior declaration specifies no linkage, then the4582// identifier has external linkage.4583if (New->hasExternalStorage() && Old->hasLinkage())4584/* Okay */;4585else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&4586!New->isStaticDataMember() &&4587Old->getCanonicalDecl()->getStorageClass() == SC_Static) {4588Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();4589Diag(OldLocation, PrevDiag);4590return New->setInvalidDecl();4591}45924593// Check if extern is followed by non-extern and vice-versa.4594if (New->hasExternalStorage() &&4595!Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {4596Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();4597Diag(OldLocation, PrevDiag);4598return New->setInvalidDecl();4599}4600if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&4601!New->hasExternalStorage()) {4602Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();4603Diag(OldLocation, PrevDiag);4604return New->setInvalidDecl();4605}46064607if (CheckRedeclarationInModule(New, Old))4608return;46094610// Variables with external linkage are analyzed in FinalizeDeclaratorGroup.46114612// FIXME: The test for external storage here seems wrong? We still4613// need to check for mismatches.4614if (!New->hasExternalStorage() && !New->isFileVarDecl() &&4615// Don't complain about out-of-line definitions of static members.4616!(Old->getLexicalDeclContext()->isRecord() &&4617!New->getLexicalDeclContext()->isRecord())) {4618Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();4619Diag(OldLocation, PrevDiag);4620return New->setInvalidDecl();4621}46224623if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {4624if (VarDecl *Def = Old->getDefinition()) {4625// C++1z [dcl.fcn.spec]p4:4626// If the definition of a variable appears in a translation unit before4627// its first declaration as inline, the program is ill-formed.4628Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;4629Diag(Def->getLocation(), diag::note_previous_definition);4630}4631}46324633// If this redeclaration makes the variable inline, we may need to add it to4634// UndefinedButUsed.4635if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&4636!Old->getDefinition() && !New->isThisDeclarationADefinition())4637UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),4638SourceLocation()));46394640if (New->getTLSKind() != Old->getTLSKind()) {4641if (!Old->getTLSKind()) {4642Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();4643Diag(OldLocation, PrevDiag);4644} else if (!New->getTLSKind()) {4645Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();4646Diag(OldLocation, PrevDiag);4647} else {4648// Do not allow redeclaration to change the variable between requiring4649// static and dynamic initialization.4650// FIXME: GCC allows this, but uses the TLS keyword on the first4651// declaration to determine the kind. Do we need to be compatible here?4652Diag(New->getLocation(), diag::err_thread_thread_different_kind)4653<< New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);4654Diag(OldLocation, PrevDiag);4655}4656}46574658// C++ doesn't have tentative definitions, so go right ahead and check here.4659if (getLangOpts().CPlusPlus) {4660if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&4661Old->getCanonicalDecl()->isConstexpr()) {4662// This definition won't be a definition any more once it's been merged.4663Diag(New->getLocation(),4664diag::warn_deprecated_redundant_constexpr_static_def);4665} else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {4666VarDecl *Def = Old->getDefinition();4667if (Def && checkVarDeclRedefinition(Def, New))4668return;4669}4670}46714672if (haveIncompatibleLanguageLinkages(Old, New)) {4673Diag(New->getLocation(), diag::err_different_language_linkage) << New;4674Diag(OldLocation, PrevDiag);4675New->setInvalidDecl();4676return;4677}46784679// Merge "used" flag.4680if (Old->getMostRecentDecl()->isUsed(false))4681New->setIsUsed();46824683// Keep a chain of previous declarations.4684New->setPreviousDecl(Old);4685if (NewTemplate)4686NewTemplate->setPreviousDecl(OldTemplate);46874688// Inherit access appropriately.4689New->setAccess(Old->getAccess());4690if (NewTemplate)4691NewTemplate->setAccess(New->getAccess());46924693if (Old->isInline())4694New->setImplicitlyInline();4695}46964697void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {4698SourceManager &SrcMgr = getSourceManager();4699auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);4700auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());4701auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);4702auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);4703auto &HSI = PP.getHeaderSearchInfo();4704StringRef HdrFilename =4705SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));47064707auto noteFromModuleOrInclude = [&](Module *Mod,4708SourceLocation IncLoc) -> bool {4709// Redefinition errors with modules are common with non modular mapped4710// headers, example: a non-modular header H in module A that also gets4711// included directly in a TU. Pointing twice to the same header/definition4712// is confusing, try to get better diagnostics when modules is on.4713if (IncLoc.isValid()) {4714if (Mod) {4715Diag(IncLoc, diag::note_redefinition_modules_same_file)4716<< HdrFilename.str() << Mod->getFullModuleName();4717if (!Mod->DefinitionLoc.isInvalid())4718Diag(Mod->DefinitionLoc, diag::note_defined_here)4719<< Mod->getFullModuleName();4720} else {4721Diag(IncLoc, diag::note_redefinition_include_same_file)4722<< HdrFilename.str();4723}4724return true;4725}47264727return false;4728};47294730// Is it the same file and same offset? Provide more information on why4731// this leads to a redefinition error.4732if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {4733SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);4734SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);4735bool EmittedDiag =4736noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);4737EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);47384739// If the header has no guards, emit a note suggesting one.4740if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))4741Diag(Old->getLocation(), diag::note_use_ifdef_guards);47424743if (EmittedDiag)4744return;4745}47464747// Redefinition coming from different files or couldn't do better above.4748if (Old->getLocation().isValid())4749Diag(Old->getLocation(), diag::note_previous_definition);4750}47514752bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {4753if (!hasVisibleDefinition(Old) &&4754(New->getFormalLinkage() == Linkage::Internal || New->isInline() ||4755isa<VarTemplateSpecializationDecl>(New) ||4756New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||4757New->getDeclContext()->isDependentContext())) {4758// The previous definition is hidden, and multiple definitions are4759// permitted (in separate TUs). Demote this to a declaration.4760New->demoteThisDefinitionToDeclaration();47614762// Make the canonical definition visible.4763if (auto *OldTD = Old->getDescribedVarTemplate())4764makeMergedDefinitionVisible(OldTD);4765makeMergedDefinitionVisible(Old);4766return false;4767} else {4768Diag(New->getLocation(), diag::err_redefinition) << New;4769notePreviousDefinition(Old, New->getLocation());4770New->setInvalidDecl();4771return true;4772}4773}47744775Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,4776DeclSpec &DS,4777const ParsedAttributesView &DeclAttrs,4778RecordDecl *&AnonRecord) {4779return ParsedFreeStandingDeclSpec(4780S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);4781}47824783// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to4784// disambiguate entities defined in different scopes.4785// While the VS2015 ABI fixes potential miscompiles, it is also breaks4786// compatibility.4787// We will pick our mangling number depending on which version of MSVC is being4788// targeted.4789static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {4790return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)4791? S->getMSCurManglingNumber()4792: S->getMSLastManglingNumber();4793}47944795void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {4796if (!Context.getLangOpts().CPlusPlus)4797return;47984799if (isa<CXXRecordDecl>(Tag->getParent())) {4800// If this tag is the direct child of a class, number it if4801// it is anonymous.4802if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())4803return;4804MangleNumberingContext &MCtx =4805Context.getManglingNumberContext(Tag->getParent());4806Context.setManglingNumber(4807Tag, MCtx.getManglingNumber(4808Tag, getMSManglingNumber(getLangOpts(), TagScope)));4809return;4810}48114812// If this tag isn't a direct child of a class, number it if it is local.4813MangleNumberingContext *MCtx;4814Decl *ManglingContextDecl;4815std::tie(MCtx, ManglingContextDecl) =4816getCurrentMangleNumberContext(Tag->getDeclContext());4817if (MCtx) {4818Context.setManglingNumber(4819Tag, MCtx->getManglingNumber(4820Tag, getMSManglingNumber(getLangOpts(), TagScope)));4821}4822}48234824namespace {4825struct NonCLikeKind {4826enum {4827None,4828BaseClass,4829DefaultMemberInit,4830Lambda,4831Friend,4832OtherMember,4833Invalid,4834} Kind = None;4835SourceRange Range;48364837explicit operator bool() { return Kind != None; }4838};4839}48404841/// Determine whether a class is C-like, according to the rules of C++4842/// [dcl.typedef] for anonymous classes with typedef names for linkage.4843static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {4844if (RD->isInvalidDecl())4845return {NonCLikeKind::Invalid, {}};48464847// C++ [dcl.typedef]p9: [P1766R1]4848// An unnamed class with a typedef name for linkage purposes shall not4849//4850// -- have any base classes4851if (RD->getNumBases())4852return {NonCLikeKind::BaseClass,4853SourceRange(RD->bases_begin()->getBeginLoc(),4854RD->bases_end()[-1].getEndLoc())};4855bool Invalid = false;4856for (Decl *D : RD->decls()) {4857// Don't complain about things we already diagnosed.4858if (D->isInvalidDecl()) {4859Invalid = true;4860continue;4861}48624863// -- have any [...] default member initializers4864if (auto *FD = dyn_cast<FieldDecl>(D)) {4865if (FD->hasInClassInitializer()) {4866auto *Init = FD->getInClassInitializer();4867return {NonCLikeKind::DefaultMemberInit,4868Init ? Init->getSourceRange() : D->getSourceRange()};4869}4870continue;4871}48724873// FIXME: We don't allow friend declarations. This violates the wording of4874// P1766, but not the intent.4875if (isa<FriendDecl>(D))4876return {NonCLikeKind::Friend, D->getSourceRange()};48774878// -- declare any members other than non-static data members, member4879// enumerations, or member classes,4880if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||4881isa<EnumDecl>(D))4882continue;4883auto *MemberRD = dyn_cast<CXXRecordDecl>(D);4884if (!MemberRD) {4885if (D->isImplicit())4886continue;4887return {NonCLikeKind::OtherMember, D->getSourceRange()};4888}48894890// -- contain a lambda-expression,4891if (MemberRD->isLambda())4892return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};48934894// and all member classes shall also satisfy these requirements4895// (recursively).4896if (MemberRD->isThisDeclarationADefinition()) {4897if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))4898return Kind;4899}4900}49014902return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};4903}49044905void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,4906TypedefNameDecl *NewTD) {4907if (TagFromDeclSpec->isInvalidDecl())4908return;49094910// Do nothing if the tag already has a name for linkage purposes.4911if (TagFromDeclSpec->hasNameForLinkage())4912return;49134914// A well-formed anonymous tag must always be a TagUseKind::Definition.4915assert(TagFromDeclSpec->isThisDeclarationADefinition());49164917// The type must match the tag exactly; no qualifiers allowed.4918if (!Context.hasSameType(NewTD->getUnderlyingType(),4919Context.getTagDeclType(TagFromDeclSpec))) {4920if (getLangOpts().CPlusPlus)4921Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);4922return;4923}49244925// C++ [dcl.typedef]p9: [P1766R1, applied as DR]4926// An unnamed class with a typedef name for linkage purposes shall [be4927// C-like].4928//4929// FIXME: Also diagnose if we've already computed the linkage. That ideally4930// shouldn't happen, but there are constructs that the language rule doesn't4931// disallow for which we can't reasonably avoid computing linkage early.4932const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);4933NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)4934: NonCLikeKind();4935bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();4936if (NonCLike || ChangesLinkage) {4937if (NonCLike.Kind == NonCLikeKind::Invalid)4938return;49394940unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;4941if (ChangesLinkage) {4942// If the linkage changes, we can't accept this as an extension.4943if (NonCLike.Kind == NonCLikeKind::None)4944DiagID = diag::err_typedef_changes_linkage;4945else4946DiagID = diag::err_non_c_like_anon_struct_in_typedef;4947}49484949SourceLocation FixitLoc =4950getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());4951llvm::SmallString<40> TextToInsert;4952TextToInsert += ' ';4953TextToInsert += NewTD->getIdentifier()->getName();49544955Diag(FixitLoc, DiagID)4956<< isa<TypeAliasDecl>(NewTD)4957<< FixItHint::CreateInsertion(FixitLoc, TextToInsert);4958if (NonCLike.Kind != NonCLikeKind::None) {4959Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)4960<< NonCLike.Kind - 1 << NonCLike.Range;4961}4962Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)4963<< NewTD << isa<TypeAliasDecl>(NewTD);49644965if (ChangesLinkage)4966return;4967}49684969// Otherwise, set this as the anon-decl typedef for the tag.4970TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);4971}49724973static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {4974DeclSpec::TST T = DS.getTypeSpecType();4975switch (T) {4976case DeclSpec::TST_class:4977return 0;4978case DeclSpec::TST_struct:4979return 1;4980case DeclSpec::TST_interface:4981return 2;4982case DeclSpec::TST_union:4983return 3;4984case DeclSpec::TST_enum:4985if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {4986if (ED->isScopedUsingClassTag())4987return 5;4988if (ED->isScoped())4989return 6;4990}4991return 4;4992default:4993llvm_unreachable("unexpected type specifier");4994}4995}49964997Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,4998DeclSpec &DS,4999const ParsedAttributesView &DeclAttrs,5000MultiTemplateParamsArg TemplateParams,5001bool IsExplicitInstantiation,5002RecordDecl *&AnonRecord) {5003Decl *TagD = nullptr;5004TagDecl *Tag = nullptr;5005if (DS.getTypeSpecType() == DeclSpec::TST_class ||5006DS.getTypeSpecType() == DeclSpec::TST_struct ||5007DS.getTypeSpecType() == DeclSpec::TST_interface ||5008DS.getTypeSpecType() == DeclSpec::TST_union ||5009DS.getTypeSpecType() == DeclSpec::TST_enum) {5010TagD = DS.getRepAsDecl();50115012if (!TagD) // We probably had an error5013return nullptr;50145015// Note that the above type specs guarantee that the5016// type rep is a Decl, whereas in many of the others5017// it's a Type.5018if (isa<TagDecl>(TagD))5019Tag = cast<TagDecl>(TagD);5020else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))5021Tag = CTD->getTemplatedDecl();5022}50235024if (Tag) {5025handleTagNumbering(Tag, S);5026Tag->setFreeStanding();5027if (Tag->isInvalidDecl())5028return Tag;5029}50305031if (unsigned TypeQuals = DS.getTypeQualifiers()) {5032// Enforce C99 6.7.3p2: "Types other than pointer types derived from object5033// or incomplete types shall not be restrict-qualified."5034if (TypeQuals & DeclSpec::TQ_restrict)5035Diag(DS.getRestrictSpecLoc(),5036diag::err_typecheck_invalid_restrict_not_pointer_noarg)5037<< DS.getSourceRange();5038}50395040if (DS.isInlineSpecified())5041Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)5042<< getLangOpts().CPlusPlus17;50435044if (DS.hasConstexprSpecifier()) {5045// C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations5046// and definitions of functions and variables.5047// C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to5048// the declaration of a function or function template5049if (Tag)5050Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)5051<< GetDiagnosticTypeSpecifierID(DS)5052<< static_cast<int>(DS.getConstexprSpecifier());5053else if (getLangOpts().C23)5054Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);5055else5056Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)5057<< static_cast<int>(DS.getConstexprSpecifier());5058// Don't emit warnings after this error.5059return TagD;5060}50615062DiagnoseFunctionSpecifiers(DS);50635064if (DS.isFriendSpecified()) {5065// If we're dealing with a decl but not a TagDecl, assume that5066// whatever routines created it handled the friendship aspect.5067if (TagD && !Tag)5068return nullptr;5069return ActOnFriendTypeDecl(S, DS, TemplateParams);5070}50715072// Track whether this decl-specifier declares anything.5073bool DeclaresAnything = true;50745075// Handle anonymous struct definitions.5076if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {5077if (!Record->getDeclName() && Record->isCompleteDefinition() &&5078DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {5079if (getLangOpts().CPlusPlus ||5080Record->getDeclContext()->isRecord()) {5081// If CurContext is a DeclContext that can contain statements,5082// RecursiveASTVisitor won't visit the decls that5083// BuildAnonymousStructOrUnion() will put into CurContext.5084// Also store them here so that they can be part of the5085// DeclStmt that gets created in this case.5086// FIXME: Also return the IndirectFieldDecls created by5087// BuildAnonymousStructOr union, for the same reason?5088if (CurContext->isFunctionOrMethod())5089AnonRecord = Record;5090return BuildAnonymousStructOrUnion(S, DS, AS, Record,5091Context.getPrintingPolicy());5092}50935094DeclaresAnything = false;5095}5096}50975098// C11 6.7.2.1p2:5099// A struct-declaration that does not declare an anonymous structure or5100// anonymous union shall contain a struct-declarator-list.5101//5102// This rule also existed in C89 and C99; the grammar for struct-declaration5103// did not permit a struct-declaration without a struct-declarator-list.5104if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&5105DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {5106// Check for Microsoft C extension: anonymous struct/union member.5107// Handle 2 kinds of anonymous struct/union:5108// struct STRUCT;5109// union UNION;5110// and5111// STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.5112// UNION_TYPE; <- where UNION_TYPE is a typedef union.5113if ((Tag && Tag->getDeclName()) ||5114DS.getTypeSpecType() == DeclSpec::TST_typename) {5115RecordDecl *Record = nullptr;5116if (Tag)5117Record = dyn_cast<RecordDecl>(Tag);5118else if (const RecordType *RT =5119DS.getRepAsType().get()->getAsStructureType())5120Record = RT->getDecl();5121else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())5122Record = UT->getDecl();51235124if (Record && getLangOpts().MicrosoftExt) {5125Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)5126<< Record->isUnion() << DS.getSourceRange();5127return BuildMicrosoftCAnonymousStruct(S, DS, Record);5128}51295130DeclaresAnything = false;5131}5132}51335134// Skip all the checks below if we have a type error.5135if (DS.getTypeSpecType() == DeclSpec::TST_error ||5136(TagD && TagD->isInvalidDecl()))5137return TagD;51385139if (getLangOpts().CPlusPlus &&5140DS.getStorageClassSpec() != DeclSpec::SCS_typedef)5141if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))5142if (Enum->enumerator_begin() == Enum->enumerator_end() &&5143!Enum->getIdentifier() && !Enum->isInvalidDecl())5144DeclaresAnything = false;51455146if (!DS.isMissingDeclaratorOk()) {5147// Customize diagnostic for a typedef missing a name.5148if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)5149Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)5150<< DS.getSourceRange();5151else5152DeclaresAnything = false;5153}51545155if (DS.isModulePrivateSpecified() &&5156Tag && Tag->getDeclContext()->isFunctionOrMethod())5157Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)5158<< llvm::to_underlying(Tag->getTagKind())5159<< FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());51605161ActOnDocumentableDecl(TagD);51625163// C 6.7/2:5164// A declaration [...] shall declare at least a declarator [...], a tag,5165// or the members of an enumeration.5166// C++ [dcl.dcl]p3:5167// [If there are no declarators], and except for the declaration of an5168// unnamed bit-field, the decl-specifier-seq shall introduce one or more5169// names into the program, or shall redeclare a name introduced by a5170// previous declaration.5171if (!DeclaresAnything) {5172// In C, we allow this as a (popular) extension / bug. Don't bother5173// producing further diagnostics for redundant qualifiers after this.5174Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())5175? diag::err_no_declarators5176: diag::ext_no_declarators)5177<< DS.getSourceRange();5178return TagD;5179}51805181// C++ [dcl.stc]p1:5182// If a storage-class-specifier appears in a decl-specifier-seq, [...] the5183// init-declarator-list of the declaration shall not be empty.5184// C++ [dcl.fct.spec]p1:5185// If a cv-qualifier appears in a decl-specifier-seq, the5186// init-declarator-list of the declaration shall not be empty.5187//5188// Spurious qualifiers here appear to be valid in C.5189unsigned DiagID = diag::warn_standalone_specifier;5190if (getLangOpts().CPlusPlus)5191DiagID = diag::ext_standalone_specifier;51925193// Note that a linkage-specification sets a storage class, but5194// 'extern "C" struct foo;' is actually valid and not theoretically5195// useless.5196if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {5197if (SCS == DeclSpec::SCS_mutable)5198// Since mutable is not a viable storage class specifier in C, there is5199// no reason to treat it as an extension. Instead, diagnose as an error.5200Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);5201else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)5202Diag(DS.getStorageClassSpecLoc(), DiagID)5203<< DeclSpec::getSpecifierName(SCS);5204}52055206if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())5207Diag(DS.getThreadStorageClassSpecLoc(), DiagID)5208<< DeclSpec::getSpecifierName(TSCS);5209if (DS.getTypeQualifiers()) {5210if (DS.getTypeQualifiers() & DeclSpec::TQ_const)5211Diag(DS.getConstSpecLoc(), DiagID) << "const";5212if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)5213Diag(DS.getConstSpecLoc(), DiagID) << "volatile";5214// Restrict is covered above.5215if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)5216Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";5217if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)5218Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";5219}52205221// Warn about ignored type attributes, for example:5222// __attribute__((aligned)) struct A;5223// Attributes should be placed after tag to apply to type declaration.5224if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {5225DeclSpec::TST TypeSpecType = DS.getTypeSpecType();5226if (TypeSpecType == DeclSpec::TST_class ||5227TypeSpecType == DeclSpec::TST_struct ||5228TypeSpecType == DeclSpec::TST_interface ||5229TypeSpecType == DeclSpec::TST_union ||5230TypeSpecType == DeclSpec::TST_enum) {52315232auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {5233unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;5234if (AL.isAlignas() && !getLangOpts().CPlusPlus)5235DiagnosticId = diag::warn_attribute_ignored;5236else if (AL.isRegularKeywordAttribute())5237DiagnosticId = diag::err_declspec_keyword_has_no_effect;5238else5239DiagnosticId = diag::warn_declspec_attribute_ignored;5240Diag(AL.getLoc(), DiagnosticId)5241<< AL << GetDiagnosticTypeSpecifierID(DS);5242};52435244llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);5245llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);5246}5247}52485249return TagD;5250}52515252/// We are trying to inject an anonymous member into the given scope;5253/// check if there's an existing declaration that can't be overloaded.5254///5255/// \return true if this is a forbidden redeclaration5256static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,5257DeclContext *Owner,5258DeclarationName Name,5259SourceLocation NameLoc, bool IsUnion,5260StorageClass SC) {5261LookupResult R(SemaRef, Name, NameLoc,5262Owner->isRecord() ? Sema::LookupMemberName5263: Sema::LookupOrdinaryName,5264RedeclarationKind::ForVisibleRedeclaration);5265if (!SemaRef.LookupName(R, S)) return false;52665267// Pick a representative declaration.5268NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();5269assert(PrevDecl && "Expected a non-null Decl");52705271if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))5272return false;52735274if (SC == StorageClass::SC_None &&5275PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&5276(Owner->isFunctionOrMethod() || Owner->isRecord())) {5277if (!Owner->isRecord())5278SemaRef.DiagPlaceholderVariableDefinition(NameLoc);5279return false;5280}52815282SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)5283<< IsUnion << Name;5284SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);52855286return true;5287}52885289void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {5290if (auto *RD = dyn_cast_if_present<RecordDecl>(D))5291DiagPlaceholderFieldDeclDefinitions(RD);5292}52935294void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {5295if (!getLangOpts().CPlusPlus)5296return;52975298// This function can be parsed before we have validated the5299// structure as an anonymous struct5300if (Record->isAnonymousStructOrUnion())5301return;53025303const NamedDecl *First = 0;5304for (const Decl *D : Record->decls()) {5305const NamedDecl *ND = dyn_cast<NamedDecl>(D);5306if (!ND || !ND->isPlaceholderVar(getLangOpts()))5307continue;5308if (!First)5309First = ND;5310else5311DiagPlaceholderVariableDefinition(ND->getLocation());5312}5313}53145315/// InjectAnonymousStructOrUnionMembers - Inject the members of the5316/// anonymous struct or union AnonRecord into the owning context Owner5317/// and scope S. This routine will be invoked just after we realize5318/// that an unnamed union or struct is actually an anonymous union or5319/// struct, e.g.,5320///5321/// @code5322/// union {5323/// int i;5324/// float f;5325/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and5326/// // f into the surrounding scope.x5327/// @endcode5328///5329/// This routine is recursive, injecting the names of nested anonymous5330/// structs/unions into the owning context and scope as well.5331static bool5332InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,5333RecordDecl *AnonRecord, AccessSpecifier AS,5334StorageClass SC,5335SmallVectorImpl<NamedDecl *> &Chaining) {5336bool Invalid = false;53375338// Look every FieldDecl and IndirectFieldDecl with a name.5339for (auto *D : AnonRecord->decls()) {5340if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&5341cast<NamedDecl>(D)->getDeclName()) {5342ValueDecl *VD = cast<ValueDecl>(D);5343if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),5344VD->getLocation(), AnonRecord->isUnion(),5345SC)) {5346// C++ [class.union]p2:5347// The names of the members of an anonymous union shall be5348// distinct from the names of any other entity in the5349// scope in which the anonymous union is declared.5350Invalid = true;5351} else {5352// C++ [class.union]p2:5353// For the purpose of name lookup, after the anonymous union5354// definition, the members of the anonymous union are5355// considered to have been defined in the scope in which the5356// anonymous union is declared.5357unsigned OldChainingSize = Chaining.size();5358if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))5359Chaining.append(IF->chain_begin(), IF->chain_end());5360else5361Chaining.push_back(VD);53625363assert(Chaining.size() >= 2);5364NamedDecl **NamedChain =5365new (SemaRef.Context)NamedDecl*[Chaining.size()];5366for (unsigned i = 0; i < Chaining.size(); i++)5367NamedChain[i] = Chaining[i];53685369IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(5370SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),5371VD->getType(), {NamedChain, Chaining.size()});53725373for (const auto *Attr : VD->attrs())5374IndirectField->addAttr(Attr->clone(SemaRef.Context));53755376IndirectField->setAccess(AS);5377IndirectField->setImplicit();5378SemaRef.PushOnScopeChains(IndirectField, S);53795380// That includes picking up the appropriate access specifier.5381if (AS != AS_none) IndirectField->setAccess(AS);53825383Chaining.resize(OldChainingSize);5384}5385}5386}53875388return Invalid;5389}53905391/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to5392/// a VarDecl::StorageClass. Any error reporting is up to the caller:5393/// illegal input values are mapped to SC_None.5394static StorageClass5395StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {5396DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();5397assert(StorageClassSpec != DeclSpec::SCS_typedef &&5398"Parser allowed 'typedef' as storage class VarDecl.");5399switch (StorageClassSpec) {5400case DeclSpec::SCS_unspecified: return SC_None;5401case DeclSpec::SCS_extern:5402if (DS.isExternInLinkageSpec())5403return SC_None;5404return SC_Extern;5405case DeclSpec::SCS_static: return SC_Static;5406case DeclSpec::SCS_auto: return SC_Auto;5407case DeclSpec::SCS_register: return SC_Register;5408case DeclSpec::SCS_private_extern: return SC_PrivateExtern;5409// Illegal SCSs map to None: error reporting is up to the caller.5410case DeclSpec::SCS_mutable: // Fall through.5411case DeclSpec::SCS_typedef: return SC_None;5412}5413llvm_unreachable("unknown storage class specifier");5414}54155416static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {5417assert(Record->hasInClassInitializer());54185419for (const auto *I : Record->decls()) {5420const auto *FD = dyn_cast<FieldDecl>(I);5421if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))5422FD = IFD->getAnonField();5423if (FD && FD->hasInClassInitializer())5424return FD->getLocation();5425}54265427llvm_unreachable("couldn't find in-class initializer");5428}54295430static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,5431SourceLocation DefaultInitLoc) {5432if (!Parent->isUnion() || !Parent->hasInClassInitializer())5433return;54345435S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);5436S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;5437}54385439static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,5440CXXRecordDecl *AnonUnion) {5441if (!Parent->isUnion() || !Parent->hasInClassInitializer())5442return;54435444checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));5445}54465447Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,5448AccessSpecifier AS,5449RecordDecl *Record,5450const PrintingPolicy &Policy) {5451DeclContext *Owner = Record->getDeclContext();54525453// Diagnose whether this anonymous struct/union is an extension.5454if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)5455Diag(Record->getLocation(), diag::ext_anonymous_union);5456else if (!Record->isUnion() && getLangOpts().CPlusPlus)5457Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);5458else if (!Record->isUnion() && !getLangOpts().C11)5459Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);54605461// C and C++ require different kinds of checks for anonymous5462// structs/unions.5463bool Invalid = false;5464if (getLangOpts().CPlusPlus) {5465const char *PrevSpec = nullptr;5466if (Record->isUnion()) {5467// C++ [class.union]p6:5468// C++17 [class.union.anon]p2:5469// Anonymous unions declared in a named namespace or in the5470// global namespace shall be declared static.5471unsigned DiagID;5472DeclContext *OwnerScope = Owner->getRedeclContext();5473if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&5474(OwnerScope->isTranslationUnit() ||5475(OwnerScope->isNamespace() &&5476!cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {5477Diag(Record->getLocation(), diag::err_anonymous_union_not_static)5478<< FixItHint::CreateInsertion(Record->getLocation(), "static ");54795480// Recover by adding 'static'.5481DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),5482PrevSpec, DiagID, Policy);5483}5484// C++ [class.union]p6:5485// A storage class is not allowed in a declaration of an5486// anonymous union in a class scope.5487else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&5488isa<RecordDecl>(Owner)) {5489Diag(DS.getStorageClassSpecLoc(),5490diag::err_anonymous_union_with_storage_spec)5491<< FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());54925493// Recover by removing the storage specifier.5494DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,5495SourceLocation(),5496PrevSpec, DiagID, Context.getPrintingPolicy());5497}5498}54995500// Ignore const/volatile/restrict qualifiers.5501if (DS.getTypeQualifiers()) {5502if (DS.getTypeQualifiers() & DeclSpec::TQ_const)5503Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)5504<< Record->isUnion() << "const"5505<< FixItHint::CreateRemoval(DS.getConstSpecLoc());5506if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)5507Diag(DS.getVolatileSpecLoc(),5508diag::ext_anonymous_struct_union_qualified)5509<< Record->isUnion() << "volatile"5510<< FixItHint::CreateRemoval(DS.getVolatileSpecLoc());5511if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)5512Diag(DS.getRestrictSpecLoc(),5513diag::ext_anonymous_struct_union_qualified)5514<< Record->isUnion() << "restrict"5515<< FixItHint::CreateRemoval(DS.getRestrictSpecLoc());5516if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)5517Diag(DS.getAtomicSpecLoc(),5518diag::ext_anonymous_struct_union_qualified)5519<< Record->isUnion() << "_Atomic"5520<< FixItHint::CreateRemoval(DS.getAtomicSpecLoc());5521if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)5522Diag(DS.getUnalignedSpecLoc(),5523diag::ext_anonymous_struct_union_qualified)5524<< Record->isUnion() << "__unaligned"5525<< FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());55265527DS.ClearTypeQualifiers();5528}55295530// C++ [class.union]p2:5531// The member-specification of an anonymous union shall only5532// define non-static data members. [Note: nested types and5533// functions cannot be declared within an anonymous union. ]5534for (auto *Mem : Record->decls()) {5535// Ignore invalid declarations; we already diagnosed them.5536if (Mem->isInvalidDecl())5537continue;55385539if (auto *FD = dyn_cast<FieldDecl>(Mem)) {5540// C++ [class.union]p3:5541// An anonymous union shall not have private or protected5542// members (clause 11).5543assert(FD->getAccess() != AS_none);5544if (FD->getAccess() != AS_public) {5545Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)5546<< Record->isUnion() << (FD->getAccess() == AS_protected);5547Invalid = true;5548}55495550// C++ [class.union]p15551// An object of a class with a non-trivial constructor, a non-trivial5552// copy constructor, a non-trivial destructor, or a non-trivial copy5553// assignment operator cannot be a member of a union, nor can an5554// array of such objects.5555if (CheckNontrivialField(FD))5556Invalid = true;5557} else if (Mem->isImplicit()) {5558// Any implicit members are fine.5559} else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {5560// This is a type that showed up in an5561// elaborated-type-specifier inside the anonymous struct or5562// union, but which actually declares a type outside of the5563// anonymous struct or union. It's okay.5564} else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {5565if (!MemRecord->isAnonymousStructOrUnion() &&5566MemRecord->getDeclName()) {5567// Visual C++ allows type definition in anonymous struct or union.5568if (getLangOpts().MicrosoftExt)5569Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)5570<< Record->isUnion();5571else {5572// This is a nested type declaration.5573Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)5574<< Record->isUnion();5575Invalid = true;5576}5577} else {5578// This is an anonymous type definition within another anonymous type.5579// This is a popular extension, provided by Plan9, MSVC and GCC, but5580// not part of standard C++.5581Diag(MemRecord->getLocation(),5582diag::ext_anonymous_record_with_anonymous_type)5583<< Record->isUnion();5584}5585} else if (isa<AccessSpecDecl>(Mem)) {5586// Any access specifier is fine.5587} else if (isa<StaticAssertDecl>(Mem)) {5588// In C++1z, static_assert declarations are also fine.5589} else {5590// We have something that isn't a non-static data5591// member. Complain about it.5592unsigned DK = diag::err_anonymous_record_bad_member;5593if (isa<TypeDecl>(Mem))5594DK = diag::err_anonymous_record_with_type;5595else if (isa<FunctionDecl>(Mem))5596DK = diag::err_anonymous_record_with_function;5597else if (isa<VarDecl>(Mem))5598DK = diag::err_anonymous_record_with_static;55995600// Visual C++ allows type definition in anonymous struct or union.5601if (getLangOpts().MicrosoftExt &&5602DK == diag::err_anonymous_record_with_type)5603Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)5604<< Record->isUnion();5605else {5606Diag(Mem->getLocation(), DK) << Record->isUnion();5607Invalid = true;5608}5609}5610}56115612// C++11 [class.union]p8 (DR1460):5613// At most one variant member of a union may have a5614// brace-or-equal-initializer.5615if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&5616Owner->isRecord())5617checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),5618cast<CXXRecordDecl>(Record));5619}56205621if (!Record->isUnion() && !Owner->isRecord()) {5622Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)5623<< getLangOpts().CPlusPlus;5624Invalid = true;5625}56265627// C++ [dcl.dcl]p3:5628// [If there are no declarators], and except for the declaration of an5629// unnamed bit-field, the decl-specifier-seq shall introduce one or more5630// names into the program5631// C++ [class.mem]p2:5632// each such member-declaration shall either declare at least one member5633// name of the class or declare at least one unnamed bit-field5634//5635// For C this is an error even for a named struct, and is diagnosed elsewhere.5636if (getLangOpts().CPlusPlus && Record->field_empty())5637Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();56385639// Mock up a declarator.5640Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);5641StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);5642TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc);5643assert(TInfo && "couldn't build declarator info for anonymous struct/union");56445645// Create a declaration for this anonymous struct/union.5646NamedDecl *Anon = nullptr;5647if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {5648Anon = FieldDecl::Create(5649Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),5650/*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,5651/*BitWidth=*/nullptr, /*Mutable=*/false,5652/*InitStyle=*/ICIS_NoInit);5653Anon->setAccess(AS);5654ProcessDeclAttributes(S, Anon, Dc);56555656if (getLangOpts().CPlusPlus)5657FieldCollector->Add(cast<FieldDecl>(Anon));5658} else {5659DeclSpec::SCS SCSpec = DS.getStorageClassSpec();5660if (SCSpec == DeclSpec::SCS_mutable) {5661// mutable can only appear on non-static class members, so it's always5662// an error here5663Diag(Record->getLocation(), diag::err_mutable_nonmember);5664Invalid = true;5665SC = SC_None;5666}56675668Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),5669Record->getLocation(), /*IdentifierInfo=*/nullptr,5670Context.getTypeDeclType(Record), TInfo, SC);5671if (Invalid)5672Anon->setInvalidDecl();56735674ProcessDeclAttributes(S, Anon, Dc);56755676// Default-initialize the implicit variable. This initialization will be5677// trivial in almost all cases, except if a union member has an in-class5678// initializer:5679// union { int n = 0; };5680ActOnUninitializedDecl(Anon);5681}5682Anon->setImplicit();56835684// Mark this as an anonymous struct/union type.5685Record->setAnonymousStructOrUnion(true);56865687// Add the anonymous struct/union object to the current5688// context. We'll be referencing this object when we refer to one of5689// its members.5690Owner->addDecl(Anon);56915692// Inject the members of the anonymous struct/union into the owning5693// context and into the identifier resolver chain for name lookup5694// purposes.5695SmallVector<NamedDecl*, 2> Chain;5696Chain.push_back(Anon);56975698if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,5699Chain))5700Invalid = true;57015702if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {5703if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {5704MangleNumberingContext *MCtx;5705Decl *ManglingContextDecl;5706std::tie(MCtx, ManglingContextDecl) =5707getCurrentMangleNumberContext(NewVD->getDeclContext());5708if (MCtx) {5709Context.setManglingNumber(5710NewVD, MCtx->getManglingNumber(5711NewVD, getMSManglingNumber(getLangOpts(), S)));5712Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));5713}5714}5715}57165717if (Invalid)5718Anon->setInvalidDecl();57195720return Anon;5721}57225723Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,5724RecordDecl *Record) {5725assert(Record && "expected a record!");57265727// Mock up a declarator.5728Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);5729TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc);5730assert(TInfo && "couldn't build declarator info for anonymous struct");57315732auto *ParentDecl = cast<RecordDecl>(CurContext);5733QualType RecTy = Context.getTypeDeclType(Record);57345735// Create a declaration for this anonymous struct.5736NamedDecl *Anon =5737FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),5738/*IdentifierInfo=*/nullptr, RecTy, TInfo,5739/*BitWidth=*/nullptr, /*Mutable=*/false,5740/*InitStyle=*/ICIS_NoInit);5741Anon->setImplicit();57425743// Add the anonymous struct object to the current context.5744CurContext->addDecl(Anon);57455746// Inject the members of the anonymous struct into the current5747// context and into the identifier resolver chain for name lookup5748// purposes.5749SmallVector<NamedDecl*, 2> Chain;5750Chain.push_back(Anon);57515752RecordDecl *RecordDef = Record->getDefinition();5753if (RequireCompleteSizedType(Anon->getLocation(), RecTy,5754diag::err_field_incomplete_or_sizeless) ||5755InjectAnonymousStructOrUnionMembers(5756*this, S, CurContext, RecordDef, AS_none,5757StorageClassSpecToVarDeclStorageClass(DS), Chain)) {5758Anon->setInvalidDecl();5759ParentDecl->setInvalidDecl();5760}57615762return Anon;5763}57645765DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {5766return GetNameFromUnqualifiedId(D.getName());5767}57685769DeclarationNameInfo5770Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {5771DeclarationNameInfo NameInfo;5772NameInfo.setLoc(Name.StartLocation);57735774switch (Name.getKind()) {57755776case UnqualifiedIdKind::IK_ImplicitSelfParam:5777case UnqualifiedIdKind::IK_Identifier:5778NameInfo.setName(Name.Identifier);5779return NameInfo;57805781case UnqualifiedIdKind::IK_DeductionGuideName: {5782// C++ [temp.deduct.guide]p3:5783// The simple-template-id shall name a class template specialization.5784// The template-name shall be the same identifier as the template-name5785// of the simple-template-id.5786// These together intend to imply that the template-name shall name a5787// class template.5788// FIXME: template<typename T> struct X {};5789// template<typename T> using Y = X<T>;5790// Y(int) -> Y<int>;5791// satisfies these rules but does not name a class template.5792TemplateName TN = Name.TemplateName.get().get();5793auto *Template = TN.getAsTemplateDecl();5794if (!Template || !isa<ClassTemplateDecl>(Template)) {5795Diag(Name.StartLocation,5796diag::err_deduction_guide_name_not_class_template)5797<< (int)getTemplateNameKindForDiagnostics(TN) << TN;5798if (Template)5799NoteTemplateLocation(*Template);5800return DeclarationNameInfo();5801}58025803NameInfo.setName(5804Context.DeclarationNames.getCXXDeductionGuideName(Template));5805return NameInfo;5806}58075808case UnqualifiedIdKind::IK_OperatorFunctionId:5809NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(5810Name.OperatorFunctionId.Operator));5811NameInfo.setCXXOperatorNameRange(SourceRange(5812Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));5813return NameInfo;58145815case UnqualifiedIdKind::IK_LiteralOperatorId:5816NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(5817Name.Identifier));5818NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);5819return NameInfo;58205821case UnqualifiedIdKind::IK_ConversionFunctionId: {5822TypeSourceInfo *TInfo;5823QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);5824if (Ty.isNull())5825return DeclarationNameInfo();5826NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(5827Context.getCanonicalType(Ty)));5828NameInfo.setNamedTypeInfo(TInfo);5829return NameInfo;5830}58315832case UnqualifiedIdKind::IK_ConstructorName: {5833TypeSourceInfo *TInfo;5834QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);5835if (Ty.isNull())5836return DeclarationNameInfo();5837NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(5838Context.getCanonicalType(Ty)));5839NameInfo.setNamedTypeInfo(TInfo);5840return NameInfo;5841}58425843case UnqualifiedIdKind::IK_ConstructorTemplateId: {5844// In well-formed code, we can only have a constructor5845// template-id that refers to the current context, so go there5846// to find the actual type being constructed.5847CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);5848if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)5849return DeclarationNameInfo();58505851// Determine the type of the class being constructed.5852QualType CurClassType = Context.getTypeDeclType(CurClass);58535854// FIXME: Check two things: that the template-id names the same type as5855// CurClassType, and that the template-id does not occur when the name5856// was qualified.58575858NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(5859Context.getCanonicalType(CurClassType)));5860// FIXME: should we retrieve TypeSourceInfo?5861NameInfo.setNamedTypeInfo(nullptr);5862return NameInfo;5863}58645865case UnqualifiedIdKind::IK_DestructorName: {5866TypeSourceInfo *TInfo;5867QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);5868if (Ty.isNull())5869return DeclarationNameInfo();5870NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(5871Context.getCanonicalType(Ty)));5872NameInfo.setNamedTypeInfo(TInfo);5873return NameInfo;5874}58755876case UnqualifiedIdKind::IK_TemplateId: {5877TemplateName TName = Name.TemplateId->Template.get();5878SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;5879return Context.getNameForTemplate(TName, TNameLoc);5880}58815882} // switch (Name.getKind())58835884llvm_unreachable("Unknown name kind");5885}58865887static QualType getCoreType(QualType Ty) {5888do {5889if (Ty->isPointerType() || Ty->isReferenceType())5890Ty = Ty->getPointeeType();5891else if (Ty->isArrayType())5892Ty = Ty->castAsArrayTypeUnsafe()->getElementType();5893else5894return Ty.withoutLocalFastQualifiers();5895} while (true);5896}58975898/// hasSimilarParameters - Determine whether the C++ functions Declaration5899/// and Definition have "nearly" matching parameters. This heuristic is5900/// used to improve diagnostics in the case where an out-of-line function5901/// definition doesn't match any declaration within the class or namespace.5902/// Also sets Params to the list of indices to the parameters that differ5903/// between the declaration and the definition. If hasSimilarParameters5904/// returns true and Params is empty, then all of the parameters match.5905static bool hasSimilarParameters(ASTContext &Context,5906FunctionDecl *Declaration,5907FunctionDecl *Definition,5908SmallVectorImpl<unsigned> &Params) {5909Params.clear();5910if (Declaration->param_size() != Definition->param_size())5911return false;5912for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {5913QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();5914QualType DefParamTy = Definition->getParamDecl(Idx)->getType();59155916// The parameter types are identical5917if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))5918continue;59195920QualType DeclParamBaseTy = getCoreType(DeclParamTy);5921QualType DefParamBaseTy = getCoreType(DefParamTy);5922const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();5923const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();59245925if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||5926(DeclTyName && DeclTyName == DefTyName))5927Params.push_back(Idx);5928else // The two parameters aren't even close5929return false;5930}59315932return true;5933}59345935/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given5936/// declarator needs to be rebuilt in the current instantiation.5937/// Any bits of declarator which appear before the name are valid for5938/// consideration here. That's specifically the type in the decl spec5939/// and the base type in any member-pointer chunks.5940static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,5941DeclarationName Name) {5942// The types we specifically need to rebuild are:5943// - typenames, typeofs, and decltypes5944// - types which will become injected class names5945// Of course, we also need to rebuild any type referencing such a5946// type. It's safest to just say "dependent", but we call out a5947// few cases here.59485949DeclSpec &DS = D.getMutableDeclSpec();5950switch (DS.getTypeSpecType()) {5951case DeclSpec::TST_typename:5952case DeclSpec::TST_typeofType:5953case DeclSpec::TST_typeof_unqualType:5954#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:5955#include "clang/Basic/TransformTypeTraits.def"5956case DeclSpec::TST_atomic: {5957// Grab the type from the parser.5958TypeSourceInfo *TSI = nullptr;5959QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);5960if (T.isNull() || !T->isInstantiationDependentType()) break;59615962// Make sure there's a type source info. This isn't really much5963// of a waste; most dependent types should have type source info5964// attached already.5965if (!TSI)5966TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());59675968// Rebuild the type in the current instantiation.5969TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);5970if (!TSI) return true;59715972// Store the new type back in the decl spec.5973ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);5974DS.UpdateTypeRep(LocType);5975break;5976}59775978case DeclSpec::TST_decltype:5979case DeclSpec::TST_typeof_unqualExpr:5980case DeclSpec::TST_typeofExpr: {5981Expr *E = DS.getRepAsExpr();5982ExprResult Result = S.RebuildExprInCurrentInstantiation(E);5983if (Result.isInvalid()) return true;5984DS.UpdateExprRep(Result.get());5985break;5986}59875988default:5989// Nothing to do for these decl specs.5990break;5991}59925993// It doesn't matter what order we do this in.5994for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {5995DeclaratorChunk &Chunk = D.getTypeObject(I);59965997// The only type information in the declarator which can come5998// before the declaration name is the base type of a member5999// pointer.6000if (Chunk.Kind != DeclaratorChunk::MemberPointer)6001continue;60026003// Rebuild the scope specifier in-place.6004CXXScopeSpec &SS = Chunk.Mem.Scope();6005if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))6006return true;6007}60086009return false;6010}60116012/// Returns true if the declaration is declared in a system header or from a6013/// system macro.6014static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {6015return SM.isInSystemHeader(D->getLocation()) ||6016SM.isInSystemMacro(D->getLocation());6017}60186019void Sema::warnOnReservedIdentifier(const NamedDecl *D) {6020// Avoid warning twice on the same identifier, and don't warn on redeclaration6021// of system decl.6022if (D->getPreviousDecl() || D->isImplicit())6023return;6024ReservedIdentifierStatus Status = D->isReserved(getLangOpts());6025if (Status != ReservedIdentifierStatus::NotReserved &&6026!isFromSystemHeader(Context.getSourceManager(), D)) {6027Diag(D->getLocation(), diag::warn_reserved_extern_symbol)6028<< D << static_cast<int>(Status);6029}6030}60316032Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {6033D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);60346035// Check if we are in an `omp begin/end declare variant` scope. Handle this6036// declaration only if the `bind_to_declaration` extension is set.6037SmallVector<FunctionDecl *, 4> Bases;6038if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())6039if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(6040llvm::omp::TraitProperty::6041implementation_extension_bind_to_declaration))6042OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(6043S, D, MultiTemplateParamsArg(), Bases);60446045Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());60466047if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&6048Dcl && Dcl->getDeclContext()->isFileContext())6049Dcl->setTopLevelDeclInObjCContainer();60506051if (!Bases.empty())6052OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl,6053Bases);60546055return Dcl;6056}60576058bool Sema::DiagnoseClassNameShadow(DeclContext *DC,6059DeclarationNameInfo NameInfo) {6060DeclarationName Name = NameInfo.getName();60616062CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);6063while (Record && Record->isAnonymousStructOrUnion())6064Record = dyn_cast<CXXRecordDecl>(Record->getParent());6065if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {6066Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;6067return true;6068}60696070return false;6071}60726073bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,6074DeclarationName Name,6075SourceLocation Loc,6076TemplateIdAnnotation *TemplateId,6077bool IsMemberSpecialization) {6078assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "6079"without nested-name-specifier");6080DeclContext *Cur = CurContext;6081while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))6082Cur = Cur->getParent();60836084// If the user provided a superfluous scope specifier that refers back to the6085// class in which the entity is already declared, diagnose and ignore it.6086//6087// class X {6088// void X::f();6089// };6090//6091// Note, it was once ill-formed to give redundant qualification in all6092// contexts, but that rule was removed by DR482.6093if (Cur->Equals(DC)) {6094if (Cur->isRecord()) {6095Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification6096: diag::err_member_extra_qualification)6097<< Name << FixItHint::CreateRemoval(SS.getRange());6098SS.clear();6099} else {6100Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;6101}6102return false;6103}61046105// Check whether the qualifying scope encloses the scope of the original6106// declaration. For a template-id, we perform the checks in6107// CheckTemplateSpecializationScope.6108if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {6109if (Cur->isRecord())6110Diag(Loc, diag::err_member_qualification)6111<< Name << SS.getRange();6112else if (isa<TranslationUnitDecl>(DC))6113Diag(Loc, diag::err_invalid_declarator_global_scope)6114<< Name << SS.getRange();6115else if (isa<FunctionDecl>(Cur))6116Diag(Loc, diag::err_invalid_declarator_in_function)6117<< Name << SS.getRange();6118else if (isa<BlockDecl>(Cur))6119Diag(Loc, diag::err_invalid_declarator_in_block)6120<< Name << SS.getRange();6121else if (isa<ExportDecl>(Cur)) {6122if (!isa<NamespaceDecl>(DC))6123Diag(Loc, diag::err_export_non_namespace_scope_name)6124<< Name << SS.getRange();6125else6126// The cases that DC is not NamespaceDecl should be handled in6127// CheckRedeclarationExported.6128return false;6129} else6130Diag(Loc, diag::err_invalid_declarator_scope)6131<< Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();61326133return true;6134}61356136if (Cur->isRecord()) {6137// Cannot qualify members within a class.6138Diag(Loc, diag::err_member_qualification)6139<< Name << SS.getRange();6140SS.clear();61416142// C++ constructors and destructors with incorrect scopes can break6143// our AST invariants by having the wrong underlying types. If6144// that's the case, then drop this declaration entirely.6145if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||6146Name.getNameKind() == DeclarationName::CXXDestructorName) &&6147!Context.hasSameType(Name.getCXXNameType(),6148Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))6149return true;61506151return false;6152}61536154// C++23 [temp.names]p5:6155// The keyword template shall not appear immediately after a declarative6156// nested-name-specifier.6157//6158// First check the template-id (if any), and then check each component of the6159// nested-name-specifier in reverse order.6160//6161// FIXME: nested-name-specifiers in friend declarations are declarative,6162// but we don't call diagnoseQualifiedDeclaration for them. We should.6163if (TemplateId && TemplateId->TemplateKWLoc.isValid())6164Diag(Loc, diag::ext_template_after_declarative_nns)6165<< FixItHint::CreateRemoval(TemplateId->TemplateKWLoc);61666167NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());6168do {6169if (SpecLoc.getNestedNameSpecifier()->getKind() ==6170NestedNameSpecifier::TypeSpecWithTemplate)6171Diag(Loc, diag::ext_template_after_declarative_nns)6172<< FixItHint::CreateRemoval(6173SpecLoc.getTypeLoc().getTemplateKeywordLoc());61746175if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {6176if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {6177// C++23 [expr.prim.id.qual]p3:6178// [...] If a nested-name-specifier N is declarative and has a6179// simple-template-id with a template argument list A that involves a6180// template parameter, let T be the template nominated by N without A.6181// T shall be a class template.6182if (TST->isDependentType() && TST->isTypeAlias())6183Diag(Loc, diag::ext_alias_template_in_declarative_nns)6184<< SpecLoc.getLocalSourceRange();6185} else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {6186// C++23 [expr.prim.id.qual]p2:6187// [...] A declarative nested-name-specifier shall not have a6188// computed-type-specifier.6189//6190// CWG2858 changed this from 'decltype-specifier' to6191// 'computed-type-specifier'.6192Diag(Loc, diag::err_computed_type_in_declarative_nns)6193<< T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();6194}6195}6196} while ((SpecLoc = SpecLoc.getPrefix()));61976198return false;6199}62006201NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,6202MultiTemplateParamsArg TemplateParamLists) {6203// TODO: consider using NameInfo for diagnostic.6204DeclarationNameInfo NameInfo = GetNameForDeclarator(D);6205DeclarationName Name = NameInfo.getName();62066207// All of these full declarators require an identifier. If it doesn't have6208// one, the ParsedFreeStandingDeclSpec action should be used.6209if (D.isDecompositionDeclarator()) {6210return ActOnDecompositionDeclarator(S, D, TemplateParamLists);6211} else if (!Name) {6212if (!D.isInvalidType()) // Reject this if we think it is valid.6213Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)6214<< D.getDeclSpec().getSourceRange() << D.getSourceRange();6215return nullptr;6216} else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))6217return nullptr;62186219DeclContext *DC = CurContext;6220if (D.getCXXScopeSpec().isInvalid())6221D.setInvalidType();6222else if (D.getCXXScopeSpec().isSet()) {6223if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),6224UPPC_DeclarationQualifier))6225return nullptr;62266227bool EnteringContext = !D.getDeclSpec().isFriendSpecified();6228DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);6229if (!DC || isa<EnumDecl>(DC)) {6230// If we could not compute the declaration context, it's because the6231// declaration context is dependent but does not refer to a class,6232// class template, or class template partial specialization. Complain6233// and return early, to avoid the coming semantic disaster.6234Diag(D.getIdentifierLoc(),6235diag::err_template_qualified_declarator_no_match)6236<< D.getCXXScopeSpec().getScopeRep()6237<< D.getCXXScopeSpec().getRange();6238return nullptr;6239}6240bool IsDependentContext = DC->isDependentContext();62416242if (!IsDependentContext &&6243RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))6244return nullptr;62456246// If a class is incomplete, do not parse entities inside it.6247if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {6248Diag(D.getIdentifierLoc(),6249diag::err_member_def_undefined_record)6250<< Name << DC << D.getCXXScopeSpec().getRange();6251return nullptr;6252}6253if (!D.getDeclSpec().isFriendSpecified()) {6254TemplateIdAnnotation *TemplateId =6255D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId6256? D.getName().TemplateId6257: nullptr;6258if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, Name,6259D.getIdentifierLoc(), TemplateId,6260/*IsMemberSpecialization=*/false)) {6261if (DC->isRecord())6262return nullptr;62636264D.setInvalidType();6265}6266}62676268// Check whether we need to rebuild the type of the given6269// declaration in the current instantiation.6270if (EnteringContext && IsDependentContext &&6271TemplateParamLists.size() != 0) {6272ContextRAII SavedContext(*this, DC);6273if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))6274D.setInvalidType();6275}6276}62776278TypeSourceInfo *TInfo = GetTypeForDeclarator(D);6279QualType R = TInfo->getType();62806281if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,6282UPPC_DeclarationType))6283D.setInvalidType();62846285LookupResult Previous(*this, NameInfo, LookupOrdinaryName,6286forRedeclarationInCurContext());62876288// See if this is a redefinition of a variable in the same scope.6289if (!D.getCXXScopeSpec().isSet()) {6290bool IsLinkageLookup = false;6291bool CreateBuiltins = false;62926293// If the declaration we're planning to build will be a function6294// or object with linkage, then look for another declaration with6295// linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).6296//6297// If the declaration we're planning to build will be declared with6298// external linkage in the translation unit, create any builtin with6299// the same name.6300if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)6301/* Do nothing*/;6302else if (CurContext->isFunctionOrMethod() &&6303(D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||6304R->isFunctionType())) {6305IsLinkageLookup = true;6306CreateBuiltins =6307CurContext->getEnclosingNamespaceContext()->isTranslationUnit();6308} else if (CurContext->getRedeclContext()->isTranslationUnit() &&6309D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)6310CreateBuiltins = true;63116312if (IsLinkageLookup) {6313Previous.clear(LookupRedeclarationWithLinkage);6314Previous.setRedeclarationKind(6315RedeclarationKind::ForExternalRedeclaration);6316}63176318LookupName(Previous, S, CreateBuiltins);6319} else { // Something like "int foo::x;"6320LookupQualifiedName(Previous, DC);63216322// C++ [dcl.meaning]p1:6323// When the declarator-id is qualified, the declaration shall refer to a6324// previously declared member of the class or namespace to which the6325// qualifier refers (or, in the case of a namespace, of an element of the6326// inline namespace set of that namespace (7.3.1)) or to a specialization6327// thereof; [...]6328//6329// Note that we already checked the context above, and that we do not have6330// enough information to make sure that Previous contains the declaration6331// we want to match. For example, given:6332//6333// class X {6334// void f();6335// void f(float);6336// };6337//6338// void X::f(int) { } // ill-formed6339//6340// In this case, Previous will point to the overload set6341// containing the two f's declared in X, but neither of them6342// matches.63436344RemoveUsingDecls(Previous);6345}63466347if (auto *TPD = Previous.getAsSingle<NamedDecl>();6348TPD && TPD->isTemplateParameter()) {6349// Older versions of clang allowed the names of function/variable templates6350// to shadow the names of their template parameters. For the compatibility6351// purposes we detect such cases and issue a default-to-error warning that6352// can be disabled with -Wno-strict-primary-template-shadow.6353if (!D.isInvalidType()) {6354bool AllowForCompatibility = false;6355if (Scope *DeclParent = S->getDeclParent();6356Scope *TemplateParamParent = S->getTemplateParamParent()) {6357AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&6358TemplateParamParent->isDeclScope(TPD);6359}6360DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,6361AllowForCompatibility);6362}63636364// Just pretend that we didn't see the previous declaration.6365Previous.clear();6366}63676368if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))6369// Forget that the previous declaration is the injected-class-name.6370Previous.clear();63716372// In C++, the previous declaration we find might be a tag type6373// (class or enum). In this case, the new declaration will hide the6374// tag type. Note that this applies to functions, function templates, and6375// variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.6376if (Previous.isSingleTagDecl() &&6377D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&6378(TemplateParamLists.size() == 0 || R->isFunctionType()))6379Previous.clear();63806381// Check that there are no default arguments other than in the parameters6382// of a function declaration (C++ only).6383if (getLangOpts().CPlusPlus)6384CheckExtraCXXDefaultArguments(D);63856386/// Get the innermost enclosing declaration scope.6387S = S->getDeclParent();63886389NamedDecl *New;63906391bool AddToScope = true;6392if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {6393if (TemplateParamLists.size()) {6394Diag(D.getIdentifierLoc(), diag::err_template_typedef);6395return nullptr;6396}63976398New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);6399} else if (R->isFunctionType()) {6400New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,6401TemplateParamLists,6402AddToScope);6403} else {6404New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,6405AddToScope);6406}64076408if (!New)6409return nullptr;64106411// If this has an identifier and is not a function template specialization,6412// add it to the scope stack.6413if (New->getDeclName() && AddToScope)6414PushOnScopeChains(New, S);64156416if (OpenMP().isInOpenMPDeclareTargetContext())6417OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);64186419return New;6420}64216422/// Helper method to turn variable array types into constant array6423/// types in certain situations which would otherwise be errors (for6424/// GCC compatibility).6425static QualType TryToFixInvalidVariablyModifiedType(QualType T,6426ASTContext &Context,6427bool &SizeIsNegative,6428llvm::APSInt &Oversized) {6429// This method tries to turn a variable array into a constant6430// array even when the size isn't an ICE. This is necessary6431// for compatibility with code that depends on gcc's buggy6432// constant expression folding, like struct {char x[(int)(char*)2];}6433SizeIsNegative = false;6434Oversized = 0;64356436if (T->isDependentType())6437return QualType();64386439QualifierCollector Qs;6440const Type *Ty = Qs.strip(T);64416442if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {6443QualType Pointee = PTy->getPointeeType();6444QualType FixedType =6445TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,6446Oversized);6447if (FixedType.isNull()) return FixedType;6448FixedType = Context.getPointerType(FixedType);6449return Qs.apply(Context, FixedType);6450}6451if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {6452QualType Inner = PTy->getInnerType();6453QualType FixedType =6454TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,6455Oversized);6456if (FixedType.isNull()) return FixedType;6457FixedType = Context.getParenType(FixedType);6458return Qs.apply(Context, FixedType);6459}64606461const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);6462if (!VLATy)6463return QualType();64646465QualType ElemTy = VLATy->getElementType();6466if (ElemTy->isVariablyModifiedType()) {6467ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,6468SizeIsNegative, Oversized);6469if (ElemTy.isNull())6470return QualType();6471}64726473Expr::EvalResult Result;6474if (!VLATy->getSizeExpr() ||6475!VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))6476return QualType();64776478llvm::APSInt Res = Result.Val.getInt();64796480// Check whether the array size is negative.6481if (Res.isSigned() && Res.isNegative()) {6482SizeIsNegative = true;6483return QualType();6484}64856486// Check whether the array is too large to be addressed.6487unsigned ActiveSizeBits =6488(!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&6489!ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())6490? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)6491: Res.getActiveBits();6492if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {6493Oversized = Res;6494return QualType();6495}64966497QualType FoldedArrayType = Context.getConstantArrayType(6498ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);6499return Qs.apply(Context, FoldedArrayType);6500}65016502static void6503FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {6504SrcTL = SrcTL.getUnqualifiedLoc();6505DstTL = DstTL.getUnqualifiedLoc();6506if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {6507PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();6508FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),6509DstPTL.getPointeeLoc());6510DstPTL.setStarLoc(SrcPTL.getStarLoc());6511return;6512}6513if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {6514ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();6515FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),6516DstPTL.getInnerLoc());6517DstPTL.setLParenLoc(SrcPTL.getLParenLoc());6518DstPTL.setRParenLoc(SrcPTL.getRParenLoc());6519return;6520}6521ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();6522ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();6523TypeLoc SrcElemTL = SrcATL.getElementLoc();6524TypeLoc DstElemTL = DstATL.getElementLoc();6525if (VariableArrayTypeLoc SrcElemATL =6526SrcElemTL.getAs<VariableArrayTypeLoc>()) {6527ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();6528FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);6529} else {6530DstElemTL.initializeFullCopy(SrcElemTL);6531}6532DstATL.setLBracketLoc(SrcATL.getLBracketLoc());6533DstATL.setSizeExpr(SrcATL.getSizeExpr());6534DstATL.setRBracketLoc(SrcATL.getRBracketLoc());6535}65366537/// Helper method to turn variable array types into constant array6538/// types in certain situations which would otherwise be errors (for6539/// GCC compatibility).6540static TypeSourceInfo*6541TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,6542ASTContext &Context,6543bool &SizeIsNegative,6544llvm::APSInt &Oversized) {6545QualType FixedTy6546= TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,6547SizeIsNegative, Oversized);6548if (FixedTy.isNull())6549return nullptr;6550TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);6551FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),6552FixedTInfo->getTypeLoc());6553return FixedTInfo;6554}65556556bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,6557QualType &T, SourceLocation Loc,6558unsigned FailedFoldDiagID) {6559bool SizeIsNegative;6560llvm::APSInt Oversized;6561TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(6562TInfo, Context, SizeIsNegative, Oversized);6563if (FixedTInfo) {6564Diag(Loc, diag::ext_vla_folded_to_constant);6565TInfo = FixedTInfo;6566T = FixedTInfo->getType();6567return true;6568}65696570if (SizeIsNegative)6571Diag(Loc, diag::err_typecheck_negative_array_size);6572else if (Oversized.getBoolValue())6573Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);6574else if (FailedFoldDiagID)6575Diag(Loc, FailedFoldDiagID);6576return false;6577}65786579void6580Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {6581if (!getLangOpts().CPlusPlus &&6582ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())6583// Don't need to track declarations in the TU in C.6584return;65856586// Note that we have a locally-scoped external with this name.6587Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);6588}65896590NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {6591// FIXME: We can have multiple results via __attribute__((overloadable)).6592auto Result = Context.getExternCContextDecl()->lookup(Name);6593return Result.empty() ? nullptr : *Result.begin();6594}65956596void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {6597// FIXME: We should probably indicate the identifier in question to avoid6598// confusion for constructs like "virtual int a(), b;"6599if (DS.isVirtualSpecified())6600Diag(DS.getVirtualSpecLoc(),6601diag::err_virtual_non_function);66026603if (DS.hasExplicitSpecifier())6604Diag(DS.getExplicitSpecLoc(),6605diag::err_explicit_non_function);66066607if (DS.isNoreturnSpecified())6608Diag(DS.getNoreturnSpecLoc(),6609diag::err_noreturn_non_function);6610}66116612NamedDecl*6613Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,6614TypeSourceInfo *TInfo, LookupResult &Previous) {6615// Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).6616if (D.getCXXScopeSpec().isSet()) {6617Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)6618<< D.getCXXScopeSpec().getRange();6619D.setInvalidType();6620// Pretend we didn't see the scope specifier.6621DC = CurContext;6622Previous.clear();6623}66246625DiagnoseFunctionSpecifiers(D.getDeclSpec());66266627if (D.getDeclSpec().isInlineSpecified())6628Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)6629<< getLangOpts().CPlusPlus17;6630if (D.getDeclSpec().hasConstexprSpecifier())6631Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)6632<< 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());66336634if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {6635if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)6636Diag(D.getName().StartLocation,6637diag::err_deduction_guide_invalid_specifier)6638<< "typedef";6639else6640Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)6641<< D.getName().getSourceRange();6642return nullptr;6643}66446645TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);6646if (!NewTD) return nullptr;66476648// Handle attributes prior to checking for duplicates in MergeVarDecl6649ProcessDeclAttributes(S, NewTD, D);66506651CheckTypedefForVariablyModifiedType(S, NewTD);66526653bool Redeclaration = D.isRedeclaration();6654NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);6655D.setRedeclaration(Redeclaration);6656return ND;6657}66586659void6660Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {6661// C99 6.7.7p2: If a typedef name specifies a variably modified type6662// then it shall have block scope.6663// Note that variably modified types must be fixed before merging the decl so6664// that redeclarations will match.6665TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();6666QualType T = TInfo->getType();6667if (T->isVariablyModifiedType()) {6668setFunctionHasBranchProtectedScope();66696670if (S->getFnParent() == nullptr) {6671bool SizeIsNegative;6672llvm::APSInt Oversized;6673TypeSourceInfo *FixedTInfo =6674TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,6675SizeIsNegative,6676Oversized);6677if (FixedTInfo) {6678Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);6679NewTD->setTypeSourceInfo(FixedTInfo);6680} else {6681if (SizeIsNegative)6682Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);6683else if (T->isVariableArrayType())6684Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);6685else if (Oversized.getBoolValue())6686Diag(NewTD->getLocation(), diag::err_array_too_large)6687<< toString(Oversized, 10);6688else6689Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);6690NewTD->setInvalidDecl();6691}6692}6693}6694}66956696NamedDecl*6697Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,6698LookupResult &Previous, bool &Redeclaration) {66996700// Find the shadowed declaration before filtering for scope.6701NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);67026703// Merge the decl with the existing one if appropriate. If the decl is6704// in an outer scope, it isn't the same thing.6705FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,6706/*AllowInlineNamespace*/false);6707filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);6708if (!Previous.empty()) {6709Redeclaration = true;6710MergeTypedefNameDecl(S, NewTD, Previous);6711} else {6712inferGslPointerAttribute(NewTD);6713}67146715if (ShadowedDecl && !Redeclaration)6716CheckShadow(NewTD, ShadowedDecl, Previous);67176718// If this is the C FILE type, notify the AST context.6719if (IdentifierInfo *II = NewTD->getIdentifier())6720if (!NewTD->isInvalidDecl() &&6721NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {6722switch (II->getNotableIdentifierID()) {6723case tok::NotableIdentifierKind::FILE:6724Context.setFILEDecl(NewTD);6725break;6726case tok::NotableIdentifierKind::jmp_buf:6727Context.setjmp_bufDecl(NewTD);6728break;6729case tok::NotableIdentifierKind::sigjmp_buf:6730Context.setsigjmp_bufDecl(NewTD);6731break;6732case tok::NotableIdentifierKind::ucontext_t:6733Context.setucontext_tDecl(NewTD);6734break;6735case tok::NotableIdentifierKind::float_t:6736case tok::NotableIdentifierKind::double_t:6737NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));6738break;6739default:6740break;6741}6742}67436744return NewTD;6745}67466747/// Determines whether the given declaration is an out-of-scope6748/// previous declaration.6749///6750/// This routine should be invoked when name lookup has found a6751/// previous declaration (PrevDecl) that is not in the scope where a6752/// new declaration by the same name is being introduced. If the new6753/// declaration occurs in a local scope, previous declarations with6754/// linkage may still be considered previous declarations (C996755/// 6.2.2p4-5, C++ [basic.link]p6).6756///6757/// \param PrevDecl the previous declaration found by name6758/// lookup6759///6760/// \param DC the context in which the new declaration is being6761/// declared.6762///6763/// \returns true if PrevDecl is an out-of-scope previous declaration6764/// for a new delcaration with the same name.6765static bool6766isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,6767ASTContext &Context) {6768if (!PrevDecl)6769return false;67706771if (!PrevDecl->hasLinkage())6772return false;67736774if (Context.getLangOpts().CPlusPlus) {6775// C++ [basic.link]p6:6776// If there is a visible declaration of an entity with linkage6777// having the same name and type, ignoring entities declared6778// outside the innermost enclosing namespace scope, the block6779// scope declaration declares that same entity and receives the6780// linkage of the previous declaration.6781DeclContext *OuterContext = DC->getRedeclContext();6782if (!OuterContext->isFunctionOrMethod())6783// This rule only applies to block-scope declarations.6784return false;67856786DeclContext *PrevOuterContext = PrevDecl->getDeclContext();6787if (PrevOuterContext->isRecord())6788// We found a member function: ignore it.6789return false;67906791// Find the innermost enclosing namespace for the new and6792// previous declarations.6793OuterContext = OuterContext->getEnclosingNamespaceContext();6794PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();67956796// The previous declaration is in a different namespace, so it6797// isn't the same function.6798if (!OuterContext->Equals(PrevOuterContext))6799return false;6800}68016802return true;6803}68046805static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {6806CXXScopeSpec &SS = D.getCXXScopeSpec();6807if (!SS.isSet()) return;6808DD->setQualifierInfo(SS.getWithLocInContext(S.Context));6809}68106811void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {6812if (Decl->getType().hasAddressSpace())6813return;6814if (Decl->getType()->isDependentType())6815return;6816if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {6817QualType Type = Var->getType();6818if (Type->isSamplerT() || Type->isVoidType())6819return;6820LangAS ImplAS = LangAS::opencl_private;6821// OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the6822// __opencl_c_program_scope_global_variables feature, the address space6823// for a variable at program scope or a static or extern variable inside6824// a function are inferred to be __global.6825if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&6826Var->hasGlobalStorage())6827ImplAS = LangAS::opencl_global;6828// If the original type from a decayed type is an array type and that array6829// type has no address space yet, deduce it now.6830if (auto DT = dyn_cast<DecayedType>(Type)) {6831auto OrigTy = DT->getOriginalType();6832if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {6833// Add the address space to the original array type and then propagate6834// that to the element type through `getAsArrayType`.6835OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);6836OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);6837// Re-generate the decayed type.6838Type = Context.getDecayedType(OrigTy);6839}6840}6841Type = Context.getAddrSpaceQualType(Type, ImplAS);6842// Apply any qualifiers (including address space) from the array type to6843// the element type. This implements C99 6.7.3p8: "If the specification of6844// an array type includes any type qualifiers, the element type is so6845// qualified, not the array type."6846if (Type->isArrayType())6847Type = QualType(Context.getAsArrayType(Type), 0);6848Decl->setType(Type);6849}6850}68516852static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {6853// Ensure that an auto decl is deduced otherwise the checks below might cache6854// the wrong linkage.6855assert(S.ParsingInitForAutoVars.count(&ND) == 0);68566857// 'weak' only applies to declarations with external linkage.6858if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {6859if (!ND.isExternallyVisible()) {6860S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);6861ND.dropAttr<WeakAttr>();6862}6863}6864if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {6865if (ND.isExternallyVisible()) {6866S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);6867ND.dropAttrs<WeakRefAttr, AliasAttr>();6868}6869}68706871if (auto *VD = dyn_cast<VarDecl>(&ND)) {6872if (VD->hasInit()) {6873if (const auto *Attr = VD->getAttr<AliasAttr>()) {6874assert(VD->isThisDeclarationADefinition() &&6875!VD->isExternallyVisible() && "Broken AliasAttr handled late!");6876S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;6877VD->dropAttr<AliasAttr>();6878}6879}6880}68816882// 'selectany' only applies to externally visible variable declarations.6883// It does not apply to functions.6884if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {6885if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {6886S.Diag(Attr->getLocation(),6887diag::err_attribute_selectany_non_extern_data);6888ND.dropAttr<SelectAnyAttr>();6889}6890}68916892if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {6893if (!ND.isExternallyVisible())6894S.Diag(Attr->getLocation(),6895diag::warn_attribute_hybrid_patchable_non_extern);6896}6897if (const InheritableAttr *Attr = getDLLAttr(&ND)) {6898auto *VD = dyn_cast<VarDecl>(&ND);6899bool IsAnonymousNS = false;6900bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();6901if (VD) {6902const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());6903while (NS && !IsAnonymousNS) {6904IsAnonymousNS = NS->isAnonymousNamespace();6905NS = dyn_cast<NamespaceDecl>(NS->getParent());6906}6907}6908// dll attributes require external linkage. Static locals may have external6909// linkage but still cannot be explicitly imported or exported.6910// In Microsoft mode, a variable defined in anonymous namespace must have6911// external linkage in order to be exported.6912bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;6913if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||6914(!AnonNSInMicrosoftMode &&6915(!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {6916S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)6917<< &ND << Attr;6918ND.setInvalidDecl();6919}6920}69216922// Check the attributes on the function type, if any.6923if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {6924// Don't declare this variable in the second operand of the for-statement;6925// GCC miscompiles that by ending its lifetime before evaluating the6926// third operand. See gcc.gnu.org/PR86769.6927AttributedTypeLoc ATL;6928for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();6929(ATL = TL.getAsAdjusted<AttributedTypeLoc>());6930TL = ATL.getModifiedLoc()) {6931// The [[lifetimebound]] attribute can be applied to the implicit object6932// parameter of a non-static member function (other than a ctor or dtor)6933// by applying it to the function type.6934if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {6935const auto *MD = dyn_cast<CXXMethodDecl>(FD);6936if (!MD || MD->isStatic()) {6937S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)6938<< !MD << A->getRange();6939} else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {6940S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)6941<< isa<CXXDestructorDecl>(MD) << A->getRange();6942}6943}6944}6945}6946}69476948static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,6949NamedDecl *NewDecl,6950bool IsSpecialization,6951bool IsDefinition) {6952if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())6953return;69546955bool IsTemplate = false;6956if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {6957OldDecl = OldTD->getTemplatedDecl();6958IsTemplate = true;6959if (!IsSpecialization)6960IsDefinition = false;6961}6962if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {6963NewDecl = NewTD->getTemplatedDecl();6964IsTemplate = true;6965}69666967if (!OldDecl || !NewDecl)6968return;69696970const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();6971const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();6972const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();6973const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();69746975// dllimport and dllexport are inheritable attributes so we have to exclude6976// inherited attribute instances.6977bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||6978(NewExportAttr && !NewExportAttr->isInherited());69796980// A redeclaration is not allowed to add a dllimport or dllexport attribute,6981// the only exception being explicit specializations.6982// Implicitly generated declarations are also excluded for now because there6983// is no other way to switch these to use dllimport or dllexport.6984bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;69856986if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {6987// Allow with a warning for free functions and global variables.6988bool JustWarn = false;6989if (!OldDecl->isCXXClassMember()) {6990auto *VD = dyn_cast<VarDecl>(OldDecl);6991if (VD && !VD->getDescribedVarTemplate())6992JustWarn = true;6993auto *FD = dyn_cast<FunctionDecl>(OldDecl);6994if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)6995JustWarn = true;6996}69976998// We cannot change a declaration that's been used because IR has already6999// been emitted. Dllimported functions will still work though (modulo7000// address equality) as they can use the thunk.7001if (OldDecl->isUsed())7002if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)7003JustWarn = false;70047005unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration7006: diag::err_attribute_dll_redeclaration;7007S.Diag(NewDecl->getLocation(), DiagID)7008<< NewDecl7009<< (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);7010S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);7011if (!JustWarn) {7012NewDecl->setInvalidDecl();7013return;7014}7015}70167017// A redeclaration is not allowed to drop a dllimport attribute, the only7018// exceptions being inline function definitions (except for function7019// templates), local extern declarations, qualified friend declarations or7020// special MSVC extension: in the last case, the declaration is treated as if7021// it were marked dllexport.7022bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;7023bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();7024if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {7025// Ignore static data because out-of-line definitions are diagnosed7026// separately.7027IsStaticDataMember = VD->isStaticDataMember();7028IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=7029VarDecl::DeclarationOnly;7030} else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {7031IsInline = FD->isInlined();7032IsQualifiedFriend = FD->getQualifier() &&7033FD->getFriendObjectKind() == Decl::FOK_Declared;7034}70357036if (OldImportAttr && !HasNewAttr &&7037(!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&7038!NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {7039if (IsMicrosoftABI && IsDefinition) {7040if (IsSpecialization) {7041S.Diag(7042NewDecl->getLocation(),7043diag::err_attribute_dllimport_function_specialization_definition);7044S.Diag(OldImportAttr->getLocation(), diag::note_attribute);7045NewDecl->dropAttr<DLLImportAttr>();7046} else {7047S.Diag(NewDecl->getLocation(),7048diag::warn_redeclaration_without_import_attribute)7049<< NewDecl;7050S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);7051NewDecl->dropAttr<DLLImportAttr>();7052NewDecl->addAttr(DLLExportAttr::CreateImplicit(7053S.Context, NewImportAttr->getRange()));7054}7055} else if (IsMicrosoftABI && IsSpecialization) {7056assert(!IsDefinition);7057// MSVC allows this. Keep the inherited attribute.7058} else {7059S.Diag(NewDecl->getLocation(),7060diag::warn_redeclaration_without_attribute_prev_attribute_ignored)7061<< NewDecl << OldImportAttr;7062S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);7063S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);7064OldDecl->dropAttr<DLLImportAttr>();7065NewDecl->dropAttr<DLLImportAttr>();7066}7067} else if (IsInline && OldImportAttr && !IsMicrosoftABI) {7068// In MinGW, seeing a function declared inline drops the dllimport7069// attribute.7070OldDecl->dropAttr<DLLImportAttr>();7071NewDecl->dropAttr<DLLImportAttr>();7072S.Diag(NewDecl->getLocation(),7073diag::warn_dllimport_dropped_from_inline_function)7074<< NewDecl << OldImportAttr;7075}70767077// A specialization of a class template member function is processed here7078// since it's a redeclaration. If the parent class is dllexport, the7079// specialization inherits that attribute. This doesn't happen automatically7080// since the parent class isn't instantiated until later.7081if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {7082if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&7083!NewImportAttr && !NewExportAttr) {7084if (const DLLExportAttr *ParentExportAttr =7085MD->getParent()->getAttr<DLLExportAttr>()) {7086DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);7087NewAttr->setInherited(true);7088NewDecl->addAttr(NewAttr);7089}7090}7091}7092}70937094/// Given that we are within the definition of the given function,7095/// will that definition behave like C99's 'inline', where the7096/// definition is discarded except for optimization purposes?7097static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {7098// Try to avoid calling GetGVALinkageForFunction.70997100// All cases of this require the 'inline' keyword.7101if (!FD->isInlined()) return false;71027103// This is only possible in C++ with the gnu_inline attribute.7104if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())7105return false;71067107// Okay, go ahead and call the relatively-more-expensive function.7108return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;7109}71107111/// Determine whether a variable is extern "C" prior to attaching7112/// an initializer. We can't just call isExternC() here, because that7113/// will also compute and cache whether the declaration is externally7114/// visible, which might change when we attach the initializer.7115///7116/// This can only be used if the declaration is known to not be a7117/// redeclaration of an internal linkage declaration.7118///7119/// For instance:7120///7121/// auto x = []{};7122///7123/// Attaching the initializer here makes this declaration not externally7124/// visible, because its type has internal linkage.7125///7126/// FIXME: This is a hack.7127template<typename T>7128static bool isIncompleteDeclExternC(Sema &S, const T *D) {7129if (S.getLangOpts().CPlusPlus) {7130// In C++, the overloadable attribute negates the effects of extern "C".7131if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())7132return false;71337134// So do CUDA's host/device attributes.7135if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||7136D->template hasAttr<CUDAHostAttr>()))7137return false;7138}7139return D->isExternC();7140}71417142static bool shouldConsiderLinkage(const VarDecl *VD) {7143const DeclContext *DC = VD->getDeclContext()->getRedeclContext();7144if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||7145isa<OMPDeclareMapperDecl>(DC))7146return VD->hasExternalStorage();7147if (DC->isFileContext())7148return true;7149if (DC->isRecord())7150return false;7151if (DC->getDeclKind() == Decl::HLSLBuffer)7152return false;71537154if (isa<RequiresExprBodyDecl>(DC))7155return false;7156llvm_unreachable("Unexpected context");7157}71587159static bool shouldConsiderLinkage(const FunctionDecl *FD) {7160const DeclContext *DC = FD->getDeclContext()->getRedeclContext();7161if (DC->isFileContext() || DC->isFunctionOrMethod() ||7162isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))7163return true;7164if (DC->isRecord())7165return false;7166llvm_unreachable("Unexpected context");7167}71687169static bool hasParsedAttr(Scope *S, const Declarator &PD,7170ParsedAttr::Kind Kind) {7171// Check decl attributes on the DeclSpec.7172if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))7173return true;71747175// Walk the declarator structure, checking decl attributes that were in a type7176// position to the decl itself.7177for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {7178if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))7179return true;7180}71817182// Finally, check attributes on the decl itself.7183return PD.getAttributes().hasAttribute(Kind) ||7184PD.getDeclarationAttributes().hasAttribute(Kind);7185}71867187bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {7188if (!DC->isFunctionOrMethod())7189return false;71907191// If this is a local extern function or variable declared within a function7192// template, don't add it into the enclosing namespace scope until it is7193// instantiated; it might have a dependent type right now.7194if (DC->isDependentContext())7195return true;71967197// C++11 [basic.link]p7:7198// When a block scope declaration of an entity with linkage is not found to7199// refer to some other declaration, then that entity is a member of the7200// innermost enclosing namespace.7201//7202// Per C++11 [namespace.def]p6, the innermost enclosing namespace is a7203// semantically-enclosing namespace, not a lexically-enclosing one.7204while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))7205DC = DC->getParent();7206return true;7207}72087209/// Returns true if given declaration has external C language linkage.7210static bool isDeclExternC(const Decl *D) {7211if (const auto *FD = dyn_cast<FunctionDecl>(D))7212return FD->isExternC();7213if (const auto *VD = dyn_cast<VarDecl>(D))7214return VD->isExternC();72157216llvm_unreachable("Unknown type of decl!");7217}72187219/// Returns true if there hasn't been any invalid type diagnosed.7220static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {7221DeclContext *DC = NewVD->getDeclContext();7222QualType R = NewVD->getType();72237224// OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.7225// OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function7226// argument.7227if (R->isImageType() || R->isPipeType()) {7228Se.Diag(NewVD->getLocation(),7229diag::err_opencl_type_can_only_be_used_as_function_parameter)7230<< R;7231NewVD->setInvalidDecl();7232return false;7233}72347235// OpenCL v1.2 s6.9.r:7236// The event type cannot be used to declare a program scope variable.7237// OpenCL v2.0 s6.9.q:7238// The clk_event_t and reserve_id_t types cannot be declared in program7239// scope.7240if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {7241if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {7242Se.Diag(NewVD->getLocation(),7243diag::err_invalid_type_for_program_scope_var)7244<< R;7245NewVD->setInvalidDecl();7246return false;7247}7248}72497250// OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.7251if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",7252Se.getLangOpts())) {7253QualType NR = R.getCanonicalType();7254while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||7255NR->isReferenceType()) {7256if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||7257NR->isFunctionReferenceType()) {7258Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)7259<< NR->isReferenceType();7260NewVD->setInvalidDecl();7261return false;7262}7263NR = NR->getPointeeType();7264}7265}72667267if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",7268Se.getLangOpts())) {7269// OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and7270// half array type (unless the cl_khr_fp16 extension is enabled).7271if (Se.Context.getBaseElementType(R)->isHalfType()) {7272Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;7273NewVD->setInvalidDecl();7274return false;7275}7276}72777278// OpenCL v1.2 s6.9.r:7279// The event type cannot be used with the __local, __constant and __global7280// address space qualifiers.7281if (R->isEventT()) {7282if (R.getAddressSpace() != LangAS::opencl_private) {7283Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);7284NewVD->setInvalidDecl();7285return false;7286}7287}72887289if (R->isSamplerT()) {7290// OpenCL v1.2 s6.9.b p4:7291// The sampler type cannot be used with the __local and __global address7292// space qualifiers.7293if (R.getAddressSpace() == LangAS::opencl_local ||7294R.getAddressSpace() == LangAS::opencl_global) {7295Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);7296NewVD->setInvalidDecl();7297}72987299// OpenCL v1.2 s6.12.14.1:7300// A global sampler must be declared with either the constant address7301// space qualifier or with the const qualifier.7302if (DC->isTranslationUnit() &&7303!(R.getAddressSpace() == LangAS::opencl_constant ||7304R.isConstQualified())) {7305Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);7306NewVD->setInvalidDecl();7307}7308if (NewVD->isInvalidDecl())7309return false;7310}73117312return true;7313}73147315template <typename AttrTy>7316static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {7317const TypedefNameDecl *TND = TT->getDecl();7318if (const auto *Attribute = TND->getAttr<AttrTy>()) {7319AttrTy *Clone = Attribute->clone(S.Context);7320Clone->setInherited(true);7321D->addAttr(Clone);7322}7323}73247325// This function emits warning and a corresponding note based on the7326// ReadOnlyPlacementAttr attribute. The warning checks that all global variable7327// declarations of an annotated type must be const qualified.7328void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {7329QualType VarType = VD->getType().getCanonicalType();73307331// Ignore local declarations (for now) and those with const qualification.7332// TODO: Local variables should not be allowed if their type declaration has7333// ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.7334if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())7335return;73367337if (VarType->isArrayType()) {7338// Retrieve element type for array declarations.7339VarType = S.getASTContext().getBaseElementType(VarType);7340}73417342const RecordDecl *RD = VarType->getAsRecordDecl();73437344// Check if the record declaration is present and if it has any attributes.7345if (RD == nullptr)7346return;73477348if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {7349S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;7350S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);7351return;7352}7353}73547355NamedDecl *Sema::ActOnVariableDeclarator(7356Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,7357LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,7358bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {7359QualType R = TInfo->getType();7360DeclarationName Name = GetNameForDeclarator(D).getName();73617362IdentifierInfo *II = Name.getAsIdentifierInfo();7363bool IsPlaceholderVariable = false;73647365if (D.isDecompositionDeclarator()) {7366// Take the name of the first declarator as our name for diagnostic7367// purposes.7368auto &Decomp = D.getDecompositionDeclarator();7369if (!Decomp.bindings().empty()) {7370II = Decomp.bindings()[0].Name;7371Name = II;7372}7373} else if (!II) {7374Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;7375return nullptr;7376}737773787379DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();7380StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());73817382if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&7383SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {7384IsPlaceholderVariable = true;7385if (!Previous.empty()) {7386NamedDecl *PrevDecl = *Previous.begin();7387bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(7388DC->getRedeclContext());7389if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))7390DiagPlaceholderVariableDefinition(D.getIdentifierLoc());7391}7392}73937394// dllimport globals without explicit storage class are treated as extern. We7395// have to change the storage class this early to get the right DeclContext.7396if (SC == SC_None && !DC->isRecord() &&7397hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&7398!hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))7399SC = SC_Extern;74007401DeclContext *OriginalDC = DC;7402bool IsLocalExternDecl = SC == SC_Extern &&7403adjustContextForLocalExternDecl(DC);74047405if (SCSpec == DeclSpec::SCS_mutable) {7406// mutable can only appear on non-static class members, so it's always7407// an error here7408Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);7409D.setInvalidType();7410SC = SC_None;7411}74127413if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&7414!D.getAsmLabel() && !getSourceManager().isInSystemMacro(7415D.getDeclSpec().getStorageClassSpecLoc())) {7416// In C++11, the 'register' storage class specifier is deprecated.7417// Suppress the warning in system macros, it's used in macros in some7418// popular C system headers, such as in glibc's htonl() macro.7419Diag(D.getDeclSpec().getStorageClassSpecLoc(),7420getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class7421: diag::warn_deprecated_register)7422<< FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());7423}74247425DiagnoseFunctionSpecifiers(D.getDeclSpec());74267427if (!DC->isRecord() && S->getFnParent() == nullptr) {7428// C99 6.9p2: The storage-class specifiers auto and register shall not7429// appear in the declaration specifiers in an external declaration.7430// Global Register+Asm is a GNU extension we support.7431if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {7432Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);7433D.setInvalidType();7434}7435}74367437// If this variable has a VLA type and an initializer, try to7438// fold to a constant-sized type. This is otherwise invalid.7439if (D.hasInitializer() && R->isVariableArrayType())7440tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),7441/*DiagID=*/0);74427443if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {7444const AutoType *AT = TL.getTypePtr();7445CheckConstrainedAuto(AT, TL.getConceptNameLoc());7446}74477448bool IsMemberSpecialization = false;7449bool IsVariableTemplateSpecialization = false;7450bool IsPartialSpecialization = false;7451bool IsVariableTemplate = false;7452VarDecl *NewVD = nullptr;7453VarTemplateDecl *NewTemplate = nullptr;7454TemplateParameterList *TemplateParams = nullptr;7455if (!getLangOpts().CPlusPlus) {7456NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),7457II, R, TInfo, SC);74587459if (R->getContainedDeducedType())7460ParsingInitForAutoVars.insert(NewVD);74617462if (D.isInvalidType())7463NewVD->setInvalidDecl();74647465if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&7466NewVD->hasLocalStorage())7467checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),7468NTCUC_AutoVar, NTCUK_Destruct);7469} else {7470bool Invalid = false;7471// Match up the template parameter lists with the scope specifier, then7472// determine whether we have a template or a template specialization.7473TemplateParams = MatchTemplateParametersToScopeSpecifier(7474D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),7475D.getCXXScopeSpec(),7476D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId7477? D.getName().TemplateId7478: nullptr,7479TemplateParamLists,7480/*never a friend*/ false, IsMemberSpecialization, Invalid);74817482if (TemplateParams) {7483if (!TemplateParams->size() &&7484D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {7485// There is an extraneous 'template<>' for this variable. Complain7486// about it, but allow the declaration of the variable.7487Diag(TemplateParams->getTemplateLoc(),7488diag::err_template_variable_noparams)7489<< II7490<< SourceRange(TemplateParams->getTemplateLoc(),7491TemplateParams->getRAngleLoc());7492TemplateParams = nullptr;7493} else {7494// Check that we can declare a template here.7495if (CheckTemplateDeclScope(S, TemplateParams))7496return nullptr;74977498if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {7499// This is an explicit specialization or a partial specialization.7500IsVariableTemplateSpecialization = true;7501IsPartialSpecialization = TemplateParams->size() > 0;7502} else { // if (TemplateParams->size() > 0)7503// This is a template declaration.7504IsVariableTemplate = true;75057506// Only C++1y supports variable templates (N3651).7507Diag(D.getIdentifierLoc(),7508getLangOpts().CPlusPlus147509? diag::warn_cxx11_compat_variable_template7510: diag::ext_variable_template);7511}7512}7513} else {7514// Check that we can declare a member specialization here.7515if (!TemplateParamLists.empty() && IsMemberSpecialization &&7516CheckTemplateDeclScope(S, TemplateParamLists.back()))7517return nullptr;7518assert((Invalid ||7519D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&7520"should have a 'template<>' for this decl");7521}75227523bool IsExplicitSpecialization =7524IsVariableTemplateSpecialization && !IsPartialSpecialization;75257526// C++ [temp.expl.spec]p2:7527// The declaration in an explicit-specialization shall not be an7528// export-declaration. An explicit specialization shall not use a7529// storage-class-specifier other than thread_local.7530//7531// We use the storage-class-specifier from DeclSpec because we may have7532// added implicit 'extern' for declarations with __declspec(dllimport)!7533if (SCSpec != DeclSpec::SCS_unspecified &&7534(IsExplicitSpecialization || IsMemberSpecialization)) {7535Diag(D.getDeclSpec().getStorageClassSpecLoc(),7536diag::ext_explicit_specialization_storage_class)7537<< FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());7538}75397540if (CurContext->isRecord()) {7541if (SC == SC_Static) {7542if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {7543// Walk up the enclosing DeclContexts to check for any that are7544// incompatible with static data members.7545const DeclContext *FunctionOrMethod = nullptr;7546const CXXRecordDecl *AnonStruct = nullptr;7547for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {7548if (Ctxt->isFunctionOrMethod()) {7549FunctionOrMethod = Ctxt;7550break;7551}7552const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);7553if (ParentDecl && !ParentDecl->getDeclName()) {7554AnonStruct = ParentDecl;7555break;7556}7557}7558if (FunctionOrMethod) {7559// C++ [class.static.data]p5: A local class shall not have static7560// data members.7561Diag(D.getIdentifierLoc(),7562diag::err_static_data_member_not_allowed_in_local_class)7563<< Name << RD->getDeclName()7564<< llvm::to_underlying(RD->getTagKind());7565} else if (AnonStruct) {7566// C++ [class.static.data]p4: Unnamed classes and classes contained7567// directly or indirectly within unnamed classes shall not contain7568// static data members.7569Diag(D.getIdentifierLoc(),7570diag::err_static_data_member_not_allowed_in_anon_struct)7571<< Name << llvm::to_underlying(AnonStruct->getTagKind());7572Invalid = true;7573} else if (RD->isUnion()) {7574// C++98 [class.union]p1: If a union contains a static data member,7575// the program is ill-formed. C++11 drops this restriction.7576Diag(D.getIdentifierLoc(),7577getLangOpts().CPlusPlus117578? diag::warn_cxx98_compat_static_data_member_in_union7579: diag::ext_static_data_member_in_union)7580<< Name;7581}7582}7583} else if (IsVariableTemplate || IsPartialSpecialization) {7584// There is no such thing as a member field template.7585Diag(D.getIdentifierLoc(), diag::err_template_member)7586<< II << TemplateParams->getSourceRange();7587// Recover by pretending this is a static data member template.7588SC = SC_Static;7589}7590} else if (DC->isRecord()) {7591// This is an out-of-line definition of a static data member.7592switch (SC) {7593case SC_None:7594break;7595case SC_Static:7596Diag(D.getDeclSpec().getStorageClassSpecLoc(),7597diag::err_static_out_of_line)7598<< FixItHint::CreateRemoval(7599D.getDeclSpec().getStorageClassSpecLoc());7600break;7601case SC_Auto:7602case SC_Register:7603case SC_Extern:7604// [dcl.stc] p2: The auto or register specifiers shall be applied only7605// to names of variables declared in a block or to function parameters.7606// [dcl.stc] p6: The extern specifier cannot be used in the declaration7607// of class members76087609Diag(D.getDeclSpec().getStorageClassSpecLoc(),7610diag::err_storage_class_for_static_member)7611<< FixItHint::CreateRemoval(7612D.getDeclSpec().getStorageClassSpecLoc());7613break;7614case SC_PrivateExtern:7615llvm_unreachable("C storage class in c++!");7616}7617}76187619if (IsVariableTemplateSpecialization) {7620SourceLocation TemplateKWLoc =7621TemplateParamLists.size() > 07622? TemplateParamLists[0]->getTemplateLoc()7623: SourceLocation();7624DeclResult Res = ActOnVarTemplateSpecialization(7625S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,7626IsPartialSpecialization);7627if (Res.isInvalid())7628return nullptr;7629NewVD = cast<VarDecl>(Res.get());7630AddToScope = false;7631} else if (D.isDecompositionDeclarator()) {7632NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),7633D.getIdentifierLoc(), R, TInfo, SC,7634Bindings);7635} else7636NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),7637D.getIdentifierLoc(), II, R, TInfo, SC);76387639// If this is supposed to be a variable template, create it as such.7640if (IsVariableTemplate) {7641NewTemplate =7642VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,7643TemplateParams, NewVD);7644NewVD->setDescribedVarTemplate(NewTemplate);7645}76467647// If this decl has an auto type in need of deduction, make a note of the7648// Decl so we can diagnose uses of it in its own initializer.7649if (R->getContainedDeducedType())7650ParsingInitForAutoVars.insert(NewVD);76517652if (D.isInvalidType() || Invalid) {7653NewVD->setInvalidDecl();7654if (NewTemplate)7655NewTemplate->setInvalidDecl();7656}76577658SetNestedNameSpecifier(*this, NewVD, D);76597660// If we have any template parameter lists that don't directly belong to7661// the variable (matching the scope specifier), store them.7662// An explicit variable template specialization does not own any template7663// parameter lists.7664unsigned VDTemplateParamLists =7665(TemplateParams && !IsExplicitSpecialization) ? 1 : 0;7666if (TemplateParamLists.size() > VDTemplateParamLists)7667NewVD->setTemplateParameterListsInfo(7668Context, TemplateParamLists.drop_back(VDTemplateParamLists));7669}76707671if (D.getDeclSpec().isInlineSpecified()) {7672if (!getLangOpts().CPlusPlus) {7673Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)7674<< 0;7675} else if (CurContext->isFunctionOrMethod()) {7676// 'inline' is not allowed on block scope variable declaration.7677Diag(D.getDeclSpec().getInlineSpecLoc(),7678diag::err_inline_declaration_block_scope) << Name7679<< FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());7680} else {7681Diag(D.getDeclSpec().getInlineSpecLoc(),7682getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable7683: diag::ext_inline_variable);7684NewVD->setInlineSpecified();7685}7686}76877688// Set the lexical context. If the declarator has a C++ scope specifier, the7689// lexical context will be different from the semantic context.7690NewVD->setLexicalDeclContext(CurContext);7691if (NewTemplate)7692NewTemplate->setLexicalDeclContext(CurContext);76937694if (IsLocalExternDecl) {7695if (D.isDecompositionDeclarator())7696for (auto *B : Bindings)7697B->setLocalExternDecl();7698else7699NewVD->setLocalExternDecl();7700}77017702bool EmitTLSUnsupportedError = false;7703if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {7704// C++11 [dcl.stc]p4:7705// When thread_local is applied to a variable of block scope the7706// storage-class-specifier static is implied if it does not appear7707// explicitly.7708// Core issue: 'static' is not implied if the variable is declared7709// 'extern'.7710if (NewVD->hasLocalStorage() &&7711(SCSpec != DeclSpec::SCS_unspecified ||7712TSCS != DeclSpec::TSCS_thread_local ||7713!DC->isFunctionOrMethod()))7714Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),7715diag::err_thread_non_global)7716<< DeclSpec::getSpecifierName(TSCS);7717else if (!Context.getTargetInfo().isTLSSupported()) {7718if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||7719getLangOpts().SYCLIsDevice) {7720// Postpone error emission until we've collected attributes required to7721// figure out whether it's a host or device variable and whether the7722// error should be ignored.7723EmitTLSUnsupportedError = true;7724// We still need to mark the variable as TLS so it shows up in AST with7725// proper storage class for other tools to use even if we're not going7726// to emit any code for it.7727NewVD->setTSCSpec(TSCS);7728} else7729Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),7730diag::err_thread_unsupported);7731} else7732NewVD->setTSCSpec(TSCS);7733}77347735switch (D.getDeclSpec().getConstexprSpecifier()) {7736case ConstexprSpecKind::Unspecified:7737break;77387739case ConstexprSpecKind::Consteval:7740Diag(D.getDeclSpec().getConstexprSpecLoc(),7741diag::err_constexpr_wrong_decl_kind)7742<< static_cast<int>(D.getDeclSpec().getConstexprSpecifier());7743[[fallthrough]];77447745case ConstexprSpecKind::Constexpr:7746NewVD->setConstexpr(true);7747// C++1z [dcl.spec.constexpr]p1:7748// A static data member declared with the constexpr specifier is7749// implicitly an inline variable.7750if (NewVD->isStaticDataMember() &&7751(getLangOpts().CPlusPlus17 ||7752Context.getTargetInfo().getCXXABI().isMicrosoft()))7753NewVD->setImplicitlyInline();7754break;77557756case ConstexprSpecKind::Constinit:7757if (!NewVD->hasGlobalStorage())7758Diag(D.getDeclSpec().getConstexprSpecLoc(),7759diag::err_constinit_local_variable);7760else7761NewVD->addAttr(7762ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),7763ConstInitAttr::Keyword_constinit));7764break;7765}77667767// C99 6.7.4p37768// An inline definition of a function with external linkage shall7769// not contain a definition of a modifiable object with static or7770// thread storage duration...7771// We only apply this when the function is required to be defined7772// elsewhere, i.e. when the function is not 'extern inline'. Note7773// that a local variable with thread storage duration still has to7774// be marked 'static'. Also note that it's possible to get these7775// semantics in C++ using __attribute__((gnu_inline)).7776if (SC == SC_Static && S->getFnParent() != nullptr &&7777!NewVD->getType().isConstQualified()) {7778FunctionDecl *CurFD = getCurFunctionDecl();7779if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {7780Diag(D.getDeclSpec().getStorageClassSpecLoc(),7781diag::warn_static_local_in_extern_inline);7782MaybeSuggestAddingStaticToDecl(CurFD);7783}7784}77857786if (D.getDeclSpec().isModulePrivateSpecified()) {7787if (IsVariableTemplateSpecialization)7788Diag(NewVD->getLocation(), diag::err_module_private_specialization)7789<< (IsPartialSpecialization ? 1 : 0)7790<< FixItHint::CreateRemoval(7791D.getDeclSpec().getModulePrivateSpecLoc());7792else if (IsMemberSpecialization)7793Diag(NewVD->getLocation(), diag::err_module_private_specialization)7794<< 27795<< FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());7796else if (NewVD->hasLocalStorage())7797Diag(NewVD->getLocation(), diag::err_module_private_local)7798<< 0 << NewVD7799<< SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())7800<< FixItHint::CreateRemoval(7801D.getDeclSpec().getModulePrivateSpecLoc());7802else {7803NewVD->setModulePrivate();7804if (NewTemplate)7805NewTemplate->setModulePrivate();7806for (auto *B : Bindings)7807B->setModulePrivate();7808}7809}78107811if (getLangOpts().OpenCL) {7812deduceOpenCLAddressSpace(NewVD);78137814DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();7815if (TSC != TSCS_unspecified) {7816Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),7817diag::err_opencl_unknown_type_specifier)7818<< getLangOpts().getOpenCLVersionString()7819<< DeclSpec::getSpecifierName(TSC) << 1;7820NewVD->setInvalidDecl();7821}7822}78237824// WebAssembly tables are always in address space 1 (wasm_var). Don't apply7825// address space if the table has local storage (semantic checks elsewhere7826// will produce an error anyway).7827if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {7828if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&7829!NewVD->hasLocalStorage()) {7830QualType Type = Context.getAddrSpaceQualType(7831NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));7832NewVD->setType(Type);7833}7834}78357836// Handle attributes prior to checking for duplicates in MergeVarDecl7837ProcessDeclAttributes(S, NewVD, D);78387839// FIXME: This is probably the wrong location to be doing this and we should7840// probably be doing this for more attributes (especially for function7841// pointer attributes such as format, warn_unused_result, etc.). Ideally7842// the code to copy attributes would be generated by TableGen.7843if (R->isFunctionPointerType())7844if (const auto *TT = R->getAs<TypedefType>())7845copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);78467847if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||7848getLangOpts().SYCLIsDevice) {7849if (EmitTLSUnsupportedError &&7850((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||7851(getLangOpts().OpenMPIsTargetDevice &&7852OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))7853Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),7854diag::err_thread_unsupported);78557856if (EmitTLSUnsupportedError &&7857(LangOpts.SYCLIsDevice ||7858(LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))7859targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);7860// CUDA B.2.5: "__shared__ and __constant__ variables have implied static7861// storage [duration]."7862if (SC == SC_None && S->getFnParent() != nullptr &&7863(NewVD->hasAttr<CUDASharedAttr>() ||7864NewVD->hasAttr<CUDAConstantAttr>())) {7865NewVD->setStorageClass(SC_Static);7866}7867}78687869// Ensure that dllimport globals without explicit storage class are treated as7870// extern. The storage class is set above using parsed attributes. Now we can7871// check the VarDecl itself.7872assert(!NewVD->hasAttr<DLLImportAttr>() ||7873NewVD->getAttr<DLLImportAttr>()->isInherited() ||7874NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);78757876// In auto-retain/release, infer strong retension for variables of7877// retainable type.7878if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))7879NewVD->setInvalidDecl();78807881// Handle GNU asm-label extension (encoded as an attribute).7882if (Expr *E = (Expr*)D.getAsmLabel()) {7883// The parser guarantees this is a string.7884StringLiteral *SE = cast<StringLiteral>(E);7885StringRef Label = SE->getString();7886if (S->getFnParent() != nullptr) {7887switch (SC) {7888case SC_None:7889case SC_Auto:7890Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;7891break;7892case SC_Register:7893// Local Named register7894if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&7895DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))7896Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;7897break;7898case SC_Static:7899case SC_Extern:7900case SC_PrivateExtern:7901break;7902}7903} else if (SC == SC_Register) {7904// Global Named register7905if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {7906const auto &TI = Context.getTargetInfo();7907bool HasSizeMismatch;79087909if (!TI.isValidGCCRegisterName(Label))7910Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;7911else if (!TI.validateGlobalRegisterVariable(Label,7912Context.getTypeSize(R),7913HasSizeMismatch))7914Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;7915else if (HasSizeMismatch)7916Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;7917}79187919if (!R->isIntegralType(Context) && !R->isPointerType()) {7920Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);7921NewVD->setInvalidDecl(true);7922}7923}79247925NewVD->addAttr(AsmLabelAttr::Create(Context, Label,7926/*IsLiteralLabel=*/true,7927SE->getStrTokenLoc(0)));7928} else if (!ExtnameUndeclaredIdentifiers.empty()) {7929llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =7930ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());7931if (I != ExtnameUndeclaredIdentifiers.end()) {7932if (isDeclExternC(NewVD)) {7933NewVD->addAttr(I->second);7934ExtnameUndeclaredIdentifiers.erase(I);7935} else7936Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)7937<< /*Variable*/1 << NewVD;7938}7939}79407941// Find the shadowed declaration before filtering for scope.7942NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()7943? getShadowedDeclaration(NewVD, Previous)7944: nullptr;79457946// Don't consider existing declarations that are in a different7947// scope and are out-of-semantic-context declarations (if the new7948// declaration has linkage).7949FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),7950D.getCXXScopeSpec().isNotEmpty() ||7951IsMemberSpecialization ||7952IsVariableTemplateSpecialization);79537954// Check whether the previous declaration is in the same block scope. This7955// affects whether we merge types with it, per C++11 [dcl.array]p3.7956if (getLangOpts().CPlusPlus &&7957NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())7958NewVD->setPreviousDeclInSameBlockScope(7959Previous.isSingleResult() && !Previous.isShadowed() &&7960isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));79617962if (!getLangOpts().CPlusPlus) {7963D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));7964} else {7965// If this is an explicit specialization of a static data member, check it.7966if (IsMemberSpecialization && !IsVariableTemplateSpecialization &&7967!NewVD->isInvalidDecl() && CheckMemberSpecialization(NewVD, Previous))7968NewVD->setInvalidDecl();79697970// Merge the decl with the existing one if appropriate.7971if (!Previous.empty()) {7972if (Previous.isSingleResult() &&7973isa<FieldDecl>(Previous.getFoundDecl()) &&7974D.getCXXScopeSpec().isSet()) {7975// The user tried to define a non-static data member7976// out-of-line (C++ [dcl.meaning]p1).7977Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)7978<< D.getCXXScopeSpec().getRange();7979Previous.clear();7980NewVD->setInvalidDecl();7981}7982} else if (D.getCXXScopeSpec().isSet() &&7983!IsVariableTemplateSpecialization) {7984// No previous declaration in the qualifying scope.7985Diag(D.getIdentifierLoc(), diag::err_no_member)7986<< Name << computeDeclContext(D.getCXXScopeSpec(), true)7987<< D.getCXXScopeSpec().getRange();7988NewVD->setInvalidDecl();7989}79907991if (!IsPlaceholderVariable)7992D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));79937994// CheckVariableDeclaration will set NewVD as invalid if something is in7995// error like WebAssembly tables being declared as arrays with a non-zero7996// size, but then parsing continues and emits further errors on that line.7997// To avoid that we check here if it happened and return nullptr.7998if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())7999return nullptr;80008001if (NewTemplate) {8002VarTemplateDecl *PrevVarTemplate =8003NewVD->getPreviousDecl()8004? NewVD->getPreviousDecl()->getDescribedVarTemplate()8005: nullptr;80068007// Check the template parameter list of this declaration, possibly8008// merging in the template parameter list from the previous variable8009// template declaration.8010if (CheckTemplateParameterList(8011TemplateParams,8012PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()8013: nullptr,8014(D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&8015DC->isDependentContext())8016? TPC_ClassTemplateMember8017: TPC_VarTemplate))8018NewVD->setInvalidDecl();80198020// If we are providing an explicit specialization of a static variable8021// template, make a note of that.8022if (PrevVarTemplate &&8023PrevVarTemplate->getInstantiatedFromMemberTemplate())8024PrevVarTemplate->setMemberSpecialization();8025}8026}80278028// Diagnose shadowed variables iff this isn't a redeclaration.8029if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())8030CheckShadow(NewVD, ShadowedDecl, Previous);80318032ProcessPragmaWeak(S, NewVD);80338034// If this is the first declaration of an extern C variable, update8035// the map of such variables.8036if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&8037isIncompleteDeclExternC(*this, NewVD))8038RegisterLocallyScopedExternCDecl(NewVD, S);80398040if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {8041MangleNumberingContext *MCtx;8042Decl *ManglingContextDecl;8043std::tie(MCtx, ManglingContextDecl) =8044getCurrentMangleNumberContext(NewVD->getDeclContext());8045if (MCtx) {8046Context.setManglingNumber(8047NewVD, MCtx->getManglingNumber(8048NewVD, getMSManglingNumber(getLangOpts(), S)));8049Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));8050}8051}80528053// Special handling of variable named 'main'.8054if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&8055NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&8056!getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {80578058// C++ [basic.start.main]p38059// A program that declares a variable main at global scope is ill-formed.8060if (getLangOpts().CPlusPlus)8061Diag(D.getBeginLoc(), diag::err_main_global_variable);80628063// In C, and external-linkage variable named main results in undefined8064// behavior.8065else if (NewVD->hasExternalFormalLinkage())8066Diag(D.getBeginLoc(), diag::warn_main_redefined);8067}80688069if (D.isRedeclaration() && !Previous.empty()) {8070NamedDecl *Prev = Previous.getRepresentativeDecl();8071checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,8072D.isFunctionDefinition());8073}80748075if (NewTemplate) {8076if (NewVD->isInvalidDecl())8077NewTemplate->setInvalidDecl();8078ActOnDocumentableDecl(NewTemplate);8079return NewTemplate;8080}80818082if (IsMemberSpecialization && !NewVD->isInvalidDecl())8083CompleteMemberSpecialization(NewVD, Previous);80848085emitReadOnlyPlacementAttrWarning(*this, NewVD);80868087return NewVD;8088}80898090/// Enum describing the %select options in diag::warn_decl_shadow.8091enum ShadowedDeclKind {8092SDK_Local,8093SDK_Global,8094SDK_StaticMember,8095SDK_Field,8096SDK_Typedef,8097SDK_Using,8098SDK_StructuredBinding8099};81008101/// Determine what kind of declaration we're shadowing.8102static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,8103const DeclContext *OldDC) {8104if (isa<TypeAliasDecl>(ShadowedDecl))8105return SDK_Using;8106else if (isa<TypedefDecl>(ShadowedDecl))8107return SDK_Typedef;8108else if (isa<BindingDecl>(ShadowedDecl))8109return SDK_StructuredBinding;8110else if (isa<RecordDecl>(OldDC))8111return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;81128113return OldDC->isFileContext() ? SDK_Global : SDK_Local;8114}81158116/// Return the location of the capture if the given lambda captures the given8117/// variable \p VD, or an invalid source location otherwise.8118static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,8119const VarDecl *VD) {8120for (const Capture &Capture : LSI->Captures) {8121if (Capture.isVariableCapture() && Capture.getVariable() == VD)8122return Capture.getLocation();8123}8124return SourceLocation();8125}81268127static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,8128const LookupResult &R) {8129// Only diagnose if we're shadowing an unambiguous field or variable.8130if (R.getResultKind() != LookupResult::Found)8131return false;81328133// Return false if warning is ignored.8134return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());8135}81368137NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,8138const LookupResult &R) {8139if (!shouldWarnIfShadowedDecl(Diags, R))8140return nullptr;81418142// Don't diagnose declarations at file scope.8143if (D->hasGlobalStorage() && !D->isStaticLocal())8144return nullptr;81458146NamedDecl *ShadowedDecl = R.getFoundDecl();8147return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl8148: nullptr;8149}81508151NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,8152const LookupResult &R) {8153// Don't warn if typedef declaration is part of a class8154if (D->getDeclContext()->isRecord())8155return nullptr;81568157if (!shouldWarnIfShadowedDecl(Diags, R))8158return nullptr;81598160NamedDecl *ShadowedDecl = R.getFoundDecl();8161return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;8162}81638164NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,8165const LookupResult &R) {8166if (!shouldWarnIfShadowedDecl(Diags, R))8167return nullptr;81688169NamedDecl *ShadowedDecl = R.getFoundDecl();8170return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl8171: nullptr;8172}81738174void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,8175const LookupResult &R) {8176DeclContext *NewDC = D->getDeclContext();81778178if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {8179// Fields are not shadowed by variables in C++ static methods.8180if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))8181if (MD->isStatic())8182return;81838184// Fields shadowed by constructor parameters are a special case. Usually8185// the constructor initializes the field with the parameter.8186if (isa<CXXConstructorDecl>(NewDC))8187if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {8188// Remember that this was shadowed so we can either warn about its8189// modification or its existence depending on warning settings.8190ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});8191return;8192}8193}81948195if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))8196if (shadowedVar->isExternC()) {8197// For shadowing external vars, make sure that we point to the global8198// declaration, not a locally scoped extern declaration.8199for (auto *I : shadowedVar->redecls())8200if (I->isFileVarDecl()) {8201ShadowedDecl = I;8202break;8203}8204}82058206DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();82078208unsigned WarningDiag = diag::warn_decl_shadow;8209SourceLocation CaptureLoc;8210if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {8211if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {8212if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {8213if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {8214const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());8215if (RD->getLambdaCaptureDefault() == LCD_None) {8216// Try to avoid warnings for lambdas with an explicit capture8217// list. Warn only when the lambda captures the shadowed decl8218// explicitly.8219CaptureLoc = getCaptureLocation(LSI, VD);8220if (CaptureLoc.isInvalid())8221WarningDiag = diag::warn_decl_shadow_uncaptured_local;8222} else {8223// Remember that this was shadowed so we can avoid the warning if8224// the shadowed decl isn't captured and the warning settings allow8225// it.8226cast<LambdaScopeInfo>(getCurFunction())8227->ShadowingDecls.push_back({D, VD});8228return;8229}8230}8231if (isa<FieldDecl>(ShadowedDecl)) {8232// If lambda can capture this, then emit default shadowing warning,8233// Otherwise it is not really a shadowing case since field is not8234// available in lambda's body.8235// At this point we don't know that lambda can capture this, so8236// remember that this was shadowed and delay until we know.8237cast<LambdaScopeInfo>(getCurFunction())8238->ShadowingDecls.push_back({D, ShadowedDecl});8239return;8240}8241}8242if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);8243VD && VD->hasLocalStorage()) {8244// A variable can't shadow a local variable in an enclosing scope, if8245// they are separated by a non-capturing declaration context.8246for (DeclContext *ParentDC = NewDC;8247ParentDC && !ParentDC->Equals(OldDC);8248ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {8249// Only block literals, captured statements, and lambda expressions8250// can capture; other scopes don't.8251if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&8252!isLambdaCallOperator(ParentDC)) {8253return;8254}8255}8256}8257}8258}82598260// Never warn about shadowing a placeholder variable.8261if (ShadowedDecl->isPlaceholderVar(getLangOpts()))8262return;82638264// Only warn about certain kinds of shadowing for class members.8265if (NewDC && NewDC->isRecord()) {8266// In particular, don't warn about shadowing non-class members.8267if (!OldDC->isRecord())8268return;82698270// TODO: should we warn about static data members shadowing8271// static data members from base classes?82728273// TODO: don't diagnose for inaccessible shadowed members.8274// This is hard to do perfectly because we might friend the8275// shadowing context, but that's just a false negative.8276}827782788279DeclarationName Name = R.getLookupName();82808281// Emit warning and note.8282ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);8283Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;8284if (!CaptureLoc.isInvalid())8285Diag(CaptureLoc, diag::note_var_explicitly_captured_here)8286<< Name << /*explicitly*/ 1;8287Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);8288}82898290void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {8291for (const auto &Shadow : LSI->ShadowingDecls) {8292const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;8293// Try to avoid the warning when the shadowed decl isn't captured.8294const DeclContext *OldDC = ShadowedDecl->getDeclContext();8295if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {8296SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);8297Diag(Shadow.VD->getLocation(),8298CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local8299: diag::warn_decl_shadow)8300<< Shadow.VD->getDeclName()8301<< computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;8302if (CaptureLoc.isValid())8303Diag(CaptureLoc, diag::note_var_explicitly_captured_here)8304<< Shadow.VD->getDeclName() << /*explicitly*/ 0;8305Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);8306} else if (isa<FieldDecl>(ShadowedDecl)) {8307Diag(Shadow.VD->getLocation(),8308LSI->isCXXThisCaptured() ? diag::warn_decl_shadow8309: diag::warn_decl_shadow_uncaptured_local)8310<< Shadow.VD->getDeclName()8311<< computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;8312Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);8313}8314}8315}83168317void Sema::CheckShadow(Scope *S, VarDecl *D) {8318if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))8319return;83208321LookupResult R(*this, D->getDeclName(), D->getLocation(),8322Sema::LookupOrdinaryName,8323RedeclarationKind::ForVisibleRedeclaration);8324LookupName(R, S);8325if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))8326CheckShadow(D, ShadowedDecl, R);8327}83288329/// Check if 'E', which is an expression that is about to be modified, refers8330/// to a constructor parameter that shadows a field.8331void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {8332// Quickly ignore expressions that can't be shadowing ctor parameters.8333if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())8334return;8335E = E->IgnoreParenImpCasts();8336auto *DRE = dyn_cast<DeclRefExpr>(E);8337if (!DRE)8338return;8339const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());8340auto I = ShadowingDecls.find(D);8341if (I == ShadowingDecls.end())8342return;8343const NamedDecl *ShadowedDecl = I->second;8344const DeclContext *OldDC = ShadowedDecl->getDeclContext();8345Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;8346Diag(D->getLocation(), diag::note_var_declared_here) << D;8347Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);83488349// Avoid issuing multiple warnings about the same decl.8350ShadowingDecls.erase(I);8351}83528353/// Check for conflict between this global or extern "C" declaration and8354/// previous global or extern "C" declarations. This is only used in C++.8355template<typename T>8356static bool checkGlobalOrExternCConflict(8357Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {8358assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");8359NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());83608361if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {8362// The common case: this global doesn't conflict with any extern "C"8363// declaration.8364return false;8365}83668367if (Prev) {8368if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {8369// Both the old and new declarations have C language linkage. This is a8370// redeclaration.8371Previous.clear();8372Previous.addDecl(Prev);8373return true;8374}83758376// This is a global, non-extern "C" declaration, and there is a previous8377// non-global extern "C" declaration. Diagnose if this is a variable8378// declaration.8379if (!isa<VarDecl>(ND))8380return false;8381} else {8382// The declaration is extern "C". Check for any declaration in the8383// translation unit which might conflict.8384if (IsGlobal) {8385// We have already performed the lookup into the translation unit.8386IsGlobal = false;8387for (LookupResult::iterator I = Previous.begin(), E = Previous.end();8388I != E; ++I) {8389if (isa<VarDecl>(*I)) {8390Prev = *I;8391break;8392}8393}8394} else {8395DeclContext::lookup_result R =8396S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());8397for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();8398I != E; ++I) {8399if (isa<VarDecl>(*I)) {8400Prev = *I;8401break;8402}8403// FIXME: If we have any other entity with this name in global scope,8404// the declaration is ill-formed, but that is a defect: it breaks the8405// 'stat' hack, for instance. Only variables can have mangled name8406// clashes with extern "C" declarations, so only they deserve a8407// diagnostic.8408}8409}84108411if (!Prev)8412return false;8413}84148415// Use the first declaration's location to ensure we point at something which8416// is lexically inside an extern "C" linkage-spec.8417assert(Prev && "should have found a previous declaration to diagnose");8418if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))8419Prev = FD->getFirstDecl();8420else8421Prev = cast<VarDecl>(Prev)->getFirstDecl();84228423S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)8424<< IsGlobal << ND;8425S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)8426<< IsGlobal;8427return false;8428}84298430/// Apply special rules for handling extern "C" declarations. Returns \c true8431/// if we have found that this is a redeclaration of some prior entity.8432///8433/// Per C++ [dcl.link]p6:8434/// Two declarations [for a function or variable] with C language linkage8435/// with the same name that appear in different scopes refer to the same8436/// [entity]. An entity with C language linkage shall not be declared with8437/// the same name as an entity in global scope.8438template<typename T>8439static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,8440LookupResult &Previous) {8441if (!S.getLangOpts().CPlusPlus) {8442// In C, when declaring a global variable, look for a corresponding 'extern'8443// variable declared in function scope. We don't need this in C++, because8444// we find local extern decls in the surrounding file-scope DeclContext.8445if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {8446if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {8447Previous.clear();8448Previous.addDecl(Prev);8449return true;8450}8451}8452return false;8453}84548455// A declaration in the translation unit can conflict with an extern "C"8456// declaration.8457if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())8458return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);84598460// An extern "C" declaration can conflict with a declaration in the8461// translation unit or can be a redeclaration of an extern "C" declaration8462// in another scope.8463if (isIncompleteDeclExternC(S,ND))8464return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);84658466// Neither global nor extern "C": nothing to do.8467return false;8468}84698470static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,8471QualType T) {8472QualType CanonT = SemaRef.Context.getCanonicalType(T);8473// C23 6.7.1p5: An object declared with storage-class specifier constexpr or8474// any of its members, even recursively, shall not have an atomic type, or a8475// variably modified type, or a type that is volatile or restrict qualified.8476if (CanonT->isVariablyModifiedType()) {8477SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;8478return true;8479}84808481// Arrays are qualified by their element type, so get the base type (this8482// works on non-arrays as well).8483CanonT = SemaRef.Context.getBaseElementType(CanonT);84848485if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||8486CanonT.isRestrictQualified()) {8487SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;8488return true;8489}84908491if (CanonT->isRecordType()) {8492const RecordDecl *RD = CanonT->getAsRecordDecl();8493if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {8494return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());8495}))8496return true;8497}84988499return false;8500}85018502void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {8503// If the decl is already known invalid, don't check it.8504if (NewVD->isInvalidDecl())8505return;85068507QualType T = NewVD->getType();85088509// Defer checking an 'auto' type until its initializer is attached.8510if (T->isUndeducedType())8511return;85128513if (NewVD->hasAttrs())8514CheckAlignasUnderalignment(NewVD);85158516if (T->isObjCObjectType()) {8517Diag(NewVD->getLocation(), diag::err_statically_allocated_object)8518<< FixItHint::CreateInsertion(NewVD->getLocation(), "*");8519T = Context.getObjCObjectPointerType(T);8520NewVD->setType(T);8521}85228523// Emit an error if an address space was applied to decl with local storage.8524// This includes arrays of objects with address space qualifiers, but not8525// automatic variables that point to other address spaces.8526// ISO/IEC TR 18037 S5.1.28527if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&8528T.getAddressSpace() != LangAS::Default) {8529Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;8530NewVD->setInvalidDecl();8531return;8532}85338534// OpenCL v1.2 s6.8 - The static qualifier is valid only in program8535// scope.8536if (getLangOpts().OpenCLVersion == 120 &&8537!getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",8538getLangOpts()) &&8539NewVD->isStaticLocal()) {8540Diag(NewVD->getLocation(), diag::err_static_function_scope);8541NewVD->setInvalidDecl();8542return;8543}85448545if (getLangOpts().OpenCL) {8546if (!diagnoseOpenCLTypes(*this, NewVD))8547return;85488549// OpenCL v2.0 s6.12.5 - The __block storage type is not supported.8550if (NewVD->hasAttr<BlocksAttr>()) {8551Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);8552return;8553}85548555if (T->isBlockPointerType()) {8556// OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and8557// can't use 'extern' storage class.8558if (!T.isConstQualified()) {8559Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)8560<< 0 /*const*/;8561NewVD->setInvalidDecl();8562return;8563}8564if (NewVD->hasExternalStorage()) {8565Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);8566NewVD->setInvalidDecl();8567return;8568}8569}85708571// FIXME: Adding local AS in C++ for OpenCL might make sense.8572if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||8573NewVD->hasExternalStorage()) {8574if (!T->isSamplerT() && !T->isDependentType() &&8575!(T.getAddressSpace() == LangAS::opencl_constant ||8576(T.getAddressSpace() == LangAS::opencl_global &&8577getOpenCLOptions().areProgramScopeVariablesSupported(8578getLangOpts())))) {8579int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;8580if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))8581Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)8582<< Scope << "global or constant";8583else8584Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)8585<< Scope << "constant";8586NewVD->setInvalidDecl();8587return;8588}8589} else {8590if (T.getAddressSpace() == LangAS::opencl_global) {8591Diag(NewVD->getLocation(), diag::err_opencl_function_variable)8592<< 1 /*is any function*/ << "global";8593NewVD->setInvalidDecl();8594return;8595}8596if (T.getAddressSpace() == LangAS::opencl_constant ||8597T.getAddressSpace() == LangAS::opencl_local) {8598FunctionDecl *FD = getCurFunctionDecl();8599// OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables8600// in functions.8601if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {8602if (T.getAddressSpace() == LangAS::opencl_constant)8603Diag(NewVD->getLocation(), diag::err_opencl_function_variable)8604<< 0 /*non-kernel only*/ << "constant";8605else8606Diag(NewVD->getLocation(), diag::err_opencl_function_variable)8607<< 0 /*non-kernel only*/ << "local";8608NewVD->setInvalidDecl();8609return;8610}8611// OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be8612// in the outermost scope of a kernel function.8613if (FD && FD->hasAttr<OpenCLKernelAttr>()) {8614if (!getCurScope()->isFunctionScope()) {8615if (T.getAddressSpace() == LangAS::opencl_constant)8616Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)8617<< "constant";8618else8619Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)8620<< "local";8621NewVD->setInvalidDecl();8622return;8623}8624}8625} else if (T.getAddressSpace() != LangAS::opencl_private &&8626// If we are parsing a template we didn't deduce an addr8627// space yet.8628T.getAddressSpace() != LangAS::Default) {8629// Do not allow other address spaces on automatic variable.8630Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;8631NewVD->setInvalidDecl();8632return;8633}8634}8635}86368637if (NewVD->hasLocalStorage() && T.isObjCGCWeak()8638&& !NewVD->hasAttr<BlocksAttr>()) {8639if (getLangOpts().getGC() != LangOptions::NonGC)8640Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);8641else {8642assert(!getLangOpts().ObjCAutoRefCount);8643Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);8644}8645}86468647// WebAssembly tables must be static with a zero length and can't be8648// declared within functions.8649if (T->isWebAssemblyTableType()) {8650if (getCurScope()->getParent()) { // Parent is null at top-level8651Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);8652NewVD->setInvalidDecl();8653return;8654}8655if (NewVD->getStorageClass() != SC_Static) {8656Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);8657NewVD->setInvalidDecl();8658return;8659}8660const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());8661if (!ATy || ATy->getZExtSize() != 0) {8662Diag(NewVD->getLocation(),8663diag::err_typecheck_wasm_table_must_have_zero_length);8664NewVD->setInvalidDecl();8665return;8666}8667}86688669bool isVM = T->isVariablyModifiedType();8670if (isVM || NewVD->hasAttr<CleanupAttr>() ||8671NewVD->hasAttr<BlocksAttr>())8672setFunctionHasBranchProtectedScope();86738674if ((isVM && NewVD->hasLinkage()) ||8675(T->isVariableArrayType() && NewVD->hasGlobalStorage())) {8676bool SizeIsNegative;8677llvm::APSInt Oversized;8678TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(8679NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);8680QualType FixedT;8681if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())8682FixedT = FixedTInfo->getType();8683else if (FixedTInfo) {8684// Type and type-as-written are canonically different. We need to fix up8685// both types separately.8686FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,8687Oversized);8688}8689if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {8690const VariableArrayType *VAT = Context.getAsVariableArrayType(T);8691// FIXME: This won't give the correct result for8692// int a[10][n];8693SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();86948695if (NewVD->isFileVarDecl())8696Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)8697<< SizeRange;8698else if (NewVD->isStaticLocal())8699Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)8700<< SizeRange;8701else8702Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)8703<< SizeRange;8704NewVD->setInvalidDecl();8705return;8706}87078708if (!FixedTInfo) {8709if (NewVD->isFileVarDecl())8710Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);8711else8712Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);8713NewVD->setInvalidDecl();8714return;8715}87168717Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);8718NewVD->setType(FixedT);8719NewVD->setTypeSourceInfo(FixedTInfo);8720}87218722if (T->isVoidType()) {8723// C++98 [dcl.stc]p5: The extern specifier can be applied only to the names8724// of objects and functions.8725if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {8726Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)8727<< T;8728NewVD->setInvalidDecl();8729return;8730}8731}87328733if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {8734Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);8735NewVD->setInvalidDecl();8736return;8737}87388739if (!NewVD->hasLocalStorage() && T->isSizelessType() &&8740!T.isWebAssemblyReferenceType()) {8741Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;8742NewVD->setInvalidDecl();8743return;8744}87458746if (isVM && NewVD->hasAttr<BlocksAttr>()) {8747Diag(NewVD->getLocation(), diag::err_block_on_vm);8748NewVD->setInvalidDecl();8749return;8750}87518752if (getLangOpts().C23 && NewVD->isConstexpr() &&8753CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {8754NewVD->setInvalidDecl();8755return;8756}87578758if (NewVD->isConstexpr() && !T->isDependentType() &&8759RequireLiteralType(NewVD->getLocation(), T,8760diag::err_constexpr_var_non_literal)) {8761NewVD->setInvalidDecl();8762return;8763}87648765// PPC MMA non-pointer types are not allowed as non-local variable types.8766if (Context.getTargetInfo().getTriple().isPPC64() &&8767!NewVD->isLocalVarDecl() &&8768PPC().CheckPPCMMAType(T, NewVD->getLocation())) {8769NewVD->setInvalidDecl();8770return;8771}87728773// Check that SVE types are only used in functions with SVE available.8774if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {8775const FunctionDecl *FD = cast<FunctionDecl>(CurContext);8776llvm::StringMap<bool> CallerFeatureMap;8777Context.getFunctionFeatureMap(CallerFeatureMap, FD);87788779if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {8780if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {8781Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;8782NewVD->setInvalidDecl();8783return;8784} else if (!IsArmStreamingFunction(FD,8785/*IncludeLocallyStreaming=*/true)) {8786Diag(NewVD->getLocation(),8787diag::err_sve_vector_in_non_streaming_function)8788<< T;8789NewVD->setInvalidDecl();8790return;8791}8792}8793}87948795if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {8796const FunctionDecl *FD = cast<FunctionDecl>(CurContext);8797llvm::StringMap<bool> CallerFeatureMap;8798Context.getFunctionFeatureMap(CallerFeatureMap, FD);8799RISCV().checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),8800CallerFeatureMap);8801}8802}88038804bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {8805CheckVariableDeclarationType(NewVD);88068807// If the decl is already known invalid, don't check it.8808if (NewVD->isInvalidDecl())8809return false;88108811// If we did not find anything by this name, look for a non-visible8812// extern "C" declaration with the same name.8813if (Previous.empty() &&8814checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))8815Previous.setShadowed();88168817if (!Previous.empty()) {8818MergeVarDecl(NewVD, Previous);8819return true;8820}8821return false;8822}88238824bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {8825llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;88268827// Look for methods in base classes that this method might override.8828CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,8829/*DetectVirtual=*/false);8830auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {8831CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();8832DeclarationName Name = MD->getDeclName();88338834if (Name.getNameKind() == DeclarationName::CXXDestructorName) {8835// We really want to find the base class destructor here.8836QualType T = Context.getTypeDeclType(BaseRecord);8837CanQualType CT = Context.getCanonicalType(T);8838Name = Context.DeclarationNames.getCXXDestructorName(CT);8839}88408841for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {8842CXXMethodDecl *BaseMD =8843dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());8844if (!BaseMD || !BaseMD->isVirtual() ||8845IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,8846/*ConsiderCudaAttrs=*/true))8847continue;8848if (!CheckExplicitObjectOverride(MD, BaseMD))8849continue;8850if (Overridden.insert(BaseMD).second) {8851MD->addOverriddenMethod(BaseMD);8852CheckOverridingFunctionReturnType(MD, BaseMD);8853CheckOverridingFunctionAttributes(MD, BaseMD);8854CheckOverridingFunctionExceptionSpec(MD, BaseMD);8855CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);8856}88578858// A method can only override one function from each base class. We8859// don't track indirectly overridden methods from bases of bases.8860return true;8861}88628863return false;8864};88658866DC->lookupInBases(VisitBase, Paths);8867return !Overridden.empty();8868}88698870namespace {8871// Struct for holding all of the extra arguments needed by8872// DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.8873struct ActOnFDArgs {8874Scope *S;8875Declarator &D;8876MultiTemplateParamsArg TemplateParamLists;8877bool AddToScope;8878};8879} // end anonymous namespace88808881namespace {88828883// Callback to only accept typo corrections that have a non-zero edit distance.8884// Also only accept corrections that have the same parent decl.8885class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {8886public:8887DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,8888CXXRecordDecl *Parent)8889: Context(Context), OriginalFD(TypoFD),8890ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}88918892bool ValidateCandidate(const TypoCorrection &candidate) override {8893if (candidate.getEditDistance() == 0)8894return false;88958896SmallVector<unsigned, 1> MismatchedParams;8897for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),8898CDeclEnd = candidate.end();8899CDecl != CDeclEnd; ++CDecl) {8900FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);89018902if (FD && !FD->hasBody() &&8903hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {8904if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {8905CXXRecordDecl *Parent = MD->getParent();8906if (Parent && Parent->getCanonicalDecl() == ExpectedParent)8907return true;8908} else if (!ExpectedParent) {8909return true;8910}8911}8912}89138914return false;8915}89168917std::unique_ptr<CorrectionCandidateCallback> clone() override {8918return std::make_unique<DifferentNameValidatorCCC>(*this);8919}89208921private:8922ASTContext &Context;8923FunctionDecl *OriginalFD;8924CXXRecordDecl *ExpectedParent;8925};89268927} // end anonymous namespace89288929void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {8930TypoCorrectedFunctionDefinitions.insert(F);8931}89328933/// Generate diagnostics for an invalid function redeclaration.8934///8935/// This routine handles generating the diagnostic messages for an invalid8936/// function redeclaration, including finding possible similar declarations8937/// or performing typo correction if there are no previous declarations with8938/// the same name.8939///8940/// Returns a NamedDecl iff typo correction was performed and substituting in8941/// the new declaration name does not cause new errors.8942static NamedDecl *DiagnoseInvalidRedeclaration(8943Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,8944ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {8945DeclarationName Name = NewFD->getDeclName();8946DeclContext *NewDC = NewFD->getDeclContext();8947SmallVector<unsigned, 1> MismatchedParams;8948SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;8949TypoCorrection Correction;8950bool IsDefinition = ExtraArgs.D.isFunctionDefinition();8951unsigned DiagMsg =8952IsLocalFriend ? diag::err_no_matching_local_friend :8953NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :8954diag::err_member_decl_does_not_match;8955LookupResult Prev(SemaRef, Name, NewFD->getLocation(),8956IsLocalFriend ? Sema::LookupLocalFriendName8957: Sema::LookupOrdinaryName,8958RedeclarationKind::ForVisibleRedeclaration);89598960NewFD->setInvalidDecl();8961if (IsLocalFriend)8962SemaRef.LookupName(Prev, S);8963else8964SemaRef.LookupQualifiedName(Prev, NewDC);8965assert(!Prev.isAmbiguous() &&8966"Cannot have an ambiguity in previous-declaration lookup");8967CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);8968DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,8969MD ? MD->getParent() : nullptr);8970if (!Prev.empty()) {8971for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();8972Func != FuncEnd; ++Func) {8973FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);8974if (FD &&8975hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {8976// Add 1 to the index so that 0 can mean the mismatch didn't8977// involve a parameter8978unsigned ParamNum =8979MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;8980NearMatches.push_back(std::make_pair(FD, ParamNum));8981}8982}8983// If the qualified name lookup yielded nothing, try typo correction8984} else if ((Correction = SemaRef.CorrectTypo(8985Prev.getLookupNameInfo(), Prev.getLookupKind(), S,8986&ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,8987IsLocalFriend ? nullptr : NewDC))) {8988// Set up everything for the call to ActOnFunctionDeclarator8989ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),8990ExtraArgs.D.getIdentifierLoc());8991Previous.clear();8992Previous.setLookupName(Correction.getCorrection());8993for (TypoCorrection::decl_iterator CDecl = Correction.begin(),8994CDeclEnd = Correction.end();8995CDecl != CDeclEnd; ++CDecl) {8996FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);8997if (FD && !FD->hasBody() &&8998hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {8999Previous.addDecl(FD);9000}9001}9002bool wasRedeclaration = ExtraArgs.D.isRedeclaration();90039004NamedDecl *Result;9005// Retry building the function declaration with the new previous9006// declarations, and with errors suppressed.9007{9008// Trap errors.9009Sema::SFINAETrap Trap(SemaRef);90109011// TODO: Refactor ActOnFunctionDeclarator so that we can call only the9012// pieces need to verify the typo-corrected C++ declaration and hopefully9013// eliminate the need for the parameter pack ExtraArgs.9014Result = SemaRef.ActOnFunctionDeclarator(9015ExtraArgs.S, ExtraArgs.D,9016Correction.getCorrectionDecl()->getDeclContext(),9017NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,9018ExtraArgs.AddToScope);90199020if (Trap.hasErrorOccurred())9021Result = nullptr;9022}90239024if (Result) {9025// Determine which correction we picked.9026Decl *Canonical = Result->getCanonicalDecl();9027for (LookupResult::iterator I = Previous.begin(), E = Previous.end();9028I != E; ++I)9029if ((*I)->getCanonicalDecl() == Canonical)9030Correction.setCorrectionDecl(*I);90319032// Let Sema know about the correction.9033SemaRef.MarkTypoCorrectedFunctionDefinition(Result);9034SemaRef.diagnoseTypo(9035Correction,9036SemaRef.PDiag(IsLocalFriend9037? diag::err_no_matching_local_friend_suggest9038: diag::err_member_decl_does_not_match_suggest)9039<< Name << NewDC << IsDefinition);9040return Result;9041}90429043// Pretend the typo correction never occurred9044ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),9045ExtraArgs.D.getIdentifierLoc());9046ExtraArgs.D.setRedeclaration(wasRedeclaration);9047Previous.clear();9048Previous.setLookupName(Name);9049}90509051SemaRef.Diag(NewFD->getLocation(), DiagMsg)9052<< Name << NewDC << IsDefinition << NewFD->getLocation();90539054bool NewFDisConst = false;9055if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))9056NewFDisConst = NewMD->isConst();90579058for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator9059NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();9060NearMatch != NearMatchEnd; ++NearMatch) {9061FunctionDecl *FD = NearMatch->first;9062CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);9063bool FDisConst = MD && MD->isConst();9064bool IsMember = MD || !IsLocalFriend;90659066// FIXME: These notes are poorly worded for the local friend case.9067if (unsigned Idx = NearMatch->second) {9068ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);9069SourceLocation Loc = FDParam->getTypeSpecStartLoc();9070if (Loc.isInvalid()) Loc = FD->getLocation();9071SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match9072: diag::note_local_decl_close_param_match)9073<< Idx << FDParam->getType()9074<< NewFD->getParamDecl(Idx - 1)->getType();9075} else if (FDisConst != NewFDisConst) {9076auto DB = SemaRef.Diag(FD->getLocation(),9077diag::note_member_def_close_const_match)9078<< NewFDisConst << FD->getSourceRange().getEnd();9079if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)9080DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),9081" const");9082else if (FTI.hasMethodTypeQualifiers() &&9083FTI.getConstQualifierLoc().isValid())9084DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());9085} else {9086SemaRef.Diag(FD->getLocation(),9087IsMember ? diag::note_member_def_close_match9088: diag::note_local_decl_close_match);9089}9090}9091return nullptr;9092}90939094static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {9095switch (D.getDeclSpec().getStorageClassSpec()) {9096default: llvm_unreachable("Unknown storage class!");9097case DeclSpec::SCS_auto:9098case DeclSpec::SCS_register:9099case DeclSpec::SCS_mutable:9100SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),9101diag::err_typecheck_sclass_func);9102D.getMutableDeclSpec().ClearStorageClassSpecs();9103D.setInvalidType();9104break;9105case DeclSpec::SCS_unspecified: break;9106case DeclSpec::SCS_extern:9107if (D.getDeclSpec().isExternInLinkageSpec())9108return SC_None;9109return SC_Extern;9110case DeclSpec::SCS_static: {9111if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {9112// C99 6.7.1p5:9113// The declaration of an identifier for a function that has9114// block scope shall have no explicit storage-class specifier9115// other than extern9116// See also (C++ [dcl.stc]p4).9117SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),9118diag::err_static_block_func);9119break;9120} else9121return SC_Static;9122}9123case DeclSpec::SCS_private_extern: return SC_PrivateExtern;9124}91259126// No explicit storage class has already been returned9127return SC_None;9128}91299130static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,9131DeclContext *DC, QualType &R,9132TypeSourceInfo *TInfo,9133StorageClass SC,9134bool &IsVirtualOkay) {9135DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);9136DeclarationName Name = NameInfo.getName();91379138FunctionDecl *NewFD = nullptr;9139bool isInline = D.getDeclSpec().isInlineSpecified();91409141ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();9142if (ConstexprKind == ConstexprSpecKind::Constinit ||9143(SemaRef.getLangOpts().C23 &&9144ConstexprKind == ConstexprSpecKind::Constexpr)) {91459146if (SemaRef.getLangOpts().C23)9147SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),9148diag::err_c23_constexpr_not_variable);9149else9150SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),9151diag::err_constexpr_wrong_decl_kind)9152<< static_cast<int>(ConstexprKind);9153ConstexprKind = ConstexprSpecKind::Unspecified;9154D.getMutableDeclSpec().ClearConstexprSpec();9155}91569157if (!SemaRef.getLangOpts().CPlusPlus) {9158// Determine whether the function was written with a prototype. This is9159// true when:9160// - there is a prototype in the declarator, or9161// - the type R of the function is some kind of typedef or other non-9162// attributed reference to a type name (which eventually refers to a9163// function type). Note, we can't always look at the adjusted type to9164// check this case because attributes may cause a non-function9165// declarator to still have a function type. e.g.,9166// typedef void func(int a);9167// __attribute__((noreturn)) func other_func; // This has a prototype9168bool HasPrototype =9169(D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||9170(D.getDeclSpec().isTypeRep() &&9171SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)9172->isFunctionProtoType()) ||9173(!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());9174assert(9175(HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&9176"Strict prototypes are required");91779178NewFD = FunctionDecl::Create(9179SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,9180SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,9181ConstexprSpecKind::Unspecified,9182/*TrailingRequiresClause=*/nullptr);9183if (D.isInvalidType())9184NewFD->setInvalidDecl();91859186return NewFD;9187}91889189ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();9190Expr *TrailingRequiresClause = D.getTrailingRequiresClause();91919192SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);91939194if (Name.getNameKind() == DeclarationName::CXXConstructorName) {9195// This is a C++ constructor declaration.9196assert(DC->isRecord() &&9197"Constructors can only be declared in a member context");91989199R = SemaRef.CheckConstructorDeclarator(D, R, SC);9200return CXXConstructorDecl::Create(9201SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,9202TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),9203isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,9204InheritedConstructor(), TrailingRequiresClause);92059206} else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {9207// This is a C++ destructor declaration.9208if (DC->isRecord()) {9209R = SemaRef.CheckDestructorDeclarator(D, R, SC);9210CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);9211CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(9212SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,9213SemaRef.getCurFPFeatures().isFPConstrained(), isInline,9214/*isImplicitlyDeclared=*/false, ConstexprKind,9215TrailingRequiresClause);9216// User defined destructors start as not selected if the class definition is still9217// not done.9218if (Record->isBeingDefined())9219NewDD->setIneligibleOrNotSelected(true);92209221// If the destructor needs an implicit exception specification, set it9222// now. FIXME: It'd be nice to be able to create the right type to start9223// with, but the type needs to reference the destructor declaration.9224if (SemaRef.getLangOpts().CPlusPlus11)9225SemaRef.AdjustDestructorExceptionSpec(NewDD);92269227IsVirtualOkay = true;9228return NewDD;92299230} else {9231SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);9232D.setInvalidType();92339234// Create a FunctionDecl to satisfy the function definition parsing9235// code path.9236return FunctionDecl::Create(9237SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,9238TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,9239/*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);9240}92419242} else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {9243if (!DC->isRecord()) {9244SemaRef.Diag(D.getIdentifierLoc(),9245diag::err_conv_function_not_member);9246return nullptr;9247}92489249SemaRef.CheckConversionDeclarator(D, R, SC);9250if (D.isInvalidType())9251return nullptr;92529253IsVirtualOkay = true;9254return CXXConversionDecl::Create(9255SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,9256TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,9257ExplicitSpecifier, ConstexprKind, SourceLocation(),9258TrailingRequiresClause);92599260} else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {9261if (TrailingRequiresClause)9262SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),9263diag::err_trailing_requires_clause_on_deduction_guide)9264<< TrailingRequiresClause->getSourceRange();9265if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))9266return nullptr;9267return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),9268ExplicitSpecifier, NameInfo, R, TInfo,9269D.getEndLoc());9270} else if (DC->isRecord()) {9271// If the name of the function is the same as the name of the record,9272// then this must be an invalid constructor that has a return type.9273// (The parser checks for a return type and makes the declarator a9274// constructor if it has no return type).9275if (Name.getAsIdentifierInfo() &&9276Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){9277SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)9278<< SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())9279<< SourceRange(D.getIdentifierLoc());9280return nullptr;9281}92829283// This is a C++ method declaration.9284CXXMethodDecl *Ret = CXXMethodDecl::Create(9285SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,9286TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,9287ConstexprKind, SourceLocation(), TrailingRequiresClause);9288IsVirtualOkay = !Ret->isStatic();9289return Ret;9290} else {9291bool isFriend =9292SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();9293if (!isFriend && SemaRef.CurContext->isRecord())9294return nullptr;92959296// Determine whether the function was written with a9297// prototype. This true when:9298// - we're in C++ (where every function has a prototype),9299return FunctionDecl::Create(9300SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,9301SemaRef.getCurFPFeatures().isFPConstrained(), isInline,9302true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);9303}9304}93059306enum OpenCLParamType {9307ValidKernelParam,9308PtrPtrKernelParam,9309PtrKernelParam,9310InvalidAddrSpacePtrKernelParam,9311InvalidKernelParam,9312RecordKernelParam9313};93149315static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {9316// Size dependent types are just typedefs to normal integer types9317// (e.g. unsigned long), so we cannot distinguish them from other typedefs to9318// integers other than by their names.9319StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};93209321// Remove typedefs one by one until we reach a typedef9322// for a size dependent type.9323QualType DesugaredTy = Ty;9324do {9325ArrayRef<StringRef> Names(SizeTypeNames);9326auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());9327if (Names.end() != Match)9328return true;93299330Ty = DesugaredTy;9331DesugaredTy = Ty.getSingleStepDesugaredType(C);9332} while (DesugaredTy != Ty);93339334return false;9335}93369337static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {9338if (PT->isDependentType())9339return InvalidKernelParam;93409341if (PT->isPointerType() || PT->isReferenceType()) {9342QualType PointeeType = PT->getPointeeType();9343if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||9344PointeeType.getAddressSpace() == LangAS::opencl_private ||9345PointeeType.getAddressSpace() == LangAS::Default)9346return InvalidAddrSpacePtrKernelParam;93479348if (PointeeType->isPointerType()) {9349// This is a pointer to pointer parameter.9350// Recursively check inner type.9351OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);9352if (ParamKind == InvalidAddrSpacePtrKernelParam ||9353ParamKind == InvalidKernelParam)9354return ParamKind;93559356// OpenCL v3.0 s6.11.a:9357// A restriction to pass pointers to pointers only applies to OpenCL C9358// v1.2 or below.9359if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)9360return ValidKernelParam;93619362return PtrPtrKernelParam;9363}93649365// C++ for OpenCL v1.0 s2.4:9366// Moreover the types used in parameters of the kernel functions must be:9367// Standard layout types for pointer parameters. The same applies to9368// reference if an implementation supports them in kernel parameters.9369if (S.getLangOpts().OpenCLCPlusPlus &&9370!S.getOpenCLOptions().isAvailableOption(9371"__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {9372auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();9373bool IsStandardLayoutType = true;9374if (CXXRec) {9375// If template type is not ODR-used its definition is only available9376// in the template definition not its instantiation.9377// FIXME: This logic doesn't work for types that depend on template9378// parameter (PR58590).9379if (!CXXRec->hasDefinition())9380CXXRec = CXXRec->getTemplateInstantiationPattern();9381if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())9382IsStandardLayoutType = false;9383}9384if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&9385!IsStandardLayoutType)9386return InvalidKernelParam;9387}93889389// OpenCL v1.2 s6.9.p:9390// A restriction to pass pointers only applies to OpenCL C v1.2 or below.9391if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)9392return ValidKernelParam;93939394return PtrKernelParam;9395}93969397// OpenCL v1.2 s6.9.k:9398// Arguments to kernel functions in a program cannot be declared with the9399// built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and9400// uintptr_t or a struct and/or union that contain fields declared to be one9401// of these built-in scalar types.9402if (isOpenCLSizeDependentType(S.getASTContext(), PT))9403return InvalidKernelParam;94049405if (PT->isImageType())9406return PtrKernelParam;94079408if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())9409return InvalidKernelParam;94109411// OpenCL extension spec v1.2 s9.5:9412// This extension adds support for half scalar and vector types as built-in9413// types that can be used for arithmetic operations, conversions etc.9414if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&9415PT->isHalfType())9416return InvalidKernelParam;94179418// Look into an array argument to check if it has a forbidden type.9419if (PT->isArrayType()) {9420const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();9421// Call ourself to check an underlying type of an array. Since the9422// getPointeeOrArrayElementType returns an innermost type which is not an9423// array, this recursive call only happens once.9424return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));9425}94269427// C++ for OpenCL v1.0 s2.4:9428// Moreover the types used in parameters of the kernel functions must be:9429// Trivial and standard-layout types C++17 [basic.types] (plain old data9430// types) for parameters passed by value;9431if (S.getLangOpts().OpenCLCPlusPlus &&9432!S.getOpenCLOptions().isAvailableOption(9433"__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&9434!PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))9435return InvalidKernelParam;94369437if (PT->isRecordType())9438return RecordKernelParam;94399440return ValidKernelParam;9441}94429443static void checkIsValidOpenCLKernelParameter(9444Sema &S,9445Declarator &D,9446ParmVarDecl *Param,9447llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {9448QualType PT = Param->getType();94499450// Cache the valid types we encounter to avoid rechecking structs that are9451// used again9452if (ValidTypes.count(PT.getTypePtr()))9453return;94549455switch (getOpenCLKernelParameterType(S, PT)) {9456case PtrPtrKernelParam:9457// OpenCL v3.0 s6.11.a:9458// A kernel function argument cannot be declared as a pointer to a pointer9459// type. [...] This restriction only applies to OpenCL C 1.2 or below.9460S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);9461D.setInvalidType();9462return;94639464case InvalidAddrSpacePtrKernelParam:9465// OpenCL v1.0 s6.5:9466// __kernel function arguments declared to be a pointer of a type can point9467// to one of the following address spaces only : __global, __local or9468// __constant.9469S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);9470D.setInvalidType();9471return;94729473// OpenCL v1.2 s6.9.k:9474// Arguments to kernel functions in a program cannot be declared with the9475// built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and9476// uintptr_t or a struct and/or union that contain fields declared to be9477// one of these built-in scalar types.94789479case InvalidKernelParam:9480// OpenCL v1.2 s6.8 n:9481// A kernel function argument cannot be declared9482// of event_t type.9483// Do not diagnose half type since it is diagnosed as invalid argument9484// type for any function elsewhere.9485if (!PT->isHalfType()) {9486S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;94879488// Explain what typedefs are involved.9489const TypedefType *Typedef = nullptr;9490while ((Typedef = PT->getAs<TypedefType>())) {9491SourceLocation Loc = Typedef->getDecl()->getLocation();9492// SourceLocation may be invalid for a built-in type.9493if (Loc.isValid())9494S.Diag(Loc, diag::note_entity_declared_at) << PT;9495PT = Typedef->desugar();9496}9497}94989499D.setInvalidType();9500return;95019502case PtrKernelParam:9503case ValidKernelParam:9504ValidTypes.insert(PT.getTypePtr());9505return;95069507case RecordKernelParam:9508break;9509}95109511// Track nested structs we will inspect9512SmallVector<const Decl *, 4> VisitStack;95139514// Track where we are in the nested structs. Items will migrate from9515// VisitStack to HistoryStack as we do the DFS for bad field.9516SmallVector<const FieldDecl *, 4> HistoryStack;9517HistoryStack.push_back(nullptr);95189519// At this point we already handled everything except of a RecordType or9520// an ArrayType of a RecordType.9521assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");9522const RecordType *RecTy =9523PT->getPointeeOrArrayElementType()->getAs<RecordType>();9524const RecordDecl *OrigRecDecl = RecTy->getDecl();95259526VisitStack.push_back(RecTy->getDecl());9527assert(VisitStack.back() && "First decl null?");95289529do {9530const Decl *Next = VisitStack.pop_back_val();9531if (!Next) {9532assert(!HistoryStack.empty());9533// Found a marker, we have gone up a level9534if (const FieldDecl *Hist = HistoryStack.pop_back_val())9535ValidTypes.insert(Hist->getType().getTypePtr());95369537continue;9538}95399540// Adds everything except the original parameter declaration (which is not a9541// field itself) to the history stack.9542const RecordDecl *RD;9543if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {9544HistoryStack.push_back(Field);95459546QualType FieldTy = Field->getType();9547// Other field types (known to be valid or invalid) are handled while we9548// walk around RecordDecl::fields().9549assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&9550"Unexpected type.");9551const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();95529553RD = FieldRecTy->castAs<RecordType>()->getDecl();9554} else {9555RD = cast<RecordDecl>(Next);9556}95579558// Add a null marker so we know when we've gone back up a level9559VisitStack.push_back(nullptr);95609561for (const auto *FD : RD->fields()) {9562QualType QT = FD->getType();95639564if (ValidTypes.count(QT.getTypePtr()))9565continue;95669567OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);9568if (ParamType == ValidKernelParam)9569continue;95709571if (ParamType == RecordKernelParam) {9572VisitStack.push_back(FD);9573continue;9574}95759576// OpenCL v1.2 s6.9.p:9577// Arguments to kernel functions that are declared to be a struct or union9578// do not allow OpenCL objects to be passed as elements of the struct or9579// union. This restriction was lifted in OpenCL v2.0 with the introduction9580// of SVM.9581if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||9582ParamType == InvalidAddrSpacePtrKernelParam) {9583S.Diag(Param->getLocation(),9584diag::err_record_with_pointers_kernel_param)9585<< PT->isUnionType()9586<< PT;9587} else {9588S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;9589}95909591S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)9592<< OrigRecDecl->getDeclName();95939594// We have an error, now let's go back up through history and show where9595// the offending field came from9596for (ArrayRef<const FieldDecl *>::const_iterator9597I = HistoryStack.begin() + 1,9598E = HistoryStack.end();9599I != E; ++I) {9600const FieldDecl *OuterField = *I;9601S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)9602<< OuterField->getType();9603}96049605S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)9606<< QT->isPointerType()9607<< QT;9608D.setInvalidType();9609return;9610}9611} while (!VisitStack.empty());9612}96139614/// Find the DeclContext in which a tag is implicitly declared if we see an9615/// elaborated type specifier in the specified context, and lookup finds9616/// nothing.9617static DeclContext *getTagInjectionContext(DeclContext *DC) {9618while (!DC->isFileContext() && !DC->isFunctionOrMethod())9619DC = DC->getParent();9620return DC;9621}96229623/// Find the Scope in which a tag is implicitly declared if we see an9624/// elaborated type specifier in the specified context, and lookup finds9625/// nothing.9626static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {9627while (S->isClassScope() ||9628(LangOpts.CPlusPlus &&9629S->isFunctionPrototypeScope()) ||9630((S->getFlags() & Scope::DeclScope) == 0) ||9631(S->getEntity() && S->getEntity()->isTransparentContext()))9632S = S->getParent();9633return S;9634}96359636/// Determine whether a declaration matches a known function in namespace std.9637static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,9638unsigned BuiltinID) {9639switch (BuiltinID) {9640case Builtin::BI__GetExceptionInfo:9641// No type checking whatsoever.9642return Ctx.getTargetInfo().getCXXABI().isMicrosoft();96439644case Builtin::BIaddressof:9645case Builtin::BI__addressof:9646case Builtin::BIforward:9647case Builtin::BIforward_like:9648case Builtin::BImove:9649case Builtin::BImove_if_noexcept:9650case Builtin::BIas_const: {9651// Ensure that we don't treat the algorithm9652// OutputIt std::move(InputIt, InputIt, OutputIt)9653// as the builtin std::move.9654const auto *FPT = FD->getType()->castAs<FunctionProtoType>();9655return FPT->getNumParams() == 1 && !FPT->isVariadic();9656}96579658default:9659return false;9660}9661}96629663NamedDecl*9664Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,9665TypeSourceInfo *TInfo, LookupResult &Previous,9666MultiTemplateParamsArg TemplateParamListsRef,9667bool &AddToScope) {9668QualType R = TInfo->getType();96699670assert(R->isFunctionType());9671if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())9672Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);96739674SmallVector<TemplateParameterList *, 4> TemplateParamLists;9675llvm::append_range(TemplateParamLists, TemplateParamListsRef);9676if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {9677if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&9678Invented->getDepth() == TemplateParamLists.back()->getDepth())9679TemplateParamLists.back() = Invented;9680else9681TemplateParamLists.push_back(Invented);9682}96839684// TODO: consider using NameInfo for diagnostic.9685DeclarationNameInfo NameInfo = GetNameForDeclarator(D);9686DeclarationName Name = NameInfo.getName();9687StorageClass SC = getFunctionStorageClass(*this, D);96889689if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())9690Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),9691diag::err_invalid_thread)9692<< DeclSpec::getSpecifierName(TSCS);96939694if (D.isFirstDeclarationOfMember())9695adjustMemberFunctionCC(9696R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),9697D.isCtorOrDtor(), D.getIdentifierLoc());96989699bool isFriend = false;9700FunctionTemplateDecl *FunctionTemplate = nullptr;9701bool isMemberSpecialization = false;9702bool isFunctionTemplateSpecialization = false;97039704bool HasExplicitTemplateArgs = false;9705TemplateArgumentListInfo TemplateArgs;97069707bool isVirtualOkay = false;97089709DeclContext *OriginalDC = DC;9710bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);97119712FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,9713isVirtualOkay);9714if (!NewFD) return nullptr;97159716if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())9717NewFD->setTopLevelDeclInObjCContainer();97189719// Set the lexical context. If this is a function-scope declaration, or has a9720// C++ scope specifier, or is the object of a friend declaration, the lexical9721// context will be different from the semantic context.9722NewFD->setLexicalDeclContext(CurContext);97239724if (IsLocalExternDecl)9725NewFD->setLocalExternDecl();97269727if (getLangOpts().CPlusPlus) {9728// The rules for implicit inlines changed in C++20 for methods and friends9729// with an in-class definition (when such a definition is not attached to9730// the global module). User-specified 'inline' overrides this (set when9731// the function decl is created above).9732// FIXME: We need a better way to separate C++ standard and clang modules.9733bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||9734NewFD->isConstexpr() || NewFD->isConsteval() ||9735!NewFD->getOwningModule() ||9736NewFD->isFromGlobalModule() ||9737NewFD->getOwningModule()->isHeaderLikeModule();9738bool isInline = D.getDeclSpec().isInlineSpecified();9739bool isVirtual = D.getDeclSpec().isVirtualSpecified();9740bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();9741isFriend = D.getDeclSpec().isFriendSpecified();9742if (isFriend && !isInline && D.isFunctionDefinition()) {9743// Pre-C++20 [class.friend]p59744// A function can be defined in a friend declaration of a9745// class . . . . Such a function is implicitly inline.9746// Post C++20 [class.friend]p79747// Such a function is implicitly an inline function if it is attached9748// to the global module.9749NewFD->setImplicitlyInline(ImplicitInlineCXX20);9750}97519752// If this is a method defined in an __interface, and is not a constructor9753// or an overloaded operator, then set the pure flag (isVirtual will already9754// return true).9755if (const CXXRecordDecl *Parent =9756dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {9757if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())9758NewFD->setIsPureVirtual(true);97599760// C++ [class.union]p29761// A union can have member functions, but not virtual functions.9762if (isVirtual && Parent->isUnion()) {9763Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);9764NewFD->setInvalidDecl();9765}9766if ((Parent->isClass() || Parent->isStruct()) &&9767Parent->hasAttr<SYCLSpecialClassAttr>() &&9768NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&9769NewFD->getName() == "__init" && D.isFunctionDefinition()) {9770if (auto *Def = Parent->getDefinition())9771Def->setInitMethod(true);9772}9773}97749775SetNestedNameSpecifier(*this, NewFD, D);9776isMemberSpecialization = false;9777isFunctionTemplateSpecialization = false;9778if (D.isInvalidType())9779NewFD->setInvalidDecl();97809781// Match up the template parameter lists with the scope specifier, then9782// determine whether we have a template or a template specialization.9783bool Invalid = false;9784TemplateIdAnnotation *TemplateId =9785D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId9786? D.getName().TemplateId9787: nullptr;9788TemplateParameterList *TemplateParams =9789MatchTemplateParametersToScopeSpecifier(9790D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),9791D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,9792isMemberSpecialization, Invalid);9793if (TemplateParams) {9794// Check that we can declare a template here.9795if (CheckTemplateDeclScope(S, TemplateParams))9796NewFD->setInvalidDecl();97979798if (TemplateParams->size() > 0) {9799// This is a function template98009801// A destructor cannot be a template.9802if (Name.getNameKind() == DeclarationName::CXXDestructorName) {9803Diag(NewFD->getLocation(), diag::err_destructor_template);9804NewFD->setInvalidDecl();9805// Function template with explicit template arguments.9806} else if (TemplateId) {9807Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)9808<< SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);9809NewFD->setInvalidDecl();9810}98119812// If we're adding a template to a dependent context, we may need to9813// rebuilding some of the types used within the template parameter list,9814// now that we know what the current instantiation is.9815if (DC->isDependentContext()) {9816ContextRAII SavedContext(*this, DC);9817if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))9818Invalid = true;9819}98209821FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,9822NewFD->getLocation(),9823Name, TemplateParams,9824NewFD);9825FunctionTemplate->setLexicalDeclContext(CurContext);9826NewFD->setDescribedFunctionTemplate(FunctionTemplate);98279828// For source fidelity, store the other template param lists.9829if (TemplateParamLists.size() > 1) {9830NewFD->setTemplateParameterListsInfo(Context,9831ArrayRef<TemplateParameterList *>(TemplateParamLists)9832.drop_back(1));9833}9834} else {9835// This is a function template specialization.9836isFunctionTemplateSpecialization = true;9837// For source fidelity, store all the template param lists.9838if (TemplateParamLists.size() > 0)9839NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);98409841// C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".9842if (isFriend) {9843// We want to remove the "template<>", found here.9844SourceRange RemoveRange = TemplateParams->getSourceRange();98459846// If we remove the template<> and the name is not a9847// template-id, we're actually silently creating a problem:9848// the friend declaration will refer to an untemplated decl,9849// and clearly the user wants a template specialization. So9850// we need to insert '<>' after the name.9851SourceLocation InsertLoc;9852if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {9853InsertLoc = D.getName().getSourceRange().getEnd();9854InsertLoc = getLocForEndOfToken(InsertLoc);9855}98569857Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)9858<< Name << RemoveRange9859<< FixItHint::CreateRemoval(RemoveRange)9860<< FixItHint::CreateInsertion(InsertLoc, "<>");9861Invalid = true;98629863// Recover by faking up an empty template argument list.9864HasExplicitTemplateArgs = true;9865TemplateArgs.setLAngleLoc(InsertLoc);9866TemplateArgs.setRAngleLoc(InsertLoc);9867}9868}9869} else {9870// Check that we can declare a template here.9871if (!TemplateParamLists.empty() && isMemberSpecialization &&9872CheckTemplateDeclScope(S, TemplateParamLists.back()))9873NewFD->setInvalidDecl();98749875// All template param lists were matched against the scope specifier:9876// this is NOT (an explicit specialization of) a template.9877if (TemplateParamLists.size() > 0)9878// For source fidelity, store all the template param lists.9879NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);98809881// "friend void foo<>(int);" is an implicit specialization decl.9882if (isFriend && TemplateId)9883isFunctionTemplateSpecialization = true;9884}98859886// If this is a function template specialization and the unqualified-id of9887// the declarator-id is a template-id, convert the template argument list9888// into our AST format and check for unexpanded packs.9889if (isFunctionTemplateSpecialization && TemplateId) {9890HasExplicitTemplateArgs = true;98919892TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);9893TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);9894ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),9895TemplateId->NumArgs);9896translateTemplateArguments(TemplateArgsPtr, TemplateArgs);98979898// FIXME: Should we check for unexpanded packs if this was an (invalid)9899// declaration of a function template partial specialization? Should we9900// consider the unexpanded pack context to be a partial specialization?9901for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {9902if (DiagnoseUnexpandedParameterPack(9903ArgLoc, isFriend ? UPPC_FriendDeclaration9904: UPPC_ExplicitSpecialization))9905NewFD->setInvalidDecl();9906}9907}99089909if (Invalid) {9910NewFD->setInvalidDecl();9911if (FunctionTemplate)9912FunctionTemplate->setInvalidDecl();9913}99149915// C++ [dcl.fct.spec]p5:9916// The virtual specifier shall only be used in declarations of9917// nonstatic class member functions that appear within a9918// member-specification of a class declaration; see 10.3.9919//9920if (isVirtual && !NewFD->isInvalidDecl()) {9921if (!isVirtualOkay) {9922Diag(D.getDeclSpec().getVirtualSpecLoc(),9923diag::err_virtual_non_function);9924} else if (!CurContext->isRecord()) {9925// 'virtual' was specified outside of the class.9926Diag(D.getDeclSpec().getVirtualSpecLoc(),9927diag::err_virtual_out_of_class)9928<< FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());9929} else if (NewFD->getDescribedFunctionTemplate()) {9930// C++ [temp.mem]p3:9931// A member function template shall not be virtual.9932Diag(D.getDeclSpec().getVirtualSpecLoc(),9933diag::err_virtual_member_function_template)9934<< FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());9935} else {9936// Okay: Add virtual to the method.9937NewFD->setVirtualAsWritten(true);9938}99399940if (getLangOpts().CPlusPlus14 &&9941NewFD->getReturnType()->isUndeducedType())9942Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);9943}99449945// C++ [dcl.fct.spec]p3:9946// The inline specifier shall not appear on a block scope function9947// declaration.9948if (isInline && !NewFD->isInvalidDecl()) {9949if (CurContext->isFunctionOrMethod()) {9950// 'inline' is not allowed on block scope function declaration.9951Diag(D.getDeclSpec().getInlineSpecLoc(),9952diag::err_inline_declaration_block_scope) << Name9953<< FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());9954}9955}99569957// C++ [dcl.fct.spec]p6:9958// The explicit specifier shall be used only in the declaration of a9959// constructor or conversion function within its class definition;9960// see 12.3.1 and 12.3.2.9961if (hasExplicit && !NewFD->isInvalidDecl() &&9962!isa<CXXDeductionGuideDecl>(NewFD)) {9963if (!CurContext->isRecord()) {9964// 'explicit' was specified outside of the class.9965Diag(D.getDeclSpec().getExplicitSpecLoc(),9966diag::err_explicit_out_of_class)9967<< FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());9968} else if (!isa<CXXConstructorDecl>(NewFD) &&9969!isa<CXXConversionDecl>(NewFD)) {9970// 'explicit' was specified on a function that wasn't a constructor9971// or conversion function.9972Diag(D.getDeclSpec().getExplicitSpecLoc(),9973diag::err_explicit_non_ctor_or_conv_function)9974<< FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());9975}9976}99779978ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();9979if (ConstexprKind != ConstexprSpecKind::Unspecified) {9980// C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors9981// are implicitly inline.9982NewFD->setImplicitlyInline();99839984// C++11 [dcl.constexpr]p3: functions declared constexpr are required to9985// be either constructors or to return a literal type. Therefore,9986// destructors cannot be declared constexpr.9987if (isa<CXXDestructorDecl>(NewFD) &&9988(!getLangOpts().CPlusPlus20 ||9989ConstexprKind == ConstexprSpecKind::Consteval)) {9990Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)9991<< static_cast<int>(ConstexprKind);9992NewFD->setConstexprKind(getLangOpts().CPlusPlus209993? ConstexprSpecKind::Unspecified9994: ConstexprSpecKind::Constexpr);9995}9996// C++20 [dcl.constexpr]p2: An allocation function, or a9997// deallocation function shall not be declared with the consteval9998// specifier.9999if (ConstexprKind == ConstexprSpecKind::Consteval &&10000(NewFD->getOverloadedOperator() == OO_New ||10001NewFD->getOverloadedOperator() == OO_Array_New ||10002NewFD->getOverloadedOperator() == OO_Delete ||10003NewFD->getOverloadedOperator() == OO_Array_Delete)) {10004Diag(D.getDeclSpec().getConstexprSpecLoc(),10005diag::err_invalid_consteval_decl_kind)10006<< NewFD;10007NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);10008}10009}1001010011// If __module_private__ was specified, mark the function accordingly.10012if (D.getDeclSpec().isModulePrivateSpecified()) {10013if (isFunctionTemplateSpecialization) {10014SourceLocation ModulePrivateLoc10015= D.getDeclSpec().getModulePrivateSpecLoc();10016Diag(ModulePrivateLoc, diag::err_module_private_specialization)10017<< 010018<< FixItHint::CreateRemoval(ModulePrivateLoc);10019} else {10020NewFD->setModulePrivate();10021if (FunctionTemplate)10022FunctionTemplate->setModulePrivate();10023}10024}1002510026if (isFriend) {10027if (FunctionTemplate) {10028FunctionTemplate->setObjectOfFriendDecl();10029FunctionTemplate->setAccess(AS_public);10030}10031NewFD->setObjectOfFriendDecl();10032NewFD->setAccess(AS_public);10033}1003410035// If a function is defined as defaulted or deleted, mark it as such now.10036// We'll do the relevant checks on defaulted / deleted functions later.10037switch (D.getFunctionDefinitionKind()) {10038case FunctionDefinitionKind::Declaration:10039case FunctionDefinitionKind::Definition:10040break;1004110042case FunctionDefinitionKind::Defaulted:10043NewFD->setDefaulted();10044break;1004510046case FunctionDefinitionKind::Deleted:10047NewFD->setDeletedAsWritten();10048break;10049}1005010051if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&10052D.isFunctionDefinition() && !isInline) {10053// Pre C++20 [class.mfct]p2:10054// A member function may be defined (8.4) in its class definition, in10055// which case it is an inline member function (7.1.2)10056// Post C++20 [class.mfct]p1:10057// If a member function is attached to the global module and is defined10058// in its class definition, it is inline.10059NewFD->setImplicitlyInline(ImplicitInlineCXX20);10060}1006110062if (!isFriend && SC != SC_None) {10063// C++ [temp.expl.spec]p2:10064// The declaration in an explicit-specialization shall not be an10065// export-declaration. An explicit specialization shall not use a10066// storage-class-specifier other than thread_local.10067//10068// We diagnose friend declarations with storage-class-specifiers10069// elsewhere.10070if (isFunctionTemplateSpecialization || isMemberSpecialization) {10071Diag(D.getDeclSpec().getStorageClassSpecLoc(),10072diag::ext_explicit_specialization_storage_class)10073<< FixItHint::CreateRemoval(10074D.getDeclSpec().getStorageClassSpecLoc());10075}1007610077if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {10078assert(isa<CXXMethodDecl>(NewFD) &&10079"Out-of-line member function should be a CXXMethodDecl");10080// C++ [class.static]p1:10081// A data or function member of a class may be declared static10082// in a class definition, in which case it is a static member of10083// the class.1008410085// Complain about the 'static' specifier if it's on an out-of-line10086// member function definition.1008710088// MSVC permits the use of a 'static' storage specifier on an10089// out-of-line member function template declaration and class member10090// template declaration (MSVC versions before 2015), warn about this.10091Diag(D.getDeclSpec().getStorageClassSpecLoc(),10092((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&10093cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||10094(getLangOpts().MSVCCompat &&10095NewFD->getDescribedFunctionTemplate()))10096? diag::ext_static_out_of_line10097: diag::err_static_out_of_line)10098<< FixItHint::CreateRemoval(10099D.getDeclSpec().getStorageClassSpecLoc());10100}10101}1010210103// C++11 [except.spec]p15:10104// A deallocation function with no exception-specification is treated10105// as if it were specified with noexcept(true).10106const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();10107if ((Name.getCXXOverloadedOperator() == OO_Delete ||10108Name.getCXXOverloadedOperator() == OO_Array_Delete) &&10109getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())10110NewFD->setType(Context.getFunctionType(10111FPT->getReturnType(), FPT->getParamTypes(),10112FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));1011310114// C++20 [dcl.inline]/710115// If an inline function or variable that is attached to a named module10116// is declared in a definition domain, it shall be defined in that10117// domain.10118// So, if the current declaration does not have a definition, we must10119// check at the end of the TU (or when the PMF starts) to see that we10120// have a definition at that point.10121if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&10122NewFD->isInNamedModule()) {10123PendingInlineFuncDecls.insert(NewFD);10124}10125}1012610127// Filter out previous declarations that don't match the scope.10128FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),10129D.getCXXScopeSpec().isNotEmpty() ||10130isMemberSpecialization ||10131isFunctionTemplateSpecialization);1013210133// Handle GNU asm-label extension (encoded as an attribute).10134if (Expr *E = (Expr*) D.getAsmLabel()) {10135// The parser guarantees this is a string.10136StringLiteral *SE = cast<StringLiteral>(E);10137NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),10138/*IsLiteralLabel=*/true,10139SE->getStrTokenLoc(0)));10140} else if (!ExtnameUndeclaredIdentifiers.empty()) {10141llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =10142ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());10143if (I != ExtnameUndeclaredIdentifiers.end()) {10144if (isDeclExternC(NewFD)) {10145NewFD->addAttr(I->second);10146ExtnameUndeclaredIdentifiers.erase(I);10147} else10148Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)10149<< /*Variable*/0 << NewFD;10150}10151}1015210153// Copy the parameter declarations from the declarator D to the function10154// declaration NewFD, if they are available. First scavenge them into Params.10155SmallVector<ParmVarDecl*, 16> Params;10156unsigned FTIIdx;10157if (D.isFunctionDeclarator(FTIIdx)) {10158DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;1015910160// Check for C99 6.7.5.3p10 - foo(void) is a non-varargs10161// function that takes no arguments, not a function that takes a10162// single void argument.10163// We let through "const void" here because Sema::GetTypeForDeclarator10164// already checks for that case.10165if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {10166for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {10167ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);10168assert(Param->getDeclContext() != NewFD && "Was set before ?");10169Param->setDeclContext(NewFD);10170Params.push_back(Param);1017110172if (Param->isInvalidDecl())10173NewFD->setInvalidDecl();10174}10175}1017610177if (!getLangOpts().CPlusPlus) {10178// In C, find all the tag declarations from the prototype and move them10179// into the function DeclContext. Remove them from the surrounding tag10180// injection context of the function, which is typically but not always10181// the TU.10182DeclContext *PrototypeTagContext =10183getTagInjectionContext(NewFD->getLexicalDeclContext());10184for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {10185auto *TD = dyn_cast<TagDecl>(NonParmDecl);1018610187// We don't want to reparent enumerators. Look at their parent enum10188// instead.10189if (!TD) {10190if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))10191TD = cast<EnumDecl>(ECD->getDeclContext());10192}10193if (!TD)10194continue;10195DeclContext *TagDC = TD->getLexicalDeclContext();10196if (!TagDC->containsDecl(TD))10197continue;10198TagDC->removeDecl(TD);10199TD->setDeclContext(NewFD);10200NewFD->addDecl(TD);1020110202// Preserve the lexical DeclContext if it is not the surrounding tag10203// injection context of the FD. In this example, the semantic context of10204// E will be f and the lexical context will be S, while both the10205// semantic and lexical contexts of S will be f:10206// void f(struct S { enum E { a } f; } s);10207if (TagDC != PrototypeTagContext)10208TD->setLexicalDeclContext(TagDC);10209}10210}10211} else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {10212// When we're declaring a function with a typedef, typeof, etc as in the10213// following example, we'll need to synthesize (unnamed)10214// parameters for use in the declaration.10215//10216// @code10217// typedef void fn(int);10218// fn f;10219// @endcode1022010221// Synthesize a parameter for each argument type.10222for (const auto &AI : FT->param_types()) {10223ParmVarDecl *Param =10224BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);10225Param->setScopeInfo(0, Params.size());10226Params.push_back(Param);10227}10228} else {10229assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&10230"Should not need args for typedef of non-prototype fn");10231}1023210233// Finally, we know we have the right number of parameters, install them.10234NewFD->setParams(Params);1023510236if (D.getDeclSpec().isNoreturnSpecified())10237NewFD->addAttr(10238C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));1023910240// Functions returning a variably modified type violate C99 6.7.5.2p210241// because all functions have linkage.10242if (!NewFD->isInvalidDecl() &&10243NewFD->getReturnType()->isVariablyModifiedType()) {10244Diag(NewFD->getLocation(), diag::err_vm_func_decl);10245NewFD->setInvalidDecl();10246}1024710248// Apply an implicit SectionAttr if '#pragma clang section text' is active10249if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&10250!NewFD->hasAttr<SectionAttr>())10251NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(10252Context, PragmaClangTextSection.SectionName,10253PragmaClangTextSection.PragmaLocation));1025410255// Apply an implicit SectionAttr if #pragma code_seg is active.10256if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&10257!NewFD->hasAttr<SectionAttr>()) {10258NewFD->addAttr(SectionAttr::CreateImplicit(10259Context, CodeSegStack.CurrentValue->getString(),10260CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));10261if (UnifySection(CodeSegStack.CurrentValue->getString(),10262ASTContext::PSF_Implicit | ASTContext::PSF_Execute |10263ASTContext::PSF_Read,10264NewFD))10265NewFD->dropAttr<SectionAttr>();10266}1026710268// Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is10269// active.10270if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&10271!NewFD->hasAttr<StrictGuardStackCheckAttr>())10272NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(10273Context, PragmaClangTextSection.PragmaLocation));1027410275// Apply an implicit CodeSegAttr from class declspec or10276// apply an implicit SectionAttr from #pragma code_seg if active.10277if (!NewFD->hasAttr<CodeSegAttr>()) {10278if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,10279D.isFunctionDefinition())) {10280NewFD->addAttr(SAttr);10281}10282}1028310284// Handle attributes.10285ProcessDeclAttributes(S, NewFD, D);10286const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();10287if (NewTVA && !NewTVA->isDefaultVersion() &&10288!Context.getTargetInfo().hasFeature("fmv")) {10289// Don't add to scope fmv functions declarations if fmv disabled10290AddToScope = false;10291return NewFD;10292}1029310294if (getLangOpts().OpenCL || getLangOpts().HLSL) {10295// Neither OpenCL nor HLSL allow an address space qualifyer on a return10296// type.10297//10298// OpenCL v1.1 s6.5: Using an address space qualifier in a function return10299// type declaration will generate a compilation error.10300LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();10301if (AddressSpace != LangAS::Default) {10302Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);10303NewFD->setInvalidDecl();10304}10305}1030610307if (!getLangOpts().CPlusPlus) {10308// Perform semantic checking on the function declaration.10309if (!NewFD->isInvalidDecl() && NewFD->isMain())10310CheckMain(NewFD, D.getDeclSpec());1031110312if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())10313CheckMSVCRTEntryPoint(NewFD);1031410315if (!NewFD->isInvalidDecl())10316D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,10317isMemberSpecialization,10318D.isFunctionDefinition()));10319else if (!Previous.empty())10320// Recover gracefully from an invalid redeclaration.10321D.setRedeclaration(true);10322assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||10323Previous.getResultKind() != LookupResult::FoundOverloaded) &&10324"previous declaration set still overloaded");1032510326// Diagnose no-prototype function declarations with calling conventions that10327// don't support variadic calls. Only do this in C and do it after merging10328// possibly prototyped redeclarations.10329const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();10330if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {10331CallingConv CC = FT->getExtInfo().getCC();10332if (!supportsVariadicCall(CC)) {10333// Windows system headers sometimes accidentally use stdcall without10334// (void) parameters, so we relax this to a warning.10335int DiagID =10336CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;10337Diag(NewFD->getLocation(), DiagID)10338<< FunctionType::getNameForCallConv(CC);10339}10340}1034110342if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||10343NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())10344checkNonTrivialCUnion(NewFD->getReturnType(),10345NewFD->getReturnTypeSourceRange().getBegin(),10346NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);10347} else {10348// C++11 [replacement.functions]p3:10349// The program's definitions shall not be specified as inline.10350//10351// N.B. We diagnose declarations instead of definitions per LWG issue 2340.10352//10353// Suppress the diagnostic if the function is __attribute__((used)), since10354// that forces an external definition to be emitted.10355if (D.getDeclSpec().isInlineSpecified() &&10356NewFD->isReplaceableGlobalAllocationFunction() &&10357!NewFD->hasAttr<UsedAttr>())10358Diag(D.getDeclSpec().getInlineSpecLoc(),10359diag::ext_operator_new_delete_declared_inline)10360<< NewFD->getDeclName();1036110362if (Expr *TRC = NewFD->getTrailingRequiresClause()) {10363// C++20 [dcl.decl.general]p4:10364// The optional requires-clause in an init-declarator or10365// member-declarator shall be present only if the declarator declares a10366// templated function.10367//10368// C++20 [temp.pre]p8:10369// An entity is templated if it is10370// - a template,10371// - an entity defined or created in a templated entity,10372// - a member of a templated entity,10373// - an enumerator for an enumeration that is a templated entity, or10374// - the closure type of a lambda-expression appearing in the10375// declaration of a templated entity.10376//10377// [Note 6: A local class, a local or block variable, or a friend10378// function defined in a templated entity is a templated entity.10379// — end note]10380//10381// A templated function is a function template or a function that is10382// templated. A templated class is a class template or a class that is10383// templated. A templated variable is a variable template or a variable10384// that is templated.10385if (!FunctionTemplate) {10386if (isFunctionTemplateSpecialization || isMemberSpecialization) {10387// C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):10388// An explicit specialization shall not have a trailing10389// requires-clause unless it declares a function template.10390//10391// Since a friend function template specialization cannot be10392// definition, and since a non-template friend declaration with a10393// trailing requires-clause must be a definition, we diagnose10394// friend function template specializations with trailing10395// requires-clauses on the same path as explicit specializations10396// even though they aren't necessarily prohibited by the same10397// language rule.10398Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)10399<< isFriend;10400} else if (isFriend && NewFD->isTemplated() &&10401!D.isFunctionDefinition()) {10402// C++ [temp.friend]p9:10403// A non-template friend declaration with a requires-clause shall be10404// a definition.10405Diag(NewFD->getBeginLoc(),10406diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);10407NewFD->setInvalidDecl();10408} else if (!NewFD->isTemplated() ||10409!(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {10410Diag(TRC->getBeginLoc(),10411diag::err_constrained_non_templated_function);10412}10413}10414}1041510416// We do not add HD attributes to specializations here because10417// they may have different constexpr-ness compared to their10418// templates and, after maybeAddHostDeviceAttrs() is applied,10419// may end up with different effective targets. Instead, a10420// specialization inherits its target attributes from its template10421// in the CheckFunctionTemplateSpecialization() call below.10422if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)10423CUDA().maybeAddHostDeviceAttrs(NewFD, Previous);1042410425// Handle explicit specializations of function templates10426// and friend function declarations with an explicit10427// template argument list.10428if (isFunctionTemplateSpecialization) {10429bool isDependentSpecialization = false;10430if (isFriend) {10431// For friend function specializations, this is a dependent10432// specialization if its semantic context is dependent, its10433// type is dependent, or if its template-id is dependent.10434isDependentSpecialization =10435DC->isDependentContext() || NewFD->getType()->isDependentType() ||10436(HasExplicitTemplateArgs &&10437TemplateSpecializationType::10438anyInstantiationDependentTemplateArguments(10439TemplateArgs.arguments()));10440assert((!isDependentSpecialization ||10441(HasExplicitTemplateArgs == isDependentSpecialization)) &&10442"dependent friend function specialization without template "10443"args");10444} else {10445// For class-scope explicit specializations of function templates,10446// if the lexical context is dependent, then the specialization10447// is dependent.10448isDependentSpecialization =10449CurContext->isRecord() && CurContext->isDependentContext();10450}1045110452TemplateArgumentListInfo *ExplicitTemplateArgs =10453HasExplicitTemplateArgs ? &TemplateArgs : nullptr;10454if (isDependentSpecialization) {10455// If it's a dependent specialization, it may not be possible10456// to determine the primary template (for explicit specializations)10457// or befriended declaration (for friends) until the enclosing10458// template is instantiated. In such cases, we store the declarations10459// found by name lookup and defer resolution until instantiation.10460if (CheckDependentFunctionTemplateSpecialization(10461NewFD, ExplicitTemplateArgs, Previous))10462NewFD->setInvalidDecl();10463} else if (!NewFD->isInvalidDecl()) {10464if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,10465Previous))10466NewFD->setInvalidDecl();10467}10468} else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {10469if (CheckMemberSpecialization(NewFD, Previous))10470NewFD->setInvalidDecl();10471}1047210473// Perform semantic checking on the function declaration.10474if (!NewFD->isInvalidDecl() && NewFD->isMain())10475CheckMain(NewFD, D.getDeclSpec());1047610477if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())10478CheckMSVCRTEntryPoint(NewFD);1047910480if (!NewFD->isInvalidDecl())10481D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,10482isMemberSpecialization,10483D.isFunctionDefinition()));10484else if (!Previous.empty())10485// Recover gracefully from an invalid redeclaration.10486D.setRedeclaration(true);1048710488assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||10489!D.isRedeclaration() ||10490Previous.getResultKind() != LookupResult::FoundOverloaded) &&10491"previous declaration set still overloaded");1049210493NamedDecl *PrincipalDecl = (FunctionTemplate10494? cast<NamedDecl>(FunctionTemplate)10495: NewFD);1049610497if (isFriend && NewFD->getPreviousDecl()) {10498AccessSpecifier Access = AS_public;10499if (!NewFD->isInvalidDecl())10500Access = NewFD->getPreviousDecl()->getAccess();1050110502NewFD->setAccess(Access);10503if (FunctionTemplate) FunctionTemplate->setAccess(Access);10504}1050510506if (NewFD->isOverloadedOperator() && !DC->isRecord() &&10507PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))10508PrincipalDecl->setNonMemberOperator();1050910510// If we have a function template, check the template parameter10511// list. This will check and merge default template arguments.10512if (FunctionTemplate) {10513FunctionTemplateDecl *PrevTemplate =10514FunctionTemplate->getPreviousDecl();10515CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),10516PrevTemplate ? PrevTemplate->getTemplateParameters()10517: nullptr,10518D.getDeclSpec().isFriendSpecified()10519? (D.isFunctionDefinition()10520? TPC_FriendFunctionTemplateDefinition10521: TPC_FriendFunctionTemplate)10522: (D.getCXXScopeSpec().isSet() &&10523DC && DC->isRecord() &&10524DC->isDependentContext())10525? TPC_ClassTemplateMember10526: TPC_FunctionTemplate);10527}1052810529if (NewFD->isInvalidDecl()) {10530// Ignore all the rest of this.10531} else if (!D.isRedeclaration()) {10532struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,10533AddToScope };10534// Fake up an access specifier if it's supposed to be a class member.10535if (isa<CXXRecordDecl>(NewFD->getDeclContext()))10536NewFD->setAccess(AS_public);1053710538// Qualified decls generally require a previous declaration.10539if (D.getCXXScopeSpec().isSet()) {10540// ...with the major exception of templated-scope or10541// dependent-scope friend declarations.1054210543// TODO: we currently also suppress this check in dependent10544// contexts because (1) the parameter depth will be off when10545// matching friend templates and (2) we might actually be10546// selecting a friend based on a dependent factor. But there10547// are situations where these conditions don't apply and we10548// can actually do this check immediately.10549//10550// Unless the scope is dependent, it's always an error if qualified10551// redeclaration lookup found nothing at all. Diagnose that now;10552// nothing will diagnose that error later.10553if (isFriend &&10554(D.getCXXScopeSpec().getScopeRep()->isDependent() ||10555(!Previous.empty() && CurContext->isDependentContext()))) {10556// ignore these10557} else if (NewFD->isCPUDispatchMultiVersion() ||10558NewFD->isCPUSpecificMultiVersion()) {10559// ignore this, we allow the redeclaration behavior here to create new10560// versions of the function.10561} else {10562// The user tried to provide an out-of-line definition for a10563// function that is a member of a class or namespace, but there10564// was no such member function declared (C++ [class.mfct]p2,10565// C++ [namespace.memdef]p2). For example:10566//10567// class X {10568// void f() const;10569// };10570//10571// void X::f() { } // ill-formed10572//10573// Complain about this problem, and attempt to suggest close10574// matches (e.g., those that differ only in cv-qualifiers and10575// whether the parameter types are references).1057610577if (NamedDecl *Result = DiagnoseInvalidRedeclaration(10578*this, Previous, NewFD, ExtraArgs, false, nullptr)) {10579AddToScope = ExtraArgs.AddToScope;10580return Result;10581}10582}1058310584// Unqualified local friend declarations are required to resolve10585// to something.10586} else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {10587if (NamedDecl *Result = DiagnoseInvalidRedeclaration(10588*this, Previous, NewFD, ExtraArgs, true, S)) {10589AddToScope = ExtraArgs.AddToScope;10590return Result;10591}10592}10593} else if (!D.isFunctionDefinition() &&10594isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&10595!isFriend && !isFunctionTemplateSpecialization &&10596!isMemberSpecialization) {10597// An out-of-line member function declaration must also be a10598// definition (C++ [class.mfct]p2).10599// Note that this is not the case for explicit specializations of10600// function templates or member functions of class templates, per10601// C++ [temp.expl.spec]p2. We also allow these declarations as an10602// extension for compatibility with old SWIG code which likes to10603// generate them.10604Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)10605<< D.getCXXScopeSpec().getRange();10606}10607}1060810609if (getLangOpts().HLSL && D.isFunctionDefinition()) {10610// Any top level function could potentially be specified as an entry.10611if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())10612HLSL().ActOnTopLevelFunction(NewFD);1061310614if (NewFD->hasAttr<HLSLShaderAttr>())10615HLSL().CheckEntryPoint(NewFD);10616}1061710618// If this is the first declaration of a library builtin function, add10619// attributes as appropriate.10620if (!D.isRedeclaration()) {10621if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {10622if (unsigned BuiltinID = II->getBuiltinID()) {10623bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);10624if (!InStdNamespace &&10625NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {10626if (NewFD->getLanguageLinkage() == CLanguageLinkage) {10627// Validate the type matches unless this builtin is specified as10628// matching regardless of its declared type.10629if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {10630NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));10631} else {10632ASTContext::GetBuiltinTypeError Error;10633LookupNecessaryTypesForBuiltin(S, BuiltinID);10634QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);1063510636if (!Error && !BuiltinType.isNull() &&10637Context.hasSameFunctionTypeIgnoringExceptionSpec(10638NewFD->getType(), BuiltinType))10639NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));10640}10641}10642} else if (InStdNamespace && NewFD->isInStdNamespace() &&10643isStdBuiltin(Context, NewFD, BuiltinID)) {10644NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));10645}10646}10647}10648}1064910650ProcessPragmaWeak(S, NewFD);10651checkAttributesAfterMerging(*this, *NewFD);1065210653AddKnownFunctionAttributes(NewFD);1065410655if (NewFD->hasAttr<OverloadableAttr>() &&10656!NewFD->getType()->getAs<FunctionProtoType>()) {10657Diag(NewFD->getLocation(),10658diag::err_attribute_overloadable_no_prototype)10659<< NewFD;10660NewFD->dropAttr<OverloadableAttr>();10661}1066210663// If there's a #pragma GCC visibility in scope, and this isn't a class10664// member, set the visibility of this function.10665if (!DC->isRecord() && NewFD->isExternallyVisible())10666AddPushedVisibilityAttribute(NewFD);1066710668// If there's a #pragma clang arc_cf_code_audited in scope, consider10669// marking the function.10670ObjC().AddCFAuditedAttribute(NewFD);1067110672// If this is a function definition, check if we have to apply any10673// attributes (i.e. optnone and no_builtin) due to a pragma.10674if (D.isFunctionDefinition()) {10675AddRangeBasedOptnone(NewFD);10676AddImplicitMSFunctionNoBuiltinAttr(NewFD);10677AddSectionMSAllocText(NewFD);10678ModifyFnAttributesMSPragmaOptimize(NewFD);10679}1068010681// If this is the first declaration of an extern C variable, update10682// the map of such variables.10683if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&10684isIncompleteDeclExternC(*this, NewFD))10685RegisterLocallyScopedExternCDecl(NewFD, S);1068610687// Set this FunctionDecl's range up to the right paren.10688NewFD->setRangeEnd(D.getSourceRange().getEnd());1068910690if (D.isRedeclaration() && !Previous.empty()) {10691NamedDecl *Prev = Previous.getRepresentativeDecl();10692checkDLLAttributeRedeclaration(*this, Prev, NewFD,10693isMemberSpecialization ||10694isFunctionTemplateSpecialization,10695D.isFunctionDefinition());10696}1069710698if (getLangOpts().CUDA) {10699IdentifierInfo *II = NewFD->getIdentifier();10700if (II && II->isStr(CUDA().getConfigureFuncName()) &&10701!NewFD->isInvalidDecl() &&10702NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {10703if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())10704Diag(NewFD->getLocation(), diag::err_config_scalar_return)10705<< CUDA().getConfigureFuncName();10706Context.setcudaConfigureCallDecl(NewFD);10707}1070810709// Variadic functions, other than a *declaration* of printf, are not allowed10710// in device-side CUDA code, unless someone passed10711// -fcuda-allow-variadic-functions.10712if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&10713(NewFD->hasAttr<CUDADeviceAttr>() ||10714NewFD->hasAttr<CUDAGlobalAttr>()) &&10715!(II && II->isStr("printf") && NewFD->isExternC() &&10716!D.isFunctionDefinition())) {10717Diag(NewFD->getLocation(), diag::err_variadic_device_fn);10718}10719}1072010721MarkUnusedFileScopedDecl(NewFD);10722107231072410725if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {10726// OpenCL v1.2 s6.8 static is invalid for kernel functions.10727if (SC == SC_Static) {10728Diag(D.getIdentifierLoc(), diag::err_static_kernel);10729D.setInvalidType();10730}1073110732// OpenCL v1.2, s6.9 -- Kernels can only have return type void.10733if (!NewFD->getReturnType()->isVoidType()) {10734SourceRange RTRange = NewFD->getReturnTypeSourceRange();10735Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)10736<< (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")10737: FixItHint());10738D.setInvalidType();10739}1074010741llvm::SmallPtrSet<const Type *, 16> ValidTypes;10742for (auto *Param : NewFD->parameters())10743checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);1074410745if (getLangOpts().OpenCLCPlusPlus) {10746if (DC->isRecord()) {10747Diag(D.getIdentifierLoc(), diag::err_method_kernel);10748D.setInvalidType();10749}10750if (FunctionTemplate) {10751Diag(D.getIdentifierLoc(), diag::err_template_kernel);10752D.setInvalidType();10753}10754}10755}1075610757if (getLangOpts().CPlusPlus) {10758// Precalculate whether this is a friend function template with a constraint10759// that depends on an enclosing template, per [temp.friend]p9.10760if (isFriend && FunctionTemplate &&10761FriendConstraintsDependOnEnclosingTemplate(NewFD)) {10762NewFD->setFriendConstraintRefersToEnclosingTemplate(true);1076310764// C++ [temp.friend]p9:10765// A friend function template with a constraint that depends on a10766// template parameter from an enclosing template shall be a definition.10767if (!D.isFunctionDefinition()) {10768Diag(NewFD->getBeginLoc(),10769diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);10770NewFD->setInvalidDecl();10771}10772}1077310774if (FunctionTemplate) {10775if (NewFD->isInvalidDecl())10776FunctionTemplate->setInvalidDecl();10777return FunctionTemplate;10778}1077910780if (isMemberSpecialization && !NewFD->isInvalidDecl())10781CompleteMemberSpecialization(NewFD, Previous);10782}1078310784for (const ParmVarDecl *Param : NewFD->parameters()) {10785QualType PT = Param->getType();1078610787// OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value10788// types.10789if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {10790if(const PipeType *PipeTy = PT->getAs<PipeType>()) {10791QualType ElemTy = PipeTy->getElementType();10792if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {10793Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );10794D.setInvalidType();10795}10796}10797}10798// WebAssembly tables can't be used as function parameters.10799if (Context.getTargetInfo().getTriple().isWasm()) {10800if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {10801Diag(Param->getTypeSpecStartLoc(),10802diag::err_wasm_table_as_function_parameter);10803D.setInvalidType();10804}10805}10806}1080710808// Diagnose availability attributes. Availability cannot be used on functions10809// that are run during load/unload.10810if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {10811if (NewFD->hasAttr<ConstructorAttr>()) {10812Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)10813<< 1;10814NewFD->dropAttr<AvailabilityAttr>();10815}10816if (NewFD->hasAttr<DestructorAttr>()) {10817Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)10818<< 2;10819NewFD->dropAttr<AvailabilityAttr>();10820}10821}1082210823// Diagnose no_builtin attribute on function declaration that are not a10824// definition.10825// FIXME: We should really be doing this in10826// SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to10827// the FunctionDecl and at this point of the code10828// FunctionDecl::isThisDeclarationADefinition() which always returns `false`10829// because Sema::ActOnStartOfFunctionDef has not been called yet.10830if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())10831switch (D.getFunctionDefinitionKind()) {10832case FunctionDefinitionKind::Defaulted:10833case FunctionDefinitionKind::Deleted:10834Diag(NBA->getLocation(),10835diag::err_attribute_no_builtin_on_defaulted_deleted_function)10836<< NBA->getSpelling();10837break;10838case FunctionDefinitionKind::Declaration:10839Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)10840<< NBA->getSpelling();10841break;10842case FunctionDefinitionKind::Definition:10843break;10844}1084510846// Similar to no_builtin logic above, at this point of the code10847// FunctionDecl::isThisDeclarationADefinition() always returns `false`10848// because Sema::ActOnStartOfFunctionDef has not been called yet.10849if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&10850!NewFD->isInvalidDecl() &&10851D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)10852ExternalDeclarations.push_back(NewFD);1085310854return NewFD;10855}1085610857/// Return a CodeSegAttr from a containing class. The Microsoft docs say10858/// when __declspec(code_seg) "is applied to a class, all member functions of10859/// the class and nested classes -- this includes compiler-generated special10860/// member functions -- are put in the specified segment."10861/// The actual behavior is a little more complicated. The Microsoft compiler10862/// won't check outer classes if there is an active value from #pragma code_seg.10863/// The CodeSeg is always applied from the direct parent but only from outer10864/// classes when the #pragma code_seg stack is empty. See:10865/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer10866/// available since MS has removed the page.10867static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {10868const auto *Method = dyn_cast<CXXMethodDecl>(FD);10869if (!Method)10870return nullptr;10871const CXXRecordDecl *Parent = Method->getParent();10872if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {10873Attr *NewAttr = SAttr->clone(S.getASTContext());10874NewAttr->setImplicit(true);10875return NewAttr;10876}1087710878// The Microsoft compiler won't check outer classes for the CodeSeg10879// when the #pragma code_seg stack is active.10880if (S.CodeSegStack.CurrentValue)10881return nullptr;1088210883while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {10884if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {10885Attr *NewAttr = SAttr->clone(S.getASTContext());10886NewAttr->setImplicit(true);10887return NewAttr;10888}10889}10890return nullptr;10891}1089210893Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,10894bool IsDefinition) {10895if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))10896return A;10897if (!FD->hasAttr<SectionAttr>() && IsDefinition &&10898CodeSegStack.CurrentValue)10899return SectionAttr::CreateImplicit(10900getASTContext(), CodeSegStack.CurrentValue->getString(),10901CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);10902return nullptr;10903}1090410905bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,10906QualType NewT, QualType OldT) {10907if (!NewD->getLexicalDeclContext()->isDependentContext())10908return true;1090910910// For dependently-typed local extern declarations and friends, we can't10911// perform a correct type check in general until instantiation:10912//10913// int f();10914// template<typename T> void g() { T f(); }10915//10916// (valid if g() is only instantiated with T = int).10917if (NewT->isDependentType() &&10918(NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))10919return false;1092010921// Similarly, if the previous declaration was a dependent local extern10922// declaration, we don't really know its type yet.10923if (OldT->isDependentType() && OldD->isLocalExternDecl())10924return false;1092510926return true;10927}1092810929bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {10930if (!D->getLexicalDeclContext()->isDependentContext())10931return true;1093210933// Don't chain dependent friend function definitions until instantiation, to10934// permit cases like10935//10936// void func();10937// template<typename T> class C1 { friend void func() {} };10938// template<typename T> class C2 { friend void func() {} };10939//10940// ... which is valid if only one of C1 and C2 is ever instantiated.10941//10942// FIXME: This need only apply to function definitions. For now, we proxy10943// this by checking for a file-scope function. We do not want this to apply10944// to friend declarations nominating member functions, because that gets in10945// the way of access checks.10946if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())10947return false;1094810949auto *VD = dyn_cast<ValueDecl>(D);10950auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);10951return !VD || !PrevVD ||10952canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),10953PrevVD->getType());10954}1095510956/// Check the target or target_version attribute of the function for10957/// MultiVersion validity.10958///10959/// Returns true if there was an error, false otherwise.10960static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {10961const auto *TA = FD->getAttr<TargetAttr>();10962const auto *TVA = FD->getAttr<TargetVersionAttr>();10963assert(10964(TA || TVA) &&10965"MultiVersion candidate requires a target or target_version attribute");10966const TargetInfo &TargetInfo = S.Context.getTargetInfo();10967enum ErrType { Feature = 0, Architecture = 1 };1096810969if (TA) {10970ParsedTargetAttr ParseInfo =10971S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());10972if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {10973S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)10974<< Architecture << ParseInfo.CPU;10975return true;10976}10977for (const auto &Feat : ParseInfo.Features) {10978auto BareFeat = StringRef{Feat}.substr(1);10979if (Feat[0] == '-') {10980S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)10981<< Feature << ("no-" + BareFeat).str();10982return true;10983}1098410985if (!TargetInfo.validateCpuSupports(BareFeat) ||10986!TargetInfo.isValidFeatureName(BareFeat)) {10987S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)10988<< Feature << BareFeat;10989return true;10990}10991}10992}1099310994if (TVA) {10995llvm::SmallVector<StringRef, 8> Feats;10996TVA->getFeatures(Feats);10997for (const auto &Feat : Feats) {10998if (!TargetInfo.validateCpuSupports(Feat)) {10999S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)11000<< Feature << Feat;11001return true;11002}11003}11004}11005return false;11006}1100711008// Provide a white-list of attributes that are allowed to be combined with11009// multiversion functions.11010static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,11011MultiVersionKind MVKind) {11012// Note: this list/diagnosis must match the list in11013// checkMultiversionAttributesAllSame.11014switch (Kind) {11015default:11016return false;11017case attr::ArmLocallyStreaming:11018return MVKind == MultiVersionKind::TargetVersion ||11019MVKind == MultiVersionKind::TargetClones;11020case attr::Used:11021return MVKind == MultiVersionKind::Target;11022case attr::NonNull:11023case attr::NoThrow:11024return true;11025}11026}1102711028static bool checkNonMultiVersionCompatAttributes(Sema &S,11029const FunctionDecl *FD,11030const FunctionDecl *CausedFD,11031MultiVersionKind MVKind) {11032const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {11033S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)11034<< static_cast<unsigned>(MVKind) << A;11035if (CausedFD)11036S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);11037return true;11038};1103911040for (const Attr *A : FD->attrs()) {11041switch (A->getKind()) {11042case attr::CPUDispatch:11043case attr::CPUSpecific:11044if (MVKind != MultiVersionKind::CPUDispatch &&11045MVKind != MultiVersionKind::CPUSpecific)11046return Diagnose(S, A);11047break;11048case attr::Target:11049if (MVKind != MultiVersionKind::Target)11050return Diagnose(S, A);11051break;11052case attr::TargetVersion:11053if (MVKind != MultiVersionKind::TargetVersion &&11054MVKind != MultiVersionKind::TargetClones)11055return Diagnose(S, A);11056break;11057case attr::TargetClones:11058if (MVKind != MultiVersionKind::TargetClones &&11059MVKind != MultiVersionKind::TargetVersion)11060return Diagnose(S, A);11061break;11062default:11063if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))11064return Diagnose(S, A);11065break;11066}11067}11068return false;11069}1107011071bool Sema::areMultiversionVariantFunctionsCompatible(11072const FunctionDecl *OldFD, const FunctionDecl *NewFD,11073const PartialDiagnostic &NoProtoDiagID,11074const PartialDiagnosticAt &NoteCausedDiagIDAt,11075const PartialDiagnosticAt &NoSupportDiagIDAt,11076const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,11077bool ConstexprSupported, bool CLinkageMayDiffer) {11078enum DoesntSupport {11079FuncTemplates = 0,11080VirtFuncs = 1,11081DeducedReturn = 2,11082Constructors = 3,11083Destructors = 4,11084DeletedFuncs = 5,11085DefaultedFuncs = 6,11086ConstexprFuncs = 7,11087ConstevalFuncs = 8,11088Lambda = 9,11089};11090enum Different {11091CallingConv = 0,11092ReturnType = 1,11093ConstexprSpec = 2,11094InlineSpec = 3,11095Linkage = 4,11096LanguageLinkage = 5,11097};1109811099if (NoProtoDiagID.getDiagID() != 0 && OldFD &&11100!OldFD->getType()->getAs<FunctionProtoType>()) {11101Diag(OldFD->getLocation(), NoProtoDiagID);11102Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);11103return true;11104}1110511106if (NoProtoDiagID.getDiagID() != 0 &&11107!NewFD->getType()->getAs<FunctionProtoType>())11108return Diag(NewFD->getLocation(), NoProtoDiagID);1110911110if (!TemplatesSupported &&11111NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)11112return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11113<< FuncTemplates;1111411115if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {11116if (NewCXXFD->isVirtual())11117return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11118<< VirtFuncs;1111911120if (isa<CXXConstructorDecl>(NewCXXFD))11121return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11122<< Constructors;1112311124if (isa<CXXDestructorDecl>(NewCXXFD))11125return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11126<< Destructors;11127}1112811129if (NewFD->isDeleted())11130return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11131<< DeletedFuncs;1113211133if (NewFD->isDefaulted())11134return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11135<< DefaultedFuncs;1113611137if (!ConstexprSupported && NewFD->isConstexpr())11138return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11139<< (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);1114011141QualType NewQType = Context.getCanonicalType(NewFD->getType());11142const auto *NewType = cast<FunctionType>(NewQType);11143QualType NewReturnType = NewType->getReturnType();1114411145if (NewReturnType->isUndeducedType())11146return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11147<< DeducedReturn;1114811149// Ensure the return type is identical.11150if (OldFD) {11151QualType OldQType = Context.getCanonicalType(OldFD->getType());11152const auto *OldType = cast<FunctionType>(OldQType);11153FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();11154FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();1115511156const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();11157const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();1115811159bool ArmStreamingCCMismatched = false;11160if (OldFPT && NewFPT) {11161unsigned Diff =11162OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();11163// Arm-streaming, arm-streaming-compatible and non-streaming versions11164// cannot be mixed.11165if (Diff & (FunctionType::SME_PStateSMEnabledMask |11166FunctionType::SME_PStateSMCompatibleMask))11167ArmStreamingCCMismatched = true;11168}1116911170if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)11171return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;1117211173QualType OldReturnType = OldType->getReturnType();1117411175if (OldReturnType != NewReturnType)11176return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;1117711178if (OldFD->getConstexprKind() != NewFD->getConstexprKind())11179return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;1118011181if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())11182return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;1118311184if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())11185return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;1118611187if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())11188return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;1118911190if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,11191NewFD->getLocation()))11192return true;11193}11194return false;11195}1119611197static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,11198const FunctionDecl *NewFD,11199bool CausesMV,11200MultiVersionKind MVKind) {11201if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {11202S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);11203if (OldFD)11204S.Diag(OldFD->getLocation(), diag::note_previous_declaration);11205return true;11206}1120711208bool IsCPUSpecificCPUDispatchMVKind =11209MVKind == MultiVersionKind::CPUDispatch ||11210MVKind == MultiVersionKind::CPUSpecific;1121111212if (CausesMV && OldFD &&11213checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))11214return true;1121511216if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))11217return true;1121811219// Only allow transition to MultiVersion if it hasn't been used.11220if (OldFD && CausesMV && OldFD->isUsed(false))11221return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);1122211223return S.areMultiversionVariantFunctionsCompatible(11224OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),11225PartialDiagnosticAt(NewFD->getLocation(),11226S.PDiag(diag::note_multiversioning_caused_here)),11227PartialDiagnosticAt(NewFD->getLocation(),11228S.PDiag(diag::err_multiversion_doesnt_support)11229<< static_cast<unsigned>(MVKind)),11230PartialDiagnosticAt(NewFD->getLocation(),11231S.PDiag(diag::err_multiversion_diff)),11232/*TemplatesSupported=*/false,11233/*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,11234/*CLinkageMayDiffer=*/false);11235}1123611237/// Check the validity of a multiversion function declaration that is the11238/// first of its kind. Also sets the multiversion'ness' of the function itself.11239///11240/// This sets NewFD->isInvalidDecl() to true if there was an error.11241///11242/// Returns true if there was an error, false otherwise.11243static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {11244MultiVersionKind MVKind = FD->getMultiVersionKind();11245assert(MVKind != MultiVersionKind::None &&11246"Function lacks multiversion attribute");11247const auto *TA = FD->getAttr<TargetAttr>();11248const auto *TVA = FD->getAttr<TargetVersionAttr>();11249// The target attribute only causes MV if this declaration is the default,11250// otherwise it is treated as a normal function.11251if (TA && !TA->isDefaultVersion())11252return false;11253// The target_version attribute only causes Multiversioning if this11254// declaration is NOT the default version.11255if (TVA && TVA->isDefaultVersion())11256return false;1125711258if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {11259FD->setInvalidDecl();11260return true;11261}1126211263if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {11264FD->setInvalidDecl();11265return true;11266}1126711268FD->setIsMultiVersion();11269return false;11270}1127111272static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {11273for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {11274if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)11275return true;11276}1127711278return false;11279}1128011281static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {11282if (!From->getASTContext().getTargetInfo().getTriple().isAArch64())11283return;1128411285MultiVersionKind MVKindFrom = From->getMultiVersionKind();11286MultiVersionKind MVKindTo = To->getMultiVersionKind();1128711288if (MVKindTo == MultiVersionKind::None &&11289(MVKindFrom == MultiVersionKind::TargetVersion ||11290MVKindFrom == MultiVersionKind::TargetClones))11291To->addAttr(TargetVersionAttr::CreateImplicit(11292To->getASTContext(), "default", To->getSourceRange()));11293}1129411295static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,11296FunctionDecl *NewFD,11297bool &Redeclaration,11298NamedDecl *&OldDecl,11299LookupResult &Previous) {11300assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");1130111302// The definitions should be allowed in any order. If we have discovered11303// a new target version and the preceeding was the default, then add the11304// corresponding attribute to it.11305patchDefaultTargetVersion(NewFD, OldFD);1130611307const auto *NewTA = NewFD->getAttr<TargetAttr>();11308const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();11309const auto *OldTA = OldFD->getAttr<TargetAttr>();1131011311// If the old decl is NOT MultiVersioned yet, and we don't cause that11312// to change, this is a simple redeclaration.11313if (NewTA && !NewTA->isDefaultVersion() &&11314(!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))11315return false;1131611317// The target_version attribute only causes Multiversioning if this11318// declaration is NOT the default version.11319if (NewTVA && NewTVA->isDefaultVersion())11320return false;1132111322// Otherwise, this decl causes MultiVersioning.11323if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,11324NewTVA ? MultiVersionKind::TargetVersion11325: MultiVersionKind::Target)) {11326NewFD->setInvalidDecl();11327return true;11328}1132911330if (CheckMultiVersionValue(S, NewFD)) {11331NewFD->setInvalidDecl();11332return true;11333}1133411335// If this is 'default', permit the forward declaration.11336if (NewTA && NewTA->isDefaultVersion() && !OldTA) {11337Redeclaration = true;11338OldDecl = OldFD;11339OldFD->setIsMultiVersion();11340NewFD->setIsMultiVersion();11341return false;11342}1134311344if (CheckMultiVersionValue(S, OldFD)) {11345S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);11346NewFD->setInvalidDecl();11347return true;11348}1134911350if (NewTA) {11351ParsedTargetAttr OldParsed =11352S.getASTContext().getTargetInfo().parseTargetAttr(11353OldTA->getFeaturesStr());11354llvm::sort(OldParsed.Features);11355ParsedTargetAttr NewParsed =11356S.getASTContext().getTargetInfo().parseTargetAttr(11357NewTA->getFeaturesStr());11358// Sort order doesn't matter, it just needs to be consistent.11359llvm::sort(NewParsed.Features);11360if (OldParsed == NewParsed) {11361S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);11362S.Diag(OldFD->getLocation(), diag::note_previous_declaration);11363NewFD->setInvalidDecl();11364return true;11365}11366}1136711368for (const auto *FD : OldFD->redecls()) {11369const auto *CurTA = FD->getAttr<TargetAttr>();11370const auto *CurTVA = FD->getAttr<TargetVersionAttr>();11371// We allow forward declarations before ANY multiversioning attributes, but11372// nothing after the fact.11373if (PreviousDeclsHaveMultiVersionAttribute(FD) &&11374((NewTA && (!CurTA || CurTA->isInherited())) ||11375(NewTVA && (!CurTVA || CurTVA->isInherited())))) {11376S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)11377<< (NewTA ? 0 : 2);11378S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);11379NewFD->setInvalidDecl();11380return true;11381}11382}1138311384OldFD->setIsMultiVersion();11385NewFD->setIsMultiVersion();11386Redeclaration = false;11387OldDecl = nullptr;11388Previous.clear();11389return false;11390}1139111392static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {11393MultiVersionKind OldKind = Old->getMultiVersionKind();11394MultiVersionKind NewKind = New->getMultiVersionKind();1139511396if (OldKind == NewKind || OldKind == MultiVersionKind::None ||11397NewKind == MultiVersionKind::None)11398return true;1139911400if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {11401switch (OldKind) {11402case MultiVersionKind::TargetVersion:11403return NewKind == MultiVersionKind::TargetClones;11404case MultiVersionKind::TargetClones:11405return NewKind == MultiVersionKind::TargetVersion;11406default:11407return false;11408}11409} else {11410switch (OldKind) {11411case MultiVersionKind::CPUDispatch:11412return NewKind == MultiVersionKind::CPUSpecific;11413case MultiVersionKind::CPUSpecific:11414return NewKind == MultiVersionKind::CPUDispatch;11415default:11416return false;11417}11418}11419}1142011421/// Check the validity of a new function declaration being added to an existing11422/// multiversioned declaration collection.11423static bool CheckMultiVersionAdditionalDecl(11424Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,11425const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,11426const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,11427LookupResult &Previous) {1142811429// Disallow mixing of multiversioning types.11430if (!MultiVersionTypesCompatible(OldFD, NewFD)) {11431S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);11432S.Diag(OldFD->getLocation(), diag::note_previous_declaration);11433NewFD->setInvalidDecl();11434return true;11435}1143611437// Add the default target_version attribute if it's missing.11438patchDefaultTargetVersion(OldFD, NewFD);11439patchDefaultTargetVersion(NewFD, OldFD);1144011441const auto *NewTA = NewFD->getAttr<TargetAttr>();11442const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();11443MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();11444[[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();1144511446ParsedTargetAttr NewParsed;11447if (NewTA) {11448NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(11449NewTA->getFeaturesStr());11450llvm::sort(NewParsed.Features);11451}11452llvm::SmallVector<StringRef, 8> NewFeats;11453if (NewTVA) {11454NewTVA->getFeatures(NewFeats);11455llvm::sort(NewFeats);11456}1145711458bool UseMemberUsingDeclRules =11459S.CurContext->isRecord() && !NewFD->getFriendObjectKind();1146011461bool MayNeedOverloadableChecks =11462AllowOverloadingOfFunction(Previous, S.Context, NewFD);1146311464// Next, check ALL non-invalid non-overloads to see if this is a redeclaration11465// of a previous member of the MultiVersion set.11466for (NamedDecl *ND : Previous) {11467FunctionDecl *CurFD = ND->getAsFunction();11468if (!CurFD || CurFD->isInvalidDecl())11469continue;11470if (MayNeedOverloadableChecks &&11471S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))11472continue;1147311474switch (NewMVKind) {11475case MultiVersionKind::None:11476assert(OldMVKind == MultiVersionKind::TargetClones &&11477"Only target_clones can be omitted in subsequent declarations");11478break;11479case MultiVersionKind::Target: {11480const auto *CurTA = CurFD->getAttr<TargetAttr>();11481if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {11482NewFD->setIsMultiVersion();11483Redeclaration = true;11484OldDecl = ND;11485return false;11486}1148711488ParsedTargetAttr CurParsed =11489S.getASTContext().getTargetInfo().parseTargetAttr(11490CurTA->getFeaturesStr());11491llvm::sort(CurParsed.Features);11492if (CurParsed == NewParsed) {11493S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);11494S.Diag(CurFD->getLocation(), diag::note_previous_declaration);11495NewFD->setInvalidDecl();11496return true;11497}11498break;11499}11500case MultiVersionKind::TargetVersion: {11501if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {11502if (CurTVA->getName() == NewTVA->getName()) {11503NewFD->setIsMultiVersion();11504Redeclaration = true;11505OldDecl = ND;11506return false;11507}11508llvm::SmallVector<StringRef, 8> CurFeats;11509CurTVA->getFeatures(CurFeats);11510llvm::sort(CurFeats);1151111512if (CurFeats == NewFeats) {11513S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);11514S.Diag(CurFD->getLocation(), diag::note_previous_declaration);11515NewFD->setInvalidDecl();11516return true;11517}11518} else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {11519// Default11520if (NewFeats.empty())11521break;1152211523for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {11524llvm::SmallVector<StringRef, 8> CurFeats;11525CurClones->getFeatures(CurFeats, I);11526llvm::sort(CurFeats);1152711528if (CurFeats == NewFeats) {11529S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);11530S.Diag(CurFD->getLocation(), diag::note_previous_declaration);11531NewFD->setInvalidDecl();11532return true;11533}11534}11535}11536break;11537}11538case MultiVersionKind::TargetClones: {11539assert(NewClones && "MultiVersionKind does not match attribute type");11540if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {11541if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||11542!std::equal(CurClones->featuresStrs_begin(),11543CurClones->featuresStrs_end(),11544NewClones->featuresStrs_begin())) {11545S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);11546S.Diag(CurFD->getLocation(), diag::note_previous_declaration);11547NewFD->setInvalidDecl();11548return true;11549}11550} else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {11551llvm::SmallVector<StringRef, 8> CurFeats;11552CurTVA->getFeatures(CurFeats);11553llvm::sort(CurFeats);1155411555// Default11556if (CurFeats.empty())11557break;1155811559for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {11560NewFeats.clear();11561NewClones->getFeatures(NewFeats, I);11562llvm::sort(NewFeats);1156311564if (CurFeats == NewFeats) {11565S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);11566S.Diag(CurFD->getLocation(), diag::note_previous_declaration);11567NewFD->setInvalidDecl();11568return true;11569}11570}11571break;11572}11573Redeclaration = true;11574OldDecl = CurFD;11575NewFD->setIsMultiVersion();11576return false;11577}11578case MultiVersionKind::CPUSpecific:11579case MultiVersionKind::CPUDispatch: {11580const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();11581const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();11582// Handle CPUDispatch/CPUSpecific versions.11583// Only 1 CPUDispatch function is allowed, this will make it go through11584// the redeclaration errors.11585if (NewMVKind == MultiVersionKind::CPUDispatch &&11586CurFD->hasAttr<CPUDispatchAttr>()) {11587if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&11588std::equal(11589CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),11590NewCPUDisp->cpus_begin(),11591[](const IdentifierInfo *Cur, const IdentifierInfo *New) {11592return Cur->getName() == New->getName();11593})) {11594NewFD->setIsMultiVersion();11595Redeclaration = true;11596OldDecl = ND;11597return false;11598}1159911600// If the declarations don't match, this is an error condition.11601S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);11602S.Diag(CurFD->getLocation(), diag::note_previous_declaration);11603NewFD->setInvalidDecl();11604return true;11605}11606if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {11607if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&11608std::equal(11609CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),11610NewCPUSpec->cpus_begin(),11611[](const IdentifierInfo *Cur, const IdentifierInfo *New) {11612return Cur->getName() == New->getName();11613})) {11614NewFD->setIsMultiVersion();11615Redeclaration = true;11616OldDecl = ND;11617return false;11618}1161911620// Only 1 version of CPUSpecific is allowed for each CPU.11621for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {11622for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {11623if (CurII == NewII) {11624S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)11625<< NewII;11626S.Diag(CurFD->getLocation(), diag::note_previous_declaration);11627NewFD->setInvalidDecl();11628return true;11629}11630}11631}11632}11633break;11634}11635}11636}1163711638// Else, this is simply a non-redecl case. Checking the 'value' is only11639// necessary in the Target case, since The CPUSpecific/Dispatch cases are11640// handled in the attribute adding step.11641if ((NewMVKind == MultiVersionKind::TargetVersion ||11642NewMVKind == MultiVersionKind::Target) &&11643CheckMultiVersionValue(S, NewFD)) {11644NewFD->setInvalidDecl();11645return true;11646}1164711648if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,11649!OldFD->isMultiVersion(), NewMVKind)) {11650NewFD->setInvalidDecl();11651return true;11652}1165311654// Permit forward declarations in the case where these two are compatible.11655if (!OldFD->isMultiVersion()) {11656OldFD->setIsMultiVersion();11657NewFD->setIsMultiVersion();11658Redeclaration = true;11659OldDecl = OldFD;11660return false;11661}1166211663NewFD->setIsMultiVersion();11664Redeclaration = false;11665OldDecl = nullptr;11666Previous.clear();11667return false;11668}1166911670/// Check the validity of a mulitversion function declaration.11671/// Also sets the multiversion'ness' of the function itself.11672///11673/// This sets NewFD->isInvalidDecl() to true if there was an error.11674///11675/// Returns true if there was an error, false otherwise.11676static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,11677bool &Redeclaration, NamedDecl *&OldDecl,11678LookupResult &Previous) {11679const auto *NewTA = NewFD->getAttr<TargetAttr>();11680const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();11681const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();11682const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();11683const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();11684MultiVersionKind MVKind = NewFD->getMultiVersionKind();1168511686// Main isn't allowed to become a multiversion function, however it IS11687// permitted to have 'main' be marked with the 'target' optimization hint,11688// for 'target_version' only default is allowed.11689if (NewFD->isMain()) {11690if (MVKind != MultiVersionKind::None &&11691!(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&11692!(MVKind == MultiVersionKind::TargetVersion &&11693NewTVA->isDefaultVersion())) {11694S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);11695NewFD->setInvalidDecl();11696return true;11697}11698return false;11699}1170011701const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();1170211703// Target attribute on AArch64 is not used for multiversioning11704if (NewTA && T.isAArch64())11705return false;1170611707// Target attribute on RISCV is not used for multiversioning11708if (NewTA && T.isRISCV())11709return false;1171011711if (!OldDecl || !OldDecl->getAsFunction() ||11712!OldDecl->getDeclContext()->getRedeclContext()->Equals(11713NewFD->getDeclContext()->getRedeclContext())) {11714// If there's no previous declaration, AND this isn't attempting to cause11715// multiversioning, this isn't an error condition.11716if (MVKind == MultiVersionKind::None)11717return false;11718return CheckMultiVersionFirstFunction(S, NewFD);11719}1172011721FunctionDecl *OldFD = OldDecl->getAsFunction();1172211723if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)11724return false;1172511726// Multiversioned redeclarations aren't allowed to omit the attribute, except11727// for target_clones and target_version.11728if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&11729OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&11730OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {11731S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)11732<< (OldFD->getMultiVersionKind() != MultiVersionKind::Target);11733NewFD->setInvalidDecl();11734return true;11735}1173611737if (!OldFD->isMultiVersion()) {11738switch (MVKind) {11739case MultiVersionKind::Target:11740case MultiVersionKind::TargetVersion:11741return CheckDeclarationCausesMultiVersioning(11742S, OldFD, NewFD, Redeclaration, OldDecl, Previous);11743case MultiVersionKind::TargetClones:11744if (OldFD->isUsed(false)) {11745NewFD->setInvalidDecl();11746return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);11747}11748OldFD->setIsMultiVersion();11749break;1175011751case MultiVersionKind::CPUDispatch:11752case MultiVersionKind::CPUSpecific:11753case MultiVersionKind::None:11754break;11755}11756}1175711758// At this point, we have a multiversion function decl (in OldFD) AND an11759// appropriate attribute in the current function decl. Resolve that these are11760// still compatible with previous declarations.11761return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,11762NewCPUSpec, NewClones, Redeclaration,11763OldDecl, Previous);11764}1176511766static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {11767bool IsPure = NewFD->hasAttr<PureAttr>();11768bool IsConst = NewFD->hasAttr<ConstAttr>();1176911770// If there are no pure or const attributes, there's nothing to check.11771if (!IsPure && !IsConst)11772return;1177311774// If the function is marked both pure and const, we retain the const11775// attribute because it makes stronger guarantees than the pure attribute, and11776// we drop the pure attribute explicitly to prevent later confusion about11777// semantics.11778if (IsPure && IsConst) {11779S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);11780NewFD->dropAttrs<PureAttr>();11781}1178211783// Constructors and destructors are functions which return void, so are11784// handled here as well.11785if (NewFD->getReturnType()->isVoidType()) {11786S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)11787<< IsConst;11788NewFD->dropAttrs<PureAttr, ConstAttr>();11789}11790}1179111792bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,11793LookupResult &Previous,11794bool IsMemberSpecialization,11795bool DeclIsDefn) {11796assert(!NewFD->getReturnType()->isVariablyModifiedType() &&11797"Variably modified return types are not handled here");1179811799// Determine whether the type of this function should be merged with11800// a previous visible declaration. This never happens for functions in C++,11801// and always happens in C if the previous declaration was visible.11802bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&11803!Previous.isShadowed();1180411805bool Redeclaration = false;11806NamedDecl *OldDecl = nullptr;11807bool MayNeedOverloadableChecks = false;1180811809// Merge or overload the declaration with an existing declaration of11810// the same name, if appropriate.11811if (!Previous.empty()) {11812// Determine whether NewFD is an overload of PrevDecl or11813// a declaration that requires merging. If it's an overload,11814// there's no more work to do here; we'll just add the new11815// function to the scope.11816if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {11817NamedDecl *Candidate = Previous.getRepresentativeDecl();11818if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {11819Redeclaration = true;11820OldDecl = Candidate;11821}11822} else {11823MayNeedOverloadableChecks = true;11824switch (CheckOverload(S, NewFD, Previous, OldDecl,11825/*NewIsUsingDecl*/ false)) {11826case Ovl_Match:11827Redeclaration = true;11828break;1182911830case Ovl_NonFunction:11831Redeclaration = true;11832break;1183311834case Ovl_Overload:11835Redeclaration = false;11836break;11837}11838}11839}1184011841// Check for a previous extern "C" declaration with this name.11842if (!Redeclaration &&11843checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {11844if (!Previous.empty()) {11845// This is an extern "C" declaration with the same name as a previous11846// declaration, and thus redeclares that entity...11847Redeclaration = true;11848OldDecl = Previous.getFoundDecl();11849MergeTypeWithPrevious = false;1185011851// ... except in the presence of __attribute__((overloadable)).11852if (OldDecl->hasAttr<OverloadableAttr>() ||11853NewFD->hasAttr<OverloadableAttr>()) {11854if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {11855MayNeedOverloadableChecks = true;11856Redeclaration = false;11857OldDecl = nullptr;11858}11859}11860}11861}1186211863if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))11864return Redeclaration;1186511866// PPC MMA non-pointer types are not allowed as function return types.11867if (Context.getTargetInfo().getTriple().isPPC64() &&11868PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {11869NewFD->setInvalidDecl();11870}1187111872CheckConstPureAttributesUsage(*this, NewFD);1187311874// C++ [dcl.spec.auto.general]p12:11875// Return type deduction for a templated function with a placeholder in its11876// declared type occurs when the definition is instantiated even if the11877// function body contains a return statement with a non-type-dependent11878// operand.11879//11880// C++ [temp.dep.expr]p3:11881// An id-expression is type-dependent if it is a template-id that is not a11882// concept-id and is dependent; or if its terminal name is:11883// - [...]11884// - associated by name lookup with one or more declarations of member11885// functions of a class that is the current instantiation declared with a11886// return type that contains a placeholder type,11887// - [...]11888//11889// If this is a templated function with a placeholder in its return type,11890// make the placeholder type dependent since it won't be deduced until the11891// definition is instantiated. We do this here because it needs to happen11892// for implicitly instantiated member functions/member function templates.11893if (getLangOpts().CPlusPlus14 &&11894(NewFD->isDependentContext() &&11895NewFD->getReturnType()->isUndeducedType())) {11896const FunctionProtoType *FPT =11897NewFD->getType()->castAs<FunctionProtoType>();11898QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());11899NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),11900FPT->getExtProtoInfo()));11901}1190211903// C++11 [dcl.constexpr]p8:11904// A constexpr specifier for a non-static member function that is not11905// a constructor declares that member function to be const.11906//11907// This needs to be delayed until we know whether this is an out-of-line11908// definition of a static member function.11909//11910// This rule is not present in C++1y, so we produce a backwards11911// compatibility warning whenever it happens in C++11.11912CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);11913if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&11914!MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&11915!isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {11916CXXMethodDecl *OldMD = nullptr;11917if (OldDecl)11918OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());11919if (!OldMD || !OldMD->isStatic()) {11920const FunctionProtoType *FPT =11921MD->getType()->castAs<FunctionProtoType>();11922FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();11923EPI.TypeQuals.addConst();11924MD->setType(Context.getFunctionType(FPT->getReturnType(),11925FPT->getParamTypes(), EPI));1192611927// Warn that we did this, if we're not performing template instantiation.11928// In that case, we'll have warned already when the template was defined.11929if (!inTemplateInstantiation()) {11930SourceLocation AddConstLoc;11931if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()11932.IgnoreParens().getAs<FunctionTypeLoc>())11933AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());1193411935Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)11936<< FixItHint::CreateInsertion(AddConstLoc, " const");11937}11938}11939}1194011941if (Redeclaration) {11942// NewFD and OldDecl represent declarations that need to be11943// merged.11944if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,11945DeclIsDefn)) {11946NewFD->setInvalidDecl();11947return Redeclaration;11948}1194911950Previous.clear();11951Previous.addDecl(OldDecl);1195211953if (FunctionTemplateDecl *OldTemplateDecl =11954dyn_cast<FunctionTemplateDecl>(OldDecl)) {11955auto *OldFD = OldTemplateDecl->getTemplatedDecl();11956FunctionTemplateDecl *NewTemplateDecl11957= NewFD->getDescribedFunctionTemplate();11958assert(NewTemplateDecl && "Template/non-template mismatch");1195911960// The call to MergeFunctionDecl above may have created some state in11961// NewTemplateDecl that needs to be merged with OldTemplateDecl before we11962// can add it as a redeclaration.11963NewTemplateDecl->mergePrevDecl(OldTemplateDecl);1196411965NewFD->setPreviousDeclaration(OldFD);11966if (NewFD->isCXXClassMember()) {11967NewFD->setAccess(OldTemplateDecl->getAccess());11968NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());11969}1197011971// If this is an explicit specialization of a member that is a function11972// template, mark it as a member specialization.11973if (IsMemberSpecialization &&11974NewTemplateDecl->getInstantiatedFromMemberTemplate()) {11975NewTemplateDecl->setMemberSpecialization();11976assert(OldTemplateDecl->isMemberSpecialization());11977// Explicit specializations of a member template do not inherit deleted11978// status from the parent member template that they are specializing.11979if (OldFD->isDeleted()) {11980// FIXME: This assert will not hold in the presence of modules.11981assert(OldFD->getCanonicalDecl() == OldFD);11982// FIXME: We need an update record for this AST mutation.11983OldFD->setDeletedAsWritten(false);11984}11985}1198611987} else {11988if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {11989auto *OldFD = cast<FunctionDecl>(OldDecl);11990// This needs to happen first so that 'inline' propagates.11991NewFD->setPreviousDeclaration(OldFD);11992if (NewFD->isCXXClassMember())11993NewFD->setAccess(OldFD->getAccess());11994}11995}11996} else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&11997!NewFD->getAttr<OverloadableAttr>()) {11998assert((Previous.empty() ||11999llvm::any_of(Previous,12000[](const NamedDecl *ND) {12001return ND->hasAttr<OverloadableAttr>();12002})) &&12003"Non-redecls shouldn't happen without overloadable present");1200412005auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {12006const auto *FD = dyn_cast<FunctionDecl>(ND);12007return FD && !FD->hasAttr<OverloadableAttr>();12008});1200912010if (OtherUnmarkedIter != Previous.end()) {12011Diag(NewFD->getLocation(),12012diag::err_attribute_overloadable_multiple_unmarked_overloads);12013Diag((*OtherUnmarkedIter)->getLocation(),12014diag::note_attribute_overloadable_prev_overload)12015<< false;1201612017NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));12018}12019}1202012021if (LangOpts.OpenMP)12022OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);1202312024// Semantic checking for this function declaration (in isolation).1202512026if (getLangOpts().CPlusPlus) {12027// C++-specific checks.12028if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {12029CheckConstructor(Constructor);12030} else if (CXXDestructorDecl *Destructor =12031dyn_cast<CXXDestructorDecl>(NewFD)) {12032// We check here for invalid destructor names.12033// If we have a friend destructor declaration that is dependent, we can't12034// diagnose right away because cases like this are still valid:12035// template <class T> struct A { friend T::X::~Y(); };12036// struct B { struct Y { ~Y(); }; using X = Y; };12037// template struct A<B>;12038if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||12039!Destructor->getFunctionObjectParameterType()->isDependentType()) {12040CXXRecordDecl *Record = Destructor->getParent();12041QualType ClassType = Context.getTypeDeclType(Record);1204212043DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(12044Context.getCanonicalType(ClassType));12045if (NewFD->getDeclName() != Name) {12046Diag(NewFD->getLocation(), diag::err_destructor_name);12047NewFD->setInvalidDecl();12048return Redeclaration;12049}12050}12051} else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {12052if (auto *TD = Guide->getDescribedFunctionTemplate())12053CheckDeductionGuideTemplate(TD);1205412055// A deduction guide is not on the list of entities that can be12056// explicitly specialized.12057if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)12058Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)12059<< /*explicit specialization*/ 1;12060}1206112062// Find any virtual functions that this function overrides.12063if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {12064if (!Method->isFunctionTemplateSpecialization() &&12065!Method->getDescribedFunctionTemplate() &&12066Method->isCanonicalDecl()) {12067AddOverriddenMethods(Method->getParent(), Method);12068}12069if (Method->isVirtual() && NewFD->getTrailingRequiresClause())12070// C++2a [class.virtual]p612071// A virtual method shall not have a requires-clause.12072Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),12073diag::err_constrained_virtual_method);1207412075if (Method->isStatic())12076checkThisInStaticMemberFunctionType(Method);12077}1207812079if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))12080ActOnConversionDeclarator(Conversion);1208112082// Extra checking for C++ overloaded operators (C++ [over.oper]).12083if (NewFD->isOverloadedOperator() &&12084CheckOverloadedOperatorDeclaration(NewFD)) {12085NewFD->setInvalidDecl();12086return Redeclaration;12087}1208812089// Extra checking for C++0x literal operators (C++0x [over.literal]).12090if (NewFD->getLiteralIdentifier() &&12091CheckLiteralOperatorDeclaration(NewFD)) {12092NewFD->setInvalidDecl();12093return Redeclaration;12094}1209512096// In C++, check default arguments now that we have merged decls. Unless12097// the lexical context is the class, because in this case this is done12098// during delayed parsing anyway.12099if (!CurContext->isRecord())12100CheckCXXDefaultArguments(NewFD);1210112102// If this function is declared as being extern "C", then check to see if12103// the function returns a UDT (class, struct, or union type) that is not C12104// compatible, and if it does, warn the user.12105// But, issue any diagnostic on the first declaration only.12106if (Previous.empty() && NewFD->isExternC()) {12107QualType R = NewFD->getReturnType();12108if (R->isIncompleteType() && !R->isVoidType())12109Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)12110<< NewFD << R;12111else if (!R.isPODType(Context) && !R->isVoidType() &&12112!R->isObjCObjectPointerType())12113Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;12114}1211512116// C++1z [dcl.fct]p6:12117// [...] whether the function has a non-throwing exception-specification12118// [is] part of the function type12119//12120// This results in an ABI break between C++14 and C++17 for functions whose12121// declared type includes an exception-specification in a parameter or12122// return type. (Exception specifications on the function itself are OK in12123// most cases, and exception specifications are not permitted in most other12124// contexts where they could make it into a mangling.)12125if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {12126auto HasNoexcept = [&](QualType T) -> bool {12127// Strip off declarator chunks that could be between us and a function12128// type. We don't need to look far, exception specifications are very12129// restricted prior to C++17.12130if (auto *RT = T->getAs<ReferenceType>())12131T = RT->getPointeeType();12132else if (T->isAnyPointerType())12133T = T->getPointeeType();12134else if (auto *MPT = T->getAs<MemberPointerType>())12135T = MPT->getPointeeType();12136if (auto *FPT = T->getAs<FunctionProtoType>())12137if (FPT->isNothrow())12138return true;12139return false;12140};1214112142auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();12143bool AnyNoexcept = HasNoexcept(FPT->getReturnType());12144for (QualType T : FPT->param_types())12145AnyNoexcept |= HasNoexcept(T);12146if (AnyNoexcept)12147Diag(NewFD->getLocation(),12148diag::warn_cxx17_compat_exception_spec_in_signature)12149<< NewFD;12150}1215112152if (!Redeclaration && LangOpts.CUDA)12153CUDA().checkTargetOverload(NewFD, Previous);12154}1215512156// Check if the function definition uses any AArch64 SME features without12157// having the '+sme' feature enabled and warn user if sme locally streaming12158// function returns or uses arguments with VL-based types.12159if (DeclIsDefn) {12160const auto *Attr = NewFD->getAttr<ArmNewAttr>();12161bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();12162bool UsesZA = Attr && Attr->isNewZA();12163bool UsesZT0 = Attr && Attr->isNewZT0();1216412165if (NewFD->hasAttr<ArmLocallyStreamingAttr>()) {12166if (NewFD->getReturnType()->isSizelessVectorType())12167Diag(NewFD->getLocation(),12168diag::warn_sme_locally_streaming_has_vl_args_returns)12169<< /*IsArg=*/false;12170if (llvm::any_of(NewFD->parameters(), [](ParmVarDecl *P) {12171return P->getOriginalType()->isSizelessVectorType();12172}))12173Diag(NewFD->getLocation(),12174diag::warn_sme_locally_streaming_has_vl_args_returns)12175<< /*IsArg=*/true;12176}12177if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {12178FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();12179UsesSM |=12180EPI.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;12181UsesZA |= FunctionType::getArmZAState(EPI.AArch64SMEAttributes) !=12182FunctionType::ARM_None;12183UsesZT0 |= FunctionType::getArmZT0State(EPI.AArch64SMEAttributes) !=12184FunctionType::ARM_None;12185}1218612187if (UsesSM || UsesZA) {12188llvm::StringMap<bool> FeatureMap;12189Context.getFunctionFeatureMap(FeatureMap, NewFD);12190if (!FeatureMap.contains("sme")) {12191if (UsesSM)12192Diag(NewFD->getLocation(),12193diag::err_sme_definition_using_sm_in_non_sme_target);12194else12195Diag(NewFD->getLocation(),12196diag::err_sme_definition_using_za_in_non_sme_target);12197}12198}12199if (UsesZT0) {12200llvm::StringMap<bool> FeatureMap;12201Context.getFunctionFeatureMap(FeatureMap, NewFD);12202if (!FeatureMap.contains("sme2")) {12203Diag(NewFD->getLocation(),12204diag::err_sme_definition_using_zt0_in_non_sme2_target);12205}12206}12207}1220812209return Redeclaration;12210}1221112212void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {12213// C++11 [basic.start.main]p3:12214// A program that [...] declares main to be inline, static or12215// constexpr is ill-formed.12216// C11 6.7.4p4: In a hosted environment, no function specifier(s) shall12217// appear in a declaration of main.12218// static main is not an error under C99, but we should warn about it.12219// We accept _Noreturn main as an extension.12220if (FD->getStorageClass() == SC_Static)12221Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus12222? diag::err_static_main : diag::warn_static_main)12223<< FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());12224if (FD->isInlineSpecified())12225Diag(DS.getInlineSpecLoc(), diag::err_inline_main)12226<< FixItHint::CreateRemoval(DS.getInlineSpecLoc());12227if (DS.isNoreturnSpecified()) {12228SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();12229SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));12230Diag(NoreturnLoc, diag::ext_noreturn_main);12231Diag(NoreturnLoc, diag::note_main_remove_noreturn)12232<< FixItHint::CreateRemoval(NoreturnRange);12233}12234if (FD->isConstexpr()) {12235Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)12236<< FD->isConsteval()12237<< FixItHint::CreateRemoval(DS.getConstexprSpecLoc());12238FD->setConstexprKind(ConstexprSpecKind::Unspecified);12239}1224012241if (getLangOpts().OpenCL) {12242Diag(FD->getLocation(), diag::err_opencl_no_main)12243<< FD->hasAttr<OpenCLKernelAttr>();12244FD->setInvalidDecl();12245return;12246}1224712248// Functions named main in hlsl are default entries, but don't have specific12249// signatures they are required to conform to.12250if (getLangOpts().HLSL)12251return;1225212253QualType T = FD->getType();12254assert(T->isFunctionType() && "function decl is not of function type");12255const FunctionType* FT = T->castAs<FunctionType>();1225612257// Set default calling convention for main()12258if (FT->getCallConv() != CC_C) {12259FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));12260FD->setType(QualType(FT, 0));12261T = Context.getCanonicalType(FD->getType());12262}1226312264if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {12265// In C with GNU extensions we allow main() to have non-integer return12266// type, but we should warn about the extension, and we disable the12267// implicit-return-zero rule.1226812269// GCC in C mode accepts qualified 'int'.12270if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))12271FD->setHasImplicitReturnZero(true);12272else {12273Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);12274SourceRange RTRange = FD->getReturnTypeSourceRange();12275if (RTRange.isValid())12276Diag(RTRange.getBegin(), diag::note_main_change_return_type)12277<< FixItHint::CreateReplacement(RTRange, "int");12278}12279} else {12280// In C and C++, main magically returns 0 if you fall off the end;12281// set the flag which tells us that.12282// This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.1228312284// All the standards say that main() should return 'int'.12285if (Context.hasSameType(FT->getReturnType(), Context.IntTy))12286FD->setHasImplicitReturnZero(true);12287else {12288// Otherwise, this is just a flat-out error.12289SourceRange RTRange = FD->getReturnTypeSourceRange();12290Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)12291<< (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")12292: FixItHint());12293FD->setInvalidDecl(true);12294}12295}1229612297// Treat protoless main() as nullary.12298if (isa<FunctionNoProtoType>(FT)) return;1229912300const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);12301unsigned nparams = FTP->getNumParams();12302assert(FD->getNumParams() == nparams);1230312304bool HasExtraParameters = (nparams > 3);1230512306if (FTP->isVariadic()) {12307Diag(FD->getLocation(), diag::ext_variadic_main);12308// FIXME: if we had information about the location of the ellipsis, we12309// could add a FixIt hint to remove it as a parameter.12310}1231112312// Darwin passes an undocumented fourth argument of type char**. If12313// other platforms start sprouting these, the logic below will start12314// getting shifty.12315if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())12316HasExtraParameters = false;1231712318if (HasExtraParameters) {12319Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;12320FD->setInvalidDecl(true);12321nparams = 3;12322}1232312324// FIXME: a lot of the following diagnostics would be improved12325// if we had some location information about types.1232612327QualType CharPP =12328Context.getPointerType(Context.getPointerType(Context.CharTy));12329QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };1233012331for (unsigned i = 0; i < nparams; ++i) {12332QualType AT = FTP->getParamType(i);1233312334bool mismatch = true;1233512336if (Context.hasSameUnqualifiedType(AT, Expected[i]))12337mismatch = false;12338else if (Expected[i] == CharPP) {12339// As an extension, the following forms are okay:12340// char const **12341// char const * const *12342// char * const *1234312344QualifierCollector qs;12345const PointerType* PT;12346if ((PT = qs.strip(AT)->getAs<PointerType>()) &&12347(PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&12348Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),12349Context.CharTy)) {12350qs.removeConst();12351mismatch = !qs.empty();12352}12353}1235412355if (mismatch) {12356Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];12357// TODO: suggest replacing given type with expected type12358FD->setInvalidDecl(true);12359}12360}1236112362if (nparams == 1 && !FD->isInvalidDecl()) {12363Diag(FD->getLocation(), diag::warn_main_one_arg);12364}1236512366if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {12367Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;12368FD->setInvalidDecl();12369}12370}1237112372static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {1237312374// Default calling convention for main and wmain is __cdecl12375if (FD->getName() == "main" || FD->getName() == "wmain")12376return false;1237712378// Default calling convention for MinGW is __cdecl12379const llvm::Triple &T = S.Context.getTargetInfo().getTriple();12380if (T.isWindowsGNUEnvironment())12381return false;1238212383// Default calling convention for WinMain, wWinMain and DllMain12384// is __stdcall on 32 bit Windows12385if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)12386return true;1238712388return false;12389}1239012391void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {12392QualType T = FD->getType();12393assert(T->isFunctionType() && "function decl is not of function type");12394const FunctionType *FT = T->castAs<FunctionType>();1239512396// Set an implicit return of 'zero' if the function can return some integral,12397// enumeration, pointer or nullptr type.12398if (FT->getReturnType()->isIntegralOrEnumerationType() ||12399FT->getReturnType()->isAnyPointerType() ||12400FT->getReturnType()->isNullPtrType())12401// DllMain is exempt because a return value of zero means it failed.12402if (FD->getName() != "DllMain")12403FD->setHasImplicitReturnZero(true);1240412405// Explicitly specified calling conventions are applied to MSVC entry points12406if (!hasExplicitCallingConv(T)) {12407if (isDefaultStdCall(FD, *this)) {12408if (FT->getCallConv() != CC_X86StdCall) {12409FT = Context.adjustFunctionType(12410FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));12411FD->setType(QualType(FT, 0));12412}12413} else if (FT->getCallConv() != CC_C) {12414FT = Context.adjustFunctionType(FT,12415FT->getExtInfo().withCallingConv(CC_C));12416FD->setType(QualType(FT, 0));12417}12418}1241912420if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {12421Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;12422FD->setInvalidDecl();12423}12424}1242512426bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {12427// FIXME: Need strict checking. In C89, we need to check for12428// any assignment, increment, decrement, function-calls, or12429// commas outside of a sizeof. In C99, it's the same list,12430// except that the aforementioned are allowed in unevaluated12431// expressions. Everything else falls under the12432// "may accept other forms of constant expressions" exception.12433//12434// Regular C++ code will not end up here (exceptions: language extensions,12435// OpenCL C++ etc), so the constant expression rules there don't matter.12436if (Init->isValueDependent()) {12437assert(Init->containsErrors() &&12438"Dependent code should only occur in error-recovery path.");12439return true;12440}12441const Expr *Culprit;12442if (Init->isConstantInitializer(Context, false, &Culprit))12443return false;12444Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();12445return true;12446}1244712448namespace {12449// Visits an initialization expression to see if OrigDecl is evaluated in12450// its own initialization and throws a warning if it does.12451class SelfReferenceChecker12452: public EvaluatedExprVisitor<SelfReferenceChecker> {12453Sema &S;12454Decl *OrigDecl;12455bool isRecordType;12456bool isPODType;12457bool isReferenceType;1245812459bool isInitList;12460llvm::SmallVector<unsigned, 4> InitFieldIndex;1246112462public:12463typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;1246412465SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),12466S(S), OrigDecl(OrigDecl) {12467isPODType = false;12468isRecordType = false;12469isReferenceType = false;12470isInitList = false;12471if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {12472isPODType = VD->getType().isPODType(S.Context);12473isRecordType = VD->getType()->isRecordType();12474isReferenceType = VD->getType()->isReferenceType();12475}12476}1247712478// For most expressions, just call the visitor. For initializer lists,12479// track the index of the field being initialized since fields are12480// initialized in order allowing use of previously initialized fields.12481void CheckExpr(Expr *E) {12482InitListExpr *InitList = dyn_cast<InitListExpr>(E);12483if (!InitList) {12484Visit(E);12485return;12486}1248712488// Track and increment the index here.12489isInitList = true;12490InitFieldIndex.push_back(0);12491for (auto *Child : InitList->children()) {12492CheckExpr(cast<Expr>(Child));12493++InitFieldIndex.back();12494}12495InitFieldIndex.pop_back();12496}1249712498// Returns true if MemberExpr is checked and no further checking is needed.12499// Returns false if additional checking is required.12500bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {12501llvm::SmallVector<FieldDecl*, 4> Fields;12502Expr *Base = E;12503bool ReferenceField = false;1250412505// Get the field members used.12506while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {12507FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());12508if (!FD)12509return false;12510Fields.push_back(FD);12511if (FD->getType()->isReferenceType())12512ReferenceField = true;12513Base = ME->getBase()->IgnoreParenImpCasts();12514}1251512516// Keep checking only if the base Decl is the same.12517DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);12518if (!DRE || DRE->getDecl() != OrigDecl)12519return false;1252012521// A reference field can be bound to an unininitialized field.12522if (CheckReference && !ReferenceField)12523return true;1252412525// Convert FieldDecls to their index number.12526llvm::SmallVector<unsigned, 4> UsedFieldIndex;12527for (const FieldDecl *I : llvm::reverse(Fields))12528UsedFieldIndex.push_back(I->getFieldIndex());1252912530// See if a warning is needed by checking the first difference in index12531// numbers. If field being used has index less than the field being12532// initialized, then the use is safe.12533for (auto UsedIter = UsedFieldIndex.begin(),12534UsedEnd = UsedFieldIndex.end(),12535OrigIter = InitFieldIndex.begin(),12536OrigEnd = InitFieldIndex.end();12537UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {12538if (*UsedIter < *OrigIter)12539return true;12540if (*UsedIter > *OrigIter)12541break;12542}1254312544// TODO: Add a different warning which will print the field names.12545HandleDeclRefExpr(DRE);12546return true;12547}1254812549// For most expressions, the cast is directly above the DeclRefExpr.12550// For conditional operators, the cast can be outside the conditional12551// operator if both expressions are DeclRefExpr's.12552void HandleValue(Expr *E) {12553E = E->IgnoreParens();12554if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {12555HandleDeclRefExpr(DRE);12556return;12557}1255812559if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {12560Visit(CO->getCond());12561HandleValue(CO->getTrueExpr());12562HandleValue(CO->getFalseExpr());12563return;12564}1256512566if (BinaryConditionalOperator *BCO =12567dyn_cast<BinaryConditionalOperator>(E)) {12568Visit(BCO->getCond());12569HandleValue(BCO->getFalseExpr());12570return;12571}1257212573if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {12574if (Expr *SE = OVE->getSourceExpr())12575HandleValue(SE);12576return;12577}1257812579if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {12580if (BO->getOpcode() == BO_Comma) {12581Visit(BO->getLHS());12582HandleValue(BO->getRHS());12583return;12584}12585}1258612587if (isa<MemberExpr>(E)) {12588if (isInitList) {12589if (CheckInitListMemberExpr(cast<MemberExpr>(E),12590false /*CheckReference*/))12591return;12592}1259312594Expr *Base = E->IgnoreParenImpCasts();12595while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {12596// Check for static member variables and don't warn on them.12597if (!isa<FieldDecl>(ME->getMemberDecl()))12598return;12599Base = ME->getBase()->IgnoreParenImpCasts();12600}12601if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))12602HandleDeclRefExpr(DRE);12603return;12604}1260512606Visit(E);12607}1260812609// Reference types not handled in HandleValue are handled here since all12610// uses of references are bad, not just r-value uses.12611void VisitDeclRefExpr(DeclRefExpr *E) {12612if (isReferenceType)12613HandleDeclRefExpr(E);12614}1261512616void VisitImplicitCastExpr(ImplicitCastExpr *E) {12617if (E->getCastKind() == CK_LValueToRValue) {12618HandleValue(E->getSubExpr());12619return;12620}1262112622Inherited::VisitImplicitCastExpr(E);12623}1262412625void VisitMemberExpr(MemberExpr *E) {12626if (isInitList) {12627if (CheckInitListMemberExpr(E, true /*CheckReference*/))12628return;12629}1263012631// Don't warn on arrays since they can be treated as pointers.12632if (E->getType()->canDecayToPointerType()) return;1263312634// Warn when a non-static method call is followed by non-static member12635// field accesses, which is followed by a DeclRefExpr.12636CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());12637bool Warn = (MD && !MD->isStatic());12638Expr *Base = E->getBase()->IgnoreParenImpCasts();12639while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {12640if (!isa<FieldDecl>(ME->getMemberDecl()))12641Warn = false;12642Base = ME->getBase()->IgnoreParenImpCasts();12643}1264412645if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {12646if (Warn)12647HandleDeclRefExpr(DRE);12648return;12649}1265012651// The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.12652// Visit that expression.12653Visit(Base);12654}1265512656void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {12657Expr *Callee = E->getCallee();1265812659if (isa<UnresolvedLookupExpr>(Callee))12660return Inherited::VisitCXXOperatorCallExpr(E);1266112662Visit(Callee);12663for (auto Arg: E->arguments())12664HandleValue(Arg->IgnoreParenImpCasts());12665}1266612667void VisitUnaryOperator(UnaryOperator *E) {12668// For POD record types, addresses of its own members are well-defined.12669if (E->getOpcode() == UO_AddrOf && isRecordType &&12670isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {12671if (!isPODType)12672HandleValue(E->getSubExpr());12673return;12674}1267512676if (E->isIncrementDecrementOp()) {12677HandleValue(E->getSubExpr());12678return;12679}1268012681Inherited::VisitUnaryOperator(E);12682}1268312684void VisitObjCMessageExpr(ObjCMessageExpr *E) {}1268512686void VisitCXXConstructExpr(CXXConstructExpr *E) {12687if (E->getConstructor()->isCopyConstructor()) {12688Expr *ArgExpr = E->getArg(0);12689if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))12690if (ILE->getNumInits() == 1)12691ArgExpr = ILE->getInit(0);12692if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))12693if (ICE->getCastKind() == CK_NoOp)12694ArgExpr = ICE->getSubExpr();12695HandleValue(ArgExpr);12696return;12697}12698Inherited::VisitCXXConstructExpr(E);12699}1270012701void VisitCallExpr(CallExpr *E) {12702// Treat std::move as a use.12703if (E->isCallToStdMove()) {12704HandleValue(E->getArg(0));12705return;12706}1270712708Inherited::VisitCallExpr(E);12709}1271012711void VisitBinaryOperator(BinaryOperator *E) {12712if (E->isCompoundAssignmentOp()) {12713HandleValue(E->getLHS());12714Visit(E->getRHS());12715return;12716}1271712718Inherited::VisitBinaryOperator(E);12719}1272012721// A custom visitor for BinaryConditionalOperator is needed because the12722// regular visitor would check the condition and true expression separately12723// but both point to the same place giving duplicate diagnostics.12724void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {12725Visit(E->getCond());12726Visit(E->getFalseExpr());12727}1272812729void HandleDeclRefExpr(DeclRefExpr *DRE) {12730Decl* ReferenceDecl = DRE->getDecl();12731if (OrigDecl != ReferenceDecl) return;12732unsigned diag;12733if (isReferenceType) {12734diag = diag::warn_uninit_self_reference_in_reference_init;12735} else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {12736diag = diag::warn_static_self_reference_in_init;12737} else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||12738isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||12739DRE->getDecl()->getType()->isRecordType()) {12740diag = diag::warn_uninit_self_reference_in_init;12741} else {12742// Local variables will be handled by the CFG analysis.12743return;12744}1274512746S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,12747S.PDiag(diag)12748<< DRE->getDecl() << OrigDecl->getLocation()12749<< DRE->getSourceRange());12750}12751};1275212753/// CheckSelfReference - Warns if OrigDecl is used in expression E.12754static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,12755bool DirectInit) {12756// Parameters arguments are occassionially constructed with itself,12757// for instance, in recursive functions. Skip them.12758if (isa<ParmVarDecl>(OrigDecl))12759return;1276012761E = E->IgnoreParens();1276212763// Skip checking T a = a where T is not a record or reference type.12764// Doing so is a way to silence uninitialized warnings.12765if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())12766if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))12767if (ICE->getCastKind() == CK_LValueToRValue)12768if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))12769if (DRE->getDecl() == OrigDecl)12770return;1277112772SelfReferenceChecker(S, OrigDecl).CheckExpr(E);12773}12774} // end anonymous namespace1277512776namespace {12777// Simple wrapper to add the name of a variable or (if no variable is12778// available) a DeclarationName into a diagnostic.12779struct VarDeclOrName {12780VarDecl *VDecl;12781DeclarationName Name;1278212783friend const Sema::SemaDiagnosticBuilder &12784operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {12785return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;12786}12787};12788} // end anonymous namespace1278912790QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,12791DeclarationName Name, QualType Type,12792TypeSourceInfo *TSI,12793SourceRange Range, bool DirectInit,12794Expr *Init) {12795bool IsInitCapture = !VDecl;12796assert((!VDecl || !VDecl->isInitCapture()) &&12797"init captures are expected to be deduced prior to initialization");1279812799VarDeclOrName VN{VDecl, Name};1280012801DeducedType *Deduced = Type->getContainedDeducedType();12802assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");1280312804// Diagnose auto array declarations in C23, unless it's a supported extension.12805if (getLangOpts().C23 && Type->isArrayType() &&12806!isa_and_present<StringLiteral, InitListExpr>(Init)) {12807Diag(Range.getBegin(), diag::err_auto_not_allowed)12808<< (int)Deduced->getContainedAutoType()->getKeyword()12809<< /*in array decl*/ 23 << Range;12810return QualType();12811}1281212813// C++11 [dcl.spec.auto]p312814if (!Init) {12815assert(VDecl && "no init for init capture deduction?");1281612817// Except for class argument deduction, and then for an initializing12818// declaration only, i.e. no static at class scope or extern.12819if (!isa<DeducedTemplateSpecializationType>(Deduced) ||12820VDecl->hasExternalStorage() ||12821VDecl->isStaticDataMember()) {12822Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)12823<< VDecl->getDeclName() << Type;12824return QualType();12825}12826}1282712828ArrayRef<Expr*> DeduceInits;12829if (Init)12830DeduceInits = Init;1283112832auto *PL = dyn_cast_if_present<ParenListExpr>(Init);12833if (DirectInit && PL)12834DeduceInits = PL->exprs();1283512836if (isa<DeducedTemplateSpecializationType>(Deduced)) {12837assert(VDecl && "non-auto type for init capture deduction?");12838InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);12839InitializationKind Kind = InitializationKind::CreateForInit(12840VDecl->getLocation(), DirectInit, Init);12841// FIXME: Initialization should not be taking a mutable list of inits.12842SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());12843return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,12844InitsCopy);12845}1284612847if (DirectInit) {12848if (auto *IL = dyn_cast<InitListExpr>(Init))12849DeduceInits = IL->inits();12850}1285112852// Deduction only works if we have exactly one source expression.12853if (DeduceInits.empty()) {12854// It isn't possible to write this directly, but it is possible to12855// end up in this situation with "auto x(some_pack...);"12856Diag(Init->getBeginLoc(), IsInitCapture12857? diag::err_init_capture_no_expression12858: diag::err_auto_var_init_no_expression)12859<< VN << Type << Range;12860return QualType();12861}1286212863if (DeduceInits.size() > 1) {12864Diag(DeduceInits[1]->getBeginLoc(),12865IsInitCapture ? diag::err_init_capture_multiple_expressions12866: diag::err_auto_var_init_multiple_expressions)12867<< VN << Type << Range;12868return QualType();12869}1287012871Expr *DeduceInit = DeduceInits[0];12872if (DirectInit && isa<InitListExpr>(DeduceInit)) {12873Diag(Init->getBeginLoc(), IsInitCapture12874? diag::err_init_capture_paren_braces12875: diag::err_auto_var_init_paren_braces)12876<< isa<InitListExpr>(Init) << VN << Type << Range;12877return QualType();12878}1287912880// Expressions default to 'id' when we're in a debugger.12881bool DefaultedAnyToId = false;12882if (getLangOpts().DebuggerCastResultToId &&12883Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {12884ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());12885if (Result.isInvalid()) {12886return QualType();12887}12888Init = Result.get();12889DefaultedAnyToId = true;12890}1289112892// C++ [dcl.decomp]p1:12893// If the assignment-expression [...] has array type A and no ref-qualifier12894// is present, e has type cv A12895if (VDecl && isa<DecompositionDecl>(VDecl) &&12896Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&12897DeduceInit->getType()->isConstantArrayType())12898return Context.getQualifiedType(DeduceInit->getType(),12899Type.getQualifiers());1290012901QualType DeducedType;12902TemplateDeductionInfo Info(DeduceInit->getExprLoc());12903TemplateDeductionResult Result =12904DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);12905if (Result != TemplateDeductionResult::Success &&12906Result != TemplateDeductionResult::AlreadyDiagnosed) {12907if (!IsInitCapture)12908DiagnoseAutoDeductionFailure(VDecl, DeduceInit);12909else if (isa<InitListExpr>(Init))12910Diag(Range.getBegin(),12911diag::err_init_capture_deduction_failure_from_init_list)12912<< VN12913<< (DeduceInit->getType().isNull() ? TSI->getType()12914: DeduceInit->getType())12915<< DeduceInit->getSourceRange();12916else12917Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)12918<< VN << TSI->getType()12919<< (DeduceInit->getType().isNull() ? TSI->getType()12920: DeduceInit->getType())12921<< DeduceInit->getSourceRange();12922}1292312924// Warn if we deduced 'id'. 'auto' usually implies type-safety, but using12925// 'id' instead of a specific object type prevents most of our usual12926// checks.12927// We only want to warn outside of template instantiations, though:12928// inside a template, the 'id' could have come from a parameter.12929if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&12930!DeducedType.isNull() && DeducedType->isObjCIdType()) {12931SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();12932Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;12933}1293412935return DeducedType;12936}1293712938bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,12939Expr *Init) {12940assert(!Init || !Init->containsErrors());12941QualType DeducedType = deduceVarTypeFromInitializer(12942VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),12943VDecl->getSourceRange(), DirectInit, Init);12944if (DeducedType.isNull()) {12945VDecl->setInvalidDecl();12946return true;12947}1294812949VDecl->setType(DeducedType);12950assert(VDecl->isLinkageValid());1295112952// In ARC, infer lifetime.12953if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))12954VDecl->setInvalidDecl();1295512956if (getLangOpts().OpenCL)12957deduceOpenCLAddressSpace(VDecl);1295812959// If this is a redeclaration, check that the type we just deduced matches12960// the previously declared type.12961if (VarDecl *Old = VDecl->getPreviousDecl()) {12962// We never need to merge the type, because we cannot form an incomplete12963// array of auto, nor deduce such a type.12964MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);12965}1296612967// Check the deduced type is valid for a variable declaration.12968CheckVariableDeclarationType(VDecl);12969return VDecl->isInvalidDecl();12970}1297112972void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,12973SourceLocation Loc) {12974if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))12975Init = EWC->getSubExpr();1297612977if (auto *CE = dyn_cast<ConstantExpr>(Init))12978Init = CE->getSubExpr();1297912980QualType InitType = Init->getType();12981assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||12982InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&12983"shouldn't be called if type doesn't have a non-trivial C struct");12984if (auto *ILE = dyn_cast<InitListExpr>(Init)) {12985for (auto *I : ILE->inits()) {12986if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&12987!I->getType().hasNonTrivialToPrimitiveCopyCUnion())12988continue;12989SourceLocation SL = I->getExprLoc();12990checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);12991}12992return;12993}1299412995if (isa<ImplicitValueInitExpr>(Init)) {12996if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())12997checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,12998NTCUK_Init);12999} else {13000// Assume all other explicit initializers involving copying some existing13001// object.13002// TODO: ignore any explicit initializers where we can guarantee13003// copy-elision.13004if (InitType.hasNonTrivialToPrimitiveCopyCUnion())13005checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);13006}13007}1300813009namespace {1301013011bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {13012// Ignore unavailable fields. A field can be marked as unavailable explicitly13013// in the source code or implicitly by the compiler if it is in a union13014// defined in a system header and has non-trivial ObjC ownership13015// qualifications. We don't want those fields to participate in determining13016// whether the containing union is non-trivial.13017return FD->hasAttr<UnavailableAttr>();13018}1301913020struct DiagNonTrivalCUnionDefaultInitializeVisitor13021: DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,13022void> {13023using Super =13024DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,13025void>;1302613027DiagNonTrivalCUnionDefaultInitializeVisitor(13028QualType OrigTy, SourceLocation OrigLoc,13029Sema::NonTrivialCUnionContext UseContext, Sema &S)13030: OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}1303113032void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,13033const FieldDecl *FD, bool InNonTrivialUnion) {13034if (const auto *AT = S.Context.getAsArrayType(QT))13035return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,13036InNonTrivialUnion);13037return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);13038}1303913040void visitARCStrong(QualType QT, const FieldDecl *FD,13041bool InNonTrivialUnion) {13042if (InNonTrivialUnion)13043S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)13044<< 1 << 0 << QT << FD->getName();13045}1304613047void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {13048if (InNonTrivialUnion)13049S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)13050<< 1 << 0 << QT << FD->getName();13051}1305213053void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {13054const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();13055if (RD->isUnion()) {13056if (OrigLoc.isValid()) {13057bool IsUnion = false;13058if (auto *OrigRD = OrigTy->getAsRecordDecl())13059IsUnion = OrigRD->isUnion();13060S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)13061<< 0 << OrigTy << IsUnion << UseContext;13062// Reset OrigLoc so that this diagnostic is emitted only once.13063OrigLoc = SourceLocation();13064}13065InNonTrivialUnion = true;13066}1306713068if (InNonTrivialUnion)13069S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)13070<< 0 << 0 << QT.getUnqualifiedType() << "";1307113072for (const FieldDecl *FD : RD->fields())13073if (!shouldIgnoreForRecordTriviality(FD))13074asDerived().visit(FD->getType(), FD, InNonTrivialUnion);13075}1307613077void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}1307813079// The non-trivial C union type or the struct/union type that contains a13080// non-trivial C union.13081QualType OrigTy;13082SourceLocation OrigLoc;13083Sema::NonTrivialCUnionContext UseContext;13084Sema &S;13085};1308613087struct DiagNonTrivalCUnionDestructedTypeVisitor13088: DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {13089using Super =13090DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;1309113092DiagNonTrivalCUnionDestructedTypeVisitor(13093QualType OrigTy, SourceLocation OrigLoc,13094Sema::NonTrivialCUnionContext UseContext, Sema &S)13095: OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}1309613097void visitWithKind(QualType::DestructionKind DK, QualType QT,13098const FieldDecl *FD, bool InNonTrivialUnion) {13099if (const auto *AT = S.Context.getAsArrayType(QT))13100return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,13101InNonTrivialUnion);13102return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);13103}1310413105void visitARCStrong(QualType QT, const FieldDecl *FD,13106bool InNonTrivialUnion) {13107if (InNonTrivialUnion)13108S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)13109<< 1 << 1 << QT << FD->getName();13110}1311113112void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {13113if (InNonTrivialUnion)13114S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)13115<< 1 << 1 << QT << FD->getName();13116}1311713118void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {13119const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();13120if (RD->isUnion()) {13121if (OrigLoc.isValid()) {13122bool IsUnion = false;13123if (auto *OrigRD = OrigTy->getAsRecordDecl())13124IsUnion = OrigRD->isUnion();13125S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)13126<< 1 << OrigTy << IsUnion << UseContext;13127// Reset OrigLoc so that this diagnostic is emitted only once.13128OrigLoc = SourceLocation();13129}13130InNonTrivialUnion = true;13131}1313213133if (InNonTrivialUnion)13134S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)13135<< 0 << 1 << QT.getUnqualifiedType() << "";1313613137for (const FieldDecl *FD : RD->fields())13138if (!shouldIgnoreForRecordTriviality(FD))13139asDerived().visit(FD->getType(), FD, InNonTrivialUnion);13140}1314113142void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}13143void visitCXXDestructor(QualType QT, const FieldDecl *FD,13144bool InNonTrivialUnion) {}1314513146// The non-trivial C union type or the struct/union type that contains a13147// non-trivial C union.13148QualType OrigTy;13149SourceLocation OrigLoc;13150Sema::NonTrivialCUnionContext UseContext;13151Sema &S;13152};1315313154struct DiagNonTrivalCUnionCopyVisitor13155: CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {13156using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;1315713158DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,13159Sema::NonTrivialCUnionContext UseContext,13160Sema &S)13161: OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}1316213163void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,13164const FieldDecl *FD, bool InNonTrivialUnion) {13165if (const auto *AT = S.Context.getAsArrayType(QT))13166return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,13167InNonTrivialUnion);13168return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);13169}1317013171void visitARCStrong(QualType QT, const FieldDecl *FD,13172bool InNonTrivialUnion) {13173if (InNonTrivialUnion)13174S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)13175<< 1 << 2 << QT << FD->getName();13176}1317713178void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {13179if (InNonTrivialUnion)13180S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)13181<< 1 << 2 << QT << FD->getName();13182}1318313184void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {13185const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();13186if (RD->isUnion()) {13187if (OrigLoc.isValid()) {13188bool IsUnion = false;13189if (auto *OrigRD = OrigTy->getAsRecordDecl())13190IsUnion = OrigRD->isUnion();13191S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)13192<< 2 << OrigTy << IsUnion << UseContext;13193// Reset OrigLoc so that this diagnostic is emitted only once.13194OrigLoc = SourceLocation();13195}13196InNonTrivialUnion = true;13197}1319813199if (InNonTrivialUnion)13200S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)13201<< 0 << 2 << QT.getUnqualifiedType() << "";1320213203for (const FieldDecl *FD : RD->fields())13204if (!shouldIgnoreForRecordTriviality(FD))13205asDerived().visit(FD->getType(), FD, InNonTrivialUnion);13206}1320713208void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,13209const FieldDecl *FD, bool InNonTrivialUnion) {}13210void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}13211void visitVolatileTrivial(QualType QT, const FieldDecl *FD,13212bool InNonTrivialUnion) {}1321313214// The non-trivial C union type or the struct/union type that contains a13215// non-trivial C union.13216QualType OrigTy;13217SourceLocation OrigLoc;13218Sema::NonTrivialCUnionContext UseContext;13219Sema &S;13220};1322113222} // namespace1322313224void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,13225NonTrivialCUnionContext UseContext,13226unsigned NonTrivialKind) {13227assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||13228QT.hasNonTrivialToPrimitiveDestructCUnion() ||13229QT.hasNonTrivialToPrimitiveCopyCUnion()) &&13230"shouldn't be called if type doesn't have a non-trivial C union");1323113232if ((NonTrivialKind & NTCUK_Init) &&13233QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())13234DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)13235.visit(QT, nullptr, false);13236if ((NonTrivialKind & NTCUK_Destruct) &&13237QT.hasNonTrivialToPrimitiveDestructCUnion())13238DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)13239.visit(QT, nullptr, false);13240if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())13241DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)13242.visit(QT, nullptr, false);13243}1324413245void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {13246// If there is no declaration, there was an error parsing it. Just ignore13247// the initializer.13248if (!RealDecl) {13249CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));13250return;13251}1325213253if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {13254if (!Method->isInvalidDecl()) {13255// Pure-specifiers are handled in ActOnPureSpecifier.13256Diag(Method->getLocation(), diag::err_member_function_initialization)13257<< Method->getDeclName() << Init->getSourceRange();13258Method->setInvalidDecl();13259}13260return;13261}1326213263VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);13264if (!VDecl) {13265assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");13266Diag(RealDecl->getLocation(), diag::err_illegal_initializer);13267RealDecl->setInvalidDecl();13268return;13269}1327013271if (VDecl->isInvalidDecl()) {13272ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);13273SmallVector<Expr *> SubExprs;13274if (Res.isUsable())13275SubExprs.push_back(Res.get());13276ExprResult Recovery =13277CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), SubExprs);13278if (Expr *E = Recovery.get())13279VDecl->setInit(E);13280return;13281}1328213283// WebAssembly tables can't be used to initialise a variable.13284if (Init && !Init->getType().isNull() &&13285Init->getType()->isWebAssemblyTableType()) {13286Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;13287VDecl->setInvalidDecl();13288return;13289}1329013291// C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.13292if (VDecl->getType()->isUndeducedType()) {13293// Attempt typo correction early so that the type of the init expression can13294// be deduced based on the chosen correction if the original init contains a13295// TypoExpr.13296ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);13297if (!Res.isUsable()) {13298// There are unresolved typos in Init, just drop them.13299// FIXME: improve the recovery strategy to preserve the Init.13300RealDecl->setInvalidDecl();13301return;13302}13303if (Res.get()->containsErrors()) {13304// Invalidate the decl as we don't know the type for recovery-expr yet.13305RealDecl->setInvalidDecl();13306VDecl->setInit(Res.get());13307return;13308}13309Init = Res.get();1331013311if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))13312return;13313}1331413315// dllimport cannot be used on variable definitions.13316if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {13317Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);13318VDecl->setInvalidDecl();13319return;13320}1332113322// C99 6.7.8p5. If the declaration of an identifier has block scope, and13323// the identifier has external or internal linkage, the declaration shall13324// have no initializer for the identifier.13325// C++14 [dcl.init]p5 is the same restriction for C++.13326if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {13327Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);13328VDecl->setInvalidDecl();13329return;13330}1333113332if (!VDecl->getType()->isDependentType()) {13333// A definition must end up with a complete type, which means it must be13334// complete with the restriction that an array type might be completed by13335// the initializer; note that later code assumes this restriction.13336QualType BaseDeclType = VDecl->getType();13337if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))13338BaseDeclType = Array->getElementType();13339if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,13340diag::err_typecheck_decl_incomplete_type)) {13341RealDecl->setInvalidDecl();13342return;13343}1334413345// The variable can not have an abstract class type.13346if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),13347diag::err_abstract_type_in_decl,13348AbstractVariableType))13349VDecl->setInvalidDecl();13350}1335113352// C++ [module.import/6] external definitions are not permitted in header13353// units.13354if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&13355!VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&13356VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&13357!VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&13358!VDecl->getInstantiatedFromStaticDataMember()) {13359Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);13360VDecl->setInvalidDecl();13361}1336213363// If adding the initializer will turn this declaration into a definition,13364// and we already have a definition for this variable, diagnose or otherwise13365// handle the situation.13366if (VarDecl *Def = VDecl->getDefinition())13367if (Def != VDecl &&13368(!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&13369!VDecl->isThisDeclarationADemotedDefinition() &&13370checkVarDeclRedefinition(Def, VDecl))13371return;1337213373if (getLangOpts().CPlusPlus) {13374// C++ [class.static.data]p413375// If a static data member is of const integral or const13376// enumeration type, its declaration in the class definition can13377// specify a constant-initializer which shall be an integral13378// constant expression (5.19). In that case, the member can appear13379// in integral constant expressions. The member shall still be13380// defined in a namespace scope if it is used in the program and the13381// namespace scope definition shall not contain an initializer.13382//13383// We already performed a redefinition check above, but for static13384// data members we also need to check whether there was an in-class13385// declaration with an initializer.13386if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {13387Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)13388<< VDecl->getDeclName();13389Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),13390diag::note_previous_initializer)13391<< 0;13392return;13393}1339413395if (VDecl->hasLocalStorage())13396setFunctionHasBranchProtectedScope();1339713398if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {13399VDecl->setInvalidDecl();13400return;13401}13402}1340313404// OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside13405// a kernel function cannot be initialized."13406if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {13407Diag(VDecl->getLocation(), diag::err_local_cant_init);13408VDecl->setInvalidDecl();13409return;13410}1341113412// The LoaderUninitialized attribute acts as a definition (of undef).13413if (VDecl->hasAttr<LoaderUninitializedAttr>()) {13414Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);13415VDecl->setInvalidDecl();13416return;13417}1341813419// Get the decls type and save a reference for later, since13420// CheckInitializerTypes may change it.13421QualType DclT = VDecl->getType(), SavT = DclT;1342213423// Expressions default to 'id' when we're in a debugger13424// and we are assigning it to a variable of Objective-C pointer type.13425if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&13426Init->getType() == Context.UnknownAnyTy) {13427ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());13428if (Result.isInvalid()) {13429VDecl->setInvalidDecl();13430return;13431}13432Init = Result.get();13433}1343413435// Perform the initialization.13436ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);13437bool IsParenListInit = false;13438if (!VDecl->isInvalidDecl()) {13439InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);13440InitializationKind Kind = InitializationKind::CreateForInit(13441VDecl->getLocation(), DirectInit, Init);1344213443MultiExprArg Args = Init;13444if (CXXDirectInit)13445Args = MultiExprArg(CXXDirectInit->getExprs(),13446CXXDirectInit->getNumExprs());1344713448// Try to correct any TypoExprs in the initialization arguments.13449for (size_t Idx = 0; Idx < Args.size(); ++Idx) {13450ExprResult Res = CorrectDelayedTyposInExpr(13451Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,13452[this, Entity, Kind](Expr *E) {13453InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));13454return Init.Failed() ? ExprError() : E;13455});13456if (Res.isInvalid()) {13457VDecl->setInvalidDecl();13458} else if (Res.get() != Args[Idx]) {13459Args[Idx] = Res.get();13460}13461}13462if (VDecl->isInvalidDecl())13463return;1346413465InitializationSequence InitSeq(*this, Entity, Kind, Args,13466/*TopLevelOfInitList=*/false,13467/*TreatUnavailableAsInvalid=*/false);13468ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);13469if (Result.isInvalid()) {13470// If the provided initializer fails to initialize the var decl,13471// we attach a recovery expr for better recovery.13472auto RecoveryExpr =13473CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);13474if (RecoveryExpr.get())13475VDecl->setInit(RecoveryExpr.get());13476// In general, for error recovery purposes, the initializer doesn't play13477// part in the valid bit of the declaration. There are a few exceptions:13478// 1) if the var decl has a deduced auto type, and the type cannot be13479// deduced by an invalid initializer;13480// 2) if the var decl is a decomposition decl with a non-deduced type,13481// and the initialization fails (e.g. `int [a] = {1, 2};`);13482// Case 1) was already handled elsewhere.13483if (isa<DecompositionDecl>(VDecl)) // Case 2)13484VDecl->setInvalidDecl();13485return;13486}1348713488Init = Result.getAs<Expr>();13489IsParenListInit = !InitSeq.steps().empty() &&13490InitSeq.step_begin()->Kind ==13491InitializationSequence::SK_ParenthesizedListInit;13492QualType VDeclType = VDecl->getType();13493if (Init && !Init->getType().isNull() &&13494!Init->getType()->isDependentType() && !VDeclType->isDependentType() &&13495Context.getAsIncompleteArrayType(VDeclType) &&13496Context.getAsIncompleteArrayType(Init->getType())) {13497// Bail out if it is not possible to deduce array size from the13498// initializer.13499Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)13500<< VDeclType;13501VDecl->setInvalidDecl();13502return;13503}13504}1350513506// Check for self-references within variable initializers.13507// Variables declared within a function/method body (except for references)13508// are handled by a dataflow analysis.13509// This is undefined behavior in C++, but valid in C.13510if (getLangOpts().CPlusPlus)13511if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||13512VDecl->getType()->isReferenceType())13513CheckSelfReference(*this, RealDecl, Init, DirectInit);1351413515// If the type changed, it means we had an incomplete type that was13516// completed by the initializer. For example:13517// int ary[] = { 1, 3, 5 };13518// "ary" transitions from an IncompleteArrayType to a ConstantArrayType.13519if (!VDecl->isInvalidDecl() && (DclT != SavT))13520VDecl->setType(DclT);1352113522if (!VDecl->isInvalidDecl()) {13523checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);1352413525if (VDecl->hasAttr<BlocksAttr>())13526ObjC().checkRetainCycles(VDecl, Init);1352713528// It is safe to assign a weak reference into a strong variable.13529// Although this code can still have problems:13530// id x = self.weakProp;13531// id y = self.weakProp;13532// we do not warn to warn spuriously when 'x' and 'y' are on separate13533// paths through the function. This should be revisited if13534// -Wrepeated-use-of-weak is made flow-sensitive.13535if (FunctionScopeInfo *FSI = getCurFunction())13536if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||13537VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&13538!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,13539Init->getBeginLoc()))13540FSI->markSafeWeakUse(Init);13541}1354213543// The initialization is usually a full-expression.13544//13545// FIXME: If this is a braced initialization of an aggregate, it is not13546// an expression, and each individual field initializer is a separate13547// full-expression. For instance, in:13548//13549// struct Temp { ~Temp(); };13550// struct S { S(Temp); };13551// struct T { S a, b; } t = { Temp(), Temp() }13552//13553// we should destroy the first Temp before constructing the second.13554ExprResult Result =13555ActOnFinishFullExpr(Init, VDecl->getLocation(),13556/*DiscardedValue*/ false, VDecl->isConstexpr());13557if (Result.isInvalid()) {13558VDecl->setInvalidDecl();13559return;13560}13561Init = Result.get();1356213563// Attach the initializer to the decl.13564VDecl->setInit(Init);1356513566if (VDecl->isLocalVarDecl()) {13567// Don't check the initializer if the declaration is malformed.13568if (VDecl->isInvalidDecl()) {13569// do nothing1357013571// OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.13572// This is true even in C++ for OpenCL.13573} else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {13574CheckForConstantInitializer(Init);1357513576// Otherwise, C++ does not restrict the initializer.13577} else if (getLangOpts().CPlusPlus) {13578// do nothing1357913580// C99 6.7.8p4: All the expressions in an initializer for an object that has13581// static storage duration shall be constant expressions or string literals.13582} else if (VDecl->getStorageClass() == SC_Static) {13583CheckForConstantInitializer(Init);1358413585// C89 is stricter than C99 for aggregate initializers.13586// C89 6.5.7p3: All the expressions [...] in an initializer list13587// for an object that has aggregate or union type shall be13588// constant expressions.13589} else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&13590isa<InitListExpr>(Init)) {13591CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);13592}1359313594if (auto *E = dyn_cast<ExprWithCleanups>(Init))13595if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))13596if (VDecl->hasLocalStorage())13597BE->getBlockDecl()->setCanAvoidCopyToHeap();13598} else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&13599VDecl->getLexicalDeclContext()->isRecord()) {13600// This is an in-class initialization for a static data member, e.g.,13601//13602// struct S {13603// static const int value = 17;13604// };1360513606// C++ [class.mem]p4:13607// A member-declarator can contain a constant-initializer only13608// if it declares a static member (9.4) of const integral or13609// const enumeration type, see 9.4.2.13610//13611// C++11 [class.static.data]p3:13612// If a non-volatile non-inline const static data member is of integral13613// or enumeration type, its declaration in the class definition can13614// specify a brace-or-equal-initializer in which every initializer-clause13615// that is an assignment-expression is a constant expression. A static13616// data member of literal type can be declared in the class definition13617// with the constexpr specifier; if so, its declaration shall specify a13618// brace-or-equal-initializer in which every initializer-clause that is13619// an assignment-expression is a constant expression.1362013621// Do nothing on dependent types.13622if (DclT->isDependentType()) {1362313624// Allow any 'static constexpr' members, whether or not they are of literal13625// type. We separately check that every constexpr variable is of literal13626// type.13627} else if (VDecl->isConstexpr()) {1362813629// Require constness.13630} else if (!DclT.isConstQualified()) {13631Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)13632<< Init->getSourceRange();13633VDecl->setInvalidDecl();1363413635// We allow integer constant expressions in all cases.13636} else if (DclT->isIntegralOrEnumerationType()) {13637// Check whether the expression is a constant expression.13638SourceLocation Loc;13639if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())13640// In C++11, a non-constexpr const static data member with an13641// in-class initializer cannot be volatile.13642Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);13643else if (Init->isValueDependent())13644; // Nothing to check.13645else if (Init->isIntegerConstantExpr(Context, &Loc))13646; // Ok, it's an ICE!13647else if (Init->getType()->isScopedEnumeralType() &&13648Init->isCXX11ConstantExpr(Context))13649; // Ok, it is a scoped-enum constant expression.13650else if (Init->isEvaluatable(Context)) {13651// If we can constant fold the initializer through heroics, accept it,13652// but report this as a use of an extension for -pedantic.13653Diag(Loc, diag::ext_in_class_initializer_non_constant)13654<< Init->getSourceRange();13655} else {13656// Otherwise, this is some crazy unknown case. Report the issue at the13657// location provided by the isIntegerConstantExpr failed check.13658Diag(Loc, diag::err_in_class_initializer_non_constant)13659<< Init->getSourceRange();13660VDecl->setInvalidDecl();13661}1366213663// We allow foldable floating-point constants as an extension.13664} else if (DclT->isFloatingType()) { // also permits complex, which is ok13665// In C++98, this is a GNU extension. In C++11, it is not, but we support13666// it anyway and provide a fixit to add the 'constexpr'.13667if (getLangOpts().CPlusPlus11) {13668Diag(VDecl->getLocation(),13669diag::ext_in_class_initializer_float_type_cxx11)13670<< DclT << Init->getSourceRange();13671Diag(VDecl->getBeginLoc(),13672diag::note_in_class_initializer_float_type_cxx11)13673<< FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");13674} else {13675Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)13676<< DclT << Init->getSourceRange();1367713678if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {13679Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)13680<< Init->getSourceRange();13681VDecl->setInvalidDecl();13682}13683}1368413685// Suggest adding 'constexpr' in C++11 for literal types.13686} else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {13687Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)13688<< DclT << Init->getSourceRange()13689<< FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");13690VDecl->setConstexpr(true);1369113692} else {13693Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)13694<< DclT << Init->getSourceRange();13695VDecl->setInvalidDecl();13696}13697} else if (VDecl->isFileVarDecl()) {13698// In C, extern is typically used to avoid tentative definitions when13699// declaring variables in headers, but adding an initializer makes it a13700// definition. This is somewhat confusing, so GCC and Clang both warn on it.13701// In C++, extern is often used to give implicitly static const variables13702// external linkage, so don't warn in that case. If selectany is present,13703// this might be header code intended for C and C++ inclusion, so apply the13704// C++ rules.13705if (VDecl->getStorageClass() == SC_Extern &&13706((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||13707!Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&13708!(getLangOpts().CPlusPlus && VDecl->isExternC()) &&13709!isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))13710Diag(VDecl->getLocation(), diag::warn_extern_init);1371113712// In Microsoft C++ mode, a const variable defined in namespace scope has13713// external linkage by default if the variable is declared with13714// __declspec(dllexport).13715if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&13716getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&13717VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())13718VDecl->setStorageClass(SC_Extern);1371913720// C99 6.7.8p4. All file scoped initializers need to be constant.13721// Avoid duplicate diagnostics for constexpr variables.13722if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&13723!VDecl->isConstexpr())13724CheckForConstantInitializer(Init);13725}1372613727QualType InitType = Init->getType();13728if (!InitType.isNull() &&13729(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||13730InitType.hasNonTrivialToPrimitiveCopyCUnion()))13731checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());1373213733// We will represent direct-initialization similarly to copy-initialization:13734// int x(1); -as-> int x = 1;13735// ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);13736//13737// Clients that want to distinguish between the two forms, can check for13738// direct initializer using VarDecl::getInitStyle().13739// A major benefit is that clients that don't particularly care about which13740// exactly form was it (like the CodeGen) can handle both cases without13741// special case code.1374213743// C++ 8.5p11:13744// The form of initialization (using parentheses or '=') is generally13745// insignificant, but does matter when the entity being initialized has a13746// class type.13747if (CXXDirectInit) {13748assert(DirectInit && "Call-style initializer must be direct init.");13749VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit13750: VarDecl::CallInit);13751} else if (DirectInit) {13752// This must be list-initialization. No other way is direct-initialization.13753VDecl->setInitStyle(VarDecl::ListInit);13754}1375513756if (LangOpts.OpenMP &&13757(LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&13758VDecl->isFileVarDecl())13759DeclsToCheckForDeferredDiags.insert(VDecl);13760CheckCompleteVariableDeclaration(VDecl);13761}1376213763void Sema::ActOnInitializerError(Decl *D) {13764// Our main concern here is re-establishing invariants like "a13765// variable's type is either dependent or complete".13766if (!D || D->isInvalidDecl()) return;1376713768VarDecl *VD = dyn_cast<VarDecl>(D);13769if (!VD) return;1377013771// Bindings are not usable if we can't make sense of the initializer.13772if (auto *DD = dyn_cast<DecompositionDecl>(D))13773for (auto *BD : DD->bindings())13774BD->setInvalidDecl();1377513776// Auto types are meaningless if we can't make sense of the initializer.13777if (VD->getType()->isUndeducedType()) {13778D->setInvalidDecl();13779return;13780}1378113782QualType Ty = VD->getType();13783if (Ty->isDependentType()) return;1378413785// Require a complete type.13786if (RequireCompleteType(VD->getLocation(),13787Context.getBaseElementType(Ty),13788diag::err_typecheck_decl_incomplete_type)) {13789VD->setInvalidDecl();13790return;13791}1379213793// Require a non-abstract type.13794if (RequireNonAbstractType(VD->getLocation(), Ty,13795diag::err_abstract_type_in_decl,13796AbstractVariableType)) {13797VD->setInvalidDecl();13798return;13799}1380013801// Don't bother complaining about constructors or destructors,13802// though.13803}1380413805void Sema::ActOnUninitializedDecl(Decl *RealDecl) {13806// If there is no declaration, there was an error parsing it. Just ignore it.13807if (!RealDecl)13808return;1380913810if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {13811QualType Type = Var->getType();1381213813// C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.13814if (isa<DecompositionDecl>(RealDecl)) {13815Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;13816Var->setInvalidDecl();13817return;13818}1381913820if (Type->isUndeducedType() &&13821DeduceVariableDeclarationType(Var, false, nullptr))13822return;1382313824// C++11 [class.static.data]p3: A static data member can be declared with13825// the constexpr specifier; if so, its declaration shall specify13826// a brace-or-equal-initializer.13827// C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to13828// the definition of a variable [...] or the declaration of a static data13829// member.13830if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&13831!Var->isThisDeclarationADemotedDefinition()) {13832if (Var->isStaticDataMember()) {13833// C++1z removes the relevant rule; the in-class declaration is always13834// a definition there.13835if (!getLangOpts().CPlusPlus17 &&13836!Context.getTargetInfo().getCXXABI().isMicrosoft()) {13837Diag(Var->getLocation(),13838diag::err_constexpr_static_mem_var_requires_init)13839<< Var;13840Var->setInvalidDecl();13841return;13842}13843} else {13844Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);13845Var->setInvalidDecl();13846return;13847}13848}1384913850// OpenCL v1.1 s6.5.3: variables declared in the constant address space must13851// be initialized.13852if (!Var->isInvalidDecl() &&13853Var->getType().getAddressSpace() == LangAS::opencl_constant &&13854Var->getStorageClass() != SC_Extern && !Var->getInit()) {13855bool HasConstExprDefaultConstructor = false;13856if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {13857for (auto *Ctor : RD->ctors()) {13858if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&13859Ctor->getMethodQualifiers().getAddressSpace() ==13860LangAS::opencl_constant) {13861HasConstExprDefaultConstructor = true;13862}13863}13864}13865if (!HasConstExprDefaultConstructor) {13866Diag(Var->getLocation(), diag::err_opencl_constant_no_init);13867Var->setInvalidDecl();13868return;13869}13870}1387113872if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {13873if (Var->getStorageClass() == SC_Extern) {13874Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)13875<< Var;13876Var->setInvalidDecl();13877return;13878}13879if (RequireCompleteType(Var->getLocation(), Var->getType(),13880diag::err_typecheck_decl_incomplete_type)) {13881Var->setInvalidDecl();13882return;13883}13884if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {13885if (!RD->hasTrivialDefaultConstructor()) {13886Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);13887Var->setInvalidDecl();13888return;13889}13890}13891// The declaration is uninitialized, no need for further checks.13892return;13893}1389413895VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();13896if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&13897Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())13898checkNonTrivialCUnion(Var->getType(), Var->getLocation(),13899NTCUC_DefaultInitializedObject, NTCUK_Init);139001390113902switch (DefKind) {13903case VarDecl::Definition:13904if (!Var->isStaticDataMember() || !Var->getAnyInitializer())13905break;1390613907// We have an out-of-line definition of a static data member13908// that has an in-class initializer, so we type-check this like13909// a declaration.13910//13911[[fallthrough]];1391213913case VarDecl::DeclarationOnly:13914// It's only a declaration.1391513916// Block scope. C99 6.7p7: If an identifier for an object is13917// declared with no linkage (C99 6.2.2p6), the type for the13918// object shall be complete.13919if (!Type->isDependentType() && Var->isLocalVarDecl() &&13920!Var->hasLinkage() && !Var->isInvalidDecl() &&13921RequireCompleteType(Var->getLocation(), Type,13922diag::err_typecheck_decl_incomplete_type))13923Var->setInvalidDecl();1392413925// Make sure that the type is not abstract.13926if (!Type->isDependentType() && !Var->isInvalidDecl() &&13927RequireNonAbstractType(Var->getLocation(), Type,13928diag::err_abstract_type_in_decl,13929AbstractVariableType))13930Var->setInvalidDecl();13931if (!Type->isDependentType() && !Var->isInvalidDecl() &&13932Var->getStorageClass() == SC_PrivateExtern) {13933Diag(Var->getLocation(), diag::warn_private_extern);13934Diag(Var->getLocation(), diag::note_private_extern);13935}1393613937if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&13938!Var->isInvalidDecl())13939ExternalDeclarations.push_back(Var);1394013941return;1394213943case VarDecl::TentativeDefinition:13944// File scope. C99 6.9.2p2: A declaration of an identifier for an13945// object that has file scope without an initializer, and without a13946// storage-class specifier or with the storage-class specifier "static",13947// constitutes a tentative definition. Note: A tentative definition with13948// external linkage is valid (C99 6.2.2p5).13949if (!Var->isInvalidDecl()) {13950if (const IncompleteArrayType *ArrayT13951= Context.getAsIncompleteArrayType(Type)) {13952if (RequireCompleteSizedType(13953Var->getLocation(), ArrayT->getElementType(),13954diag::err_array_incomplete_or_sizeless_type))13955Var->setInvalidDecl();13956} else if (Var->getStorageClass() == SC_Static) {13957// C99 6.9.2p3: If the declaration of an identifier for an object is13958// a tentative definition and has internal linkage (C99 6.2.2p3), the13959// declared type shall not be an incomplete type.13960// NOTE: code such as the following13961// static struct s;13962// struct s { int a; };13963// is accepted by gcc. Hence here we issue a warning instead of13964// an error and we do not invalidate the static declaration.13965// NOTE: to avoid multiple warnings, only check the first declaration.13966if (Var->isFirstDecl())13967RequireCompleteType(Var->getLocation(), Type,13968diag::ext_typecheck_decl_incomplete_type);13969}13970}1397113972// Record the tentative definition; we're done.13973if (!Var->isInvalidDecl())13974TentativeDefinitions.push_back(Var);13975return;13976}1397713978// Provide a specific diagnostic for uninitialized variable13979// definitions with incomplete array type.13980if (Type->isIncompleteArrayType()) {13981if (Var->isConstexpr())13982Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)13983<< Var;13984else13985Diag(Var->getLocation(),13986diag::err_typecheck_incomplete_array_needs_initializer);13987Var->setInvalidDecl();13988return;13989}1399013991// Provide a specific diagnostic for uninitialized variable13992// definitions with reference type.13993if (Type->isReferenceType()) {13994Diag(Var->getLocation(), diag::err_reference_var_requires_init)13995<< Var << SourceRange(Var->getLocation(), Var->getLocation());13996return;13997}1399813999// Do not attempt to type-check the default initializer for a14000// variable with dependent type.14001if (Type->isDependentType())14002return;1400314004if (Var->isInvalidDecl())14005return;1400614007if (!Var->hasAttr<AliasAttr>()) {14008if (RequireCompleteType(Var->getLocation(),14009Context.getBaseElementType(Type),14010diag::err_typecheck_decl_incomplete_type)) {14011Var->setInvalidDecl();14012return;14013}14014} else {14015return;14016}1401714018// The variable can not have an abstract class type.14019if (RequireNonAbstractType(Var->getLocation(), Type,14020diag::err_abstract_type_in_decl,14021AbstractVariableType)) {14022Var->setInvalidDecl();14023return;14024}1402514026// Check for jumps past the implicit initializer. C++0x14027// clarifies that this applies to a "variable with automatic14028// storage duration", not a "local variable".14029// C++11 [stmt.dcl]p314030// A program that jumps from a point where a variable with automatic14031// storage duration is not in scope to a point where it is in scope is14032// ill-formed unless the variable has scalar type, class type with a14033// trivial default constructor and a trivial destructor, a cv-qualified14034// version of one of these types, or an array of one of the preceding14035// types and is declared without an initializer.14036if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {14037if (const RecordType *Record14038= Context.getBaseElementType(Type)->getAs<RecordType>()) {14039CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());14040// Mark the function (if we're in one) for further checking even if the14041// looser rules of C++11 do not require such checks, so that we can14042// diagnose incompatibilities with C++98.14043if (!CXXRecord->isPOD())14044setFunctionHasBranchProtectedScope();14045}14046}14047// In OpenCL, we can't initialize objects in the __local address space,14048// even implicitly, so don't synthesize an implicit initializer.14049if (getLangOpts().OpenCL &&14050Var->getType().getAddressSpace() == LangAS::opencl_local)14051return;14052// C++03 [dcl.init]p9:14053// If no initializer is specified for an object, and the14054// object is of (possibly cv-qualified) non-POD class type (or14055// array thereof), the object shall be default-initialized; if14056// the object is of const-qualified type, the underlying class14057// type shall have a user-declared default14058// constructor. Otherwise, if no initializer is specified for14059// a non- static object, the object and its subobjects, if14060// any, have an indeterminate initial value); if the object14061// or any of its subobjects are of const-qualified type, the14062// program is ill-formed.14063// C++0x [dcl.init]p11:14064// If no initializer is specified for an object, the object is14065// default-initialized; [...].14066InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);14067InitializationKind Kind14068= InitializationKind::CreateDefault(Var->getLocation());1406914070InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);14071ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);1407214073if (Init.get()) {14074Var->setInit(MaybeCreateExprWithCleanups(Init.get()));14075// This is important for template substitution.14076Var->setInitStyle(VarDecl::CallInit);14077} else if (Init.isInvalid()) {14078// If default-init fails, attach a recovery-expr initializer to track14079// that initialization was attempted and failed.14080auto RecoveryExpr =14081CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});14082if (RecoveryExpr.get())14083Var->setInit(RecoveryExpr.get());14084}1408514086CheckCompleteVariableDeclaration(Var);14087}14088}1408914090void Sema::ActOnCXXForRangeDecl(Decl *D) {14091// If there is no declaration, there was an error parsing it. Ignore it.14092if (!D)14093return;1409414095VarDecl *VD = dyn_cast<VarDecl>(D);14096if (!VD) {14097Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);14098D->setInvalidDecl();14099return;14100}1410114102VD->setCXXForRangeDecl(true);1410314104// for-range-declaration cannot be given a storage class specifier.14105int Error = -1;14106switch (VD->getStorageClass()) {14107case SC_None:14108break;14109case SC_Extern:14110Error = 0;14111break;14112case SC_Static:14113Error = 1;14114break;14115case SC_PrivateExtern:14116Error = 2;14117break;14118case SC_Auto:14119Error = 3;14120break;14121case SC_Register:14122Error = 4;14123break;14124}1412514126// for-range-declaration cannot be given a storage class specifier con't.14127switch (VD->getTSCSpec()) {14128case TSCS_thread_local:14129Error = 6;14130break;14131case TSCS___thread:14132case TSCS__Thread_local:14133case TSCS_unspecified:14134break;14135}1413614137if (Error != -1) {14138Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)14139<< VD << Error;14140D->setInvalidDecl();14141}14142}1414314144StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,14145IdentifierInfo *Ident,14146ParsedAttributes &Attrs) {14147// C++1y [stmt.iter]p1:14148// A range-based for statement of the form14149// for ( for-range-identifier : for-range-initializer ) statement14150// is equivalent to14151// for ( auto&& for-range-identifier : for-range-initializer ) statement14152DeclSpec DS(Attrs.getPool().getFactory());1415314154const char *PrevSpec;14155unsigned DiagID;14156DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,14157getPrintingPolicy());1415814159Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);14160D.SetIdentifier(Ident, IdentLoc);14161D.takeAttributes(Attrs);1416214163D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),14164IdentLoc);14165Decl *Var = ActOnDeclarator(S, D);14166cast<VarDecl>(Var)->setCXXForRangeDecl(true);14167FinalizeDeclaration(Var);14168return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,14169Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()14170: IdentLoc);14171}1417214173void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {14174if (var->isInvalidDecl()) return;1417514176CUDA().MaybeAddConstantAttr(var);1417714178if (getLangOpts().OpenCL) {14179// OpenCL v2.0 s6.12.5 - Every block variable declaration must have an14180// initialiser14181if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&14182!var->hasInit()) {14183Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)14184<< 1 /*Init*/;14185var->setInvalidDecl();14186return;14187}14188}1418914190// In Objective-C, don't allow jumps past the implicit initialization of a14191// local retaining variable.14192if (getLangOpts().ObjC &&14193var->hasLocalStorage()) {14194switch (var->getType().getObjCLifetime()) {14195case Qualifiers::OCL_None:14196case Qualifiers::OCL_ExplicitNone:14197case Qualifiers::OCL_Autoreleasing:14198break;1419914200case Qualifiers::OCL_Weak:14201case Qualifiers::OCL_Strong:14202setFunctionHasBranchProtectedScope();14203break;14204}14205}1420614207if (var->hasLocalStorage() &&14208var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)14209setFunctionHasBranchProtectedScope();1421014211// Warn about externally-visible variables being defined without a14212// prior declaration. We only want to do this for global14213// declarations, but we also specifically need to avoid doing it for14214// class members because the linkage of an anonymous class can14215// change if it's later given a typedef name.14216if (var->isThisDeclarationADefinition() &&14217var->getDeclContext()->getRedeclContext()->isFileContext() &&14218var->isExternallyVisible() && var->hasLinkage() &&14219!var->isInline() && !var->getDescribedVarTemplate() &&14220var->getStorageClass() != SC_Register &&14221!isa<VarTemplatePartialSpecializationDecl>(var) &&14222!isTemplateInstantiation(var->getTemplateSpecializationKind()) &&14223!getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,14224var->getLocation())) {14225// Find a previous declaration that's not a definition.14226VarDecl *prev = var->getPreviousDecl();14227while (prev && prev->isThisDeclarationADefinition())14228prev = prev->getPreviousDecl();1422914230if (!prev) {14231Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;14232Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)14233<< /* variable */ 0;14234}14235}1423614237// Cache the result of checking for constant initialization.14238std::optional<bool> CacheHasConstInit;14239const Expr *CacheCulprit = nullptr;14240auto checkConstInit = [&]() mutable {14241if (!CacheHasConstInit)14242CacheHasConstInit = var->getInit()->isConstantInitializer(14243Context, var->getType()->isReferenceType(), &CacheCulprit);14244return *CacheHasConstInit;14245};1424614247if (var->getTLSKind() == VarDecl::TLS_Static) {14248if (var->getType().isDestructedType()) {14249// GNU C++98 edits for __thread, [basic.start.term]p3:14250// The type of an object with thread storage duration shall not14251// have a non-trivial destructor.14252Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);14253if (getLangOpts().CPlusPlus11)14254Diag(var->getLocation(), diag::note_use_thread_local);14255} else if (getLangOpts().CPlusPlus && var->hasInit()) {14256if (!checkConstInit()) {14257// GNU C++98 edits for __thread, [basic.start.init]p4:14258// An object of thread storage duration shall not require dynamic14259// initialization.14260// FIXME: Need strict checking here.14261Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)14262<< CacheCulprit->getSourceRange();14263if (getLangOpts().CPlusPlus11)14264Diag(var->getLocation(), diag::note_use_thread_local);14265}14266}14267}142681426914270if (!var->getType()->isStructureType() && var->hasInit() &&14271isa<InitListExpr>(var->getInit())) {14272const auto *ILE = cast<InitListExpr>(var->getInit());14273unsigned NumInits = ILE->getNumInits();14274if (NumInits > 2)14275for (unsigned I = 0; I < NumInits; ++I) {14276const auto *Init = ILE->getInit(I);14277if (!Init)14278break;14279const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());14280if (!SL)14281break;1428214283unsigned NumConcat = SL->getNumConcatenated();14284// Diagnose missing comma in string array initialization.14285// Do not warn when all the elements in the initializer are concatenated14286// together. Do not warn for macros too.14287if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {14288bool OnlyOneMissingComma = true;14289for (unsigned J = I + 1; J < NumInits; ++J) {14290const auto *Init = ILE->getInit(J);14291if (!Init)14292break;14293const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());14294if (!SLJ || SLJ->getNumConcatenated() > 1) {14295OnlyOneMissingComma = false;14296break;14297}14298}1429914300if (OnlyOneMissingComma) {14301SmallVector<FixItHint, 1> Hints;14302for (unsigned i = 0; i < NumConcat - 1; ++i)14303Hints.push_back(FixItHint::CreateInsertion(14304PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));1430514306Diag(SL->getStrTokenLoc(1),14307diag::warn_concatenated_literal_array_init)14308<< Hints;14309Diag(SL->getBeginLoc(),14310diag::note_concatenated_string_literal_silence);14311}14312// In any case, stop now.14313break;14314}14315}14316}143171431814319QualType type = var->getType();1432014321if (var->hasAttr<BlocksAttr>())14322getCurFunction()->addByrefBlockVar(var);1432314324Expr *Init = var->getInit();14325bool GlobalStorage = var->hasGlobalStorage();14326bool IsGlobal = GlobalStorage && !var->isStaticLocal();14327QualType baseType = Context.getBaseElementType(type);14328bool HasConstInit = true;1432914330if (getLangOpts().C23 && var->isConstexpr() && !Init)14331Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)14332<< var;1433314334// Check whether the initializer is sufficiently constant.14335if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&14336!type->isDependentType() && Init && !Init->isValueDependent() &&14337(GlobalStorage || var->isConstexpr() ||14338var->mightBeUsableInConstantExpressions(Context))) {14339// If this variable might have a constant initializer or might be usable in14340// constant expressions, check whether or not it actually is now. We can't14341// do this lazily, because the result might depend on things that change14342// later, such as which constexpr functions happen to be defined.14343SmallVector<PartialDiagnosticAt, 8> Notes;14344if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {14345// Prior to C++11, in contexts where a constant initializer is required,14346// the set of valid constant initializers is described by syntactic rules14347// in [expr.const]p2-6.14348// FIXME: Stricter checking for these rules would be useful for constinit /14349// -Wglobal-constructors.14350HasConstInit = checkConstInit();1435114352// Compute and cache the constant value, and remember that we have a14353// constant initializer.14354if (HasConstInit) {14355(void)var->checkForConstantInitialization(Notes);14356Notes.clear();14357} else if (CacheCulprit) {14358Notes.emplace_back(CacheCulprit->getExprLoc(),14359PDiag(diag::note_invalid_subexpr_in_const_expr));14360Notes.back().second << CacheCulprit->getSourceRange();14361}14362} else {14363// Evaluate the initializer to see if it's a constant initializer.14364HasConstInit = var->checkForConstantInitialization(Notes);14365}1436614367if (HasConstInit) {14368// FIXME: Consider replacing the initializer with a ConstantExpr.14369} else if (var->isConstexpr()) {14370SourceLocation DiagLoc = var->getLocation();14371// If the note doesn't add any useful information other than a source14372// location, fold it into the primary diagnostic.14373if (Notes.size() == 1 && Notes[0].second.getDiagID() ==14374diag::note_invalid_subexpr_in_const_expr) {14375DiagLoc = Notes[0].first;14376Notes.clear();14377}14378Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)14379<< var << Init->getSourceRange();14380for (unsigned I = 0, N = Notes.size(); I != N; ++I)14381Diag(Notes[I].first, Notes[I].second);14382} else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {14383auto *Attr = var->getAttr<ConstInitAttr>();14384Diag(var->getLocation(), diag::err_require_constant_init_failed)14385<< Init->getSourceRange();14386Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)14387<< Attr->getRange() << Attr->isConstinit();14388for (auto &it : Notes)14389Diag(it.first, it.second);14390} else if (IsGlobal &&14391!getDiagnostics().isIgnored(diag::warn_global_constructor,14392var->getLocation())) {14393// Warn about globals which don't have a constant initializer. Don't14394// warn about globals with a non-trivial destructor because we already14395// warned about them.14396CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();14397if (!(RD && !RD->hasTrivialDestructor())) {14398// checkConstInit() here permits trivial default initialization even in14399// C++11 onwards, where such an initializer is not a constant initializer14400// but nonetheless doesn't require a global constructor.14401if (!checkConstInit())14402Diag(var->getLocation(), diag::warn_global_constructor)14403<< Init->getSourceRange();14404}14405}14406}1440714408// Apply section attributes and pragmas to global variables.14409if (GlobalStorage && var->isThisDeclarationADefinition() &&14410!inTemplateInstantiation()) {14411PragmaStack<StringLiteral *> *Stack = nullptr;14412int SectionFlags = ASTContext::PSF_Read;14413bool MSVCEnv =14414Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();14415std::optional<QualType::NonConstantStorageReason> Reason;14416if (HasConstInit &&14417!(Reason = var->getType().isNonConstantStorage(Context, true, false))) {14418Stack = &ConstSegStack;14419} else {14420SectionFlags |= ASTContext::PSF_Write;14421Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;14422}14423if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {14424if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)14425SectionFlags |= ASTContext::PSF_Implicit;14426UnifySection(SA->getName(), SectionFlags, var);14427} else if (Stack->CurrentValue) {14428if (Stack != &ConstSegStack && MSVCEnv &&14429ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&14430var->getType().isConstQualified()) {14431assert((!Reason || Reason != QualType::NonConstantStorageReason::14432NonConstNonReferenceType) &&14433"This case should've already been handled elsewhere");14434Diag(var->getLocation(), diag::warn_section_msvc_compat)14435<< var << ConstSegStack.CurrentValue << (int)(!HasConstInit14436? QualType::NonConstantStorageReason::NonTrivialCtor14437: *Reason);14438}14439SectionFlags |= ASTContext::PSF_Implicit;14440auto SectionName = Stack->CurrentValue->getString();14441var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,14442Stack->CurrentPragmaLocation,14443SectionAttr::Declspec_allocate));14444if (UnifySection(SectionName, SectionFlags, var))14445var->dropAttr<SectionAttr>();14446}1444714448// Apply the init_seg attribute if this has an initializer. If the14449// initializer turns out to not be dynamic, we'll end up ignoring this14450// attribute.14451if (CurInitSeg && var->getInit())14452var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),14453CurInitSegLoc));14454}1445514456// All the following checks are C++ only.14457if (!getLangOpts().CPlusPlus) {14458// If this variable must be emitted, add it as an initializer for the14459// current module.14460if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())14461Context.addModuleInitializer(ModuleScopes.back().Module, var);14462return;14463}1446414465// Require the destructor.14466if (!type->isDependentType())14467if (const RecordType *recordType = baseType->getAs<RecordType>())14468FinalizeVarWithDestructor(var, recordType);1446914470// If this variable must be emitted, add it as an initializer for the current14471// module.14472if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())14473Context.addModuleInitializer(ModuleScopes.back().Module, var);1447414475// Build the bindings if this is a structured binding declaration.14476if (auto *DD = dyn_cast<DecompositionDecl>(var))14477CheckCompleteDecompositionDeclaration(DD);14478}1447914480void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {14481assert(VD->isStaticLocal());1448214483auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());1448414485// Find outermost function when VD is in lambda function.14486while (FD && !getDLLAttr(FD) &&14487!FD->hasAttr<DLLExportStaticLocalAttr>() &&14488!FD->hasAttr<DLLImportStaticLocalAttr>()) {14489FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());14490}1449114492if (!FD)14493return;1449414495// Static locals inherit dll attributes from their function.14496if (Attr *A = getDLLAttr(FD)) {14497auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));14498NewAttr->setInherited(true);14499VD->addAttr(NewAttr);14500} else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {14501auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);14502NewAttr->setInherited(true);14503VD->addAttr(NewAttr);1450414505// Export this function to enforce exporting this static variable even14506// if it is not used in this compilation unit.14507if (!FD->hasAttr<DLLExportAttr>())14508FD->addAttr(NewAttr);1450914510} else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {14511auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);14512NewAttr->setInherited(true);14513VD->addAttr(NewAttr);14514}14515}1451614517void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {14518assert(VD->getTLSKind());1451914520// Perform TLS alignment check here after attributes attached to the variable14521// which may affect the alignment have been processed. Only perform the check14522// if the target has a maximum TLS alignment (zero means no constraints).14523if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {14524// Protect the check so that it's not performed on dependent types and14525// dependent alignments (we can't determine the alignment in that case).14526if (!VD->hasDependentAlignment()) {14527CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);14528if (Context.getDeclAlign(VD) > MaxAlignChars) {14529Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)14530<< (unsigned)Context.getDeclAlign(VD).getQuantity() << VD14531<< (unsigned)MaxAlignChars.getQuantity();14532}14533}14534}14535}1453614537void Sema::FinalizeDeclaration(Decl *ThisDecl) {14538// Note that we are no longer parsing the initializer for this declaration.14539ParsingInitForAutoVars.erase(ThisDecl);1454014541VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);14542if (!VD)14543return;1454414545// Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active14546if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&14547!inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {14548if (PragmaClangBSSSection.Valid)14549VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(14550Context, PragmaClangBSSSection.SectionName,14551PragmaClangBSSSection.PragmaLocation));14552if (PragmaClangDataSection.Valid)14553VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(14554Context, PragmaClangDataSection.SectionName,14555PragmaClangDataSection.PragmaLocation));14556if (PragmaClangRodataSection.Valid)14557VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(14558Context, PragmaClangRodataSection.SectionName,14559PragmaClangRodataSection.PragmaLocation));14560if (PragmaClangRelroSection.Valid)14561VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(14562Context, PragmaClangRelroSection.SectionName,14563PragmaClangRelroSection.PragmaLocation));14564}1456514566if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {14567for (auto *BD : DD->bindings()) {14568FinalizeDeclaration(BD);14569}14570}1457114572checkAttributesAfterMerging(*this, *VD);1457314574if (VD->isStaticLocal())14575CheckStaticLocalForDllExport(VD);1457614577if (VD->getTLSKind())14578CheckThreadLocalForLargeAlignment(VD);1457914580// Perform check for initializers of device-side global variables.14581// CUDA allows empty constructors as initializers (see E.2.3.1, CUDA14582// 7.5). We must also apply the same checks to all __shared__14583// variables whether they are local or not. CUDA also allows14584// constant initializers for __constant__ and __device__ variables.14585if (getLangOpts().CUDA)14586CUDA().checkAllowedInitializer(VD);1458714588// Grab the dllimport or dllexport attribute off of the VarDecl.14589const InheritableAttr *DLLAttr = getDLLAttr(VD);1459014591// Imported static data members cannot be defined out-of-line.14592if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {14593if (VD->isStaticDataMember() && VD->isOutOfLine() &&14594VD->isThisDeclarationADefinition()) {14595// We allow definitions of dllimport class template static data members14596// with a warning.14597CXXRecordDecl *Context =14598cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());14599bool IsClassTemplateMember =14600isa<ClassTemplatePartialSpecializationDecl>(Context) ||14601Context->getDescribedClassTemplate();1460214603Diag(VD->getLocation(),14604IsClassTemplateMember14605? diag::warn_attribute_dllimport_static_field_definition14606: diag::err_attribute_dllimport_static_field_definition);14607Diag(IA->getLocation(), diag::note_attribute);14608if (!IsClassTemplateMember)14609VD->setInvalidDecl();14610}14611}1461214613// dllimport/dllexport variables cannot be thread local, their TLS index14614// isn't exported with the variable.14615if (DLLAttr && VD->getTLSKind()) {14616auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());14617if (F && getDLLAttr(F)) {14618assert(VD->isStaticLocal());14619// But if this is a static local in a dlimport/dllexport function, the14620// function will never be inlined, which means the var would never be14621// imported, so having it marked import/export is safe.14622} else {14623Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD14624<< DLLAttr;14625VD->setInvalidDecl();14626}14627}1462814629if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {14630if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {14631Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)14632<< Attr;14633VD->dropAttr<UsedAttr>();14634}14635}14636if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {14637if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {14638Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)14639<< Attr;14640VD->dropAttr<RetainAttr>();14641}14642}1464314644const DeclContext *DC = VD->getDeclContext();14645// If there's a #pragma GCC visibility in scope, and this isn't a class14646// member, set the visibility of this variable.14647if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())14648AddPushedVisibilityAttribute(VD);1464914650// FIXME: Warn on unused var template partial specializations.14651if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))14652MarkUnusedFileScopedDecl(VD);1465314654// Now we have parsed the initializer and can update the table of magic14655// tag values.14656if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||14657!VD->getType()->isIntegralOrEnumerationType())14658return;1465914660for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {14661const Expr *MagicValueExpr = VD->getInit();14662if (!MagicValueExpr) {14663continue;14664}14665std::optional<llvm::APSInt> MagicValueInt;14666if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {14667Diag(I->getRange().getBegin(),14668diag::err_type_tag_for_datatype_not_ice)14669<< LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();14670continue;14671}14672if (MagicValueInt->getActiveBits() > 64) {14673Diag(I->getRange().getBegin(),14674diag::err_type_tag_for_datatype_too_large)14675<< LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();14676continue;14677}14678uint64_t MagicValue = MagicValueInt->getZExtValue();14679RegisterTypeTagForDatatype(I->getArgumentKind(),14680MagicValue,14681I->getMatchingCType(),14682I->getLayoutCompatible(),14683I->getMustBeNull());14684}14685}1468614687static bool hasDeducedAuto(DeclaratorDecl *DD) {14688auto *VD = dyn_cast<VarDecl>(DD);14689return VD && !VD->getType()->hasAutoForTrailingReturnType();14690}1469114692Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,14693ArrayRef<Decl *> Group) {14694SmallVector<Decl*, 8> Decls;1469514696if (DS.isTypeSpecOwned())14697Decls.push_back(DS.getRepAsDecl());1469814699DeclaratorDecl *FirstDeclaratorInGroup = nullptr;14700DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;14701bool DiagnosedMultipleDecomps = false;14702DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;14703bool DiagnosedNonDeducedAuto = false;1470414705for (Decl *D : Group) {14706if (!D)14707continue;14708// Check if the Decl has been declared in '#pragma omp declare target'14709// directive and has static storage duration.14710if (auto *VD = dyn_cast<VarDecl>(D);14711LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&14712VD->hasGlobalStorage())14713OpenMP().ActOnOpenMPDeclareTargetInitializer(D);14714// For declarators, there are some additional syntactic-ish checks we need14715// to perform.14716if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {14717if (!FirstDeclaratorInGroup)14718FirstDeclaratorInGroup = DD;14719if (!FirstDecompDeclaratorInGroup)14720FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);14721if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&14722!hasDeducedAuto(DD))14723FirstNonDeducedAutoInGroup = DD;1472414725if (FirstDeclaratorInGroup != DD) {14726// A decomposition declaration cannot be combined with any other14727// declaration in the same group.14728if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {14729Diag(FirstDecompDeclaratorInGroup->getLocation(),14730diag::err_decomp_decl_not_alone)14731<< FirstDeclaratorInGroup->getSourceRange()14732<< DD->getSourceRange();14733DiagnosedMultipleDecomps = true;14734}1473514736// A declarator that uses 'auto' in any way other than to declare a14737// variable with a deduced type cannot be combined with any other14738// declarator in the same group.14739if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {14740Diag(FirstNonDeducedAutoInGroup->getLocation(),14741diag::err_auto_non_deduced_not_alone)14742<< FirstNonDeducedAutoInGroup->getType()14743->hasAutoForTrailingReturnType()14744<< FirstDeclaratorInGroup->getSourceRange()14745<< DD->getSourceRange();14746DiagnosedNonDeducedAuto = true;14747}14748}14749}1475014751Decls.push_back(D);14752}1475314754if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {14755if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {14756handleTagNumbering(Tag, S);14757if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&14758getLangOpts().CPlusPlus)14759Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);14760}14761}1476214763return BuildDeclaratorGroup(Decls);14764}1476514766Sema::DeclGroupPtrTy14767Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {14768// C++14 [dcl.spec.auto]p7: (DR1347)14769// If the type that replaces the placeholder type is not the same in each14770// deduction, the program is ill-formed.14771if (Group.size() > 1) {14772QualType Deduced;14773VarDecl *DeducedDecl = nullptr;14774for (unsigned i = 0, e = Group.size(); i != e; ++i) {14775VarDecl *D = dyn_cast<VarDecl>(Group[i]);14776if (!D || D->isInvalidDecl())14777break;14778DeducedType *DT = D->getType()->getContainedDeducedType();14779if (!DT || DT->getDeducedType().isNull())14780continue;14781if (Deduced.isNull()) {14782Deduced = DT->getDeducedType();14783DeducedDecl = D;14784} else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {14785auto *AT = dyn_cast<AutoType>(DT);14786auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),14787diag::err_auto_different_deductions)14788<< (AT ? (unsigned)AT->getKeyword() : 3) << Deduced14789<< DeducedDecl->getDeclName() << DT->getDeducedType()14790<< D->getDeclName();14791if (DeducedDecl->hasInit())14792Dia << DeducedDecl->getInit()->getSourceRange();14793if (D->getInit())14794Dia << D->getInit()->getSourceRange();14795D->setInvalidDecl();14796break;14797}14798}14799}1480014801ActOnDocumentableDecls(Group);1480214803return DeclGroupPtrTy::make(14804DeclGroupRef::Create(Context, Group.data(), Group.size()));14805}1480614807void Sema::ActOnDocumentableDecl(Decl *D) {14808ActOnDocumentableDecls(D);14809}1481014811void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {14812// Don't parse the comment if Doxygen diagnostics are ignored.14813if (Group.empty() || !Group[0])14814return;1481514816if (Diags.isIgnored(diag::warn_doc_param_not_found,14817Group[0]->getLocation()) &&14818Diags.isIgnored(diag::warn_unknown_comment_command_name,14819Group[0]->getLocation()))14820return;1482114822if (Group.size() >= 2) {14823// This is a decl group. Normally it will contain only declarations14824// produced from declarator list. But in case we have any definitions or14825// additional declaration references:14826// 'typedef struct S {} S;'14827// 'typedef struct S *S;'14828// 'struct S *pS;'14829// FinalizeDeclaratorGroup adds these as separate declarations.14830Decl *MaybeTagDecl = Group[0];14831if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {14832Group = Group.slice(1);14833}14834}1483514836// FIMXE: We assume every Decl in the group is in the same file.14837// This is false when preprocessor constructs the group from decls in14838// different files (e. g. macros or #include).14839Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());14840}1484114842void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {14843// Check that there are no default arguments inside the type of this14844// parameter.14845if (getLangOpts().CPlusPlus)14846CheckExtraCXXDefaultArguments(D);1484714848// Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).14849if (D.getCXXScopeSpec().isSet()) {14850Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)14851<< D.getCXXScopeSpec().getRange();14852}1485314854// [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a14855// simple identifier except [...irrelevant cases...].14856switch (D.getName().getKind()) {14857case UnqualifiedIdKind::IK_Identifier:14858break;1485914860case UnqualifiedIdKind::IK_OperatorFunctionId:14861case UnqualifiedIdKind::IK_ConversionFunctionId:14862case UnqualifiedIdKind::IK_LiteralOperatorId:14863case UnqualifiedIdKind::IK_ConstructorName:14864case UnqualifiedIdKind::IK_DestructorName:14865case UnqualifiedIdKind::IK_ImplicitSelfParam:14866case UnqualifiedIdKind::IK_DeductionGuideName:14867Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)14868<< GetNameForDeclarator(D).getName();14869break;1487014871case UnqualifiedIdKind::IK_TemplateId:14872case UnqualifiedIdKind::IK_ConstructorTemplateId:14873// GetNameForDeclarator would not produce a useful name in this case.14874Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);14875break;14876}14877}1487814879static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,14880SourceLocation ExplicitThisLoc) {14881if (!ExplicitThisLoc.isValid())14882return;14883assert(S.getLangOpts().CPlusPlus &&14884"explicit parameter in non-cplusplus mode");14885if (!S.getLangOpts().CPlusPlus23)14886S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)14887<< P->getSourceRange();1488814889// C++2b [dcl.fct/7] An explicit object parameter shall not be a function14890// parameter pack.14891if (P->isParameterPack()) {14892S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)14893<< P->getSourceRange();14894return;14895}14896P->setExplicitObjectParameterLoc(ExplicitThisLoc);14897if (LambdaScopeInfo *LSI = S.getCurLambda())14898LSI->ExplicitObjectParameter = P;14899}1490014901Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,14902SourceLocation ExplicitThisLoc) {14903const DeclSpec &DS = D.getDeclSpec();1490414905// Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.1490614907// C++03 [dcl.stc]p2 also permits 'auto'.14908StorageClass SC = SC_None;14909if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {14910SC = SC_Register;14911// In C++11, the 'register' storage class specifier is deprecated.14912// In C++17, it is not allowed, but we tolerate it as an extension.14913if (getLangOpts().CPlusPlus11) {14914Diag(DS.getStorageClassSpecLoc(),14915getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class14916: diag::warn_deprecated_register)14917<< FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());14918}14919} else if (getLangOpts().CPlusPlus &&14920DS.getStorageClassSpec() == DeclSpec::SCS_auto) {14921SC = SC_Auto;14922} else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {14923Diag(DS.getStorageClassSpecLoc(),14924diag::err_invalid_storage_class_in_func_decl);14925D.getMutableDeclSpec().ClearStorageClassSpecs();14926}1492714928if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())14929Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)14930<< DeclSpec::getSpecifierName(TSCS);14931if (DS.isInlineSpecified())14932Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)14933<< getLangOpts().CPlusPlus17;14934if (DS.hasConstexprSpecifier())14935Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)14936<< 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());1493714938DiagnoseFunctionSpecifiers(DS);1493914940CheckFunctionOrTemplateParamDeclarator(S, D);1494114942TypeSourceInfo *TInfo = GetTypeForDeclarator(D);14943QualType parmDeclType = TInfo->getType();1494414945// Check for redeclaration of parameters, e.g. int foo(int x, int x);14946const IdentifierInfo *II = D.getIdentifier();14947if (II) {14948LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,14949RedeclarationKind::ForVisibleRedeclaration);14950LookupName(R, S);14951if (!R.empty()) {14952NamedDecl *PrevDecl = *R.begin();14953if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {14954// Maybe we will complain about the shadowed template parameter.14955DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);14956// Just pretend that we didn't see the previous declaration.14957PrevDecl = nullptr;14958}14959if (PrevDecl && S->isDeclScope(PrevDecl)) {14960Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;14961Diag(PrevDecl->getLocation(), diag::note_previous_declaration);14962// Recover by removing the name14963II = nullptr;14964D.SetIdentifier(nullptr, D.getIdentifierLoc());14965D.setInvalidType(true);14966}14967}14968}1496914970// Temporarily put parameter variables in the translation unit, not14971// the enclosing context. This prevents them from accidentally14972// looking like class members in C++.14973ParmVarDecl *New =14974CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),14975D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);1497614977if (D.isInvalidType())14978New->setInvalidDecl();1497914980CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);1498114982assert(S->isFunctionPrototypeScope());14983assert(S->getFunctionPrototypeDepth() >= 1);14984New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,14985S->getNextFunctionPrototypeIndex());1498614987// Add the parameter declaration into this scope.14988S->AddDecl(New);14989if (II)14990IdResolver.AddDecl(New);1499114992ProcessDeclAttributes(S, New, D);1499314994if (D.getDeclSpec().isModulePrivateSpecified())14995Diag(New->getLocation(), diag::err_module_private_local)14996<< 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())14997<< FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());1499814999if (New->hasAttr<BlocksAttr>()) {15000Diag(New->getLocation(), diag::err_block_on_nonlocal);15001}1500215003if (getLangOpts().OpenCL)15004deduceOpenCLAddressSpace(New);1500515006return New;15007}1500815009ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,15010SourceLocation Loc,15011QualType T) {15012/* FIXME: setting StartLoc == Loc.15013Would it be worth to modify callers so as to provide proper source15014location for the unnamed parameters, embedding the parameter's type? */15015ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,15016T, Context.getTrivialTypeSourceInfo(T, Loc),15017SC_None, nullptr);15018Param->setImplicit();15019return Param;15020}1502115022void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {15023// Don't diagnose unused-parameter errors in template instantiations; we15024// will already have done so in the template itself.15025if (inTemplateInstantiation())15026return;1502715028for (const ParmVarDecl *Parameter : Parameters) {15029if (!Parameter->isReferenced() && Parameter->getDeclName() &&15030!Parameter->hasAttr<UnusedAttr>() &&15031!Parameter->getIdentifier()->isPlaceholder()) {15032Diag(Parameter->getLocation(), diag::warn_unused_parameter)15033<< Parameter->getDeclName();15034}15035}15036}1503715038void Sema::DiagnoseSizeOfParametersAndReturnValue(15039ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {15040if (LangOpts.NumLargeByValueCopy == 0) // No check.15041return;1504215043// Warn if the return value is pass-by-value and larger than the specified15044// threshold.15045if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {15046unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();15047if (Size > LangOpts.NumLargeByValueCopy)15048Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;15049}1505015051// Warn if any parameter is pass-by-value and larger than the specified15052// threshold.15053for (const ParmVarDecl *Parameter : Parameters) {15054QualType T = Parameter->getType();15055if (T->isDependentType() || !T.isPODType(Context))15056continue;15057unsigned Size = Context.getTypeSizeInChars(T).getQuantity();15058if (Size > LangOpts.NumLargeByValueCopy)15059Diag(Parameter->getLocation(), diag::warn_parameter_size)15060<< Parameter << Size;15061}15062}1506315064ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,15065SourceLocation NameLoc,15066const IdentifierInfo *Name, QualType T,15067TypeSourceInfo *TSInfo, StorageClass SC) {15068// In ARC, infer a lifetime qualifier for appropriate parameter types.15069if (getLangOpts().ObjCAutoRefCount &&15070T.getObjCLifetime() == Qualifiers::OCL_None &&15071T->isObjCLifetimeType()) {1507215073Qualifiers::ObjCLifetime lifetime;1507415075// Special cases for arrays:15076// - if it's const, use __unsafe_unretained15077// - otherwise, it's an error15078if (T->isArrayType()) {15079if (!T.isConstQualified()) {15080if (DelayedDiagnostics.shouldDelayDiagnostics())15081DelayedDiagnostics.add(15082sema::DelayedDiagnostic::makeForbiddenType(15083NameLoc, diag::err_arc_array_param_no_ownership, T, false));15084else15085Diag(NameLoc, diag::err_arc_array_param_no_ownership)15086<< TSInfo->getTypeLoc().getSourceRange();15087}15088lifetime = Qualifiers::OCL_ExplicitNone;15089} else {15090lifetime = T->getObjCARCImplicitLifetime();15091}15092T = Context.getLifetimeQualifiedType(T, lifetime);15093}1509415095ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,15096Context.getAdjustedParameterType(T),15097TSInfo, SC, nullptr);1509815099// Make a note if we created a new pack in the scope of a lambda, so that15100// we know that references to that pack must also be expanded within the15101// lambda scope.15102if (New->isParameterPack())15103if (auto *LSI = getEnclosingLambda())15104LSI->LocalPacks.push_back(New);1510515106if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||15107New->getType().hasNonTrivialToPrimitiveCopyCUnion())15108checkNonTrivialCUnion(New->getType(), New->getLocation(),15109NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);1511015111// Parameter declarators cannot be interface types. All ObjC objects are15112// passed by reference.15113if (T->isObjCObjectType()) {15114SourceLocation TypeEndLoc =15115getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());15116Diag(NameLoc,15117diag::err_object_cannot_be_passed_returned_by_value) << 1 << T15118<< FixItHint::CreateInsertion(TypeEndLoc, "*");15119T = Context.getObjCObjectPointerType(T);15120New->setType(T);15121}1512215123// ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage15124// duration shall not be qualified by an address-space qualifier."15125// Since all parameters have automatic store duration, they can not have15126// an address space.15127if (T.getAddressSpace() != LangAS::Default &&15128// OpenCL allows function arguments declared to be an array of a type15129// to be qualified with an address space.15130!(getLangOpts().OpenCL &&15131(T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&15132// WebAssembly allows reference types as parameters. Funcref in particular15133// lives in a different address space.15134!(T->isFunctionPointerType() &&15135T.getAddressSpace() == LangAS::wasm_funcref)) {15136Diag(NameLoc, diag::err_arg_with_address_space);15137New->setInvalidDecl();15138}1513915140// PPC MMA non-pointer types are not allowed as function argument types.15141if (Context.getTargetInfo().getTriple().isPPC64() &&15142PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {15143New->setInvalidDecl();15144}1514515146return New;15147}1514815149void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,15150SourceLocation LocAfterDecls) {15151DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();1515215153// C99 6.9.1p6 "If a declarator includes an identifier list, each declaration15154// in the declaration list shall have at least one declarator, those15155// declarators shall only declare identifiers from the identifier list, and15156// every identifier in the identifier list shall be declared.15157//15158// C89 3.7.1p5 "If a declarator includes an identifier list, only the15159// identifiers it names shall be declared in the declaration list."15160//15161// This is why we only diagnose in C99 and later. Note, the other conditions15162// listed are checked elsewhere.15163if (!FTI.hasPrototype) {15164for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {15165--i;15166if (FTI.Params[i].Param == nullptr) {15167if (getLangOpts().C99) {15168SmallString<256> Code;15169llvm::raw_svector_ostream(Code)15170<< " int " << FTI.Params[i].Ident->getName() << ";\n";15171Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)15172<< FTI.Params[i].Ident15173<< FixItHint::CreateInsertion(LocAfterDecls, Code);15174}1517515176// Implicitly declare the argument as type 'int' for lack of a better15177// type.15178AttributeFactory attrs;15179DeclSpec DS(attrs);15180const char* PrevSpec; // unused15181unsigned DiagID; // unused15182DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,15183DiagID, Context.getPrintingPolicy());15184// Use the identifier location for the type source range.15185DS.SetRangeStart(FTI.Params[i].IdentLoc);15186DS.SetRangeEnd(FTI.Params[i].IdentLoc);15187Declarator ParamD(DS, ParsedAttributesView::none(),15188DeclaratorContext::KNRTypeList);15189ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);15190FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);15191}15192}15193}15194}1519515196Decl *15197Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,15198MultiTemplateParamsArg TemplateParameterLists,15199SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {15200assert(getCurFunctionDecl() == nullptr && "Function parsing confused");15201assert(D.isFunctionDeclarator() && "Not a function declarator!");15202Scope *ParentScope = FnBodyScope->getParent();1520315204// Check if we are in an `omp begin/end declare variant` scope. If we are, and15205// we define a non-templated function definition, we will create a declaration15206// instead (=BaseFD), and emit the definition with a mangled name afterwards.15207// The base function declaration will have the equivalent of an `omp declare15208// variant` annotation which specifies the mangled definition as a15209// specialization function under the OpenMP context defined as part of the15210// `omp begin declare variant`.15211SmallVector<FunctionDecl *, 4> Bases;15212if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())15213OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(15214ParentScope, D, TemplateParameterLists, Bases);1521515216D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);15217Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);15218Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);1521915220if (!Bases.empty())15221OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl,15222Bases);1522315224return Dcl;15225}1522615227void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {15228Consumer.HandleInlineFunctionDefinition(D);15229}1523015231static bool FindPossiblePrototype(const FunctionDecl *FD,15232const FunctionDecl *&PossiblePrototype) {15233for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;15234Prev = Prev->getPreviousDecl()) {15235// Ignore any declarations that occur in function or method15236// scope, because they aren't visible from the header.15237if (Prev->getLexicalDeclContext()->isFunctionOrMethod())15238continue;1523915240PossiblePrototype = Prev;15241return Prev->getType()->isFunctionProtoType();15242}15243return false;15244}1524515246static bool15247ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,15248const FunctionDecl *&PossiblePrototype) {15249// Don't warn about invalid declarations.15250if (FD->isInvalidDecl())15251return false;1525215253// Or declarations that aren't global.15254if (!FD->isGlobal())15255return false;1525615257// Don't warn about C++ member functions.15258if (isa<CXXMethodDecl>(FD))15259return false;1526015261// Don't warn about 'main'.15262if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))15263if (IdentifierInfo *II = FD->getIdentifier())15264if (II->isStr("main") || II->isStr("efi_main"))15265return false;1526615267if (FD->isMSVCRTEntryPoint())15268return false;1526915270// Don't warn about inline functions.15271if (FD->isInlined())15272return false;1527315274// Don't warn about function templates.15275if (FD->getDescribedFunctionTemplate())15276return false;1527715278// Don't warn about function template specializations.15279if (FD->isFunctionTemplateSpecialization())15280return false;1528115282// Don't warn for OpenCL kernels.15283if (FD->hasAttr<OpenCLKernelAttr>())15284return false;1528515286// Don't warn on explicitly deleted functions.15287if (FD->isDeleted())15288return false;1528915290// Don't warn on implicitly local functions (such as having local-typed15291// parameters).15292if (!FD->isExternallyVisible())15293return false;1529415295// If we were able to find a potential prototype, don't warn.15296if (FindPossiblePrototype(FD, PossiblePrototype))15297return false;1529815299return true;15300}1530115302void15303Sema::CheckForFunctionRedefinition(FunctionDecl *FD,15304const FunctionDecl *EffectiveDefinition,15305SkipBodyInfo *SkipBody) {15306const FunctionDecl *Definition = EffectiveDefinition;15307if (!Definition &&15308!FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))15309return;1531015311if (Definition->getFriendObjectKind() != Decl::FOK_None) {15312if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {15313if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {15314// A merged copy of the same function, instantiated as a member of15315// the same class, is OK.15316if (declaresSameEntity(OrigFD, OrigDef) &&15317declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),15318cast<Decl>(FD->getLexicalDeclContext())))15319return;15320}15321}15322}1532315324if (canRedefineFunction(Definition, getLangOpts()))15325return;1532615327// Don't emit an error when this is redefinition of a typo-corrected15328// definition.15329if (TypoCorrectedFunctionDefinitions.count(Definition))15330return;1533115332// If we don't have a visible definition of the function, and it's inline or15333// a template, skip the new definition.15334if (SkipBody && !hasVisibleDefinition(Definition) &&15335(Definition->getFormalLinkage() == Linkage::Internal ||15336Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||15337Definition->getNumTemplateParameterLists())) {15338SkipBody->ShouldSkip = true;15339SkipBody->Previous = const_cast<FunctionDecl*>(Definition);15340if (auto *TD = Definition->getDescribedFunctionTemplate())15341makeMergedDefinitionVisible(TD);15342makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));15343return;15344}1534515346if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&15347Definition->getStorageClass() == SC_Extern)15348Diag(FD->getLocation(), diag::err_redefinition_extern_inline)15349<< FD << getLangOpts().CPlusPlus;15350else15351Diag(FD->getLocation(), diag::err_redefinition) << FD;1535215353Diag(Definition->getLocation(), diag::note_previous_definition);15354FD->setInvalidDecl();15355}1535615357LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {15358CXXRecordDecl *LambdaClass = CallOperator->getParent();1535915360LambdaScopeInfo *LSI = PushLambdaScope();15361LSI->CallOperator = CallOperator;15362LSI->Lambda = LambdaClass;15363LSI->ReturnType = CallOperator->getReturnType();15364// This function in calls in situation where the context of the call operator15365// is not entered, so we set AfterParameterList to false, so that15366// `tryCaptureVariable` finds explicit captures in the appropriate context.15367LSI->AfterParameterList = false;15368const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();1536915370if (LCD == LCD_None)15371LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;15372else if (LCD == LCD_ByCopy)15373LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;15374else if (LCD == LCD_ByRef)15375LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;15376DeclarationNameInfo DNI = CallOperator->getNameInfo();1537715378LSI->IntroducerRange = DNI.getCXXOperatorNameRange();15379LSI->Mutable = !CallOperator->isConst();15380if (CallOperator->isExplicitObjectMemberFunction())15381LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);1538215383// Add the captures to the LSI so they can be noted as already15384// captured within tryCaptureVar.15385auto I = LambdaClass->field_begin();15386for (const auto &C : LambdaClass->captures()) {15387if (C.capturesVariable()) {15388ValueDecl *VD = C.getCapturedVar();15389if (VD->isInitCapture())15390CurrentInstantiationScope->InstantiatedLocal(VD, VD);15391const bool ByRef = C.getCaptureKind() == LCK_ByRef;15392LSI->addCapture(VD, /*IsBlock*/false, ByRef,15393/*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),15394/*EllipsisLoc*/C.isPackExpansion()15395? C.getEllipsisLoc() : SourceLocation(),15396I->getType(), /*Invalid*/false);1539715398} else if (C.capturesThis()) {15399LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),15400C.getCaptureKind() == LCK_StarThis);15401} else {15402LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),15403I->getType());15404}15405++I;15406}15407return LSI;15408}1540915410Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,15411SkipBodyInfo *SkipBody,15412FnBodyKind BodyKind) {15413if (!D) {15414// Parsing the function declaration failed in some way. Push on a fake scope15415// anyway so we can try to parse the function body.15416PushFunctionScope();15417PushExpressionEvaluationContext(ExprEvalContexts.back().Context);15418return D;15419}1542015421FunctionDecl *FD = nullptr;1542215423if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))15424FD = FunTmpl->getTemplatedDecl();15425else15426FD = cast<FunctionDecl>(D);1542715428// Do not push if it is a lambda because one is already pushed when building15429// the lambda in ActOnStartOfLambdaDefinition().15430if (!isLambdaCallOperator(FD))15431// [expr.const]/p14.115432// An expression or conversion is in an immediate function context if it is15433// potentially evaluated and either: its innermost enclosing non-block scope15434// is a function parameter scope of an immediate function.15435PushExpressionEvaluationContext(15436FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext15437: ExprEvalContexts.back().Context);1543815439// Each ExpressionEvaluationContextRecord also keeps track of whether the15440// context is nested in an immediate function context, so smaller contexts15441// that appear inside immediate functions (like variable initializers) are15442// considered to be inside an immediate function context even though by15443// themselves they are not immediate function contexts. But when a new15444// function is entered, we need to reset this tracking, since the entered15445// function might be not an immediate function.15446ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();15447ExprEvalContexts.back().InImmediateEscalatingFunctionContext =15448getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();1544915450// Check for defining attributes before the check for redefinition.15451if (const auto *Attr = FD->getAttr<AliasAttr>()) {15452Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;15453FD->dropAttr<AliasAttr>();15454FD->setInvalidDecl();15455}15456if (const auto *Attr = FD->getAttr<IFuncAttr>()) {15457Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;15458FD->dropAttr<IFuncAttr>();15459FD->setInvalidDecl();15460}15461if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {15462if (!Context.getTargetInfo().hasFeature("fmv") &&15463!Attr->isDefaultVersion()) {15464// If function multi versioning disabled skip parsing function body15465// defined with non-default target_version attribute15466if (SkipBody)15467SkipBody->ShouldSkip = true;15468return nullptr;15469}15470}1547115472if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {15473if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&15474Ctor->isDefaultConstructor() &&15475Context.getTargetInfo().getCXXABI().isMicrosoft()) {15476// If this is an MS ABI dllexport default constructor, instantiate any15477// default arguments.15478InstantiateDefaultCtorDefaultArgs(Ctor);15479}15480}1548115482// See if this is a redefinition. If 'will have body' (or similar) is already15483// set, then these checks were already performed when it was set.15484if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&15485!FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {15486CheckForFunctionRedefinition(FD, nullptr, SkipBody);1548715488// If we're skipping the body, we're done. Don't enter the scope.15489if (SkipBody && SkipBody->ShouldSkip)15490return D;15491}1549215493// Mark this function as "will have a body eventually". This lets users to15494// call e.g. isInlineDefinitionExternallyVisible while we're still parsing15495// this function.15496FD->setWillHaveBody();1549715498// If we are instantiating a generic lambda call operator, push15499// a LambdaScopeInfo onto the function stack. But use the information15500// that's already been calculated (ActOnLambdaExpr) to prime the current15501// LambdaScopeInfo.15502// When the template operator is being specialized, the LambdaScopeInfo,15503// has to be properly restored so that tryCaptureVariable doesn't try15504// and capture any new variables. In addition when calculating potential15505// captures during transformation of nested lambdas, it is necessary to15506// have the LSI properly restored.15507if (isGenericLambdaCallOperatorSpecialization(FD)) {15508// C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly15509// instantiated, explicitly specialized.15510if (FD->getTemplateSpecializationInfo()15511->isExplicitInstantiationOrSpecialization()) {15512Diag(FD->getLocation(), diag::err_lambda_explicit_spec);15513FD->setInvalidDecl();15514PushFunctionScope();15515} else {15516assert(inTemplateInstantiation() &&15517"There should be an active template instantiation on the stack "15518"when instantiating a generic lambda!");15519RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));15520}15521} else {15522// Enter a new function scope15523PushFunctionScope();15524}1552515526// Builtin functions cannot be defined.15527if (unsigned BuiltinID = FD->getBuiltinID()) {15528if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&15529!Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {15530Diag(FD->getLocation(), diag::err_builtin_definition) << FD;15531FD->setInvalidDecl();15532}15533}1553415535// The return type of a function definition must be complete (C99 6.9.1p3).15536// C++23 [dcl.fct.def.general]/p215537// The type of [...] the return for a function definition15538// shall not be a (possibly cv-qualified) class type that is incomplete15539// or abstract within the function body unless the function is deleted.15540QualType ResultType = FD->getReturnType();15541if (!ResultType->isDependentType() && !ResultType->isVoidType() &&15542!FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&15543(RequireCompleteType(FD->getLocation(), ResultType,15544diag::err_func_def_incomplete_result) ||15545RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),15546diag::err_abstract_type_in_decl,15547AbstractReturnType)))15548FD->setInvalidDecl();1554915550if (FnBodyScope)15551PushDeclContext(FnBodyScope, FD);1555215553// Check the validity of our function parameters15554if (BodyKind != FnBodyKind::Delete)15555CheckParmsForFunctionDef(FD->parameters(),15556/*CheckParameterNames=*/true);1555715558// Add non-parameter declarations already in the function to the current15559// scope.15560if (FnBodyScope) {15561for (Decl *NPD : FD->decls()) {15562auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);15563if (!NonParmDecl)15564continue;15565assert(!isa<ParmVarDecl>(NonParmDecl) &&15566"parameters should not be in newly created FD yet");1556715568// If the decl has a name, make it accessible in the current scope.15569if (NonParmDecl->getDeclName())15570PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);1557115572// Similarly, dive into enums and fish their constants out, making them15573// accessible in this scope.15574if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {15575for (auto *EI : ED->enumerators())15576PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);15577}15578}15579}1558015581// Introduce our parameters into the function scope15582for (auto *Param : FD->parameters()) {15583Param->setOwningFunction(FD);1558415585// If this has an identifier, add it to the scope stack.15586if (Param->getIdentifier() && FnBodyScope) {15587CheckShadow(FnBodyScope, Param);1558815589PushOnScopeChains(Param, FnBodyScope);15590}15591}1559215593// C++ [module.import/6] external definitions are not permitted in header15594// units. Deleted and Defaulted functions are implicitly inline (but the15595// inline state is not set at this point, so check the BodyKind explicitly).15596// FIXME: Consider an alternate location for the test where the inlined()15597// state is complete.15598if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&15599!FD->isInvalidDecl() && !FD->isInlined() &&15600BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&15601FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&15602!FD->isTemplateInstantiation()) {15603assert(FD->isThisDeclarationADefinition());15604Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);15605FD->setInvalidDecl();15606}1560715608// Ensure that the function's exception specification is instantiated.15609if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())15610ResolveExceptionSpec(D->getLocation(), FPT);1561115612// dllimport cannot be applied to non-inline function definitions.15613if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&15614!FD->isTemplateInstantiation()) {15615assert(!FD->hasAttr<DLLExportAttr>());15616Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);15617FD->setInvalidDecl();15618return D;15619}1562015621// Some function attributes (like OptimizeNoneAttr) need actions before15622// parsing body started.15623applyFunctionAttributesBeforeParsingBody(D);1562415625// We want to attach documentation to original Decl (which might be15626// a function template).15627ActOnDocumentableDecl(D);15628if (getCurLexicalContext()->isObjCContainer() &&15629getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&15630getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)15631Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);1563215633return D;15634}1563515636void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {15637if (!FD || FD->isInvalidDecl())15638return;15639if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))15640FD = TD->getTemplatedDecl();15641if (FD && FD->hasAttr<OptimizeNoneAttr>()) {15642FPOptionsOverride FPO;15643FPO.setDisallowOptimizations();15644CurFPFeatures.applyChanges(FPO);15645FpPragmaStack.CurrentValue =15646CurFPFeatures.getChangesFrom(FPOptions(LangOpts));15647}15648}1564915650void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {15651ReturnStmt **Returns = Scope->Returns.data();1565215653for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {15654if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {15655if (!NRVOCandidate->isNRVOVariable())15656Returns[I]->setNRVOCandidate(nullptr);15657}15658}15659}1566015661bool Sema::canDelayFunctionBody(const Declarator &D) {15662// We can't delay parsing the body of a constexpr function template (yet).15663if (D.getDeclSpec().hasConstexprSpecifier())15664return false;1566515666// We can't delay parsing the body of a function template with a deduced15667// return type (yet).15668if (D.getDeclSpec().hasAutoTypeSpec()) {15669// If the placeholder introduces a non-deduced trailing return type,15670// we can still delay parsing it.15671if (D.getNumTypeObjects()) {15672const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);15673if (Outer.Kind == DeclaratorChunk::Function &&15674Outer.Fun.hasTrailingReturnType()) {15675QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());15676return Ty.isNull() || !Ty->isUndeducedType();15677}15678}15679return false;15680}1568115682return true;15683}1568415685bool Sema::canSkipFunctionBody(Decl *D) {15686// We cannot skip the body of a function (or function template) which is15687// constexpr, since we may need to evaluate its body in order to parse the15688// rest of the file.15689// We cannot skip the body of a function with an undeduced return type,15690// because any callers of that function need to know the type.15691if (const FunctionDecl *FD = D->getAsFunction()) {15692if (FD->isConstexpr())15693return false;15694// We can't simply call Type::isUndeducedType here, because inside template15695// auto can be deduced to a dependent type, which is not considered15696// "undeduced".15697if (FD->getReturnType()->getContainedDeducedType())15698return false;15699}15700return Consumer.shouldSkipFunctionBody(D);15701}1570215703Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {15704if (!Decl)15705return nullptr;15706if (FunctionDecl *FD = Decl->getAsFunction())15707FD->setHasSkippedBody();15708else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))15709MD->setHasSkippedBody();15710return Decl;15711}1571215713Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {15714return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);15715}1571615717/// RAII object that pops an ExpressionEvaluationContext when exiting a function15718/// body.15719class ExitFunctionBodyRAII {15720public:15721ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}15722~ExitFunctionBodyRAII() {15723if (!IsLambda)15724S.PopExpressionEvaluationContext();15725}1572615727private:15728Sema &S;15729bool IsLambda = false;15730};1573115732static void diagnoseImplicitlyRetainedSelf(Sema &S) {15733llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;1573415735auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {15736if (EscapeInfo.count(BD))15737return EscapeInfo[BD];1573815739bool R = false;15740const BlockDecl *CurBD = BD;1574115742do {15743R = !CurBD->doesNotEscape();15744if (R)15745break;15746CurBD = CurBD->getParent()->getInnermostBlockDecl();15747} while (CurBD);1574815749return EscapeInfo[BD] = R;15750};1575115752// If the location where 'self' is implicitly retained is inside a escaping15753// block, emit a diagnostic.15754for (const std::pair<SourceLocation, const BlockDecl *> &P :15755S.ImplicitlyRetainedSelfLocs)15756if (IsOrNestedInEscapingBlock(P.second))15757S.Diag(P.first, diag::warn_implicitly_retains_self)15758<< FixItHint::CreateInsertion(P.first, "self->");15759}1576015761static bool methodHasName(const FunctionDecl *FD, StringRef Name) {15762return isa<CXXMethodDecl>(FD) && FD->param_empty() &&15763FD->getDeclName().isIdentifier() && FD->getName() == Name;15764}1576515766bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {15767return methodHasName(FD, "get_return_object");15768}1576915770bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {15771return FD->isStatic() &&15772methodHasName(FD, "get_return_object_on_allocation_failure");15773}1577415775void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {15776RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();15777if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())15778return;15779// Allow some_promise_type::get_return_object().15780if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))15781return;15782if (!FD->hasAttr<CoroWrapperAttr>())15783Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;15784}1578515786Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,15787bool IsInstantiation) {15788FunctionScopeInfo *FSI = getCurFunction();15789FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;1579015791if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())15792FD->addAttr(StrictFPAttr::CreateImplicit(Context));1579315794sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();15795sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;1579615797// If we skip function body, we can't tell if a function is a coroutine.15798if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {15799if (FSI->isCoroutine())15800CheckCompletedCoroutineBody(FD, Body);15801else15802CheckCoroutineWrapper(FD);15803}1580415805{15806// Do not call PopExpressionEvaluationContext() if it is a lambda because15807// one is already popped when finishing the lambda in BuildLambdaExpr().15808// This is meant to pop the context added in ActOnStartOfFunctionDef().15809ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));15810if (FD) {15811// If this is called by Parser::ParseFunctionDefinition() after marking15812// the declaration as deleted, and if the deleted-function-body contains15813// a message (C++26), then a DefaultedOrDeletedInfo will have already been15814// added to store that message; do not overwrite it in that case.15815//15816// Since this would always set the body to 'nullptr' in that case anyway,15817// which is already done when the function decl is initially created,15818// always skipping this irrespective of whether there is a delete message15819// should not be a problem.15820if (!FD->isDeletedAsWritten())15821FD->setBody(Body);15822FD->setWillHaveBody(false);15823CheckImmediateEscalatingFunctionDefinition(FD, FSI);1582415825if (getLangOpts().CPlusPlus14) {15826if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&15827FD->getReturnType()->isUndeducedType()) {15828// For a function with a deduced result type to return void,15829// the result type as written must be 'auto' or 'decltype(auto)',15830// possibly cv-qualified or constrained, but not ref-qualified.15831if (!FD->getReturnType()->getAs<AutoType>()) {15832Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)15833<< FD->getReturnType();15834FD->setInvalidDecl();15835} else {15836// Falling off the end of the function is the same as 'return;'.15837Expr *Dummy = nullptr;15838if (DeduceFunctionTypeFromReturnExpr(15839FD, dcl->getLocation(), Dummy,15840FD->getReturnType()->getAs<AutoType>()))15841FD->setInvalidDecl();15842}15843}15844} else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {15845// In C++11, we don't use 'auto' deduction rules for lambda call15846// operators because we don't support return type deduction.15847auto *LSI = getCurLambda();15848if (LSI->HasImplicitReturnType) {15849deduceClosureReturnType(*LSI);1585015851// C++11 [expr.prim.lambda]p4:15852// [...] if there are no return statements in the compound-statement15853// [the deduced type is] the type void15854QualType RetType =15855LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;1585615857// Update the return type to the deduced type.15858const auto *Proto = FD->getType()->castAs<FunctionProtoType>();15859FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),15860Proto->getExtProtoInfo()));15861}15862}1586315864// If the function implicitly returns zero (like 'main') or is naked,15865// don't complain about missing return statements.15866if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())15867WP.disableCheckFallThrough();1586815869// MSVC permits the use of pure specifier (=0) on function definition,15870// defined at class scope, warn about this non-standard construct.15871if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&15872!FD->isOutOfLine())15873Diag(FD->getLocation(), diag::ext_pure_function_definition);1587415875if (!FD->isInvalidDecl()) {15876// Don't diagnose unused parameters of defaulted, deleted or naked15877// functions.15878if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&15879!FD->hasAttr<NakedAttr>())15880DiagnoseUnusedParameters(FD->parameters());15881DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),15882FD->getReturnType(), FD);1588315884// If this is a structor, we need a vtable.15885if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))15886MarkVTableUsed(FD->getLocation(), Constructor->getParent());15887else if (CXXDestructorDecl *Destructor =15888dyn_cast<CXXDestructorDecl>(FD))15889MarkVTableUsed(FD->getLocation(), Destructor->getParent());1589015891// Try to apply the named return value optimization. We have to check15892// if we can do this here because lambdas keep return statements around15893// to deduce an implicit return type.15894if (FD->getReturnType()->isRecordType() &&15895(!getLangOpts().CPlusPlus || !FD->isDependentContext()))15896computeNRVO(Body, FSI);15897}1589815899// GNU warning -Wmissing-prototypes:15900// Warn if a global function is defined without a previous15901// prototype declaration. This warning is issued even if the15902// definition itself provides a prototype. The aim is to detect15903// global functions that fail to be declared in header files.15904const FunctionDecl *PossiblePrototype = nullptr;15905if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {15906Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;1590715908if (PossiblePrototype) {15909// We found a declaration that is not a prototype,15910// but that could be a zero-parameter prototype15911if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {15912TypeLoc TL = TI->getTypeLoc();15913if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())15914Diag(PossiblePrototype->getLocation(),15915diag::note_declaration_not_a_prototype)15916<< (FD->getNumParams() != 0)15917<< (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(15918FTL.getRParenLoc(), "void")15919: FixItHint{});15920}15921} else {15922// Returns true if the token beginning at this Loc is `const`.15923auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,15924const LangOptions &LangOpts) {15925std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);15926if (LocInfo.first.isInvalid())15927return false;1592815929bool Invalid = false;15930StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);15931if (Invalid)15932return false;1593315934if (LocInfo.second > Buffer.size())15935return false;1593615937const char *LexStart = Buffer.data() + LocInfo.second;15938StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);1593915940return StartTok.consume_front("const") &&15941(StartTok.empty() || isWhitespace(StartTok[0]) ||15942StartTok.starts_with("/*") || StartTok.starts_with("//"));15943};1594415945auto findBeginLoc = [&]() {15946// If the return type has `const` qualifier, we want to insert15947// `static` before `const` (and not before the typename).15948if ((FD->getReturnType()->isAnyPointerType() &&15949FD->getReturnType()->getPointeeType().isConstQualified()) ||15950FD->getReturnType().isConstQualified()) {15951// But only do this if we can determine where the `const` is.1595215953if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),15954getLangOpts()))1595515956return FD->getBeginLoc();15957}15958return FD->getTypeSpecStartLoc();15959};15960Diag(FD->getTypeSpecStartLoc(),15961diag::note_static_for_internal_linkage)15962<< /* function */ 115963<< (FD->getStorageClass() == SC_None15964? FixItHint::CreateInsertion(findBeginLoc(), "static ")15965: FixItHint{});15966}15967}1596815969// We might not have found a prototype because we didn't wish to warn on15970// the lack of a missing prototype. Try again without the checks for15971// whether we want to warn on the missing prototype.15972if (!PossiblePrototype)15973(void)FindPossiblePrototype(FD, PossiblePrototype);1597415975// If the function being defined does not have a prototype, then we may15976// need to diagnose it as changing behavior in C23 because we now know15977// whether the function accepts arguments or not. This only handles the15978// case where the definition has no prototype but does have parameters15979// and either there is no previous potential prototype, or the previous15980// potential prototype also has no actual prototype. This handles cases15981// like:15982// void f(); void f(a) int a; {}15983// void g(a) int a; {}15984// See MergeFunctionDecl() for other cases of the behavior change15985// diagnostic. See GetFullTypeForDeclarator() for handling of a function15986// type without a prototype.15987if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&15988(!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&15989!PossiblePrototype->isImplicit()))) {15990// The function definition has parameters, so this will change behavior15991// in C23. If there is a possible prototype, it comes before the15992// function definition.15993// FIXME: The declaration may have already been diagnosed as being15994// deprecated in GetFullTypeForDeclarator() if it had no arguments, but15995// there's no way to test for the "changes behavior" condition in15996// SemaType.cpp when forming the declaration's function type. So, we do15997// this awkward dance instead.15998//15999// If we have a possible prototype and it declares a function with a16000// prototype, we don't want to diagnose it; if we have a possible16001// prototype and it has no prototype, it may have already been16002// diagnosed in SemaType.cpp as deprecated depending on whether16003// -Wstrict-prototypes is enabled. If we already warned about it being16004// deprecated, add a note that it also changes behavior. If we didn't16005// warn about it being deprecated (because the diagnostic is not16006// enabled), warn now that it is deprecated and changes behavior.1600716008// This K&R C function definition definitely changes behavior in C23,16009// so diagnose it.16010Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)16011<< /*definition*/ 1 << /* not supported in C23 */ 0;1601216013// If we have a possible prototype for the function which is a user-16014// visible declaration, we already tested that it has no prototype.16015// This will change behavior in C23. This gets a warning rather than a16016// note because it's the same behavior-changing problem as with the16017// definition.16018if (PossiblePrototype)16019Diag(PossiblePrototype->getLocation(),16020diag::warn_non_prototype_changes_behavior)16021<< /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 116022<< /*definition*/ 1;16023}1602416025// Warn on CPUDispatch with an actual body.16026if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)16027if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))16028if (!CmpndBody->body_empty())16029Diag(CmpndBody->body_front()->getBeginLoc(),16030diag::warn_dispatch_body_ignored);1603116032if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {16033const CXXMethodDecl *KeyFunction;16034if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&16035MD->isVirtual() &&16036(KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&16037MD == KeyFunction->getCanonicalDecl()) {16038// Update the key-function state if necessary for this ABI.16039if (FD->isInlined() &&16040!Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {16041Context.setNonKeyFunction(MD);1604216043// If the newly-chosen key function is already defined, then we16044// need to mark the vtable as used retroactively.16045KeyFunction = Context.getCurrentKeyFunction(MD->getParent());16046const FunctionDecl *Definition;16047if (KeyFunction && KeyFunction->isDefined(Definition))16048MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);16049} else {16050// We just defined they key function; mark the vtable as used.16051MarkVTableUsed(FD->getLocation(), MD->getParent(), true);16052}16053}16054}1605516056assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&16057"Function parsing confused");16058} else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {16059assert(MD == getCurMethodDecl() && "Method parsing confused");16060MD->setBody(Body);16061if (!MD->isInvalidDecl()) {16062DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),16063MD->getReturnType(), MD);1606416065if (Body)16066computeNRVO(Body, FSI);16067}16068if (FSI->ObjCShouldCallSuper) {16069Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)16070<< MD->getSelector().getAsString();16071FSI->ObjCShouldCallSuper = false;16072}16073if (FSI->ObjCWarnForNoDesignatedInitChain) {16074const ObjCMethodDecl *InitMethod = nullptr;16075bool isDesignated =16076MD->isDesignatedInitializerForTheInterface(&InitMethod);16077assert(isDesignated && InitMethod);16078(void)isDesignated;1607916080auto superIsNSObject = [&](const ObjCMethodDecl *MD) {16081auto IFace = MD->getClassInterface();16082if (!IFace)16083return false;16084auto SuperD = IFace->getSuperClass();16085if (!SuperD)16086return false;16087return SuperD->getIdentifier() ==16088ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);16089};16090// Don't issue this warning for unavailable inits or direct subclasses16091// of NSObject.16092if (!MD->isUnavailable() && !superIsNSObject(MD)) {16093Diag(MD->getLocation(),16094diag::warn_objc_designated_init_missing_super_call);16095Diag(InitMethod->getLocation(),16096diag::note_objc_designated_init_marked_here);16097}16098FSI->ObjCWarnForNoDesignatedInitChain = false;16099}16100if (FSI->ObjCWarnForNoInitDelegation) {16101// Don't issue this warning for unavailable inits.16102if (!MD->isUnavailable())16103Diag(MD->getLocation(),16104diag::warn_objc_secondary_init_missing_init_call);16105FSI->ObjCWarnForNoInitDelegation = false;16106}1610716108diagnoseImplicitlyRetainedSelf(*this);16109} else {16110// Parsing the function declaration failed in some way. Pop the fake scope16111// we pushed on.16112PopFunctionScopeInfo(ActivePolicy, dcl);16113return nullptr;16114}1611516116if (Body && FSI->HasPotentialAvailabilityViolations)16117DiagnoseUnguardedAvailabilityViolations(dcl);1611816119assert(!FSI->ObjCShouldCallSuper &&16120"This should only be set for ObjC methods, which should have been "16121"handled in the block above.");1612216123// Verify and clean out per-function state.16124if (Body && (!FD || !FD->isDefaulted())) {16125// C++ constructors that have function-try-blocks can't have return16126// statements in the handlers of that block. (C++ [except.handle]p14)16127// Verify this.16128if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))16129DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));1613016131// Verify that gotos and switch cases don't jump into scopes illegally.16132if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())16133DiagnoseInvalidJumps(Body);1613416135if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {16136if (!Destructor->getParent()->isDependentType())16137CheckDestructor(Destructor);1613816139MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),16140Destructor->getParent());16141}1614216143// If any errors have occurred, clear out any temporaries that may have16144// been leftover. This ensures that these temporaries won't be picked up16145// for deletion in some later function.16146if (hasUncompilableErrorOccurred() ||16147hasAnyUnrecoverableErrorsInThisFunction() ||16148getDiagnostics().getSuppressAllDiagnostics()) {16149DiscardCleanupsInEvaluationContext();16150}16151if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {16152// Since the body is valid, issue any analysis-based warnings that are16153// enabled.16154ActivePolicy = &WP;16155}1615616157if (!IsInstantiation && FD &&16158(FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&16159!FD->isInvalidDecl() &&16160!CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))16161FD->setInvalidDecl();1616216163if (FD && FD->hasAttr<NakedAttr>()) {16164for (const Stmt *S : Body->children()) {16165// Allow local register variables without initializer as they don't16166// require prologue.16167bool RegisterVariables = false;16168if (auto *DS = dyn_cast<DeclStmt>(S)) {16169for (const auto *Decl : DS->decls()) {16170if (const auto *Var = dyn_cast<VarDecl>(Decl)) {16171RegisterVariables =16172Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();16173if (!RegisterVariables)16174break;16175}16176}16177}16178if (RegisterVariables)16179continue;16180if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {16181Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);16182Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);16183FD->setInvalidDecl();16184break;16185}16186}16187}1618816189assert(ExprCleanupObjects.size() ==16190ExprEvalContexts.back().NumCleanupObjects &&16191"Leftover temporaries in function");16192assert(!Cleanup.exprNeedsCleanups() &&16193"Unaccounted cleanups in function");16194assert(MaybeODRUseExprs.empty() &&16195"Leftover expressions for odr-use checking");16196}16197} // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop16198// the declaration context below. Otherwise, we're unable to transform16199// 'this' expressions when transforming immediate context functions.1620016201if (!IsInstantiation)16202PopDeclContext();1620316204PopFunctionScopeInfo(ActivePolicy, dcl);16205// If any errors have occurred, clear out any temporaries that may have16206// been leftover. This ensures that these temporaries won't be picked up for16207// deletion in some later function.16208if (hasUncompilableErrorOccurred()) {16209DiscardCleanupsInEvaluationContext();16210}1621116212if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||16213!LangOpts.OMPTargetTriples.empty())) ||16214LangOpts.CUDA || LangOpts.SYCLIsDevice)) {16215auto ES = getEmissionStatus(FD);16216if (ES == Sema::FunctionEmissionStatus::Emitted ||16217ES == Sema::FunctionEmissionStatus::Unknown)16218DeclsToCheckForDeferredDiags.insert(FD);16219}1622016221if (FD && !FD->isDeleted())16222checkTypeSupport(FD->getType(), FD->getLocation(), FD);1622316224return dcl;16225}1622616227/// When we finish delayed parsing of an attribute, we must attach it to the16228/// relevant Decl.16229void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,16230ParsedAttributes &Attrs) {16231// Always attach attributes to the underlying decl.16232if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))16233D = TD->getTemplatedDecl();16234ProcessDeclAttributeList(S, D, Attrs);16235ProcessAPINotes(D);1623616237if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))16238if (Method->isStatic())16239checkThisInStaticMemberFunctionAttributes(Method);16240}1624116242NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,16243IdentifierInfo &II, Scope *S) {16244// It is not valid to implicitly define a function in C23.16245assert(LangOpts.implicitFunctionsAllowed() &&16246"Implicit function declarations aren't allowed in this language mode");1624716248// Find the scope in which the identifier is injected and the corresponding16249// DeclContext.16250// FIXME: C89 does not say what happens if there is no enclosing block scope.16251// In that case, we inject the declaration into the translation unit scope16252// instead.16253Scope *BlockScope = S;16254while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())16255BlockScope = BlockScope->getParent();1625616257// Loop until we find a DeclContext that is either a function/method or the16258// translation unit, which are the only two valid places to implicitly define16259// a function. This avoids accidentally defining the function within a tag16260// declaration, for example.16261Scope *ContextScope = BlockScope;16262while (!ContextScope->getEntity() ||16263(!ContextScope->getEntity()->isFunctionOrMethod() &&16264!ContextScope->getEntity()->isTranslationUnit()))16265ContextScope = ContextScope->getParent();16266ContextRAII SavedContext(*this, ContextScope->getEntity());1626716268// Before we produce a declaration for an implicitly defined16269// function, see whether there was a locally-scoped declaration of16270// this name as a function or variable. If so, use that16271// (non-visible) declaration, and complain about it.16272NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);16273if (ExternCPrev) {16274// We still need to inject the function into the enclosing block scope so16275// that later (non-call) uses can see it.16276PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);1627716278// C89 footnote 38:16279// If in fact it is not defined as having type "function returning int",16280// the behavior is undefined.16281if (!isa<FunctionDecl>(ExternCPrev) ||16282!Context.typesAreCompatible(16283cast<FunctionDecl>(ExternCPrev)->getType(),16284Context.getFunctionNoProtoType(Context.IntTy))) {16285Diag(Loc, diag::ext_use_out_of_scope_declaration)16286<< ExternCPrev << !getLangOpts().C99;16287Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);16288return ExternCPrev;16289}16290}1629116292// Extension in C99 (defaults to error). Legal in C89, but warn about it.16293unsigned diag_id;16294if (II.getName().starts_with("__builtin_"))16295diag_id = diag::warn_builtin_unknown;16296// OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.16297else if (getLangOpts().C99)16298diag_id = diag::ext_implicit_function_decl_c99;16299else16300diag_id = diag::warn_implicit_function_decl;1630116302TypoCorrection Corrected;16303// Because typo correction is expensive, only do it if the implicit16304// function declaration is going to be treated as an error.16305//16306// Perform the correction before issuing the main diagnostic, as some16307// consumers use typo-correction callbacks to enhance the main diagnostic.16308if (S && !ExternCPrev &&16309(Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {16310DeclFilterCCC<FunctionDecl> CCC{};16311Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,16312S, nullptr, CCC, CTK_NonError);16313}1631416315Diag(Loc, diag_id) << &II;16316if (Corrected) {16317// If the correction is going to suggest an implicitly defined function,16318// skip the correction as not being a particularly good idea.16319bool Diagnose = true;16320if (const auto *D = Corrected.getCorrectionDecl())16321Diagnose = !D->isImplicit();16322if (Diagnose)16323diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),16324/*ErrorRecovery*/ false);16325}1632616327// If we found a prior declaration of this function, don't bother building16328// another one. We've already pushed that one into scope, so there's nothing16329// more to do.16330if (ExternCPrev)16331return ExternCPrev;1633216333// Set a Declarator for the implicit definition: int foo();16334const char *Dummy;16335AttributeFactory attrFactory;16336DeclSpec DS(attrFactory);16337unsigned DiagID;16338bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,16339Context.getPrintingPolicy());16340(void)Error; // Silence warning.16341assert(!Error && "Error setting up implicit decl!");16342SourceLocation NoLoc;16343Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);16344D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,16345/*IsAmbiguous=*/false,16346/*LParenLoc=*/NoLoc,16347/*Params=*/nullptr,16348/*NumParams=*/0,16349/*EllipsisLoc=*/NoLoc,16350/*RParenLoc=*/NoLoc,16351/*RefQualifierIsLvalueRef=*/true,16352/*RefQualifierLoc=*/NoLoc,16353/*MutableLoc=*/NoLoc, EST_None,16354/*ESpecRange=*/SourceRange(),16355/*Exceptions=*/nullptr,16356/*ExceptionRanges=*/nullptr,16357/*NumExceptions=*/0,16358/*NoexceptExpr=*/nullptr,16359/*ExceptionSpecTokens=*/nullptr,16360/*DeclsInPrototype=*/std::nullopt,16361Loc, Loc, D),16362std::move(DS.getAttributes()), SourceLocation());16363D.SetIdentifier(&II, Loc);1636416365// Insert this function into the enclosing block scope.16366FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));16367FD->setImplicit();1636816369AddKnownFunctionAttributes(FD);1637016371return FD;16372}1637316374void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(16375FunctionDecl *FD) {16376if (FD->isInvalidDecl())16377return;1637816379if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&16380FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)16381return;1638216383std::optional<unsigned> AlignmentParam;16384bool IsNothrow = false;16385if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))16386return;1638716388// C++2a [basic.stc.dynamic.allocation]p4:16389// An allocation function that has a non-throwing exception specification16390// indicates failure by returning a null pointer value. Any other allocation16391// function never returns a null pointer value and indicates failure only by16392// throwing an exception [...]16393//16394// However, -fcheck-new invalidates this possible assumption, so don't add16395// NonNull when that is enabled.16396if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&16397!getLangOpts().CheckNew)16398FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));1639916400// C++2a [basic.stc.dynamic.allocation]p2:16401// An allocation function attempts to allocate the requested amount of16402// storage. [...] If the request succeeds, the value returned by a16403// replaceable allocation function is a [...] pointer value p0 different16404// from any previously returned value p1 [...]16405//16406// However, this particular information is being added in codegen,16407// because there is an opt-out switch for it (-fno-assume-sane-operator-new)1640816409// C++2a [basic.stc.dynamic.allocation]p2:16410// An allocation function attempts to allocate the requested amount of16411// storage. If it is successful, it returns the address of the start of a16412// block of storage whose length in bytes is at least as large as the16413// requested size.16414if (!FD->hasAttr<AllocSizeAttr>()) {16415FD->addAttr(AllocSizeAttr::CreateImplicit(16416Context, /*ElemSizeParam=*/ParamIdx(1, FD),16417/*NumElemsParam=*/ParamIdx(), FD->getLocation()));16418}1641916420// C++2a [basic.stc.dynamic.allocation]p3:16421// For an allocation function [...], the pointer returned on a successful16422// call shall represent the address of storage that is aligned as follows:16423// (3.1) If the allocation function takes an argument of type16424// std​::​align_Âval_Ât, the storage will have the alignment16425// specified by the value of this argument.16426if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {16427FD->addAttr(AllocAlignAttr::CreateImplicit(16428Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));16429}1643016431// FIXME:16432// C++2a [basic.stc.dynamic.allocation]p3:16433// For an allocation function [...], the pointer returned on a successful16434// call shall represent the address of storage that is aligned as follows:16435// (3.2) Otherwise, if the allocation function is named operator new[],16436// the storage is aligned for any object that does not have16437// new-extended alignment ([basic.align]) and is no larger than the16438// requested size.16439// (3.3) Otherwise, the storage is aligned for any object that does not16440// have new-extended alignment and is of the requested size.16441}1644216443void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {16444if (FD->isInvalidDecl())16445return;1644616447// If this is a built-in function, map its builtin attributes to16448// actual attributes.16449if (unsigned BuiltinID = FD->getBuiltinID()) {16450// Handle printf-formatting attributes.16451unsigned FormatIdx;16452bool HasVAListArg;16453if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {16454if (!FD->hasAttr<FormatAttr>()) {16455const char *fmt = "printf";16456unsigned int NumParams = FD->getNumParams();16457if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)16458FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())16459fmt = "NSString";16460FD->addAttr(FormatAttr::CreateImplicit(Context,16461&Context.Idents.get(fmt),16462FormatIdx+1,16463HasVAListArg ? 0 : FormatIdx+2,16464FD->getLocation()));16465}16466}16467if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,16468HasVAListArg)) {16469if (!FD->hasAttr<FormatAttr>())16470FD->addAttr(FormatAttr::CreateImplicit(Context,16471&Context.Idents.get("scanf"),16472FormatIdx+1,16473HasVAListArg ? 0 : FormatIdx+2,16474FD->getLocation()));16475}1647616477// Handle automatically recognized callbacks.16478SmallVector<int, 4> Encoding;16479if (!FD->hasAttr<CallbackAttr>() &&16480Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))16481FD->addAttr(CallbackAttr::CreateImplicit(16482Context, Encoding.data(), Encoding.size(), FD->getLocation()));1648316484// Mark const if we don't care about errno and/or floating point exceptions16485// that are the only thing preventing the function from being const. This16486// allows IRgen to use LLVM intrinsics for such functions.16487bool NoExceptions =16488getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;16489bool ConstWithoutErrnoAndExceptions =16490Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);16491bool ConstWithoutExceptions =16492Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);16493if (!FD->hasAttr<ConstAttr>() &&16494(ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&16495(!ConstWithoutErrnoAndExceptions ||16496(!getLangOpts().MathErrno && NoExceptions)) &&16497(!ConstWithoutExceptions || NoExceptions))16498FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));1649916500// We make "fma" on GNU or Windows const because we know it does not set16501// errno in those environments even though it could set errno based on the16502// C standard.16503const llvm::Triple &Trip = Context.getTargetInfo().getTriple();16504if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&16505!FD->hasAttr<ConstAttr>()) {16506switch (BuiltinID) {16507case Builtin::BI__builtin_fma:16508case Builtin::BI__builtin_fmaf:16509case Builtin::BI__builtin_fmal:16510case Builtin::BIfma:16511case Builtin::BIfmaf:16512case Builtin::BIfmal:16513FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));16514break;16515default:16516break;16517}16518}1651916520if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&16521!FD->hasAttr<ReturnsTwiceAttr>())16522FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,16523FD->getLocation()));16524if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())16525FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));16526if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())16527FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));16528if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())16529FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));16530if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&16531!FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {16532// Add the appropriate attribute, depending on the CUDA compilation mode16533// and which target the builtin belongs to. For example, during host16534// compilation, aux builtins are __device__, while the rest are __host__.16535if (getLangOpts().CUDAIsDevice !=16536Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))16537FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));16538else16539FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));16540}1654116542// Add known guaranteed alignment for allocation functions.16543switch (BuiltinID) {16544case Builtin::BImemalign:16545case Builtin::BIaligned_alloc:16546if (!FD->hasAttr<AllocAlignAttr>())16547FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),16548FD->getLocation()));16549break;16550default:16551break;16552}1655316554// Add allocsize attribute for allocation functions.16555switch (BuiltinID) {16556case Builtin::BIcalloc:16557FD->addAttr(AllocSizeAttr::CreateImplicit(16558Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));16559break;16560case Builtin::BImemalign:16561case Builtin::BIaligned_alloc:16562case Builtin::BIrealloc:16563FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),16564ParamIdx(), FD->getLocation()));16565break;16566case Builtin::BImalloc:16567FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),16568ParamIdx(), FD->getLocation()));16569break;16570default:16571break;16572}1657316574// Add lifetime attribute to std::move, std::fowrard et al.16575switch (BuiltinID) {16576case Builtin::BIaddressof:16577case Builtin::BI__addressof:16578case Builtin::BI__builtin_addressof:16579case Builtin::BIas_const:16580case Builtin::BIforward:16581case Builtin::BIforward_like:16582case Builtin::BImove:16583case Builtin::BImove_if_noexcept:16584if (ParmVarDecl *P = FD->getParamDecl(0u);16585!P->hasAttr<LifetimeBoundAttr>())16586P->addAttr(16587LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));16588break;16589default:16590break;16591}16592}1659316594AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);1659516596// If C++ exceptions are enabled but we are told extern "C" functions cannot16597// throw, add an implicit nothrow attribute to any extern "C" function we come16598// across.16599if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&16600FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {16601const auto *FPT = FD->getType()->getAs<FunctionProtoType>();16602if (!FPT || FPT->getExceptionSpecType() == EST_None)16603FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));16604}1660516606IdentifierInfo *Name = FD->getIdentifier();16607if (!Name)16608return;16609if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||16610(isa<LinkageSpecDecl>(FD->getDeclContext()) &&16611cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==16612LinkageSpecLanguageIDs::C)) {16613// Okay: this could be a libc/libm/Objective-C function we know16614// about.16615} else16616return;1661716618if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {16619// FIXME: asprintf and vasprintf aren't C99 functions. Should they be16620// target-specific builtins, perhaps?16621if (!FD->hasAttr<FormatAttr>())16622FD->addAttr(FormatAttr::CreateImplicit(Context,16623&Context.Idents.get("printf"), 2,16624Name->isStr("vasprintf") ? 0 : 3,16625FD->getLocation()));16626}1662716628if (Name->isStr("__CFStringMakeConstantString")) {16629// We already have a __builtin___CFStringMakeConstantString,16630// but builds that use -fno-constant-cfstrings don't go through that.16631if (!FD->hasAttr<FormatArgAttr>())16632FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),16633FD->getLocation()));16634}16635}1663616637TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,16638TypeSourceInfo *TInfo) {16639assert(D.getIdentifier() && "Wrong callback for declspec without declarator");16640assert(!T.isNull() && "GetTypeForDeclarator() returned null type");1664116642if (!TInfo) {16643assert(D.isInvalidType() && "no declarator info for valid type");16644TInfo = Context.getTrivialTypeSourceInfo(T);16645}1664616647// Scope manipulation handled by caller.16648TypedefDecl *NewTD =16649TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),16650D.getIdentifierLoc(), D.getIdentifier(), TInfo);1665116652// Bail out immediately if we have an invalid declaration.16653if (D.isInvalidType()) {16654NewTD->setInvalidDecl();16655return NewTD;16656}1665716658if (D.getDeclSpec().isModulePrivateSpecified()) {16659if (CurContext->isFunctionOrMethod())16660Diag(NewTD->getLocation(), diag::err_module_private_local)16661<< 2 << NewTD16662<< SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())16663<< FixItHint::CreateRemoval(16664D.getDeclSpec().getModulePrivateSpecLoc());16665else16666NewTD->setModulePrivate();16667}1666816669// C++ [dcl.typedef]p8:16670// If the typedef declaration defines an unnamed class (or16671// enum), the first typedef-name declared by the declaration16672// to be that class type (or enum type) is used to denote the16673// class type (or enum type) for linkage purposes only.16674// We need to check whether the type was declared in the declaration.16675switch (D.getDeclSpec().getTypeSpecType()) {16676case TST_enum:16677case TST_struct:16678case TST_interface:16679case TST_union:16680case TST_class: {16681TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());16682setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);16683break;16684}1668516686default:16687break;16688}1668916690return NewTD;16691}1669216693bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {16694SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();16695QualType T = TI->getType();1669616697if (T->isDependentType())16698return false;1669916700// This doesn't use 'isIntegralType' despite the error message mentioning16701// integral type because isIntegralType would also allow enum types in C.16702if (const BuiltinType *BT = T->getAs<BuiltinType>())16703if (BT->isInteger())16704return false;1670516706return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)16707<< T << T->isBitIntType();16708}1670916710bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,16711QualType EnumUnderlyingTy, bool IsFixed,16712const EnumDecl *Prev) {16713if (IsScoped != Prev->isScoped()) {16714Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)16715<< Prev->isScoped();16716Diag(Prev->getLocation(), diag::note_previous_declaration);16717return true;16718}1671916720if (IsFixed && Prev->isFixed()) {16721if (!EnumUnderlyingTy->isDependentType() &&16722!Prev->getIntegerType()->isDependentType() &&16723!Context.hasSameUnqualifiedType(EnumUnderlyingTy,16724Prev->getIntegerType())) {16725// TODO: Highlight the underlying type of the redeclaration.16726Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)16727<< EnumUnderlyingTy << Prev->getIntegerType();16728Diag(Prev->getLocation(), diag::note_previous_declaration)16729<< Prev->getIntegerTypeRange();16730return true;16731}16732} else if (IsFixed != Prev->isFixed()) {16733Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)16734<< Prev->isFixed();16735Diag(Prev->getLocation(), diag::note_previous_declaration);16736return true;16737}1673816739return false;16740}1674116742/// Get diagnostic %select index for tag kind for16743/// redeclaration diagnostic message.16744/// WARNING: Indexes apply to particular diagnostics only!16745///16746/// \returns diagnostic %select index.16747static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {16748switch (Tag) {16749case TagTypeKind::Struct:16750return 0;16751case TagTypeKind::Interface:16752return 1;16753case TagTypeKind::Class:16754return 2;16755default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");16756}16757}1675816759/// Determine if tag kind is a class-key compatible with16760/// class for redeclaration (class, struct, or __interface).16761///16762/// \returns true iff the tag kind is compatible.16763static bool isClassCompatTagKind(TagTypeKind Tag)16764{16765return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||16766Tag == TagTypeKind::Interface;16767}1676816769Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,16770TagTypeKind TTK) {16771if (isa<TypedefDecl>(PrevDecl))16772return NTK_Typedef;16773else if (isa<TypeAliasDecl>(PrevDecl))16774return NTK_TypeAlias;16775else if (isa<ClassTemplateDecl>(PrevDecl))16776return NTK_Template;16777else if (isa<TypeAliasTemplateDecl>(PrevDecl))16778return NTK_TypeAliasTemplate;16779else if (isa<TemplateTemplateParmDecl>(PrevDecl))16780return NTK_TemplateTemplateArgument;16781switch (TTK) {16782case TagTypeKind::Struct:16783case TagTypeKind::Interface:16784case TagTypeKind::Class:16785return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;16786case TagTypeKind::Union:16787return NTK_NonUnion;16788case TagTypeKind::Enum:16789return NTK_NonEnum;16790}16791llvm_unreachable("invalid TTK");16792}1679316794bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,16795TagTypeKind NewTag, bool isDefinition,16796SourceLocation NewTagLoc,16797const IdentifierInfo *Name) {16798// C++ [dcl.type.elab]p3:16799// The class-key or enum keyword present in the16800// elaborated-type-specifier shall agree in kind with the16801// declaration to which the name in the elaborated-type-specifier16802// refers. This rule also applies to the form of16803// elaborated-type-specifier that declares a class-name or16804// friend class since it can be construed as referring to the16805// definition of the class. Thus, in any16806// elaborated-type-specifier, the enum keyword shall be used to16807// refer to an enumeration (7.2), the union class-key shall be16808// used to refer to a union (clause 9), and either the class or16809// struct class-key shall be used to refer to a class (clause 9)16810// declared using the class or struct class-key.16811TagTypeKind OldTag = Previous->getTagKind();16812if (OldTag != NewTag &&16813!(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))16814return false;1681516816// Tags are compatible, but we might still want to warn on mismatched tags.16817// Non-class tags can't be mismatched at this point.16818if (!isClassCompatTagKind(NewTag))16819return true;1682016821// Declarations for which -Wmismatched-tags is disabled are entirely ignored16822// by our warning analysis. We don't want to warn about mismatches with (eg)16823// declarations in system headers that are designed to be specialized, but if16824// a user asks us to warn, we should warn if their code contains mismatched16825// declarations.16826auto IsIgnoredLoc = [&](SourceLocation Loc) {16827return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,16828Loc);16829};16830if (IsIgnoredLoc(NewTagLoc))16831return true;1683216833auto IsIgnored = [&](const TagDecl *Tag) {16834return IsIgnoredLoc(Tag->getLocation());16835};16836while (IsIgnored(Previous)) {16837Previous = Previous->getPreviousDecl();16838if (!Previous)16839return true;16840OldTag = Previous->getTagKind();16841}1684216843bool isTemplate = false;16844if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))16845isTemplate = Record->getDescribedClassTemplate();1684616847if (inTemplateInstantiation()) {16848if (OldTag != NewTag) {16849// In a template instantiation, do not offer fix-its for tag mismatches16850// since they usually mess up the template instead of fixing the problem.16851Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)16852<< getRedeclDiagFromTagKind(NewTag) << isTemplate << Name16853<< getRedeclDiagFromTagKind(OldTag);16854// FIXME: Note previous location?16855}16856return true;16857}1685816859if (isDefinition) {16860// On definitions, check all previous tags and issue a fix-it for each16861// one that doesn't match the current tag.16862if (Previous->getDefinition()) {16863// Don't suggest fix-its for redefinitions.16864return true;16865}1686616867bool previousMismatch = false;16868for (const TagDecl *I : Previous->redecls()) {16869if (I->getTagKind() != NewTag) {16870// Ignore previous declarations for which the warning was disabled.16871if (IsIgnored(I))16872continue;1687316874if (!previousMismatch) {16875previousMismatch = true;16876Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)16877<< getRedeclDiagFromTagKind(NewTag) << isTemplate << Name16878<< getRedeclDiagFromTagKind(I->getTagKind());16879}16880Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)16881<< getRedeclDiagFromTagKind(NewTag)16882<< FixItHint::CreateReplacement(I->getInnerLocStart(),16883TypeWithKeyword::getTagTypeKindName(NewTag));16884}16885}16886return true;16887}1688816889// Identify the prevailing tag kind: this is the kind of the definition (if16890// there is a non-ignored definition), or otherwise the kind of the prior16891// (non-ignored) declaration.16892const TagDecl *PrevDef = Previous->getDefinition();16893if (PrevDef && IsIgnored(PrevDef))16894PrevDef = nullptr;16895const TagDecl *Redecl = PrevDef ? PrevDef : Previous;16896if (Redecl->getTagKind() != NewTag) {16897Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)16898<< getRedeclDiagFromTagKind(NewTag) << isTemplate << Name16899<< getRedeclDiagFromTagKind(OldTag);16900Diag(Redecl->getLocation(), diag::note_previous_use);1690116902// If there is a previous definition, suggest a fix-it.16903if (PrevDef) {16904Diag(NewTagLoc, diag::note_struct_class_suggestion)16905<< getRedeclDiagFromTagKind(Redecl->getTagKind())16906<< FixItHint::CreateReplacement(SourceRange(NewTagLoc),16907TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));16908}16909}1691016911return true;16912}1691316914/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name16915/// from an outer enclosing namespace or file scope inside a friend declaration.16916/// This should provide the commented out code in the following snippet:16917/// namespace N {16918/// struct X;16919/// namespace M {16920/// struct Y { friend struct /*N::*/ X; };16921/// }16922/// }16923static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,16924SourceLocation NameLoc) {16925// While the decl is in a namespace, do repeated lookup of that name and see16926// if we get the same namespace back. If we do not, continue until16927// translation unit scope, at which point we have a fully qualified NNS.16928SmallVector<IdentifierInfo *, 4> Namespaces;16929DeclContext *DC = ND->getDeclContext()->getRedeclContext();16930for (; !DC->isTranslationUnit(); DC = DC->getParent()) {16931// This tag should be declared in a namespace, which can only be enclosed by16932// other namespaces. Bail if there's an anonymous namespace in the chain.16933NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);16934if (!Namespace || Namespace->isAnonymousNamespace())16935return FixItHint();16936IdentifierInfo *II = Namespace->getIdentifier();16937Namespaces.push_back(II);16938NamedDecl *Lookup = SemaRef.LookupSingleName(16939S, II, NameLoc, Sema::LookupNestedNameSpecifierName);16940if (Lookup == Namespace)16941break;16942}1694316944// Once we have all the namespaces, reverse them to go outermost first, and16945// build an NNS.16946SmallString<64> Insertion;16947llvm::raw_svector_ostream OS(Insertion);16948if (DC->isTranslationUnit())16949OS << "::";16950std::reverse(Namespaces.begin(), Namespaces.end());16951for (auto *II : Namespaces)16952OS << II->getName() << "::";16953return FixItHint::CreateInsertion(NameLoc, Insertion);16954}1695516956/// Determine whether a tag originally declared in context \p OldDC can16957/// be redeclared with an unqualified name in \p NewDC (assuming name lookup16958/// found a declaration in \p OldDC as a previous decl, perhaps through a16959/// using-declaration).16960static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,16961DeclContext *NewDC) {16962OldDC = OldDC->getRedeclContext();16963NewDC = NewDC->getRedeclContext();1696416965if (OldDC->Equals(NewDC))16966return true;1696716968// In MSVC mode, we allow a redeclaration if the contexts are related (either16969// encloses the other).16970if (S.getLangOpts().MSVCCompat &&16971(OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))16972return true;1697316974return false;16975}1697616977DeclResult16978Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,16979CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,16980const ParsedAttributesView &Attrs, AccessSpecifier AS,16981SourceLocation ModulePrivateLoc,16982MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,16983bool &IsDependent, SourceLocation ScopedEnumKWLoc,16984bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,16985bool IsTypeSpecifier, bool IsTemplateParamOrArg,16986OffsetOfKind OOK, SkipBodyInfo *SkipBody) {16987// If this is not a definition, it must have a name.16988IdentifierInfo *OrigName = Name;16989assert((Name != nullptr || TUK == TagUseKind::Definition) &&16990"Nameless record must be a definition!");16991assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);1699216993OwnedDecl = false;16994TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);16995bool ScopedEnum = ScopedEnumKWLoc.isValid();1699616997// FIXME: Check member specializations more carefully.16998bool isMemberSpecialization = false;16999bool Invalid = false;1700017001// We only need to do this matching if we have template parameters17002// or a scope specifier, which also conveniently avoids this work17003// for non-C++ cases.17004if (TemplateParameterLists.size() > 0 ||17005(SS.isNotEmpty() && TUK != TagUseKind::Reference)) {17006TemplateParameterList *TemplateParams =17007MatchTemplateParametersToScopeSpecifier(17008KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,17009TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);1701017011// C++23 [dcl.type.elab] p2:17012// If an elaborated-type-specifier is the sole constituent of a17013// declaration, the declaration is ill-formed unless it is an explicit17014// specialization, an explicit instantiation or it has one of the17015// following forms: [...]17016// C++23 [dcl.enum] p1:17017// If the enum-head-name of an opaque-enum-declaration contains a17018// nested-name-specifier, the declaration shall be an explicit17019// specialization.17020//17021// FIXME: Class template partial specializations can be forward declared17022// per CWG2213, but the resolution failed to allow qualified forward17023// declarations. This is almost certainly unintentional, so we allow them.17024if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&17025!isMemberSpecialization)17026Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)17027<< TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();1702817029if (TemplateParams) {17030if (Kind == TagTypeKind::Enum) {17031Diag(KWLoc, diag::err_enum_template);17032return true;17033}1703417035if (TemplateParams->size() > 0) {17036// This is a declaration or definition of a class template (which may17037// be a member of another template).1703817039if (Invalid)17040return true;1704117042OwnedDecl = false;17043DeclResult Result = CheckClassTemplate(17044S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,17045AS, ModulePrivateLoc,17046/*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,17047TemplateParameterLists.data(), SkipBody);17048return Result.get();17049} else {17050// The "template<>" header is extraneous.17051Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)17052<< TypeWithKeyword::getTagTypeKindName(Kind) << Name;17053isMemberSpecialization = true;17054}17055}1705617057if (!TemplateParameterLists.empty() && isMemberSpecialization &&17058CheckTemplateDeclScope(S, TemplateParameterLists.back()))17059return true;17060}1706117062if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {17063// C++23 [dcl.type.elab]p4:17064// If an elaborated-type-specifier appears with the friend specifier as17065// an entire member-declaration, the member-declaration shall have one17066// of the following forms:17067// friend class-key nested-name-specifier(opt) identifier ;17068// friend class-key simple-template-id ;17069// friend class-key nested-name-specifier template(opt)17070// simple-template-id ;17071//17072// Since enum is not a class-key, so declarations like "friend enum E;"17073// are ill-formed. Although CWG2363 reaffirms that such declarations are17074// invalid, most implementations accept so we issue a pedantic warning.17075Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(17076ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);17077assert(ScopedEnum || !ScopedEnumUsesClassTag);17078Diag(KWLoc, diag::note_enum_friend)17079<< (ScopedEnum + ScopedEnumUsesClassTag);17080}1708117082// Figure out the underlying type if this a enum declaration. We need to do17083// this early, because it's needed to detect if this is an incompatible17084// redeclaration.17085llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;17086bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;1708717088if (Kind == TagTypeKind::Enum) {17089if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {17090// No underlying type explicitly specified, or we failed to parse the17091// type, default to int.17092EnumUnderlying = Context.IntTy.getTypePtr();17093} else if (UnderlyingType.get()) {17094// C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an17095// integral type; any cv-qualification is ignored.17096TypeSourceInfo *TI = nullptr;17097GetTypeFromParser(UnderlyingType.get(), &TI);17098EnumUnderlying = TI;1709917100if (CheckEnumUnderlyingType(TI))17101// Recover by falling back to int.17102EnumUnderlying = Context.IntTy.getTypePtr();1710317104if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,17105UPPC_FixedUnderlyingType))17106EnumUnderlying = Context.IntTy.getTypePtr();1710717108} else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {17109// For MSVC ABI compatibility, unfixed enums must use an underlying type17110// of 'int'. However, if this is an unfixed forward declaration, don't set17111// the underlying type unless the user enables -fms-compatibility. This17112// makes unfixed forward declared enums incomplete and is more conforming.17113if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)17114EnumUnderlying = Context.IntTy.getTypePtr();17115}17116}1711717118DeclContext *SearchDC = CurContext;17119DeclContext *DC = CurContext;17120bool isStdBadAlloc = false;17121bool isStdAlignValT = false;1712217123RedeclarationKind Redecl = forRedeclarationInCurContext();17124if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)17125Redecl = RedeclarationKind::NotForRedeclaration;1712617127/// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C17128/// implemented asks for structural equivalence checking, the returned decl17129/// here is passed back to the parser, allowing the tag body to be parsed.17130auto createTagFromNewDecl = [&]() -> TagDecl * {17131assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");17132// If there is an identifier, use the location of the identifier as the17133// location of the decl, otherwise use the location of the struct/union17134// keyword.17135SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;17136TagDecl *New = nullptr;1713717138if (Kind == TagTypeKind::Enum) {17139New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,17140ScopedEnum, ScopedEnumUsesClassTag, IsFixed);17141// If this is an undefined enum, bail.17142if (TUK != TagUseKind::Definition && !Invalid)17143return nullptr;17144if (EnumUnderlying) {17145EnumDecl *ED = cast<EnumDecl>(New);17146if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())17147ED->setIntegerTypeSourceInfo(TI);17148else17149ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));17150QualType EnumTy = ED->getIntegerType();17151ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)17152? Context.getPromotedIntegerType(EnumTy)17153: EnumTy);17154}17155} else { // struct/union17156New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,17157nullptr);17158}1715917160if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {17161// Add alignment attributes if necessary; these attributes are checked17162// when the ASTContext lays out the structure.17163//17164// It is important for implementing the correct semantics that this17165// happen here (in ActOnTag). The #pragma pack stack is17166// maintained as a result of parser callbacks which can occur at17167// many points during the parsing of a struct declaration (because17168// the #pragma tokens are effectively skipped over during the17169// parsing of the struct).17170if (TUK == TagUseKind::Definition &&17171(!SkipBody || !SkipBody->ShouldSkip)) {17172AddAlignmentAttributesForRecord(RD);17173AddMsStructLayoutForRecord(RD);17174}17175}17176New->setLexicalDeclContext(CurContext);17177return New;17178};1717917180LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);17181if (Name && SS.isNotEmpty()) {17182// We have a nested-name tag ('struct foo::bar').1718317184// Check for invalid 'foo::'.17185if (SS.isInvalid()) {17186Name = nullptr;17187goto CreateNewDecl;17188}1718917190// If this is a friend or a reference to a class in a dependent17191// context, don't try to make a decl for it.17192if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {17193DC = computeDeclContext(SS, false);17194if (!DC) {17195IsDependent = true;17196return true;17197}17198} else {17199DC = computeDeclContext(SS, true);17200if (!DC) {17201Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)17202<< SS.getRange();17203return true;17204}17205}1720617207if (RequireCompleteDeclContext(SS, DC))17208return true;1720917210SearchDC = DC;17211// Look-up name inside 'foo::'.17212LookupQualifiedName(Previous, DC);1721317214if (Previous.isAmbiguous())17215return true;1721617217if (Previous.empty()) {17218// Name lookup did not find anything. However, if the17219// nested-name-specifier refers to the current instantiation,17220// and that current instantiation has any dependent base17221// classes, we might find something at instantiation time: treat17222// this as a dependent elaborated-type-specifier.17223// But this only makes any sense for reference-like lookups.17224if (Previous.wasNotFoundInCurrentInstantiation() &&17225(TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {17226IsDependent = true;17227return true;17228}1722917230// A tag 'foo::bar' must already exist.17231Diag(NameLoc, diag::err_not_tag_in_scope)17232<< llvm::to_underlying(Kind) << Name << DC << SS.getRange();17233Name = nullptr;17234Invalid = true;17235goto CreateNewDecl;17236}17237} else if (Name) {17238// C++14 [class.mem]p14:17239// If T is the name of a class, then each of the following shall have a17240// name different from T:17241// -- every member of class T that is itself a type17242if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&17243DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))17244return true;1724517246// If this is a named struct, check to see if there was a previous forward17247// declaration or definition.17248// FIXME: We're looking into outer scopes here, even when we17249// shouldn't be. Doing so can result in ambiguities that we17250// shouldn't be diagnosing.17251LookupName(Previous, S);1725217253// When declaring or defining a tag, ignore ambiguities introduced17254// by types using'ed into this scope.17255if (Previous.isAmbiguous() &&17256(TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {17257LookupResult::Filter F = Previous.makeFilter();17258while (F.hasNext()) {17259NamedDecl *ND = F.next();17260if (!ND->getDeclContext()->getRedeclContext()->Equals(17261SearchDC->getRedeclContext()))17262F.erase();17263}17264F.done();17265}1726617267// C++11 [namespace.memdef]p3:17268// If the name in a friend declaration is neither qualified nor17269// a template-id and the declaration is a function or an17270// elaborated-type-specifier, the lookup to determine whether17271// the entity has been previously declared shall not consider17272// any scopes outside the innermost enclosing namespace.17273//17274// MSVC doesn't implement the above rule for types, so a friend tag17275// declaration may be a redeclaration of a type declared in an enclosing17276// scope. They do implement this rule for friend functions.17277//17278// Does it matter that this should be by scope instead of by17279// semantic context?17280if (!Previous.empty() && TUK == TagUseKind::Friend) {17281DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();17282LookupResult::Filter F = Previous.makeFilter();17283bool FriendSawTagOutsideEnclosingNamespace = false;17284while (F.hasNext()) {17285NamedDecl *ND = F.next();17286DeclContext *DC = ND->getDeclContext()->getRedeclContext();17287if (DC->isFileContext() &&17288!EnclosingNS->Encloses(ND->getDeclContext())) {17289if (getLangOpts().MSVCCompat)17290FriendSawTagOutsideEnclosingNamespace = true;17291else17292F.erase();17293}17294}17295F.done();1729617297// Diagnose this MSVC extension in the easy case where lookup would have17298// unambiguously found something outside the enclosing namespace.17299if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {17300NamedDecl *ND = Previous.getFoundDecl();17301Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)17302<< createFriendTagNNSFixIt(*this, ND, S, NameLoc);17303}17304}1730517306// Note: there used to be some attempt at recovery here.17307if (Previous.isAmbiguous())17308return true;1730917310if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {17311// FIXME: This makes sure that we ignore the contexts associated17312// with C structs, unions, and enums when looking for a matching17313// tag declaration or definition. See the similar lookup tweak17314// in Sema::LookupName; is there a better way to deal with this?17315while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))17316SearchDC = SearchDC->getParent();17317} else if (getLangOpts().CPlusPlus) {17318// Inside ObjCContainer want to keep it as a lexical decl context but go17319// past it (most often to TranslationUnit) to find the semantic decl17320// context.17321while (isa<ObjCContainerDecl>(SearchDC))17322SearchDC = SearchDC->getParent();17323}17324} else if (getLangOpts().CPlusPlus) {17325// Don't use ObjCContainerDecl as the semantic decl context for anonymous17326// TagDecl the same way as we skip it for named TagDecl.17327while (isa<ObjCContainerDecl>(SearchDC))17328SearchDC = SearchDC->getParent();17329}1733017331if (Previous.isSingleResult() &&17332Previous.getFoundDecl()->isTemplateParameter()) {17333// Maybe we will complain about the shadowed template parameter.17334DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());17335// Just pretend that we didn't see the previous declaration.17336Previous.clear();17337}1733817339if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&17340DC->Equals(getStdNamespace())) {17341if (Name->isStr("bad_alloc")) {17342// This is a declaration of or a reference to "std::bad_alloc".17343isStdBadAlloc = true;1734417345// If std::bad_alloc has been implicitly declared (but made invisible to17346// name lookup), fill in this implicit declaration as the previous17347// declaration, so that the declarations get chained appropriately.17348if (Previous.empty() && StdBadAlloc)17349Previous.addDecl(getStdBadAlloc());17350} else if (Name->isStr("align_val_t")) {17351isStdAlignValT = true;17352if (Previous.empty() && StdAlignValT)17353Previous.addDecl(getStdAlignValT());17354}17355}1735617357// If we didn't find a previous declaration, and this is a reference17358// (or friend reference), move to the correct scope. In C++, we17359// also need to do a redeclaration lookup there, just in case17360// there's a shadow friend decl.17361if (Name && Previous.empty() &&17362(TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||17363IsTemplateParamOrArg)) {17364if (Invalid) goto CreateNewDecl;17365assert(SS.isEmpty());1736617367if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {17368// C++ [basic.scope.pdecl]p5:17369// -- for an elaborated-type-specifier of the form17370//17371// class-key identifier17372//17373// if the elaborated-type-specifier is used in the17374// decl-specifier-seq or parameter-declaration-clause of a17375// function defined in namespace scope, the identifier is17376// declared as a class-name in the namespace that contains17377// the declaration; otherwise, except as a friend17378// declaration, the identifier is declared in the smallest17379// non-class, non-function-prototype scope that contains the17380// declaration.17381//17382// C99 6.7.2.3p8 has a similar (but not identical!) provision for17383// C structs and unions.17384//17385// It is an error in C++ to declare (rather than define) an enum17386// type, including via an elaborated type specifier. We'll17387// diagnose that later; for now, declare the enum in the same17388// scope as we would have picked for any other tag type.17389//17390// GNU C also supports this behavior as part of its incomplete17391// enum types extension, while GNU C++ does not.17392//17393// Find the context where we'll be declaring the tag.17394// FIXME: We would like to maintain the current DeclContext as the17395// lexical context,17396SearchDC = getTagInjectionContext(SearchDC);1739717398// Find the scope where we'll be declaring the tag.17399S = getTagInjectionScope(S, getLangOpts());17400} else {17401assert(TUK == TagUseKind::Friend);17402CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);1740317404// C++ [namespace.memdef]p3:17405// If a friend declaration in a non-local class first declares a17406// class or function, the friend class or function is a member of17407// the innermost enclosing namespace.17408SearchDC = RD->isLocalClass() ? RD->isLocalClass()17409: SearchDC->getEnclosingNamespaceContext();17410}1741117412// In C++, we need to do a redeclaration lookup to properly17413// diagnose some problems.17414// FIXME: redeclaration lookup is also used (with and without C++) to find a17415// hidden declaration so that we don't get ambiguity errors when using a17416// type declared by an elaborated-type-specifier. In C that is not correct17417// and we should instead merge compatible types found by lookup.17418if (getLangOpts().CPlusPlus) {17419// FIXME: This can perform qualified lookups into function contexts,17420// which are meaningless.17421Previous.setRedeclarationKind(forRedeclarationInCurContext());17422LookupQualifiedName(Previous, SearchDC);17423} else {17424Previous.setRedeclarationKind(forRedeclarationInCurContext());17425LookupName(Previous, S);17426}17427}1742817429// If we have a known previous declaration to use, then use it.17430if (Previous.empty() && SkipBody && SkipBody->Previous)17431Previous.addDecl(SkipBody->Previous);1743217433if (!Previous.empty()) {17434NamedDecl *PrevDecl = Previous.getFoundDecl();17435NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();1743617437// It's okay to have a tag decl in the same scope as a typedef17438// which hides a tag decl in the same scope. Finding this17439// with a redeclaration lookup can only actually happen in C++.17440//17441// This is also okay for elaborated-type-specifiers, which is17442// technically forbidden by the current standard but which is17443// okay according to the likely resolution of an open issue;17444// see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#40717445if (getLangOpts().CPlusPlus) {17446if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {17447if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {17448TagDecl *Tag = TT->getDecl();17449if (Tag->getDeclName() == Name &&17450Tag->getDeclContext()->getRedeclContext()17451->Equals(TD->getDeclContext()->getRedeclContext())) {17452PrevDecl = Tag;17453Previous.clear();17454Previous.addDecl(Tag);17455Previous.resolveKind();17456}17457}17458}17459}1746017461// If this is a redeclaration of a using shadow declaration, it must17462// declare a tag in the same context. In MSVC mode, we allow a17463// redefinition if either context is within the other.17464if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {17465auto *OldTag = dyn_cast<TagDecl>(PrevDecl);17466if (SS.isEmpty() && TUK != TagUseKind::Reference &&17467TUK != TagUseKind::Friend &&17468isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&17469!(OldTag && isAcceptableTagRedeclContext(17470*this, OldTag->getDeclContext(), SearchDC))) {17471Diag(KWLoc, diag::err_using_decl_conflict_reverse);17472Diag(Shadow->getTargetDecl()->getLocation(),17473diag::note_using_decl_target);17474Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)17475<< 0;17476// Recover by ignoring the old declaration.17477Previous.clear();17478goto CreateNewDecl;17479}17480}1748117482if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {17483// If this is a use of a previous tag, or if the tag is already declared17484// in the same scope (so that the definition/declaration completes or17485// rementions the tag), reuse the decl.17486if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||17487isDeclInScope(DirectPrevDecl, SearchDC, S,17488SS.isNotEmpty() || isMemberSpecialization)) {17489// Make sure that this wasn't declared as an enum and now used as a17490// struct or something similar.17491if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,17492TUK == TagUseKind::Definition, KWLoc,17493Name)) {17494bool SafeToContinue =17495(PrevTagDecl->getTagKind() != TagTypeKind::Enum &&17496Kind != TagTypeKind::Enum);17497if (SafeToContinue)17498Diag(KWLoc, diag::err_use_with_wrong_tag)17499<< Name17500<< FixItHint::CreateReplacement(SourceRange(KWLoc),17501PrevTagDecl->getKindName());17502else17503Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;17504Diag(PrevTagDecl->getLocation(), diag::note_previous_use);1750517506if (SafeToContinue)17507Kind = PrevTagDecl->getTagKind();17508else {17509// Recover by making this an anonymous redefinition.17510Name = nullptr;17511Previous.clear();17512Invalid = true;17513}17514}1751517516if (Kind == TagTypeKind::Enum &&17517PrevTagDecl->getTagKind() == TagTypeKind::Enum) {17518const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);17519if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)17520return PrevTagDecl;1752117522QualType EnumUnderlyingTy;17523if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())17524EnumUnderlyingTy = TI->getType().getUnqualifiedType();17525else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())17526EnumUnderlyingTy = QualType(T, 0);1752717528// All conflicts with previous declarations are recovered by17529// returning the previous declaration, unless this is a definition,17530// in which case we want the caller to bail out.17531if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,17532ScopedEnum, EnumUnderlyingTy,17533IsFixed, PrevEnum))17534return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;17535}1753617537// C++11 [class.mem]p1:17538// A member shall not be declared twice in the member-specification,17539// except that a nested class or member class template can be declared17540// and then later defined.17541if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&17542S->isDeclScope(PrevDecl)) {17543Diag(NameLoc, diag::ext_member_redeclared);17544Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);17545}1754617547if (!Invalid) {17548// If this is a use, just return the declaration we found, unless17549// we have attributes.17550if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {17551if (!Attrs.empty()) {17552// FIXME: Diagnose these attributes. For now, we create a new17553// declaration to hold them.17554} else if (TUK == TagUseKind::Reference &&17555(PrevTagDecl->getFriendObjectKind() ==17556Decl::FOK_Undeclared ||17557PrevDecl->getOwningModule() != getCurrentModule()) &&17558SS.isEmpty()) {17559// This declaration is a reference to an existing entity, but17560// has different visibility from that entity: it either makes17561// a friend visible or it makes a type visible in a new module.17562// In either case, create a new declaration. We only do this if17563// the declaration would have meant the same thing if no prior17564// declaration were found, that is, if it was found in the same17565// scope where we would have injected a declaration.17566if (!getTagInjectionContext(CurContext)->getRedeclContext()17567->Equals(PrevDecl->getDeclContext()->getRedeclContext()))17568return PrevTagDecl;17569// This is in the injected scope, create a new declaration in17570// that scope.17571S = getTagInjectionScope(S, getLangOpts());17572} else {17573return PrevTagDecl;17574}17575}1757617577// Diagnose attempts to redefine a tag.17578if (TUK == TagUseKind::Definition) {17579if (NamedDecl *Def = PrevTagDecl->getDefinition()) {17580// If we're defining a specialization and the previous definition17581// is from an implicit instantiation, don't emit an error17582// here; we'll catch this in the general case below.17583bool IsExplicitSpecializationAfterInstantiation = false;17584if (isMemberSpecialization) {17585if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))17586IsExplicitSpecializationAfterInstantiation =17587RD->getTemplateSpecializationKind() !=17588TSK_ExplicitSpecialization;17589else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))17590IsExplicitSpecializationAfterInstantiation =17591ED->getTemplateSpecializationKind() !=17592TSK_ExplicitSpecialization;17593}1759417595// Note that clang allows ODR-like semantics for ObjC/C, i.e., do17596// not keep more that one definition around (merge them). However,17597// ensure the decl passes the structural compatibility check in17598// C11 6.2.7/1 (or 6.1.2.6/1 in C89).17599NamedDecl *Hidden = nullptr;17600if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {17601// There is a definition of this tag, but it is not visible. We17602// explicitly make use of C++'s one definition rule here, and17603// assume that this definition is identical to the hidden one17604// we already have. Make the existing definition visible and17605// use it in place of this one.17606if (!getLangOpts().CPlusPlus) {17607// Postpone making the old definition visible until after we17608// complete parsing the new one and do the structural17609// comparison.17610SkipBody->CheckSameAsPrevious = true;17611SkipBody->New = createTagFromNewDecl();17612SkipBody->Previous = Def;17613return Def;17614} else {17615SkipBody->ShouldSkip = true;17616SkipBody->Previous = Def;17617makeMergedDefinitionVisible(Hidden);17618// Carry on and handle it like a normal definition. We'll17619// skip starting the definition later.17620}17621} else if (!IsExplicitSpecializationAfterInstantiation) {17622// A redeclaration in function prototype scope in C isn't17623// visible elsewhere, so merely issue a warning.17624if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())17625Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;17626else17627Diag(NameLoc, diag::err_redefinition) << Name;17628notePreviousDefinition(Def,17629NameLoc.isValid() ? NameLoc : KWLoc);17630// If this is a redefinition, recover by making this17631// struct be anonymous, which will make any later17632// references get the previous definition.17633Name = nullptr;17634Previous.clear();17635Invalid = true;17636}17637} else {17638// If the type is currently being defined, complain17639// about a nested redefinition.17640auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();17641if (TD->isBeingDefined()) {17642Diag(NameLoc, diag::err_nested_redefinition) << Name;17643Diag(PrevTagDecl->getLocation(),17644diag::note_previous_definition);17645Name = nullptr;17646Previous.clear();17647Invalid = true;17648}17649}1765017651// Okay, this is definition of a previously declared or referenced17652// tag. We're going to create a new Decl for it.17653}1765417655// Okay, we're going to make a redeclaration. If this is some kind17656// of reference, make sure we build the redeclaration in the same DC17657// as the original, and ignore the current access specifier.17658if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {17659SearchDC = PrevTagDecl->getDeclContext();17660AS = AS_none;17661}17662}17663// If we get here we have (another) forward declaration or we17664// have a definition. Just create a new decl.1766517666} else {17667// If we get here, this is a definition of a new tag type in a nested17668// scope, e.g. "struct foo; void bar() { struct foo; }", just create a17669// new decl/type. We set PrevDecl to NULL so that the entities17670// have distinct types.17671Previous.clear();17672}17673// If we get here, we're going to create a new Decl. If PrevDecl17674// is non-NULL, it's a definition of the tag declared by17675// PrevDecl. If it's NULL, we have a new definition.1767617677// Otherwise, PrevDecl is not a tag, but was found with tag17678// lookup. This is only actually possible in C++, where a few17679// things like templates still live in the tag namespace.17680} else {17681// Use a better diagnostic if an elaborated-type-specifier17682// found the wrong kind of type on the first17683// (non-redeclaration) lookup.17684if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&17685!Previous.isForRedeclaration()) {17686NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);17687Diag(NameLoc, diag::err_tag_reference_non_tag)17688<< PrevDecl << NTK << llvm::to_underlying(Kind);17689Diag(PrevDecl->getLocation(), diag::note_declared_at);17690Invalid = true;1769117692// Otherwise, only diagnose if the declaration is in scope.17693} else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,17694SS.isNotEmpty() || isMemberSpecialization)) {17695// do nothing1769617697// Diagnose implicit declarations introduced by elaborated types.17698} else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {17699NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);17700Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;17701Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;17702Invalid = true;1770317704// Otherwise it's a declaration. Call out a particularly common17705// case here.17706} else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {17707unsigned Kind = 0;17708if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;17709Diag(NameLoc, diag::err_tag_definition_of_typedef)17710<< Name << Kind << TND->getUnderlyingType();17711Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;17712Invalid = true;1771317714// Otherwise, diagnose.17715} else {17716// The tag name clashes with something else in the target scope,17717// issue an error and recover by making this tag be anonymous.17718Diag(NameLoc, diag::err_redefinition_different_kind) << Name;17719notePreviousDefinition(PrevDecl, NameLoc);17720Name = nullptr;17721Invalid = true;17722}1772317724// The existing declaration isn't relevant to us; we're in a17725// new scope, so clear out the previous declaration.17726Previous.clear();17727}17728}1772917730CreateNewDecl:1773117732TagDecl *PrevDecl = nullptr;17733if (Previous.isSingleResult())17734PrevDecl = cast<TagDecl>(Previous.getFoundDecl());1773517736// If there is an identifier, use the location of the identifier as the17737// location of the decl, otherwise use the location of the struct/union17738// keyword.17739SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;1774017741// Otherwise, create a new declaration. If there is a previous17742// declaration of the same entity, the two will be linked via17743// PrevDecl.17744TagDecl *New;1774517746if (Kind == TagTypeKind::Enum) {17747// FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:17748// enum X { A, B, C } D; D should chain to X.17749New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,17750cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,17751ScopedEnumUsesClassTag, IsFixed);1775217753if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))17754StdAlignValT = cast<EnumDecl>(New);1775517756// If this is an undefined enum, warn.17757if (TUK != TagUseKind::Definition && !Invalid) {17758TagDecl *Def;17759if (IsFixed && cast<EnumDecl>(New)->isFixed()) {17760// C++0x: 7.2p2: opaque-enum-declaration.17761// Conflicts are diagnosed above. Do nothing.17762}17763else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {17764Diag(Loc, diag::ext_forward_ref_enum_def)17765<< New;17766Diag(Def->getLocation(), diag::note_previous_definition);17767} else {17768unsigned DiagID = diag::ext_forward_ref_enum;17769if (getLangOpts().MSVCCompat)17770DiagID = diag::ext_ms_forward_ref_enum;17771else if (getLangOpts().CPlusPlus)17772DiagID = diag::err_forward_ref_enum;17773Diag(Loc, DiagID);17774}17775}1777617777if (EnumUnderlying) {17778EnumDecl *ED = cast<EnumDecl>(New);17779if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())17780ED->setIntegerTypeSourceInfo(TI);17781else17782ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));17783QualType EnumTy = ED->getIntegerType();17784ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)17785? Context.getPromotedIntegerType(EnumTy)17786: EnumTy);17787assert(ED->isComplete() && "enum with type should be complete");17788}17789} else {17790// struct/union/class1779117792// FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:17793// struct X { int A; } D; D should chain to X.17794if (getLangOpts().CPlusPlus) {17795// FIXME: Look for a way to use RecordDecl for simple structs.17796New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,17797cast_or_null<CXXRecordDecl>(PrevDecl));1779817799if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))17800StdBadAlloc = cast<CXXRecordDecl>(New);17801} else17802New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,17803cast_or_null<RecordDecl>(PrevDecl));17804}1780517806// Only C23 and later allow defining new types in 'offsetof()'.17807if (OOK != OOK_Outside && TUK == TagUseKind::Definition &&17808!getLangOpts().CPlusPlus && !getLangOpts().C23)17809Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)17810<< (OOK == OOK_Macro) << New->getSourceRange();1781117812// C++11 [dcl.type]p3:17813// A type-specifier-seq shall not define a class or enumeration [...].17814if (!Invalid && getLangOpts().CPlusPlus &&17815(IsTypeSpecifier || IsTemplateParamOrArg) &&17816TUK == TagUseKind::Definition) {17817Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)17818<< Context.getTagDeclType(New);17819Invalid = true;17820}1782117822if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&17823DC->getDeclKind() == Decl::Enum) {17824Diag(New->getLocation(), diag::err_type_defined_in_enum)17825<< Context.getTagDeclType(New);17826Invalid = true;17827}1782817829// Maybe add qualifier info.17830if (SS.isNotEmpty()) {17831if (SS.isSet()) {17832// If this is either a declaration or a definition, check the17833// nested-name-specifier against the current context.17834if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&17835diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,17836/*TemplateId=*/nullptr,17837isMemberSpecialization))17838Invalid = true;1783917840New->setQualifierInfo(SS.getWithLocInContext(Context));17841if (TemplateParameterLists.size() > 0) {17842New->setTemplateParameterListsInfo(Context, TemplateParameterLists);17843}17844}17845else17846Invalid = true;17847}1784817849if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {17850// Add alignment attributes if necessary; these attributes are checked when17851// the ASTContext lays out the structure.17852//17853// It is important for implementing the correct semantics that this17854// happen here (in ActOnTag). The #pragma pack stack is17855// maintained as a result of parser callbacks which can occur at17856// many points during the parsing of a struct declaration (because17857// the #pragma tokens are effectively skipped over during the17858// parsing of the struct).17859if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {17860AddAlignmentAttributesForRecord(RD);17861AddMsStructLayoutForRecord(RD);17862}17863}1786417865if (ModulePrivateLoc.isValid()) {17866if (isMemberSpecialization)17867Diag(New->getLocation(), diag::err_module_private_specialization)17868<< 217869<< FixItHint::CreateRemoval(ModulePrivateLoc);17870// __module_private__ does not apply to local classes. However, we only17871// diagnose this as an error when the declaration specifiers are17872// freestanding. Here, we just ignore the __module_private__.17873else if (!SearchDC->isFunctionOrMethod())17874New->setModulePrivate();17875}1787617877// If this is a specialization of a member class (of a class template),17878// check the specialization.17879if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))17880Invalid = true;1788117882// If we're declaring or defining a tag in function prototype scope in C,17883// note that this type can only be used within the function and add it to17884// the list of decls to inject into the function definition scope.17885if ((Name || Kind == TagTypeKind::Enum) &&17886getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {17887if (getLangOpts().CPlusPlus) {17888// C++ [dcl.fct]p6:17889// Types shall not be defined in return or parameter types.17890if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {17891Diag(Loc, diag::err_type_defined_in_param_type)17892<< Name;17893Invalid = true;17894}17895} else if (!PrevDecl) {17896Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);17897}17898}1789917900if (Invalid)17901New->setInvalidDecl();1790217903// Set the lexical context. If the tag has a C++ scope specifier, the17904// lexical context will be different from the semantic context.17905New->setLexicalDeclContext(CurContext);1790617907// Mark this as a friend decl if applicable.17908// In Microsoft mode, a friend declaration also acts as a forward17909// declaration so we always pass true to setObjectOfFriendDecl to make17910// the tag name visible.17911if (TUK == TagUseKind::Friend)17912New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);1791317914// Set the access specifier.17915if (!Invalid && SearchDC->isRecord())17916SetMemberAccessSpecifier(New, PrevDecl, AS);1791717918if (PrevDecl)17919CheckRedeclarationInModule(New, PrevDecl);1792017921if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))17922New->startDefinition();1792317924ProcessDeclAttributeList(S, New, Attrs);17925AddPragmaAttributes(S, New);1792617927// If this has an identifier, add it to the scope stack.17928if (TUK == TagUseKind::Friend) {17929// We might be replacing an existing declaration in the lookup tables;17930// if so, borrow its access specifier.17931if (PrevDecl)17932New->setAccess(PrevDecl->getAccess());1793317934DeclContext *DC = New->getDeclContext()->getRedeclContext();17935DC->makeDeclVisibleInContext(New);17936if (Name) // can be null along some error paths17937if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))17938PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);17939} else if (Name) {17940S = getNonFieldDeclScope(S);17941PushOnScopeChains(New, S, true);17942} else {17943CurContext->addDecl(New);17944}1794517946// If this is the C FILE type, notify the AST context.17947if (IdentifierInfo *II = New->getIdentifier())17948if (!New->isInvalidDecl() &&17949New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&17950II->isStr("FILE"))17951Context.setFILEDecl(New);1795217953if (PrevDecl)17954mergeDeclAttributes(New, PrevDecl);1795517956if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {17957inferGslOwnerPointerAttribute(CXXRD);17958inferNullableClassAttribute(CXXRD);17959}1796017961// If there's a #pragma GCC visibility in scope, set the visibility of this17962// record.17963AddPushedVisibilityAttribute(New);1796417965if (isMemberSpecialization && !New->isInvalidDecl())17966CompleteMemberSpecialization(New, Previous);1796717968OwnedDecl = true;17969// In C++, don't return an invalid declaration. We can't recover well from17970// the cases where we make the type anonymous.17971if (Invalid && getLangOpts().CPlusPlus) {17972if (New->isBeingDefined())17973if (auto RD = dyn_cast<RecordDecl>(New))17974RD->completeDefinition();17975return true;17976} else if (SkipBody && SkipBody->ShouldSkip) {17977return SkipBody->Previous;17978} else {17979return New;17980}17981}1798217983void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {17984AdjustDeclIfTemplate(TagD);17985TagDecl *Tag = cast<TagDecl>(TagD);1798617987// Enter the tag context.17988PushDeclContext(S, Tag);1798917990ActOnDocumentableDecl(TagD);1799117992// If there's a #pragma GCC visibility in scope, set the visibility of this17993// record.17994AddPushedVisibilityAttribute(Tag);17995}1799617997bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {17998if (!hasStructuralCompatLayout(Prev, SkipBody.New))17999return false;1800018001// Make the previous decl visible.18002makeMergedDefinitionVisible(SkipBody.Previous);18003return true;18004}1800518006void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,18007SourceLocation FinalLoc,18008bool IsFinalSpelledSealed,18009bool IsAbstract,18010SourceLocation LBraceLoc) {18011AdjustDeclIfTemplate(TagD);18012CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);1801318014FieldCollector->StartClass();1801518016if (!Record->getIdentifier())18017return;1801818019if (IsAbstract)18020Record->markAbstract();1802118022if (FinalLoc.isValid()) {18023Record->addAttr(FinalAttr::Create(Context, FinalLoc,18024IsFinalSpelledSealed18025? FinalAttr::Keyword_sealed18026: FinalAttr::Keyword_final));18027}18028// C++ [class]p2:18029// [...] The class-name is also inserted into the scope of the18030// class itself; this is known as the injected-class-name. For18031// purposes of access checking, the injected-class-name is treated18032// as if it were a public member name.18033CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(18034Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),18035Record->getLocation(), Record->getIdentifier(),18036/*PrevDecl=*/nullptr,18037/*DelayTypeCreation=*/true);18038Context.getTypeDeclType(InjectedClassName, Record);18039InjectedClassName->setImplicit();18040InjectedClassName->setAccess(AS_public);18041if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())18042InjectedClassName->setDescribedClassTemplate(Template);18043PushOnScopeChains(InjectedClassName, S);18044assert(InjectedClassName->isInjectedClassName() &&18045"Broken injected-class-name");18046}1804718048void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,18049SourceRange BraceRange) {18050AdjustDeclIfTemplate(TagD);18051TagDecl *Tag = cast<TagDecl>(TagD);18052Tag->setBraceRange(BraceRange);1805318054// Make sure we "complete" the definition even it is invalid.18055if (Tag->isBeingDefined()) {18056assert(Tag->isInvalidDecl() && "We should already have completed it");18057if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))18058RD->completeDefinition();18059}1806018061if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {18062FieldCollector->FinishClass();18063if (RD->hasAttr<SYCLSpecialClassAttr>()) {18064auto *Def = RD->getDefinition();18065assert(Def && "The record is expected to have a completed definition");18066unsigned NumInitMethods = 0;18067for (auto *Method : Def->methods()) {18068if (!Method->getIdentifier())18069continue;18070if (Method->getName() == "__init")18071NumInitMethods++;18072}18073if (NumInitMethods > 1 || !Def->hasInitMethod())18074Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);18075}1807618077// If we're defining a dynamic class in a module interface unit, we always18078// need to produce the vtable for it, even if the vtable is not used in the18079// current TU.18080//18081// The case where the current class is not dynamic is handled in18082// MarkVTableUsed.18083if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())18084MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);18085}1808618087// Exit this scope of this tag's definition.18088PopDeclContext();1808918090if (getCurLexicalContext()->isObjCContainer() &&18091Tag->getDeclContext()->isFileContext())18092Tag->setTopLevelDeclInObjCContainer();1809318094// Notify the consumer that we've defined a tag.18095if (!Tag->isInvalidDecl())18096Consumer.HandleTagDeclDefinition(Tag);1809718098// Clangs implementation of #pragma align(packed) differs in bitfield layout18099// from XLs and instead matches the XL #pragma pack(1) behavior.18100if (Context.getTargetInfo().getTriple().isOSAIX() &&18101AlignPackStack.hasValue()) {18102AlignPackInfo APInfo = AlignPackStack.CurrentValue;18103// Only diagnose #pragma align(packed).18104if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)18105return;18106const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);18107if (!RD)18108return;18109// Only warn if there is at least 1 bitfield member.18110if (llvm::any_of(RD->fields(),18111[](const FieldDecl *FD) { return FD->isBitField(); }))18112Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);18113}18114}1811518116void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {18117AdjustDeclIfTemplate(TagD);18118TagDecl *Tag = cast<TagDecl>(TagD);18119Tag->setInvalidDecl();1812018121// Make sure we "complete" the definition even it is invalid.18122if (Tag->isBeingDefined()) {18123if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))18124RD->completeDefinition();18125}1812618127// We're undoing ActOnTagStartDefinition here, not18128// ActOnStartCXXMemberDeclarations, so we don't have to mess with18129// the FieldCollector.1813018131PopDeclContext();18132}1813318134// Note that FieldName may be null for anonymous bitfields.18135ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,18136const IdentifierInfo *FieldName,18137QualType FieldTy, bool IsMsStruct,18138Expr *BitWidth) {18139assert(BitWidth);18140if (BitWidth->containsErrors())18141return ExprError();1814218143// C99 6.7.2.1p4 - verify the field type.18144// C++ 9.6p3: A bit-field shall have integral or enumeration type.18145if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {18146// Handle incomplete and sizeless types with a specific error.18147if (RequireCompleteSizedType(FieldLoc, FieldTy,18148diag::err_field_incomplete_or_sizeless))18149return ExprError();18150if (FieldName)18151return Diag(FieldLoc, diag::err_not_integral_type_bitfield)18152<< FieldName << FieldTy << BitWidth->getSourceRange();18153return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)18154<< FieldTy << BitWidth->getSourceRange();18155} else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),18156UPPC_BitFieldWidth))18157return ExprError();1815818159// If the bit-width is type- or value-dependent, don't try to check18160// it now.18161if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())18162return BitWidth;1816318164llvm::APSInt Value;18165ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);18166if (ICE.isInvalid())18167return ICE;18168BitWidth = ICE.get();1816918170// Zero-width bitfield is ok for anonymous field.18171if (Value == 0 && FieldName)18172return Diag(FieldLoc, diag::err_bitfield_has_zero_width)18173<< FieldName << BitWidth->getSourceRange();1817418175if (Value.isSigned() && Value.isNegative()) {18176if (FieldName)18177return Diag(FieldLoc, diag::err_bitfield_has_negative_width)18178<< FieldName << toString(Value, 10);18179return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)18180<< toString(Value, 10);18181}1818218183// The size of the bit-field must not exceed our maximum permitted object18184// size.18185if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {18186return Diag(FieldLoc, diag::err_bitfield_too_wide)18187<< !FieldName << FieldName << toString(Value, 10);18188}1818918190if (!FieldTy->isDependentType()) {18191uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);18192uint64_t TypeWidth = Context.getIntWidth(FieldTy);18193bool BitfieldIsOverwide = Value.ugt(TypeWidth);1819418195// Over-wide bitfields are an error in C or when using the MSVC bitfield18196// ABI.18197bool CStdConstraintViolation =18198BitfieldIsOverwide && !getLangOpts().CPlusPlus;18199bool MSBitfieldViolation =18200Value.ugt(TypeStorageSize) &&18201(IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());18202if (CStdConstraintViolation || MSBitfieldViolation) {18203unsigned DiagWidth =18204CStdConstraintViolation ? TypeWidth : TypeStorageSize;18205return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)18206<< (bool)FieldName << FieldName << toString(Value, 10)18207<< !CStdConstraintViolation << DiagWidth;18208}1820918210// Warn on types where the user might conceivably expect to get all18211// specified bits as value bits: that's all integral types other than18212// 'bool'.18213if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {18214Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)18215<< FieldName << toString(Value, 10)18216<< (unsigned)TypeWidth;18217}18218}1821918220return BitWidth;18221}1822218223Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,18224Declarator &D, Expr *BitfieldWidth) {18225FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,18226D, BitfieldWidth,18227/*InitStyle=*/ICIS_NoInit, AS_public);18228return Res;18229}1823018231FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,18232SourceLocation DeclStart,18233Declarator &D, Expr *BitWidth,18234InClassInitStyle InitStyle,18235AccessSpecifier AS) {18236if (D.isDecompositionDeclarator()) {18237const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();18238Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)18239<< Decomp.getSourceRange();18240return nullptr;18241}1824218243const IdentifierInfo *II = D.getIdentifier();18244SourceLocation Loc = DeclStart;18245if (II) Loc = D.getIdentifierLoc();1824618247TypeSourceInfo *TInfo = GetTypeForDeclarator(D);18248QualType T = TInfo->getType();18249if (getLangOpts().CPlusPlus) {18250CheckExtraCXXDefaultArguments(D);1825118252if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,18253UPPC_DataMemberType)) {18254D.setInvalidType();18255T = Context.IntTy;18256TInfo = Context.getTrivialTypeSourceInfo(T, Loc);18257}18258}1825918260DiagnoseFunctionSpecifiers(D.getDeclSpec());1826118262if (D.getDeclSpec().isInlineSpecified())18263Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)18264<< getLangOpts().CPlusPlus17;18265if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())18266Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),18267diag::err_invalid_thread)18268<< DeclSpec::getSpecifierName(TSCS);1826918270// Check to see if this name was declared as a member previously18271NamedDecl *PrevDecl = nullptr;18272LookupResult Previous(*this, II, Loc, LookupMemberName,18273RedeclarationKind::ForVisibleRedeclaration);18274LookupName(Previous, S);18275switch (Previous.getResultKind()) {18276case LookupResult::Found:18277case LookupResult::FoundUnresolvedValue:18278PrevDecl = Previous.getAsSingle<NamedDecl>();18279break;1828018281case LookupResult::FoundOverloaded:18282PrevDecl = Previous.getRepresentativeDecl();18283break;1828418285case LookupResult::NotFound:18286case LookupResult::NotFoundInCurrentInstantiation:18287case LookupResult::Ambiguous:18288break;18289}18290Previous.suppressDiagnostics();1829118292if (PrevDecl && PrevDecl->isTemplateParameter()) {18293// Maybe we will complain about the shadowed template parameter.18294DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);18295// Just pretend that we didn't see the previous declaration.18296PrevDecl = nullptr;18297}1829818299if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))18300PrevDecl = nullptr;1830118302bool Mutable18303= (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);18304SourceLocation TSSL = D.getBeginLoc();18305FieldDecl *NewFD18306= CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,18307TSSL, AS, PrevDecl, &D);1830818309if (NewFD->isInvalidDecl())18310Record->setInvalidDecl();1831118312if (D.getDeclSpec().isModulePrivateSpecified())18313NewFD->setModulePrivate();1831418315if (NewFD->isInvalidDecl() && PrevDecl) {18316// Don't introduce NewFD into scope; there's already something18317// with the same name in the same scope.18318} else if (II) {18319PushOnScopeChains(NewFD, S);18320} else18321Record->addDecl(NewFD);1832218323return NewFD;18324}1832518326FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,18327TypeSourceInfo *TInfo,18328RecordDecl *Record, SourceLocation Loc,18329bool Mutable, Expr *BitWidth,18330InClassInitStyle InitStyle,18331SourceLocation TSSL,18332AccessSpecifier AS, NamedDecl *PrevDecl,18333Declarator *D) {18334const IdentifierInfo *II = Name.getAsIdentifierInfo();18335bool InvalidDecl = false;18336if (D) InvalidDecl = D->isInvalidType();1833718338// If we receive a broken type, recover by assuming 'int' and18339// marking this declaration as invalid.18340if (T.isNull() || T->containsErrors()) {18341InvalidDecl = true;18342T = Context.IntTy;18343}1834418345QualType EltTy = Context.getBaseElementType(T);18346if (!EltTy->isDependentType() && !EltTy->containsErrors()) {18347if (RequireCompleteSizedType(Loc, EltTy,18348diag::err_field_incomplete_or_sizeless)) {18349// Fields of incomplete type force their record to be invalid.18350Record->setInvalidDecl();18351InvalidDecl = true;18352} else {18353NamedDecl *Def;18354EltTy->isIncompleteType(&Def);18355if (Def && Def->isInvalidDecl()) {18356Record->setInvalidDecl();18357InvalidDecl = true;18358}18359}18360}1836118362// TR 18037 does not allow fields to be declared with address space18363if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||18364T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {18365Diag(Loc, diag::err_field_with_address_space);18366Record->setInvalidDecl();18367InvalidDecl = true;18368}1836918370if (LangOpts.OpenCL) {18371// OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be18372// used as structure or union field: image, sampler, event or block types.18373if (T->isEventT() || T->isImageType() || T->isSamplerT() ||18374T->isBlockPointerType()) {18375Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;18376Record->setInvalidDecl();18377InvalidDecl = true;18378}18379// OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension18380// is enabled.18381if (BitWidth && !getOpenCLOptions().isAvailableOption(18382"__cl_clang_bitfields", LangOpts)) {18383Diag(Loc, diag::err_opencl_bitfields);18384InvalidDecl = true;18385}18386}1838718388// Anonymous bit-fields cannot be cv-qualified (CWG 2229).18389if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&18390T.hasQualifiers()) {18391InvalidDecl = true;18392Diag(Loc, diag::err_anon_bitfield_qualifiers);18393}1839418395// C99 6.7.2.1p8: A member of a structure or union may have any type other18396// than a variably modified type.18397if (!InvalidDecl && T->isVariablyModifiedType()) {18398if (!tryToFixVariablyModifiedVarType(18399TInfo, T, Loc, diag::err_typecheck_field_variable_size))18400InvalidDecl = true;18401}1840218403// Fields can not have abstract class types18404if (!InvalidDecl && RequireNonAbstractType(Loc, T,18405diag::err_abstract_type_in_decl,18406AbstractFieldType))18407InvalidDecl = true;1840818409if (InvalidDecl)18410BitWidth = nullptr;18411// If this is declared as a bit-field, check the bit-field.18412if (BitWidth) {18413BitWidth =18414VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();18415if (!BitWidth) {18416InvalidDecl = true;18417BitWidth = nullptr;18418}18419}1842018421// Check that 'mutable' is consistent with the type of the declaration.18422if (!InvalidDecl && Mutable) {18423unsigned DiagID = 0;18424if (T->isReferenceType())18425DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference18426: diag::err_mutable_reference;18427else if (T.isConstQualified())18428DiagID = diag::err_mutable_const;1842918430if (DiagID) {18431SourceLocation ErrLoc = Loc;18432if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())18433ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();18434Diag(ErrLoc, DiagID);18435if (DiagID != diag::ext_mutable_reference) {18436Mutable = false;18437InvalidDecl = true;18438}18439}18440}1844118442// C++11 [class.union]p8 (DR1460):18443// At most one variant member of a union may have a18444// brace-or-equal-initializer.18445if (InitStyle != ICIS_NoInit)18446checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);1844718448FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,18449BitWidth, Mutable, InitStyle);18450if (InvalidDecl)18451NewFD->setInvalidDecl();1845218453if (PrevDecl && !isa<TagDecl>(PrevDecl) &&18454!PrevDecl->isPlaceholderVar(getLangOpts())) {18455Diag(Loc, diag::err_duplicate_member) << II;18456Diag(PrevDecl->getLocation(), diag::note_previous_declaration);18457NewFD->setInvalidDecl();18458}1845918460if (!InvalidDecl && getLangOpts().CPlusPlus) {18461if (Record->isUnion()) {18462if (const RecordType *RT = EltTy->getAs<RecordType>()) {18463CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());18464if (RDecl->getDefinition()) {18465// C++ [class.union]p1: An object of a class with a non-trivial18466// constructor, a non-trivial copy constructor, a non-trivial18467// destructor, or a non-trivial copy assignment operator18468// cannot be a member of a union, nor can an array of such18469// objects.18470if (CheckNontrivialField(NewFD))18471NewFD->setInvalidDecl();18472}18473}1847418475// C++ [class.union]p1: If a union contains a member of reference type,18476// the program is ill-formed, except when compiling with MSVC extensions18477// enabled.18478if (EltTy->isReferenceType()) {18479Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?18480diag::ext_union_member_of_reference_type :18481diag::err_union_member_of_reference_type)18482<< NewFD->getDeclName() << EltTy;18483if (!getLangOpts().MicrosoftExt)18484NewFD->setInvalidDecl();18485}18486}18487}1848818489// FIXME: We need to pass in the attributes given an AST18490// representation, not a parser representation.18491if (D) {18492// FIXME: The current scope is almost... but not entirely... correct here.18493ProcessDeclAttributes(getCurScope(), NewFD, *D);1849418495if (NewFD->hasAttrs())18496CheckAlignasUnderalignment(NewFD);18497}1849818499// In auto-retain/release, infer strong retension for fields of18500// retainable type.18501if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))18502NewFD->setInvalidDecl();1850318504if (T.isObjCGCWeak())18505Diag(Loc, diag::warn_attribute_weak_on_field);1850618507// PPC MMA non-pointer types are not allowed as field types.18508if (Context.getTargetInfo().getTriple().isPPC64() &&18509PPC().CheckPPCMMAType(T, NewFD->getLocation()))18510NewFD->setInvalidDecl();1851118512NewFD->setAccess(AS);18513return NewFD;18514}1851518516bool Sema::CheckNontrivialField(FieldDecl *FD) {18517assert(FD);18518assert(getLangOpts().CPlusPlus && "valid check only for C++");1851918520if (FD->isInvalidDecl() || FD->getType()->isDependentType())18521return false;1852218523QualType EltTy = Context.getBaseElementType(FD->getType());18524if (const RecordType *RT = EltTy->getAs<RecordType>()) {18525CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());18526if (RDecl->getDefinition()) {18527// We check for copy constructors before constructors18528// because otherwise we'll never get complaints about18529// copy constructors.1853018531CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;18532// We're required to check for any non-trivial constructors. Since the18533// implicit default constructor is suppressed if there are any18534// user-declared constructors, we just need to check that there is a18535// trivial default constructor and a trivial copy constructor. (We don't18536// worry about move constructors here, since this is a C++98 check.)18537if (RDecl->hasNonTrivialCopyConstructor())18538member = CXXSpecialMemberKind::CopyConstructor;18539else if (!RDecl->hasTrivialDefaultConstructor())18540member = CXXSpecialMemberKind::DefaultConstructor;18541else if (RDecl->hasNonTrivialCopyAssignment())18542member = CXXSpecialMemberKind::CopyAssignment;18543else if (RDecl->hasNonTrivialDestructor())18544member = CXXSpecialMemberKind::Destructor;1854518546if (member != CXXSpecialMemberKind::Invalid) {18547if (!getLangOpts().CPlusPlus11 &&18548getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {18549// Objective-C++ ARC: it is an error to have a non-trivial field of18550// a union. However, system headers in Objective-C programs18551// occasionally have Objective-C lifetime objects within unions,18552// and rather than cause the program to fail, we make those18553// members unavailable.18554SourceLocation Loc = FD->getLocation();18555if (getSourceManager().isInSystemHeader(Loc)) {18556if (!FD->hasAttr<UnavailableAttr>())18557FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",18558UnavailableAttr::IR_ARCFieldWithOwnership, Loc));18559return false;18560}18561}1856218563Diag(18564FD->getLocation(),18565getLangOpts().CPlusPlus1118566? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member18567: diag::err_illegal_union_or_anon_struct_member)18568<< FD->getParent()->isUnion() << FD->getDeclName()18569<< llvm::to_underlying(member);18570DiagnoseNontrivial(RDecl, member);18571return !getLangOpts().CPlusPlus11;18572}18573}18574}1857518576return false;18577}1857818579void Sema::ActOnLastBitfield(SourceLocation DeclLoc,18580SmallVectorImpl<Decl *> &AllIvarDecls) {18581if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())18582return;1858318584Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];18585ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);1858618587if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))18588return;18589ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);18590if (!ID) {18591if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {18592if (!CD->IsClassExtension())18593return;18594}18595// No need to add this to end of @implementation.18596else18597return;18598}18599// All conditions are met. Add a new bitfield to the tail end of ivars.18600llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);18601Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);1860218603Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),18604DeclLoc, DeclLoc, nullptr,18605Context.CharTy,18606Context.getTrivialTypeSourceInfo(Context.CharTy,18607DeclLoc),18608ObjCIvarDecl::Private, BW,18609true);18610AllIvarDecls.push_back(Ivar);18611}1861218613/// [class.dtor]p4:18614/// At the end of the definition of a class, overload resolution is18615/// performed among the prospective destructors declared in that class with18616/// an empty argument list to select the destructor for the class, also18617/// known as the selected destructor.18618///18619/// We do the overload resolution here, then mark the selected constructor in the AST.18620/// Later CXXRecordDecl::getDestructor() will return the selected constructor.18621static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {18622if (!Record->hasUserDeclaredDestructor()) {18623return;18624}1862518626SourceLocation Loc = Record->getLocation();18627OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);1862818629for (auto *Decl : Record->decls()) {18630if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {18631if (DD->isInvalidDecl())18632continue;18633S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},18634OCS);18635assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");18636}18637}1863818639if (OCS.empty()) {18640return;18641}18642OverloadCandidateSet::iterator Best;18643unsigned Msg = 0;18644OverloadCandidateDisplayKind DisplayKind;1864518646switch (OCS.BestViableFunction(S, Loc, Best)) {18647case OR_Success:18648case OR_Deleted:18649Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));18650break;1865118652case OR_Ambiguous:18653Msg = diag::err_ambiguous_destructor;18654DisplayKind = OCD_AmbiguousCandidates;18655break;1865618657case OR_No_Viable_Function:18658Msg = diag::err_no_viable_destructor;18659DisplayKind = OCD_AllCandidates;18660break;18661}1866218663if (Msg) {18664// OpenCL have got their own thing going with destructors. It's slightly broken,18665// but we allow it.18666if (!S.LangOpts.OpenCL) {18667PartialDiagnostic Diag = S.PDiag(Msg) << Record;18668OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});18669Record->setInvalidDecl();18670}18671// It's a bit hacky: At this point we've raised an error but we want the18672// rest of the compiler to continue somehow working. However almost18673// everything we'll try to do with the class will depend on there being a18674// destructor. So let's pretend the first one is selected and hope for the18675// best.18676Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));18677}18678}1867918680/// [class.mem.special]p518681/// Two special member functions are of the same kind if:18682/// - they are both default constructors,18683/// - they are both copy or move constructors with the same first parameter18684/// type, or18685/// - they are both copy or move assignment operators with the same first18686/// parameter type and the same cv-qualifiers and ref-qualifier, if any.18687static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,18688CXXMethodDecl *M1,18689CXXMethodDecl *M2,18690CXXSpecialMemberKind CSM) {18691// We don't want to compare templates to non-templates: See18692// https://github.com/llvm/llvm-project/issues/5920618693if (CSM == CXXSpecialMemberKind::DefaultConstructor)18694return bool(M1->getDescribedFunctionTemplate()) ==18695bool(M2->getDescribedFunctionTemplate());18696// FIXME: better resolve CWG18697// https://cplusplus.github.io/CWG/issues/2787.html18698if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),18699M2->getNonObjectParameter(0)->getType()))18700return false;18701if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),18702M2->getFunctionObjectParameterReferenceType()))18703return false;1870418705return true;18706}1870718708/// [class.mem.special]p6:18709/// An eligible special member function is a special member function for which:18710/// - the function is not deleted,18711/// - the associated constraints, if any, are satisfied, and18712/// - no special member function of the same kind whose associated constraints18713/// [CWG2595], if any, are satisfied is more constrained.18714static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,18715ArrayRef<CXXMethodDecl *> Methods,18716CXXSpecialMemberKind CSM) {18717SmallVector<bool, 4> SatisfactionStatus;1871818719for (CXXMethodDecl *Method : Methods) {18720const Expr *Constraints = Method->getTrailingRequiresClause();18721if (!Constraints)18722SatisfactionStatus.push_back(true);18723else {18724ConstraintSatisfaction Satisfaction;18725if (S.CheckFunctionConstraints(Method, Satisfaction))18726SatisfactionStatus.push_back(false);18727else18728SatisfactionStatus.push_back(Satisfaction.IsSatisfied);18729}18730}1873118732for (size_t i = 0; i < Methods.size(); i++) {18733if (!SatisfactionStatus[i])18734continue;18735CXXMethodDecl *Method = Methods[i];18736CXXMethodDecl *OrigMethod = Method;18737if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())18738OrigMethod = cast<CXXMethodDecl>(MF);1873918740const Expr *Constraints = OrigMethod->getTrailingRequiresClause();18741bool AnotherMethodIsMoreConstrained = false;18742for (size_t j = 0; j < Methods.size(); j++) {18743if (i == j || !SatisfactionStatus[j])18744continue;18745CXXMethodDecl *OtherMethod = Methods[j];18746if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())18747OtherMethod = cast<CXXMethodDecl>(MF);1874818749if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,18750CSM))18751continue;1875218753const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();18754if (!OtherConstraints)18755continue;18756if (!Constraints) {18757AnotherMethodIsMoreConstrained = true;18758break;18759}18760if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,18761{Constraints},18762AnotherMethodIsMoreConstrained)) {18763// There was an error with the constraints comparison. Exit the loop18764// and don't consider this function eligible.18765AnotherMethodIsMoreConstrained = true;18766}18767if (AnotherMethodIsMoreConstrained)18768break;18769}18770// FIXME: Do not consider deleted methods as eligible after implementing18771// DR1734 and DR1496.18772if (!AnotherMethodIsMoreConstrained) {18773Method->setIneligibleOrNotSelected(false);18774Record->addedEligibleSpecialMemberFunction(Method,187751 << llvm::to_underlying(CSM));18776}18777}18778}1877918780static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,18781CXXRecordDecl *Record) {18782SmallVector<CXXMethodDecl *, 4> DefaultConstructors;18783SmallVector<CXXMethodDecl *, 4> CopyConstructors;18784SmallVector<CXXMethodDecl *, 4> MoveConstructors;18785SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;18786SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;1878718788for (auto *Decl : Record->decls()) {18789auto *MD = dyn_cast<CXXMethodDecl>(Decl);18790if (!MD) {18791auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);18792if (FTD)18793MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());18794}18795if (!MD)18796continue;18797if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {18798if (CD->isInvalidDecl())18799continue;18800if (CD->isDefaultConstructor())18801DefaultConstructors.push_back(MD);18802else if (CD->isCopyConstructor())18803CopyConstructors.push_back(MD);18804else if (CD->isMoveConstructor())18805MoveConstructors.push_back(MD);18806} else if (MD->isCopyAssignmentOperator()) {18807CopyAssignmentOperators.push_back(MD);18808} else if (MD->isMoveAssignmentOperator()) {18809MoveAssignmentOperators.push_back(MD);18810}18811}1881218813SetEligibleMethods(S, Record, DefaultConstructors,18814CXXSpecialMemberKind::DefaultConstructor);18815SetEligibleMethods(S, Record, CopyConstructors,18816CXXSpecialMemberKind::CopyConstructor);18817SetEligibleMethods(S, Record, MoveConstructors,18818CXXSpecialMemberKind::MoveConstructor);18819SetEligibleMethods(S, Record, CopyAssignmentOperators,18820CXXSpecialMemberKind::CopyAssignment);18821SetEligibleMethods(S, Record, MoveAssignmentOperators,18822CXXSpecialMemberKind::MoveAssignment);18823}1882418825void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,18826ArrayRef<Decl *> Fields, SourceLocation LBrac,18827SourceLocation RBrac,18828const ParsedAttributesView &Attrs) {18829assert(EnclosingDecl && "missing record or interface decl");1883018831// If this is an Objective-C @implementation or category and we have18832// new fields here we should reset the layout of the interface since18833// it will now change.18834if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {18835ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);18836switch (DC->getKind()) {18837default: break;18838case Decl::ObjCCategory:18839Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());18840break;18841case Decl::ObjCImplementation:18842Context.18843ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());18844break;18845}18846}1884718848RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);18849CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);1885018851// Start counting up the number of named members; make sure to include18852// members of anonymous structs and unions in the total.18853unsigned NumNamedMembers = 0;18854if (Record) {18855for (const auto *I : Record->decls()) {18856if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))18857if (IFD->getDeclName())18858++NumNamedMembers;18859}18860}1886118862// Verify that all the fields are okay.18863SmallVector<FieldDecl*, 32> RecFields;1886418865for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();18866i != end; ++i) {18867FieldDecl *FD = cast<FieldDecl>(*i);1886818869// Get the type for the field.18870const Type *FDTy = FD->getType().getTypePtr();1887118872if (!FD->isAnonymousStructOrUnion()) {18873// Remember all fields written by the user.18874RecFields.push_back(FD);18875}1887618877// If the field is already invalid for some reason, don't emit more18878// diagnostics about it.18879if (FD->isInvalidDecl()) {18880EnclosingDecl->setInvalidDecl();18881continue;18882}1888318884// C99 6.7.2.1p2:18885// A structure or union shall not contain a member with18886// incomplete or function type (hence, a structure shall not18887// contain an instance of itself, but may contain a pointer to18888// an instance of itself), except that the last member of a18889// structure with more than one named member may have incomplete18890// array type; such a structure (and any union containing,18891// possibly recursively, a member that is such a structure)18892// shall not be a member of a structure or an element of an18893// array.18894bool IsLastField = (i + 1 == Fields.end());18895if (FDTy->isFunctionType()) {18896// Field declared as a function.18897Diag(FD->getLocation(), diag::err_field_declared_as_function)18898<< FD->getDeclName();18899FD->setInvalidDecl();18900EnclosingDecl->setInvalidDecl();18901continue;18902} else if (FDTy->isIncompleteArrayType() &&18903(Record || isa<ObjCContainerDecl>(EnclosingDecl))) {18904if (Record) {18905// Flexible array member.18906// Microsoft and g++ is more permissive regarding flexible array.18907// It will accept flexible array in union and also18908// as the sole element of a struct/class.18909unsigned DiagID = 0;18910if (!Record->isUnion() && !IsLastField) {18911Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)18912<< FD->getDeclName() << FD->getType()18913<< llvm::to_underlying(Record->getTagKind());18914Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);18915FD->setInvalidDecl();18916EnclosingDecl->setInvalidDecl();18917continue;18918} else if (Record->isUnion())18919DiagID = getLangOpts().MicrosoftExt18920? diag::ext_flexible_array_union_ms18921: diag::ext_flexible_array_union_gnu;18922else if (NumNamedMembers < 1)18923DiagID = getLangOpts().MicrosoftExt18924? diag::ext_flexible_array_empty_aggregate_ms18925: diag::ext_flexible_array_empty_aggregate_gnu;1892618927if (DiagID)18928Diag(FD->getLocation(), DiagID)18929<< FD->getDeclName() << llvm::to_underlying(Record->getTagKind());18930// While the layout of types that contain virtual bases is not specified18931// by the C++ standard, both the Itanium and Microsoft C++ ABIs place18932// virtual bases after the derived members. This would make a flexible18933// array member declared at the end of an object not adjacent to the end18934// of the type.18935if (CXXRecord && CXXRecord->getNumVBases() != 0)18936Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)18937<< FD->getDeclName() << llvm::to_underlying(Record->getTagKind());18938if (!getLangOpts().C99)18939Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)18940<< FD->getDeclName() << llvm::to_underlying(Record->getTagKind());1894118942// If the element type has a non-trivial destructor, we would not18943// implicitly destroy the elements, so disallow it for now.18944//18945// FIXME: GCC allows this. We should probably either implicitly delete18946// the destructor of the containing class, or just allow this.18947QualType BaseElem = Context.getBaseElementType(FD->getType());18948if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {18949Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)18950<< FD->getDeclName() << FD->getType();18951FD->setInvalidDecl();18952EnclosingDecl->setInvalidDecl();18953continue;18954}18955// Okay, we have a legal flexible array member at the end of the struct.18956Record->setHasFlexibleArrayMember(true);18957} else {18958// In ObjCContainerDecl ivars with incomplete array type are accepted,18959// unless they are followed by another ivar. That check is done18960// elsewhere, after synthesized ivars are known.18961}18962} else if (!FDTy->isDependentType() &&18963RequireCompleteSizedType(18964FD->getLocation(), FD->getType(),18965diag::err_field_incomplete_or_sizeless)) {18966// Incomplete type18967FD->setInvalidDecl();18968EnclosingDecl->setInvalidDecl();18969continue;18970} else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {18971if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {18972// A type which contains a flexible array member is considered to be a18973// flexible array member.18974Record->setHasFlexibleArrayMember(true);18975if (!Record->isUnion()) {18976// If this is a struct/class and this is not the last element, reject18977// it. Note that GCC supports variable sized arrays in the middle of18978// structures.18979if (!IsLastField)18980Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)18981<< FD->getDeclName() << FD->getType();18982else {18983// We support flexible arrays at the end of structs in18984// other structs as an extension.18985Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)18986<< FD->getDeclName();18987}18988}18989}18990if (isa<ObjCContainerDecl>(EnclosingDecl) &&18991RequireNonAbstractType(FD->getLocation(), FD->getType(),18992diag::err_abstract_type_in_decl,18993AbstractIvarType)) {18994// Ivars can not have abstract class types18995FD->setInvalidDecl();18996}18997if (Record && FDTTy->getDecl()->hasObjectMember())18998Record->setHasObjectMember(true);18999if (Record && FDTTy->getDecl()->hasVolatileMember())19000Record->setHasVolatileMember(true);19001} else if (FDTy->isObjCObjectType()) {19002/// A field cannot be an Objective-c object19003Diag(FD->getLocation(), diag::err_statically_allocated_object)19004<< FixItHint::CreateInsertion(FD->getLocation(), "*");19005QualType T = Context.getObjCObjectPointerType(FD->getType());19006FD->setType(T);19007} else if (Record && Record->isUnion() &&19008FD->getType().hasNonTrivialObjCLifetime() &&19009getSourceManager().isInSystemHeader(FD->getLocation()) &&19010!getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&19011(FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||19012!Context.hasDirectOwnershipQualifier(FD->getType()))) {19013// For backward compatibility, fields of C unions declared in system19014// headers that have non-trivial ObjC ownership qualifications are marked19015// as unavailable unless the qualifier is explicit and __strong. This can19016// break ABI compatibility between programs compiled with ARC and MRR, but19017// is a better option than rejecting programs using those unions under19018// ARC.19019FD->addAttr(UnavailableAttr::CreateImplicit(19020Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,19021FD->getLocation()));19022} else if (getLangOpts().ObjC &&19023getLangOpts().getGC() != LangOptions::NonGC && Record &&19024!Record->hasObjectMember()) {19025if (FD->getType()->isObjCObjectPointerType() ||19026FD->getType().isObjCGCStrong())19027Record->setHasObjectMember(true);19028else if (Context.getAsArrayType(FD->getType())) {19029QualType BaseType = Context.getBaseElementType(FD->getType());19030if (BaseType->isRecordType() &&19031BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())19032Record->setHasObjectMember(true);19033else if (BaseType->isObjCObjectPointerType() ||19034BaseType.isObjCGCStrong())19035Record->setHasObjectMember(true);19036}19037}1903819039if (Record && !getLangOpts().CPlusPlus &&19040!shouldIgnoreForRecordTriviality(FD)) {19041QualType FT = FD->getType();19042if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {19043Record->setNonTrivialToPrimitiveDefaultInitialize(true);19044if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||19045Record->isUnion())19046Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);19047}19048QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();19049if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {19050Record->setNonTrivialToPrimitiveCopy(true);19051if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())19052Record->setHasNonTrivialToPrimitiveCopyCUnion(true);19053}19054if (FT.isDestructedType()) {19055Record->setNonTrivialToPrimitiveDestroy(true);19056Record->setParamDestroyedInCallee(true);19057if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())19058Record->setHasNonTrivialToPrimitiveDestructCUnion(true);19059}1906019061if (const auto *RT = FT->getAs<RecordType>()) {19062if (RT->getDecl()->getArgPassingRestrictions() ==19063RecordArgPassingKind::CanNeverPassInRegs)19064Record->setArgPassingRestrictions(19065RecordArgPassingKind::CanNeverPassInRegs);19066} else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)19067Record->setArgPassingRestrictions(19068RecordArgPassingKind::CanNeverPassInRegs);19069}1907019071if (Record && FD->getType().isVolatileQualified())19072Record->setHasVolatileMember(true);19073// Keep track of the number of named members.19074if (FD->getIdentifier())19075++NumNamedMembers;19076}1907719078// Okay, we successfully defined 'Record'.19079if (Record) {19080bool Completed = false;19081if (S) {19082Scope *Parent = S->getParent();19083if (Parent && Parent->isTypeAliasScope() &&19084Parent->isTemplateParamScope())19085Record->setInvalidDecl();19086}1908719088if (CXXRecord) {19089if (!CXXRecord->isInvalidDecl()) {19090// Set access bits correctly on the directly-declared conversions.19091for (CXXRecordDecl::conversion_iterator19092I = CXXRecord->conversion_begin(),19093E = CXXRecord->conversion_end(); I != E; ++I)19094I.setAccess((*I)->getAccess());19095}1909619097// Add any implicitly-declared members to this class.19098AddImplicitlyDeclaredMembersToClass(CXXRecord);1909919100if (!CXXRecord->isDependentType()) {19101if (!CXXRecord->isInvalidDecl()) {19102// If we have virtual base classes, we may end up finding multiple19103// final overriders for a given virtual function. Check for this19104// problem now.19105if (CXXRecord->getNumVBases()) {19106CXXFinalOverriderMap FinalOverriders;19107CXXRecord->getFinalOverriders(FinalOverriders);1910819109for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),19110MEnd = FinalOverriders.end();19111M != MEnd; ++M) {19112for (OverridingMethods::iterator SO = M->second.begin(),19113SOEnd = M->second.end();19114SO != SOEnd; ++SO) {19115assert(SO->second.size() > 0 &&19116"Virtual function without overriding functions?");19117if (SO->second.size() == 1)19118continue;1911919120// C++ [class.virtual]p2:19121// In a derived class, if a virtual member function of a base19122// class subobject has more than one final overrider the19123// program is ill-formed.19124Diag(Record->getLocation(), diag::err_multiple_final_overriders)19125<< (const NamedDecl *)M->first << Record;19126Diag(M->first->getLocation(),19127diag::note_overridden_virtual_function);19128for (OverridingMethods::overriding_iterator19129OM = SO->second.begin(),19130OMEnd = SO->second.end();19131OM != OMEnd; ++OM)19132Diag(OM->Method->getLocation(), diag::note_final_overrider)19133<< (const NamedDecl *)M->first << OM->Method->getParent();1913419135Record->setInvalidDecl();19136}19137}19138CXXRecord->completeDefinition(&FinalOverriders);19139Completed = true;19140}19141}19142ComputeSelectedDestructor(*this, CXXRecord);19143ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);19144}19145}1914619147if (!Completed)19148Record->completeDefinition();1914919150// Handle attributes before checking the layout.19151ProcessDeclAttributeList(S, Record, Attrs);1915219153// Check to see if a FieldDecl is a pointer to a function.19154auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {19155const FieldDecl *FD = dyn_cast<FieldDecl>(D);19156if (!FD) {19157// Check whether this is a forward declaration that was inserted by19158// Clang. This happens when a non-forward declared / defined type is19159// used, e.g.:19160//19161// struct foo {19162// struct bar *(*f)();19163// struct bar *(*g)();19164// };19165//19166// "struct bar" shows up in the decl AST as a "RecordDecl" with an19167// incomplete definition.19168if (const auto *TD = dyn_cast<TagDecl>(D))19169return !TD->isCompleteDefinition();19170return false;19171}19172QualType FieldType = FD->getType().getDesugaredType(Context);19173if (isa<PointerType>(FieldType)) {19174QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();19175return PointeeType.getDesugaredType(Context)->isFunctionType();19176}19177return false;19178};1917919180// Maybe randomize the record's decls. We automatically randomize a record19181// of function pointers, unless it has the "no_randomize_layout" attribute.19182if (!getLangOpts().CPlusPlus &&19183(Record->hasAttr<RandomizeLayoutAttr>() ||19184(!Record->hasAttr<NoRandomizeLayoutAttr>() &&19185llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&19186!Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&19187!Record->isRandomized()) {19188SmallVector<Decl *, 32> NewDeclOrdering;19189if (randstruct::randomizeStructureLayout(Context, Record,19190NewDeclOrdering))19191Record->reorderDecls(NewDeclOrdering);19192}1919319194// We may have deferred checking for a deleted destructor. Check now.19195if (CXXRecord) {19196auto *Dtor = CXXRecord->getDestructor();19197if (Dtor && Dtor->isImplicit() &&19198ShouldDeleteSpecialMember(Dtor, CXXSpecialMemberKind::Destructor)) {19199CXXRecord->setImplicitDestructorIsDeleted();19200SetDeclDeleted(Dtor, CXXRecord->getLocation());19201}19202}1920319204if (Record->hasAttrs()) {19205CheckAlignasUnderalignment(Record);1920619207if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())19208checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),19209IA->getRange(), IA->getBestCase(),19210IA->getInheritanceModel());19211}1921219213// Check if the structure/union declaration is a type that can have zero19214// size in C. For C this is a language extension, for C++ it may cause19215// compatibility problems.19216bool CheckForZeroSize;19217if (!getLangOpts().CPlusPlus) {19218CheckForZeroSize = true;19219} else {19220// For C++ filter out types that cannot be referenced in C code.19221CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);19222CheckForZeroSize =19223CXXRecord->getLexicalDeclContext()->isExternCContext() &&19224!CXXRecord->isDependentType() && !inTemplateInstantiation() &&19225CXXRecord->isCLike();19226}19227if (CheckForZeroSize) {19228bool ZeroSize = true;19229bool IsEmpty = true;19230unsigned NonBitFields = 0;19231for (RecordDecl::field_iterator I = Record->field_begin(),19232E = Record->field_end();19233(NonBitFields == 0 || ZeroSize) && I != E; ++I) {19234IsEmpty = false;19235if (I->isUnnamedBitField()) {19236if (!I->isZeroLengthBitField(Context))19237ZeroSize = false;19238} else {19239++NonBitFields;19240QualType FieldType = I->getType();19241if (FieldType->isIncompleteType() ||19242!Context.getTypeSizeInChars(FieldType).isZero())19243ZeroSize = false;19244}19245}1924619247// Empty structs are an extension in C (C99 6.7.2.1p7). They are19248// allowed in C++, but warn if its declaration is inside19249// extern "C" block.19250if (ZeroSize) {19251Diag(RecLoc, getLangOpts().CPlusPlus ?19252diag::warn_zero_size_struct_union_in_extern_c :19253diag::warn_zero_size_struct_union_compat)19254<< IsEmpty << Record->isUnion() << (NonBitFields > 1);19255}1925619257// Structs without named members are extension in C (C99 6.7.2.1p7),19258// but are accepted by GCC.19259if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {19260Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :19261diag::ext_no_named_members_in_struct_union)19262<< Record->isUnion();19263}19264}19265} else {19266ObjCIvarDecl **ClsFields =19267reinterpret_cast<ObjCIvarDecl**>(RecFields.data());19268if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {19269ID->setEndOfDefinitionLoc(RBrac);19270// Add ivar's to class's DeclContext.19271for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {19272ClsFields[i]->setLexicalDeclContext(ID);19273ID->addDecl(ClsFields[i]);19274}19275// Must enforce the rule that ivars in the base classes may not be19276// duplicates.19277if (ID->getSuperClass())19278ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());19279} else if (ObjCImplementationDecl *IMPDecl =19280dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {19281assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");19282for (unsigned I = 0, N = RecFields.size(); I != N; ++I)19283// Ivar declared in @implementation never belongs to the implementation.19284// Only it is in implementation's lexical context.19285ClsFields[I]->setLexicalDeclContext(IMPDecl);19286ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),19287RBrac);19288IMPDecl->setIvarLBraceLoc(LBrac);19289IMPDecl->setIvarRBraceLoc(RBrac);19290} else if (ObjCCategoryDecl *CDecl =19291dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {19292// case of ivars in class extension; all other cases have been19293// reported as errors elsewhere.19294// FIXME. Class extension does not have a LocEnd field.19295// CDecl->setLocEnd(RBrac);19296// Add ivar's to class extension's DeclContext.19297// Diagnose redeclaration of private ivars.19298ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();19299for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {19300if (IDecl) {19301if (const ObjCIvarDecl *ClsIvar =19302IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {19303Diag(ClsFields[i]->getLocation(),19304diag::err_duplicate_ivar_declaration);19305Diag(ClsIvar->getLocation(), diag::note_previous_definition);19306continue;19307}19308for (const auto *Ext : IDecl->known_extensions()) {19309if (const ObjCIvarDecl *ClsExtIvar19310= Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {19311Diag(ClsFields[i]->getLocation(),19312diag::err_duplicate_ivar_declaration);19313Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);19314continue;19315}19316}19317}19318ClsFields[i]->setLexicalDeclContext(CDecl);19319CDecl->addDecl(ClsFields[i]);19320}19321CDecl->setIvarLBraceLoc(LBrac);19322CDecl->setIvarRBraceLoc(RBrac);19323}19324}19325ProcessAPINotes(Record);19326}1932719328/// Determine whether the given integral value is representable within19329/// the given type T.19330static bool isRepresentableIntegerValue(ASTContext &Context,19331llvm::APSInt &Value,19332QualType T) {19333assert((T->isIntegralType(Context) || T->isEnumeralType()) &&19334"Integral type required!");19335unsigned BitWidth = Context.getIntWidth(T);1933619337if (Value.isUnsigned() || Value.isNonNegative()) {19338if (T->isSignedIntegerOrEnumerationType())19339--BitWidth;19340return Value.getActiveBits() <= BitWidth;19341}19342return Value.getSignificantBits() <= BitWidth;19343}1934419345// Given an integral type, return the next larger integral type19346// (or a NULL type of no such type exists).19347static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {19348// FIXME: Int128/UInt128 support, which also needs to be introduced into19349// enum checking below.19350assert((T->isIntegralType(Context) ||19351T->isEnumeralType()) && "Integral type required!");19352const unsigned NumTypes = 4;19353QualType SignedIntegralTypes[NumTypes] = {19354Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy19355};19356QualType UnsignedIntegralTypes[NumTypes] = {19357Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,19358Context.UnsignedLongLongTy19359};1936019361unsigned BitWidth = Context.getTypeSize(T);19362QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes19363: UnsignedIntegralTypes;19364for (unsigned I = 0; I != NumTypes; ++I)19365if (Context.getTypeSize(Types[I]) > BitWidth)19366return Types[I];1936719368return QualType();19369}1937019371EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,19372EnumConstantDecl *LastEnumConst,19373SourceLocation IdLoc,19374IdentifierInfo *Id,19375Expr *Val) {19376unsigned IntWidth = Context.getTargetInfo().getIntWidth();19377llvm::APSInt EnumVal(IntWidth);19378QualType EltTy;1937919380if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))19381Val = nullptr;1938219383if (Val)19384Val = DefaultLvalueConversion(Val).get();1938519386if (Val) {19387if (Enum->isDependentType() || Val->isTypeDependent() ||19388Val->containsErrors())19389EltTy = Context.DependentTy;19390else {19391// FIXME: We don't allow folding in C++11 mode for an enum with a fixed19392// underlying type, but do allow it in all other contexts.19393if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {19394// C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the19395// constant-expression in the enumerator-definition shall be a converted19396// constant expression of the underlying type.19397EltTy = Enum->getIntegerType();19398ExprResult Converted =19399CheckConvertedConstantExpression(Val, EltTy, EnumVal,19400CCEK_Enumerator);19401if (Converted.isInvalid())19402Val = nullptr;19403else19404Val = Converted.get();19405} else if (!Val->isValueDependent() &&19406!(Val =19407VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)19408.get())) {19409// C99 6.7.2.2p2: Make sure we have an integer constant expression.19410} else {19411if (Enum->isComplete()) {19412EltTy = Enum->getIntegerType();1941319414// In Obj-C and Microsoft mode, require the enumeration value to be19415// representable in the underlying type of the enumeration. In C++11,19416// we perform a non-narrowing conversion as part of converted constant19417// expression checking.19418if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {19419if (Context.getTargetInfo()19420.getTriple()19421.isWindowsMSVCEnvironment()) {19422Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;19423} else {19424Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;19425}19426}1942719428// Cast to the underlying type.19429Val = ImpCastExprToType(Val, EltTy,19430EltTy->isBooleanType() ? CK_IntegralToBoolean19431: CK_IntegralCast)19432.get();19433} else if (getLangOpts().CPlusPlus) {19434// C++11 [dcl.enum]p5:19435// If the underlying type is not fixed, the type of each enumerator19436// is the type of its initializing value:19437// - If an initializer is specified for an enumerator, the19438// initializing value has the same type as the expression.19439EltTy = Val->getType();19440} else {19441// C99 6.7.2.2p2:19442// The expression that defines the value of an enumeration constant19443// shall be an integer constant expression that has a value19444// representable as an int.1944519446// Complain if the value is not representable in an int.19447if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))19448Diag(IdLoc, diag::ext_enum_value_not_int)19449<< toString(EnumVal, 10) << Val->getSourceRange()19450<< (EnumVal.isUnsigned() || EnumVal.isNonNegative());19451else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {19452// Force the type of the expression to 'int'.19453Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();19454}19455EltTy = Val->getType();19456}19457}19458}19459}1946019461if (!Val) {19462if (Enum->isDependentType())19463EltTy = Context.DependentTy;19464else if (!LastEnumConst) {19465// C++0x [dcl.enum]p5:19466// If the underlying type is not fixed, the type of each enumerator19467// is the type of its initializing value:19468// - If no initializer is specified for the first enumerator, the19469// initializing value has an unspecified integral type.19470//19471// GCC uses 'int' for its unspecified integral type, as does19472// C99 6.7.2.2p3.19473if (Enum->isFixed()) {19474EltTy = Enum->getIntegerType();19475}19476else {19477EltTy = Context.IntTy;19478}19479} else {19480// Assign the last value + 1.19481EnumVal = LastEnumConst->getInitVal();19482++EnumVal;19483EltTy = LastEnumConst->getType();1948419485// Check for overflow on increment.19486if (EnumVal < LastEnumConst->getInitVal()) {19487// C++0x [dcl.enum]p5:19488// If the underlying type is not fixed, the type of each enumerator19489// is the type of its initializing value:19490//19491// - Otherwise the type of the initializing value is the same as19492// the type of the initializing value of the preceding enumerator19493// unless the incremented value is not representable in that type,19494// in which case the type is an unspecified integral type19495// sufficient to contain the incremented value. If no such type19496// exists, the program is ill-formed.19497QualType T = getNextLargerIntegralType(Context, EltTy);19498if (T.isNull() || Enum->isFixed()) {19499// There is no integral type larger enough to represent this19500// value. Complain, then allow the value to wrap around.19501EnumVal = LastEnumConst->getInitVal();19502EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);19503++EnumVal;19504if (Enum->isFixed())19505// When the underlying type is fixed, this is ill-formed.19506Diag(IdLoc, diag::err_enumerator_wrapped)19507<< toString(EnumVal, 10)19508<< EltTy;19509else19510Diag(IdLoc, diag::ext_enumerator_increment_too_large)19511<< toString(EnumVal, 10);19512} else {19513EltTy = T;19514}1951519516// Retrieve the last enumerator's value, extent that type to the19517// type that is supposed to be large enough to represent the incremented19518// value, then increment.19519EnumVal = LastEnumConst->getInitVal();19520EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());19521EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));19522++EnumVal;1952319524// If we're not in C++, diagnose the overflow of enumerator values,19525// which in C99 means that the enumerator value is not representable in19526// an int (C99 6.7.2.2p2). However, we support GCC's extension that19527// permits enumerator values that are representable in some larger19528// integral type.19529if (!getLangOpts().CPlusPlus && !T.isNull())19530Diag(IdLoc, diag::warn_enum_value_overflow);19531} else if (!getLangOpts().CPlusPlus &&19532!EltTy->isDependentType() &&19533!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {19534// Enforce C99 6.7.2.2p2 even when we compute the next value.19535Diag(IdLoc, diag::ext_enum_value_not_int)19536<< toString(EnumVal, 10) << 1;19537}19538}19539}1954019541if (!EltTy->isDependentType()) {19542// Make the enumerator value match the signedness and size of the19543// enumerator's type.19544EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));19545EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());19546}1954719548return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,19549Val, EnumVal);19550}1955119552SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,19553SourceLocation IILoc) {19554if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||19555!getLangOpts().CPlusPlus)19556return SkipBodyInfo();1955719558// We have an anonymous enum definition. Look up the first enumerator to19559// determine if we should merge the definition with an existing one and19560// skip the body.19561NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,19562forRedeclarationInCurContext());19563auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);19564if (!PrevECD)19565return SkipBodyInfo();1956619567EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());19568NamedDecl *Hidden;19569if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {19570SkipBodyInfo Skip;19571Skip.Previous = Hidden;19572return Skip;19573}1957419575return SkipBodyInfo();19576}1957719578Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,19579SourceLocation IdLoc, IdentifierInfo *Id,19580const ParsedAttributesView &Attrs,19581SourceLocation EqualLoc, Expr *Val) {19582EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);19583EnumConstantDecl *LastEnumConst =19584cast_or_null<EnumConstantDecl>(lastEnumConst);1958519586// The scope passed in may not be a decl scope. Zip up the scope tree until19587// we find one that is.19588S = getNonFieldDeclScope(S);1958919590// Verify that there isn't already something declared with this name in this19591// scope.19592LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,19593RedeclarationKind::ForVisibleRedeclaration);19594LookupName(R, S);19595NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();1959619597if (PrevDecl && PrevDecl->isTemplateParameter()) {19598// Maybe we will complain about the shadowed template parameter.19599DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);19600// Just pretend that we didn't see the previous declaration.19601PrevDecl = nullptr;19602}1960319604// C++ [class.mem]p15:19605// If T is the name of a class, then each of the following shall have a name19606// different from T:19607// - every enumerator of every member of class T that is an unscoped19608// enumerated type19609if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())19610DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),19611DeclarationNameInfo(Id, IdLoc));1961219613EnumConstantDecl *New =19614CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);19615if (!New)19616return nullptr;1961719618if (PrevDecl) {19619if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {19620// Check for other kinds of shadowing not already handled.19621CheckShadow(New, PrevDecl, R);19622}1962319624// When in C++, we may get a TagDecl with the same name; in this case the19625// enum constant will 'hide' the tag.19626assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&19627"Received TagDecl when not in C++!");19628if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {19629if (isa<EnumConstantDecl>(PrevDecl))19630Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;19631else19632Diag(IdLoc, diag::err_redefinition) << Id;19633notePreviousDefinition(PrevDecl, IdLoc);19634return nullptr;19635}19636}1963719638// Process attributes.19639ProcessDeclAttributeList(S, New, Attrs);19640AddPragmaAttributes(S, New);19641ProcessAPINotes(New);1964219643// Register this decl in the current scope stack.19644New->setAccess(TheEnumDecl->getAccess());19645PushOnScopeChains(New, S);1964619647ActOnDocumentableDecl(New);1964819649return New;19650}1965119652// Returns true when the enum initial expression does not trigger the19653// duplicate enum warning. A few common cases are exempted as follows:19654// Element2 = Element119655// Element2 = Element1 + 119656// Element2 = Element1 - 119657// Where Element2 and Element1 are from the same enum.19658static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {19659Expr *InitExpr = ECD->getInitExpr();19660if (!InitExpr)19661return true;19662InitExpr = InitExpr->IgnoreImpCasts();1966319664if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {19665if (!BO->isAdditiveOp())19666return true;19667IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());19668if (!IL)19669return true;19670if (IL->getValue() != 1)19671return true;1967219673InitExpr = BO->getLHS();19674}1967519676// This checks if the elements are from the same enum.19677DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);19678if (!DRE)19679return true;1968019681EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());19682if (!EnumConstant)19683return true;1968419685if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=19686Enum)19687return true;1968819689return false;19690}1969119692// Emits a warning when an element is implicitly set a value that19693// a previous element has already been set to.19694static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,19695EnumDecl *Enum, QualType EnumType) {19696// Avoid anonymous enums19697if (!Enum->getIdentifier())19698return;1969919700// Only check for small enums.19701if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)19702return;1970319704if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))19705return;1970619707typedef SmallVector<EnumConstantDecl *, 3> ECDVector;19708typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;1970919710typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;1971119712// DenseMaps cannot contain the all ones int64_t value, so use unordered_map.19713typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;1971419715// Use int64_t as a key to avoid needing special handling for map keys.19716auto EnumConstantToKey = [](const EnumConstantDecl *D) {19717llvm::APSInt Val = D->getInitVal();19718return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();19719};1972019721DuplicatesVector DupVector;19722ValueToVectorMap EnumMap;1972319724// Populate the EnumMap with all values represented by enum constants without19725// an initializer.19726for (auto *Element : Elements) {19727EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);1972819729// Null EnumConstantDecl means a previous diagnostic has been emitted for19730// this constant. Skip this enum since it may be ill-formed.19731if (!ECD) {19732return;19733}1973419735// Constants with initializers are handled in the next loop.19736if (ECD->getInitExpr())19737continue;1973819739// Duplicate values are handled in the next loop.19740EnumMap.insert({EnumConstantToKey(ECD), ECD});19741}1974219743if (EnumMap.size() == 0)19744return;1974519746// Create vectors for any values that has duplicates.19747for (auto *Element : Elements) {19748// The last loop returned if any constant was null.19749EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);19750if (!ValidDuplicateEnum(ECD, Enum))19751continue;1975219753auto Iter = EnumMap.find(EnumConstantToKey(ECD));19754if (Iter == EnumMap.end())19755continue;1975619757DeclOrVector& Entry = Iter->second;19758if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {19759// Ensure constants are different.19760if (D == ECD)19761continue;1976219763// Create new vector and push values onto it.19764auto Vec = std::make_unique<ECDVector>();19765Vec->push_back(D);19766Vec->push_back(ECD);1976719768// Update entry to point to the duplicates vector.19769Entry = Vec.get();1977019771// Store the vector somewhere we can consult later for quick emission of19772// diagnostics.19773DupVector.emplace_back(std::move(Vec));19774continue;19775}1977619777ECDVector *Vec = Entry.get<ECDVector*>();19778// Make sure constants are not added more than once.19779if (*Vec->begin() == ECD)19780continue;1978119782Vec->push_back(ECD);19783}1978419785// Emit diagnostics.19786for (const auto &Vec : DupVector) {19787assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");1978819789// Emit warning for one enum constant.19790auto *FirstECD = Vec->front();19791S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)19792<< FirstECD << toString(FirstECD->getInitVal(), 10)19793<< FirstECD->getSourceRange();1979419795// Emit one note for each of the remaining enum constants with19796// the same value.19797for (auto *ECD : llvm::drop_begin(*Vec))19798S.Diag(ECD->getLocation(), diag::note_duplicate_element)19799<< ECD << toString(ECD->getInitVal(), 10)19800<< ECD->getSourceRange();19801}19802}1980319804bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,19805bool AllowMask) const {19806assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");19807assert(ED->isCompleteDefinition() && "expected enum definition");1980819809auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));19810llvm::APInt &FlagBits = R.first->second;1981119812if (R.second) {19813for (auto *E : ED->enumerators()) {19814const auto &EVal = E->getInitVal();19815// Only single-bit enumerators introduce new flag values.19816if (EVal.isPowerOf2())19817FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;19818}19819}1982019821// A value is in a flag enum if either its bits are a subset of the enum's19822// flag bits (the first condition) or we are allowing masks and the same is19823// true of its complement (the second condition). When masks are allowed, we19824// allow the common idiom of ~(enum1 | enum2) to be a valid enum value.19825//19826// While it's true that any value could be used as a mask, the assumption is19827// that a mask will have all of the insignificant bits set. Anything else is19828// likely a logic error.19829llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());19830return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));19831}1983219833void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,19834Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,19835const ParsedAttributesView &Attrs) {19836EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);19837QualType EnumType = Context.getTypeDeclType(Enum);1983819839ProcessDeclAttributeList(S, Enum, Attrs);19840ProcessAPINotes(Enum);1984119842if (Enum->isDependentType()) {19843for (unsigned i = 0, e = Elements.size(); i != e; ++i) {19844EnumConstantDecl *ECD =19845cast_or_null<EnumConstantDecl>(Elements[i]);19846if (!ECD) continue;1984719848ECD->setType(EnumType);19849}1985019851Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);19852return;19853}1985419855// TODO: If the result value doesn't fit in an int, it must be a long or long19856// long value. ISO C does not support this, but GCC does as an extension,19857// emit a warning.19858unsigned IntWidth = Context.getTargetInfo().getIntWidth();19859unsigned CharWidth = Context.getTargetInfo().getCharWidth();19860unsigned ShortWidth = Context.getTargetInfo().getShortWidth();1986119862// Verify that all the values are okay, compute the size of the values, and19863// reverse the list.19864unsigned NumNegativeBits = 0;19865unsigned NumPositiveBits = 0;1986619867for (unsigned i = 0, e = Elements.size(); i != e; ++i) {19868EnumConstantDecl *ECD =19869cast_or_null<EnumConstantDecl>(Elements[i]);19870if (!ECD) continue; // Already issued a diagnostic.1987119872const llvm::APSInt &InitVal = ECD->getInitVal();1987319874// Keep track of the size of positive and negative values.19875if (InitVal.isUnsigned() || InitVal.isNonNegative()) {19876// If the enumerator is zero that should still be counted as a positive19877// bit since we need a bit to store the value zero.19878unsigned ActiveBits = InitVal.getActiveBits();19879NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});19880} else {19881NumNegativeBits =19882std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());19883}19884}1988519886// If we have an empty set of enumerators we still need one bit.19887// From [dcl.enum]p819888// If the enumerator-list is empty, the values of the enumeration are as if19889// the enumeration had a single enumerator with value 019890if (!NumPositiveBits && !NumNegativeBits)19891NumPositiveBits = 1;1989219893// Figure out the type that should be used for this enum.19894QualType BestType;19895unsigned BestWidth;1989619897// C++0x N3000 [conv.prom]p3:19898// An rvalue of an unscoped enumeration type whose underlying19899// type is not fixed can be converted to an rvalue of the first19900// of the following types that can represent all the values of19901// the enumeration: int, unsigned int, long int, unsigned long19902// int, long long int, or unsigned long long int.19903// C99 6.4.4.3p2:19904// An identifier declared as an enumeration constant has type int.19905// The C99 rule is modified by a gcc extension19906QualType BestPromotionType;1990719908bool Packed = Enum->hasAttr<PackedAttr>();19909// -fshort-enums is the equivalent to specifying the packed attribute on all19910// enum definitions.19911if (LangOpts.ShortEnums)19912Packed = true;1991319914// If the enum already has a type because it is fixed or dictated by the19915// target, promote that type instead of analyzing the enumerators.19916if (Enum->isComplete()) {19917BestType = Enum->getIntegerType();19918if (Context.isPromotableIntegerType(BestType))19919BestPromotionType = Context.getPromotedIntegerType(BestType);19920else19921BestPromotionType = BestType;1992219923BestWidth = Context.getIntWidth(BestType);19924}19925else if (NumNegativeBits) {19926// If there is a negative value, figure out the smallest integer type (of19927// int/long/longlong) that fits.19928// If it's packed, check also if it fits a char or a short.19929if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {19930BestType = Context.SignedCharTy;19931BestWidth = CharWidth;19932} else if (Packed && NumNegativeBits <= ShortWidth &&19933NumPositiveBits < ShortWidth) {19934BestType = Context.ShortTy;19935BestWidth = ShortWidth;19936} else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {19937BestType = Context.IntTy;19938BestWidth = IntWidth;19939} else {19940BestWidth = Context.getTargetInfo().getLongWidth();1994119942if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {19943BestType = Context.LongTy;19944} else {19945BestWidth = Context.getTargetInfo().getLongLongWidth();1994619947if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)19948Diag(Enum->getLocation(), diag::ext_enum_too_large);19949BestType = Context.LongLongTy;19950}19951}19952BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);19953} else {19954// If there is no negative value, figure out the smallest type that fits19955// all of the enumerator values.19956// If it's packed, check also if it fits a char or a short.19957if (Packed && NumPositiveBits <= CharWidth) {19958BestType = Context.UnsignedCharTy;19959BestPromotionType = Context.IntTy;19960BestWidth = CharWidth;19961} else if (Packed && NumPositiveBits <= ShortWidth) {19962BestType = Context.UnsignedShortTy;19963BestPromotionType = Context.IntTy;19964BestWidth = ShortWidth;19965} else if (NumPositiveBits <= IntWidth) {19966BestType = Context.UnsignedIntTy;19967BestWidth = IntWidth;19968BestPromotionType19969= (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)19970? Context.UnsignedIntTy : Context.IntTy;19971} else if (NumPositiveBits <=19972(BestWidth = Context.getTargetInfo().getLongWidth())) {19973BestType = Context.UnsignedLongTy;19974BestPromotionType19975= (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)19976? Context.UnsignedLongTy : Context.LongTy;19977} else {19978BestWidth = Context.getTargetInfo().getLongLongWidth();19979if (NumPositiveBits > BestWidth) {19980// This can happen with bit-precise integer types, but those are not19981// allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.19982// FIXME: GCC uses __int128_t and __uint128_t for cases that fit within19983// a 128-bit integer, we should consider doing the same.19984Diag(Enum->getLocation(), diag::ext_enum_too_large);19985}19986BestType = Context.UnsignedLongLongTy;19987BestPromotionType19988= (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)19989? Context.UnsignedLongLongTy : Context.LongLongTy;19990}19991}1999219993// Loop over all of the enumerator constants, changing their types to match19994// the type of the enum if needed.19995for (auto *D : Elements) {19996auto *ECD = cast_or_null<EnumConstantDecl>(D);19997if (!ECD) continue; // Already issued a diagnostic.1999819999// Standard C says the enumerators have int type, but we allow, as an20000// extension, the enumerators to be larger than int size. If each20001// enumerator value fits in an int, type it as an int, otherwise type it the20002// same as the enumerator decl itself. This means that in "enum { X = 1U }"20003// that X has type 'int', not 'unsigned'.2000420005// Determine whether the value fits into an int.20006llvm::APSInt InitVal = ECD->getInitVal();2000720008// If it fits into an integer type, force it. Otherwise force it to match20009// the enum decl type.20010QualType NewTy;20011unsigned NewWidth;20012bool NewSign;20013if (!getLangOpts().CPlusPlus &&20014!Enum->isFixed() &&20015isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {20016NewTy = Context.IntTy;20017NewWidth = IntWidth;20018NewSign = true;20019} else if (ECD->getType() == BestType) {20020// Already the right type!20021if (getLangOpts().CPlusPlus)20022// C++ [dcl.enum]p4: Following the closing brace of an20023// enum-specifier, each enumerator has the type of its20024// enumeration.20025ECD->setType(EnumType);20026continue;20027} else {20028NewTy = BestType;20029NewWidth = BestWidth;20030NewSign = BestType->isSignedIntegerOrEnumerationType();20031}2003220033// Adjust the APSInt value.20034InitVal = InitVal.extOrTrunc(NewWidth);20035InitVal.setIsSigned(NewSign);20036ECD->setInitVal(Context, InitVal);2003720038// Adjust the Expr initializer and type.20039if (ECD->getInitExpr() &&20040!Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))20041ECD->setInitExpr(ImplicitCastExpr::Create(20042Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),20043/*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));20044if (getLangOpts().CPlusPlus)20045// C++ [dcl.enum]p4: Following the closing brace of an20046// enum-specifier, each enumerator has the type of its20047// enumeration.20048ECD->setType(EnumType);20049else20050ECD->setType(NewTy);20051}2005220053Enum->completeDefinition(BestType, BestPromotionType,20054NumPositiveBits, NumNegativeBits);2005520056CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);2005720058if (Enum->isClosedFlag()) {20059for (Decl *D : Elements) {20060EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);20061if (!ECD) continue; // Already issued a diagnostic.2006220063llvm::APSInt InitVal = ECD->getInitVal();20064if (InitVal != 0 && !InitVal.isPowerOf2() &&20065!IsValueInFlagEnum(Enum, InitVal, true))20066Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)20067<< ECD << Enum;20068}20069}2007020071// Now that the enum type is defined, ensure it's not been underaligned.20072if (Enum->hasAttrs())20073CheckAlignasUnderalignment(Enum);20074}2007520076Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,20077SourceLocation StartLoc,20078SourceLocation EndLoc) {20079StringLiteral *AsmString = cast<StringLiteral>(expr);2008020081FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,20082AsmString, StartLoc,20083EndLoc);20084CurContext->addDecl(New);20085return New;20086}2008720088TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {20089auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);20090CurContext->addDecl(New);20091PushDeclContext(S, New);20092PushFunctionScope();20093PushCompoundScope(false);20094return New;20095}2009620097void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {20098D->setStmt(Statement);20099PopCompoundScope();20100PopFunctionScopeInfo();20101PopDeclContext();20102}2010320104void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,20105IdentifierInfo* AliasName,20106SourceLocation PragmaLoc,20107SourceLocation NameLoc,20108SourceLocation AliasNameLoc) {20109NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,20110LookupOrdinaryName);20111AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),20112AttributeCommonInfo::Form::Pragma());20113AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(20114Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);2011520116// If a declaration that:20117// 1) declares a function or a variable20118// 2) has external linkage20119// already exists, add a label attribute to it.20120if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {20121if (isDeclExternC(PrevDecl))20122PrevDecl->addAttr(Attr);20123else20124Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)20125<< /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;20126// Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.20127} else20128(void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));20129}2013020131void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,20132SourceLocation PragmaLoc,20133SourceLocation NameLoc) {20134Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);2013520136if (PrevDecl) {20137PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));20138} else {20139(void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));20140}20141}2014220143void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,20144IdentifierInfo* AliasName,20145SourceLocation PragmaLoc,20146SourceLocation NameLoc,20147SourceLocation AliasNameLoc) {20148Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,20149LookupOrdinaryName);20150WeakInfo W = WeakInfo(Name, NameLoc);2015120152if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {20153if (!PrevDecl->hasAttr<AliasAttr>())20154if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))20155DeclApplyPragmaWeak(TUScope, ND, W);20156} else {20157(void)WeakUndeclaredIdentifiers[AliasName].insert(W);20158}20159}2016020161Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,20162bool Final) {20163assert(FD && "Expected non-null FunctionDecl");2016420165// SYCL functions can be template, so we check if they have appropriate20166// attribute prior to checking if it is a template.20167if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())20168return FunctionEmissionStatus::Emitted;2016920170// Templates are emitted when they're instantiated.20171if (FD->isDependentContext())20172return FunctionEmissionStatus::TemplateDiscarded;2017320174// Check whether this function is an externally visible definition.20175auto IsEmittedForExternalSymbol = [this, FD]() {20176// We have to check the GVA linkage of the function's *definition* -- if we20177// only have a declaration, we don't know whether or not the function will20178// be emitted, because (say) the definition could include "inline".20179const FunctionDecl *Def = FD->getDefinition();2018020181return Def && !isDiscardableGVALinkage(20182getASTContext().GetGVALinkageForFunction(Def));20183};2018420185if (LangOpts.OpenMPIsTargetDevice) {20186// In OpenMP device mode we will not emit host only functions, or functions20187// we don't need due to their linkage.20188std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =20189OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());20190// DevTy may be changed later by20191// #pragma omp declare target to(*) device_type(*).20192// Therefore DevTy having no value does not imply host. The emission status20193// will be checked again at the end of compilation unit with Final = true.20194if (DevTy)20195if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)20196return FunctionEmissionStatus::OMPDiscarded;20197// If we have an explicit value for the device type, or we are in a target20198// declare context, we need to emit all extern and used symbols.20199if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)20200if (IsEmittedForExternalSymbol())20201return FunctionEmissionStatus::Emitted;20202// Device mode only emits what it must, if it wasn't tagged yet and needed,20203// we'll omit it.20204if (Final)20205return FunctionEmissionStatus::OMPDiscarded;20206} else if (LangOpts.OpenMP > 45) {20207// In OpenMP host compilation prior to 5.0 everything was an emitted host20208// function. In 5.0, no_host was introduced which might cause a function to20209// be omitted.20210std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =20211OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());20212if (DevTy)20213if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)20214return FunctionEmissionStatus::OMPDiscarded;20215}2021620217if (Final && LangOpts.OpenMP && !LangOpts.CUDA)20218return FunctionEmissionStatus::Emitted;2021920220if (LangOpts.CUDA) {20221// When compiling for device, host functions are never emitted. Similarly,20222// when compiling for host, device and global functions are never emitted.20223// (Technically, we do emit a host-side stub for global functions, but this20224// doesn't count for our purposes here.)20225CUDAFunctionTarget T = CUDA().IdentifyTarget(FD);20226if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)20227return FunctionEmissionStatus::CUDADiscarded;20228if (!LangOpts.CUDAIsDevice &&20229(T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))20230return FunctionEmissionStatus::CUDADiscarded;2023120232if (IsEmittedForExternalSymbol())20233return FunctionEmissionStatus::Emitted;20234}2023520236// Otherwise, the function is known-emitted if it's in our set of20237// known-emitted functions.20238return FunctionEmissionStatus::Unknown;20239}2024020241bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {20242// Host-side references to a __global__ function refer to the stub, so the20243// function itself is never emitted and therefore should not be marked.20244// If we have host fn calls kernel fn calls host+device, the HD function20245// does not get instantiated on the host. We model this by omitting at the20246// call to the kernel from the callgraph. This ensures that, when compiling20247// for host, only HD functions actually called from the host get marked as20248// known-emitted.20249return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&20250CUDA().IdentifyTarget(Callee) == CUDAFunctionTarget::Global;20251}2025220253void Sema::diagnoseFunctionEffectMergeConflicts(20254const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc,20255SourceLocation OldLoc) {20256for (const FunctionEffectSet::Conflict &Conflict : Errs) {20257Diag(NewLoc, diag::warn_conflicting_func_effects)20258<< Conflict.Kept.description() << Conflict.Rejected.description();20259Diag(OldLoc, diag::note_previous_declaration);20260}20261}2026220263bool Sema::diagnoseConflictingFunctionEffect(20264const FunctionEffectsRef &FX, const FunctionEffectWithCondition &NewEC,20265SourceLocation NewAttrLoc) {20266// If the new effect has a condition, we can't detect conflicts until the20267// condition is resolved.20268if (NewEC.Cond.getCondition() != nullptr)20269return false;2027020271// Diagnose the new attribute as incompatible with a previous one.20272auto Incompatible = [&](const FunctionEffectWithCondition &PrevEC) {20273Diag(NewAttrLoc, diag::err_attributes_are_not_compatible)20274<< ("'" + NewEC.description() + "'")20275<< ("'" + PrevEC.description() + "'") << false;20276// We don't necessarily have the location of the previous attribute,20277// so no note.20278return true;20279};2028020281// Compare against previous attributes.20282FunctionEffect::Kind NewKind = NewEC.Effect.kind();2028320284for (const FunctionEffectWithCondition &PrevEC : FX) {20285// Again, can't check yet when the effect is conditional.20286if (PrevEC.Cond.getCondition() != nullptr)20287continue;2028820289FunctionEffect::Kind PrevKind = PrevEC.Effect.kind();20290// Note that we allow PrevKind == NewKind; it's redundant and ignored.2029120292if (PrevEC.Effect.oppositeKind() == NewKind)20293return Incompatible(PrevEC);2029420295// A new allocating is incompatible with a previous nonblocking.20296if (PrevKind == FunctionEffect::Kind::NonBlocking &&20297NewKind == FunctionEffect::Kind::Allocating)20298return Incompatible(PrevEC);2029920300// A new nonblocking is incompatible with a previous allocating.20301if (PrevKind == FunctionEffect::Kind::Allocating &&20302NewKind == FunctionEffect::Kind::NonBlocking)20303return Incompatible(PrevEC);20304}2030520306return false;20307}203082030920310