21042 lines · cpp
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// This file implements semantic analysis for declarations.10//11//===----------------------------------------------------------------------===//12 13#include "TypeLocBuilder.h"14#include "clang/AST/ASTConsumer.h"15#include "clang/AST/ASTContext.h"16#include "clang/AST/ASTLambda.h"17#include "clang/AST/CXXInheritance.h"18#include "clang/AST/CharUnits.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/MangleNumberingContext.h"27#include "clang/AST/NonTrivialTypeVisitor.h"28#include "clang/AST/Randstruct.h"29#include "clang/AST/StmtCXX.h"30#include "clang/AST/Type.h"31#include "clang/Basic/Builtins.h"32#include "clang/Basic/DiagnosticComment.h"33#include "clang/Basic/PartialDiagnostic.h"34#include "clang/Basic/SourceManager.h"35#include "clang/Basic/TargetInfo.h"36#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex37#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.38#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex39#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()40#include "clang/Sema/CXXFieldCollector.h"41#include "clang/Sema/DeclSpec.h"42#include "clang/Sema/DelayedDiagnostic.h"43#include "clang/Sema/Initialization.h"44#include "clang/Sema/Lookup.h"45#include "clang/Sema/ParsedTemplate.h"46#include "clang/Sema/Scope.h"47#include "clang/Sema/ScopeInfo.h"48#include "clang/Sema/SemaARM.h"49#include "clang/Sema/SemaCUDA.h"50#include "clang/Sema/SemaHLSL.h"51#include "clang/Sema/SemaInternal.h"52#include "clang/Sema/SemaObjC.h"53#include "clang/Sema/SemaOpenACC.h"54#include "clang/Sema/SemaOpenMP.h"55#include "clang/Sema/SemaPPC.h"56#include "clang/Sema/SemaRISCV.h"57#include "clang/Sema/SemaSYCL.h"58#include "clang/Sema/SemaSwift.h"59#include "clang/Sema/SemaWasm.h"60#include "clang/Sema/Template.h"61#include "llvm/ADT/STLForwardCompat.h"62#include "llvm/ADT/ScopeExit.h"63#include "llvm/ADT/SmallPtrSet.h"64#include "llvm/ADT/SmallString.h"65#include "llvm/ADT/StringExtras.h"66#include "llvm/ADT/StringRef.h"67#include "llvm/Support/SaveAndRestore.h"68#include "llvm/TargetParser/Triple.h"69#include <algorithm>70#include <cstring>71#include <optional>72#include <unordered_map>73 74using namespace clang;75using namespace sema;76 77Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {78 if (OwnedType) {79 Decl *Group[2] = { OwnedType, Ptr };80 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));81 }82 83 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));84}85 86namespace {87 88class TypeNameValidatorCCC final : public CorrectionCandidateCallback {89 public:90 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,91 bool AllowTemplates = false,92 bool AllowNonTemplates = true)93 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),94 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {95 WantExpressionKeywords = false;96 WantCXXNamedCasts = false;97 WantRemainingKeywords = false;98 }99 100 bool ValidateCandidate(const TypoCorrection &candidate) override {101 if (NamedDecl *ND = candidate.getCorrectionDecl()) {102 if (!AllowInvalidDecl && ND->isInvalidDecl())103 return false;104 105 if (getAsTypeTemplateDecl(ND))106 return AllowTemplates;107 108 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);109 if (!IsType)110 return false;111 112 if (AllowNonTemplates)113 return true;114 115 // An injected-class-name of a class template (specialization) is valid116 // as a template or as a non-template.117 if (AllowTemplates) {118 auto *RD = dyn_cast<CXXRecordDecl>(ND);119 if (!RD || !RD->isInjectedClassName())120 return false;121 RD = cast<CXXRecordDecl>(RD->getDeclContext());122 return RD->getDescribedClassTemplate() ||123 isa<ClassTemplateSpecializationDecl>(RD);124 }125 126 return false;127 }128 129 return !WantClassName && candidate.isKeyword();130 }131 132 std::unique_ptr<CorrectionCandidateCallback> clone() override {133 return std::make_unique<TypeNameValidatorCCC>(*this);134 }135 136 private:137 bool AllowInvalidDecl;138 bool WantClassName;139 bool AllowTemplates;140 bool AllowNonTemplates;141};142 143} // end anonymous namespace144 145void Sema::checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK,146 TypeDecl *TD, SourceLocation NameLoc) {147 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);148 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);149 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&150 FoundRD->isInjectedClassName() &&151 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {152 Diag(NameLoc,153 DCK == DiagCtorKind::Typename154 ? diag::ext_out_of_line_qualified_id_type_names_constructor155 : diag::err_out_of_line_qualified_id_type_names_constructor)156 << TD->getIdentifier() << /*Type=*/1157 << 0 /*if any keyword was present, it was 'typename'*/;158 }159 160 DiagnoseUseOfDecl(TD, NameLoc);161 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);162}163 164namespace {165enum class UnqualifiedTypeNameLookupResult {166 NotFound,167 FoundNonType,168 FoundType169};170} // end anonymous namespace171 172/// Tries to perform unqualified lookup of the type decls in bases for173/// dependent class.174/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a175/// type decl, \a FoundType if only type decls are found.176static UnqualifiedTypeNameLookupResult177lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,178 SourceLocation NameLoc,179 const CXXRecordDecl *RD) {180 if (!RD->hasDefinition())181 return UnqualifiedTypeNameLookupResult::NotFound;182 // Look for type decls in base classes.183 UnqualifiedTypeNameLookupResult FoundTypeDecl =184 UnqualifiedTypeNameLookupResult::NotFound;185 for (const auto &Base : RD->bases()) {186 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();187 if (BaseRD) {188 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(189 Base.getType().getCanonicalType())) {190 // Look for type decls in dependent base classes that have known primary191 // templates.192 if (!TST->isDependentType())193 continue;194 auto *TD = TST->getTemplateName().getAsTemplateDecl();195 if (!TD)196 continue;197 if (auto *BasePrimaryTemplate =198 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {199 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())200 BaseRD = BasePrimaryTemplate;201 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {202 if (const ClassTemplatePartialSpecializationDecl *PS =203 CTD->findPartialSpecialization(Base.getType()))204 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())205 BaseRD = PS;206 }207 }208 }209 if (BaseRD) {210 for (NamedDecl *ND : BaseRD->lookup(&II)) {211 if (!isa<TypeDecl>(ND))212 return UnqualifiedTypeNameLookupResult::FoundNonType;213 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;214 }215 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {216 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {217 case UnqualifiedTypeNameLookupResult::FoundNonType:218 return UnqualifiedTypeNameLookupResult::FoundNonType;219 case UnqualifiedTypeNameLookupResult::FoundType:220 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;221 break;222 case UnqualifiedTypeNameLookupResult::NotFound:223 break;224 }225 }226 }227 }228 229 return FoundTypeDecl;230}231 232static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,233 const IdentifierInfo &II,234 SourceLocation NameLoc) {235 // Lookup in the parent class template context, if any.236 const CXXRecordDecl *RD = nullptr;237 UnqualifiedTypeNameLookupResult FoundTypeDecl =238 UnqualifiedTypeNameLookupResult::NotFound;239 for (DeclContext *DC = S.CurContext;240 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;241 DC = DC->getParent()) {242 // Look for type decls in dependent base classes that have known primary243 // templates.244 RD = dyn_cast<CXXRecordDecl>(DC);245 if (RD && RD->getDescribedClassTemplate())246 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);247 }248 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)249 return nullptr;250 251 // We found some types in dependent base classes. Recover as if the user252 // wrote 'MyClass::II' instead of 'II', and this implicit typename was253 // allowed. We'll fully resolve the lookup during template instantiation.254 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;255 256 ASTContext &Context = S.Context;257 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());258 QualType T =259 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);260 261 CXXScopeSpec SS;262 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));263 264 TypeLocBuilder Builder;265 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);266 DepTL.setNameLoc(NameLoc);267 DepTL.setElaboratedKeywordLoc(SourceLocation());268 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));269 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));270}271 272ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,273 Scope *S, CXXScopeSpec *SS, bool isClassName,274 bool HasTrailingDot, ParsedType ObjectTypePtr,275 bool IsCtorOrDtorName,276 bool WantNontrivialTypeSourceInfo,277 bool IsClassTemplateDeductionContext,278 ImplicitTypenameContext AllowImplicitTypename,279 IdentifierInfo **CorrectedII) {280 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;281 // FIXME: Consider allowing this outside C++1z mode as an extension.282 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&283 getLangOpts().CPlusPlus17 && IsImplicitTypename &&284 !HasTrailingDot;285 286 // Determine where we will perform name lookup.287 DeclContext *LookupCtx = nullptr;288 if (ObjectTypePtr) {289 QualType ObjectType = ObjectTypePtr.get();290 if (ObjectType->isRecordType())291 LookupCtx = computeDeclContext(ObjectType);292 } else if (SS && SS->isNotEmpty()) {293 LookupCtx = computeDeclContext(*SS, false);294 295 if (!LookupCtx) {296 if (isDependentScopeSpecifier(*SS)) {297 // C++ [temp.res]p3:298 // A qualified-id that refers to a type and in which the299 // nested-name-specifier depends on a template-parameter (14.6.2)300 // shall be prefixed by the keyword typename to indicate that the301 // qualified-id denotes a type, forming an302 // elaborated-type-specifier (7.1.5.3).303 //304 // We therefore do not perform any name lookup if the result would305 // refer to a member of an unknown specialization.306 // In C++2a, in several contexts a 'typename' is not required. Also307 // allow this as an extension.308 if (IsImplicitTypename) {309 if (AllowImplicitTypename == ImplicitTypenameContext::No)310 return nullptr;311 SourceLocation QualifiedLoc = SS->getRange().getBegin();312 // FIXME: Defer the diagnostic after we build the type and use it.313 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)314 << Context.getDependentNameType(ElaboratedTypeKeyword::None,315 SS->getScopeRep(), &II);316 if (!getLangOpts().CPlusPlus20)317 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");318 }319 320 // We know from the grammar that this name refers to a type,321 // so build a dependent node to describe the type.322 if (WantNontrivialTypeSourceInfo)323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,324 (ImplicitTypenameContext)IsImplicitTypename)325 .get();326 327 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);328 QualType T = CheckTypenameType(329 IsImplicitTypename ? ElaboratedTypeKeyword::Typename330 : ElaboratedTypeKeyword::None,331 SourceLocation(), QualifierLoc, II, NameLoc);332 return ParsedType::make(T);333 }334 335 return nullptr;336 }337 338 if (!LookupCtx->isDependentContext() &&339 RequireCompleteDeclContext(*SS, LookupCtx))340 return nullptr;341 }342 343 // In the case where we know that the identifier is a class name, we know that344 // it is a type declaration (struct, class, union or enum) so we can use tag345 // name lookup.346 //347 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for348 // the component name of the type-name or simple-template-id is type-only.349 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;350 LookupResult Result(*this, &II, NameLoc, Kind);351 if (LookupCtx) {352 // Perform "qualified" name lookup into the declaration context we353 // computed, which is either the type of the base of a member access354 // expression or the declaration context associated with a prior355 // nested-name-specifier.356 LookupQualifiedName(Result, LookupCtx);357 358 if (ObjectTypePtr && Result.empty()) {359 // C++ [basic.lookup.classref]p3:360 // If the unqualified-id is ~type-name, the type-name is looked up361 // in the context of the entire postfix-expression. If the type T of362 // the object expression is of a class type C, the type-name is also363 // looked up in the scope of class C. At least one of the lookups shall364 // find a name that refers to (possibly cv-qualified) T.365 LookupName(Result, S);366 }367 } else {368 // Perform unqualified name lookup.369 LookupName(Result, S);370 371 // For unqualified lookup in a class template in MSVC mode, look into372 // dependent base classes where the primary class template is known.373 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {374 if (ParsedType TypeInBase =375 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))376 return TypeInBase;377 }378 }379 380 NamedDecl *IIDecl = nullptr;381 UsingShadowDecl *FoundUsingShadow = nullptr;382 switch (Result.getResultKind()) {383 case LookupResultKind::NotFound:384 if (CorrectedII) {385 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,386 AllowDeducedTemplate);387 TypoCorrection Correction =388 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,389 CorrectTypoKind::ErrorRecovery);390 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();391 TemplateTy Template;392 bool MemberOfUnknownSpecialization;393 UnqualifiedId TemplateName;394 TemplateName.setIdentifier(NewII, NameLoc);395 NestedNameSpecifier NNS = Correction.getCorrectionSpecifier();396 CXXScopeSpec NewSS, *NewSSPtr = SS;397 if (SS && NNS) {398 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));399 NewSSPtr = &NewSS;400 }401 if (Correction && (NNS || NewII != &II) &&402 // Ignore a correction to a template type as the to-be-corrected403 // identifier is not a template (typo correction for template names404 // is handled elsewhere).405 !(getLangOpts().CPlusPlus && NewSSPtr &&406 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,407 Template, MemberOfUnknownSpecialization))) {408 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,409 isClassName, HasTrailingDot, ObjectTypePtr,410 IsCtorOrDtorName,411 WantNontrivialTypeSourceInfo,412 IsClassTemplateDeductionContext);413 if (Ty) {414 diagnoseTypo(Correction,415 PDiag(diag::err_unknown_type_or_class_name_suggest)416 << Result.getLookupName() << isClassName);417 if (SS && NNS)418 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));419 *CorrectedII = NewII;420 return Ty;421 }422 }423 }424 Result.suppressDiagnostics();425 return nullptr;426 case LookupResultKind::NotFoundInCurrentInstantiation:427 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {428 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,429 SS->getScopeRep(), &II);430 TypeLocBuilder TLB;431 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);432 TL.setElaboratedKeywordLoc(SourceLocation());433 TL.setQualifierLoc(SS->getWithLocInContext(Context));434 TL.setNameLoc(NameLoc);435 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));436 }437 [[fallthrough]];438 case LookupResultKind::FoundOverloaded:439 case LookupResultKind::FoundUnresolvedValue:440 Result.suppressDiagnostics();441 return nullptr;442 443 case LookupResultKind::Ambiguous:444 // Recover from type-hiding ambiguities by hiding the type. We'll445 // do the lookup again when looking for an object, and we can446 // diagnose the error then. If we don't do this, then the error447 // about hiding the type will be immediately followed by an error448 // that only makes sense if the identifier was treated like a type.449 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {450 Result.suppressDiagnostics();451 return nullptr;452 }453 454 // Look to see if we have a type anywhere in the list of results.455 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();456 Res != ResEnd; ++Res) {457 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();458 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(459 RealRes) ||460 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {461 if (!IIDecl ||462 // Make the selection of the recovery decl deterministic.463 RealRes->getLocation() < IIDecl->getLocation()) {464 IIDecl = RealRes;465 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);466 }467 }468 }469 470 if (!IIDecl) {471 // None of the entities we found is a type, so there is no way472 // to even assume that the result is a type. In this case, don't473 // complain about the ambiguity. The parser will either try to474 // perform this lookup again (e.g., as an object name), which475 // will produce the ambiguity, or will complain that it expected476 // a type name.477 Result.suppressDiagnostics();478 return nullptr;479 }480 481 // We found a type within the ambiguous lookup; diagnose the482 // ambiguity and then return that type. This might be the right483 // answer, or it might not be, but it suppresses any attempt to484 // perform the name lookup again.485 break;486 487 case LookupResultKind::Found:488 IIDecl = Result.getFoundDecl();489 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());490 break;491 }492 493 assert(IIDecl && "Didn't find decl");494 495 TypeLocBuilder TLB;496 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {497 checkTypeDeclType(LookupCtx,498 IsImplicitTypename ? DiagCtorKind::Implicit499 : DiagCtorKind::None,500 TD, NameLoc);501 QualType T;502 if (FoundUsingShadow) {503 T = Context.getUsingType(ElaboratedTypeKeyword::None,504 SS ? SS->getScopeRep() : std::nullopt,505 FoundUsingShadow);506 if (!WantNontrivialTypeSourceInfo)507 return ParsedType::make(T);508 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),509 SS ? SS->getWithLocInContext(Context)510 : NestedNameSpecifierLoc(),511 NameLoc);512 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {513 T = Context.getTagType(ElaboratedTypeKeyword::None,514 SS ? SS->getScopeRep() : std::nullopt, Tag,515 /*OwnsTag=*/false);516 if (!WantNontrivialTypeSourceInfo)517 return ParsedType::make(T);518 auto TL = TLB.push<TagTypeLoc>(T);519 TL.setElaboratedKeywordLoc(SourceLocation());520 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)521 : NestedNameSpecifierLoc());522 TL.setNameLoc(NameLoc);523 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);524 TN && !isa<ObjCTypeParamDecl>(TN)) {525 T = Context.getTypedefType(ElaboratedTypeKeyword::None,526 SS ? SS->getScopeRep() : std::nullopt, TN);527 if (!WantNontrivialTypeSourceInfo)528 return ParsedType::make(T);529 TLB.push<TypedefTypeLoc>(T).set(530 /*ElaboratedKeywordLoc=*/SourceLocation(),531 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),532 NameLoc);533 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {534 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,535 SS ? SS->getScopeRep() : std::nullopt,536 UD);537 if (!WantNontrivialTypeSourceInfo)538 return ParsedType::make(T);539 TLB.push<UnresolvedUsingTypeLoc>(T).set(540 /*ElaboratedKeywordLoc=*/SourceLocation(),541 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),542 NameLoc);543 } else {544 T = Context.getTypeDeclType(TD);545 if (!WantNontrivialTypeSourceInfo)546 return ParsedType::make(T);547 if (isa<ObjCTypeParamType>(T))548 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);549 else550 TLB.pushTypeSpec(T).setNameLoc(NameLoc);551 }552 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));553 }554 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {555 (void)DiagnoseUseOfDecl(IDecl, NameLoc);556 if (!HasTrailingDot) {557 // FIXME: Support UsingType for this case.558 QualType T = Context.getObjCInterfaceType(IDecl);559 if (!WantNontrivialTypeSourceInfo)560 return ParsedType::make(T);561 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);562 TL.setNameLoc(NameLoc);563 // FIXME: Pass in this source location.564 TL.setNameEndLoc(NameLoc);565 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));566 }567 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {568 (void)DiagnoseUseOfDecl(UD, NameLoc);569 // Recover with 'int'570 return ParsedType::make(Context.IntTy);571 } else if (AllowDeducedTemplate) {572 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {573 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);574 // FIXME: Support UsingType here.575 TemplateName Template = Context.getQualifiedTemplateName(576 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,577 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));578 QualType T = Context.getDeducedTemplateSpecializationType(579 ElaboratedTypeKeyword::None, Template, QualType(), false);580 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);581 TL.setElaboratedKeywordLoc(SourceLocation());582 TL.setNameLoc(NameLoc);583 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)584 : NestedNameSpecifierLoc());585 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));586 }587 }588 589 // As it's not plausibly a type, suppress diagnostics.590 Result.suppressDiagnostics();591 return nullptr;592}593 594// Builds a fake NNS for the given decl context.595static NestedNameSpecifier596synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {597 for (;; DC = DC->getLookupParent()) {598 DC = DC->getPrimaryContext();599 auto *ND = dyn_cast<NamespaceDecl>(DC);600 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())601 return NestedNameSpecifier(Context, ND, std::nullopt);602 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))603 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());604 if (isa<TranslationUnitDecl>(DC))605 return NestedNameSpecifier::getGlobal();606 }607 llvm_unreachable("something isn't in TU scope?");608}609 610/// Find the parent class with dependent bases of the innermost enclosing method611/// context. Do not look for enclosing CXXRecordDecls directly, or we will end612/// up allowing unqualified dependent type names at class-level, which MSVC613/// correctly rejects.614static const CXXRecordDecl *615findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {616 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {617 DC = DC->getPrimaryContext();618 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))619 if (MD->getParent()->hasAnyDependentBases())620 return MD->getParent();621 }622 return nullptr;623}624 625ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,626 SourceLocation NameLoc,627 bool IsTemplateTypeArg) {628 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");629 630 NestedNameSpecifier NNS = std::nullopt;631 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {632 // If we weren't able to parse a default template argument, delay lookup633 // until instantiation time by making a non-dependent DependentTypeName. We634 // pretend we saw a NestedNameSpecifier referring to the current scope, and635 // lookup is retried.636 // FIXME: This hurts our diagnostic quality, since we get errors like "no637 // type named 'Foo' in 'current_namespace'" when the user didn't write any638 // name specifiers.639 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);640 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;641 } else if (const CXXRecordDecl *RD =642 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {643 // Build a DependentNameType that will perform lookup into RD at644 // instantiation time.645 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());646 647 // Diagnose that this identifier was undeclared, and retry the lookup during648 // template instantiation.649 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II650 << RD;651 } else {652 // This is not a situation that we should recover from.653 return ParsedType();654 }655 656 QualType T =657 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);658 659 // Build type location information. We synthesized the qualifier, so we have660 // to build a fake NestedNameSpecifierLoc.661 NestedNameSpecifierLocBuilder NNSLocBuilder;662 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));663 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);664 665 TypeLocBuilder Builder;666 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);667 DepTL.setNameLoc(NameLoc);668 DepTL.setElaboratedKeywordLoc(SourceLocation());669 DepTL.setQualifierLoc(QualifierLoc);670 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));671}672 673DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {674 // Do a tag name lookup in this scope.675 LookupResult R(*this, &II, SourceLocation(), LookupTagName);676 LookupName(R, S, false);677 R.suppressDiagnostics();678 if (R.getResultKind() == LookupResultKind::Found)679 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {680 switch (TD->getTagKind()) {681 case TagTypeKind::Struct:682 return DeclSpec::TST_struct;683 case TagTypeKind::Interface:684 return DeclSpec::TST_interface;685 case TagTypeKind::Union:686 return DeclSpec::TST_union;687 case TagTypeKind::Class:688 return DeclSpec::TST_class;689 case TagTypeKind::Enum:690 return DeclSpec::TST_enum;691 }692 }693 694 return DeclSpec::TST_unspecified;695}696 697bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {698 if (!CurContext->isRecord())699 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();700 701 switch (SS->getScopeRep().getKind()) {702 case NestedNameSpecifier::Kind::MicrosoftSuper:703 return true;704 case NestedNameSpecifier::Kind::Type: {705 QualType T(SS->getScopeRep().getAsType(), 0);706 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())707 if (Context.hasSameUnqualifiedType(T, Base.getType()))708 return true;709 [[fallthrough]];710 }711 default:712 return S->isFunctionPrototypeScope();713 }714}715 716void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,717 SourceLocation IILoc,718 Scope *S,719 CXXScopeSpec *SS,720 ParsedType &SuggestedType,721 bool IsTemplateName) {722 // Don't report typename errors for editor placeholders.723 if (II->isEditorPlaceholder())724 return;725 // We don't have anything to suggest (yet).726 SuggestedType = nullptr;727 728 // There may have been a typo in the name of the type. Look up typo729 // results, in case we have something that we can suggest.730 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,731 /*AllowTemplates=*/IsTemplateName,732 /*AllowNonTemplates=*/!IsTemplateName);733 if (TypoCorrection Corrected =734 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,735 CCC, CorrectTypoKind::ErrorRecovery)) {736 // FIXME: Support error recovery for the template-name case.737 bool CanRecover = !IsTemplateName;738 if (Corrected.isKeyword()) {739 // We corrected to a keyword.740 diagnoseTypo(Corrected,741 PDiag(IsTemplateName ? diag::err_no_template_suggest742 : diag::err_unknown_typename_suggest)743 << II);744 II = Corrected.getCorrectionAsIdentifierInfo();745 } else {746 // We found a similarly-named type or interface; suggest that.747 if (!SS || !SS->isSet()) {748 diagnoseTypo(Corrected,749 PDiag(IsTemplateName ? diag::err_no_template_suggest750 : diag::err_unknown_typename_suggest)751 << II, CanRecover);752 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {753 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));754 bool DroppedSpecifier =755 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;756 diagnoseTypo(Corrected,757 PDiag(IsTemplateName758 ? diag::err_no_member_template_suggest759 : diag::err_unknown_nested_typename_suggest)760 << II << DC << DroppedSpecifier << SS->getRange(),761 CanRecover);762 } else {763 llvm_unreachable("could not have corrected a typo here");764 }765 766 if (!CanRecover)767 return;768 769 CXXScopeSpec tmpSS;770 if (Corrected.getCorrectionSpecifier())771 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),772 SourceRange(IILoc));773 // FIXME: Support class template argument deduction here.774 SuggestedType =775 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,776 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,777 /*IsCtorOrDtorName=*/false,778 /*WantNontrivialTypeSourceInfo=*/true);779 }780 return;781 }782 783 if (getLangOpts().CPlusPlus && !IsTemplateName) {784 // See if II is a class template that the user forgot to pass arguments to.785 UnqualifiedId Name;786 Name.setIdentifier(II, IILoc);787 CXXScopeSpec EmptySS;788 TemplateTy TemplateResult;789 bool MemberOfUnknownSpecialization;790 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,791 Name, nullptr, true, TemplateResult,792 MemberOfUnknownSpecialization) == TNK_Type_template) {793 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);794 return;795 }796 }797 798 // FIXME: Should we move the logic that tries to recover from a missing tag799 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?800 801 if (!SS || (!SS->isSet() && !SS->isInvalid()))802 Diag(IILoc, IsTemplateName ? diag::err_no_template803 : diag::err_unknown_typename)804 << II;805 else if (DeclContext *DC = computeDeclContext(*SS, false))806 Diag(IILoc, IsTemplateName ? diag::err_no_member_template807 : diag::err_typename_nested_not_found)808 << II << DC << SS->getRange();809 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {810 SuggestedType =811 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();812 } else if (isDependentScopeSpecifier(*SS)) {813 unsigned DiagID = diag::err_typename_missing;814 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))815 DiagID = diag::ext_typename_missing;816 817 SuggestedType =818 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();819 820 Diag(SS->getRange().getBegin(), DiagID)821 << GetTypeFromParser(SuggestedType)822 << SourceRange(SS->getRange().getBegin(), IILoc)823 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");824 } else {825 assert(SS && SS->isInvalid() &&826 "Invalid scope specifier has already been diagnosed");827 }828}829 830/// Determine whether the given result set contains either a type name831/// or832static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {833 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&834 NextToken.is(tok::less);835 836 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {837 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))838 return true;839 840 if (CheckTemplate && isa<TemplateDecl>(*I))841 return true;842 }843 844 return false;845}846 847static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,848 Scope *S, CXXScopeSpec &SS,849 IdentifierInfo *&Name,850 SourceLocation NameLoc) {851 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);852 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());853 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {854 StringRef FixItTagName;855 switch (Tag->getTagKind()) {856 case TagTypeKind::Class:857 FixItTagName = "class ";858 break;859 860 case TagTypeKind::Enum:861 FixItTagName = "enum ";862 break;863 864 case TagTypeKind::Struct:865 FixItTagName = "struct ";866 break;867 868 case TagTypeKind::Interface:869 FixItTagName = "__interface ";870 break;871 872 case TagTypeKind::Union:873 FixItTagName = "union ";874 break;875 }876 877 StringRef TagName = FixItTagName.drop_back();878 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)879 << Name << TagName << SemaRef.getLangOpts().CPlusPlus880 << FixItHint::CreateInsertion(NameLoc, FixItTagName);881 882 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();883 I != IEnd; ++I)884 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)885 << Name << TagName;886 887 // Replace lookup results with just the tag decl.888 Result.clear(Sema::LookupTagName);889 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());890 return true;891 }892 893 return false;894}895 896Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,897 IdentifierInfo *&Name,898 SourceLocation NameLoc,899 const Token &NextToken,900 CorrectionCandidateCallback *CCC) {901 DeclarationNameInfo NameInfo(Name, NameLoc);902 ObjCMethodDecl *CurMethod = getCurMethodDecl();903 904 assert(NextToken.isNot(tok::coloncolon) &&905 "parse nested name specifiers before calling ClassifyName");906 if (getLangOpts().CPlusPlus && SS.isSet() &&907 isCurrentClassName(*Name, S, &SS)) {908 // Per [class.qual]p2, this names the constructors of SS, not the909 // injected-class-name. We don't have a classification for that.910 // There's not much point caching this result, since the parser911 // will reject it later.912 return NameClassification::Unknown();913 }914 915 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);916 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),917 /*AllowBuiltinCreation=*/!CurMethod);918 919 if (SS.isInvalid())920 return NameClassification::Error();921 922 // For unqualified lookup in a class template in MSVC mode, look into923 // dependent base classes where the primary class template is known.924 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {925 if (ParsedType TypeInBase =926 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))927 return TypeInBase;928 }929 930 // Perform lookup for Objective-C instance variables (including automatically931 // synthesized instance variables), if we're in an Objective-C method.932 // FIXME: This lookup really, really needs to be folded in to the normal933 // unqualified lookup mechanism.934 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {935 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);936 if (Ivar.isInvalid())937 return NameClassification::Error();938 if (Ivar.isUsable())939 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));940 941 // We defer builtin creation until after ivar lookup inside ObjC methods.942 if (Result.empty())943 LookupBuiltin(Result);944 }945 946 bool SecondTry = false;947 bool IsFilteredTemplateName = false;948 949Corrected:950 switch (Result.getResultKind()) {951 case LookupResultKind::NotFound:952 // If an unqualified-id is followed by a '(', then we have a function953 // call.954 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {955 // In C++, this is an ADL-only call.956 // FIXME: Reference?957 if (getLangOpts().CPlusPlus)958 return NameClassification::UndeclaredNonType();959 960 // C90 6.3.2.2:961 // If the expression that precedes the parenthesized argument list in a962 // function call consists solely of an identifier, and if no963 // declaration is visible for this identifier, the identifier is964 // implicitly declared exactly as if, in the innermost block containing965 // the function call, the declaration966 //967 // extern int identifier ();968 //969 // appeared.970 //971 // We also allow this in C99 as an extension. However, this is not972 // allowed in all language modes as functions without prototypes may not973 // be supported.974 if (getLangOpts().implicitFunctionsAllowed()) {975 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))976 return NameClassification::NonType(D);977 }978 }979 980 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {981 // In C++20 onwards, this could be an ADL-only call to a function982 // template, and we're required to assume that this is a template name.983 //984 // FIXME: Find a way to still do typo correction in this case.985 TemplateName Template =986 Context.getAssumedTemplateName(NameInfo.getName());987 return NameClassification::UndeclaredTemplate(Template);988 }989 990 // In C, we first see whether there is a tag type by the same name, in991 // which case it's likely that the user just forgot to write "enum",992 // "struct", or "union".993 if (!getLangOpts().CPlusPlus && !SecondTry &&994 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {995 break;996 }997 998 // Perform typo correction to determine if there is another name that is999 // close to this name.1000 if (!SecondTry && CCC) {1001 SecondTry = true;1002 if (TypoCorrection Corrected =1003 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,1004 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {1005 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;1006 unsigned QualifiedDiag = diag::err_no_member_suggest;1007 1008 NamedDecl *FirstDecl = Corrected.getFoundDecl();1009 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();1010 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&1011 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {1012 UnqualifiedDiag = diag::err_no_template_suggest;1013 QualifiedDiag = diag::err_no_member_template_suggest;1014 } else if (UnderlyingFirstDecl &&1015 (isa<TypeDecl>(UnderlyingFirstDecl) ||1016 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||1017 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {1018 UnqualifiedDiag = diag::err_unknown_typename_suggest;1019 QualifiedDiag = diag::err_unknown_nested_typename_suggest;1020 }1021 1022 if (SS.isEmpty()) {1023 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);1024 } else {// FIXME: is this even reachable? Test it.1025 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));1026 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&1027 Name->getName() == CorrectedStr;1028 diagnoseTypo(Corrected, PDiag(QualifiedDiag)1029 << Name << computeDeclContext(SS, false)1030 << DroppedSpecifier << SS.getRange());1031 }1032 1033 // Update the name, so that the caller has the new name.1034 Name = Corrected.getCorrectionAsIdentifierInfo();1035 1036 // Typo correction corrected to a keyword.1037 if (Corrected.isKeyword())1038 return Name;1039 1040 // Also update the LookupResult...1041 // FIXME: This should probably go away at some point1042 Result.clear();1043 Result.setLookupName(Corrected.getCorrection());1044 if (FirstDecl)1045 Result.addDecl(FirstDecl);1046 1047 // If we found an Objective-C instance variable, let1048 // LookupInObjCMethod build the appropriate expression to1049 // reference the ivar.1050 // FIXME: This is a gross hack.1051 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {1052 DeclResult R =1053 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());1054 if (R.isInvalid())1055 return NameClassification::Error();1056 if (R.isUsable())1057 return NameClassification::NonType(Ivar);1058 }1059 1060 goto Corrected;1061 }1062 }1063 1064 // We failed to correct; just fall through and let the parser deal with it.1065 Result.suppressDiagnostics();1066 return NameClassification::Unknown();1067 1068 case LookupResultKind::NotFoundInCurrentInstantiation: {1069 // We performed name lookup into the current instantiation, and there were1070 // dependent bases, so we treat this result the same way as any other1071 // dependent nested-name-specifier.1072 1073 // C++ [temp.res]p2:1074 // A name used in a template declaration or definition and that is1075 // dependent on a template-parameter is assumed not to name a type1076 // unless the applicable name lookup finds a type name or the name is1077 // qualified by the keyword typename.1078 //1079 // FIXME: If the next token is '<', we might want to ask the parser to1080 // perform some heroics to see if we actually have a1081 // template-argument-list, which would indicate a missing 'template'1082 // keyword here.1083 return NameClassification::DependentNonType();1084 }1085 1086 case LookupResultKind::Found:1087 case LookupResultKind::FoundOverloaded:1088 case LookupResultKind::FoundUnresolvedValue:1089 break;1090 1091 case LookupResultKind::Ambiguous:1092 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&1093 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,1094 /*AllowDependent=*/false)) {1095 // C++ [temp.local]p3:1096 // A lookup that finds an injected-class-name (10.2) can result in an1097 // ambiguity in certain cases (for example, if it is found in more than1098 // one base class). If all of the injected-class-names that are found1099 // refer to specializations of the same class template, and if the name1100 // is followed by a template-argument-list, the reference refers to the1101 // class template itself and not a specialization thereof, and is not1102 // ambiguous.1103 //1104 // This filtering can make an ambiguous result into an unambiguous one,1105 // so try again after filtering out template names.1106 FilterAcceptableTemplateNames(Result);1107 if (!Result.isAmbiguous()) {1108 IsFilteredTemplateName = true;1109 break;1110 }1111 }1112 1113 // Diagnose the ambiguity and return an error.1114 return NameClassification::Error();1115 }1116 1117 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&1118 (IsFilteredTemplateName ||1119 hasAnyAcceptableTemplateNames(1120 Result, /*AllowFunctionTemplates=*/true,1121 /*AllowDependent=*/false,1122 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&1123 getLangOpts().CPlusPlus20))) {1124 // C++ [temp.names]p3:1125 // After name lookup (3.4) finds that a name is a template-name or that1126 // an operator-function-id or a literal- operator-id refers to a set of1127 // overloaded functions any member of which is a function template if1128 // this is followed by a <, the < is always taken as the delimiter of a1129 // template-argument-list and never as the less-than operator.1130 // C++2a [temp.names]p2:1131 // A name is also considered to refer to a template if it is an1132 // unqualified-id followed by a < and name lookup finds either one1133 // or more functions or finds nothing.1134 if (!IsFilteredTemplateName)1135 FilterAcceptableTemplateNames(Result);1136 1137 bool IsFunctionTemplate;1138 bool IsVarTemplate;1139 TemplateName Template;1140 if (Result.end() - Result.begin() > 1) {1141 IsFunctionTemplate = true;1142 Template = Context.getOverloadedTemplateName(Result.begin(),1143 Result.end());1144 } else if (!Result.empty()) {1145 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(1146 *Result.begin(), /*AllowFunctionTemplates=*/true,1147 /*AllowDependent=*/false));1148 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);1149 IsVarTemplate = isa<VarTemplateDecl>(TD);1150 1151 UsingShadowDecl *FoundUsingShadow =1152 dyn_cast<UsingShadowDecl>(*Result.begin());1153 assert(!FoundUsingShadow ||1154 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));1155 Template = Context.getQualifiedTemplateName(1156 SS.getScopeRep(),1157 /*TemplateKeyword=*/false,1158 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));1159 } else {1160 // All results were non-template functions. This is a function template1161 // name.1162 IsFunctionTemplate = true;1163 Template = Context.getAssumedTemplateName(NameInfo.getName());1164 }1165 1166 if (IsFunctionTemplate) {1167 // Function templates always go through overload resolution, at which1168 // point we'll perform the various checks (e.g., accessibility) we need1169 // to based on which function we selected.1170 Result.suppressDiagnostics();1171 1172 return NameClassification::FunctionTemplate(Template);1173 }1174 1175 return IsVarTemplate ? NameClassification::VarTemplate(Template)1176 : NameClassification::TypeTemplate(Template);1177 }1178 1179 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {1180 QualType T;1181 TypeLocBuilder TLB;1182 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {1183 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),1184 USD);1185 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),1186 SS.getWithLocInContext(Context), NameLoc);1187 } else {1188 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),1189 Type);1190 if (isa<TagType>(T)) {1191 auto TTL = TLB.push<TagTypeLoc>(T);1192 TTL.setElaboratedKeywordLoc(SourceLocation());1193 TTL.setQualifierLoc(SS.getWithLocInContext(Context));1194 TTL.setNameLoc(NameLoc);1195 } else if (isa<TypedefType>(T)) {1196 TLB.push<TypedefTypeLoc>(T).set(1197 /*ElaboratedKeywordLoc=*/SourceLocation(),1198 SS.getWithLocInContext(Context), NameLoc);1199 } else if (isa<UnresolvedUsingType>(T)) {1200 TLB.push<UnresolvedUsingTypeLoc>(T).set(1201 /*ElaboratedKeywordLoc=*/SourceLocation(),1202 SS.getWithLocInContext(Context), NameLoc);1203 } else {1204 TLB.pushTypeSpec(T).setNameLoc(NameLoc);1205 }1206 }1207 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));1208 };1209 1210 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();1211 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {1212 DiagnoseUseOfDecl(Type, NameLoc);1213 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);1214 return BuildTypeFor(Type, *Result.begin());1215 }1216 1217 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);1218 if (!Class) {1219 // FIXME: It's unfortunate that we don't have a Type node for handling this.1220 if (ObjCCompatibleAliasDecl *Alias =1221 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))1222 Class = Alias->getClassInterface();1223 }1224 1225 if (Class) {1226 DiagnoseUseOfDecl(Class, NameLoc);1227 1228 if (NextToken.is(tok::period)) {1229 // Interface. <something> is parsed as a property reference expression.1230 // Just return "unknown" as a fall-through for now.1231 Result.suppressDiagnostics();1232 return NameClassification::Unknown();1233 }1234 1235 QualType T = Context.getObjCInterfaceType(Class);1236 return ParsedType::make(T);1237 }1238 1239 if (isa<ConceptDecl>(FirstDecl)) {1240 // We want to preserve the UsingShadowDecl for concepts.1241 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))1242 return NameClassification::Concept(TemplateName(USD));1243 return NameClassification::Concept(1244 TemplateName(cast<TemplateDecl>(FirstDecl)));1245 }1246 1247 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {1248 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);1249 return NameClassification::Error();1250 }1251 1252 // We can have a type template here if we're classifying a template argument.1253 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&1254 !isa<VarTemplateDecl>(FirstDecl))1255 return NameClassification::TypeTemplate(1256 TemplateName(cast<TemplateDecl>(FirstDecl)));1257 1258 // Check for a tag type hidden by a non-type decl in a few cases where it1259 // seems likely a type is wanted instead of the non-type that was found.1260 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);1261 if ((NextToken.is(tok::identifier) ||1262 (NextIsOp &&1263 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&1264 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {1265 TypeDecl *Type = Result.getAsSingle<TypeDecl>();1266 DiagnoseUseOfDecl(Type, NameLoc);1267 return BuildTypeFor(Type, *Result.begin());1268 }1269 1270 // If we already know which single declaration is referenced, just annotate1271 // that declaration directly. Defer resolving even non-overloaded class1272 // member accesses, as we need to defer certain access checks until we know1273 // the context.1274 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));1275 if (Result.isSingleResult() && !ADL &&1276 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))1277 return NameClassification::NonType(Result.getRepresentativeDecl());1278 1279 // Otherwise, this is an overload set that we will need to resolve later.1280 Result.suppressDiagnostics();1281 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(1282 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),1283 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),1284 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));1285}1286 1287ExprResult1288Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,1289 SourceLocation NameLoc) {1290 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");1291 CXXScopeSpec SS;1292 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);1293 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);1294}1295 1296ExprResult1297Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,1298 IdentifierInfo *Name,1299 SourceLocation NameLoc,1300 bool IsAddressOfOperand) {1301 DeclarationNameInfo NameInfo(Name, NameLoc);1302 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),1303 NameInfo, IsAddressOfOperand,1304 /*TemplateArgs=*/nullptr);1305}1306 1307ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,1308 NamedDecl *Found,1309 SourceLocation NameLoc,1310 const Token &NextToken) {1311 if (getCurMethodDecl() && SS.isEmpty())1312 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))1313 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);1314 1315 // Reconstruct the lookup result.1316 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);1317 Result.addDecl(Found);1318 Result.resolveKind();1319 1320 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));1321 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);1322}1323 1324ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {1325 // For an implicit class member access, transform the result into a member1326 // access expression if necessary.1327 auto *ULE = cast<UnresolvedLookupExpr>(E);1328 if ((*ULE->decls_begin())->isCXXClassMember()) {1329 CXXScopeSpec SS;1330 SS.Adopt(ULE->getQualifierLoc());1331 1332 // Reconstruct the lookup result.1333 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),1334 LookupOrdinaryName);1335 Result.setNamingClass(ULE->getNamingClass());1336 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)1337 Result.addDecl(*I, I.getAccess());1338 Result.resolveKind();1339 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,1340 nullptr, S);1341 }1342 1343 // Otherwise, this is already in the form we needed, and no further checks1344 // are necessary.1345 return ULE;1346}1347 1348Sema::TemplateNameKindForDiagnostics1349Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {1350 auto *TD = Name.getAsTemplateDecl();1351 if (!TD)1352 return TemplateNameKindForDiagnostics::DependentTemplate;1353 if (isa<ClassTemplateDecl>(TD))1354 return TemplateNameKindForDiagnostics::ClassTemplate;1355 if (isa<FunctionTemplateDecl>(TD))1356 return TemplateNameKindForDiagnostics::FunctionTemplate;1357 if (isa<VarTemplateDecl>(TD))1358 return TemplateNameKindForDiagnostics::VarTemplate;1359 if (isa<TypeAliasTemplateDecl>(TD))1360 return TemplateNameKindForDiagnostics::AliasTemplate;1361 if (isa<TemplateTemplateParmDecl>(TD))1362 return TemplateNameKindForDiagnostics::TemplateTemplateParam;1363 if (isa<ConceptDecl>(TD))1364 return TemplateNameKindForDiagnostics::Concept;1365 return TemplateNameKindForDiagnostics::DependentTemplate;1366}1367 1368void Sema::PushDeclContext(Scope *S, DeclContext *DC) {1369 assert(DC->getLexicalParent() == CurContext &&1370 "The next DeclContext should be lexically contained in the current one.");1371 CurContext = DC;1372 S->setEntity(DC);1373}1374 1375void Sema::PopDeclContext() {1376 assert(CurContext && "DeclContext imbalance!");1377 1378 CurContext = CurContext->getLexicalParent();1379 assert(CurContext && "Popped translation unit!");1380}1381 1382Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,1383 Decl *D) {1384 // Unlike PushDeclContext, the context to which we return is not necessarily1385 // the containing DC of TD, because the new context will be some pre-existing1386 // TagDecl definition instead of a fresh one.1387 auto Result = static_cast<SkippedDefinitionContext>(CurContext);1388 CurContext = cast<TagDecl>(D)->getDefinition();1389 assert(CurContext && "skipping definition of undefined tag");1390 // Start lookups from the parent of the current context; we don't want to look1391 // into the pre-existing complete definition.1392 S->setEntity(CurContext->getLookupParent());1393 return Result;1394}1395 1396void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {1397 CurContext = static_cast<decltype(CurContext)>(Context);1398}1399 1400void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {1401 // C++0x [basic.lookup.unqual]p13:1402 // A name used in the definition of a static data member of class1403 // X (after the qualified-id of the static member) is looked up as1404 // if the name was used in a member function of X.1405 // C++0x [basic.lookup.unqual]p14:1406 // If a variable member of a namespace is defined outside of the1407 // scope of its namespace then any name used in the definition of1408 // the variable member (after the declarator-id) is looked up as1409 // if the definition of the variable member occurred in its1410 // namespace.1411 // Both of these imply that we should push a scope whose context1412 // is the semantic context of the declaration. We can't use1413 // PushDeclContext here because that context is not necessarily1414 // lexically contained in the current context. Fortunately,1415 // the containing scope should have the appropriate information.1416 1417 assert(!S->getEntity() && "scope already has entity");1418 1419#ifndef NDEBUG1420 Scope *Ancestor = S->getParent();1421 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();1422 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");1423#endif1424 1425 CurContext = DC;1426 S->setEntity(DC);1427 1428 if (S->getParent()->isTemplateParamScope()) {1429 // Also set the corresponding entities for all immediately-enclosing1430 // template parameter scopes.1431 EnterTemplatedContext(S->getParent(), DC);1432 }1433}1434 1435void Sema::ExitDeclaratorContext(Scope *S) {1436 assert(S->getEntity() == CurContext && "Context imbalance!");1437 1438 // Switch back to the lexical context. The safety of this is1439 // enforced by an assert in EnterDeclaratorContext.1440 Scope *Ancestor = S->getParent();1441 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();1442 CurContext = Ancestor->getEntity();1443 1444 // We don't need to do anything with the scope, which is going to1445 // disappear.1446}1447 1448void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {1449 assert(S->isTemplateParamScope() &&1450 "expected to be initializing a template parameter scope");1451 1452 // C++20 [temp.local]p7:1453 // In the definition of a member of a class template that appears outside1454 // of the class template definition, the name of a member of the class1455 // template hides the name of a template-parameter of any enclosing class1456 // templates (but not a template-parameter of the member if the member is a1457 // class or function template).1458 // C++20 [temp.local]p9:1459 // In the definition of a class template or in the definition of a member1460 // of such a template that appears outside of the template definition, for1461 // each non-dependent base class (13.8.2.1), if the name of the base class1462 // or the name of a member of the base class is the same as the name of a1463 // template-parameter, the base class name or member name hides the1464 // template-parameter name (6.4.10).1465 //1466 // This means that a template parameter scope should be searched immediately1467 // after searching the DeclContext for which it is a template parameter1468 // scope. For example, for1469 // template<typename T> template<typename U> template<typename V>1470 // void N::A<T>::B<U>::f(...)1471 // we search V then B<U> (and base classes) then U then A<T> (and base1472 // classes) then T then N then ::.1473 unsigned ScopeDepth = getTemplateDepth(S);1474 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {1475 DeclContext *SearchDCAfterScope = DC;1476 for (; DC; DC = DC->getLookupParent()) {1477 if (const TemplateParameterList *TPL =1478 cast<Decl>(DC)->getDescribedTemplateParams()) {1479 unsigned DCDepth = TPL->getDepth() + 1;1480 if (DCDepth > ScopeDepth)1481 continue;1482 if (ScopeDepth == DCDepth)1483 SearchDCAfterScope = DC = DC->getLookupParent();1484 break;1485 }1486 }1487 S->setLookupEntity(SearchDCAfterScope);1488 }1489}1490 1491void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {1492 // We assume that the caller has already called1493 // ActOnReenterTemplateScope so getTemplatedDecl() works.1494 FunctionDecl *FD = D->getAsFunction();1495 if (!FD)1496 return;1497 1498 // Same implementation as PushDeclContext, but enters the context1499 // from the lexical parent, rather than the top-level class.1500 assert(CurContext == FD->getLexicalParent() &&1501 "The next DeclContext should be lexically contained in the current one.");1502 CurContext = FD;1503 S->setEntity(CurContext);1504 1505 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {1506 ParmVarDecl *Param = FD->getParamDecl(P);1507 // If the parameter has an identifier, then add it to the scope1508 if (Param->getIdentifier()) {1509 S->AddDecl(Param);1510 IdResolver.AddDecl(Param);1511 }1512 }1513}1514 1515void Sema::ActOnExitFunctionContext() {1516 // Same implementation as PopDeclContext, but returns to the lexical parent,1517 // rather than the top-level class.1518 assert(CurContext && "DeclContext imbalance!");1519 CurContext = CurContext->getLexicalParent();1520 assert(CurContext && "Popped translation unit!");1521}1522 1523/// Determine whether overloading is allowed for a new function1524/// declaration considering prior declarations of the same name.1525///1526/// This routine determines whether overloading is possible, not1527/// whether a new declaration actually overloads a previous one.1528/// It will return true in C++ (where overloads are always permitted)1529/// or, as a C extension, when either the new declaration or a1530/// previous one is declared with the 'overloadable' attribute.1531static bool AllowOverloadingOfFunction(const LookupResult &Previous,1532 ASTContext &Context,1533 const FunctionDecl *New) {1534 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())1535 return true;1536 1537 // Multiversion function declarations are not overloads in the1538 // usual sense of that term, but lookup will report that an1539 // overload set was found if more than one multiversion function1540 // declaration is present for the same name. It is therefore1541 // inadequate to assume that some prior declaration(s) had1542 // the overloadable attribute; checking is required. Since one1543 // declaration is permitted to omit the attribute, it is necessary1544 // to check at least two; hence the 'any_of' check below. Note that1545 // the overloadable attribute is implicitly added to declarations1546 // that were required to have it but did not.1547 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {1548 return llvm::any_of(Previous, [](const NamedDecl *ND) {1549 return ND->hasAttr<OverloadableAttr>();1550 });1551 } else if (Previous.getResultKind() == LookupResultKind::Found)1552 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();1553 1554 return false;1555}1556 1557void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {1558 // Move up the scope chain until we find the nearest enclosing1559 // non-transparent context. The declaration will be introduced into this1560 // scope.1561 while (S->getEntity() && S->getEntity()->isTransparentContext())1562 S = S->getParent();1563 1564 // Add scoped declarations into their context, so that they can be1565 // found later. Declarations without a context won't be inserted1566 // into any context.1567 if (AddToContext)1568 CurContext->addDecl(D);1569 1570 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they1571 // are function-local declarations.1572 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())1573 return;1574 1575 // Template instantiations should also not be pushed into scope.1576 if (isa<FunctionDecl>(D) &&1577 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())1578 return;1579 1580 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {1581 S->AddDecl(D);1582 return;1583 }1584 // If this replaces anything in the current scope,1585 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),1586 IEnd = IdResolver.end();1587 for (; I != IEnd; ++I) {1588 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {1589 S->RemoveDecl(*I);1590 IdResolver.RemoveDecl(*I);1591 1592 // Should only need to replace one decl.1593 break;1594 }1595 }1596 1597 S->AddDecl(D);1598 1599 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {1600 // Implicitly-generated labels may end up getting generated in an order that1601 // isn't strictly lexical, which breaks name lookup. Be careful to insert1602 // the label at the appropriate place in the identifier chain.1603 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {1604 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();1605 if (IDC == CurContext) {1606 if (!S->isDeclScope(*I))1607 continue;1608 } else if (IDC->Encloses(CurContext))1609 break;1610 }1611 1612 IdResolver.InsertDeclAfter(I, D);1613 } else {1614 IdResolver.AddDecl(D);1615 }1616 warnOnReservedIdentifier(D);1617}1618 1619bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,1620 bool AllowInlineNamespace) const {1621 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);1622}1623 1624Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {1625 DeclContext *TargetDC = DC->getPrimaryContext();1626 do {1627 if (DeclContext *ScopeDC = S->getEntity())1628 if (ScopeDC->getPrimaryContext() == TargetDC)1629 return S;1630 } while ((S = S->getParent()));1631 1632 return nullptr;1633}1634 1635static bool isOutOfScopePreviousDeclaration(NamedDecl *,1636 DeclContext*,1637 ASTContext&);1638 1639void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,1640 bool ConsiderLinkage,1641 bool AllowInlineNamespace) {1642 LookupResult::Filter F = R.makeFilter();1643 while (F.hasNext()) {1644 NamedDecl *D = F.next();1645 1646 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))1647 continue;1648 1649 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))1650 continue;1651 1652 F.erase();1653 }1654 1655 F.done();1656}1657 1658static bool isImplicitInstantiation(NamedDecl *D) {1659 if (auto *VD = dyn_cast<VarDecl>(D))1660 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;1661 if (auto *FD = dyn_cast<FunctionDecl>(D))1662 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;1663 if (auto *RD = dyn_cast<CXXRecordDecl>(D))1664 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;1665 1666 return false;1667}1668 1669bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {1670 // [module.interface]p7:1671 // A declaration is attached to a module as follows:1672 // - If the declaration is a non-dependent friend declaration that nominates a1673 // function with a declarator-id that is a qualified-id or template-id or that1674 // nominates a class other than with an elaborated-type-specifier with neither1675 // a nested-name-specifier nor a simple-template-id, it is attached to the1676 // module to which the friend is attached ([basic.link]).1677 if (New->getFriendObjectKind() &&1678 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {1679 New->setLocalOwningModule(Old->getOwningModule());1680 makeMergedDefinitionVisible(New);1681 return false;1682 }1683 1684 // Although we have questions for the module ownership of implicit1685 // instantiations, it should be sure that we shouldn't diagnose the1686 // redeclaration of incorrect module ownership for different implicit1687 // instantiations in different modules. We will diagnose the redeclaration of1688 // incorrect module ownership for the template itself.1689 if (isImplicitInstantiation(New) || isImplicitInstantiation(Old))1690 return false;1691 1692 Module *NewM = New->getOwningModule();1693 Module *OldM = Old->getOwningModule();1694 1695 if (NewM && NewM->isPrivateModule())1696 NewM = NewM->Parent;1697 if (OldM && OldM->isPrivateModule())1698 OldM = OldM->Parent;1699 1700 if (NewM == OldM)1701 return false;1702 1703 if (NewM && OldM) {1704 // A module implementation unit has visibility of the decls in its1705 // implicitly imported interface.1706 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)1707 return false;1708 1709 // Partitions are part of the module, but a partition could import another1710 // module, so verify that the PMIs agree.1711 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&1712 getASTContext().isInSameModule(NewM, OldM))1713 return false;1714 }1715 1716 bool NewIsModuleInterface = NewM && NewM->isNamedModule();1717 bool OldIsModuleInterface = OldM && OldM->isNamedModule();1718 if (NewIsModuleInterface || OldIsModuleInterface) {1719 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:1720 // if a declaration of D [...] appears in the purview of a module, all1721 // other such declarations shall appear in the purview of the same module1722 Diag(New->getLocation(), diag::err_mismatched_owning_module)1723 << New1724 << NewIsModuleInterface1725 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")1726 << OldIsModuleInterface1727 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");1728 Diag(Old->getLocation(), diag::note_previous_declaration);1729 New->setInvalidDecl();1730 return true;1731 }1732 1733 return false;1734}1735 1736bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {1737 // [module.interface]p1:1738 // An export-declaration shall inhabit a namespace scope.1739 //1740 // So it is meaningless to talk about redeclaration which is not at namespace1741 // scope.1742 if (!New->getLexicalDeclContext()1743 ->getNonTransparentContext()1744 ->isFileContext() ||1745 !Old->getLexicalDeclContext()1746 ->getNonTransparentContext()1747 ->isFileContext())1748 return false;1749 1750 bool IsNewExported = New->isInExportDeclContext();1751 bool IsOldExported = Old->isInExportDeclContext();1752 1753 // It should be irrevelant if both of them are not exported.1754 if (!IsNewExported && !IsOldExported)1755 return false;1756 1757 if (IsOldExported)1758 return false;1759 1760 // If the Old declaration are not attached to named modules1761 // and the New declaration are attached to global module.1762 // It should be fine to allow the export since it doesn't change1763 // the linkage of declarations. See1764 // https://github.com/llvm/llvm-project/issues/98583 for details.1765 if (!Old->isInNamedModule() && New->getOwningModule() &&1766 New->getOwningModule()->isImplicitGlobalModule())1767 return false;1768 1769 assert(IsNewExported);1770 1771 auto Lk = Old->getFormalLinkage();1772 int S = 0;1773 if (Lk == Linkage::Internal)1774 S = 1;1775 else if (Lk == Linkage::Module)1776 S = 2;1777 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;1778 Diag(Old->getLocation(), diag::note_previous_declaration);1779 return true;1780}1781 1782bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {1783 if (CheckRedeclarationModuleOwnership(New, Old))1784 return true;1785 1786 if (CheckRedeclarationExported(New, Old))1787 return true;1788 1789 return false;1790}1791 1792bool Sema::IsRedefinitionInModule(const NamedDecl *New,1793 const NamedDecl *Old) const {1794 assert(getASTContext().isSameEntity(New, Old) &&1795 "New and Old are not the same definition, we should diagnostic it "1796 "immediately instead of checking it.");1797 assert(const_cast<Sema *>(this)->isReachable(New) &&1798 const_cast<Sema *>(this)->isReachable(Old) &&1799 "We shouldn't see unreachable definitions here.");1800 1801 Module *NewM = New->getOwningModule();1802 Module *OldM = Old->getOwningModule();1803 1804 // We only checks for named modules here. The header like modules is skipped.1805 // FIXME: This is not right if we import the header like modules in the module1806 // purview.1807 //1808 // For example, assuming "header.h" provides definition for `D`.1809 // ```C++1810 // //--- M.cppm1811 // export module M;1812 // import "header.h"; // or #include "header.h" but import it by clang modules1813 // actually.1814 //1815 // //--- Use.cpp1816 // import M;1817 // import "header.h"; // or uses clang modules.1818 // ```1819 //1820 // In this case, `D` has multiple definitions in multiple TU (M.cppm and1821 // Use.cpp) and `D` is attached to a named module `M`. The compiler should1822 // reject it. But the current implementation couldn't detect the case since we1823 // don't record the information about the importee modules.1824 //1825 // But this might not be painful in practice. Since the design of C++20 Named1826 // Modules suggests us to use headers in global module fragment instead of1827 // module purview.1828 if (NewM && NewM->isHeaderLikeModule())1829 NewM = nullptr;1830 if (OldM && OldM->isHeaderLikeModule())1831 OldM = nullptr;1832 1833 if (!NewM && !OldM)1834 return true;1835 1836 // [basic.def.odr]p14.31837 // Each such definition shall not be attached to a named module1838 // ([module.unit]).1839 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))1840 return true;1841 1842 // Then New and Old lives in the same TU if their share one same module unit.1843 if (NewM)1844 NewM = NewM->getTopLevelModule();1845 if (OldM)1846 OldM = OldM->getTopLevelModule();1847 return OldM == NewM;1848}1849 1850static bool isUsingDeclNotAtClassScope(NamedDecl *D) {1851 if (D->getDeclContext()->isFileContext())1852 return false;1853 1854 return isa<UsingShadowDecl>(D) ||1855 isa<UnresolvedUsingTypenameDecl>(D) ||1856 isa<UnresolvedUsingValueDecl>(D);1857}1858 1859/// Removes using shadow declarations not at class scope from the lookup1860/// results.1861static void RemoveUsingDecls(LookupResult &R) {1862 LookupResult::Filter F = R.makeFilter();1863 while (F.hasNext())1864 if (isUsingDeclNotAtClassScope(F.next()))1865 F.erase();1866 1867 F.done();1868}1869 1870/// Check for this common pattern:1871/// @code1872/// class S {1873/// S(const S&); // DO NOT IMPLEMENT1874/// void operator=(const S&); // DO NOT IMPLEMENT1875/// };1876/// @endcode1877static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {1878 // FIXME: Should check for private access too but access is set after we get1879 // the decl here.1880 if (D->doesThisDeclarationHaveABody())1881 return false;1882 1883 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))1884 return CD->isCopyConstructor();1885 return D->isCopyAssignmentOperator();1886}1887 1888bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {1889 const DeclContext *DC = D->getDeclContext();1890 while (!DC->isTranslationUnit()) {1891 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){1892 if (!RD->hasNameForLinkage())1893 return true;1894 }1895 DC = DC->getParent();1896 }1897 1898 return !D->isExternallyVisible();1899}1900 1901// FIXME: This needs to be refactored; some other isInMainFile users want1902// these semantics.1903static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {1904 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)1905 return false;1906 return S.SourceMgr.isInMainFile(Loc);1907}1908 1909bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {1910 assert(D);1911 1912 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())1913 return false;1914 1915 // Ignore all entities declared within templates, and out-of-line definitions1916 // of members of class templates.1917 if (D->getDeclContext()->isDependentContext() ||1918 D->getLexicalDeclContext()->isDependentContext())1919 return false;1920 1921 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {1922 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)1923 return false;1924 // A non-out-of-line declaration of a member specialization was implicitly1925 // instantiated; it's the out-of-line declaration that we're interested in.1926 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&1927 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())1928 return false;1929 1930 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {1931 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))1932 return false;1933 } else {1934 // 'static inline' functions are defined in headers; don't warn.1935 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))1936 return false;1937 }1938 1939 if (FD->doesThisDeclarationHaveABody() &&1940 Context.DeclMustBeEmitted(FD))1941 return false;1942 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {1943 // Constants and utility variables are defined in headers with internal1944 // linkage; don't warn. (Unlike functions, there isn't a convenient marker1945 // like "inline".)1946 if (!isMainFileLoc(*this, VD->getLocation()))1947 return false;1948 1949 if (Context.DeclMustBeEmitted(VD))1950 return false;1951 1952 if (VD->isStaticDataMember() &&1953 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)1954 return false;1955 if (VD->isStaticDataMember() &&1956 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&1957 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())1958 return false;1959 1960 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))1961 return false;1962 } else {1963 return false;1964 }1965 1966 // Only warn for unused decls internal to the translation unit.1967 // FIXME: This seems like a bogus check; it suppresses -Wunused-function1968 // for inline functions defined in the main source file, for instance.1969 return mightHaveNonExternalLinkage(D);1970}1971 1972void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {1973 if (!D)1974 return;1975 1976 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {1977 const FunctionDecl *First = FD->getFirstDecl();1978 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))1979 return; // First should already be in the vector.1980 }1981 1982 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {1983 const VarDecl *First = VD->getFirstDecl();1984 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))1985 return; // First should already be in the vector.1986 }1987 1988 if (ShouldWarnIfUnusedFileScopedDecl(D))1989 UnusedFileScopedDecls.push_back(D);1990}1991 1992static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,1993 const NamedDecl *D) {1994 if (D->isInvalidDecl())1995 return false;1996 1997 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {1998 // For a decomposition declaration, warn if none of the bindings are1999 // referenced, instead of if the variable itself is referenced (which2000 // it is, by the bindings' expressions).2001 bool IsAllIgnored = true;2002 for (const auto *BD : DD->bindings()) {2003 if (BD->isReferenced())2004 return false;2005 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||2006 BD->hasAttr<UnusedAttr>());2007 }2008 if (IsAllIgnored)2009 return false;2010 } else if (!D->getDeclName()) {2011 return false;2012 } else if (D->isReferenced() || D->isUsed()) {2013 return false;2014 }2015 2016 if (D->isPlaceholderVar(LangOpts))2017 return false;2018 2019 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||2020 D->hasAttr<CleanupAttr>())2021 return false;2022 2023 if (isa<LabelDecl>(D))2024 return true;2025 2026 // Except for labels, we only care about unused decls that are local to2027 // functions.2028 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();2029 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))2030 // For dependent types, the diagnostic is deferred.2031 WithinFunction =2032 WithinFunction || (R->isLocalClass() && !R->isDependentType());2033 if (!WithinFunction)2034 return false;2035 2036 if (isa<TypedefNameDecl>(D))2037 return true;2038 2039 // White-list anything that isn't a local variable.2040 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))2041 return false;2042 2043 // Types of valid local variables should be complete, so this should succeed.2044 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {2045 2046 const Expr *Init = VD->getInit();2047 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))2048 Init = Cleanups->getSubExpr();2049 2050 const auto *Ty = VD->getType().getTypePtr();2051 2052 // Only look at the outermost level of typedef.2053 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {2054 // Allow anything marked with __attribute__((unused)).2055 if (TT->getDecl()->hasAttr<UnusedAttr>())2056 return false;2057 }2058 2059 // Warn for reference variables whose initializtion performs lifetime2060 // extension.2061 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);2062 MTE && MTE->getExtendingDecl()) {2063 Ty = VD->getType().getNonReferenceType().getTypePtr();2064 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();2065 }2066 2067 // If we failed to complete the type for some reason, or if the type is2068 // dependent, don't diagnose the variable.2069 if (Ty->isIncompleteType() || Ty->isDependentType())2070 return false;2071 2072 // Look at the element type to ensure that the warning behaviour is2073 // consistent for both scalars and arrays.2074 Ty = Ty->getBaseElementTypeUnsafe();2075 2076 if (const TagDecl *Tag = Ty->getAsTagDecl()) {2077 if (Tag->hasAttr<UnusedAttr>())2078 return false;2079 2080 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {2081 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())2082 return false;2083 2084 if (Init) {2085 const auto *Construct =2086 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());2087 if (Construct && !Construct->isElidable()) {2088 const CXXConstructorDecl *CD = Construct->getConstructor();2089 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&2090 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))2091 return false;2092 }2093 2094 // Suppress the warning if we don't know how this is constructed, and2095 // it could possibly be non-trivial constructor.2096 if (Init->isTypeDependent()) {2097 for (const CXXConstructorDecl *Ctor : RD->ctors())2098 if (!Ctor->isTrivial())2099 return false;2100 }2101 2102 // Suppress the warning if the constructor is unresolved because2103 // its arguments are dependent.2104 if (isa<CXXUnresolvedConstructExpr>(Init))2105 return false;2106 }2107 }2108 }2109 2110 // TODO: __attribute__((unused)) templates?2111 }2112 2113 return true;2114}2115 2116static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,2117 FixItHint &Hint) {2118 if (isa<LabelDecl>(D)) {2119 SourceLocation AfterColon = Lexer::findLocationAfterToken(2120 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),2121 /*SkipTrailingWhitespaceAndNewline=*/false);2122 if (AfterColon.isInvalid())2123 return;2124 Hint = FixItHint::CreateRemoval(2125 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));2126 }2127}2128 2129void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {2130 DiagnoseUnusedNestedTypedefs(2131 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });2132}2133 2134void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,2135 DiagReceiverTy DiagReceiver) {2136 if (D->isDependentType())2137 return;2138 2139 for (auto *TmpD : D->decls()) {2140 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))2141 DiagnoseUnusedDecl(T, DiagReceiver);2142 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))2143 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);2144 }2145}2146 2147void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {2148 DiagnoseUnusedDecl(2149 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });2150}2151 2152void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {2153 if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D))2154 return;2155 2156 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {2157 // typedefs can be referenced later on, so the diagnostics are emitted2158 // at end-of-translation-unit.2159 UnusedLocalTypedefNameCandidates.insert(TD);2160 return;2161 }2162 2163 FixItHint Hint;2164 GenerateFixForUnusedDecl(D, Context, Hint);2165 2166 unsigned DiagID;2167 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())2168 DiagID = diag::warn_unused_exception_param;2169 else if (isa<LabelDecl>(D))2170 DiagID = diag::warn_unused_label;2171 else2172 DiagID = diag::warn_unused_variable;2173 2174 SourceLocation DiagLoc = D->getLocation();2175 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));2176}2177 2178void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,2179 DiagReceiverTy DiagReceiver) {2180 // If it's not referenced, it can't be set. If it has the Cleanup attribute,2181 // it's not really unused.2182 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())2183 return;2184 2185 // In C++, `_` variables behave as if they were maybe_unused2186 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))2187 return;2188 2189 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();2190 2191 if (Ty->isReferenceType() || Ty->isDependentType())2192 return;2193 2194 if (const TagDecl *Tag = Ty->getAsTagDecl()) {2195 if (Tag->hasAttr<UnusedAttr>())2196 return;2197 // In C++, don't warn for record types that don't have WarnUnusedAttr, to2198 // mimic gcc's behavior.2199 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);2200 RD && !RD->hasAttr<WarnUnusedAttr>())2201 return;2202 }2203 2204 // Don't warn about __block Objective-C pointer variables, as they might2205 // be assigned in the block but not used elsewhere for the purpose of lifetime2206 // extension.2207 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())2208 return;2209 2210 // Don't warn about Objective-C pointer variables with precise lifetime2211 // semantics; they can be used to ensure ARC releases the object at a known2212 // time, which may mean assignment but no other references.2213 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())2214 return;2215 2216 auto iter = RefsMinusAssignments.find(VD);2217 if (iter == RefsMinusAssignments.end())2218 return;2219 2220 assert(iter->getSecond() >= 0 &&2221 "Found a negative number of references to a VarDecl");2222 if (int RefCnt = iter->getSecond(); RefCnt > 0) {2223 // Assume the given VarDecl is "used" if its ref count stored in2224 // `RefMinusAssignments` is positive, with one exception.2225 //2226 // For a C++ variable whose decl (with initializer) entirely consist the2227 // condition expression of a if/while/for construct,2228 // Clang creates a DeclRefExpr for the condition expression rather than a2229 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref2230 // count stored in `RefMinusAssignment` equals 1 when the variable is never2231 // used in the body of the if/while/for construct.2232 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);2233 if (!UnusedCXXCondDecl)2234 return;2235 }2236 2237 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter2238 : diag::warn_unused_but_set_variable;2239 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);2240}2241 2242static void CheckPoppedLabel(LabelDecl *L, Sema &S,2243 Sema::DiagReceiverTy DiagReceiver) {2244 // Verify that we have no forward references left. If so, there was a goto2245 // or address of a label taken, but no definition of it. Label fwd2246 // definitions are indicated with a null substmt which is also not a resolved2247 // MS inline assembly label name.2248 bool Diagnose = false;2249 if (L->isMSAsmLabel())2250 Diagnose = !L->isResolvedMSAsmLabel();2251 else2252 Diagnose = L->getStmt() == nullptr;2253 if (Diagnose)2254 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)2255 << L);2256}2257 2258void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {2259 S->applyNRVO();2260 2261 if (S->decl_empty()) return;2262 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&2263 "Scope shouldn't contain decls!");2264 2265 /// We visit the decls in non-deterministic order, but we want diagnostics2266 /// emitted in deterministic order. Collect any diagnostic that may be emitted2267 /// and sort the diagnostics before emitting them, after we visited all decls.2268 struct LocAndDiag {2269 SourceLocation Loc;2270 std::optional<SourceLocation> PreviousDeclLoc;2271 PartialDiagnostic PD;2272 };2273 SmallVector<LocAndDiag, 16> DeclDiags;2274 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {2275 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});2276 };2277 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,2278 SourceLocation PreviousDeclLoc,2279 PartialDiagnostic PD) {2280 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});2281 };2282 2283 for (auto *TmpD : S->decls()) {2284 assert(TmpD && "This decl didn't get pushed??");2285 2286 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");2287 NamedDecl *D = cast<NamedDecl>(TmpD);2288 2289 // Diagnose unused variables in this scope.2290 if (!S->hasUnrecoverableErrorOccurred()) {2291 DiagnoseUnusedDecl(D, addDiag);2292 if (const auto *RD = dyn_cast<RecordDecl>(D))2293 DiagnoseUnusedNestedTypedefs(RD, addDiag);2294 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {2295 DiagnoseUnusedButSetDecl(VD, addDiag);2296 RefsMinusAssignments.erase(VD);2297 }2298 }2299 2300 if (!D->getDeclName()) continue;2301 2302 // If this was a forward reference to a label, verify it was defined.2303 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))2304 CheckPoppedLabel(LD, *this, addDiag);2305 2306 // Partial translation units that are created in incremental processing must2307 // not clean up the IdResolver because PTUs should take into account the2308 // declarations that came from previous PTUs.2309 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||2310 getLangOpts().CPlusPlus)2311 IdResolver.RemoveDecl(D);2312 2313 // Warn on it if we are shadowing a declaration.2314 auto ShadowI = ShadowingDecls.find(D);2315 if (ShadowI != ShadowingDecls.end()) {2316 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {2317 addDiagWithPrev(D->getLocation(), FD->getLocation(),2318 PDiag(diag::warn_ctor_parm_shadows_field)2319 << D << FD << FD->getParent());2320 }2321 ShadowingDecls.erase(ShadowI);2322 }2323 }2324 2325 llvm::sort(DeclDiags,2326 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {2327 // The particular order for diagnostics is not important, as long2328 // as the order is deterministic. Using the raw location is going2329 // to generally be in source order unless there are macro2330 // expansions involved.2331 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();2332 });2333 for (const LocAndDiag &D : DeclDiags) {2334 Diag(D.Loc, D.PD);2335 if (D.PreviousDeclLoc)2336 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);2337 }2338}2339 2340Scope *Sema::getNonFieldDeclScope(Scope *S) {2341 while (((S->getFlags() & Scope::DeclScope) == 0) ||2342 (S->getEntity() && S->getEntity()->isTransparentContext()) ||2343 (S->isClassScope() && !getLangOpts().CPlusPlus))2344 S = S->getParent();2345 return S;2346}2347 2348static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,2349 ASTContext::GetBuiltinTypeError Error) {2350 switch (Error) {2351 case ASTContext::GE_None:2352 return "";2353 case ASTContext::GE_Missing_type:2354 return BuiltinInfo.getHeaderName(ID);2355 case ASTContext::GE_Missing_stdio:2356 return "stdio.h";2357 case ASTContext::GE_Missing_setjmp:2358 return "setjmp.h";2359 case ASTContext::GE_Missing_ucontext:2360 return "ucontext.h";2361 }2362 llvm_unreachable("unhandled error kind");2363}2364 2365FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,2366 unsigned ID, SourceLocation Loc) {2367 DeclContext *Parent = Context.getTranslationUnitDecl();2368 2369 if (getLangOpts().CPlusPlus) {2370 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(2371 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);2372 CLinkageDecl->setImplicit();2373 Parent->addDecl(CLinkageDecl);2374 Parent = CLinkageDecl;2375 }2376 2377 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;2378 if (Context.BuiltinInfo.isImmediate(ID)) {2379 assert(getLangOpts().CPlusPlus20 &&2380 "consteval builtins should only be available in C++20 mode");2381 ConstexprKind = ConstexprSpecKind::Consteval;2382 }2383 2384 FunctionDecl *New = FunctionDecl::Create(2385 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,2386 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,2387 Type->isFunctionProtoType(), ConstexprKind);2388 New->setImplicit();2389 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));2390 2391 // Create Decl objects for each parameter, adding them to the2392 // FunctionDecl.2393 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {2394 SmallVector<ParmVarDecl *, 16> Params;2395 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {2396 ParmVarDecl *parm = ParmVarDecl::Create(2397 Context, New, SourceLocation(), SourceLocation(), nullptr,2398 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);2399 parm->setScopeInfo(0, i);2400 Params.push_back(parm);2401 }2402 New->setParams(Params);2403 }2404 2405 AddKnownFunctionAttributes(New);2406 return New;2407}2408 2409NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,2410 Scope *S, bool ForRedeclaration,2411 SourceLocation Loc) {2412 LookupNecessaryTypesForBuiltin(S, ID);2413 2414 ASTContext::GetBuiltinTypeError Error;2415 QualType R = Context.GetBuiltinType(ID, Error);2416 if (Error) {2417 if (!ForRedeclaration)2418 return nullptr;2419 2420 // If we have a builtin without an associated type we should not emit a2421 // warning when we were not able to find a type for it.2422 if (Error == ASTContext::GE_Missing_type ||2423 Context.BuiltinInfo.allowTypeMismatch(ID))2424 return nullptr;2425 2426 // If we could not find a type for setjmp it is because the jmp_buf type was2427 // not defined prior to the setjmp declaration.2428 if (Error == ASTContext::GE_Missing_setjmp) {2429 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)2430 << Context.BuiltinInfo.getName(ID);2431 return nullptr;2432 }2433 2434 // Generally, we emit a warning that the declaration requires the2435 // appropriate header.2436 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)2437 << getHeaderName(Context.BuiltinInfo, ID, Error)2438 << Context.BuiltinInfo.getName(ID);2439 return nullptr;2440 }2441 2442 if (!ForRedeclaration &&2443 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||2444 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {2445 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c992446 : diag::ext_implicit_lib_function_decl)2447 << Context.BuiltinInfo.getName(ID) << R;2448 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))2449 Diag(Loc, diag::note_include_header_or_declare)2450 << Header << Context.BuiltinInfo.getName(ID);2451 }2452 2453 if (R.isNull())2454 return nullptr;2455 2456 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);2457 RegisterLocallyScopedExternCDecl(New, S);2458 2459 // TUScope is the translation-unit scope to insert this function into.2460 // FIXME: This is hideous. We need to teach PushOnScopeChains to2461 // relate Scopes to DeclContexts, and probably eliminate CurContext2462 // entirely, but we're not there yet.2463 DeclContext *SavedContext = CurContext;2464 CurContext = New->getDeclContext();2465 PushOnScopeChains(New, TUScope);2466 CurContext = SavedContext;2467 return New;2468}2469 2470/// Typedef declarations don't have linkage, but they still denote the same2471/// entity if their types are the same.2472/// FIXME: This is notionally doing the same thing as ASTReaderDecl's2473/// isSameEntity.2474static void2475filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,2476 LookupResult &Previous) {2477 // This is only interesting when modules are enabled.2478 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)2479 return;2480 2481 // Empty sets are uninteresting.2482 if (Previous.empty())2483 return;2484 2485 LookupResult::Filter Filter = Previous.makeFilter();2486 while (Filter.hasNext()) {2487 NamedDecl *Old = Filter.next();2488 2489 // Non-hidden declarations are never ignored.2490 if (S.isVisible(Old))2491 continue;2492 2493 // Declarations of the same entity are not ignored, even if they have2494 // different linkages.2495 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {2496 if (S.Context.hasSameType(OldTD->getUnderlyingType(),2497 Decl->getUnderlyingType()))2498 continue;2499 2500 // If both declarations give a tag declaration a typedef name for linkage2501 // purposes, then they declare the same entity.2502 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&2503 Decl->getAnonDeclWithTypedefName())2504 continue;2505 }2506 2507 Filter.erase();2508 }2509 2510 Filter.done();2511}2512 2513bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {2514 QualType OldType;2515 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))2516 OldType = OldTypedef->getUnderlyingType();2517 else2518 OldType = Context.getTypeDeclType(Old);2519 QualType NewType = New->getUnderlyingType();2520 2521 if (NewType->isVariablyModifiedType()) {2522 // Must not redefine a typedef with a variably-modified type.2523 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;2524 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)2525 << Kind << NewType;2526 if (Old->getLocation().isValid())2527 notePreviousDefinition(Old, New->getLocation());2528 New->setInvalidDecl();2529 return true;2530 }2531 2532 if (OldType != NewType &&2533 !OldType->isDependentType() &&2534 !NewType->isDependentType() &&2535 !Context.hasSameType(OldType, NewType)) {2536 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;2537 Diag(New->getLocation(), diag::err_redefinition_different_typedef)2538 << Kind << NewType << OldType;2539 if (Old->getLocation().isValid())2540 notePreviousDefinition(Old, New->getLocation());2541 New->setInvalidDecl();2542 return true;2543 }2544 return false;2545}2546 2547void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,2548 LookupResult &OldDecls) {2549 // If the new decl is known invalid already, don't bother doing any2550 // merging checks.2551 if (New->isInvalidDecl()) return;2552 2553 // Allow multiple definitions for ObjC built-in typedefs.2554 // FIXME: Verify the underlying types are equivalent!2555 if (getLangOpts().ObjC) {2556 const IdentifierInfo *TypeID = New->getIdentifier();2557 switch (TypeID->getLength()) {2558 default: break;2559 case 2:2560 {2561 if (!TypeID->isStr("id"))2562 break;2563 QualType T = New->getUnderlyingType();2564 if (!T->isPointerType())2565 break;2566 if (!T->isVoidPointerType()) {2567 QualType PT = T->castAs<PointerType>()->getPointeeType();2568 if (!PT->isStructureType())2569 break;2570 }2571 Context.setObjCIdRedefinitionType(T);2572 // Install the built-in type for 'id', ignoring the current definition.2573 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),2574 Context.getObjCIdType());2575 return;2576 }2577 case 5:2578 if (!TypeID->isStr("Class"))2579 break;2580 Context.setObjCClassRedefinitionType(New->getUnderlyingType());2581 // Install the built-in type for 'Class', ignoring the current definition.2582 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),2583 Context.getObjCClassType());2584 return;2585 case 3:2586 if (!TypeID->isStr("SEL"))2587 break;2588 Context.setObjCSelRedefinitionType(New->getUnderlyingType());2589 // Install the built-in type for 'SEL', ignoring the current definition.2590 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),2591 Context.getObjCSelType());2592 return;2593 }2594 // Fall through - the typedef name was not a builtin type.2595 }2596 2597 // Verify the old decl was also a type.2598 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();2599 if (!Old) {2600 Diag(New->getLocation(), diag::err_redefinition_different_kind)2601 << New->getDeclName();2602 2603 NamedDecl *OldD = OldDecls.getRepresentativeDecl();2604 if (OldD->getLocation().isValid())2605 notePreviousDefinition(OldD, New->getLocation());2606 2607 return New->setInvalidDecl();2608 }2609 2610 // If the old declaration is invalid, just give up here.2611 if (Old->isInvalidDecl())2612 return New->setInvalidDecl();2613 2614 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {2615 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);2616 auto *NewTag = New->getAnonDeclWithTypedefName();2617 NamedDecl *Hidden = nullptr;2618 if (OldTag && NewTag &&2619 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&2620 !hasVisibleDefinition(OldTag, &Hidden)) {2621 // There is a definition of this tag, but it is not visible. Use it2622 // instead of our tag.2623 if (OldTD->isModed())2624 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),2625 OldTD->getUnderlyingType());2626 else2627 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());2628 2629 // Make the old tag definition visible.2630 makeMergedDefinitionVisible(Hidden);2631 2632 CleanupMergedEnum(S, NewTag);2633 }2634 }2635 2636 // If the typedef types are not identical, reject them in all languages and2637 // with any extensions enabled.2638 if (isIncompatibleTypedef(Old, New))2639 return;2640 2641 // The types match. Link up the redeclaration chain and merge attributes if2642 // the old declaration was a typedef.2643 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {2644 New->setPreviousDecl(Typedef);2645 mergeDeclAttributes(New, Old);2646 }2647 2648 if (getLangOpts().MicrosoftExt)2649 return;2650 2651 if (getLangOpts().CPlusPlus) {2652 // C++ [dcl.typedef]p2:2653 // In a given non-class scope, a typedef specifier can be used to2654 // redefine the name of any type declared in that scope to refer2655 // to the type to which it already refers.2656 if (!isa<CXXRecordDecl>(CurContext))2657 return;2658 2659 // C++0x [dcl.typedef]p4:2660 // In a given class scope, a typedef specifier can be used to redefine2661 // any class-name declared in that scope that is not also a typedef-name2662 // to refer to the type to which it already refers.2663 //2664 // This wording came in via DR424, which was a correction to the2665 // wording in DR56, which accidentally banned code like:2666 //2667 // struct S {2668 // typedef struct A { } A;2669 // };2670 //2671 // in the C++03 standard. We implement the C++0x semantics, which2672 // allow the above but disallow2673 //2674 // struct S {2675 // typedef int I;2676 // typedef int I;2677 // };2678 //2679 // since that was the intent of DR56.2680 if (!isa<TypedefNameDecl>(Old))2681 return;2682 2683 Diag(New->getLocation(), diag::err_redefinition)2684 << New->getDeclName();2685 notePreviousDefinition(Old, New->getLocation());2686 return New->setInvalidDecl();2687 }2688 2689 // Modules always permit redefinition of typedefs, as does C11.2690 if (getLangOpts().Modules || getLangOpts().C11)2691 return;2692 2693 // If we have a redefinition of a typedef in C, emit a warning. This warning2694 // is normally mapped to an error, but can be controlled with2695 // -Wtypedef-redefinition. If either the original or the redefinition is2696 // in a system header, don't emit this for compatibility with GCC.2697 if (getDiagnostics().getSuppressSystemWarnings() &&2698 // Some standard types are defined implicitly in Clang (e.g. OpenCL).2699 (Old->isImplicit() ||2700 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||2701 Context.getSourceManager().isInSystemHeader(New->getLocation())))2702 return;2703 2704 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)2705 << New->getDeclName();2706 notePreviousDefinition(Old, New->getLocation());2707}2708 2709void Sema::CleanupMergedEnum(Scope *S, Decl *New) {2710 // If this was an unscoped enumeration, yank all of its enumerators2711 // out of the scope.2712 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {2713 Scope *EnumScope = getNonFieldDeclScope(S);2714 for (auto *ECD : ED->enumerators()) {2715 assert(EnumScope->isDeclScope(ECD));2716 EnumScope->RemoveDecl(ECD);2717 IdResolver.RemoveDecl(ECD);2718 }2719 }2720}2721 2722/// DeclhasAttr - returns true if decl Declaration already has the target2723/// attribute.2724static bool DeclHasAttr(const Decl *D, const Attr *A) {2725 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);2726 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);2727 for (const auto *i : D->attrs())2728 if (i->getKind() == A->getKind()) {2729 if (Ann) {2730 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())2731 return true;2732 continue;2733 }2734 // FIXME: Don't hardcode this check2735 if (OA && isa<OwnershipAttr>(i))2736 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();2737 return true;2738 }2739 2740 return false;2741}2742 2743static bool isAttributeTargetADefinition(Decl *D) {2744 if (VarDecl *VD = dyn_cast<VarDecl>(D))2745 return VD->isThisDeclarationADefinition();2746 if (TagDecl *TD = dyn_cast<TagDecl>(D))2747 return TD->isCompleteDefinition() || TD->isBeingDefined();2748 return true;2749}2750 2751/// Merge alignment attributes from \p Old to \p New, taking into account the2752/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.2753///2754/// \return \c true if any attributes were added to \p New.2755static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {2756 // Look for alignas attributes on Old, and pick out whichever attribute2757 // specifies the strictest alignment requirement.2758 AlignedAttr *OldAlignasAttr = nullptr;2759 AlignedAttr *OldStrictestAlignAttr = nullptr;2760 unsigned OldAlign = 0;2761 for (auto *I : Old->specific_attrs<AlignedAttr>()) {2762 // FIXME: We have no way of representing inherited dependent alignments2763 // in a case like:2764 // template<int A, int B> struct alignas(A) X;2765 // template<int A, int B> struct alignas(B) X {};2766 // For now, we just ignore any alignas attributes which are not on the2767 // definition in such a case.2768 if (I->isAlignmentDependent())2769 return false;2770 2771 if (I->isAlignas())2772 OldAlignasAttr = I;2773 2774 unsigned Align = I->getAlignment(S.Context);2775 if (Align > OldAlign) {2776 OldAlign = Align;2777 OldStrictestAlignAttr = I;2778 }2779 }2780 2781 // Look for alignas attributes on New.2782 AlignedAttr *NewAlignasAttr = nullptr;2783 unsigned NewAlign = 0;2784 for (auto *I : New->specific_attrs<AlignedAttr>()) {2785 if (I->isAlignmentDependent())2786 return false;2787 2788 if (I->isAlignas())2789 NewAlignasAttr = I;2790 2791 unsigned Align = I->getAlignment(S.Context);2792 if (Align > NewAlign)2793 NewAlign = Align;2794 }2795 2796 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {2797 // Both declarations have 'alignas' attributes. We require them to match.2798 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but2799 // fall short. (If two declarations both have alignas, they must both match2800 // every definition, and so must match each other if there is a definition.)2801 2802 // If either declaration only contains 'alignas(0)' specifiers, then it2803 // specifies the natural alignment for the type.2804 if (OldAlign == 0 || NewAlign == 0) {2805 QualType Ty;2806 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))2807 Ty = VD->getType();2808 else2809 Ty = S.Context.getCanonicalTagType(cast<TagDecl>(New));2810 2811 if (OldAlign == 0)2812 OldAlign = S.Context.getTypeAlign(Ty);2813 if (NewAlign == 0)2814 NewAlign = S.Context.getTypeAlign(Ty);2815 }2816 2817 if (OldAlign != NewAlign) {2818 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)2819 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()2820 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();2821 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);2822 }2823 }2824 2825 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {2826 // C++11 [dcl.align]p6:2827 // if any declaration of an entity has an alignment-specifier,2828 // every defining declaration of that entity shall specify an2829 // equivalent alignment.2830 // C11 6.7.5/7:2831 // If the definition of an object does not have an alignment2832 // specifier, any other declaration of that object shall also2833 // have no alignment specifier.2834 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)2835 << OldAlignasAttr;2836 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)2837 << OldAlignasAttr;2838 }2839 2840 bool AnyAdded = false;2841 2842 // Ensure we have an attribute representing the strictest alignment.2843 if (OldAlign > NewAlign) {2844 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);2845 Clone->setInherited(true);2846 New->addAttr(Clone);2847 AnyAdded = true;2848 }2849 2850 // Ensure we have an alignas attribute if the old declaration had one.2851 if (OldAlignasAttr && !NewAlignasAttr &&2852 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {2853 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);2854 Clone->setInherited(true);2855 New->addAttr(Clone);2856 AnyAdded = true;2857 }2858 2859 return AnyAdded;2860}2861 2862#define WANT_DECL_MERGE_LOGIC2863#include "clang/Sema/AttrParsedAttrImpl.inc"2864#undef WANT_DECL_MERGE_LOGIC2865 2866static bool mergeDeclAttribute(Sema &S, NamedDecl *D,2867 const InheritableAttr *Attr,2868 AvailabilityMergeKind AMK) {2869 // Diagnose any mutual exclusions between the attribute that we want to add2870 // and attributes that already exist on the declaration.2871 if (!DiagnoseMutualExclusions(S, D, Attr))2872 return false;2873 2874 // This function copies an attribute Attr from a previous declaration to the2875 // new declaration D if the new declaration doesn't itself have that attribute2876 // yet or if that attribute allows duplicates.2877 // If you're adding a new attribute that requires logic different from2878 // "use explicit attribute on decl if present, else use attribute from2879 // previous decl", for example if the attribute needs to be consistent2880 // between redeclarations, you need to call a custom merge function here.2881 InheritableAttr *NewAttr = nullptr;2882 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))2883 NewAttr = S.mergeAvailabilityAttr(2884 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),2885 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),2886 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,2887 AA->getPriority(), AA->getEnvironment());2888 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))2889 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());2890 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))2891 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());2892 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))2893 NewAttr = S.mergeDLLImportAttr(D, *ImportA);2894 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))2895 NewAttr = S.mergeDLLExportAttr(D, *ExportA);2896 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))2897 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());2898 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))2899 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),2900 FA->getFirstArg());2901 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))2902 NewAttr = S.mergeFormatMatchesAttr(2903 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());2904 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))2905 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());2906 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))2907 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());2908 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))2909 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),2910 IA->getInheritanceModel());2911 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))2912 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,2913 &S.Context.Idents.get(AA->getSpelling()));2914 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&2915 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||2916 isa<CUDAGlobalAttr>(Attr))) {2917 // CUDA target attributes are part of function signature for2918 // overloading purposes and must not be merged.2919 return false;2920 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))2921 NewAttr = S.mergeMinSizeAttr(D, *MA);2922 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))2923 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());2924 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))2925 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);2926 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))2927 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);2928 else if (isa<AlignedAttr>(Attr))2929 // AlignedAttrs are handled separately, because we need to handle all2930 // such attributes on a declaration at the same time.2931 NewAttr = nullptr;2932 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&2933 (AMK == AvailabilityMergeKind::Override ||2934 AMK == AvailabilityMergeKind::ProtocolImplementation ||2935 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))2936 NewAttr = nullptr;2937 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))2938 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());2939 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))2940 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);2941 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))2942 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);2943 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))2944 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);2945 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))2946 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);2947 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))2948 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);2949 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))2950 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),2951 NT->getZ());2952 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))2953 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),2954 WS->getPreferred(),2955 WS->getSpelledArgsCount());2956 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))2957 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());2958 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))2959 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());2960 else if (isa<SuppressAttr>(Attr))2961 // Do nothing. Each redeclaration should be suppressed separately.2962 NewAttr = nullptr;2963 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))2964 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);2965 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))2966 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));2967 2968 if (NewAttr) {2969 NewAttr->setInherited(true);2970 D->addAttr(NewAttr);2971 if (isa<MSInheritanceAttr>(NewAttr))2972 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));2973 return true;2974 }2975 2976 return false;2977}2978 2979static const NamedDecl *getDefinition(const Decl *D) {2980 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {2981 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())2982 return Def;2983 return nullptr;2984 }2985 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {2986 const VarDecl *Def = VD->getDefinition();2987 if (Def)2988 return Def;2989 return VD->getActingDefinition();2990 }2991 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {2992 const FunctionDecl *Def = nullptr;2993 if (FD->isDefined(Def, true))2994 return Def;2995 }2996 return nullptr;2997}2998 2999static bool hasAttribute(const Decl *D, attr::Kind Kind) {3000 for (const auto *Attribute : D->attrs())3001 if (Attribute->getKind() == Kind)3002 return true;3003 return false;3004}3005 3006/// checkNewAttributesAfterDef - If we already have a definition, check that3007/// there are no new attributes in this declaration.3008static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {3009 if (!New->hasAttrs())3010 return;3011 3012 const NamedDecl *Def = getDefinition(Old);3013 if (!Def || Def == New)3014 return;3015 3016 AttrVec &NewAttributes = New->getAttrs();3017 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {3018 Attr *NewAttribute = NewAttributes[I];3019 3020 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {3021 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {3022 SkipBodyInfo SkipBody;3023 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);3024 3025 // If we're skipping this definition, drop the "alias" attribute.3026 if (SkipBody.ShouldSkip) {3027 NewAttributes.erase(NewAttributes.begin() + I);3028 --E;3029 continue;3030 }3031 } else {3032 VarDecl *VD = cast<VarDecl>(New);3033 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==3034 VarDecl::TentativeDefinition3035 ? diag::err_alias_after_tentative3036 : diag::err_redefinition;3037 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();3038 if (Diag == diag::err_redefinition)3039 S.notePreviousDefinition(Def, VD->getLocation());3040 else3041 S.Diag(Def->getLocation(), diag::note_previous_definition);3042 VD->setInvalidDecl();3043 }3044 ++I;3045 continue;3046 }3047 3048 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {3049 // Tentative definitions are only interesting for the alias check above.3050 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {3051 ++I;3052 continue;3053 }3054 }3055 3056 if (hasAttribute(Def, NewAttribute->getKind())) {3057 ++I;3058 continue; // regular attr merging will take care of validating this.3059 }3060 3061 if (isa<C11NoReturnAttr>(NewAttribute)) {3062 // C's _Noreturn is allowed to be added to a function after it is defined.3063 ++I;3064 continue;3065 } else if (isa<UuidAttr>(NewAttribute)) {3066 // msvc will allow a subsequent definition to add an uuid to a class3067 ++I;3068 continue;3069 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(3070 NewAttribute) &&3071 NewAttribute->isStandardAttributeSyntax()) {3072 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the3073 // deprecated attribute can later be re-declared with the attribute and3074 // vice-versa.3075 // C++17 [dcl.attr.unused]p4: A name or entity declared without the3076 // maybe_unused attribute can later be redeclared with the attribute and3077 // vice versa.3078 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the3079 // nodiscard attribute can later be redeclared with the attribute and3080 // vice-versa.3081 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.3082 ++I;3083 continue;3084 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {3085 if (AA->isAlignas()) {3086 // C++11 [dcl.align]p6:3087 // if any declaration of an entity has an alignment-specifier,3088 // every defining declaration of that entity shall specify an3089 // equivalent alignment.3090 // C11 6.7.5/7:3091 // If the definition of an object does not have an alignment3092 // specifier, any other declaration of that object shall also3093 // have no alignment specifier.3094 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)3095 << AA;3096 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)3097 << AA;3098 NewAttributes.erase(NewAttributes.begin() + I);3099 --E;3100 continue;3101 }3102 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {3103 // If there is a C definition followed by a redeclaration with this3104 // attribute then there are two different definitions. In C++, prefer the3105 // standard diagnostics.3106 if (!S.getLangOpts().CPlusPlus) {3107 S.Diag(NewAttribute->getLocation(),3108 diag::err_loader_uninitialized_redeclaration);3109 S.Diag(Def->getLocation(), diag::note_previous_definition);3110 NewAttributes.erase(NewAttributes.begin() + I);3111 --E;3112 continue;3113 }3114 } else if (isa<SelectAnyAttr>(NewAttribute) &&3115 cast<VarDecl>(New)->isInline() &&3116 !cast<VarDecl>(New)->isInlineSpecified()) {3117 // Don't warn about applying selectany to implicitly inline variables.3118 // Older compilers and language modes would require the use of selectany3119 // to make such variables inline, and it would have no effect if we3120 // honored it.3121 ++I;3122 continue;3123 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {3124 // We allow to add OMP[Begin]DeclareVariantAttr to be added to3125 // declarations after definitions.3126 ++I;3127 continue;3128 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {3129 // Elevate latent uses of the sycl_kernel_entry_point attribute to an3130 // error since the definition will have already been created without3131 // the semantic effects of the attribute having been applied.3132 S.Diag(NewAttribute->getLocation(),3133 diag::err_sycl_entry_point_after_definition)3134 << NewAttribute;3135 S.Diag(Def->getLocation(), diag::note_previous_definition);3136 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();3137 ++I;3138 continue;3139 } else if (isa<SYCLExternalAttr>(NewAttribute)) {3140 // SYCLExternalAttr may be added after a definition.3141 ++I;3142 continue;3143 }3144 3145 S.Diag(NewAttribute->getLocation(),3146 diag::warn_attribute_precede_definition);3147 S.Diag(Def->getLocation(), diag::note_previous_definition);3148 NewAttributes.erase(NewAttributes.begin() + I);3149 --E;3150 }3151}3152 3153static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,3154 const ConstInitAttr *CIAttr,3155 bool AttrBeforeInit) {3156 SourceLocation InsertLoc = InitDecl->getInnerLocStart();3157 3158 // Figure out a good way to write this specifier on the old declaration.3159 // FIXME: We should just use the spelling of CIAttr, but we don't preserve3160 // enough of the attribute list spelling information to extract that without3161 // heroics.3162 std::string SuitableSpelling;3163 if (S.getLangOpts().CPlusPlus20)3164 SuitableSpelling = std::string(3165 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));3166 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)3167 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(3168 InsertLoc, {tok::l_square, tok::l_square,3169 S.PP.getIdentifierInfo("clang"), tok::coloncolon,3170 S.PP.getIdentifierInfo("require_constant_initialization"),3171 tok::r_square, tok::r_square}));3172 if (SuitableSpelling.empty())3173 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(3174 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,3175 S.PP.getIdentifierInfo("require_constant_initialization"),3176 tok::r_paren, tok::r_paren}));3177 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)3178 SuitableSpelling = "constinit";3179 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)3180 SuitableSpelling = "[[clang::require_constant_initialization]]";3181 if (SuitableSpelling.empty())3182 SuitableSpelling = "__attribute__((require_constant_initialization))";3183 SuitableSpelling += " ";3184 3185 if (AttrBeforeInit) {3186 // extern constinit int a;3187 // int a = 0; // error (missing 'constinit'), accepted as extension3188 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");3189 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)3190 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);3191 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);3192 } else {3193 // int a = 0;3194 // constinit extern int a; // error (missing 'constinit')3195 S.Diag(CIAttr->getLocation(),3196 CIAttr->isConstinit() ? diag::err_constinit_added_too_late3197 : diag::warn_require_const_init_added_too_late)3198 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));3199 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)3200 << CIAttr->isConstinit()3201 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);3202 }3203}3204 3205void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,3206 AvailabilityMergeKind AMK) {3207 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {3208 UsedAttr *NewAttr = OldAttr->clone(Context);3209 NewAttr->setInherited(true);3210 New->addAttr(NewAttr);3211 }3212 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {3213 RetainAttr *NewAttr = OldAttr->clone(Context);3214 NewAttr->setInherited(true);3215 New->addAttr(NewAttr);3216 }3217 3218 if (!Old->hasAttrs() && !New->hasAttrs())3219 return;3220 3221 // [dcl.constinit]p1:3222 // If the [constinit] specifier is applied to any declaration of a3223 // variable, it shall be applied to the initializing declaration.3224 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();3225 const auto *NewConstInit = New->getAttr<ConstInitAttr>();3226 if (bool(OldConstInit) != bool(NewConstInit)) {3227 const auto *OldVD = cast<VarDecl>(Old);3228 auto *NewVD = cast<VarDecl>(New);3229 3230 // Find the initializing declaration. Note that we might not have linked3231 // the new declaration into the redeclaration chain yet.3232 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();3233 if (!InitDecl &&3234 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))3235 InitDecl = NewVD;3236 3237 if (InitDecl == NewVD) {3238 // This is the initializing declaration. If it would inherit 'constinit',3239 // that's ill-formed. (Note that we do not apply this to the attribute3240 // form).3241 if (OldConstInit && OldConstInit->isConstinit())3242 diagnoseMissingConstinit(*this, NewVD, OldConstInit,3243 /*AttrBeforeInit=*/true);3244 } else if (NewConstInit) {3245 // This is the first time we've been told that this declaration should3246 // have a constant initializer. If we already saw the initializing3247 // declaration, this is too late.3248 if (InitDecl && InitDecl != NewVD) {3249 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,3250 /*AttrBeforeInit=*/false);3251 NewVD->dropAttr<ConstInitAttr>();3252 }3253 }3254 }3255 3256 // Attributes declared post-definition are currently ignored.3257 checkNewAttributesAfterDef(*this, New, Old);3258 3259 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {3260 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {3261 if (!OldA->isEquivalent(NewA)) {3262 // This redeclaration changes __asm__ label.3263 Diag(New->getLocation(), diag::err_different_asm_label);3264 Diag(OldA->getLocation(), diag::note_previous_declaration);3265 }3266 } else if (Old->isUsed()) {3267 // This redeclaration adds an __asm__ label to a declaration that has3268 // already been ODR-used.3269 Diag(New->getLocation(), diag::err_late_asm_label_name)3270 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();3271 }3272 }3273 3274 // Re-declaration cannot add abi_tag's.3275 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {3276 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {3277 for (const auto &NewTag : NewAbiTagAttr->tags()) {3278 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {3279 Diag(NewAbiTagAttr->getLocation(),3280 diag::err_new_abi_tag_on_redeclaration)3281 << NewTag;3282 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);3283 }3284 }3285 } else {3286 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);3287 Diag(Old->getLocation(), diag::note_previous_declaration);3288 }3289 }3290 3291 // This redeclaration adds a section attribute.3292 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {3293 if (auto *VD = dyn_cast<VarDecl>(New)) {3294 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {3295 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);3296 Diag(Old->getLocation(), diag::note_previous_declaration);3297 }3298 }3299 }3300 3301 // Redeclaration adds code-seg attribute.3302 const auto *NewCSA = New->getAttr<CodeSegAttr>();3303 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&3304 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {3305 Diag(New->getLocation(), diag::warn_mismatched_section)3306 << 0 /*codeseg*/;3307 Diag(Old->getLocation(), diag::note_previous_declaration);3308 }3309 3310 if (!Old->hasAttrs())3311 return;3312 3313 bool foundAny = New->hasAttrs();3314 3315 // Ensure that any moving of objects within the allocated map is done before3316 // we process them.3317 if (!foundAny) New->setAttrs(AttrVec());3318 3319 for (auto *I : Old->specific_attrs<InheritableAttr>()) {3320 // Ignore deprecated/unavailable/availability attributes if requested.3321 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;3322 if (isa<DeprecatedAttr>(I) ||3323 isa<UnavailableAttr>(I) ||3324 isa<AvailabilityAttr>(I)) {3325 switch (AMK) {3326 case AvailabilityMergeKind::None:3327 continue;3328 3329 case AvailabilityMergeKind::Redeclaration:3330 case AvailabilityMergeKind::Override:3331 case AvailabilityMergeKind::ProtocolImplementation:3332 case AvailabilityMergeKind::OptionalProtocolImplementation:3333 LocalAMK = AMK;3334 break;3335 }3336 }3337 3338 // Already handled.3339 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))3340 continue;3341 3342 if (isa<InferredNoReturnAttr>(I)) {3343 if (auto *FD = dyn_cast<FunctionDecl>(New);3344 FD &&3345 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)3346 continue; // Don't propagate inferred noreturn attributes to explicit3347 }3348 3349 if (mergeDeclAttribute(*this, New, I, LocalAMK))3350 foundAny = true;3351 }3352 3353 if (mergeAlignedAttrs(*this, New, Old))3354 foundAny = true;3355 3356 if (!foundAny) New->dropAttrs();3357}3358 3359void Sema::CheckAttributesOnDeducedType(Decl *D) {3360 for (const Attr *A : D->attrs())3361 checkAttrIsTypeDependent(D, A);3362}3363 3364// Returns the number of added attributes.3365template <class T>3366static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,3367 Sema &S) {3368 unsigned found = 0;3369 for (const auto *I : From->specific_attrs<T>()) {3370 if (!DeclHasAttr(To, I)) {3371 T *newAttr = cast<T>(I->clone(S.Context));3372 newAttr->setInherited(true);3373 To->addAttr(newAttr);3374 ++found;3375 }3376 }3377 return found;3378}3379 3380template <class F>3381static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,3382 F &&propagator) {3383 if (!From->hasAttrs()) {3384 return;3385 }3386 3387 bool foundAny = To->hasAttrs();3388 3389 // Ensure that any moving of objects within the allocated map is3390 // done before we process them.3391 if (!foundAny)3392 To->setAttrs(AttrVec());3393 3394 foundAny |= std::forward<F>(propagator)(To, From) != 0;3395 3396 if (!foundAny)3397 To->dropAttrs();3398}3399 3400/// mergeParamDeclAttributes - Copy attributes from the old parameter3401/// to the new one.3402static void mergeParamDeclAttributes(ParmVarDecl *newDecl,3403 const ParmVarDecl *oldDecl,3404 Sema &S) {3405 // C++11 [dcl.attr.depend]p2:3406 // The first declaration of a function shall specify the3407 // carries_dependency attribute for its declarator-id if any declaration3408 // of the function specifies the carries_dependency attribute.3409 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();3410 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {3411 S.Diag(CDA->getLocation(),3412 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;3413 // Find the first declaration of the parameter.3414 // FIXME: Should we build redeclaration chains for function parameters?3415 const FunctionDecl *FirstFD =3416 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();3417 const ParmVarDecl *FirstVD =3418 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());3419 S.Diag(FirstVD->getLocation(),3420 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;3421 }3422 3423 propagateAttributes(3424 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {3425 unsigned found = 0;3426 found += propagateAttribute<InheritableParamAttr>(To, From, S);3427 // Propagate the lifetimebound attribute from parameters to the3428 // most recent declaration. Note that this doesn't include the implicit3429 // 'this' parameter, as the attribute is applied to the function type in3430 // that case.3431 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);3432 return found;3433 });3434}3435 3436static bool EquivalentArrayTypes(QualType Old, QualType New,3437 const ASTContext &Ctx) {3438 3439 auto NoSizeInfo = [&Ctx](QualType Ty) {3440 if (Ty->isIncompleteArrayType() || Ty->isPointerType())3441 return true;3442 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))3443 return VAT->getSizeModifier() == ArraySizeModifier::Star;3444 return false;3445 };3446 3447 // `type[]` is equivalent to `type *` and `type[*]`.3448 if (NoSizeInfo(Old) && NoSizeInfo(New))3449 return true;3450 3451 // Don't try to compare VLA sizes, unless one of them has the star modifier.3452 if (Old->isVariableArrayType() && New->isVariableArrayType()) {3453 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);3454 const auto *NewVAT = Ctx.getAsVariableArrayType(New);3455 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^3456 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))3457 return false;3458 return true;3459 }3460 3461 // Only compare size, ignore Size modifiers and CVR.3462 if (Old->isConstantArrayType() && New->isConstantArrayType()) {3463 return Ctx.getAsConstantArrayType(Old)->getSize() ==3464 Ctx.getAsConstantArrayType(New)->getSize();3465 }3466 3467 // Don't try to compare dependent sized array3468 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {3469 return true;3470 }3471 3472 return Old == New;3473}3474 3475static void mergeParamDeclTypes(ParmVarDecl *NewParam,3476 const ParmVarDecl *OldParam,3477 Sema &S) {3478 if (auto Oldnullability = OldParam->getType()->getNullability()) {3479 if (auto Newnullability = NewParam->getType()->getNullability()) {3480 if (*Oldnullability != *Newnullability) {3481 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)3482 << DiagNullabilityKind(3483 *Newnullability,3484 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)3485 != 0))3486 << DiagNullabilityKind(3487 *Oldnullability,3488 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)3489 != 0));3490 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);3491 }3492 } else {3493 QualType NewT = NewParam->getType();3494 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);3495 NewParam->setType(NewT);3496 }3497 }3498 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());3499 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());3500 if (OldParamDT && NewParamDT &&3501 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {3502 QualType OldParamOT = OldParamDT->getOriginalType();3503 QualType NewParamOT = NewParamDT->getOriginalType();3504 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {3505 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)3506 << NewParam << NewParamOT;3507 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)3508 << OldParamOT;3509 }3510 }3511}3512 3513namespace {3514 3515/// Used in MergeFunctionDecl to keep track of function parameters in3516/// C.3517struct GNUCompatibleParamWarning {3518 ParmVarDecl *OldParm;3519 ParmVarDecl *NewParm;3520 QualType PromotedType;3521};3522 3523} // end anonymous namespace3524 3525// Determine whether the previous declaration was a definition, implicit3526// declaration, or a declaration.3527template <typename T>3528static std::pair<diag::kind, SourceLocation>3529getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {3530 diag::kind PrevDiag;3531 SourceLocation OldLocation = Old->getLocation();3532 if (Old->isThisDeclarationADefinition())3533 PrevDiag = diag::note_previous_definition;3534 else if (Old->isImplicit()) {3535 PrevDiag = diag::note_previous_implicit_declaration;3536 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {3537 if (FD->getBuiltinID())3538 PrevDiag = diag::note_previous_builtin_declaration;3539 }3540 if (OldLocation.isInvalid())3541 OldLocation = New->getLocation();3542 } else3543 PrevDiag = diag::note_previous_declaration;3544 return std::make_pair(PrevDiag, OldLocation);3545}3546 3547/// canRedefineFunction - checks if a function can be redefined. Currently,3548/// only extern inline functions can be redefined, and even then only in3549/// GNU89 mode.3550static bool canRedefineFunction(const FunctionDecl *FD,3551 const LangOptions& LangOpts) {3552 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&3553 !LangOpts.CPlusPlus &&3554 FD->isInlineSpecified() &&3555 FD->getStorageClass() == SC_Extern);3556}3557 3558const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {3559 const AttributedType *AT = T->getAs<AttributedType>();3560 while (AT && !AT->isCallingConv())3561 AT = AT->getModifiedType()->getAs<AttributedType>();3562 return AT;3563}3564 3565template <typename T>3566static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {3567 const DeclContext *DC = Old->getDeclContext();3568 if (DC->isRecord())3569 return false;3570 3571 LanguageLinkage OldLinkage = Old->getLanguageLinkage();3572 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())3573 return true;3574 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())3575 return true;3576 return false;3577}3578 3579template<typename T> static bool isExternC(T *D) { return D->isExternC(); }3580static bool isExternC(VarTemplateDecl *) { return false; }3581static bool isExternC(FunctionTemplateDecl *) { return false; }3582 3583/// Check whether a redeclaration of an entity introduced by a3584/// using-declaration is valid, given that we know it's not an overload3585/// (nor a hidden tag declaration).3586template<typename ExpectedDecl>3587static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,3588 ExpectedDecl *New) {3589 // C++11 [basic.scope.declarative]p4:3590 // Given a set of declarations in a single declarative region, each of3591 // which specifies the same unqualified name,3592 // -- they shall all refer to the same entity, or all refer to functions3593 // and function templates; or3594 // -- exactly one declaration shall declare a class name or enumeration3595 // name that is not a typedef name and the other declarations shall all3596 // refer to the same variable or enumerator, or all refer to functions3597 // and function templates; in this case the class name or enumeration3598 // name is hidden (3.3.10).3599 3600 // C++11 [namespace.udecl]p14:3601 // If a function declaration in namespace scope or block scope has the3602 // same name and the same parameter-type-list as a function introduced3603 // by a using-declaration, and the declarations do not declare the same3604 // function, the program is ill-formed.3605 3606 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());3607 if (Old &&3608 !Old->getDeclContext()->getRedeclContext()->Equals(3609 New->getDeclContext()->getRedeclContext()) &&3610 !(isExternC(Old) && isExternC(New)))3611 Old = nullptr;3612 3613 if (!Old) {3614 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);3615 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);3616 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;3617 return true;3618 }3619 return false;3620}3621 3622static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,3623 const FunctionDecl *B) {3624 assert(A->getNumParams() == B->getNumParams());3625 3626 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {3627 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();3628 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();3629 if (AttrA == AttrB)3630 return true;3631 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&3632 AttrA->isDynamic() == AttrB->isDynamic();3633 };3634 3635 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);3636}3637 3638/// If necessary, adjust the semantic declaration context for a qualified3639/// declaration to name the correct inline namespace within the qualifier.3640static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,3641 DeclaratorDecl *OldD) {3642 // The only case where we need to update the DeclContext is when3643 // redeclaration lookup for a qualified name finds a declaration3644 // in an inline namespace within the context named by the qualifier:3645 //3646 // inline namespace N { int f(); }3647 // int ::f(); // Sema DC needs adjusting from :: to N::.3648 //3649 // For unqualified declarations, the semantic context *can* change3650 // along the redeclaration chain (for local extern declarations,3651 // extern "C" declarations, and friend declarations in particular).3652 if (!NewD->getQualifier())3653 return;3654 3655 // NewD is probably already in the right context.3656 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();3657 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();3658 if (NamedDC->Equals(SemaDC))3659 return;3660 3661 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||3662 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&3663 "unexpected context for redeclaration");3664 3665 auto *LexDC = NewD->getLexicalDeclContext();3666 auto FixSemaDC = [=](NamedDecl *D) {3667 if (!D)3668 return;3669 D->setDeclContext(SemaDC);3670 D->setLexicalDeclContext(LexDC);3671 };3672 3673 FixSemaDC(NewD);3674 if (auto *FD = dyn_cast<FunctionDecl>(NewD))3675 FixSemaDC(FD->getDescribedFunctionTemplate());3676 else if (auto *VD = dyn_cast<VarDecl>(NewD))3677 FixSemaDC(VD->getDescribedVarTemplate());3678}3679 3680bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,3681 bool MergeTypeWithOld, bool NewDeclIsDefn) {3682 // Verify the old decl was also a function.3683 FunctionDecl *Old = OldD->getAsFunction();3684 if (!Old) {3685 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {3686 // We don't need to check the using friend pattern from other module unit3687 // since we should have diagnosed such cases in its unit already.3688 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {3689 Diag(New->getLocation(), diag::err_using_decl_friend);3690 Diag(Shadow->getTargetDecl()->getLocation(),3691 diag::note_using_decl_target);3692 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)3693 << 0;3694 return true;3695 }3696 3697 // Check whether the two declarations might declare the same function or3698 // function template.3699 if (FunctionTemplateDecl *NewTemplate =3700 New->getDescribedFunctionTemplate()) {3701 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,3702 NewTemplate))3703 return true;3704 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())3705 ->getAsFunction();3706 } else {3707 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))3708 return true;3709 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());3710 }3711 } else {3712 Diag(New->getLocation(), diag::err_redefinition_different_kind)3713 << New->getDeclName();3714 notePreviousDefinition(OldD, New->getLocation());3715 return true;3716 }3717 }3718 3719 // If the old declaration was found in an inline namespace and the new3720 // declaration was qualified, update the DeclContext to match.3721 adjustDeclContextForDeclaratorDecl(New, Old);3722 3723 // If the old declaration is invalid, just give up here.3724 if (Old->isInvalidDecl())3725 return true;3726 3727 // Disallow redeclaration of some builtins.3728 if (!getASTContext().canBuiltinBeRedeclared(Old)) {3729 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();3730 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)3731 << Old << Old->getType();3732 return true;3733 }3734 3735 diag::kind PrevDiag;3736 SourceLocation OldLocation;3737 std::tie(PrevDiag, OldLocation) =3738 getNoteDiagForInvalidRedeclaration(Old, New);3739 3740 // Don't complain about this if we're in GNU89 mode and the old function3741 // is an extern inline function.3742 // Don't complain about specializations. They are not supposed to have3743 // storage classes.3744 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&3745 New->getStorageClass() == SC_Static &&3746 Old->hasExternalFormalLinkage() &&3747 !New->getTemplateSpecializationInfo() &&3748 !canRedefineFunction(Old, getLangOpts())) {3749 if (getLangOpts().MicrosoftExt) {3750 Diag(New->getLocation(), diag::ext_static_non_static) << New;3751 Diag(OldLocation, PrevDiag) << Old << Old->getType();3752 } else {3753 Diag(New->getLocation(), diag::err_static_non_static) << New;3754 Diag(OldLocation, PrevDiag) << Old << Old->getType();3755 return true;3756 }3757 }3758 3759 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())3760 if (!Old->hasAttr<InternalLinkageAttr>()) {3761 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)3762 << ILA;3763 Diag(Old->getLocation(), diag::note_previous_declaration);3764 New->dropAttr<InternalLinkageAttr>();3765 }3766 3767 if (auto *EA = New->getAttr<ErrorAttr>()) {3768 if (!Old->hasAttr<ErrorAttr>()) {3769 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;3770 Diag(Old->getLocation(), diag::note_previous_declaration);3771 New->dropAttr<ErrorAttr>();3772 }3773 }3774 3775 if (CheckRedeclarationInModule(New, Old))3776 return true;3777 3778 if (!getLangOpts().CPlusPlus) {3779 bool OldOvl = Old->hasAttr<OverloadableAttr>();3780 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {3781 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)3782 << New << OldOvl;3783 3784 // Try our best to find a decl that actually has the overloadable3785 // attribute for the note. In most cases (e.g. programs with only one3786 // broken declaration/definition), this won't matter.3787 //3788 // FIXME: We could do this if we juggled some extra state in3789 // OverloadableAttr, rather than just removing it.3790 const Decl *DiagOld = Old;3791 if (OldOvl) {3792 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {3793 const auto *A = D->getAttr<OverloadableAttr>();3794 return A && !A->isImplicit();3795 });3796 // If we've implicitly added *all* of the overloadable attrs to this3797 // chain, emitting a "previous redecl" note is pointless.3798 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;3799 }3800 3801 if (DiagOld)3802 Diag(DiagOld->getLocation(),3803 diag::note_attribute_overloadable_prev_overload)3804 << OldOvl;3805 3806 if (OldOvl)3807 New->addAttr(OverloadableAttr::CreateImplicit(Context));3808 else3809 New->dropAttr<OverloadableAttr>();3810 }3811 }3812 3813 // It is not permitted to redeclare an SME function with different SME3814 // attributes.3815 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {3816 Diag(New->getLocation(), diag::err_sme_attr_mismatch)3817 << New->getType() << Old->getType();3818 Diag(OldLocation, diag::note_previous_declaration);3819 return true;3820 }3821 3822 // If a function is first declared with a calling convention, but is later3823 // declared or defined without one, all following decls assume the calling3824 // convention of the first.3825 //3826 // It's OK if a function is first declared without a calling convention,3827 // but is later declared or defined with the default calling convention.3828 //3829 // To test if either decl has an explicit calling convention, we look for3830 // AttributedType sugar nodes on the type as written. If they are missing or3831 // were canonicalized away, we assume the calling convention was implicit.3832 //3833 // Note also that we DO NOT return at this point, because we still have3834 // other tests to run.3835 QualType OldQType = Context.getCanonicalType(Old->getType());3836 QualType NewQType = Context.getCanonicalType(New->getType());3837 const FunctionType *OldType = cast<FunctionType>(OldQType);3838 const FunctionType *NewType = cast<FunctionType>(NewQType);3839 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();3840 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();3841 bool RequiresAdjustment = false;3842 3843 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {3844 FunctionDecl *First = Old->getFirstDecl();3845 const FunctionType *FT =3846 First->getType().getCanonicalType()->castAs<FunctionType>();3847 FunctionType::ExtInfo FI = FT->getExtInfo();3848 bool NewCCExplicit = getCallingConvAttributedType(New->getType());3849 if (!NewCCExplicit) {3850 // Inherit the CC from the previous declaration if it was specified3851 // there but not here.3852 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());3853 RequiresAdjustment = true;3854 } else if (Old->getBuiltinID()) {3855 // Builtin attribute isn't propagated to the new one yet at this point,3856 // so we check if the old one is a builtin.3857 3858 // Calling Conventions on a Builtin aren't really useful and setting a3859 // default calling convention and cdecl'ing some builtin redeclarations is3860 // common, so warn and ignore the calling convention on the redeclaration.3861 Diag(New->getLocation(), diag::warn_cconv_unsupported)3862 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())3863 << (int)CallingConventionIgnoredReason::BuiltinFunction;3864 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());3865 RequiresAdjustment = true;3866 } else {3867 // Calling conventions aren't compatible, so complain.3868 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());3869 Diag(New->getLocation(), diag::err_cconv_change)3870 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())3871 << !FirstCCExplicit3872 << (!FirstCCExplicit ? "" :3873 FunctionType::getNameForCallConv(FI.getCC()));3874 3875 // Put the note on the first decl, since it is the one that matters.3876 Diag(First->getLocation(), diag::note_previous_declaration);3877 return true;3878 }3879 }3880 3881 // FIXME: diagnose the other way around?3882 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {3883 NewTypeInfo = NewTypeInfo.withNoReturn(true);3884 RequiresAdjustment = true;3885 }3886 3887 // If the declaration is marked with cfi_unchecked_callee but the definition3888 // isn't, the definition is also cfi_unchecked_callee.3889 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {3890 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {3891 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();3892 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();3893 3894 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {3895 EPI2.CFIUncheckedCallee = true;3896 NewQType = Context.getFunctionType(FPT2->getReturnType(),3897 FPT2->getParamTypes(), EPI2);3898 NewType = cast<FunctionType>(NewQType);3899 New->setType(NewQType);3900 }3901 }3902 }3903 3904 // Merge regparm attribute.3905 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||3906 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {3907 if (NewTypeInfo.getHasRegParm()) {3908 Diag(New->getLocation(), diag::err_regparm_mismatch)3909 << NewType->getRegParmType()3910 << OldType->getRegParmType();3911 Diag(OldLocation, diag::note_previous_declaration);3912 return true;3913 }3914 3915 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());3916 RequiresAdjustment = true;3917 }3918 3919 // Merge ns_returns_retained attribute.3920 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {3921 if (NewTypeInfo.getProducesResult()) {3922 Diag(New->getLocation(), diag::err_function_attribute_mismatch)3923 << "'ns_returns_retained'";3924 Diag(OldLocation, diag::note_previous_declaration);3925 return true;3926 }3927 3928 NewTypeInfo = NewTypeInfo.withProducesResult(true);3929 RequiresAdjustment = true;3930 }3931 3932 if (OldTypeInfo.getNoCallerSavedRegs() !=3933 NewTypeInfo.getNoCallerSavedRegs()) {3934 if (NewTypeInfo.getNoCallerSavedRegs()) {3935 AnyX86NoCallerSavedRegistersAttr *Attr =3936 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();3937 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;3938 Diag(OldLocation, diag::note_previous_declaration);3939 return true;3940 }3941 3942 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);3943 RequiresAdjustment = true;3944 }3945 3946 if (RequiresAdjustment) {3947 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();3948 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);3949 New->setType(QualType(AdjustedType, 0));3950 NewQType = Context.getCanonicalType(New->getType());3951 }3952 3953 // If this redeclaration makes the function inline, we may need to add it to3954 // UndefinedButUsed.3955 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&3956 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&3957 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())3958 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),3959 SourceLocation()));3960 3961 // If this redeclaration makes it newly gnu_inline, we don't want to warn3962 // about it.3963 if (New->hasAttr<GNUInlineAttr>() &&3964 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {3965 UndefinedButUsed.erase(Old->getCanonicalDecl());3966 }3967 3968 // If pass_object_size params don't match up perfectly, this isn't a valid3969 // redeclaration.3970 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&3971 !hasIdenticalPassObjectSizeAttrs(Old, New)) {3972 Diag(New->getLocation(), diag::err_different_pass_object_size_params)3973 << New->getDeclName();3974 Diag(OldLocation, PrevDiag) << Old << Old->getType();3975 return true;3976 }3977 3978 QualType OldQTypeForComparison = OldQType;3979 if (Context.hasAnyFunctionEffects()) {3980 const auto OldFX = Old->getFunctionEffects();3981 const auto NewFX = New->getFunctionEffects();3982 if (OldFX != NewFX) {3983 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);3984 for (const auto &Diff : Diffs) {3985 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {3986 Diag(New->getLocation(),3987 diag::warn_mismatched_func_effect_redeclaration)3988 << Diff.effectName();3989 Diag(Old->getLocation(), diag::note_previous_declaration);3990 }3991 }3992 // Following a warning, we could skip merging effects from the previous3993 // declaration, but that would trigger an additional "conflicting types"3994 // error.3995 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {3996 FunctionEffectSet::Conflicts MergeErrs;3997 FunctionEffectSet MergedFX =3998 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);3999 if (!MergeErrs.empty())4000 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),4001 Old->getLocation());4002 4003 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();4004 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);4005 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),4006 NewFPT->getParamTypes(), EPI);4007 4008 New->setType(ModQT);4009 NewQType = New->getType();4010 4011 // Revise OldQTForComparison to include the merged effects,4012 // so as not to fail due to differences later.4013 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {4014 EPI = OldFPT->getExtProtoInfo();4015 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);4016 OldQTypeForComparison = Context.getFunctionType(4017 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);4018 }4019 if (OldFX.empty()) {4020 // A redeclaration may add the attribute to a previously seen function4021 // body which needs to be verified.4022 maybeAddDeclWithEffects(Old, MergedFX);4023 }4024 }4025 }4026 }4027 4028 if (getLangOpts().CPlusPlus) {4029 OldQType = Context.getCanonicalType(Old->getType());4030 NewQType = Context.getCanonicalType(New->getType());4031 4032 // Go back to the type source info to compare the declared return types,4033 // per C++1y [dcl.type.auto]p13:4034 // Redeclarations or specializations of a function or function template4035 // with a declared return type that uses a placeholder type shall also4036 // use that placeholder, not a deduced type.4037 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();4038 QualType NewDeclaredReturnType = New->getDeclaredReturnType();4039 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&4040 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,4041 OldDeclaredReturnType)) {4042 QualType ResQT;4043 if (NewDeclaredReturnType->isObjCObjectPointerType() &&4044 OldDeclaredReturnType->isObjCObjectPointerType())4045 // FIXME: This does the wrong thing for a deduced return type.4046 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);4047 if (ResQT.isNull()) {4048 if (New->isCXXClassMember() && New->isOutOfLine())4049 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)4050 << New << New->getReturnTypeSourceRange();4051 else if (Old->isExternC() && New->isExternC() &&4052 !Old->hasAttr<OverloadableAttr>() &&4053 !New->hasAttr<OverloadableAttr>())4054 Diag(New->getLocation(), diag::err_conflicting_types) << New;4055 else4056 Diag(New->getLocation(), diag::err_ovl_diff_return_type)4057 << New->getReturnTypeSourceRange();4058 Diag(OldLocation, PrevDiag) << Old << Old->getType()4059 << Old->getReturnTypeSourceRange();4060 return true;4061 }4062 else4063 NewQType = ResQT;4064 }4065 4066 QualType OldReturnType = OldType->getReturnType();4067 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();4068 if (OldReturnType != NewReturnType) {4069 // If this function has a deduced return type and has already been4070 // defined, copy the deduced value from the old declaration.4071 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();4072 if (OldAT && OldAT->isDeduced()) {4073 QualType DT = OldAT->getDeducedType();4074 if (DT.isNull()) {4075 New->setType(SubstAutoTypeDependent(New->getType()));4076 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));4077 } else {4078 New->setType(SubstAutoType(New->getType(), DT));4079 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));4080 }4081 }4082 }4083 4084 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);4085 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);4086 if (OldMethod && NewMethod) {4087 // Preserve triviality.4088 NewMethod->setTrivial(OldMethod->isTrivial());4089 4090 // MSVC allows explicit template specialization at class scope:4091 // 2 CXXMethodDecls referring to the same function will be injected.4092 // We don't want a redeclaration error.4093 bool IsClassScopeExplicitSpecialization =4094 OldMethod->isFunctionTemplateSpecialization() &&4095 NewMethod->isFunctionTemplateSpecialization();4096 bool isFriend = NewMethod->getFriendObjectKind();4097 4098 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&4099 !IsClassScopeExplicitSpecialization) {4100 // -- Member function declarations with the same name and the4101 // same parameter types cannot be overloaded if any of them4102 // is a static member function declaration.4103 if (OldMethod->isStatic() != NewMethod->isStatic()) {4104 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);4105 Diag(OldLocation, PrevDiag) << Old << Old->getType();4106 return true;4107 }4108 4109 // C++ [class.mem]p1:4110 // [...] A member shall not be declared twice in the4111 // member-specification, except that a nested class or member4112 // class template can be declared and then later defined.4113 if (!inTemplateInstantiation()) {4114 unsigned NewDiag;4115 if (isa<CXXConstructorDecl>(OldMethod))4116 NewDiag = diag::err_constructor_redeclared;4117 else if (isa<CXXDestructorDecl>(NewMethod))4118 NewDiag = diag::err_destructor_redeclared;4119 else if (isa<CXXConversionDecl>(NewMethod))4120 NewDiag = diag::err_conv_function_redeclared;4121 else4122 NewDiag = diag::err_member_redeclared;4123 4124 Diag(New->getLocation(), NewDiag);4125 } else {4126 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)4127 << New << New->getType();4128 }4129 Diag(OldLocation, PrevDiag) << Old << Old->getType();4130 return true;4131 4132 // Complain if this is an explicit declaration of a special4133 // member that was initially declared implicitly.4134 //4135 // As an exception, it's okay to befriend such methods in order4136 // to permit the implicit constructor/destructor/operator calls.4137 } else if (OldMethod->isImplicit()) {4138 if (isFriend) {4139 NewMethod->setImplicit();4140 } else {4141 Diag(NewMethod->getLocation(),4142 diag::err_definition_of_implicitly_declared_member)4143 << New << getSpecialMember(OldMethod);4144 return true;4145 }4146 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {4147 Diag(NewMethod->getLocation(),4148 diag::err_definition_of_explicitly_defaulted_member)4149 << getSpecialMember(OldMethod);4150 return true;4151 }4152 }4153 4154 // C++1z [over.load]p24155 // Certain function declarations cannot be overloaded:4156 // -- Function declarations that differ only in the return type,4157 // the exception specification, or both cannot be overloaded.4158 4159 // Check the exception specifications match. This may recompute the type of4160 // both Old and New if it resolved exception specifications, so grab the4161 // types again after this. Because this updates the type, we do this before4162 // any of the other checks below, which may update the "de facto" NewQType4163 // but do not necessarily update the type of New.4164 if (CheckEquivalentExceptionSpec(Old, New))4165 return true;4166 4167 // C++11 [dcl.attr.noreturn]p1:4168 // The first declaration of a function shall specify the noreturn4169 // attribute if any declaration of that function specifies the noreturn4170 // attribute.4171 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())4172 if (!Old->hasAttr<CXX11NoReturnAttr>()) {4173 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)4174 << NRA;4175 Diag(Old->getLocation(), diag::note_previous_declaration);4176 }4177 4178 // C++11 [dcl.attr.depend]p2:4179 // The first declaration of a function shall specify the4180 // carries_dependency attribute for its declarator-id if any declaration4181 // of the function specifies the carries_dependency attribute.4182 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();4183 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {4184 Diag(CDA->getLocation(),4185 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;4186 Diag(Old->getFirstDecl()->getLocation(),4187 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;4188 }4189 4190 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":4191 // When a function is declared with SYCL_EXTERNAL, that macro must be4192 // used on the first declaration of that function in the translation unit.4193 // Redeclarations of the function in the same translation unit may4194 // optionally use SYCL_EXTERNAL, but this is not required.4195 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();4196 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {4197 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)4198 << SEA;4199 Diag(Old->getLocation(), diag::note_previous_declaration);4200 }4201 4202 // (C++98 8.3.5p3):4203 // All declarations for a function shall agree exactly in both the4204 // return type and the parameter-type-list.4205 // We also want to respect all the extended bits except noreturn.4206 4207 // noreturn should now match unless the old type info didn't have it.4208 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {4209 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();4210 const FunctionType *OldTypeForComparison4211 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));4212 OldQTypeForComparison = QualType(OldTypeForComparison, 0);4213 assert(OldQTypeForComparison.isCanonical());4214 }4215 4216 if (haveIncompatibleLanguageLinkages(Old, New)) {4217 // As a special case, retain the language linkage from previous4218 // declarations of a friend function as an extension.4219 //4220 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC4221 // and is useful because there's otherwise no way to specify language4222 // linkage within class scope.4223 //4224 // Check cautiously as the friend object kind isn't yet complete.4225 if (New->getFriendObjectKind() != Decl::FOK_None) {4226 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;4227 Diag(OldLocation, PrevDiag);4228 } else {4229 Diag(New->getLocation(), diag::err_different_language_linkage) << New;4230 Diag(OldLocation, PrevDiag);4231 return true;4232 }4233 }4234 4235 // HLSL check parameters for matching ABI specifications.4236 if (getLangOpts().HLSL) {4237 if (HLSL().CheckCompatibleParameterABI(New, Old))4238 return true;4239 4240 // If no errors are generated when checking parameter ABIs we can check if4241 // the two declarations have the same type ignoring the ABIs and if so,4242 // the declarations can be merged. This case for merging is only valid in4243 // HLSL because there are no valid cases of merging mismatched parameter4244 // ABIs except the HLSL implicit in and explicit in.4245 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,4246 NewQType))4247 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);4248 // Fall through for conflicting redeclarations and redefinitions.4249 }4250 4251 // If the function types are compatible, merge the declarations. Ignore the4252 // exception specifier because it was already checked above in4253 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics4254 // about incompatible types under -fms-compatibility.4255 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,4256 NewQType))4257 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);4258 4259 // If the types are imprecise (due to dependent constructs in friends or4260 // local extern declarations), it's OK if they differ. We'll check again4261 // during instantiation.4262 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))4263 return false;4264 4265 // Fall through for conflicting redeclarations and redefinitions.4266 }4267 4268 // C: Function types need to be compatible, not identical. This handles4269 // duplicate function decls like "void f(int); void f(enum X);" properly.4270 if (!getLangOpts().CPlusPlus) {4271 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other4272 // type is specified by a function definition that contains a (possibly4273 // empty) identifier list, both shall agree in the number of parameters4274 // and the type of each parameter shall be compatible with the type that4275 // results from the application of default argument promotions to the4276 // type of the corresponding identifier. ...4277 // This cannot be handled by ASTContext::typesAreCompatible() because that4278 // doesn't know whether the function type is for a definition or not when4279 // eventually calling ASTContext::mergeFunctionTypes(). The only situation4280 // we need to cover here is that the number of arguments agree as the4281 // default argument promotion rules were already checked by4282 // ASTContext::typesAreCompatible().4283 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&4284 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {4285 if (Old->hasInheritedPrototype())4286 Old = Old->getCanonicalDecl();4287 Diag(New->getLocation(), diag::err_conflicting_types) << New;4288 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();4289 return true;4290 }4291 4292 // If we are merging two functions where only one of them has a prototype,4293 // we may have enough information to decide to issue a diagnostic that the4294 // function without a prototype will change behavior in C23. This handles4295 // cases like:4296 // void i(); void i(int j);4297 // void i(int j); void i();4298 // void i(); void i(int j) {}4299 // See ActOnFinishFunctionBody() for other cases of the behavior change4300 // diagnostic. See GetFullTypeForDeclarator() for handling of a function4301 // type without a prototype.4302 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&4303 !New->isImplicit() && !Old->isImplicit()) {4304 const FunctionDecl *WithProto, *WithoutProto;4305 if (New->hasWrittenPrototype()) {4306 WithProto = New;4307 WithoutProto = Old;4308 } else {4309 WithProto = Old;4310 WithoutProto = New;4311 }4312 4313 if (WithProto->getNumParams() != 0) {4314 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {4315 // The one without the prototype will be changing behavior in C23, so4316 // warn about that one so long as it's a user-visible declaration.4317 bool IsWithoutProtoADef = false, IsWithProtoADef = false;4318 if (WithoutProto == New)4319 IsWithoutProtoADef = NewDeclIsDefn;4320 else4321 IsWithProtoADef = NewDeclIsDefn;4322 Diag(WithoutProto->getLocation(),4323 diag::warn_non_prototype_changes_behavior)4324 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)4325 << (WithoutProto == Old) << IsWithProtoADef;4326 4327 // The reason the one without the prototype will be changing behavior4328 // is because of the one with the prototype, so note that so long as4329 // it's a user-visible declaration. There is one exception to this:4330 // when the new declaration is a definition without a prototype, the4331 // old declaration with a prototype is not the cause of the issue,4332 // and that does not need to be noted because the one with a4333 // prototype will not change behavior in C23.4334 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&4335 !IsWithoutProtoADef)4336 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);4337 }4338 }4339 }4340 4341 if (Context.typesAreCompatible(OldQType, NewQType)) {4342 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();4343 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();4344 const FunctionProtoType *OldProto = nullptr;4345 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&4346 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {4347 // The old declaration provided a function prototype, but the4348 // new declaration does not. Merge in the prototype.4349 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");4350 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),4351 OldProto->getParamTypes(),4352 OldProto->getExtProtoInfo());4353 New->setType(NewQType);4354 New->setHasInheritedPrototype();4355 4356 // Synthesize parameters with the same types.4357 SmallVector<ParmVarDecl *, 16> Params;4358 for (const auto &ParamType : OldProto->param_types()) {4359 ParmVarDecl *Param = ParmVarDecl::Create(4360 Context, New, SourceLocation(), SourceLocation(), nullptr,4361 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);4362 Param->setScopeInfo(0, Params.size());4363 Param->setImplicit();4364 Params.push_back(Param);4365 }4366 4367 New->setParams(Params);4368 }4369 4370 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);4371 }4372 }4373 4374 // Check if the function types are compatible when pointer size address4375 // spaces are ignored.4376 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))4377 return false;4378 4379 // GNU C permits a K&R definition to follow a prototype declaration4380 // if the declared types of the parameters in the K&R definition4381 // match the types in the prototype declaration, even when the4382 // promoted types of the parameters from the K&R definition differ4383 // from the types in the prototype. GCC then keeps the types from4384 // the prototype.4385 //4386 // If a variadic prototype is followed by a non-variadic K&R definition,4387 // the K&R definition becomes variadic. This is sort of an edge case, but4388 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and4389 // C99 6.9.1p8.4390 if (!getLangOpts().CPlusPlus &&4391 Old->hasPrototype() && !New->hasPrototype() &&4392 New->getType()->getAs<FunctionProtoType>() &&4393 Old->getNumParams() == New->getNumParams()) {4394 SmallVector<QualType, 16> ArgTypes;4395 SmallVector<GNUCompatibleParamWarning, 16> Warnings;4396 const FunctionProtoType *OldProto4397 = Old->getType()->getAs<FunctionProtoType>();4398 const FunctionProtoType *NewProto4399 = New->getType()->getAs<FunctionProtoType>();4400 4401 // Determine whether this is the GNU C extension.4402 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),4403 NewProto->getReturnType());4404 bool LooseCompatible = !MergedReturn.isNull();4405 for (unsigned Idx = 0, End = Old->getNumParams();4406 LooseCompatible && Idx != End; ++Idx) {4407 ParmVarDecl *OldParm = Old->getParamDecl(Idx);4408 ParmVarDecl *NewParm = New->getParamDecl(Idx);4409 if (Context.typesAreCompatible(OldParm->getType(),4410 NewProto->getParamType(Idx))) {4411 ArgTypes.push_back(NewParm->getType());4412 } else if (Context.typesAreCompatible(OldParm->getType(),4413 NewParm->getType(),4414 /*CompareUnqualified=*/true)) {4415 GNUCompatibleParamWarning Warn = { OldParm, NewParm,4416 NewProto->getParamType(Idx) };4417 Warnings.push_back(Warn);4418 ArgTypes.push_back(NewParm->getType());4419 } else4420 LooseCompatible = false;4421 }4422 4423 if (LooseCompatible) {4424 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {4425 Diag(Warnings[Warn].NewParm->getLocation(),4426 diag::ext_param_promoted_not_compatible_with_prototype)4427 << Warnings[Warn].PromotedType4428 << Warnings[Warn].OldParm->getType();4429 if (Warnings[Warn].OldParm->getLocation().isValid())4430 Diag(Warnings[Warn].OldParm->getLocation(),4431 diag::note_previous_declaration);4432 }4433 4434 if (MergeTypeWithOld)4435 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,4436 OldProto->getExtProtoInfo()));4437 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);4438 }4439 4440 // Fall through to diagnose conflicting types.4441 }4442 4443 // A function that has already been declared has been redeclared or4444 // defined with a different type; show an appropriate diagnostic.4445 4446 // If the previous declaration was an implicitly-generated builtin4447 // declaration, then at the very least we should use a specialized note.4448 unsigned BuiltinID;4449 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {4450 // If it's actually a library-defined builtin function like 'malloc'4451 // or 'printf', just warn about the incompatible redeclaration.4452 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {4453 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;4454 Diag(OldLocation, diag::note_previous_builtin_declaration)4455 << Old << Old->getType();4456 return false;4457 }4458 4459 PrevDiag = diag::note_previous_builtin_declaration;4460 }4461 4462 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();4463 Diag(OldLocation, PrevDiag) << Old << Old->getType();4464 return true;4465}4466 4467bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,4468 Scope *S, bool MergeTypeWithOld) {4469 // Merge the attributes4470 mergeDeclAttributes(New, Old);4471 4472 // Merge "pure" flag.4473 if (Old->isPureVirtual())4474 New->setIsPureVirtual();4475 4476 // Merge "used" flag.4477 if (Old->getMostRecentDecl()->isUsed(false))4478 New->setIsUsed();4479 4480 // Merge attributes from the parameters. These can mismatch with K&R4481 // declarations.4482 if (New->getNumParams() == Old->getNumParams())4483 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {4484 ParmVarDecl *NewParam = New->getParamDecl(i);4485 ParmVarDecl *OldParam = Old->getParamDecl(i);4486 mergeParamDeclAttributes(NewParam, OldParam, *this);4487 mergeParamDeclTypes(NewParam, OldParam, *this);4488 }4489 4490 if (getLangOpts().CPlusPlus)4491 return MergeCXXFunctionDecl(New, Old, S);4492 4493 // Merge the function types so the we get the composite types for the return4494 // and argument types. Per C11 6.2.7/4, only update the type if the old decl4495 // was visible.4496 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());4497 if (!Merged.isNull() && MergeTypeWithOld)4498 New->setType(Merged);4499 4500 return false;4501}4502 4503void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,4504 ObjCMethodDecl *oldMethod) {4505 // Merge the attributes, including deprecated/unavailable4506 AvailabilityMergeKind MergeKind =4507 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())4508 ? (oldMethod->isOptional()4509 ? AvailabilityMergeKind::OptionalProtocolImplementation4510 : AvailabilityMergeKind::ProtocolImplementation)4511 : isa<ObjCImplDecl>(newMethod->getDeclContext())4512 ? AvailabilityMergeKind::Redeclaration4513 : AvailabilityMergeKind::Override;4514 4515 mergeDeclAttributes(newMethod, oldMethod, MergeKind);4516 4517 // Merge attributes from the parameters.4518 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),4519 oe = oldMethod->param_end();4520 for (ObjCMethodDecl::param_iterator4521 ni = newMethod->param_begin(), ne = newMethod->param_end();4522 ni != ne && oi != oe; ++ni, ++oi)4523 mergeParamDeclAttributes(*ni, *oi, *this);4524 4525 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);4526}4527 4528static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {4529 assert(!S.Context.hasSameType(New->getType(), Old->getType()));4530 4531 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()4532 ? diag::err_redefinition_different_type4533 : diag::err_redeclaration_different_type)4534 << New->getDeclName() << New->getType() << Old->getType();4535 4536 diag::kind PrevDiag;4537 SourceLocation OldLocation;4538 std::tie(PrevDiag, OldLocation)4539 = getNoteDiagForInvalidRedeclaration(Old, New);4540 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();4541 New->setInvalidDecl();4542}4543 4544void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,4545 bool MergeTypeWithOld) {4546 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())4547 return;4548 4549 QualType MergedT;4550 if (getLangOpts().CPlusPlus) {4551 if (New->getType()->isUndeducedType()) {4552 // We don't know what the new type is until the initializer is attached.4553 return;4554 } else if (Context.hasSameType(New->getType(), Old->getType())) {4555 // These could still be something that needs exception specs checked.4556 return MergeVarDeclExceptionSpecs(New, Old);4557 }4558 // C++ [basic.link]p10:4559 // [...] the types specified by all declarations referring to a given4560 // object or function shall be identical, except that declarations for an4561 // array object can specify array types that differ by the presence or4562 // absence of a major array bound (8.3.4).4563 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {4564 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());4565 const ArrayType *NewArray = Context.getAsArrayType(New->getType());4566 4567 // We are merging a variable declaration New into Old. If it has an array4568 // bound, and that bound differs from Old's bound, we should diagnose the4569 // mismatch.4570 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {4571 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;4572 PrevVD = PrevVD->getPreviousDecl()) {4573 QualType PrevVDTy = PrevVD->getType();4574 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())4575 continue;4576 4577 if (!Context.hasSameType(New->getType(), PrevVDTy))4578 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);4579 }4580 }4581 4582 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {4583 if (Context.hasSameType(OldArray->getElementType(),4584 NewArray->getElementType()))4585 MergedT = New->getType();4586 }4587 // FIXME: Check visibility. New is hidden but has a complete type. If New4588 // has no array bound, it should not inherit one from Old, if Old is not4589 // visible.4590 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {4591 if (Context.hasSameType(OldArray->getElementType(),4592 NewArray->getElementType()))4593 MergedT = Old->getType();4594 }4595 }4596 else if (New->getType()->isObjCObjectPointerType() &&4597 Old->getType()->isObjCObjectPointerType()) {4598 MergedT = Context.mergeObjCGCQualifiers(New->getType(),4599 Old->getType());4600 }4601 } else {4602 // C 6.2.7p2:4603 // All declarations that refer to the same object or function shall have4604 // compatible type.4605 MergedT = Context.mergeTypes(New->getType(), Old->getType());4606 }4607 if (MergedT.isNull()) {4608 // It's OK if we couldn't merge types if either type is dependent, for a4609 // block-scope variable. In other cases (static data members of class4610 // templates, variable templates, ...), we require the types to be4611 // equivalent.4612 // FIXME: The C++ standard doesn't say anything about this.4613 if ((New->getType()->isDependentType() ||4614 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {4615 // If the old type was dependent, we can't merge with it, so the new type4616 // becomes dependent for now. We'll reproduce the original type when we4617 // instantiate the TypeSourceInfo for the variable.4618 if (!New->getType()->isDependentType() && MergeTypeWithOld)4619 New->setType(Context.DependentTy);4620 return;4621 }4622 return diagnoseVarDeclTypeMismatch(*this, New, Old);4623 }4624 4625 // Don't actually update the type on the new declaration if the old4626 // declaration was an extern declaration in a different scope.4627 if (MergeTypeWithOld)4628 New->setType(MergedT);4629}4630 4631static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,4632 LookupResult &Previous) {4633 // C11 6.2.7p4:4634 // For an identifier with internal or external linkage declared4635 // in a scope in which a prior declaration of that identifier is4636 // visible, if the prior declaration specifies internal or4637 // external linkage, the type of the identifier at the later4638 // declaration becomes the composite type.4639 //4640 // If the variable isn't visible, we do not merge with its type.4641 if (Previous.isShadowed())4642 return false;4643 4644 if (S.getLangOpts().CPlusPlus) {4645 // C++11 [dcl.array]p3:4646 // If there is a preceding declaration of the entity in the same4647 // scope in which the bound was specified, an omitted array bound4648 // is taken to be the same as in that earlier declaration.4649 return NewVD->isPreviousDeclInSameBlockScope() ||4650 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&4651 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());4652 } else {4653 // If the old declaration was function-local, don't merge with its4654 // type unless we're in the same function.4655 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||4656 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();4657 }4658}4659 4660void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {4661 // If the new decl is already invalid, don't do any other checking.4662 if (New->isInvalidDecl())4663 return;4664 4665 if (!shouldLinkPossiblyHiddenDecl(Previous, New))4666 return;4667 4668 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();4669 4670 // Verify the old decl was also a variable or variable template.4671 VarDecl *Old = nullptr;4672 VarTemplateDecl *OldTemplate = nullptr;4673 if (Previous.isSingleResult()) {4674 if (NewTemplate) {4675 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());4676 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;4677 4678 if (auto *Shadow =4679 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))4680 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))4681 return New->setInvalidDecl();4682 } else {4683 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());4684 4685 if (auto *Shadow =4686 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))4687 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))4688 return New->setInvalidDecl();4689 }4690 }4691 if (!Old) {4692 Diag(New->getLocation(), diag::err_redefinition_different_kind)4693 << New->getDeclName();4694 notePreviousDefinition(Previous.getRepresentativeDecl(),4695 New->getLocation());4696 return New->setInvalidDecl();4697 }4698 4699 // If the old declaration was found in an inline namespace and the new4700 // declaration was qualified, update the DeclContext to match.4701 adjustDeclContextForDeclaratorDecl(New, Old);4702 4703 // Ensure the template parameters are compatible.4704 if (NewTemplate &&4705 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),4706 OldTemplate->getTemplateParameters(),4707 /*Complain=*/true, TPL_TemplateMatch))4708 return New->setInvalidDecl();4709 4710 // C++ [class.mem]p1:4711 // A member shall not be declared twice in the member-specification [...]4712 //4713 // Here, we need only consider static data members.4714 if (Old->isStaticDataMember() && !New->isOutOfLine()) {4715 Diag(New->getLocation(), diag::err_duplicate_member)4716 << New->getIdentifier();4717 Diag(Old->getLocation(), diag::note_previous_declaration);4718 New->setInvalidDecl();4719 }4720 4721 mergeDeclAttributes(New, Old);4722 // Warn if an already-defined variable is made a weak_import in a subsequent4723 // declaration4724 if (New->hasAttr<WeakImportAttr>())4725 for (auto *D = Old; D; D = D->getPreviousDecl()) {4726 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {4727 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();4728 Diag(D->getLocation(), diag::note_previous_definition);4729 // Remove weak_import attribute on new declaration.4730 New->dropAttr<WeakImportAttr>();4731 break;4732 }4733 }4734 4735 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())4736 if (!Old->hasAttr<InternalLinkageAttr>()) {4737 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)4738 << ILA;4739 Diag(Old->getLocation(), diag::note_previous_declaration);4740 New->dropAttr<InternalLinkageAttr>();4741 }4742 4743 // Merge the types.4744 VarDecl *MostRecent = Old->getMostRecentDecl();4745 if (MostRecent != Old) {4746 MergeVarDeclTypes(New, MostRecent,4747 mergeTypeWithPrevious(*this, New, MostRecent, Previous));4748 if (New->isInvalidDecl())4749 return;4750 }4751 4752 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));4753 if (New->isInvalidDecl())4754 return;4755 4756 diag::kind PrevDiag;4757 SourceLocation OldLocation;4758 std::tie(PrevDiag, OldLocation) =4759 getNoteDiagForInvalidRedeclaration(Old, New);4760 4761 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.4762 if (New->getStorageClass() == SC_Static &&4763 !New->isStaticDataMember() &&4764 Old->hasExternalFormalLinkage()) {4765 if (getLangOpts().MicrosoftExt) {4766 Diag(New->getLocation(), diag::ext_static_non_static)4767 << New->getDeclName();4768 Diag(OldLocation, PrevDiag);4769 } else {4770 Diag(New->getLocation(), diag::err_static_non_static)4771 << New->getDeclName();4772 Diag(OldLocation, PrevDiag);4773 return New->setInvalidDecl();4774 }4775 }4776 // C99 6.2.2p4:4777 // For an identifier declared with the storage-class specifier4778 // extern in a scope in which a prior declaration of that4779 // identifier is visible,23) if the prior declaration specifies4780 // internal or external linkage, the linkage of the identifier at4781 // the later declaration is the same as the linkage specified at4782 // the prior declaration. If no prior declaration is visible, or4783 // if the prior declaration specifies no linkage, then the4784 // identifier has external linkage.4785 if (New->hasExternalStorage() && Old->hasLinkage())4786 /* Okay */;4787 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&4788 !New->isStaticDataMember() &&4789 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {4790 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();4791 Diag(OldLocation, PrevDiag);4792 return New->setInvalidDecl();4793 }4794 4795 // Check if extern is followed by non-extern and vice-versa.4796 if (New->hasExternalStorage() &&4797 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {4798 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();4799 Diag(OldLocation, PrevDiag);4800 return New->setInvalidDecl();4801 }4802 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&4803 !New->hasExternalStorage()) {4804 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();4805 Diag(OldLocation, PrevDiag);4806 return New->setInvalidDecl();4807 }4808 4809 if (CheckRedeclarationInModule(New, Old))4810 return;4811 4812 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.4813 4814 // FIXME: The test for external storage here seems wrong? We still4815 // need to check for mismatches.4816 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&4817 // Don't complain about out-of-line definitions of static members.4818 !(Old->getLexicalDeclContext()->isRecord() &&4819 !New->getLexicalDeclContext()->isRecord())) {4820 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();4821 Diag(OldLocation, PrevDiag);4822 return New->setInvalidDecl();4823 }4824 4825 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {4826 if (VarDecl *Def = Old->getDefinition()) {4827 // C++1z [dcl.fcn.spec]p4:4828 // If the definition of a variable appears in a translation unit before4829 // its first declaration as inline, the program is ill-formed.4830 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;4831 Diag(Def->getLocation(), diag::note_previous_definition);4832 }4833 }4834 4835 // If this redeclaration makes the variable inline, we may need to add it to4836 // UndefinedButUsed.4837 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&4838 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&4839 !Old->isInAnotherModuleUnit())4840 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),4841 SourceLocation()));4842 4843 if (New->getTLSKind() != Old->getTLSKind()) {4844 if (!Old->getTLSKind()) {4845 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();4846 Diag(OldLocation, PrevDiag);4847 } else if (!New->getTLSKind()) {4848 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();4849 Diag(OldLocation, PrevDiag);4850 } else {4851 // Do not allow redeclaration to change the variable between requiring4852 // static and dynamic initialization.4853 // FIXME: GCC allows this, but uses the TLS keyword on the first4854 // declaration to determine the kind. Do we need to be compatible here?4855 Diag(New->getLocation(), diag::err_thread_thread_different_kind)4856 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);4857 Diag(OldLocation, PrevDiag);4858 }4859 }4860 4861 // C++ doesn't have tentative definitions, so go right ahead and check here.4862 if (getLangOpts().CPlusPlus) {4863 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&4864 Old->getCanonicalDecl()->isConstexpr()) {4865 // This definition won't be a definition any more once it's been merged.4866 Diag(New->getLocation(),4867 diag::warn_deprecated_redundant_constexpr_static_def);4868 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {4869 VarDecl *Def = Old->getDefinition();4870 if (Def && checkVarDeclRedefinition(Def, New))4871 return;4872 }4873 } else {4874 // C++ may not have a tentative definition rule, but it has a different4875 // rule about what constitutes a definition in the first place. See4876 // [basic.def]p2 for details, but the basic idea is: if the old declaration4877 // contains the extern specifier and doesn't have an initializer, it's fine4878 // in C++.4879 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {4880 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)4881 << New;4882 Diag(Old->getLocation(), diag::note_previous_declaration);4883 }4884 }4885 4886 if (haveIncompatibleLanguageLinkages(Old, New)) {4887 Diag(New->getLocation(), diag::err_different_language_linkage) << New;4888 Diag(OldLocation, PrevDiag);4889 New->setInvalidDecl();4890 return;4891 }4892 4893 // Merge "used" flag.4894 if (Old->getMostRecentDecl()->isUsed(false))4895 New->setIsUsed();4896 4897 // Keep a chain of previous declarations.4898 New->setPreviousDecl(Old);4899 if (NewTemplate)4900 NewTemplate->setPreviousDecl(OldTemplate);4901 4902 // Inherit access appropriately.4903 New->setAccess(Old->getAccess());4904 if (NewTemplate)4905 NewTemplate->setAccess(New->getAccess());4906 4907 if (Old->isInline())4908 New->setImplicitlyInline();4909}4910 4911void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {4912 SourceManager &SrcMgr = getSourceManager();4913 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);4914 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());4915 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);4916 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);4917 auto &HSI = PP.getHeaderSearchInfo();4918 StringRef HdrFilename =4919 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));4920 4921 auto noteFromModuleOrInclude = [&](Module *Mod,4922 SourceLocation IncLoc) -> bool {4923 // Redefinition errors with modules are common with non modular mapped4924 // headers, example: a non-modular header H in module A that also gets4925 // included directly in a TU. Pointing twice to the same header/definition4926 // is confusing, try to get better diagnostics when modules is on.4927 if (IncLoc.isValid()) {4928 if (Mod) {4929 Diag(IncLoc, diag::note_redefinition_modules_same_file)4930 << HdrFilename.str() << Mod->getFullModuleName();4931 if (!Mod->DefinitionLoc.isInvalid())4932 Diag(Mod->DefinitionLoc, diag::note_defined_here)4933 << Mod->getFullModuleName();4934 } else {4935 Diag(IncLoc, diag::note_redefinition_include_same_file)4936 << HdrFilename.str();4937 }4938 return true;4939 }4940 4941 return false;4942 };4943 4944 // Is it the same file and same offset? Provide more information on why4945 // this leads to a redefinition error.4946 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {4947 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);4948 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);4949 bool EmittedDiag =4950 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);4951 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);4952 4953 // If the header has no guards, emit a note suggesting one.4954 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))4955 Diag(Old->getLocation(), diag::note_use_ifdef_guards);4956 4957 if (EmittedDiag)4958 return;4959 }4960 4961 // Redefinition coming from different files or couldn't do better above.4962 if (Old->getLocation().isValid())4963 Diag(Old->getLocation(), diag::note_previous_definition);4964}4965 4966bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {4967 if (!hasVisibleDefinition(Old) &&4968 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||4969 isa<VarTemplateSpecializationDecl>(New) ||4970 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||4971 New->getDeclContext()->isDependentContext() ||4972 New->hasAttr<SelectAnyAttr>())) {4973 // The previous definition is hidden, and multiple definitions are4974 // permitted (in separate TUs). Demote this to a declaration.4975 New->demoteThisDefinitionToDeclaration();4976 4977 // Make the canonical definition visible.4978 if (auto *OldTD = Old->getDescribedVarTemplate())4979 makeMergedDefinitionVisible(OldTD);4980 makeMergedDefinitionVisible(Old);4981 return false;4982 } else {4983 Diag(New->getLocation(), diag::err_redefinition) << New;4984 notePreviousDefinition(Old, New->getLocation());4985 New->setInvalidDecl();4986 return true;4987 }4988}4989 4990Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,4991 DeclSpec &DS,4992 const ParsedAttributesView &DeclAttrs,4993 RecordDecl *&AnonRecord) {4994 return ParsedFreeStandingDeclSpec(4995 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);4996}4997 4998// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to4999// disambiguate entities defined in different scopes.5000// While the VS2015 ABI fixes potential miscompiles, it is also breaks5001// compatibility.5002// We will pick our mangling number depending on which version of MSVC is being5003// targeted.5004static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {5005 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)5006 ? S->getMSCurManglingNumber()5007 : S->getMSLastManglingNumber();5008}5009 5010void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {5011 if (!Context.getLangOpts().CPlusPlus)5012 return;5013 5014 if (isa<CXXRecordDecl>(Tag->getParent())) {5015 // If this tag is the direct child of a class, number it if5016 // it is anonymous.5017 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())5018 return;5019 MangleNumberingContext &MCtx =5020 Context.getManglingNumberContext(Tag->getParent());5021 Context.setManglingNumber(5022 Tag, MCtx.getManglingNumber(5023 Tag, getMSManglingNumber(getLangOpts(), TagScope)));5024 return;5025 }5026 5027 // If this tag isn't a direct child of a class, number it if it is local.5028 MangleNumberingContext *MCtx;5029 Decl *ManglingContextDecl;5030 std::tie(MCtx, ManglingContextDecl) =5031 getCurrentMangleNumberContext(Tag->getDeclContext());5032 if (MCtx) {5033 Context.setManglingNumber(5034 Tag, MCtx->getManglingNumber(5035 Tag, getMSManglingNumber(getLangOpts(), TagScope)));5036 }5037}5038 5039namespace {5040struct NonCLikeKind {5041 enum {5042 None,5043 BaseClass,5044 DefaultMemberInit,5045 Lambda,5046 Friend,5047 OtherMember,5048 Invalid,5049 } Kind = None;5050 SourceRange Range;5051 5052 explicit operator bool() { return Kind != None; }5053};5054}5055 5056/// Determine whether a class is C-like, according to the rules of C++5057/// [dcl.typedef] for anonymous classes with typedef names for linkage.5058static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {5059 if (RD->isInvalidDecl())5060 return {NonCLikeKind::Invalid, {}};5061 5062 // C++ [dcl.typedef]p9: [P1766R1]5063 // An unnamed class with a typedef name for linkage purposes shall not5064 //5065 // -- have any base classes5066 if (RD->getNumBases())5067 return {NonCLikeKind::BaseClass,5068 SourceRange(RD->bases_begin()->getBeginLoc(),5069 RD->bases_end()[-1].getEndLoc())};5070 bool Invalid = false;5071 for (Decl *D : RD->decls()) {5072 // Don't complain about things we already diagnosed.5073 if (D->isInvalidDecl()) {5074 Invalid = true;5075 continue;5076 }5077 5078 // -- have any [...] default member initializers5079 if (auto *FD = dyn_cast<FieldDecl>(D)) {5080 if (FD->hasInClassInitializer()) {5081 auto *Init = FD->getInClassInitializer();5082 return {NonCLikeKind::DefaultMemberInit,5083 Init ? Init->getSourceRange() : D->getSourceRange()};5084 }5085 continue;5086 }5087 5088 // FIXME: We don't allow friend declarations. This violates the wording of5089 // P1766, but not the intent.5090 if (isa<FriendDecl>(D))5091 return {NonCLikeKind::Friend, D->getSourceRange()};5092 5093 // -- declare any members other than non-static data members, member5094 // enumerations, or member classes,5095 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||5096 isa<EnumDecl>(D))5097 continue;5098 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);5099 if (!MemberRD) {5100 if (D->isImplicit())5101 continue;5102 return {NonCLikeKind::OtherMember, D->getSourceRange()};5103 }5104 5105 // -- contain a lambda-expression,5106 if (MemberRD->isLambda())5107 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};5108 5109 // and all member classes shall also satisfy these requirements5110 // (recursively).5111 if (MemberRD->isThisDeclarationADefinition()) {5112 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))5113 return Kind;5114 }5115 }5116 5117 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};5118}5119 5120void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,5121 TypedefNameDecl *NewTD) {5122 if (TagFromDeclSpec->isInvalidDecl())5123 return;5124 5125 // Do nothing if the tag already has a name for linkage purposes.5126 if (TagFromDeclSpec->hasNameForLinkage())5127 return;5128 5129 // A well-formed anonymous tag must always be a TagUseKind::Definition.5130 assert(TagFromDeclSpec->isThisDeclarationADefinition());5131 5132 // The type must match the tag exactly; no qualifiers allowed.5133 if (!Context.hasSameType(NewTD->getUnderlyingType(),5134 Context.getCanonicalTagType(TagFromDeclSpec))) {5135 if (getLangOpts().CPlusPlus)5136 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);5137 return;5138 }5139 5140 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]5141 // An unnamed class with a typedef name for linkage purposes shall [be5142 // C-like].5143 //5144 // FIXME: Also diagnose if we've already computed the linkage. That ideally5145 // shouldn't happen, but there are constructs that the language rule doesn't5146 // disallow for which we can't reasonably avoid computing linkage early.5147 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);5148 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)5149 : NonCLikeKind();5150 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();5151 if (NonCLike || ChangesLinkage) {5152 if (NonCLike.Kind == NonCLikeKind::Invalid)5153 return;5154 5155 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;5156 if (ChangesLinkage) {5157 // If the linkage changes, we can't accept this as an extension.5158 if (NonCLike.Kind == NonCLikeKind::None)5159 DiagID = diag::err_typedef_changes_linkage;5160 else5161 DiagID = diag::err_non_c_like_anon_struct_in_typedef;5162 }5163 5164 SourceLocation FixitLoc =5165 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());5166 llvm::SmallString<40> TextToInsert;5167 TextToInsert += ' ';5168 TextToInsert += NewTD->getIdentifier()->getName();5169 5170 Diag(FixitLoc, DiagID)5171 << isa<TypeAliasDecl>(NewTD)5172 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);5173 if (NonCLike.Kind != NonCLikeKind::None) {5174 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)5175 << NonCLike.Kind - 1 << NonCLike.Range;5176 }5177 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)5178 << NewTD << isa<TypeAliasDecl>(NewTD);5179 5180 if (ChangesLinkage)5181 return;5182 }5183 5184 // Otherwise, set this as the anon-decl typedef for the tag.5185 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);5186 5187 // Now that we have a name for the tag, process API notes again.5188 ProcessAPINotes(TagFromDeclSpec);5189}5190 5191static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {5192 DeclSpec::TST T = DS.getTypeSpecType();5193 switch (T) {5194 case DeclSpec::TST_class:5195 return 0;5196 case DeclSpec::TST_struct:5197 return 1;5198 case DeclSpec::TST_interface:5199 return 2;5200 case DeclSpec::TST_union:5201 return 3;5202 case DeclSpec::TST_enum:5203 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {5204 if (ED->isScopedUsingClassTag())5205 return 5;5206 if (ED->isScoped())5207 return 6;5208 }5209 return 4;5210 default:5211 llvm_unreachable("unexpected type specifier");5212 }5213}5214 5215Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,5216 DeclSpec &DS,5217 const ParsedAttributesView &DeclAttrs,5218 MultiTemplateParamsArg TemplateParams,5219 bool IsExplicitInstantiation,5220 RecordDecl *&AnonRecord,5221 SourceLocation EllipsisLoc) {5222 Decl *TagD = nullptr;5223 TagDecl *Tag = nullptr;5224 if (DS.getTypeSpecType() == DeclSpec::TST_class ||5225 DS.getTypeSpecType() == DeclSpec::TST_struct ||5226 DS.getTypeSpecType() == DeclSpec::TST_interface ||5227 DS.getTypeSpecType() == DeclSpec::TST_union ||5228 DS.getTypeSpecType() == DeclSpec::TST_enum) {5229 TagD = DS.getRepAsDecl();5230 5231 if (!TagD) // We probably had an error5232 return nullptr;5233 5234 // Note that the above type specs guarantee that the5235 // type rep is a Decl, whereas in many of the others5236 // it's a Type.5237 if (isa<TagDecl>(TagD))5238 Tag = cast<TagDecl>(TagD);5239 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))5240 Tag = CTD->getTemplatedDecl();5241 }5242 5243 if (Tag) {5244 handleTagNumbering(Tag, S);5245 Tag->setFreeStanding();5246 if (Tag->isInvalidDecl())5247 return Tag;5248 }5249 5250 if (unsigned TypeQuals = DS.getTypeQualifiers()) {5251 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object5252 // or incomplete types shall not be restrict-qualified."5253 if (TypeQuals & DeclSpec::TQ_restrict)5254 Diag(DS.getRestrictSpecLoc(),5255 diag::err_typecheck_invalid_restrict_not_pointer_noarg)5256 << DS.getSourceRange();5257 }5258 5259 if (DS.isInlineSpecified())5260 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)5261 << getLangOpts().CPlusPlus17;5262 5263 if (DS.hasConstexprSpecifier()) {5264 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations5265 // and definitions of functions and variables.5266 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to5267 // the declaration of a function or function template5268 if (Tag)5269 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)5270 << GetDiagnosticTypeSpecifierID(DS)5271 << static_cast<int>(DS.getConstexprSpecifier());5272 else if (getLangOpts().C23)5273 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);5274 else5275 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)5276 << static_cast<int>(DS.getConstexprSpecifier());5277 // Don't emit warnings after this error.5278 return TagD;5279 }5280 5281 DiagnoseFunctionSpecifiers(DS);5282 5283 if (DS.isFriendSpecified()) {5284 // If we're dealing with a decl but not a TagDecl, assume that5285 // whatever routines created it handled the friendship aspect.5286 if (TagD && !Tag)5287 return nullptr;5288 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);5289 }5290 5291 assert(EllipsisLoc.isInvalid() &&5292 "Friend ellipsis but not friend-specified?");5293 5294 // Track whether this decl-specifier declares anything.5295 bool DeclaresAnything = true;5296 5297 // Handle anonymous struct definitions.5298 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {5299 if (!Record->getDeclName() && Record->isCompleteDefinition() &&5300 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {5301 if (getLangOpts().CPlusPlus ||5302 Record->getDeclContext()->isRecord()) {5303 // If CurContext is a DeclContext that can contain statements,5304 // RecursiveASTVisitor won't visit the decls that5305 // BuildAnonymousStructOrUnion() will put into CurContext.5306 // Also store them here so that they can be part of the5307 // DeclStmt that gets created in this case.5308 // FIXME: Also return the IndirectFieldDecls created by5309 // BuildAnonymousStructOr union, for the same reason?5310 if (CurContext->isFunctionOrMethod())5311 AnonRecord = Record;5312 return BuildAnonymousStructOrUnion(S, DS, AS, Record,5313 Context.getPrintingPolicy());5314 }5315 5316 DeclaresAnything = false;5317 }5318 }5319 5320 // C11 6.7.2.1p2:5321 // A struct-declaration that does not declare an anonymous structure or5322 // anonymous union shall contain a struct-declarator-list.5323 //5324 // This rule also existed in C89 and C99; the grammar for struct-declaration5325 // did not permit a struct-declaration without a struct-declarator-list.5326 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&5327 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {5328 // Check for Microsoft C extension: anonymous struct/union member.5329 // Handle 2 kinds of anonymous struct/union:5330 // struct STRUCT;5331 // union UNION;5332 // and5333 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.5334 // UNION_TYPE; <- where UNION_TYPE is a typedef union.5335 if ((Tag && Tag->getDeclName()) ||5336 DS.getTypeSpecType() == DeclSpec::TST_typename) {5337 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)5338 : DS.getRepAsType().get()->getAsRecordDecl();5339 if (Record && getLangOpts().MicrosoftExt) {5340 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)5341 << Record->isUnion() << DS.getSourceRange();5342 return BuildMicrosoftCAnonymousStruct(S, DS, Record);5343 }5344 5345 DeclaresAnything = false;5346 }5347 }5348 5349 // Skip all the checks below if we have a type error.5350 if (DS.getTypeSpecType() == DeclSpec::TST_error ||5351 (TagD && TagD->isInvalidDecl()))5352 return TagD;5353 5354 if (getLangOpts().CPlusPlus &&5355 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)5356 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))5357 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&5358 !Enum->isInvalidDecl())5359 DeclaresAnything = false;5360 5361 if (!DS.isMissingDeclaratorOk()) {5362 // Customize diagnostic for a typedef missing a name.5363 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)5364 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)5365 << DS.getSourceRange();5366 else5367 DeclaresAnything = false;5368 }5369 5370 if (DS.isModulePrivateSpecified() &&5371 Tag && Tag->getDeclContext()->isFunctionOrMethod())5372 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)5373 << Tag->getTagKind()5374 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());5375 5376 ActOnDocumentableDecl(TagD);5377 5378 // C 6.7/2:5379 // A declaration [...] shall declare at least a declarator [...], a tag,5380 // or the members of an enumeration.5381 // C++ [dcl.dcl]p3:5382 // [If there are no declarators], and except for the declaration of an5383 // unnamed bit-field, the decl-specifier-seq shall introduce one or more5384 // names into the program, or shall redeclare a name introduced by a5385 // previous declaration.5386 if (!DeclaresAnything) {5387 // In C, we allow this as a (popular) extension / bug. Don't bother5388 // producing further diagnostics for redundant qualifiers after this.5389 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())5390 ? diag::err_no_declarators5391 : diag::ext_no_declarators)5392 << DS.getSourceRange();5393 return TagD;5394 }5395 5396 // C++ [dcl.stc]p1:5397 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the5398 // init-declarator-list of the declaration shall not be empty.5399 // C++ [dcl.fct.spec]p1:5400 // If a cv-qualifier appears in a decl-specifier-seq, the5401 // init-declarator-list of the declaration shall not be empty.5402 //5403 // Spurious qualifiers here appear to be valid in C.5404 unsigned DiagID = diag::warn_standalone_specifier;5405 if (getLangOpts().CPlusPlus)5406 DiagID = diag::ext_standalone_specifier;5407 5408 // Note that a linkage-specification sets a storage class, but5409 // 'extern "C" struct foo;' is actually valid and not theoretically5410 // useless.5411 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {5412 if (SCS == DeclSpec::SCS_mutable)5413 // Since mutable is not a viable storage class specifier in C, there is5414 // no reason to treat it as an extension. Instead, diagnose as an error.5415 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);5416 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)5417 Diag(DS.getStorageClassSpecLoc(), DiagID)5418 << DeclSpec::getSpecifierName(SCS);5419 }5420 5421 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())5422 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)5423 << DeclSpec::getSpecifierName(TSCS);5424 if (DS.getTypeQualifiers()) {5425 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)5426 Diag(DS.getConstSpecLoc(), DiagID) << "const";5427 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)5428 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";5429 // Restrict is covered above.5430 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)5431 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";5432 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)5433 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";5434 }5435 5436 // Warn about ignored type attributes, for example:5437 // __attribute__((aligned)) struct A;5438 // Attributes should be placed after tag to apply to type declaration.5439 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {5440 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();5441 if (TypeSpecType == DeclSpec::TST_class ||5442 TypeSpecType == DeclSpec::TST_struct ||5443 TypeSpecType == DeclSpec::TST_interface ||5444 TypeSpecType == DeclSpec::TST_union ||5445 TypeSpecType == DeclSpec::TST_enum) {5446 5447 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {5448 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;5449 if (AL.isAlignas() && !getLangOpts().CPlusPlus)5450 DiagnosticId = diag::warn_attribute_ignored;5451 else if (AL.isRegularKeywordAttribute())5452 DiagnosticId = diag::err_declspec_keyword_has_no_effect;5453 else5454 DiagnosticId = diag::warn_declspec_attribute_ignored;5455 Diag(AL.getLoc(), DiagnosticId)5456 << AL << GetDiagnosticTypeSpecifierID(DS);5457 };5458 5459 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);5460 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);5461 }5462 }5463 5464 return TagD;5465}5466 5467/// We are trying to inject an anonymous member into the given scope;5468/// check if there's an existing declaration that can't be overloaded.5469///5470/// \return true if this is a forbidden redeclaration5471static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,5472 DeclContext *Owner,5473 DeclarationName Name,5474 SourceLocation NameLoc, bool IsUnion,5475 StorageClass SC) {5476 LookupResult R(SemaRef, Name, NameLoc,5477 Owner->isRecord() ? Sema::LookupMemberName5478 : Sema::LookupOrdinaryName,5479 RedeclarationKind::ForVisibleRedeclaration);5480 if (!SemaRef.LookupName(R, S)) return false;5481 5482 // Pick a representative declaration.5483 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();5484 assert(PrevDecl && "Expected a non-null Decl");5485 5486 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))5487 return false;5488 5489 if (SC == StorageClass::SC_None &&5490 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&5491 (Owner->isFunctionOrMethod() || Owner->isRecord())) {5492 if (!Owner->isRecord())5493 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);5494 return false;5495 }5496 5497 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)5498 << IsUnion << Name;5499 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);5500 5501 return true;5502}5503 5504void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {5505 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))5506 DiagPlaceholderFieldDeclDefinitions(RD);5507}5508 5509void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {5510 if (!getLangOpts().CPlusPlus)5511 return;5512 5513 // This function can be parsed before we have validated the5514 // structure as an anonymous struct5515 if (Record->isAnonymousStructOrUnion())5516 return;5517 5518 const NamedDecl *First = 0;5519 for (const Decl *D : Record->decls()) {5520 const NamedDecl *ND = dyn_cast<NamedDecl>(D);5521 if (!ND || !ND->isPlaceholderVar(getLangOpts()))5522 continue;5523 if (!First)5524 First = ND;5525 else5526 DiagPlaceholderVariableDefinition(ND->getLocation());5527 }5528}5529 5530/// InjectAnonymousStructOrUnionMembers - Inject the members of the5531/// anonymous struct or union AnonRecord into the owning context Owner5532/// and scope S. This routine will be invoked just after we realize5533/// that an unnamed union or struct is actually an anonymous union or5534/// struct, e.g.,5535///5536/// @code5537/// union {5538/// int i;5539/// float f;5540/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and5541/// // f into the surrounding scope.x5542/// @endcode5543///5544/// This routine is recursive, injecting the names of nested anonymous5545/// structs/unions into the owning context and scope as well.5546static bool5547InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,5548 RecordDecl *AnonRecord, AccessSpecifier AS,5549 StorageClass SC,5550 SmallVectorImpl<NamedDecl *> &Chaining) {5551 bool Invalid = false;5552 5553 // Look every FieldDecl and IndirectFieldDecl with a name.5554 for (auto *D : AnonRecord->decls()) {5555 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&5556 cast<NamedDecl>(D)->getDeclName()) {5557 ValueDecl *VD = cast<ValueDecl>(D);5558 // C++ [class.union]p2:5559 // The names of the members of an anonymous union shall be5560 // distinct from the names of any other entity in the5561 // scope in which the anonymous union is declared.5562 5563 bool FieldInvalid = CheckAnonMemberRedeclaration(5564 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),5565 AnonRecord->isUnion(), SC);5566 if (FieldInvalid)5567 Invalid = true;5568 5569 // Inject the IndirectFieldDecl even if invalid, because later5570 // diagnostics may depend on it being present, see findDefaultInitializer.5571 5572 // C++ [class.union]p2:5573 // For the purpose of name lookup, after the anonymous union5574 // definition, the members of the anonymous union are5575 // considered to have been defined in the scope in which the5576 // anonymous union is declared.5577 unsigned OldChainingSize = Chaining.size();5578 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))5579 Chaining.append(IF->chain_begin(), IF->chain_end());5580 else5581 Chaining.push_back(VD);5582 5583 assert(Chaining.size() >= 2);5584 NamedDecl **NamedChain =5585 new (SemaRef.Context) NamedDecl *[Chaining.size()];5586 for (unsigned i = 0; i < Chaining.size(); i++)5587 NamedChain[i] = Chaining[i];5588 5589 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(5590 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),5591 VD->getType(), {NamedChain, Chaining.size()});5592 5593 for (const auto *Attr : VD->attrs())5594 IndirectField->addAttr(Attr->clone(SemaRef.Context));5595 5596 IndirectField->setAccess(AS);5597 IndirectField->setImplicit();5598 IndirectField->setInvalidDecl(FieldInvalid);5599 SemaRef.PushOnScopeChains(IndirectField, S);5600 5601 // That includes picking up the appropriate access specifier.5602 if (AS != AS_none)5603 IndirectField->setAccess(AS);5604 5605 Chaining.resize(OldChainingSize);5606 }5607 }5608 5609 return Invalid;5610}5611 5612/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to5613/// a VarDecl::StorageClass. Any error reporting is up to the caller:5614/// illegal input values are mapped to SC_None.5615static StorageClass5616StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {5617 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();5618 assert(StorageClassSpec != DeclSpec::SCS_typedef &&5619 "Parser allowed 'typedef' as storage class VarDecl.");5620 switch (StorageClassSpec) {5621 case DeclSpec::SCS_unspecified: return SC_None;5622 case DeclSpec::SCS_extern:5623 if (DS.isExternInLinkageSpec())5624 return SC_None;5625 return SC_Extern;5626 case DeclSpec::SCS_static: return SC_Static;5627 case DeclSpec::SCS_auto: return SC_Auto;5628 case DeclSpec::SCS_register: return SC_Register;5629 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;5630 // Illegal SCSs map to None: error reporting is up to the caller.5631 case DeclSpec::SCS_mutable: // Fall through.5632 case DeclSpec::SCS_typedef: return SC_None;5633 }5634 llvm_unreachable("unknown storage class specifier");5635}5636 5637static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {5638 assert(Record->hasInClassInitializer());5639 5640 for (const auto *I : Record->decls()) {5641 const auto *FD = dyn_cast<FieldDecl>(I);5642 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))5643 FD = IFD->getAnonField();5644 if (FD && FD->hasInClassInitializer())5645 return FD->getLocation();5646 }5647 5648 llvm_unreachable("couldn't find in-class initializer");5649}5650 5651static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,5652 SourceLocation DefaultInitLoc) {5653 if (!Parent->isUnion() || !Parent->hasInClassInitializer())5654 return;5655 5656 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);5657 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;5658}5659 5660static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,5661 CXXRecordDecl *AnonUnion) {5662 if (!Parent->isUnion() || !Parent->hasInClassInitializer())5663 return;5664 5665 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));5666}5667 5668Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,5669 AccessSpecifier AS,5670 RecordDecl *Record,5671 const PrintingPolicy &Policy) {5672 DeclContext *Owner = Record->getDeclContext();5673 5674 // Diagnose whether this anonymous struct/union is an extension.5675 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)5676 Diag(Record->getLocation(), diag::ext_anonymous_union);5677 else if (!Record->isUnion() && getLangOpts().CPlusPlus)5678 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);5679 else if (!Record->isUnion() && !getLangOpts().C11)5680 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);5681 5682 // C and C++ require different kinds of checks for anonymous5683 // structs/unions.5684 bool Invalid = false;5685 if (getLangOpts().CPlusPlus) {5686 const char *PrevSpec = nullptr;5687 if (Record->isUnion()) {5688 // C++ [class.union]p6:5689 // C++17 [class.union.anon]p2:5690 // Anonymous unions declared in a named namespace or in the5691 // global namespace shall be declared static.5692 unsigned DiagID;5693 DeclContext *OwnerScope = Owner->getRedeclContext();5694 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&5695 (OwnerScope->isTranslationUnit() ||5696 (OwnerScope->isNamespace() &&5697 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {5698 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)5699 << FixItHint::CreateInsertion(Record->getLocation(), "static ");5700 5701 // Recover by adding 'static'.5702 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),5703 PrevSpec, DiagID, Policy);5704 }5705 // C++ [class.union]p6:5706 // A storage class is not allowed in a declaration of an5707 // anonymous union in a class scope.5708 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&5709 isa<RecordDecl>(Owner)) {5710 Diag(DS.getStorageClassSpecLoc(),5711 diag::err_anonymous_union_with_storage_spec)5712 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());5713 5714 // Recover by removing the storage specifier.5715 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,5716 SourceLocation(),5717 PrevSpec, DiagID, Context.getPrintingPolicy());5718 }5719 }5720 5721 // Ignore const/volatile/restrict qualifiers.5722 if (DS.getTypeQualifiers()) {5723 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)5724 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)5725 << Record->isUnion() << "const"5726 << FixItHint::CreateRemoval(DS.getConstSpecLoc());5727 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)5728 Diag(DS.getVolatileSpecLoc(),5729 diag::ext_anonymous_struct_union_qualified)5730 << Record->isUnion() << "volatile"5731 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());5732 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)5733 Diag(DS.getRestrictSpecLoc(),5734 diag::ext_anonymous_struct_union_qualified)5735 << Record->isUnion() << "restrict"5736 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());5737 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)5738 Diag(DS.getAtomicSpecLoc(),5739 diag::ext_anonymous_struct_union_qualified)5740 << Record->isUnion() << "_Atomic"5741 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());5742 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)5743 Diag(DS.getUnalignedSpecLoc(),5744 diag::ext_anonymous_struct_union_qualified)5745 << Record->isUnion() << "__unaligned"5746 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());5747 5748 DS.ClearTypeQualifiers();5749 }5750 5751 // C++ [class.union]p2:5752 // The member-specification of an anonymous union shall only5753 // define non-static data members. [Note: nested types and5754 // functions cannot be declared within an anonymous union. ]5755 for (auto *Mem : Record->decls()) {5756 // Ignore invalid declarations; we already diagnosed them.5757 if (Mem->isInvalidDecl())5758 continue;5759 5760 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {5761 // C++ [class.union]p3:5762 // An anonymous union shall not have private or protected5763 // members (clause 11).5764 assert(FD->getAccess() != AS_none);5765 if (FD->getAccess() != AS_public) {5766 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)5767 << Record->isUnion() << (FD->getAccess() == AS_protected);5768 Invalid = true;5769 }5770 5771 // C++ [class.union]p15772 // An object of a class with a non-trivial constructor, a non-trivial5773 // copy constructor, a non-trivial destructor, or a non-trivial copy5774 // assignment operator cannot be a member of a union, nor can an5775 // array of such objects.5776 if (CheckNontrivialField(FD))5777 Invalid = true;5778 } else if (Mem->isImplicit()) {5779 // Any implicit members are fine.5780 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {5781 // This is a type that showed up in an5782 // elaborated-type-specifier inside the anonymous struct or5783 // union, but which actually declares a type outside of the5784 // anonymous struct or union. It's okay.5785 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {5786 if (!MemRecord->isAnonymousStructOrUnion() &&5787 MemRecord->getDeclName()) {5788 // Visual C++ allows type definition in anonymous struct or union.5789 if (getLangOpts().MicrosoftExt)5790 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)5791 << Record->isUnion();5792 else {5793 // This is a nested type declaration.5794 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)5795 << Record->isUnion();5796 Invalid = true;5797 }5798 } else {5799 // This is an anonymous type definition within another anonymous type.5800 // This is a popular extension, provided by Plan9, MSVC and GCC, but5801 // not part of standard C++.5802 Diag(MemRecord->getLocation(),5803 diag::ext_anonymous_record_with_anonymous_type)5804 << Record->isUnion();5805 }5806 } else if (isa<AccessSpecDecl>(Mem)) {5807 // Any access specifier is fine.5808 } else if (isa<StaticAssertDecl>(Mem)) {5809 // In C++1z, static_assert declarations are also fine.5810 } else {5811 // We have something that isn't a non-static data5812 // member. Complain about it.5813 unsigned DK = diag::err_anonymous_record_bad_member;5814 if (isa<TypeDecl>(Mem))5815 DK = diag::err_anonymous_record_with_type;5816 else if (isa<FunctionDecl>(Mem))5817 DK = diag::err_anonymous_record_with_function;5818 else if (isa<VarDecl>(Mem))5819 DK = diag::err_anonymous_record_with_static;5820 5821 // Visual C++ allows type definition in anonymous struct or union.5822 if (getLangOpts().MicrosoftExt &&5823 DK == diag::err_anonymous_record_with_type)5824 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)5825 << Record->isUnion();5826 else {5827 Diag(Mem->getLocation(), DK) << Record->isUnion();5828 Invalid = true;5829 }5830 }5831 }5832 5833 // C++11 [class.union]p8 (DR1460):5834 // At most one variant member of a union may have a5835 // brace-or-equal-initializer.5836 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&5837 Owner->isRecord())5838 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),5839 cast<CXXRecordDecl>(Record));5840 }5841 5842 if (!Record->isUnion() && !Owner->isRecord()) {5843 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)5844 << getLangOpts().CPlusPlus;5845 Invalid = true;5846 }5847 5848 // C++ [dcl.dcl]p3:5849 // [If there are no declarators], and except for the declaration of an5850 // unnamed bit-field, the decl-specifier-seq shall introduce one or more5851 // names into the program5852 // C++ [class.mem]p2:5853 // each such member-declaration shall either declare at least one member5854 // name of the class or declare at least one unnamed bit-field5855 //5856 // For C this is an error even for a named struct, and is diagnosed elsewhere.5857 if (getLangOpts().CPlusPlus && Record->field_empty())5858 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();5859 5860 // Mock up a declarator.5861 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);5862 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);5863 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc);5864 assert(TInfo && "couldn't build declarator info for anonymous struct/union");5865 5866 // Create a declaration for this anonymous struct/union.5867 NamedDecl *Anon = nullptr;5868 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {5869 Anon = FieldDecl::Create(5870 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),5871 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,5872 /*BitWidth=*/nullptr, /*Mutable=*/false,5873 /*InitStyle=*/ICIS_NoInit);5874 Anon->setAccess(AS);5875 ProcessDeclAttributes(S, Anon, Dc);5876 5877 if (getLangOpts().CPlusPlus)5878 FieldCollector->Add(cast<FieldDecl>(Anon));5879 } else {5880 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();5881 if (SCSpec == DeclSpec::SCS_mutable) {5882 // mutable can only appear on non-static class members, so it's always5883 // an error here5884 Diag(Record->getLocation(), diag::err_mutable_nonmember);5885 Invalid = true;5886 SC = SC_None;5887 }5888 5889 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),5890 Record->getLocation(), /*IdentifierInfo=*/nullptr,5891 Context.getCanonicalTagType(Record), TInfo, SC);5892 if (Invalid)5893 Anon->setInvalidDecl();5894 5895 ProcessDeclAttributes(S, Anon, Dc);5896 5897 // Default-initialize the implicit variable. This initialization will be5898 // trivial in almost all cases, except if a union member has an in-class5899 // initializer:5900 // union { int n = 0; };5901 ActOnUninitializedDecl(Anon);5902 }5903 Anon->setImplicit();5904 5905 // Mark this as an anonymous struct/union type.5906 Record->setAnonymousStructOrUnion(true);5907 5908 // Add the anonymous struct/union object to the current5909 // context. We'll be referencing this object when we refer to one of5910 // its members.5911 Owner->addDecl(Anon);5912 5913 // Inject the members of the anonymous struct/union into the owning5914 // context and into the identifier resolver chain for name lookup5915 // purposes.5916 SmallVector<NamedDecl*, 2> Chain;5917 Chain.push_back(Anon);5918 5919 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,5920 Chain))5921 Invalid = true;5922 5923 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {5924 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {5925 MangleNumberingContext *MCtx;5926 Decl *ManglingContextDecl;5927 std::tie(MCtx, ManglingContextDecl) =5928 getCurrentMangleNumberContext(NewVD->getDeclContext());5929 if (MCtx) {5930 Context.setManglingNumber(5931 NewVD, MCtx->getManglingNumber(5932 NewVD, getMSManglingNumber(getLangOpts(), S)));5933 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));5934 }5935 }5936 }5937 5938 if (Invalid)5939 Anon->setInvalidDecl();5940 5941 return Anon;5942}5943 5944Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,5945 RecordDecl *Record) {5946 assert(Record && "expected a record!");5947 5948 // Mock up a declarator.5949 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);5950 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc);5951 assert(TInfo && "couldn't build declarator info for anonymous struct");5952 5953 auto *ParentDecl = cast<RecordDecl>(CurContext);5954 CanQualType RecTy = Context.getCanonicalTagType(Record);5955 5956 // Create a declaration for this anonymous struct.5957 NamedDecl *Anon =5958 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),5959 /*IdentifierInfo=*/nullptr, RecTy, TInfo,5960 /*BitWidth=*/nullptr, /*Mutable=*/false,5961 /*InitStyle=*/ICIS_NoInit);5962 Anon->setImplicit();5963 5964 // Add the anonymous struct object to the current context.5965 CurContext->addDecl(Anon);5966 5967 // Inject the members of the anonymous struct into the current5968 // context and into the identifier resolver chain for name lookup5969 // purposes.5970 SmallVector<NamedDecl*, 2> Chain;5971 Chain.push_back(Anon);5972 5973 RecordDecl *RecordDef = Record->getDefinition();5974 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,5975 diag::err_field_incomplete_or_sizeless) ||5976 InjectAnonymousStructOrUnionMembers(5977 *this, S, CurContext, RecordDef, AS_none,5978 StorageClassSpecToVarDeclStorageClass(DS), Chain)) {5979 Anon->setInvalidDecl();5980 ParentDecl->setInvalidDecl();5981 }5982 5983 return Anon;5984}5985 5986DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {5987 return GetNameFromUnqualifiedId(D.getName());5988}5989 5990DeclarationNameInfo5991Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {5992 DeclarationNameInfo NameInfo;5993 NameInfo.setLoc(Name.StartLocation);5994 5995 switch (Name.getKind()) {5996 5997 case UnqualifiedIdKind::IK_ImplicitSelfParam:5998 case UnqualifiedIdKind::IK_Identifier:5999 NameInfo.setName(Name.Identifier);6000 return NameInfo;6001 6002 case UnqualifiedIdKind::IK_DeductionGuideName: {6003 // C++ [temp.deduct.guide]p3:6004 // The simple-template-id shall name a class template specialization.6005 // The template-name shall be the same identifier as the template-name6006 // of the simple-template-id.6007 // These together intend to imply that the template-name shall name a6008 // class template.6009 // FIXME: template<typename T> struct X {};6010 // template<typename T> using Y = X<T>;6011 // Y(int) -> Y<int>;6012 // satisfies these rules but does not name a class template.6013 TemplateName TN = Name.TemplateName.get().get();6014 auto *Template = TN.getAsTemplateDecl();6015 if (!Template || !isa<ClassTemplateDecl>(Template)) {6016 Diag(Name.StartLocation,6017 diag::err_deduction_guide_name_not_class_template)6018 << (int)getTemplateNameKindForDiagnostics(TN) << TN;6019 if (Template)6020 NoteTemplateLocation(*Template);6021 return DeclarationNameInfo();6022 }6023 6024 NameInfo.setName(6025 Context.DeclarationNames.getCXXDeductionGuideName(Template));6026 return NameInfo;6027 }6028 6029 case UnqualifiedIdKind::IK_OperatorFunctionId:6030 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(6031 Name.OperatorFunctionId.Operator));6032 NameInfo.setCXXOperatorNameRange(SourceRange(6033 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));6034 return NameInfo;6035 6036 case UnqualifiedIdKind::IK_LiteralOperatorId:6037 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(6038 Name.Identifier));6039 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);6040 return NameInfo;6041 6042 case UnqualifiedIdKind::IK_ConversionFunctionId: {6043 TypeSourceInfo *TInfo;6044 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);6045 if (Ty.isNull())6046 return DeclarationNameInfo();6047 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(6048 Context.getCanonicalType(Ty)));6049 NameInfo.setNamedTypeInfo(TInfo);6050 return NameInfo;6051 }6052 6053 case UnqualifiedIdKind::IK_ConstructorName: {6054 TypeSourceInfo *TInfo;6055 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);6056 if (Ty.isNull())6057 return DeclarationNameInfo();6058 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(6059 Context.getCanonicalType(Ty)));6060 NameInfo.setNamedTypeInfo(TInfo);6061 return NameInfo;6062 }6063 6064 case UnqualifiedIdKind::IK_ConstructorTemplateId: {6065 // In well-formed code, we can only have a constructor6066 // template-id that refers to the current context, so go there6067 // to find the actual type being constructed.6068 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);6069 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)6070 return DeclarationNameInfo();6071 6072 // Determine the type of the class being constructed.6073 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);6074 6075 // FIXME: Check two things: that the template-id names the same type as6076 // CurClassType, and that the template-id does not occur when the name6077 // was qualified.6078 6079 NameInfo.setName(6080 Context.DeclarationNames.getCXXConstructorName(CurClassType));6081 // FIXME: should we retrieve TypeSourceInfo?6082 NameInfo.setNamedTypeInfo(nullptr);6083 return NameInfo;6084 }6085 6086 case UnqualifiedIdKind::IK_DestructorName: {6087 TypeSourceInfo *TInfo;6088 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);6089 if (Ty.isNull())6090 return DeclarationNameInfo();6091 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(6092 Context.getCanonicalType(Ty)));6093 NameInfo.setNamedTypeInfo(TInfo);6094 return NameInfo;6095 }6096 6097 case UnqualifiedIdKind::IK_TemplateId: {6098 TemplateName TName = Name.TemplateId->Template.get();6099 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;6100 return Context.getNameForTemplate(TName, TNameLoc);6101 }6102 6103 } // switch (Name.getKind())6104 6105 llvm_unreachable("Unknown name kind");6106}6107 6108static QualType getCoreType(QualType Ty) {6109 do {6110 if (Ty->isPointerOrReferenceType())6111 Ty = Ty->getPointeeType();6112 else if (Ty->isArrayType())6113 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();6114 else6115 return Ty.withoutLocalFastQualifiers();6116 } while (true);6117}6118 6119/// hasSimilarParameters - Determine whether the C++ functions Declaration6120/// and Definition have "nearly" matching parameters. This heuristic is6121/// used to improve diagnostics in the case where an out-of-line function6122/// definition doesn't match any declaration within the class or namespace.6123/// Also sets Params to the list of indices to the parameters that differ6124/// between the declaration and the definition. If hasSimilarParameters6125/// returns true and Params is empty, then all of the parameters match.6126static bool hasSimilarParameters(ASTContext &Context,6127 FunctionDecl *Declaration,6128 FunctionDecl *Definition,6129 SmallVectorImpl<unsigned> &Params) {6130 Params.clear();6131 if (Declaration->param_size() != Definition->param_size())6132 return false;6133 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {6134 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();6135 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();6136 6137 // The parameter types are identical6138 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))6139 continue;6140 6141 QualType DeclParamBaseTy = getCoreType(DeclParamTy);6142 QualType DefParamBaseTy = getCoreType(DefParamTy);6143 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();6144 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();6145 6146 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||6147 (DeclTyName && DeclTyName == DefTyName))6148 Params.push_back(Idx);6149 else // The two parameters aren't even close6150 return false;6151 }6152 6153 return true;6154}6155 6156/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given6157/// declarator needs to be rebuilt in the current instantiation.6158/// Any bits of declarator which appear before the name are valid for6159/// consideration here. That's specifically the type in the decl spec6160/// and the base type in any member-pointer chunks.6161static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,6162 DeclarationName Name) {6163 // The types we specifically need to rebuild are:6164 // - typenames, typeofs, and decltypes6165 // - types which will become injected class names6166 // Of course, we also need to rebuild any type referencing such a6167 // type. It's safest to just say "dependent", but we call out a6168 // few cases here.6169 6170 DeclSpec &DS = D.getMutableDeclSpec();6171 switch (DS.getTypeSpecType()) {6172 case DeclSpec::TST_typename:6173 case DeclSpec::TST_typeofType:6174 case DeclSpec::TST_typeof_unqualType:6175#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:6176#include "clang/Basic/TransformTypeTraits.def"6177 case DeclSpec::TST_atomic: {6178 // Grab the type from the parser.6179 TypeSourceInfo *TSI = nullptr;6180 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);6181 if (T.isNull() || !T->isInstantiationDependentType()) break;6182 6183 // Make sure there's a type source info. This isn't really much6184 // of a waste; most dependent types should have type source info6185 // attached already.6186 if (!TSI)6187 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());6188 6189 // Rebuild the type in the current instantiation.6190 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);6191 if (!TSI) return true;6192 6193 // Store the new type back in the decl spec.6194 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);6195 DS.UpdateTypeRep(LocType);6196 break;6197 }6198 6199 case DeclSpec::TST_decltype:6200 case DeclSpec::TST_typeof_unqualExpr:6201 case DeclSpec::TST_typeofExpr: {6202 Expr *E = DS.getRepAsExpr();6203 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);6204 if (Result.isInvalid()) return true;6205 DS.UpdateExprRep(Result.get());6206 break;6207 }6208 6209 default:6210 // Nothing to do for these decl specs.6211 break;6212 }6213 6214 // It doesn't matter what order we do this in.6215 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {6216 DeclaratorChunk &Chunk = D.getTypeObject(I);6217 6218 // The only type information in the declarator which can come6219 // before the declaration name is the base type of a member6220 // pointer.6221 if (Chunk.Kind != DeclaratorChunk::MemberPointer)6222 continue;6223 6224 // Rebuild the scope specifier in-place.6225 CXXScopeSpec &SS = Chunk.Mem.Scope();6226 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))6227 return true;6228 }6229 6230 return false;6231}6232 6233/// Returns true if the declaration is declared in a system header or from a6234/// system macro.6235static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {6236 return SM.isInSystemHeader(D->getLocation()) ||6237 SM.isInSystemMacro(D->getLocation());6238}6239 6240void Sema::warnOnReservedIdentifier(const NamedDecl *D) {6241 // Avoid warning twice on the same identifier, and don't warn on redeclaration6242 // of system decl.6243 if (D->getPreviousDecl() || D->isImplicit())6244 return;6245 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());6246 if (Status != ReservedIdentifierStatus::NotReserved &&6247 !isFromSystemHeader(Context.getSourceManager(), D)) {6248 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)6249 << D << static_cast<int>(Status);6250 }6251}6252 6253Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {6254 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);6255 6256 // Check if we are in an `omp begin/end declare variant` scope. Handle this6257 // declaration only if the `bind_to_declaration` extension is set.6258 SmallVector<FunctionDecl *, 4> Bases;6259 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())6260 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(6261 llvm::omp::TraitProperty::6262 implementation_extension_bind_to_declaration))6263 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(6264 S, D, MultiTemplateParamsArg(), Bases);6265 6266 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());6267 6268 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&6269 Dcl && Dcl->getDeclContext()->isFileContext())6270 Dcl->setTopLevelDeclInObjCContainer();6271 6272 if (!Bases.empty())6273 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl,6274 Bases);6275 6276 return Dcl;6277}6278 6279bool Sema::DiagnoseClassNameShadow(DeclContext *DC,6280 DeclarationNameInfo NameInfo) {6281 DeclarationName Name = NameInfo.getName();6282 6283 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);6284 while (Record && Record->isAnonymousStructOrUnion())6285 Record = dyn_cast<CXXRecordDecl>(Record->getParent());6286 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {6287 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;6288 return true;6289 }6290 6291 return false;6292}6293 6294bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,6295 DeclarationName Name,6296 SourceLocation Loc,6297 TemplateIdAnnotation *TemplateId,6298 bool IsMemberSpecialization) {6299 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "6300 "without nested-name-specifier");6301 DeclContext *Cur = CurContext;6302 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))6303 Cur = Cur->getParent();6304 6305 // If the user provided a superfluous scope specifier that refers back to the6306 // class in which the entity is already declared, diagnose and ignore it.6307 //6308 // class X {6309 // void X::f();6310 // };6311 //6312 // Note, it was once ill-formed to give redundant qualification in all6313 // contexts, but that rule was removed by DR482.6314 if (Cur->Equals(DC)) {6315 if (Cur->isRecord()) {6316 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification6317 : diag::err_member_extra_qualification)6318 << Name << FixItHint::CreateRemoval(SS.getRange());6319 SS.clear();6320 } else {6321 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;6322 }6323 return false;6324 }6325 6326 // Check whether the qualifying scope encloses the scope of the original6327 // declaration. For a template-id, we perform the checks in6328 // CheckTemplateSpecializationScope.6329 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {6330 if (Cur->isRecord())6331 Diag(Loc, diag::err_member_qualification)6332 << Name << SS.getRange();6333 else if (isa<TranslationUnitDecl>(DC))6334 Diag(Loc, diag::err_invalid_declarator_global_scope)6335 << Name << SS.getRange();6336 else if (isa<FunctionDecl>(Cur))6337 Diag(Loc, diag::err_invalid_declarator_in_function)6338 << Name << SS.getRange();6339 else if (isa<BlockDecl>(Cur))6340 Diag(Loc, diag::err_invalid_declarator_in_block)6341 << Name << SS.getRange();6342 else if (isa<ExportDecl>(Cur)) {6343 if (!isa<NamespaceDecl>(DC))6344 Diag(Loc, diag::err_export_non_namespace_scope_name)6345 << Name << SS.getRange();6346 else6347 // The cases that DC is not NamespaceDecl should be handled in6348 // CheckRedeclarationExported.6349 return false;6350 } else6351 Diag(Loc, diag::err_invalid_declarator_scope)6352 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();6353 6354 return true;6355 }6356 6357 if (Cur->isRecord()) {6358 // Cannot qualify members within a class.6359 Diag(Loc, diag::err_member_qualification)6360 << Name << SS.getRange();6361 SS.clear();6362 6363 // C++ constructors and destructors with incorrect scopes can break6364 // our AST invariants by having the wrong underlying types. If6365 // that's the case, then drop this declaration entirely.6366 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||6367 Name.getNameKind() == DeclarationName::CXXDestructorName) &&6368 !Context.hasSameType(6369 Name.getCXXNameType(),6370 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))6371 return true;6372 6373 return false;6374 }6375 6376 // C++23 [temp.names]p5:6377 // The keyword template shall not appear immediately after a declarative6378 // nested-name-specifier.6379 //6380 // First check the template-id (if any), and then check each component of the6381 // nested-name-specifier in reverse order.6382 //6383 // FIXME: nested-name-specifiers in friend declarations are declarative,6384 // but we don't call diagnoseQualifiedDeclaration for them. We should.6385 if (TemplateId && TemplateId->TemplateKWLoc.isValid())6386 Diag(Loc, diag::ext_template_after_declarative_nns)6387 << FixItHint::CreateRemoval(TemplateId->TemplateKWLoc);6388 6389 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());6390 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;6391 TL = std::exchange(NextTL, TypeLoc())) {6392 SourceLocation TemplateKeywordLoc;6393 switch (TL.getTypeLocClass()) {6394 case TypeLoc::TemplateSpecialization: {6395 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();6396 TemplateKeywordLoc = TST.getTemplateKeywordLoc();6397 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())6398 Diag(Loc, diag::ext_alias_template_in_declarative_nns)6399 << TST.getLocalSourceRange();6400 break;6401 }6402 case TypeLoc::Decltype:6403 case TypeLoc::PackIndexing: {6404 const Type *T = TL.getTypePtr();6405 // C++23 [expr.prim.id.qual]p2:6406 // [...] A declarative nested-name-specifier shall not have a6407 // computed-type-specifier.6408 //6409 // CWG2858 changed this from 'decltype-specifier' to6410 // 'computed-type-specifier'.6411 Diag(Loc, diag::err_computed_type_in_declarative_nns)6412 << T->isDecltypeType() << TL.getSourceRange();6413 break;6414 }6415 case TypeLoc::DependentName:6416 NextTL =6417 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();6418 break;6419 default:6420 break;6421 }6422 if (TemplateKeywordLoc.isValid())6423 Diag(Loc, diag::ext_template_after_declarative_nns)6424 << FixItHint::CreateRemoval(TemplateKeywordLoc);6425 }6426 6427 return false;6428}6429 6430NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,6431 MultiTemplateParamsArg TemplateParamLists) {6432 // TODO: consider using NameInfo for diagnostic.6433 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);6434 DeclarationName Name = NameInfo.getName();6435 6436 // All of these full declarators require an identifier. If it doesn't have6437 // one, the ParsedFreeStandingDeclSpec action should be used.6438 if (D.isDecompositionDeclarator()) {6439 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);6440 } else if (!Name) {6441 if (!D.isInvalidType()) // Reject this if we think it is valid.6442 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)6443 << D.getDeclSpec().getSourceRange() << D.getSourceRange();6444 return nullptr;6445 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))6446 return nullptr;6447 6448 DeclContext *DC = CurContext;6449 if (D.getCXXScopeSpec().isInvalid())6450 D.setInvalidType();6451 else if (D.getCXXScopeSpec().isSet()) {6452 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),6453 UPPC_DeclarationQualifier))6454 return nullptr;6455 6456 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();6457 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);6458 if (!DC || isa<EnumDecl>(DC)) {6459 // If we could not compute the declaration context, it's because the6460 // declaration context is dependent but does not refer to a class,6461 // class template, or class template partial specialization. Complain6462 // and return early, to avoid the coming semantic disaster.6463 Diag(D.getIdentifierLoc(),6464 diag::err_template_qualified_declarator_no_match)6465 << D.getCXXScopeSpec().getScopeRep()6466 << D.getCXXScopeSpec().getRange();6467 return nullptr;6468 }6469 bool IsDependentContext = DC->isDependentContext();6470 6471 if (!IsDependentContext &&6472 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))6473 return nullptr;6474 6475 // If a class is incomplete, do not parse entities inside it.6476 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {6477 Diag(D.getIdentifierLoc(),6478 diag::err_member_def_undefined_record)6479 << Name << DC << D.getCXXScopeSpec().getRange();6480 return nullptr;6481 }6482 if (!D.getDeclSpec().isFriendSpecified()) {6483 TemplateIdAnnotation *TemplateId =6484 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId6485 ? D.getName().TemplateId6486 : nullptr;6487 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, Name,6488 D.getIdentifierLoc(), TemplateId,6489 /*IsMemberSpecialization=*/false)) {6490 if (DC->isRecord())6491 return nullptr;6492 6493 D.setInvalidType();6494 }6495 }6496 6497 // Check whether we need to rebuild the type of the given6498 // declaration in the current instantiation.6499 if (EnteringContext && IsDependentContext &&6500 TemplateParamLists.size() != 0) {6501 ContextRAII SavedContext(*this, DC);6502 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))6503 D.setInvalidType();6504 }6505 }6506 6507 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);6508 QualType R = TInfo->getType();6509 6510 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,6511 UPPC_DeclarationType))6512 D.setInvalidType();6513 6514 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,6515 forRedeclarationInCurContext());6516 6517 // See if this is a redefinition of a variable in the same scope.6518 if (!D.getCXXScopeSpec().isSet()) {6519 bool IsLinkageLookup = false;6520 bool CreateBuiltins = false;6521 6522 // If the declaration we're planning to build will be a function6523 // or object with linkage, then look for another declaration with6524 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).6525 //6526 // If the declaration we're planning to build will be declared with6527 // external linkage in the translation unit, create any builtin with6528 // the same name.6529 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)6530 /* Do nothing*/;6531 else if (CurContext->isFunctionOrMethod() &&6532 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||6533 R->isFunctionType())) {6534 IsLinkageLookup = true;6535 CreateBuiltins =6536 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();6537 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&6538 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)6539 CreateBuiltins = true;6540 6541 if (IsLinkageLookup) {6542 Previous.clear(LookupRedeclarationWithLinkage);6543 Previous.setRedeclarationKind(6544 RedeclarationKind::ForExternalRedeclaration);6545 }6546 6547 LookupName(Previous, S, CreateBuiltins);6548 } else { // Something like "int foo::x;"6549 LookupQualifiedName(Previous, DC);6550 6551 // C++ [dcl.meaning]p1:6552 // When the declarator-id is qualified, the declaration shall refer to a6553 // previously declared member of the class or namespace to which the6554 // qualifier refers (or, in the case of a namespace, of an element of the6555 // inline namespace set of that namespace (7.3.1)) or to a specialization6556 // thereof; [...]6557 //6558 // Note that we already checked the context above, and that we do not have6559 // enough information to make sure that Previous contains the declaration6560 // we want to match. For example, given:6561 //6562 // class X {6563 // void f();6564 // void f(float);6565 // };6566 //6567 // void X::f(int) { } // ill-formed6568 //6569 // In this case, Previous will point to the overload set6570 // containing the two f's declared in X, but neither of them6571 // matches.6572 6573 RemoveUsingDecls(Previous);6574 }6575 6576 if (auto *TPD = Previous.getAsSingle<NamedDecl>();6577 TPD && TPD->isTemplateParameter()) {6578 // Older versions of clang allowed the names of function/variable templates6579 // to shadow the names of their template parameters. For the compatibility6580 // purposes we detect such cases and issue a default-to-error warning that6581 // can be disabled with -Wno-strict-primary-template-shadow.6582 if (!D.isInvalidType()) {6583 bool AllowForCompatibility = false;6584 if (Scope *DeclParent = S->getDeclParent();6585 Scope *TemplateParamParent = S->getTemplateParamParent()) {6586 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&6587 TemplateParamParent->isDeclScope(TPD);6588 }6589 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,6590 AllowForCompatibility);6591 }6592 6593 // Just pretend that we didn't see the previous declaration.6594 Previous.clear();6595 }6596 6597 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))6598 // Forget that the previous declaration is the injected-class-name.6599 Previous.clear();6600 6601 // In C++, the previous declaration we find might be a tag type6602 // (class or enum). In this case, the new declaration will hide the6603 // tag type. Note that this applies to functions, function templates, and6604 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.6605 if (Previous.isSingleTagDecl() &&6606 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&6607 (TemplateParamLists.size() == 0 || R->isFunctionType()))6608 Previous.clear();6609 6610 // Check that there are no default arguments other than in the parameters6611 // of a function declaration (C++ only).6612 if (getLangOpts().CPlusPlus)6613 CheckExtraCXXDefaultArguments(D);6614 6615 /// Get the innermost enclosing declaration scope.6616 S = S->getDeclParent();6617 6618 NamedDecl *New;6619 6620 bool AddToScope = true;6621 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {6622 if (TemplateParamLists.size()) {6623 Diag(D.getIdentifierLoc(), diag::err_template_typedef);6624 return nullptr;6625 }6626 6627 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);6628 } else if (R->isFunctionType()) {6629 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,6630 TemplateParamLists,6631 AddToScope);6632 } else {6633 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,6634 AddToScope);6635 }6636 6637 if (!New)6638 return nullptr;6639 6640 warnOnCTypeHiddenInCPlusPlus(New);6641 6642 // If this has an identifier and is not a function template specialization,6643 // add it to the scope stack.6644 if (New->getDeclName() && AddToScope)6645 PushOnScopeChains(New, S);6646 6647 if (OpenMP().isInOpenMPDeclareTargetContext())6648 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);6649 6650 return New;6651}6652 6653/// Helper method to turn variable array types into constant array6654/// types in certain situations which would otherwise be errors (for6655/// GCC compatibility).6656static QualType TryToFixInvalidVariablyModifiedType(QualType T,6657 ASTContext &Context,6658 bool &SizeIsNegative,6659 llvm::APSInt &Oversized) {6660 // This method tries to turn a variable array into a constant6661 // array even when the size isn't an ICE. This is necessary6662 // for compatibility with code that depends on gcc's buggy6663 // constant expression folding, like struct {char x[(int)(char*)2];}6664 SizeIsNegative = false;6665 Oversized = 0;6666 6667 if (T->isDependentType())6668 return QualType();6669 6670 QualifierCollector Qs;6671 const Type *Ty = Qs.strip(T);6672 6673 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {6674 QualType Pointee = PTy->getPointeeType();6675 QualType FixedType =6676 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,6677 Oversized);6678 if (FixedType.isNull()) return FixedType;6679 FixedType = Context.getPointerType(FixedType);6680 return Qs.apply(Context, FixedType);6681 }6682 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {6683 QualType Inner = PTy->getInnerType();6684 QualType FixedType =6685 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,6686 Oversized);6687 if (FixedType.isNull()) return FixedType;6688 FixedType = Context.getParenType(FixedType);6689 return Qs.apply(Context, FixedType);6690 }6691 6692 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);6693 if (!VLATy)6694 return QualType();6695 6696 QualType ElemTy = VLATy->getElementType();6697 if (ElemTy->isVariablyModifiedType()) {6698 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,6699 SizeIsNegative, Oversized);6700 if (ElemTy.isNull())6701 return QualType();6702 }6703 6704 Expr::EvalResult Result;6705 if (!VLATy->getSizeExpr() ||6706 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))6707 return QualType();6708 6709 llvm::APSInt Res = Result.Val.getInt();6710 6711 // Check whether the array size is negative.6712 if (Res.isSigned() && Res.isNegative()) {6713 SizeIsNegative = true;6714 return QualType();6715 }6716 6717 // Check whether the array is too large to be addressed.6718 unsigned ActiveSizeBits =6719 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&6720 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())6721 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)6722 : Res.getActiveBits();6723 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {6724 Oversized = Res;6725 return QualType();6726 }6727 6728 QualType FoldedArrayType = Context.getConstantArrayType(6729 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);6730 return Qs.apply(Context, FoldedArrayType);6731}6732 6733static void6734FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {6735 SrcTL = SrcTL.getUnqualifiedLoc();6736 DstTL = DstTL.getUnqualifiedLoc();6737 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {6738 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();6739 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),6740 DstPTL.getPointeeLoc());6741 DstPTL.setStarLoc(SrcPTL.getStarLoc());6742 return;6743 }6744 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {6745 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();6746 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),6747 DstPTL.getInnerLoc());6748 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());6749 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());6750 return;6751 }6752 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();6753 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();6754 TypeLoc SrcElemTL = SrcATL.getElementLoc();6755 TypeLoc DstElemTL = DstATL.getElementLoc();6756 if (VariableArrayTypeLoc SrcElemATL =6757 SrcElemTL.getAs<VariableArrayTypeLoc>()) {6758 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();6759 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);6760 } else {6761 DstElemTL.initializeFullCopy(SrcElemTL);6762 }6763 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());6764 DstATL.setSizeExpr(SrcATL.getSizeExpr());6765 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());6766}6767 6768/// Helper method to turn variable array types into constant array6769/// types in certain situations which would otherwise be errors (for6770/// GCC compatibility).6771static TypeSourceInfo*6772TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,6773 ASTContext &Context,6774 bool &SizeIsNegative,6775 llvm::APSInt &Oversized) {6776 QualType FixedTy6777 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,6778 SizeIsNegative, Oversized);6779 if (FixedTy.isNull())6780 return nullptr;6781 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);6782 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),6783 FixedTInfo->getTypeLoc());6784 return FixedTInfo;6785}6786 6787bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,6788 QualType &T, SourceLocation Loc,6789 unsigned FailedFoldDiagID) {6790 bool SizeIsNegative;6791 llvm::APSInt Oversized;6792 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(6793 TInfo, Context, SizeIsNegative, Oversized);6794 if (FixedTInfo) {6795 Diag(Loc, diag::ext_vla_folded_to_constant);6796 TInfo = FixedTInfo;6797 T = FixedTInfo->getType();6798 return true;6799 }6800 6801 if (SizeIsNegative)6802 Diag(Loc, diag::err_typecheck_negative_array_size);6803 else if (Oversized.getBoolValue())6804 Diag(Loc, diag::err_array_too_large) << toString(6805 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,6806 /*UpperCase=*/false, /*InsertSeparators=*/true);6807 else if (FailedFoldDiagID)6808 Diag(Loc, FailedFoldDiagID);6809 return false;6810}6811 6812void6813Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {6814 if (!getLangOpts().CPlusPlus &&6815 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())6816 // Don't need to track declarations in the TU in C.6817 return;6818 6819 // Note that we have a locally-scoped external with this name.6820 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);6821}6822 6823NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {6824 // FIXME: We can have multiple results via __attribute__((overloadable)).6825 auto Result = Context.getExternCContextDecl()->lookup(Name);6826 return Result.empty() ? nullptr : *Result.begin();6827}6828 6829void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {6830 // FIXME: We should probably indicate the identifier in question to avoid6831 // confusion for constructs like "virtual int a(), b;"6832 if (DS.isVirtualSpecified())6833 Diag(DS.getVirtualSpecLoc(),6834 diag::err_virtual_non_function);6835 6836 if (DS.hasExplicitSpecifier())6837 Diag(DS.getExplicitSpecLoc(),6838 diag::err_explicit_non_function);6839 6840 if (DS.isNoreturnSpecified())6841 Diag(DS.getNoreturnSpecLoc(),6842 diag::err_noreturn_non_function);6843}6844 6845NamedDecl*6846Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,6847 TypeSourceInfo *TInfo, LookupResult &Previous) {6848 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).6849 if (D.getCXXScopeSpec().isSet()) {6850 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)6851 << D.getCXXScopeSpec().getRange();6852 D.setInvalidType();6853 // Pretend we didn't see the scope specifier.6854 DC = CurContext;6855 Previous.clear();6856 }6857 6858 DiagnoseFunctionSpecifiers(D.getDeclSpec());6859 6860 if (D.getDeclSpec().isInlineSpecified())6861 Diag(D.getDeclSpec().getInlineSpecLoc(),6862 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)6863 ? diag::warn_ms_inline_non_function6864 : diag::err_inline_non_function)6865 << getLangOpts().CPlusPlus17;6866 if (D.getDeclSpec().hasConstexprSpecifier())6867 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)6868 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());6869 6870 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {6871 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)6872 Diag(D.getName().StartLocation,6873 diag::err_deduction_guide_invalid_specifier)6874 << "typedef";6875 else6876 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)6877 << D.getName().getSourceRange();6878 return nullptr;6879 }6880 6881 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);6882 if (!NewTD) return nullptr;6883 6884 // Handle attributes prior to checking for duplicates in MergeVarDecl6885 ProcessDeclAttributes(S, NewTD, D);6886 6887 CheckTypedefForVariablyModifiedType(S, NewTD);6888 6889 bool Redeclaration = D.isRedeclaration();6890 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);6891 D.setRedeclaration(Redeclaration);6892 return ND;6893}6894 6895void6896Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {6897 // C99 6.7.7p2: If a typedef name specifies a variably modified type6898 // then it shall have block scope.6899 // Note that variably modified types must be fixed before merging the decl so6900 // that redeclarations will match.6901 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();6902 QualType T = TInfo->getType();6903 if (T->isVariablyModifiedType()) {6904 setFunctionHasBranchProtectedScope();6905 6906 if (S->getFnParent() == nullptr) {6907 bool SizeIsNegative;6908 llvm::APSInt Oversized;6909 TypeSourceInfo *FixedTInfo =6910 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,6911 SizeIsNegative,6912 Oversized);6913 if (FixedTInfo) {6914 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);6915 NewTD->setTypeSourceInfo(FixedTInfo);6916 } else {6917 if (SizeIsNegative)6918 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);6919 else if (T->isVariableArrayType())6920 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);6921 else if (Oversized.getBoolValue())6922 Diag(NewTD->getLocation(), diag::err_array_too_large)6923 << toString(Oversized, 10);6924 else6925 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);6926 NewTD->setInvalidDecl();6927 }6928 }6929 }6930}6931 6932NamedDecl*6933Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,6934 LookupResult &Previous, bool &Redeclaration) {6935 6936 // Find the shadowed declaration before filtering for scope.6937 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);6938 6939 // Merge the decl with the existing one if appropriate. If the decl is6940 // in an outer scope, it isn't the same thing.6941 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,6942 /*AllowInlineNamespace*/false);6943 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);6944 if (!Previous.empty()) {6945 Redeclaration = true;6946 MergeTypedefNameDecl(S, NewTD, Previous);6947 } else {6948 inferGslPointerAttribute(NewTD);6949 }6950 6951 if (ShadowedDecl && !Redeclaration)6952 CheckShadow(NewTD, ShadowedDecl, Previous);6953 6954 // If this is the C FILE type, notify the AST context.6955 if (IdentifierInfo *II = NewTD->getIdentifier())6956 if (!NewTD->isInvalidDecl() &&6957 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {6958 switch (II->getNotableIdentifierID()) {6959 case tok::NotableIdentifierKind::FILE:6960 Context.setFILEDecl(NewTD);6961 break;6962 case tok::NotableIdentifierKind::jmp_buf:6963 Context.setjmp_bufDecl(NewTD);6964 break;6965 case tok::NotableIdentifierKind::sigjmp_buf:6966 Context.setsigjmp_bufDecl(NewTD);6967 break;6968 case tok::NotableIdentifierKind::ucontext_t:6969 Context.setucontext_tDecl(NewTD);6970 break;6971 case tok::NotableIdentifierKind::float_t:6972 case tok::NotableIdentifierKind::double_t:6973 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));6974 break;6975 default:6976 break;6977 }6978 }6979 6980 return NewTD;6981}6982 6983/// Determines whether the given declaration is an out-of-scope6984/// previous declaration.6985///6986/// This routine should be invoked when name lookup has found a6987/// previous declaration (PrevDecl) that is not in the scope where a6988/// new declaration by the same name is being introduced. If the new6989/// declaration occurs in a local scope, previous declarations with6990/// linkage may still be considered previous declarations (C996991/// 6.2.2p4-5, C++ [basic.link]p6).6992///6993/// \param PrevDecl the previous declaration found by name6994/// lookup6995///6996/// \param DC the context in which the new declaration is being6997/// declared.6998///6999/// \returns true if PrevDecl is an out-of-scope previous declaration7000/// for a new delcaration with the same name.7001static bool7002isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,7003 ASTContext &Context) {7004 if (!PrevDecl)7005 return false;7006 7007 if (!PrevDecl->hasLinkage())7008 return false;7009 7010 if (Context.getLangOpts().CPlusPlus) {7011 // C++ [basic.link]p6:7012 // If there is a visible declaration of an entity with linkage7013 // having the same name and type, ignoring entities declared7014 // outside the innermost enclosing namespace scope, the block7015 // scope declaration declares that same entity and receives the7016 // linkage of the previous declaration.7017 DeclContext *OuterContext = DC->getRedeclContext();7018 if (!OuterContext->isFunctionOrMethod())7019 // This rule only applies to block-scope declarations.7020 return false;7021 7022 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();7023 if (PrevOuterContext->isRecord())7024 // We found a member function: ignore it.7025 return false;7026 7027 // Find the innermost enclosing namespace for the new and7028 // previous declarations.7029 OuterContext = OuterContext->getEnclosingNamespaceContext();7030 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();7031 7032 // The previous declaration is in a different namespace, so it7033 // isn't the same function.7034 if (!OuterContext->Equals(PrevOuterContext))7035 return false;7036 }7037 7038 return true;7039}7040 7041static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {7042 CXXScopeSpec &SS = D.getCXXScopeSpec();7043 if (!SS.isSet()) return;7044 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));7045}7046 7047void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {7048 if (Decl->getType().hasAddressSpace())7049 return;7050 if (Decl->getType()->isDependentType())7051 return;7052 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {7053 QualType Type = Var->getType();7054 if (Type->isSamplerT() || Type->isVoidType())7055 return;7056 LangAS ImplAS = LangAS::opencl_private;7057 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the7058 // __opencl_c_program_scope_global_variables feature, the address space7059 // for a variable at program scope or a static or extern variable inside7060 // a function are inferred to be __global.7061 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&7062 Var->hasGlobalStorage())7063 ImplAS = LangAS::opencl_global;7064 // If the original type from a decayed type is an array type and that array7065 // type has no address space yet, deduce it now.7066 if (auto DT = dyn_cast<DecayedType>(Type)) {7067 auto OrigTy = DT->getOriginalType();7068 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {7069 // Add the address space to the original array type and then propagate7070 // that to the element type through `getAsArrayType`.7071 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);7072 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);7073 // Re-generate the decayed type.7074 Type = Context.getDecayedType(OrigTy);7075 }7076 }7077 Type = Context.getAddrSpaceQualType(Type, ImplAS);7078 // Apply any qualifiers (including address space) from the array type to7079 // the element type. This implements C99 6.7.3p8: "If the specification of7080 // an array type includes any type qualifiers, the element type is so7081 // qualified, not the array type."7082 if (Type->isArrayType())7083 Type = QualType(Context.getAsArrayType(Type), 0);7084 Decl->setType(Type);7085 }7086}7087 7088static void checkWeakAttr(Sema &S, NamedDecl &ND) {7089 // 'weak' only applies to declarations with external linkage.7090 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {7091 if (!ND.isExternallyVisible()) {7092 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);7093 ND.dropAttr<WeakAttr>();7094 }7095 }7096}7097 7098static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {7099 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {7100 if (ND.isExternallyVisible()) {7101 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);7102 ND.dropAttrs<WeakRefAttr, AliasAttr>();7103 }7104 }7105}7106 7107static void checkAliasAttr(Sema &S, NamedDecl &ND) {7108 if (auto *VD = dyn_cast<VarDecl>(&ND)) {7109 if (VD->hasInit()) {7110 if (const auto *Attr = VD->getAttr<AliasAttr>()) {7111 assert(VD->isThisDeclarationADefinition() &&7112 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");7113 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;7114 VD->dropAttr<AliasAttr>();7115 }7116 }7117 }7118}7119 7120static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {7121 // 'selectany' only applies to externally visible variable declarations.7122 // It does not apply to functions.7123 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {7124 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {7125 S.Diag(Attr->getLocation(),7126 diag::err_attribute_selectany_non_extern_data);7127 ND.dropAttr<SelectAnyAttr>();7128 }7129 }7130}7131 7132static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {7133 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {7134 if (!ND.isExternallyVisible())7135 S.Diag(Attr->getLocation(),7136 diag::warn_attribute_hybrid_patchable_non_extern);7137 }7138}7139 7140static void checkInheritableAttr(Sema &S, NamedDecl &ND) {7141 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {7142 auto *VD = dyn_cast<VarDecl>(&ND);7143 bool IsAnonymousNS = false;7144 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();7145 if (VD) {7146 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());7147 while (NS && !IsAnonymousNS) {7148 IsAnonymousNS = NS->isAnonymousNamespace();7149 NS = dyn_cast<NamespaceDecl>(NS->getParent());7150 }7151 }7152 // dll attributes require external linkage. Static locals may have external7153 // linkage but still cannot be explicitly imported or exported.7154 // In Microsoft mode, a variable defined in anonymous namespace must have7155 // external linkage in order to be exported.7156 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;7157 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||7158 (!AnonNSInMicrosoftMode &&7159 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {7160 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)7161 << &ND << Attr;7162 ND.setInvalidDecl();7163 }7164 }7165}7166 7167static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {7168 // Check the attributes on the function type and function params, if any.7169 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {7170 FD = FD->getMostRecentDecl();7171 // Don't declare this variable in the second operand of the for-statement;7172 // GCC miscompiles that by ending its lifetime before evaluating the7173 // third operand. See gcc.gnu.org/PR86769.7174 AttributedTypeLoc ATL;7175 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();7176 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());7177 TL = ATL.getModifiedLoc()) {7178 // The [[lifetimebound]] attribute can be applied to the implicit object7179 // parameter of a non-static member function (other than a ctor or dtor)7180 // by applying it to the function type.7181 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {7182 const auto *MD = dyn_cast<CXXMethodDecl>(FD);7183 int NoImplicitObjectError = -1;7184 if (!MD)7185 NoImplicitObjectError = 0;7186 else if (MD->isStatic())7187 NoImplicitObjectError = 1;7188 else if (MD->isExplicitObjectMemberFunction())7189 NoImplicitObjectError = 2;7190 if (NoImplicitObjectError != -1) {7191 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)7192 << NoImplicitObjectError << A->getRange();7193 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {7194 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)7195 << isa<CXXDestructorDecl>(MD) << A->getRange();7196 } else if (MD->getReturnType()->isVoidType()) {7197 S.Diag(7198 MD->getLocation(),7199 diag::7200 err_lifetimebound_implicit_object_parameter_void_return_type);7201 }7202 }7203 }7204 7205 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {7206 const ParmVarDecl *P = FD->getParamDecl(I);7207 7208 // The [[lifetimebound]] attribute can be applied to a function parameter7209 // only if the function returns a value.7210 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {7211 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {7212 S.Diag(A->getLocation(),7213 diag::err_lifetimebound_parameter_void_return_type);7214 }7215 }7216 }7217 }7218}7219 7220static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {7221 // Ensure that an auto decl is deduced otherwise the checks below might cache7222 // the wrong linkage.7223 assert(S.ParsingInitForAutoVars.count(&ND) == 0);7224 7225 checkWeakAttr(S, ND);7226 checkWeakRefAttr(S, ND);7227 checkAliasAttr(S, ND);7228 checkSelectAnyAttr(S, ND);7229 checkHybridPatchableAttr(S, ND);7230 checkInheritableAttr(S, ND);7231 checkLifetimeBoundAttr(S, ND);7232}7233 7234static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,7235 NamedDecl *NewDecl,7236 bool IsSpecialization,7237 bool IsDefinition) {7238 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())7239 return;7240 7241 bool IsTemplate = false;7242 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {7243 OldDecl = OldTD->getTemplatedDecl();7244 IsTemplate = true;7245 if (!IsSpecialization)7246 IsDefinition = false;7247 }7248 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {7249 NewDecl = NewTD->getTemplatedDecl();7250 IsTemplate = true;7251 }7252 7253 if (!OldDecl || !NewDecl)7254 return;7255 7256 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();7257 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();7258 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();7259 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();7260 7261 // dllimport and dllexport are inheritable attributes so we have to exclude7262 // inherited attribute instances.7263 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||7264 (NewExportAttr && !NewExportAttr->isInherited());7265 7266 // A redeclaration is not allowed to add a dllimport or dllexport attribute,7267 // the only exception being explicit specializations.7268 // Implicitly generated declarations are also excluded for now because there7269 // is no other way to switch these to use dllimport or dllexport.7270 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;7271 7272 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {7273 // Allow with a warning for free functions and global variables.7274 bool JustWarn = false;7275 if (!OldDecl->isCXXClassMember()) {7276 auto *VD = dyn_cast<VarDecl>(OldDecl);7277 if (VD && !VD->getDescribedVarTemplate())7278 JustWarn = true;7279 auto *FD = dyn_cast<FunctionDecl>(OldDecl);7280 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)7281 JustWarn = true;7282 }7283 7284 // We cannot change a declaration that's been used because IR has already7285 // been emitted. Dllimported functions will still work though (modulo7286 // address equality) as they can use the thunk.7287 if (OldDecl->isUsed())7288 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)7289 JustWarn = false;7290 7291 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration7292 : diag::err_attribute_dll_redeclaration;7293 S.Diag(NewDecl->getLocation(), DiagID)7294 << NewDecl7295 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);7296 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);7297 if (!JustWarn) {7298 NewDecl->setInvalidDecl();7299 return;7300 }7301 }7302 7303 // A redeclaration is not allowed to drop a dllimport attribute, the only7304 // exceptions being inline function definitions (except for function7305 // templates), local extern declarations, qualified friend declarations or7306 // special MSVC extension: in the last case, the declaration is treated as if7307 // it were marked dllexport.7308 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;7309 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();7310 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {7311 // Ignore static data because out-of-line definitions are diagnosed7312 // separately.7313 IsStaticDataMember = VD->isStaticDataMember();7314 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=7315 VarDecl::DeclarationOnly;7316 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {7317 IsInline = FD->isInlined();7318 IsQualifiedFriend = FD->getQualifier() &&7319 FD->getFriendObjectKind() == Decl::FOK_Declared;7320 }7321 7322 if (OldImportAttr && !HasNewAttr &&7323 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&7324 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {7325 if (IsMicrosoftABI && IsDefinition) {7326 if (IsSpecialization) {7327 S.Diag(7328 NewDecl->getLocation(),7329 diag::err_attribute_dllimport_function_specialization_definition);7330 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);7331 NewDecl->dropAttr<DLLImportAttr>();7332 } else {7333 S.Diag(NewDecl->getLocation(),7334 diag::warn_redeclaration_without_import_attribute)7335 << NewDecl;7336 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);7337 NewDecl->dropAttr<DLLImportAttr>();7338 NewDecl->addAttr(DLLExportAttr::CreateImplicit(7339 S.Context, NewImportAttr->getRange()));7340 }7341 } else if (IsMicrosoftABI && IsSpecialization) {7342 assert(!IsDefinition);7343 // MSVC allows this. Keep the inherited attribute.7344 } else {7345 S.Diag(NewDecl->getLocation(),7346 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)7347 << NewDecl << OldImportAttr;7348 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);7349 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);7350 OldDecl->dropAttr<DLLImportAttr>();7351 NewDecl->dropAttr<DLLImportAttr>();7352 }7353 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {7354 // In MinGW, seeing a function declared inline drops the dllimport7355 // attribute.7356 OldDecl->dropAttr<DLLImportAttr>();7357 NewDecl->dropAttr<DLLImportAttr>();7358 S.Diag(NewDecl->getLocation(),7359 diag::warn_dllimport_dropped_from_inline_function)7360 << NewDecl << OldImportAttr;7361 }7362 7363 // A specialization of a class template member function is processed here7364 // since it's a redeclaration. If the parent class is dllexport, the7365 // specialization inherits that attribute. This doesn't happen automatically7366 // since the parent class isn't instantiated until later.7367 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {7368 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&7369 !NewImportAttr && !NewExportAttr) {7370 if (const DLLExportAttr *ParentExportAttr =7371 MD->getParent()->getAttr<DLLExportAttr>()) {7372 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);7373 NewAttr->setInherited(true);7374 NewDecl->addAttr(NewAttr);7375 }7376 }7377 }7378}7379 7380/// Given that we are within the definition of the given function,7381/// will that definition behave like C99's 'inline', where the7382/// definition is discarded except for optimization purposes?7383static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {7384 // Try to avoid calling GetGVALinkageForFunction.7385 7386 // All cases of this require the 'inline' keyword.7387 if (!FD->isInlined()) return false;7388 7389 // This is only possible in C++ with the gnu_inline attribute.7390 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())7391 return false;7392 7393 // Okay, go ahead and call the relatively-more-expensive function.7394 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;7395}7396 7397/// Determine whether a variable is extern "C" prior to attaching7398/// an initializer. We can't just call isExternC() here, because that7399/// will also compute and cache whether the declaration is externally7400/// visible, which might change when we attach the initializer.7401///7402/// This can only be used if the declaration is known to not be a7403/// redeclaration of an internal linkage declaration.7404///7405/// For instance:7406///7407/// auto x = []{};7408///7409/// Attaching the initializer here makes this declaration not externally7410/// visible, because its type has internal linkage.7411///7412/// FIXME: This is a hack.7413template<typename T>7414static bool isIncompleteDeclExternC(Sema &S, const T *D) {7415 if (S.getLangOpts().CPlusPlus) {7416 // In C++, the overloadable attribute negates the effects of extern "C".7417 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())7418 return false;7419 7420 // So do CUDA's host/device attributes.7421 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||7422 D->template hasAttr<CUDAHostAttr>()))7423 return false;7424 }7425 return D->isExternC();7426}7427 7428static bool shouldConsiderLinkage(const VarDecl *VD) {7429 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();7430 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||7431 isa<OMPDeclareMapperDecl>(DC))7432 return VD->hasExternalStorage();7433 if (DC->isFileContext())7434 return true;7435 if (DC->isRecord())7436 return false;7437 if (DC->getDeclKind() == Decl::HLSLBuffer)7438 return false;7439 7440 if (isa<RequiresExprBodyDecl>(DC))7441 return false;7442 llvm_unreachable("Unexpected context");7443}7444 7445static bool shouldConsiderLinkage(const FunctionDecl *FD) {7446 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();7447 if (DC->isFileContext() || DC->isFunctionOrMethod() ||7448 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))7449 return true;7450 if (DC->isRecord())7451 return false;7452 llvm_unreachable("Unexpected context");7453}7454 7455static bool hasParsedAttr(Scope *S, const Declarator &PD,7456 ParsedAttr::Kind Kind) {7457 // Check decl attributes on the DeclSpec.7458 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))7459 return true;7460 7461 // Walk the declarator structure, checking decl attributes that were in a type7462 // position to the decl itself.7463 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {7464 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))7465 return true;7466 }7467 7468 // Finally, check attributes on the decl itself.7469 return PD.getAttributes().hasAttribute(Kind) ||7470 PD.getDeclarationAttributes().hasAttribute(Kind);7471}7472 7473bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {7474 if (!DC->isFunctionOrMethod())7475 return false;7476 7477 // If this is a local extern function or variable declared within a function7478 // template, don't add it into the enclosing namespace scope until it is7479 // instantiated; it might have a dependent type right now.7480 if (DC->isDependentContext())7481 return true;7482 7483 // C++11 [basic.link]p7:7484 // When a block scope declaration of an entity with linkage is not found to7485 // refer to some other declaration, then that entity is a member of the7486 // innermost enclosing namespace.7487 //7488 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a7489 // semantically-enclosing namespace, not a lexically-enclosing one.7490 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))7491 DC = DC->getParent();7492 return true;7493}7494 7495/// Returns true if given declaration has external C language linkage.7496static bool isDeclExternC(const Decl *D) {7497 if (const auto *FD = dyn_cast<FunctionDecl>(D))7498 return FD->isExternC();7499 if (const auto *VD = dyn_cast<VarDecl>(D))7500 return VD->isExternC();7501 7502 llvm_unreachable("Unknown type of decl!");7503}7504 7505/// Returns true if there hasn't been any invalid type diagnosed.7506static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {7507 DeclContext *DC = NewVD->getDeclContext();7508 QualType R = NewVD->getType();7509 7510 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.7511 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function7512 // argument.7513 if (R->isImageType() || R->isPipeType()) {7514 Se.Diag(NewVD->getLocation(),7515 diag::err_opencl_type_can_only_be_used_as_function_parameter)7516 << R;7517 NewVD->setInvalidDecl();7518 return false;7519 }7520 7521 // OpenCL v1.2 s6.9.r:7522 // The event type cannot be used to declare a program scope variable.7523 // OpenCL v2.0 s6.9.q:7524 // The clk_event_t and reserve_id_t types cannot be declared in program7525 // scope.7526 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {7527 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {7528 Se.Diag(NewVD->getLocation(),7529 diag::err_invalid_type_for_program_scope_var)7530 << R;7531 NewVD->setInvalidDecl();7532 return false;7533 }7534 }7535 7536 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.7537 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",7538 Se.getLangOpts())) {7539 QualType NR = R.getCanonicalType();7540 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||7541 NR->isReferenceType()) {7542 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||7543 NR->isFunctionReferenceType()) {7544 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)7545 << NR->isReferenceType();7546 NewVD->setInvalidDecl();7547 return false;7548 }7549 NR = NR->getPointeeType();7550 }7551 }7552 7553 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",7554 Se.getLangOpts())) {7555 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and7556 // half array type (unless the cl_khr_fp16 extension is enabled).7557 if (Se.Context.getBaseElementType(R)->isHalfType()) {7558 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;7559 NewVD->setInvalidDecl();7560 return false;7561 }7562 }7563 7564 // OpenCL v1.2 s6.9.r:7565 // The event type cannot be used with the __local, __constant and __global7566 // address space qualifiers.7567 if (R->isEventT()) {7568 if (R.getAddressSpace() != LangAS::opencl_private) {7569 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);7570 NewVD->setInvalidDecl();7571 return false;7572 }7573 }7574 7575 if (R->isSamplerT()) {7576 // OpenCL v1.2 s6.9.b p4:7577 // The sampler type cannot be used with the __local and __global address7578 // space qualifiers.7579 if (R.getAddressSpace() == LangAS::opencl_local ||7580 R.getAddressSpace() == LangAS::opencl_global) {7581 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);7582 NewVD->setInvalidDecl();7583 }7584 7585 // OpenCL v1.2 s6.12.14.1:7586 // A global sampler must be declared with either the constant address7587 // space qualifier or with the const qualifier.7588 if (DC->isTranslationUnit() &&7589 !(R.getAddressSpace() == LangAS::opencl_constant ||7590 R.isConstQualified())) {7591 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);7592 NewVD->setInvalidDecl();7593 }7594 if (NewVD->isInvalidDecl())7595 return false;7596 }7597 7598 return true;7599}7600 7601template <typename AttrTy>7602static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {7603 const TypedefNameDecl *TND = TT->getDecl();7604 if (const auto *Attribute = TND->getAttr<AttrTy>()) {7605 AttrTy *Clone = Attribute->clone(S.Context);7606 Clone->setInherited(true);7607 D->addAttr(Clone);7608 }7609}7610 7611// This function emits warning and a corresponding note based on the7612// ReadOnlyPlacementAttr attribute. The warning checks that all global variable7613// declarations of an annotated type must be const qualified.7614static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {7615 QualType VarType = VD->getType().getCanonicalType();7616 7617 // Ignore local declarations (for now) and those with const qualification.7618 // TODO: Local variables should not be allowed if their type declaration has7619 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.7620 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())7621 return;7622 7623 if (VarType->isArrayType()) {7624 // Retrieve element type for array declarations.7625 VarType = S.getASTContext().getBaseElementType(VarType);7626 }7627 7628 const RecordDecl *RD = VarType->getAsRecordDecl();7629 7630 // Check if the record declaration is present and if it has any attributes.7631 if (RD == nullptr)7632 return;7633 7634 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {7635 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;7636 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);7637 return;7638 }7639}7640 7641// Checks if VD is declared at global scope or with C language linkage.7642static bool isMainVar(DeclarationName Name, VarDecl *VD) {7643 return Name.getAsIdentifierInfo() &&7644 Name.getAsIdentifierInfo()->isStr("main") &&7645 !VD->getDescribedVarTemplate() &&7646 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||7647 VD->isExternC());7648}7649 7650void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,7651 TypeSourceInfo *TInfo, VarDecl *NewVD) {7652 7653 // Quickly return if the function does not have an `asm` attribute.7654 if (E == nullptr)7655 return;7656 7657 // The parser guarantees this is a string.7658 StringLiteral *SE = cast<StringLiteral>(E);7659 StringRef Label = SE->getString();7660 QualType R = TInfo->getType();7661 if (S->getFnParent() != nullptr) {7662 switch (SC) {7663 case SC_None:7664 case SC_Auto:7665 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;7666 break;7667 case SC_Register:7668 // Local Named register7669 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&7670 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))7671 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;7672 break;7673 case SC_Static:7674 case SC_Extern:7675 case SC_PrivateExtern:7676 break;7677 }7678 } else if (SC == SC_Register) {7679 // Global Named register7680 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {7681 const auto &TI = Context.getTargetInfo();7682 bool HasSizeMismatch;7683 7684 if (!TI.isValidGCCRegisterName(Label))7685 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;7686 else if (!TI.validateGlobalRegisterVariable(Label, Context.getTypeSize(R),7687 HasSizeMismatch))7688 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;7689 else if (HasSizeMismatch)7690 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;7691 }7692 7693 if (!R->isIntegralType(Context) && !R->isPointerType()) {7694 Diag(TInfo->getTypeLoc().getBeginLoc(),7695 diag::err_asm_unsupported_register_type)7696 << TInfo->getTypeLoc().getSourceRange();7697 NewVD->setInvalidDecl(true);7698 }7699 }7700}7701 7702NamedDecl *Sema::ActOnVariableDeclarator(7703 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,7704 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,7705 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {7706 QualType R = TInfo->getType();7707 DeclarationName Name = GetNameForDeclarator(D).getName();7708 7709 IdentifierInfo *II = Name.getAsIdentifierInfo();7710 bool IsPlaceholderVariable = false;7711 7712 if (D.isDecompositionDeclarator()) {7713 // Take the name of the first declarator as our name for diagnostic7714 // purposes.7715 auto &Decomp = D.getDecompositionDeclarator();7716 if (!Decomp.bindings().empty()) {7717 II = Decomp.bindings()[0].Name;7718 Name = II;7719 }7720 } else if (!II) {7721 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;7722 return nullptr;7723 }7724 7725 7726 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();7727 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());7728 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&7729 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {7730 7731 IsPlaceholderVariable = true;7732 7733 if (!Previous.empty()) {7734 NamedDecl *PrevDecl = *Previous.begin();7735 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(7736 DC->getRedeclContext());7737 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {7738 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);7739 if (IsPlaceholderVariable)7740 DiagPlaceholderVariableDefinition(D.getIdentifierLoc());7741 }7742 }7743 }7744 7745 // dllimport globals without explicit storage class are treated as extern. We7746 // have to change the storage class this early to get the right DeclContext.7747 if (SC == SC_None && !DC->isRecord() &&7748 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&7749 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))7750 SC = SC_Extern;7751 7752 DeclContext *OriginalDC = DC;7753 bool IsLocalExternDecl = SC == SC_Extern &&7754 adjustContextForLocalExternDecl(DC);7755 7756 if (SCSpec == DeclSpec::SCS_mutable) {7757 // mutable can only appear on non-static class members, so it's always7758 // an error here7759 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);7760 D.setInvalidType();7761 SC = SC_None;7762 }7763 7764 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&7765 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(7766 D.getDeclSpec().getStorageClassSpecLoc())) {7767 // In C++11, the 'register' storage class specifier is deprecated.7768 // Suppress the warning in system macros, it's used in macros in some7769 // popular C system headers, such as in glibc's htonl() macro.7770 Diag(D.getDeclSpec().getStorageClassSpecLoc(),7771 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class7772 : diag::warn_deprecated_register)7773 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());7774 }7775 7776 DiagnoseFunctionSpecifiers(D.getDeclSpec());7777 7778 if (!DC->isRecord() && S->getFnParent() == nullptr) {7779 // C99 6.9p2: The storage-class specifiers auto and register shall not7780 // appear in the declaration specifiers in an external declaration.7781 // Global Register+Asm is a GNU extension we support.7782 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {7783 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);7784 D.setInvalidType();7785 }7786 }7787 7788 // If this variable has a VLA type and an initializer, try to7789 // fold to a constant-sized type. This is otherwise invalid.7790 if (D.hasInitializer() && R->isVariableArrayType())7791 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),7792 /*DiagID=*/0);7793 7794 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {7795 const AutoType *AT = TL.getTypePtr();7796 CheckConstrainedAuto(AT, TL.getConceptNameLoc());7797 }7798 7799 bool IsMemberSpecialization = false;7800 bool IsVariableTemplateSpecialization = false;7801 bool IsPartialSpecialization = false;7802 bool IsVariableTemplate = false;7803 VarDecl *NewVD = nullptr;7804 VarTemplateDecl *NewTemplate = nullptr;7805 TemplateParameterList *TemplateParams = nullptr;7806 if (!getLangOpts().CPlusPlus) {7807 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),7808 II, R, TInfo, SC);7809 7810 if (R->getContainedDeducedType())7811 ParsingInitForAutoVars.insert(NewVD);7812 7813 if (D.isInvalidType())7814 NewVD->setInvalidDecl();7815 7816 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&7817 NewVD->hasLocalStorage())7818 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),7819 NonTrivialCUnionContext::AutoVar, NTCUK_Destruct);7820 } else {7821 bool Invalid = false;7822 // Match up the template parameter lists with the scope specifier, then7823 // determine whether we have a template or a template specialization.7824 TemplateParams = MatchTemplateParametersToScopeSpecifier(7825 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),7826 D.getCXXScopeSpec(),7827 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId7828 ? D.getName().TemplateId7829 : nullptr,7830 TemplateParamLists,7831 /*never a friend*/ false, IsMemberSpecialization, Invalid);7832 7833 if (TemplateParams) {7834 if (DC->isDependentContext()) {7835 ContextRAII SavedContext(*this, DC);7836 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))7837 Invalid = true;7838 }7839 7840 if (!TemplateParams->size() &&7841 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {7842 // There is an extraneous 'template<>' for this variable. Complain7843 // about it, but allow the declaration of the variable.7844 Diag(TemplateParams->getTemplateLoc(),7845 diag::err_template_variable_noparams)7846 << II7847 << SourceRange(TemplateParams->getTemplateLoc(),7848 TemplateParams->getRAngleLoc());7849 TemplateParams = nullptr;7850 } else {7851 // Check that we can declare a template here.7852 if (CheckTemplateDeclScope(S, TemplateParams))7853 return nullptr;7854 7855 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {7856 // This is an explicit specialization or a partial specialization.7857 IsVariableTemplateSpecialization = true;7858 IsPartialSpecialization = TemplateParams->size() > 0;7859 } else { // if (TemplateParams->size() > 0)7860 // This is a template declaration.7861 IsVariableTemplate = true;7862 7863 // Only C++1y supports variable templates (N3651).7864 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);7865 }7866 }7867 } else {7868 // Check that we can declare a member specialization here.7869 if (!TemplateParamLists.empty() && IsMemberSpecialization &&7870 CheckTemplateDeclScope(S, TemplateParamLists.back()))7871 return nullptr;7872 assert((Invalid ||7873 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&7874 "should have a 'template<>' for this decl");7875 }7876 7877 bool IsExplicitSpecialization =7878 IsVariableTemplateSpecialization && !IsPartialSpecialization;7879 7880 // C++ [temp.expl.spec]p2:7881 // The declaration in an explicit-specialization shall not be an7882 // export-declaration. An explicit specialization shall not use a7883 // storage-class-specifier other than thread_local.7884 //7885 // We use the storage-class-specifier from DeclSpec because we may have7886 // added implicit 'extern' for declarations with __declspec(dllimport)!7887 if (SCSpec != DeclSpec::SCS_unspecified &&7888 (IsExplicitSpecialization || IsMemberSpecialization)) {7889 Diag(D.getDeclSpec().getStorageClassSpecLoc(),7890 diag::ext_explicit_specialization_storage_class)7891 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());7892 }7893 7894 if (CurContext->isRecord()) {7895 if (SC == SC_Static) {7896 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {7897 // Walk up the enclosing DeclContexts to check for any that are7898 // incompatible with static data members.7899 const DeclContext *FunctionOrMethod = nullptr;7900 const CXXRecordDecl *AnonStruct = nullptr;7901 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {7902 if (Ctxt->isFunctionOrMethod()) {7903 FunctionOrMethod = Ctxt;7904 break;7905 }7906 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);7907 if (ParentDecl && !ParentDecl->getDeclName()) {7908 AnonStruct = ParentDecl;7909 break;7910 }7911 }7912 if (FunctionOrMethod) {7913 // C++ [class.static.data]p5: A local class shall not have static7914 // data members.7915 Diag(D.getIdentifierLoc(),7916 diag::err_static_data_member_not_allowed_in_local_class)7917 << Name << RD->getDeclName() << RD->getTagKind();7918 } else if (AnonStruct) {7919 // C++ [class.static.data]p4: Unnamed classes and classes contained7920 // directly or indirectly within unnamed classes shall not contain7921 // static data members.7922 Diag(D.getIdentifierLoc(),7923 diag::err_static_data_member_not_allowed_in_anon_struct)7924 << Name << AnonStruct->getTagKind();7925 Invalid = true;7926 } else if (RD->isUnion()) {7927 // C++98 [class.union]p1: If a union contains a static data member,7928 // the program is ill-formed. C++11 drops this restriction.7929 DiagCompat(D.getIdentifierLoc(),7930 diag_compat::static_data_member_in_union)7931 << Name;7932 }7933 }7934 } else if (IsVariableTemplate || IsPartialSpecialization) {7935 // There is no such thing as a member field template.7936 Diag(D.getIdentifierLoc(), diag::err_template_member)7937 << II << TemplateParams->getSourceRange();7938 // Recover by pretending this is a static data member template.7939 SC = SC_Static;7940 }7941 } else if (DC->isRecord()) {7942 // This is an out-of-line definition of a static data member.7943 switch (SC) {7944 case SC_None:7945 break;7946 case SC_Static:7947 Diag(D.getDeclSpec().getStorageClassSpecLoc(),7948 diag::err_static_out_of_line)7949 << FixItHint::CreateRemoval(7950 D.getDeclSpec().getStorageClassSpecLoc());7951 break;7952 case SC_Auto:7953 case SC_Register:7954 case SC_Extern:7955 // [dcl.stc] p2: The auto or register specifiers shall be applied only7956 // to names of variables declared in a block or to function parameters.7957 // [dcl.stc] p6: The extern specifier cannot be used in the declaration7958 // of class members7959 7960 Diag(D.getDeclSpec().getStorageClassSpecLoc(),7961 diag::err_storage_class_for_static_member)7962 << FixItHint::CreateRemoval(7963 D.getDeclSpec().getStorageClassSpecLoc());7964 break;7965 case SC_PrivateExtern:7966 llvm_unreachable("C storage class in c++!");7967 }7968 }7969 7970 if (IsVariableTemplateSpecialization) {7971 SourceLocation TemplateKWLoc =7972 TemplateParamLists.size() > 07973 ? TemplateParamLists[0]->getTemplateLoc()7974 : SourceLocation();7975 DeclResult Res = ActOnVarTemplateSpecialization(7976 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,7977 IsPartialSpecialization);7978 if (Res.isInvalid())7979 return nullptr;7980 NewVD = cast<VarDecl>(Res.get());7981 AddToScope = false;7982 } else if (D.isDecompositionDeclarator()) {7983 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),7984 D.getIdentifierLoc(), R, TInfo, SC,7985 Bindings);7986 } else7987 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),7988 D.getIdentifierLoc(), II, R, TInfo, SC);7989 7990 // If this is supposed to be a variable template, create it as such.7991 if (IsVariableTemplate) {7992 NewTemplate =7993 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,7994 TemplateParams, NewVD);7995 NewVD->setDescribedVarTemplate(NewTemplate);7996 }7997 7998 // If this decl has an auto type in need of deduction, make a note of the7999 // Decl so we can diagnose uses of it in its own initializer.8000 if (R->getContainedDeducedType())8001 ParsingInitForAutoVars.insert(NewVD);8002 8003 if (D.isInvalidType() || Invalid) {8004 NewVD->setInvalidDecl();8005 if (NewTemplate)8006 NewTemplate->setInvalidDecl();8007 }8008 8009 SetNestedNameSpecifier(*this, NewVD, D);8010 8011 // If we have any template parameter lists that don't directly belong to8012 // the variable (matching the scope specifier), store them.8013 // An explicit variable template specialization does not own any template8014 // parameter lists.8015 unsigned VDTemplateParamLists =8016 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;8017 if (TemplateParamLists.size() > VDTemplateParamLists)8018 NewVD->setTemplateParameterListsInfo(8019 Context, TemplateParamLists.drop_back(VDTemplateParamLists));8020 }8021 8022 if (D.getDeclSpec().isInlineSpecified()) {8023 if (!getLangOpts().CPlusPlus) {8024 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)8025 << 0;8026 } else if (CurContext->isFunctionOrMethod()) {8027 // 'inline' is not allowed on block scope variable declaration.8028 Diag(D.getDeclSpec().getInlineSpecLoc(),8029 diag::err_inline_declaration_block_scope) << Name8030 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());8031 } else {8032 Diag(D.getDeclSpec().getInlineSpecLoc(),8033 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable8034 : diag::compat_pre_cxx17_inline_variable);8035 NewVD->setInlineSpecified();8036 }8037 }8038 8039 // Set the lexical context. If the declarator has a C++ scope specifier, the8040 // lexical context will be different from the semantic context.8041 NewVD->setLexicalDeclContext(CurContext);8042 if (NewTemplate)8043 NewTemplate->setLexicalDeclContext(CurContext);8044 8045 if (IsLocalExternDecl) {8046 if (D.isDecompositionDeclarator())8047 for (auto *B : Bindings)8048 B->setLocalExternDecl();8049 else8050 NewVD->setLocalExternDecl();8051 }8052 8053 bool EmitTLSUnsupportedError = false;8054 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {8055 // C++11 [dcl.stc]p4:8056 // When thread_local is applied to a variable of block scope the8057 // storage-class-specifier static is implied if it does not appear8058 // explicitly.8059 // Core issue: 'static' is not implied if the variable is declared8060 // 'extern'.8061 if (NewVD->hasLocalStorage() &&8062 (SCSpec != DeclSpec::SCS_unspecified ||8063 TSCS != DeclSpec::TSCS_thread_local ||8064 !DC->isFunctionOrMethod()))8065 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),8066 diag::err_thread_non_global)8067 << DeclSpec::getSpecifierName(TSCS);8068 else if (!Context.getTargetInfo().isTLSSupported()) {8069 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {8070 // Postpone error emission until we've collected attributes required to8071 // figure out whether it's a host or device variable and whether the8072 // error should be ignored.8073 EmitTLSUnsupportedError = true;8074 // We still need to mark the variable as TLS so it shows up in AST with8075 // proper storage class for other tools to use even if we're not going8076 // to emit any code for it.8077 NewVD->setTSCSpec(TSCS);8078 } else8079 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),8080 diag::err_thread_unsupported);8081 } else8082 NewVD->setTSCSpec(TSCS);8083 }8084 8085 switch (D.getDeclSpec().getConstexprSpecifier()) {8086 case ConstexprSpecKind::Unspecified:8087 break;8088 8089 case ConstexprSpecKind::Consteval:8090 Diag(D.getDeclSpec().getConstexprSpecLoc(),8091 diag::err_constexpr_wrong_decl_kind)8092 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());8093 [[fallthrough]];8094 8095 case ConstexprSpecKind::Constexpr:8096 NewVD->setConstexpr(true);8097 // C++1z [dcl.spec.constexpr]p1:8098 // A static data member declared with the constexpr specifier is8099 // implicitly an inline variable.8100 if (NewVD->isStaticDataMember() &&8101 (getLangOpts().CPlusPlus17 ||8102 Context.getTargetInfo().getCXXABI().isMicrosoft()))8103 NewVD->setImplicitlyInline();8104 break;8105 8106 case ConstexprSpecKind::Constinit:8107 if (!NewVD->hasGlobalStorage())8108 Diag(D.getDeclSpec().getConstexprSpecLoc(),8109 diag::err_constinit_local_variable);8110 else8111 NewVD->addAttr(8112 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),8113 ConstInitAttr::Keyword_constinit));8114 break;8115 }8116 8117 // C99 6.7.4p38118 // An inline definition of a function with external linkage shall8119 // not contain a definition of a modifiable object with static or8120 // thread storage duration...8121 // We only apply this when the function is required to be defined8122 // elsewhere, i.e. when the function is not 'extern inline'. Note8123 // that a local variable with thread storage duration still has to8124 // be marked 'static'. Also note that it's possible to get these8125 // semantics in C++ using __attribute__((gnu_inline)).8126 if (SC == SC_Static && S->getFnParent() != nullptr &&8127 !NewVD->getType().isConstQualified()) {8128 FunctionDecl *CurFD = getCurFunctionDecl();8129 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {8130 Diag(D.getDeclSpec().getStorageClassSpecLoc(),8131 diag::warn_static_local_in_extern_inline);8132 MaybeSuggestAddingStaticToDecl(CurFD);8133 }8134 }8135 8136 if (D.getDeclSpec().isModulePrivateSpecified()) {8137 if (IsVariableTemplateSpecialization)8138 Diag(NewVD->getLocation(), diag::err_module_private_specialization)8139 << (IsPartialSpecialization ? 1 : 0)8140 << FixItHint::CreateRemoval(8141 D.getDeclSpec().getModulePrivateSpecLoc());8142 else if (IsMemberSpecialization)8143 Diag(NewVD->getLocation(), diag::err_module_private_specialization)8144 << 28145 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());8146 else if (NewVD->hasLocalStorage())8147 Diag(NewVD->getLocation(), diag::err_module_private_local)8148 << 0 << NewVD8149 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())8150 << FixItHint::CreateRemoval(8151 D.getDeclSpec().getModulePrivateSpecLoc());8152 else {8153 NewVD->setModulePrivate();8154 if (NewTemplate)8155 NewTemplate->setModulePrivate();8156 for (auto *B : Bindings)8157 B->setModulePrivate();8158 }8159 }8160 8161 if (getLangOpts().OpenCL) {8162 deduceOpenCLAddressSpace(NewVD);8163 8164 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();8165 if (TSC != TSCS_unspecified) {8166 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),8167 diag::err_opencl_unknown_type_specifier)8168 << getLangOpts().getOpenCLVersionString()8169 << DeclSpec::getSpecifierName(TSC) << 1;8170 NewVD->setInvalidDecl();8171 }8172 }8173 8174 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply8175 // address space if the table has local storage (semantic checks elsewhere8176 // will produce an error anyway).8177 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {8178 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&8179 !NewVD->hasLocalStorage()) {8180 QualType Type = Context.getAddrSpaceQualType(8181 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));8182 NewVD->setType(Type);8183 }8184 }8185 8186 if (Expr *E = D.getAsmLabel()) {8187 // The parser guarantees this is a string.8188 StringLiteral *SE = cast<StringLiteral>(E);8189 StringRef Label = SE->getString();8190 8191 // Insert the asm attribute.8192 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));8193 } else if (!ExtnameUndeclaredIdentifiers.empty()) {8194 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *>::iterator I =8195 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());8196 if (I != ExtnameUndeclaredIdentifiers.end()) {8197 if (isDeclExternC(NewVD)) {8198 NewVD->addAttr(I->second);8199 ExtnameUndeclaredIdentifiers.erase(I);8200 } else8201 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)8202 << /*Variable*/ 1 << NewVD;8203 }8204 }8205 8206 // Handle attributes prior to checking for duplicates in MergeVarDecl8207 ProcessDeclAttributes(S, NewVD, D);8208 8209 if (getLangOpts().HLSL)8210 HLSL().ActOnVariableDeclarator(NewVD);8211 8212 if (getLangOpts().OpenACC)8213 OpenACC().ActOnVariableDeclarator(NewVD);8214 8215 // FIXME: This is probably the wrong location to be doing this and we should8216 // probably be doing this for more attributes (especially for function8217 // pointer attributes such as format, warn_unused_result, etc.). Ideally8218 // the code to copy attributes would be generated by TableGen.8219 if (R->isFunctionPointerType())8220 if (const auto *TT = R->getAs<TypedefType>())8221 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);8222 8223 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {8224 if (EmitTLSUnsupportedError &&8225 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||8226 (getLangOpts().OpenMPIsTargetDevice &&8227 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))8228 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),8229 diag::err_thread_unsupported);8230 8231 if (EmitTLSUnsupportedError &&8232 (LangOpts.SYCLIsDevice ||8233 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))8234 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);8235 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static8236 // storage [duration]."8237 if (SC == SC_None && S->getFnParent() != nullptr &&8238 (NewVD->hasAttr<CUDASharedAttr>() ||8239 NewVD->hasAttr<CUDAConstantAttr>())) {8240 NewVD->setStorageClass(SC_Static);8241 }8242 }8243 8244 // Ensure that dllimport globals without explicit storage class are treated as8245 // extern. The storage class is set above using parsed attributes. Now we can8246 // check the VarDecl itself.8247 assert(!NewVD->hasAttr<DLLImportAttr>() ||8248 NewVD->getAttr<DLLImportAttr>()->isInherited() ||8249 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);8250 8251 // In auto-retain/release, infer strong retension for variables of8252 // retainable type.8253 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))8254 NewVD->setInvalidDecl();8255 8256 // Check the ASM label here, as we need to know all other attributes of the8257 // Decl first. Otherwise, we can't know if the asm label refers to the8258 // host or device in a CUDA context. The device has other registers than8259 // host and we must know where the function will be placed.8260 CheckAsmLabel(S, D.getAsmLabel(), SC, TInfo, NewVD);8261 8262 // Find the shadowed declaration before filtering for scope.8263 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()8264 ? getShadowedDeclaration(NewVD, Previous)8265 : nullptr;8266 8267 // Don't consider existing declarations that are in a different8268 // scope and are out-of-semantic-context declarations (if the new8269 // declaration has linkage).8270 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),8271 D.getCXXScopeSpec().isNotEmpty() ||8272 IsMemberSpecialization ||8273 IsVariableTemplateSpecialization);8274 8275 // Check whether the previous declaration is in the same block scope. This8276 // affects whether we merge types with it, per C++11 [dcl.array]p3.8277 if (getLangOpts().CPlusPlus &&8278 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())8279 NewVD->setPreviousDeclInSameBlockScope(8280 Previous.isSingleResult() && !Previous.isShadowed() &&8281 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));8282 8283 if (!getLangOpts().CPlusPlus) {8284 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));8285 } else {8286 // If this is an explicit specialization of a static data member, check it.8287 if (IsMemberSpecialization && !IsVariableTemplate &&8288 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&8289 CheckMemberSpecialization(NewVD, Previous))8290 NewVD->setInvalidDecl();8291 8292 // Merge the decl with the existing one if appropriate.8293 if (!Previous.empty()) {8294 if (Previous.isSingleResult() &&8295 isa<FieldDecl>(Previous.getFoundDecl()) &&8296 D.getCXXScopeSpec().isSet()) {8297 // The user tried to define a non-static data member8298 // out-of-line (C++ [dcl.meaning]p1).8299 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)8300 << D.getCXXScopeSpec().getRange();8301 Previous.clear();8302 NewVD->setInvalidDecl();8303 }8304 } else if (D.getCXXScopeSpec().isSet() &&8305 !IsVariableTemplateSpecialization) {8306 // No previous declaration in the qualifying scope.8307 Diag(D.getIdentifierLoc(), diag::err_no_member)8308 << Name << computeDeclContext(D.getCXXScopeSpec(), true)8309 << D.getCXXScopeSpec().getRange();8310 NewVD->setInvalidDecl();8311 }8312 8313 if (!IsPlaceholderVariable)8314 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));8315 8316 // CheckVariableDeclaration will set NewVD as invalid if something is in8317 // error like WebAssembly tables being declared as arrays with a non-zero8318 // size, but then parsing continues and emits further errors on that line.8319 // To avoid that we check here if it happened and return nullptr.8320 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())8321 return nullptr;8322 8323 if (NewTemplate) {8324 VarTemplateDecl *PrevVarTemplate =8325 NewVD->getPreviousDecl()8326 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()8327 : nullptr;8328 8329 // Check the template parameter list of this declaration, possibly8330 // merging in the template parameter list from the previous variable8331 // template declaration.8332 if (CheckTemplateParameterList(8333 TemplateParams,8334 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()8335 : nullptr,8336 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&8337 DC->isDependentContext())8338 ? TPC_ClassTemplateMember8339 : TPC_Other))8340 NewVD->setInvalidDecl();8341 8342 // If we are providing an explicit specialization of a static variable8343 // template, make a note of that.8344 if (PrevVarTemplate &&8345 PrevVarTemplate->getInstantiatedFromMemberTemplate())8346 PrevVarTemplate->setMemberSpecialization();8347 }8348 }8349 8350 // Diagnose shadowed variables iff this isn't a redeclaration.8351 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())8352 CheckShadow(NewVD, ShadowedDecl, Previous);8353 8354 ProcessPragmaWeak(S, NewVD);8355 8356 // If this is the first declaration of an extern C variable, update8357 // the map of such variables.8358 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&8359 isIncompleteDeclExternC(*this, NewVD))8360 RegisterLocallyScopedExternCDecl(NewVD, S);8361 8362 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {8363 MangleNumberingContext *MCtx;8364 Decl *ManglingContextDecl;8365 std::tie(MCtx, ManglingContextDecl) =8366 getCurrentMangleNumberContext(NewVD->getDeclContext());8367 if (MCtx) {8368 Context.setManglingNumber(8369 NewVD, MCtx->getManglingNumber(8370 NewVD, getMSManglingNumber(getLangOpts(), S)));8371 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));8372 }8373 }8374 8375 // Special handling of variable named 'main'.8376 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {8377 // C++ [basic.start.main]p3:8378 // A program that declares8379 // - a variable main at global scope, or8380 // - an entity named main with C language linkage (in any namespace)8381 // is ill-formed8382 if (getLangOpts().CPlusPlus)8383 Diag(D.getBeginLoc(), diag::err_main_global_variable)8384 << NewVD->isExternC();8385 8386 // In C, and external-linkage variable named main results in undefined8387 // behavior.8388 else if (NewVD->hasExternalFormalLinkage())8389 Diag(D.getBeginLoc(), diag::warn_main_redefined);8390 }8391 8392 if (D.isRedeclaration() && !Previous.empty()) {8393 NamedDecl *Prev = Previous.getRepresentativeDecl();8394 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,8395 D.isFunctionDefinition());8396 }8397 8398 if (NewTemplate) {8399 if (NewVD->isInvalidDecl())8400 NewTemplate->setInvalidDecl();8401 ActOnDocumentableDecl(NewTemplate);8402 return NewTemplate;8403 }8404 8405 if (IsMemberSpecialization && !NewVD->isInvalidDecl())8406 CompleteMemberSpecialization(NewVD, Previous);8407 8408 emitReadOnlyPlacementAttrWarning(*this, NewVD);8409 8410 return NewVD;8411}8412 8413/// Enum describing the %select options in diag::warn_decl_shadow.8414enum ShadowedDeclKind {8415 SDK_Local,8416 SDK_Global,8417 SDK_StaticMember,8418 SDK_Field,8419 SDK_Typedef,8420 SDK_Using,8421 SDK_StructuredBinding8422};8423 8424/// Determine what kind of declaration we're shadowing.8425static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,8426 const DeclContext *OldDC) {8427 if (isa<TypeAliasDecl>(ShadowedDecl))8428 return SDK_Using;8429 else if (isa<TypedefDecl>(ShadowedDecl))8430 return SDK_Typedef;8431 else if (isa<BindingDecl>(ShadowedDecl))8432 return SDK_StructuredBinding;8433 else if (isa<RecordDecl>(OldDC))8434 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;8435 8436 return OldDC->isFileContext() ? SDK_Global : SDK_Local;8437}8438 8439/// Return the location of the capture if the given lambda captures the given8440/// variable \p VD, or an invalid source location otherwise.8441static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,8442 const ValueDecl *VD) {8443 for (const Capture &Capture : LSI->Captures) {8444 if (Capture.isVariableCapture() && Capture.getVariable() == VD)8445 return Capture.getLocation();8446 }8447 return SourceLocation();8448}8449 8450static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,8451 const LookupResult &R) {8452 // Only diagnose if we're shadowing an unambiguous field or variable.8453 if (R.getResultKind() != LookupResultKind::Found)8454 return false;8455 8456 // Return false if warning is ignored.8457 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());8458}8459 8460NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,8461 const LookupResult &R) {8462 if (!shouldWarnIfShadowedDecl(Diags, R))8463 return nullptr;8464 8465 // Don't diagnose declarations at file scope.8466 if (D->hasGlobalStorage() && !D->isStaticLocal())8467 return nullptr;8468 8469 NamedDecl *ShadowedDecl = R.getFoundDecl();8470 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl8471 : nullptr;8472}8473 8474NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,8475 const LookupResult &R) {8476 // Don't warn if typedef declaration is part of a class8477 if (D->getDeclContext()->isRecord())8478 return nullptr;8479 8480 if (!shouldWarnIfShadowedDecl(Diags, R))8481 return nullptr;8482 8483 NamedDecl *ShadowedDecl = R.getFoundDecl();8484 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;8485}8486 8487NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,8488 const LookupResult &R) {8489 if (!shouldWarnIfShadowedDecl(Diags, R))8490 return nullptr;8491 8492 NamedDecl *ShadowedDecl = R.getFoundDecl();8493 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl8494 : nullptr;8495}8496 8497void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,8498 const LookupResult &R) {8499 DeclContext *NewDC = D->getDeclContext();8500 8501 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {8502 if (const auto *MD =8503 dyn_cast<CXXMethodDecl>(getFunctionLevelDeclContext())) {8504 // Fields aren't shadowed in C++ static members or in member functions8505 // with an explicit object parameter.8506 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())8507 return;8508 }8509 // Fields shadowed by constructor parameters are a special case. Usually8510 // the constructor initializes the field with the parameter.8511 if (isa<CXXConstructorDecl>(NewDC))8512 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {8513 // Remember that this was shadowed so we can either warn about its8514 // modification or its existence depending on warning settings.8515 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});8516 return;8517 }8518 }8519 8520 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))8521 if (shadowedVar->isExternC()) {8522 // For shadowing external vars, make sure that we point to the global8523 // declaration, not a locally scoped extern declaration.8524 for (auto *I : shadowedVar->redecls())8525 if (I->isFileVarDecl()) {8526 ShadowedDecl = I;8527 break;8528 }8529 }8530 8531 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();8532 8533 unsigned WarningDiag = diag::warn_decl_shadow;8534 SourceLocation CaptureLoc;8535 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {8536 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {8537 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {8538 // Handle both VarDecl and BindingDecl in lambda contexts8539 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {8540 const auto *VD = cast<ValueDecl>(ShadowedDecl);8541 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());8542 if (RD->getLambdaCaptureDefault() == LCD_None) {8543 // Try to avoid warnings for lambdas with an explicit capture8544 // list. Warn only when the lambda captures the shadowed decl8545 // explicitly.8546 CaptureLoc = getCaptureLocation(LSI, VD);8547 if (CaptureLoc.isInvalid())8548 WarningDiag = diag::warn_decl_shadow_uncaptured_local;8549 } else {8550 // Remember that this was shadowed so we can avoid the warning if8551 // the shadowed decl isn't captured and the warning settings allow8552 // it.8553 cast<LambdaScopeInfo>(getCurFunction())8554 ->ShadowingDecls.push_back({D, VD});8555 return;8556 }8557 }8558 if (isa<FieldDecl>(ShadowedDecl)) {8559 // If lambda can capture this, then emit default shadowing warning,8560 // Otherwise it is not really a shadowing case since field is not8561 // available in lambda's body.8562 // At this point we don't know that lambda can capture this, so8563 // remember that this was shadowed and delay until we know.8564 cast<LambdaScopeInfo>(getCurFunction())8565 ->ShadowingDecls.push_back({D, ShadowedDecl});8566 return;8567 }8568 }8569 // Apply scoping logic to both VarDecl and BindingDecl with local storage8570 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {8571 bool HasLocalStorage = false;8572 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))8573 HasLocalStorage = VD->hasLocalStorage();8574 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))8575 HasLocalStorage =8576 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();8577 8578 if (HasLocalStorage) {8579 // A variable can't shadow a local variable or binding in an enclosing8580 // scope, if they are separated by a non-capturing declaration8581 // context.8582 for (DeclContext *ParentDC = NewDC;8583 ParentDC && !ParentDC->Equals(OldDC);8584 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {8585 // Only block literals, captured statements, and lambda expressions8586 // can capture; other scopes don't.8587 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&8588 !isLambdaCallOperator(ParentDC))8589 return;8590 }8591 }8592 }8593 }8594 }8595 8596 // Never warn about shadowing a placeholder variable.8597 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))8598 return;8599 8600 // Only warn about certain kinds of shadowing for class members.8601 if (NewDC) {8602 // In particular, don't warn about shadowing non-class members.8603 if (NewDC->isRecord() && !OldDC->isRecord())8604 return;8605 8606 // Skip shadowing check if we're in a class scope, dealing with an enum8607 // constant in a different context.8608 DeclContext *ReDC = NewDC->getRedeclContext();8609 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))8610 return;8611 8612 // TODO: should we warn about static data members shadowing8613 // static data members from base classes?8614 8615 // TODO: don't diagnose for inaccessible shadowed members.8616 // This is hard to do perfectly because we might friend the8617 // shadowing context, but that's just a false negative.8618 }8619 8620 DeclarationName Name = R.getLookupName();8621 8622 // Emit warning and note.8623 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);8624 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;8625 if (!CaptureLoc.isInvalid())8626 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)8627 << Name << /*explicitly*/ 1;8628 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);8629}8630 8631void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {8632 for (const auto &Shadow : LSI->ShadowingDecls) {8633 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;8634 // Try to avoid the warning when the shadowed decl isn't captured.8635 const DeclContext *OldDC = ShadowedDecl->getDeclContext();8636 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {8637 const auto *VD = cast<ValueDecl>(ShadowedDecl);8638 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);8639 Diag(Shadow.VD->getLocation(),8640 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local8641 : diag::warn_decl_shadow)8642 << Shadow.VD->getDeclName()8643 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;8644 if (CaptureLoc.isValid())8645 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)8646 << Shadow.VD->getDeclName() << /*explicitly*/ 0;8647 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);8648 } else if (isa<FieldDecl>(ShadowedDecl)) {8649 Diag(Shadow.VD->getLocation(),8650 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow8651 : diag::warn_decl_shadow_uncaptured_local)8652 << Shadow.VD->getDeclName()8653 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;8654 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);8655 }8656 }8657}8658 8659void Sema::CheckShadow(Scope *S, VarDecl *D) {8660 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))8661 return;8662 8663 LookupResult R(*this, D->getDeclName(), D->getLocation(),8664 Sema::LookupOrdinaryName,8665 RedeclarationKind::ForVisibleRedeclaration);8666 LookupName(R, S);8667 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))8668 CheckShadow(D, ShadowedDecl, R);8669}8670 8671/// Check if 'E', which is an expression that is about to be modified, refers8672/// to a constructor parameter that shadows a field.8673void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {8674 // Quickly ignore expressions that can't be shadowing ctor parameters.8675 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())8676 return;8677 E = E->IgnoreParenImpCasts();8678 auto *DRE = dyn_cast<DeclRefExpr>(E);8679 if (!DRE)8680 return;8681 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());8682 auto I = ShadowingDecls.find(D);8683 if (I == ShadowingDecls.end())8684 return;8685 const NamedDecl *ShadowedDecl = I->second;8686 const DeclContext *OldDC = ShadowedDecl->getDeclContext();8687 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;8688 Diag(D->getLocation(), diag::note_var_declared_here) << D;8689 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);8690 8691 // Avoid issuing multiple warnings about the same decl.8692 ShadowingDecls.erase(I);8693}8694 8695/// Check for conflict between this global or extern "C" declaration and8696/// previous global or extern "C" declarations. This is only used in C++.8697template<typename T>8698static bool checkGlobalOrExternCConflict(8699 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {8700 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");8701 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());8702 8703 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {8704 // The common case: this global doesn't conflict with any extern "C"8705 // declaration.8706 return false;8707 }8708 8709 if (Prev) {8710 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {8711 // Both the old and new declarations have C language linkage. This is a8712 // redeclaration.8713 Previous.clear();8714 Previous.addDecl(Prev);8715 return true;8716 }8717 8718 // This is a global, non-extern "C" declaration, and there is a previous8719 // non-global extern "C" declaration. Diagnose if this is a variable8720 // declaration.8721 if (!isa<VarDecl>(ND))8722 return false;8723 } else {8724 // The declaration is extern "C". Check for any declaration in the8725 // translation unit which might conflict.8726 if (IsGlobal) {8727 // We have already performed the lookup into the translation unit.8728 IsGlobal = false;8729 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();8730 I != E; ++I) {8731 if (isa<VarDecl>(*I)) {8732 Prev = *I;8733 break;8734 }8735 }8736 } else {8737 DeclContext::lookup_result R =8738 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());8739 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();8740 I != E; ++I) {8741 if (isa<VarDecl>(*I)) {8742 Prev = *I;8743 break;8744 }8745 // FIXME: If we have any other entity with this name in global scope,8746 // the declaration is ill-formed, but that is a defect: it breaks the8747 // 'stat' hack, for instance. Only variables can have mangled name8748 // clashes with extern "C" declarations, so only they deserve a8749 // diagnostic.8750 }8751 }8752 8753 if (!Prev)8754 return false;8755 }8756 8757 // Use the first declaration's location to ensure we point at something which8758 // is lexically inside an extern "C" linkage-spec.8759 assert(Prev && "should have found a previous declaration to diagnose");8760 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))8761 Prev = FD->getFirstDecl();8762 else8763 Prev = cast<VarDecl>(Prev)->getFirstDecl();8764 8765 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)8766 << IsGlobal << ND;8767 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)8768 << IsGlobal;8769 return false;8770}8771 8772/// Apply special rules for handling extern "C" declarations. Returns \c true8773/// if we have found that this is a redeclaration of some prior entity.8774///8775/// Per C++ [dcl.link]p6:8776/// Two declarations [for a function or variable] with C language linkage8777/// with the same name that appear in different scopes refer to the same8778/// [entity]. An entity with C language linkage shall not be declared with8779/// the same name as an entity in global scope.8780template<typename T>8781static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,8782 LookupResult &Previous) {8783 if (!S.getLangOpts().CPlusPlus) {8784 // In C, when declaring a global variable, look for a corresponding 'extern'8785 // variable declared in function scope. We don't need this in C++, because8786 // we find local extern decls in the surrounding file-scope DeclContext.8787 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {8788 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {8789 Previous.clear();8790 Previous.addDecl(Prev);8791 return true;8792 }8793 }8794 return false;8795 }8796 8797 // A declaration in the translation unit can conflict with an extern "C"8798 // declaration.8799 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())8800 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);8801 8802 // An extern "C" declaration can conflict with a declaration in the8803 // translation unit or can be a redeclaration of an extern "C" declaration8804 // in another scope.8805 if (isIncompleteDeclExternC(S,ND))8806 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);8807 8808 // Neither global nor extern "C": nothing to do.8809 return false;8810}8811 8812static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,8813 QualType T) {8814 QualType CanonT = SemaRef.Context.getCanonicalType(T);8815 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or8816 // any of its members, even recursively, shall not have an atomic type, or a8817 // variably modified type, or a type that is volatile or restrict qualified.8818 if (CanonT->isVariablyModifiedType()) {8819 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;8820 return true;8821 }8822 8823 // Arrays are qualified by their element type, so get the base type (this8824 // works on non-arrays as well).8825 CanonT = SemaRef.Context.getBaseElementType(CanonT);8826 8827 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||8828 CanonT.isRestrictQualified()) {8829 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;8830 return true;8831 }8832 8833 if (CanonT->isRecordType()) {8834 const RecordDecl *RD = CanonT->getAsRecordDecl();8835 if (!RD->isInvalidDecl() &&8836 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {8837 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());8838 }))8839 return true;8840 }8841 8842 return false;8843}8844 8845void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {8846 // If the decl is already known invalid, don't check it.8847 if (NewVD->isInvalidDecl())8848 return;8849 8850 QualType T = NewVD->getType();8851 8852 // Defer checking an 'auto' type until its initializer is attached.8853 if (T->isUndeducedType())8854 return;8855 8856 if (NewVD->hasAttrs())8857 CheckAlignasUnderalignment(NewVD);8858 8859 if (T->isObjCObjectType()) {8860 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)8861 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");8862 T = Context.getObjCObjectPointerType(T);8863 NewVD->setType(T);8864 }8865 8866 // Emit an error if an address space was applied to decl with local storage.8867 // This includes arrays of objects with address space qualifiers, but not8868 // automatic variables that point to other address spaces.8869 // ISO/IEC TR 18037 S5.1.28870 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&8871 T.getAddressSpace() != LangAS::Default) {8872 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;8873 NewVD->setInvalidDecl();8874 return;8875 }8876 8877 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program8878 // scope.8879 if (getLangOpts().OpenCLVersion == 120 &&8880 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",8881 getLangOpts()) &&8882 NewVD->isStaticLocal()) {8883 Diag(NewVD->getLocation(), diag::err_static_function_scope);8884 NewVD->setInvalidDecl();8885 return;8886 }8887 8888 if (getLangOpts().OpenCL) {8889 if (!diagnoseOpenCLTypes(*this, NewVD))8890 return;8891 8892 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.8893 if (NewVD->hasAttr<BlocksAttr>()) {8894 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);8895 return;8896 }8897 8898 if (T->isBlockPointerType()) {8899 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and8900 // can't use 'extern' storage class.8901 if (!T.isConstQualified()) {8902 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)8903 << 0 /*const*/;8904 NewVD->setInvalidDecl();8905 return;8906 }8907 if (NewVD->hasExternalStorage()) {8908 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);8909 NewVD->setInvalidDecl();8910 return;8911 }8912 }8913 8914 // FIXME: Adding local AS in C++ for OpenCL might make sense.8915 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||8916 NewVD->hasExternalStorage()) {8917 if (!T->isSamplerT() && !T->isDependentType() &&8918 !(T.getAddressSpace() == LangAS::opencl_constant ||8919 (T.getAddressSpace() == LangAS::opencl_global &&8920 getOpenCLOptions().areProgramScopeVariablesSupported(8921 getLangOpts())))) {8922 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;8923 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))8924 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)8925 << Scope << "global or constant";8926 else8927 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)8928 << Scope << "constant";8929 NewVD->setInvalidDecl();8930 return;8931 }8932 } else {8933 if (T.getAddressSpace() == LangAS::opencl_global) {8934 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)8935 << 1 /*is any function*/ << "global";8936 NewVD->setInvalidDecl();8937 return;8938 }8939 if (T.getAddressSpace() == LangAS::opencl_constant ||8940 T.getAddressSpace() == LangAS::opencl_local) {8941 FunctionDecl *FD = getCurFunctionDecl();8942 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables8943 // in functions.8944 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {8945 if (T.getAddressSpace() == LangAS::opencl_constant)8946 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)8947 << 0 /*non-kernel only*/ << "constant";8948 else8949 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)8950 << 0 /*non-kernel only*/ << "local";8951 NewVD->setInvalidDecl();8952 return;8953 }8954 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be8955 // in the outermost scope of a kernel function.8956 if (FD && FD->hasAttr<DeviceKernelAttr>()) {8957 if (!getCurScope()->isFunctionScope()) {8958 if (T.getAddressSpace() == LangAS::opencl_constant)8959 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)8960 << "constant";8961 else8962 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)8963 << "local";8964 NewVD->setInvalidDecl();8965 return;8966 }8967 }8968 } else if (T.getAddressSpace() != LangAS::opencl_private &&8969 // If we are parsing a template we didn't deduce an addr8970 // space yet.8971 T.getAddressSpace() != LangAS::Default) {8972 // Do not allow other address spaces on automatic variable.8973 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;8974 NewVD->setInvalidDecl();8975 return;8976 }8977 }8978 }8979 8980 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()8981 && !NewVD->hasAttr<BlocksAttr>()) {8982 if (getLangOpts().getGC() != LangOptions::NonGC)8983 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);8984 else {8985 assert(!getLangOpts().ObjCAutoRefCount);8986 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);8987 }8988 }8989 8990 // WebAssembly tables must be static with a zero length and can't be8991 // declared within functions.8992 if (T->isWebAssemblyTableType()) {8993 if (getCurScope()->getParent()) { // Parent is null at top-level8994 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);8995 NewVD->setInvalidDecl();8996 return;8997 }8998 if (NewVD->getStorageClass() != SC_Static) {8999 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);9000 NewVD->setInvalidDecl();9001 return;9002 }9003 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());9004 if (!ATy || ATy->getZExtSize() != 0) {9005 Diag(NewVD->getLocation(),9006 diag::err_typecheck_wasm_table_must_have_zero_length);9007 NewVD->setInvalidDecl();9008 return;9009 }9010 }9011 9012 // zero sized static arrays are not allowed in HIP device functions9013 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {9014 if (FunctionDecl *FD = getCurFunctionDecl();9015 FD &&9016 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {9017 if (const ConstantArrayType *ArrayT =9018 getASTContext().getAsConstantArrayType(T);9019 ArrayT && ArrayT->isZeroSize()) {9020 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;9021 }9022 }9023 }9024 9025 bool isVM = T->isVariablyModifiedType();9026 if (isVM || NewVD->hasAttr<CleanupAttr>() ||9027 NewVD->hasAttr<BlocksAttr>())9028 setFunctionHasBranchProtectedScope();9029 9030 if ((isVM && NewVD->hasLinkage()) ||9031 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {9032 bool SizeIsNegative;9033 llvm::APSInt Oversized;9034 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(9035 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);9036 QualType FixedT;9037 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())9038 FixedT = FixedTInfo->getType();9039 else if (FixedTInfo) {9040 // Type and type-as-written are canonically different. We need to fix up9041 // both types separately.9042 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,9043 Oversized);9044 }9045 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {9046 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);9047 // FIXME: This won't give the correct result for9048 // int a[10][n];9049 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();9050 9051 if (NewVD->isFileVarDecl())9052 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)9053 << SizeRange;9054 else if (NewVD->isStaticLocal())9055 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)9056 << SizeRange;9057 else9058 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)9059 << SizeRange;9060 NewVD->setInvalidDecl();9061 return;9062 }9063 9064 if (!FixedTInfo) {9065 if (NewVD->isFileVarDecl())9066 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);9067 else9068 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);9069 NewVD->setInvalidDecl();9070 return;9071 }9072 9073 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);9074 NewVD->setType(FixedT);9075 NewVD->setTypeSourceInfo(FixedTInfo);9076 }9077 9078 if (T->isVoidType()) {9079 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names9080 // of objects and functions.9081 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {9082 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)9083 << T;9084 NewVD->setInvalidDecl();9085 return;9086 }9087 }9088 9089 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {9090 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);9091 NewVD->setInvalidDecl();9092 return;9093 }9094 9095 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&9096 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {9097 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;9098 NewVD->setInvalidDecl();9099 return;9100 }9101 9102 if (isVM && NewVD->hasAttr<BlocksAttr>()) {9103 Diag(NewVD->getLocation(), diag::err_block_on_vm);9104 NewVD->setInvalidDecl();9105 return;9106 }9107 9108 if (getLangOpts().C23 && NewVD->isConstexpr() &&9109 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {9110 NewVD->setInvalidDecl();9111 return;9112 }9113 9114 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&9115 !T->isDependentType() &&9116 RequireLiteralType(NewVD->getLocation(), T,9117 diag::err_constexpr_var_non_literal)) {9118 NewVD->setInvalidDecl();9119 return;9120 }9121 9122 // PPC MMA non-pointer types are not allowed as non-local variable types.9123 if (Context.getTargetInfo().getTriple().isPPC64() &&9124 !NewVD->isLocalVarDecl() &&9125 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {9126 NewVD->setInvalidDecl();9127 return;9128 }9129 9130 // Check that SVE types are only used in functions with SVE available.9131 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {9132 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);9133 llvm::StringMap<bool> CallerFeatureMap;9134 Context.getFunctionFeatureMap(CallerFeatureMap, FD);9135 if (ARM().checkSVETypeSupport(T, NewVD->getLocation(), FD,9136 CallerFeatureMap)) {9137 NewVD->setInvalidDecl();9138 return;9139 }9140 }9141 9142 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {9143 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);9144 llvm::StringMap<bool> CallerFeatureMap;9145 Context.getFunctionFeatureMap(CallerFeatureMap, FD);9146 RISCV().checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),9147 CallerFeatureMap);9148 }9149}9150 9151bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {9152 CheckVariableDeclarationType(NewVD);9153 9154 // If the decl is already known invalid, don't check it.9155 if (NewVD->isInvalidDecl())9156 return false;9157 9158 // If we did not find anything by this name, look for a non-visible9159 // extern "C" declaration with the same name.9160 if (Previous.empty() &&9161 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))9162 Previous.setShadowed();9163 9164 if (!Previous.empty()) {9165 MergeVarDecl(NewVD, Previous);9166 return true;9167 }9168 return false;9169}9170 9171bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {9172 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;9173 9174 // Look for methods in base classes that this method might override.9175 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,9176 /*DetectVirtual=*/false);9177 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {9178 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();9179 DeclarationName Name = MD->getDeclName();9180 9181 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {9182 // We really want to find the base class destructor here.9183 Name = Context.DeclarationNames.getCXXDestructorName(9184 Context.getCanonicalTagType(BaseRecord));9185 }9186 9187 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {9188 CXXMethodDecl *BaseMD =9189 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());9190 if (!BaseMD || !BaseMD->isVirtual() ||9191 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,9192 /*ConsiderCudaAttrs=*/true))9193 continue;9194 if (!CheckExplicitObjectOverride(MD, BaseMD))9195 continue;9196 if (Overridden.insert(BaseMD).second) {9197 MD->addOverriddenMethod(BaseMD);9198 CheckOverridingFunctionReturnType(MD, BaseMD);9199 CheckOverridingFunctionAttributes(MD, BaseMD);9200 CheckOverridingFunctionExceptionSpec(MD, BaseMD);9201 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);9202 }9203 9204 // A method can only override one function from each base class. We9205 // don't track indirectly overridden methods from bases of bases.9206 return true;9207 }9208 9209 return false;9210 };9211 9212 DC->lookupInBases(VisitBase, Paths);9213 return !Overridden.empty();9214}9215 9216namespace {9217 // Struct for holding all of the extra arguments needed by9218 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.9219 struct ActOnFDArgs {9220 Scope *S;9221 Declarator &D;9222 MultiTemplateParamsArg TemplateParamLists;9223 bool AddToScope;9224 };9225} // end anonymous namespace9226 9227namespace {9228 9229// Callback to only accept typo corrections that have a non-zero edit distance.9230// Also only accept corrections that have the same parent decl.9231class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {9232 public:9233 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,9234 CXXRecordDecl *Parent)9235 : Context(Context), OriginalFD(TypoFD),9236 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}9237 9238 bool ValidateCandidate(const TypoCorrection &candidate) override {9239 if (candidate.getEditDistance() == 0)9240 return false;9241 9242 SmallVector<unsigned, 1> MismatchedParams;9243 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),9244 CDeclEnd = candidate.end();9245 CDecl != CDeclEnd; ++CDecl) {9246 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);9247 9248 if (FD && !FD->hasBody() &&9249 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {9250 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {9251 CXXRecordDecl *Parent = MD->getParent();9252 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)9253 return true;9254 } else if (!ExpectedParent) {9255 return true;9256 }9257 }9258 }9259 9260 return false;9261 }9262 9263 std::unique_ptr<CorrectionCandidateCallback> clone() override {9264 return std::make_unique<DifferentNameValidatorCCC>(*this);9265 }9266 9267 private:9268 ASTContext &Context;9269 FunctionDecl *OriginalFD;9270 CXXRecordDecl *ExpectedParent;9271};9272 9273} // end anonymous namespace9274 9275void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {9276 TypoCorrectedFunctionDefinitions.insert(F);9277}9278 9279/// Generate diagnostics for an invalid function redeclaration.9280///9281/// This routine handles generating the diagnostic messages for an invalid9282/// function redeclaration, including finding possible similar declarations9283/// or performing typo correction if there are no previous declarations with9284/// the same name.9285///9286/// Returns a NamedDecl iff typo correction was performed and substituting in9287/// the new declaration name does not cause new errors.9288static NamedDecl *DiagnoseInvalidRedeclaration(9289 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,9290 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {9291 DeclarationName Name = NewFD->getDeclName();9292 DeclContext *NewDC = NewFD->getDeclContext();9293 SmallVector<unsigned, 1> MismatchedParams;9294 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;9295 TypoCorrection Correction;9296 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();9297 unsigned DiagMsg =9298 IsLocalFriend ? diag::err_no_matching_local_friend :9299 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :9300 diag::err_member_decl_does_not_match;9301 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),9302 IsLocalFriend ? Sema::LookupLocalFriendName9303 : Sema::LookupOrdinaryName,9304 RedeclarationKind::ForVisibleRedeclaration);9305 9306 NewFD->setInvalidDecl();9307 if (IsLocalFriend)9308 SemaRef.LookupName(Prev, S);9309 else9310 SemaRef.LookupQualifiedName(Prev, NewDC);9311 assert(!Prev.isAmbiguous() &&9312 "Cannot have an ambiguity in previous-declaration lookup");9313 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);9314 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,9315 MD ? MD->getParent() : nullptr);9316 if (!Prev.empty()) {9317 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();9318 Func != FuncEnd; ++Func) {9319 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);9320 if (FD &&9321 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {9322 // Add 1 to the index so that 0 can mean the mismatch didn't9323 // involve a parameter9324 unsigned ParamNum =9325 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;9326 NearMatches.push_back(std::make_pair(FD, ParamNum));9327 }9328 }9329 // If the qualified name lookup yielded nothing, try typo correction9330 } else if ((Correction = SemaRef.CorrectTypo(9331 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,9332 &ExtraArgs.D.getCXXScopeSpec(), CCC,9333 CorrectTypoKind::ErrorRecovery,9334 IsLocalFriend ? nullptr : NewDC))) {9335 // Set up everything for the call to ActOnFunctionDeclarator9336 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),9337 ExtraArgs.D.getIdentifierLoc());9338 Previous.clear();9339 Previous.setLookupName(Correction.getCorrection());9340 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),9341 CDeclEnd = Correction.end();9342 CDecl != CDeclEnd; ++CDecl) {9343 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);9344 if (FD && !FD->hasBody() &&9345 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {9346 Previous.addDecl(FD);9347 }9348 }9349 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();9350 9351 NamedDecl *Result;9352 // Retry building the function declaration with the new previous9353 // declarations, and with errors suppressed.9354 {9355 // Trap errors.9356 Sema::SFINAETrap Trap(SemaRef);9357 9358 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the9359 // pieces need to verify the typo-corrected C++ declaration and hopefully9360 // eliminate the need for the parameter pack ExtraArgs.9361 Result = SemaRef.ActOnFunctionDeclarator(9362 ExtraArgs.S, ExtraArgs.D,9363 Correction.getCorrectionDecl()->getDeclContext(),9364 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,9365 ExtraArgs.AddToScope);9366 9367 if (Trap.hasErrorOccurred())9368 Result = nullptr;9369 }9370 9371 if (Result) {9372 // Determine which correction we picked.9373 Decl *Canonical = Result->getCanonicalDecl();9374 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();9375 I != E; ++I)9376 if ((*I)->getCanonicalDecl() == Canonical)9377 Correction.setCorrectionDecl(*I);9378 9379 // Let Sema know about the correction.9380 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);9381 SemaRef.diagnoseTypo(9382 Correction,9383 SemaRef.PDiag(IsLocalFriend9384 ? diag::err_no_matching_local_friend_suggest9385 : diag::err_member_decl_does_not_match_suggest)9386 << Name << NewDC << IsDefinition);9387 return Result;9388 }9389 9390 // Pretend the typo correction never occurred9391 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),9392 ExtraArgs.D.getIdentifierLoc());9393 ExtraArgs.D.setRedeclaration(wasRedeclaration);9394 Previous.clear();9395 Previous.setLookupName(Name);9396 }9397 9398 SemaRef.Diag(NewFD->getLocation(), DiagMsg)9399 << Name << NewDC << IsDefinition << NewFD->getLocation();9400 9401 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);9402 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {9403 CXXRecordDecl *RD = NewMD->getParent();9404 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)9405 << RD->getName() << RD->getLocation();9406 }9407 9408 bool NewFDisConst = NewMD && NewMD->isConst();9409 9410 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator9411 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();9412 NearMatch != NearMatchEnd; ++NearMatch) {9413 FunctionDecl *FD = NearMatch->first;9414 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);9415 bool FDisConst = MD && MD->isConst();9416 bool IsMember = MD || !IsLocalFriend;9417 9418 // FIXME: These notes are poorly worded for the local friend case.9419 if (unsigned Idx = NearMatch->second) {9420 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);9421 SourceLocation Loc = FDParam->getTypeSpecStartLoc();9422 if (Loc.isInvalid()) Loc = FD->getLocation();9423 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match9424 : diag::note_local_decl_close_param_match)9425 << Idx << FDParam->getType()9426 << NewFD->getParamDecl(Idx - 1)->getType();9427 } else if (FDisConst != NewFDisConst) {9428 auto DB = SemaRef.Diag(FD->getLocation(),9429 diag::note_member_def_close_const_match)9430 << NewFDisConst << FD->getSourceRange().getEnd();9431 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)9432 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),9433 " const");9434 else if (FTI.hasMethodTypeQualifiers() &&9435 FTI.getConstQualifierLoc().isValid())9436 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());9437 } else {9438 SemaRef.Diag(FD->getLocation(),9439 IsMember ? diag::note_member_def_close_match9440 : diag::note_local_decl_close_match);9441 }9442 }9443 return nullptr;9444}9445 9446static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {9447 switch (D.getDeclSpec().getStorageClassSpec()) {9448 default: llvm_unreachable("Unknown storage class!");9449 case DeclSpec::SCS_auto:9450 case DeclSpec::SCS_register:9451 case DeclSpec::SCS_mutable:9452 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),9453 diag::err_typecheck_sclass_func);9454 D.getMutableDeclSpec().ClearStorageClassSpecs();9455 D.setInvalidType();9456 break;9457 case DeclSpec::SCS_unspecified: break;9458 case DeclSpec::SCS_extern:9459 if (D.getDeclSpec().isExternInLinkageSpec())9460 return SC_None;9461 return SC_Extern;9462 case DeclSpec::SCS_static: {9463 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {9464 // C99 6.7.1p5:9465 // The declaration of an identifier for a function that has9466 // block scope shall have no explicit storage-class specifier9467 // other than extern9468 // See also (C++ [dcl.stc]p4).9469 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),9470 diag::err_static_block_func);9471 break;9472 } else9473 return SC_Static;9474 }9475 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;9476 }9477 9478 // No explicit storage class has already been returned9479 return SC_None;9480}9481 9482static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,9483 DeclContext *DC, QualType &R,9484 TypeSourceInfo *TInfo,9485 StorageClass SC,9486 bool &IsVirtualOkay) {9487 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);9488 DeclarationName Name = NameInfo.getName();9489 9490 FunctionDecl *NewFD = nullptr;9491 bool isInline = D.getDeclSpec().isInlineSpecified();9492 9493 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();9494 if (ConstexprKind == ConstexprSpecKind::Constinit ||9495 (SemaRef.getLangOpts().C23 &&9496 ConstexprKind == ConstexprSpecKind::Constexpr)) {9497 9498 if (SemaRef.getLangOpts().C23)9499 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),9500 diag::err_c23_constexpr_not_variable);9501 else9502 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),9503 diag::err_constexpr_wrong_decl_kind)9504 << static_cast<int>(ConstexprKind);9505 ConstexprKind = ConstexprSpecKind::Unspecified;9506 D.getMutableDeclSpec().ClearConstexprSpec();9507 }9508 9509 if (!SemaRef.getLangOpts().CPlusPlus) {9510 // Determine whether the function was written with a prototype. This is9511 // true when:9512 // - there is a prototype in the declarator, or9513 // - the type R of the function is some kind of typedef or other non-9514 // attributed reference to a type name (which eventually refers to a9515 // function type). Note, we can't always look at the adjusted type to9516 // check this case because attributes may cause a non-function9517 // declarator to still have a function type. e.g.,9518 // typedef void func(int a);9519 // __attribute__((noreturn)) func other_func; // This has a prototype9520 bool HasPrototype =9521 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||9522 (D.getDeclSpec().isTypeRep() &&9523 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)9524 ->isFunctionProtoType()) ||9525 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());9526 assert(9527 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&9528 "Strict prototypes are required");9529 9530 NewFD = FunctionDecl::Create(9531 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,9532 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,9533 ConstexprSpecKind::Unspecified,9534 /*TrailingRequiresClause=*/{});9535 if (D.isInvalidType())9536 NewFD->setInvalidDecl();9537 9538 return NewFD;9539 }9540 9541 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();9542 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());9543 9544 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);9545 9546 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {9547 // This is a C++ constructor declaration.9548 assert(DC->isRecord() &&9549 "Constructors can only be declared in a member context");9550 9551 R = SemaRef.CheckConstructorDeclarator(D, R, SC);9552 return CXXConstructorDecl::Create(9553 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,9554 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),9555 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,9556 InheritedConstructor(), TrailingRequiresClause);9557 9558 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {9559 // This is a C++ destructor declaration.9560 if (DC->isRecord()) {9561 R = SemaRef.CheckDestructorDeclarator(D, R, SC);9562 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);9563 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(9564 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,9565 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,9566 /*isImplicitlyDeclared=*/false, ConstexprKind,9567 TrailingRequiresClause);9568 // User defined destructors start as not selected if the class definition is still9569 // not done.9570 if (Record->isBeingDefined())9571 NewDD->setIneligibleOrNotSelected(true);9572 9573 // If the destructor needs an implicit exception specification, set it9574 // now. FIXME: It'd be nice to be able to create the right type to start9575 // with, but the type needs to reference the destructor declaration.9576 if (SemaRef.getLangOpts().CPlusPlus11)9577 SemaRef.AdjustDestructorExceptionSpec(NewDD);9578 9579 IsVirtualOkay = true;9580 return NewDD;9581 9582 } else {9583 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);9584 D.setInvalidType();9585 9586 // Create a FunctionDecl to satisfy the function definition parsing9587 // code path.9588 return FunctionDecl::Create(9589 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,9590 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,9591 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);9592 }9593 9594 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {9595 if (!DC->isRecord()) {9596 SemaRef.Diag(D.getIdentifierLoc(),9597 diag::err_conv_function_not_member);9598 return nullptr;9599 }9600 9601 SemaRef.CheckConversionDeclarator(D, R, SC);9602 if (D.isInvalidType())9603 return nullptr;9604 9605 IsVirtualOkay = true;9606 return CXXConversionDecl::Create(9607 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,9608 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,9609 ExplicitSpecifier, ConstexprKind, SourceLocation(),9610 TrailingRequiresClause);9611 9612 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {9613 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))9614 return nullptr;9615 return CXXDeductionGuideDecl::Create(9616 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,9617 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,9618 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);9619 } else if (DC->isRecord()) {9620 // If the name of the function is the same as the name of the record,9621 // then this must be an invalid constructor that has a return type.9622 // (The parser checks for a return type and makes the declarator a9623 // constructor if it has no return type).9624 if (Name.getAsIdentifierInfo() &&9625 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){9626 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)9627 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())9628 << SourceRange(D.getIdentifierLoc());9629 return nullptr;9630 }9631 9632 // This is a C++ method declaration.9633 CXXMethodDecl *Ret = CXXMethodDecl::Create(9634 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,9635 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,9636 ConstexprKind, SourceLocation(), TrailingRequiresClause);9637 IsVirtualOkay = !Ret->isStatic();9638 return Ret;9639 } else {9640 bool isFriend =9641 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();9642 if (!isFriend && SemaRef.CurContext->isRecord())9643 return nullptr;9644 9645 // Determine whether the function was written with a9646 // prototype. This true when:9647 // - we're in C++ (where every function has a prototype),9648 return FunctionDecl::Create(9649 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,9650 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,9651 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);9652 }9653}9654 9655enum OpenCLParamType {9656 ValidKernelParam,9657 PtrPtrKernelParam,9658 PtrKernelParam,9659 InvalidAddrSpacePtrKernelParam,9660 InvalidKernelParam,9661 RecordKernelParam9662};9663 9664static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {9665 // Size dependent types are just typedefs to normal integer types9666 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to9667 // integers other than by their names.9668 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};9669 9670 // Remove typedefs one by one until we reach a typedef9671 // for a size dependent type.9672 QualType DesugaredTy = Ty;9673 do {9674 ArrayRef<StringRef> Names(SizeTypeNames);9675 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());9676 if (Names.end() != Match)9677 return true;9678 9679 Ty = DesugaredTy;9680 DesugaredTy = Ty.getSingleStepDesugaredType(C);9681 } while (DesugaredTy != Ty);9682 9683 return false;9684}9685 9686static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {9687 if (PT->isDependentType())9688 return InvalidKernelParam;9689 9690 if (PT->isPointerOrReferenceType()) {9691 QualType PointeeType = PT->getPointeeType();9692 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||9693 PointeeType.getAddressSpace() == LangAS::opencl_private ||9694 PointeeType.getAddressSpace() == LangAS::Default)9695 return InvalidAddrSpacePtrKernelParam;9696 9697 if (PointeeType->isPointerType()) {9698 // This is a pointer to pointer parameter.9699 // Recursively check inner type.9700 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);9701 if (ParamKind == InvalidAddrSpacePtrKernelParam ||9702 ParamKind == InvalidKernelParam)9703 return ParamKind;9704 9705 // OpenCL v3.0 s6.11.a:9706 // A restriction to pass pointers to pointers only applies to OpenCL C9707 // v1.2 or below.9708 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)9709 return ValidKernelParam;9710 9711 return PtrPtrKernelParam;9712 }9713 9714 // C++ for OpenCL v1.0 s2.4:9715 // Moreover the types used in parameters of the kernel functions must be:9716 // Standard layout types for pointer parameters. The same applies to9717 // reference if an implementation supports them in kernel parameters.9718 if (S.getLangOpts().OpenCLCPlusPlus &&9719 !S.getOpenCLOptions().isAvailableOption(9720 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {9721 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();9722 bool IsStandardLayoutType = true;9723 if (CXXRec) {9724 // If template type is not ODR-used its definition is only available9725 // in the template definition not its instantiation.9726 // FIXME: This logic doesn't work for types that depend on template9727 // parameter (PR58590).9728 if (!CXXRec->hasDefinition())9729 CXXRec = CXXRec->getTemplateInstantiationPattern();9730 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())9731 IsStandardLayoutType = false;9732 }9733 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&9734 !IsStandardLayoutType)9735 return InvalidKernelParam;9736 }9737 9738 // OpenCL v1.2 s6.9.p:9739 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.9740 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)9741 return ValidKernelParam;9742 9743 return PtrKernelParam;9744 }9745 9746 // OpenCL v1.2 s6.9.k:9747 // Arguments to kernel functions in a program cannot be declared with the9748 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and9749 // uintptr_t or a struct and/or union that contain fields declared to be one9750 // of these built-in scalar types.9751 if (isOpenCLSizeDependentType(S.getASTContext(), PT))9752 return InvalidKernelParam;9753 9754 if (PT->isImageType())9755 return PtrKernelParam;9756 9757 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())9758 return InvalidKernelParam;9759 9760 // OpenCL extension spec v1.2 s9.5:9761 // This extension adds support for half scalar and vector types as built-in9762 // types that can be used for arithmetic operations, conversions etc.9763 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&9764 PT->isHalfType())9765 return InvalidKernelParam;9766 9767 // Look into an array argument to check if it has a forbidden type.9768 if (PT->isArrayType()) {9769 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();9770 // Call ourself to check an underlying type of an array. Since the9771 // getPointeeOrArrayElementType returns an innermost type which is not an9772 // array, this recursive call only happens once.9773 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));9774 }9775 9776 // C++ for OpenCL v1.0 s2.4:9777 // Moreover the types used in parameters of the kernel functions must be:9778 // Trivial and standard-layout types C++17 [basic.types] (plain old data9779 // types) for parameters passed by value;9780 if (S.getLangOpts().OpenCLCPlusPlus &&9781 !S.getOpenCLOptions().isAvailableOption(9782 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&9783 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))9784 return InvalidKernelParam;9785 9786 if (PT->isRecordType())9787 return RecordKernelParam;9788 9789 return ValidKernelParam;9790}9791 9792static void checkIsValidOpenCLKernelParameter(9793 Sema &S,9794 Declarator &D,9795 ParmVarDecl *Param,9796 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {9797 QualType PT = Param->getType();9798 9799 // Cache the valid types we encounter to avoid rechecking structs that are9800 // used again9801 if (ValidTypes.count(PT.getTypePtr()))9802 return;9803 9804 switch (getOpenCLKernelParameterType(S, PT)) {9805 case PtrPtrKernelParam:9806 // OpenCL v3.0 s6.11.a:9807 // A kernel function argument cannot be declared as a pointer to a pointer9808 // type. [...] This restriction only applies to OpenCL C 1.2 or below.9809 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);9810 D.setInvalidType();9811 return;9812 9813 case InvalidAddrSpacePtrKernelParam:9814 // OpenCL v1.0 s6.5:9815 // __kernel function arguments declared to be a pointer of a type can point9816 // to one of the following address spaces only : __global, __local or9817 // __constant.9818 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);9819 D.setInvalidType();9820 return;9821 9822 // OpenCL v1.2 s6.9.k:9823 // Arguments to kernel functions in a program cannot be declared with the9824 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and9825 // uintptr_t or a struct and/or union that contain fields declared to be9826 // one of these built-in scalar types.9827 9828 case InvalidKernelParam:9829 // OpenCL v1.2 s6.8 n:9830 // A kernel function argument cannot be declared9831 // of event_t type.9832 // Do not diagnose half type since it is diagnosed as invalid argument9833 // type for any function elsewhere.9834 if (!PT->isHalfType()) {9835 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;9836 9837 // Explain what typedefs are involved.9838 const TypedefType *Typedef = nullptr;9839 while ((Typedef = PT->getAs<TypedefType>())) {9840 SourceLocation Loc = Typedef->getDecl()->getLocation();9841 // SourceLocation may be invalid for a built-in type.9842 if (Loc.isValid())9843 S.Diag(Loc, diag::note_entity_declared_at) << PT;9844 PT = Typedef->desugar();9845 }9846 }9847 9848 D.setInvalidType();9849 return;9850 9851 case PtrKernelParam:9852 case ValidKernelParam:9853 ValidTypes.insert(PT.getTypePtr());9854 return;9855 9856 case RecordKernelParam:9857 break;9858 }9859 9860 // Track nested structs we will inspect9861 SmallVector<const Decl *, 4> VisitStack;9862 9863 // Track where we are in the nested structs. Items will migrate from9864 // VisitStack to HistoryStack as we do the DFS for bad field.9865 SmallVector<const FieldDecl *, 4> HistoryStack;9866 HistoryStack.push_back(nullptr);9867 9868 // At this point we already handled everything except of a RecordType.9869 assert(PT->isRecordType() && "Unexpected type.");9870 const auto *PD = PT->castAsRecordDecl();9871 VisitStack.push_back(PD);9872 assert(VisitStack.back() && "First decl null?");9873 9874 do {9875 const Decl *Next = VisitStack.pop_back_val();9876 if (!Next) {9877 assert(!HistoryStack.empty());9878 // Found a marker, we have gone up a level9879 if (const FieldDecl *Hist = HistoryStack.pop_back_val())9880 ValidTypes.insert(Hist->getType().getTypePtr());9881 9882 continue;9883 }9884 9885 // Adds everything except the original parameter declaration (which is not a9886 // field itself) to the history stack.9887 const RecordDecl *RD;9888 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {9889 HistoryStack.push_back(Field);9890 9891 QualType FieldTy = Field->getType();9892 // Other field types (known to be valid or invalid) are handled while we9893 // walk around RecordDecl::fields().9894 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&9895 "Unexpected type.");9896 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();9897 9898 RD = FieldRecTy->castAsRecordDecl();9899 } else {9900 RD = cast<RecordDecl>(Next);9901 }9902 9903 // Add a null marker so we know when we've gone back up a level9904 VisitStack.push_back(nullptr);9905 9906 for (const auto *FD : RD->fields()) {9907 QualType QT = FD->getType();9908 9909 if (ValidTypes.count(QT.getTypePtr()))9910 continue;9911 9912 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);9913 if (ParamType == ValidKernelParam)9914 continue;9915 9916 if (ParamType == RecordKernelParam) {9917 VisitStack.push_back(FD);9918 continue;9919 }9920 9921 // OpenCL v1.2 s6.9.p:9922 // Arguments to kernel functions that are declared to be a struct or union9923 // do not allow OpenCL objects to be passed as elements of the struct or9924 // union. This restriction was lifted in OpenCL v2.0 with the introduction9925 // of SVM.9926 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||9927 ParamType == InvalidAddrSpacePtrKernelParam) {9928 S.Diag(Param->getLocation(),9929 diag::err_record_with_pointers_kernel_param)9930 << PT->isUnionType()9931 << PT;9932 } else {9933 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;9934 }9935 9936 S.Diag(PD->getLocation(), diag::note_within_field_of_type)9937 << PD->getDeclName();9938 9939 // We have an error, now let's go back up through history and show where9940 // the offending field came from9941 for (ArrayRef<const FieldDecl *>::const_iterator9942 I = HistoryStack.begin() + 1,9943 E = HistoryStack.end();9944 I != E; ++I) {9945 const FieldDecl *OuterField = *I;9946 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)9947 << OuterField->getType();9948 }9949 9950 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)9951 << QT->isPointerType()9952 << QT;9953 D.setInvalidType();9954 return;9955 }9956 } while (!VisitStack.empty());9957}9958 9959/// Find the DeclContext in which a tag is implicitly declared if we see an9960/// elaborated type specifier in the specified context, and lookup finds9961/// nothing.9962static DeclContext *getTagInjectionContext(DeclContext *DC) {9963 while (!DC->isFileContext() && !DC->isFunctionOrMethod())9964 DC = DC->getParent();9965 return DC;9966}9967 9968/// Find the Scope in which a tag is implicitly declared if we see an9969/// elaborated type specifier in the specified context, and lookup finds9970/// nothing.9971static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {9972 while (S->isClassScope() ||9973 (LangOpts.CPlusPlus &&9974 S->isFunctionPrototypeScope()) ||9975 ((S->getFlags() & Scope::DeclScope) == 0) ||9976 (S->getEntity() && S->getEntity()->isTransparentContext()))9977 S = S->getParent();9978 return S;9979}9980 9981/// Determine whether a declaration matches a known function in namespace std.9982static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,9983 unsigned BuiltinID) {9984 switch (BuiltinID) {9985 case Builtin::BI__GetExceptionInfo:9986 // No type checking whatsoever.9987 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();9988 9989 case Builtin::BIaddressof:9990 case Builtin::BI__addressof:9991 case Builtin::BIforward:9992 case Builtin::BIforward_like:9993 case Builtin::BImove:9994 case Builtin::BImove_if_noexcept:9995 case Builtin::BIas_const: {9996 // Ensure that we don't treat the algorithm9997 // OutputIt std::move(InputIt, InputIt, OutputIt)9998 // as the builtin std::move.9999 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();10000 return FPT->getNumParams() == 1 && !FPT->isVariadic();10001 }10002 10003 default:10004 return false;10005 }10006}10007 10008NamedDecl*10009Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,10010 TypeSourceInfo *TInfo, LookupResult &Previous,10011 MultiTemplateParamsArg TemplateParamListsRef,10012 bool &AddToScope) {10013 QualType R = TInfo->getType();10014 10015 assert(R->isFunctionType());10016 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())10017 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);10018 10019 SmallVector<TemplateParameterList *, 4> TemplateParamLists;10020 llvm::append_range(TemplateParamLists, TemplateParamListsRef);10021 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {10022 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&10023 Invented->getDepth() == TemplateParamLists.back()->getDepth())10024 TemplateParamLists.back() = Invented;10025 else10026 TemplateParamLists.push_back(Invented);10027 }10028 10029 // TODO: consider using NameInfo for diagnostic.10030 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);10031 DeclarationName Name = NameInfo.getName();10032 StorageClass SC = getFunctionStorageClass(*this, D);10033 10034 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())10035 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),10036 diag::err_invalid_thread)10037 << DeclSpec::getSpecifierName(TSCS);10038 10039 if (D.isFirstDeclarationOfMember())10040 adjustMemberFunctionCC(10041 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),10042 D.isCtorOrDtor(), D.getIdentifierLoc());10043 10044 bool isFriend = false;10045 FunctionTemplateDecl *FunctionTemplate = nullptr;10046 bool isMemberSpecialization = false;10047 bool isFunctionTemplateSpecialization = false;10048 10049 bool HasExplicitTemplateArgs = false;10050 TemplateArgumentListInfo TemplateArgs;10051 10052 bool isVirtualOkay = false;10053 10054 DeclContext *OriginalDC = DC;10055 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);10056 10057 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,10058 isVirtualOkay);10059 if (!NewFD) return nullptr;10060 10061 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())10062 NewFD->setTopLevelDeclInObjCContainer();10063 10064 // Set the lexical context. If this is a function-scope declaration, or has a10065 // C++ scope specifier, or is the object of a friend declaration, the lexical10066 // context will be different from the semantic context.10067 NewFD->setLexicalDeclContext(CurContext);10068 10069 if (IsLocalExternDecl)10070 NewFD->setLocalExternDecl();10071 10072 if (getLangOpts().CPlusPlus) {10073 // The rules for implicit inlines changed in C++20 for methods and friends10074 // with an in-class definition (when such a definition is not attached to10075 // the global module). This does not affect declarations that are already10076 // inline (whether explicitly or implicitly by being declared constexpr,10077 // consteval, etc).10078 // FIXME: We need a better way to separate C++ standard and clang modules.10079 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||10080 !NewFD->getOwningModule() ||10081 NewFD->isFromGlobalModule() ||10082 NewFD->getOwningModule()->isHeaderLikeModule();10083 bool isInline = D.getDeclSpec().isInlineSpecified();10084 bool isVirtual = D.getDeclSpec().isVirtualSpecified();10085 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();10086 isFriend = D.getDeclSpec().isFriendSpecified();10087 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {10088 // Pre-C++20 [class.friend]p510089 // A function can be defined in a friend declaration of a10090 // class . . . . Such a function is implicitly inline.10091 // Post C++20 [class.friend]p710092 // Such a function is implicitly an inline function if it is attached10093 // to the global module.10094 NewFD->setImplicitlyInline();10095 }10096 10097 // If this is a method defined in an __interface, and is not a constructor10098 // or an overloaded operator, then set the pure flag (isVirtual will already10099 // return true).10100 if (const CXXRecordDecl *Parent =10101 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {10102 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())10103 NewFD->setIsPureVirtual(true);10104 10105 // C++ [class.union]p210106 // A union can have member functions, but not virtual functions.10107 if (isVirtual && Parent->isUnion()) {10108 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);10109 NewFD->setInvalidDecl();10110 }10111 if ((Parent->isClass() || Parent->isStruct()) &&10112 Parent->hasAttr<SYCLSpecialClassAttr>() &&10113 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&10114 NewFD->getName() == "__init" && D.isFunctionDefinition()) {10115 if (auto *Def = Parent->getDefinition())10116 Def->setInitMethod(true);10117 }10118 }10119 10120 SetNestedNameSpecifier(*this, NewFD, D);10121 isMemberSpecialization = false;10122 isFunctionTemplateSpecialization = false;10123 if (D.isInvalidType())10124 NewFD->setInvalidDecl();10125 10126 // Match up the template parameter lists with the scope specifier, then10127 // determine whether we have a template or a template specialization.10128 bool Invalid = false;10129 TemplateIdAnnotation *TemplateId =10130 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId10131 ? D.getName().TemplateId10132 : nullptr;10133 TemplateParameterList *TemplateParams =10134 MatchTemplateParametersToScopeSpecifier(10135 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),10136 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,10137 isMemberSpecialization, Invalid);10138 if (TemplateParams) {10139 // Check that we can declare a template here.10140 if (CheckTemplateDeclScope(S, TemplateParams))10141 NewFD->setInvalidDecl();10142 10143 if (TemplateParams->size() > 0) {10144 // This is a function template10145 10146 // A destructor cannot be a template.10147 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {10148 Diag(NewFD->getLocation(), diag::err_destructor_template);10149 NewFD->setInvalidDecl();10150 // Function template with explicit template arguments.10151 } else if (TemplateId) {10152 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)10153 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);10154 NewFD->setInvalidDecl();10155 }10156 10157 // If we're adding a template to a dependent context, we may need to10158 // rebuilding some of the types used within the template parameter list,10159 // now that we know what the current instantiation is.10160 if (DC->isDependentContext()) {10161 ContextRAII SavedContext(*this, DC);10162 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))10163 Invalid = true;10164 }10165 10166 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,10167 NewFD->getLocation(),10168 Name, TemplateParams,10169 NewFD);10170 FunctionTemplate->setLexicalDeclContext(CurContext);10171 NewFD->setDescribedFunctionTemplate(FunctionTemplate);10172 10173 // For source fidelity, store the other template param lists.10174 if (TemplateParamLists.size() > 1) {10175 NewFD->setTemplateParameterListsInfo(Context,10176 ArrayRef<TemplateParameterList *>(TemplateParamLists)10177 .drop_back(1));10178 }10179 } else {10180 // This is a function template specialization.10181 isFunctionTemplateSpecialization = true;10182 // For source fidelity, store all the template param lists.10183 if (TemplateParamLists.size() > 0)10184 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);10185 10186 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".10187 if (isFriend) {10188 // We want to remove the "template<>", found here.10189 SourceRange RemoveRange = TemplateParams->getSourceRange();10190 10191 // If we remove the template<> and the name is not a10192 // template-id, we're actually silently creating a problem:10193 // the friend declaration will refer to an untemplated decl,10194 // and clearly the user wants a template specialization. So10195 // we need to insert '<>' after the name.10196 SourceLocation InsertLoc;10197 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {10198 InsertLoc = D.getName().getSourceRange().getEnd();10199 InsertLoc = getLocForEndOfToken(InsertLoc);10200 }10201 10202 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)10203 << Name << RemoveRange10204 << FixItHint::CreateRemoval(RemoveRange)10205 << FixItHint::CreateInsertion(InsertLoc, "<>");10206 Invalid = true;10207 10208 // Recover by faking up an empty template argument list.10209 HasExplicitTemplateArgs = true;10210 TemplateArgs.setLAngleLoc(InsertLoc);10211 TemplateArgs.setRAngleLoc(InsertLoc);10212 }10213 }10214 } else {10215 // Check that we can declare a template here.10216 if (!TemplateParamLists.empty() && isMemberSpecialization &&10217 CheckTemplateDeclScope(S, TemplateParamLists.back()))10218 NewFD->setInvalidDecl();10219 10220 // All template param lists were matched against the scope specifier:10221 // this is NOT (an explicit specialization of) a template.10222 if (TemplateParamLists.size() > 0)10223 // For source fidelity, store all the template param lists.10224 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);10225 10226 // "friend void foo<>(int);" is an implicit specialization decl.10227 if (isFriend && TemplateId)10228 isFunctionTemplateSpecialization = true;10229 }10230 10231 // If this is a function template specialization and the unqualified-id of10232 // the declarator-id is a template-id, convert the template argument list10233 // into our AST format and check for unexpanded packs.10234 if (isFunctionTemplateSpecialization && TemplateId) {10235 HasExplicitTemplateArgs = true;10236 10237 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);10238 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);10239 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),10240 TemplateId->NumArgs);10241 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);10242 10243 // FIXME: Should we check for unexpanded packs if this was an (invalid)10244 // declaration of a function template partial specialization? Should we10245 // consider the unexpanded pack context to be a partial specialization?10246 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {10247 if (DiagnoseUnexpandedParameterPack(10248 ArgLoc, isFriend ? UPPC_FriendDeclaration10249 : UPPC_ExplicitSpecialization))10250 NewFD->setInvalidDecl();10251 }10252 }10253 10254 if (Invalid) {10255 NewFD->setInvalidDecl();10256 if (FunctionTemplate)10257 FunctionTemplate->setInvalidDecl();10258 }10259 10260 // C++ [dcl.fct.spec]p5:10261 // The virtual specifier shall only be used in declarations of10262 // nonstatic class member functions that appear within a10263 // member-specification of a class declaration; see 10.3.10264 //10265 if (isVirtual && !NewFD->isInvalidDecl()) {10266 if (!isVirtualOkay) {10267 Diag(D.getDeclSpec().getVirtualSpecLoc(),10268 diag::err_virtual_non_function);10269 } else if (!CurContext->isRecord()) {10270 // 'virtual' was specified outside of the class.10271 Diag(D.getDeclSpec().getVirtualSpecLoc(),10272 diag::err_virtual_out_of_class)10273 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());10274 } else if (NewFD->getDescribedFunctionTemplate()) {10275 // C++ [temp.mem]p3:10276 // A member function template shall not be virtual.10277 Diag(D.getDeclSpec().getVirtualSpecLoc(),10278 diag::err_virtual_member_function_template)10279 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());10280 } else {10281 // Okay: Add virtual to the method.10282 NewFD->setVirtualAsWritten(true);10283 }10284 10285 if (getLangOpts().CPlusPlus14 &&10286 NewFD->getReturnType()->isUndeducedType())10287 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);10288 }10289 10290 // C++ [dcl.fct.spec]p3:10291 // The inline specifier shall not appear on a block scope function10292 // declaration.10293 if (isInline && !NewFD->isInvalidDecl()) {10294 if (CurContext->isFunctionOrMethod()) {10295 // 'inline' is not allowed on block scope function declaration.10296 Diag(D.getDeclSpec().getInlineSpecLoc(),10297 diag::err_inline_declaration_block_scope) << Name10298 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());10299 }10300 }10301 10302 // C++ [dcl.fct.spec]p6:10303 // The explicit specifier shall be used only in the declaration of a10304 // constructor or conversion function within its class definition;10305 // see 12.3.1 and 12.3.2.10306 if (hasExplicit && !NewFD->isInvalidDecl() &&10307 !isa<CXXDeductionGuideDecl>(NewFD)) {10308 if (!CurContext->isRecord()) {10309 // 'explicit' was specified outside of the class.10310 Diag(D.getDeclSpec().getExplicitSpecLoc(),10311 diag::err_explicit_out_of_class)10312 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());10313 } else if (!isa<CXXConstructorDecl>(NewFD) &&10314 !isa<CXXConversionDecl>(NewFD)) {10315 // 'explicit' was specified on a function that wasn't a constructor10316 // or conversion function.10317 Diag(D.getDeclSpec().getExplicitSpecLoc(),10318 diag::err_explicit_non_ctor_or_conv_function)10319 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());10320 }10321 }10322 10323 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();10324 if (ConstexprKind != ConstexprSpecKind::Unspecified) {10325 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors10326 // are implicitly inline.10327 NewFD->setImplicitlyInline();10328 10329 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to10330 // be either constructors or to return a literal type. Therefore,10331 // destructors cannot be declared constexpr.10332 if (isa<CXXDestructorDecl>(NewFD) &&10333 (!getLangOpts().CPlusPlus20 ||10334 ConstexprKind == ConstexprSpecKind::Consteval)) {10335 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)10336 << static_cast<int>(ConstexprKind);10337 NewFD->setConstexprKind(getLangOpts().CPlusPlus2010338 ? ConstexprSpecKind::Unspecified10339 : ConstexprSpecKind::Constexpr);10340 }10341 // C++20 [dcl.constexpr]p2: An allocation function, or a10342 // deallocation function shall not be declared with the consteval10343 // specifier.10344 if (ConstexprKind == ConstexprSpecKind::Consteval &&10345 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {10346 Diag(D.getDeclSpec().getConstexprSpecLoc(),10347 diag::err_invalid_consteval_decl_kind)10348 << NewFD;10349 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);10350 }10351 }10352 10353 // If __module_private__ was specified, mark the function accordingly.10354 if (D.getDeclSpec().isModulePrivateSpecified()) {10355 if (isFunctionTemplateSpecialization) {10356 SourceLocation ModulePrivateLoc10357 = D.getDeclSpec().getModulePrivateSpecLoc();10358 Diag(ModulePrivateLoc, diag::err_module_private_specialization)10359 << 010360 << FixItHint::CreateRemoval(ModulePrivateLoc);10361 } else {10362 NewFD->setModulePrivate();10363 if (FunctionTemplate)10364 FunctionTemplate->setModulePrivate();10365 }10366 }10367 10368 if (isFriend) {10369 if (FunctionTemplate) {10370 FunctionTemplate->setObjectOfFriendDecl();10371 FunctionTemplate->setAccess(AS_public);10372 }10373 NewFD->setObjectOfFriendDecl();10374 NewFD->setAccess(AS_public);10375 }10376 10377 // If a function is defined as defaulted or deleted, mark it as such now.10378 // We'll do the relevant checks on defaulted / deleted functions later.10379 switch (D.getFunctionDefinitionKind()) {10380 case FunctionDefinitionKind::Declaration:10381 case FunctionDefinitionKind::Definition:10382 break;10383 10384 case FunctionDefinitionKind::Defaulted:10385 NewFD->setDefaulted();10386 break;10387 10388 case FunctionDefinitionKind::Deleted:10389 NewFD->setDeletedAsWritten();10390 break;10391 }10392 10393 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&10394 D.isFunctionDefinition()) {10395 // Pre C++20 [class.mfct]p2:10396 // A member function may be defined (8.4) in its class definition, in10397 // which case it is an inline member function (7.1.2)10398 // Post C++20 [class.mfct]p1:10399 // If a member function is attached to the global module and is defined10400 // in its class definition, it is inline.10401 NewFD->setImplicitlyInline();10402 }10403 10404 if (!isFriend && SC != SC_None) {10405 // C++ [temp.expl.spec]p2:10406 // The declaration in an explicit-specialization shall not be an10407 // export-declaration. An explicit specialization shall not use a10408 // storage-class-specifier other than thread_local.10409 //10410 // We diagnose friend declarations with storage-class-specifiers10411 // elsewhere.10412 if (isFunctionTemplateSpecialization || isMemberSpecialization) {10413 Diag(D.getDeclSpec().getStorageClassSpecLoc(),10414 diag::ext_explicit_specialization_storage_class)10415 << FixItHint::CreateRemoval(10416 D.getDeclSpec().getStorageClassSpecLoc());10417 }10418 10419 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {10420 assert(isa<CXXMethodDecl>(NewFD) &&10421 "Out-of-line member function should be a CXXMethodDecl");10422 // C++ [class.static]p1:10423 // A data or function member of a class may be declared static10424 // in a class definition, in which case it is a static member of10425 // the class.10426 10427 // Complain about the 'static' specifier if it's on an out-of-line10428 // member function definition.10429 10430 // MSVC permits the use of a 'static' storage specifier on an10431 // out-of-line member function template declaration and class member10432 // template declaration (MSVC versions before 2015), warn about this.10433 Diag(D.getDeclSpec().getStorageClassSpecLoc(),10434 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&10435 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||10436 (getLangOpts().MSVCCompat &&10437 NewFD->getDescribedFunctionTemplate()))10438 ? diag::ext_static_out_of_line10439 : diag::err_static_out_of_line)10440 << FixItHint::CreateRemoval(10441 D.getDeclSpec().getStorageClassSpecLoc());10442 }10443 }10444 10445 // C++11 [except.spec]p15:10446 // A deallocation function with no exception-specification is treated10447 // as if it were specified with noexcept(true).10448 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();10449 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&10450 !FPT->hasExceptionSpec())10451 NewFD->setType(Context.getFunctionType(10452 FPT->getReturnType(), FPT->getParamTypes(),10453 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));10454 10455 // C++20 [dcl.inline]/710456 // If an inline function or variable that is attached to a named module10457 // is declared in a definition domain, it shall be defined in that10458 // domain.10459 // So, if the current declaration does not have a definition, we must10460 // check at the end of the TU (or when the PMF starts) to see that we10461 // have a definition at that point.10462 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&10463 NewFD->isInNamedModule()) {10464 PendingInlineFuncDecls.insert(NewFD);10465 }10466 }10467 10468 // Filter out previous declarations that don't match the scope.10469 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),10470 D.getCXXScopeSpec().isNotEmpty() ||10471 isMemberSpecialization ||10472 isFunctionTemplateSpecialization);10473 10474 // Handle GNU asm-label extension (encoded as an attribute).10475 if (Expr *E = D.getAsmLabel()) {10476 // The parser guarantees this is a string.10477 StringLiteral *SE = cast<StringLiteral>(E);10478 NewFD->addAttr(10479 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));10480 } else if (!ExtnameUndeclaredIdentifiers.empty()) {10481 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =10482 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());10483 if (I != ExtnameUndeclaredIdentifiers.end()) {10484 if (isDeclExternC(NewFD)) {10485 NewFD->addAttr(I->second);10486 ExtnameUndeclaredIdentifiers.erase(I);10487 } else10488 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)10489 << /*Variable*/0 << NewFD;10490 }10491 }10492 10493 // Copy the parameter declarations from the declarator D to the function10494 // declaration NewFD, if they are available. First scavenge them into Params.10495 SmallVector<ParmVarDecl*, 16> Params;10496 unsigned FTIIdx;10497 if (D.isFunctionDeclarator(FTIIdx)) {10498 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;10499 10500 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs10501 // function that takes no arguments, not a function that takes a10502 // single void argument.10503 // We let through "const void" here because Sema::GetTypeForDeclarator10504 // already checks for that case.10505 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {10506 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {10507 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);10508 assert(Param->getDeclContext() != NewFD && "Was set before ?");10509 Param->setDeclContext(NewFD);10510 Params.push_back(Param);10511 10512 if (Param->isInvalidDecl())10513 NewFD->setInvalidDecl();10514 }10515 }10516 10517 if (!getLangOpts().CPlusPlus) {10518 // In C, find all the tag declarations from the prototype and move them10519 // into the function DeclContext. Remove them from the surrounding tag10520 // injection context of the function, which is typically but not always10521 // the TU.10522 DeclContext *PrototypeTagContext =10523 getTagInjectionContext(NewFD->getLexicalDeclContext());10524 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {10525 auto *TD = dyn_cast<TagDecl>(NonParmDecl);10526 10527 // We don't want to reparent enumerators. Look at their parent enum10528 // instead.10529 if (!TD) {10530 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))10531 TD = cast<EnumDecl>(ECD->getDeclContext());10532 }10533 if (!TD)10534 continue;10535 DeclContext *TagDC = TD->getLexicalDeclContext();10536 if (!TagDC->containsDecl(TD))10537 continue;10538 TagDC->removeDecl(TD);10539 TD->setDeclContext(NewFD);10540 NewFD->addDecl(TD);10541 10542 // Preserve the lexical DeclContext if it is not the surrounding tag10543 // injection context of the FD. In this example, the semantic context of10544 // E will be f and the lexical context will be S, while both the10545 // semantic and lexical contexts of S will be f:10546 // void f(struct S { enum E { a } f; } s);10547 if (TagDC != PrototypeTagContext)10548 TD->setLexicalDeclContext(TagDC);10549 }10550 }10551 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {10552 // When we're declaring a function with a typedef, typeof, etc as in the10553 // following example, we'll need to synthesize (unnamed)10554 // parameters for use in the declaration.10555 //10556 // @code10557 // typedef void fn(int);10558 // fn f;10559 // @endcode10560 10561 // Synthesize a parameter for each argument type.10562 for (const auto &AI : FT->param_types()) {10563 ParmVarDecl *Param =10564 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);10565 Param->setScopeInfo(0, Params.size());10566 Params.push_back(Param);10567 }10568 } else {10569 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&10570 "Should not need args for typedef of non-prototype fn");10571 }10572 10573 // Finally, we know we have the right number of parameters, install them.10574 NewFD->setParams(Params);10575 10576 // If this declarator is a declaration and not a definition, its parameters10577 // will not be pushed onto a scope chain. That means we will not issue any10578 // reserved identifier warnings for the declaration, but we will for the10579 // definition. Handle those here.10580 if (!D.isFunctionDefinition()) {10581 for (const ParmVarDecl *PVD : Params)10582 warnOnReservedIdentifier(PVD);10583 }10584 10585 if (D.getDeclSpec().isNoreturnSpecified())10586 NewFD->addAttr(10587 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));10588 10589 // Functions returning a variably modified type violate C99 6.7.5.2p210590 // because all functions have linkage.10591 if (!NewFD->isInvalidDecl() &&10592 NewFD->getReturnType()->isVariablyModifiedType()) {10593 Diag(NewFD->getLocation(), diag::err_vm_func_decl);10594 NewFD->setInvalidDecl();10595 }10596 10597 // Apply an implicit SectionAttr if '#pragma clang section text' is active10598 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&10599 !NewFD->hasAttr<SectionAttr>())10600 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(10601 Context, PragmaClangTextSection.SectionName,10602 PragmaClangTextSection.PragmaLocation));10603 10604 // Apply an implicit SectionAttr if #pragma code_seg is active.10605 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&10606 !NewFD->hasAttr<SectionAttr>()) {10607 NewFD->addAttr(SectionAttr::CreateImplicit(10608 Context, CodeSegStack.CurrentValue->getString(),10609 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));10610 if (UnifySection(CodeSegStack.CurrentValue->getString(),10611 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |10612 ASTContext::PSF_Read,10613 NewFD))10614 NewFD->dropAttr<SectionAttr>();10615 }10616 10617 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is10618 // active.10619 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&10620 !NewFD->hasAttr<StrictGuardStackCheckAttr>())10621 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(10622 Context, PragmaClangTextSection.PragmaLocation));10623 10624 // Apply an implicit CodeSegAttr from class declspec or10625 // apply an implicit SectionAttr from #pragma code_seg if active.10626 if (!NewFD->hasAttr<CodeSegAttr>()) {10627 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,10628 D.isFunctionDefinition())) {10629 NewFD->addAttr(SAttr);10630 }10631 }10632 10633 // Handle attributes.10634 ProcessDeclAttributes(S, NewFD, D);10635 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();10636 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&10637 !NewTVA->isDefaultVersion() &&10638 !Context.getTargetInfo().hasFeature("fmv")) {10639 // Don't add to scope fmv functions declarations if fmv disabled10640 AddToScope = false;10641 return NewFD;10642 }10643 10644 if (getLangOpts().OpenCL || getLangOpts().HLSL) {10645 // Neither OpenCL nor HLSL allow an address space qualifyer on a return10646 // type.10647 //10648 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return10649 // type declaration will generate a compilation error.10650 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();10651 if (AddressSpace != LangAS::Default) {10652 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);10653 NewFD->setInvalidDecl();10654 }10655 }10656 10657 if (!getLangOpts().CPlusPlus) {10658 // Perform semantic checking on the function declaration.10659 if (!NewFD->isInvalidDecl() && NewFD->isMain())10660 CheckMain(NewFD, D.getDeclSpec());10661 10662 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())10663 CheckMSVCRTEntryPoint(NewFD);10664 10665 if (!NewFD->isInvalidDecl())10666 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,10667 isMemberSpecialization,10668 D.isFunctionDefinition()));10669 else if (!Previous.empty())10670 // Recover gracefully from an invalid redeclaration.10671 D.setRedeclaration(true);10672 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||10673 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&10674 "previous declaration set still overloaded");10675 10676 // Diagnose no-prototype function declarations with calling conventions that10677 // don't support variadic calls. Only do this in C and do it after merging10678 // possibly prototyped redeclarations.10679 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();10680 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {10681 CallingConv CC = FT->getExtInfo().getCC();10682 if (!supportsVariadicCall(CC)) {10683 // Windows system headers sometimes accidentally use stdcall without10684 // (void) parameters, so we relax this to a warning.10685 int DiagID =10686 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;10687 Diag(NewFD->getLocation(), DiagID)10688 << FunctionType::getNameForCallConv(CC);10689 }10690 }10691 10692 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||10693 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())10694 checkNonTrivialCUnion(10695 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),10696 NonTrivialCUnionContext::FunctionReturn, NTCUK_Destruct | NTCUK_Copy);10697 } else {10698 // C++11 [replacement.functions]p3:10699 // The program's definitions shall not be specified as inline.10700 //10701 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.10702 //10703 // Suppress the diagnostic if the function is __attribute__((used)), since10704 // that forces an external definition to be emitted.10705 if (D.getDeclSpec().isInlineSpecified() &&10706 NewFD->isReplaceableGlobalAllocationFunction() &&10707 !NewFD->hasAttr<UsedAttr>())10708 Diag(D.getDeclSpec().getInlineSpecLoc(),10709 diag::ext_operator_new_delete_declared_inline)10710 << NewFD->getDeclName();10711 10712 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {10713 // C++20 [dcl.decl.general]p4:10714 // The optional requires-clause in an init-declarator or10715 // member-declarator shall be present only if the declarator declares a10716 // templated function.10717 //10718 // C++20 [temp.pre]p8:10719 // An entity is templated if it is10720 // - a template,10721 // - an entity defined or created in a templated entity,10722 // - a member of a templated entity,10723 // - an enumerator for an enumeration that is a templated entity, or10724 // - the closure type of a lambda-expression appearing in the10725 // declaration of a templated entity.10726 //10727 // [Note 6: A local class, a local or block variable, or a friend10728 // function defined in a templated entity is a templated entity.10729 // — end note]10730 //10731 // A templated function is a function template or a function that is10732 // templated. A templated class is a class template or a class that is10733 // templated. A templated variable is a variable template or a variable10734 // that is templated.10735 if (!FunctionTemplate) {10736 if (isFunctionTemplateSpecialization || isMemberSpecialization) {10737 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):10738 // An explicit specialization shall not have a trailing10739 // requires-clause unless it declares a function template.10740 //10741 // Since a friend function template specialization cannot be10742 // definition, and since a non-template friend declaration with a10743 // trailing requires-clause must be a definition, we diagnose10744 // friend function template specializations with trailing10745 // requires-clauses on the same path as explicit specializations10746 // even though they aren't necessarily prohibited by the same10747 // language rule.10748 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)10749 << isFriend;10750 } else if (isFriend && NewFD->isTemplated() &&10751 !D.isFunctionDefinition()) {10752 // C++ [temp.friend]p9:10753 // A non-template friend declaration with a requires-clause shall be10754 // a definition.10755 Diag(NewFD->getBeginLoc(),10756 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);10757 NewFD->setInvalidDecl();10758 } else if (!NewFD->isTemplated() ||10759 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {10760 Diag(TRC->getBeginLoc(),10761 diag::err_constrained_non_templated_function);10762 }10763 }10764 }10765 10766 // We do not add HD attributes to specializations here because10767 // they may have different constexpr-ness compared to their10768 // templates and, after maybeAddHostDeviceAttrs() is applied,10769 // may end up with different effective targets. Instead, a10770 // specialization inherits its target attributes from its template10771 // in the CheckFunctionTemplateSpecialization() call below.10772 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)10773 CUDA().maybeAddHostDeviceAttrs(NewFD, Previous);10774 10775 // Handle explicit specializations of function templates10776 // and friend function declarations with an explicit10777 // template argument list.10778 if (isFunctionTemplateSpecialization) {10779 bool isDependentSpecialization = false;10780 if (isFriend) {10781 // For friend function specializations, this is a dependent10782 // specialization if its semantic context is dependent, its10783 // type is dependent, or if its template-id is dependent.10784 isDependentSpecialization =10785 DC->isDependentContext() || NewFD->getType()->isDependentType() ||10786 (HasExplicitTemplateArgs &&10787 TemplateSpecializationType::10788 anyInstantiationDependentTemplateArguments(10789 TemplateArgs.arguments()));10790 assert((!isDependentSpecialization ||10791 (HasExplicitTemplateArgs == isDependentSpecialization)) &&10792 "dependent friend function specialization without template "10793 "args");10794 } else {10795 // For class-scope explicit specializations of function templates,10796 // if the lexical context is dependent, then the specialization10797 // is dependent.10798 isDependentSpecialization =10799 CurContext->isRecord() && CurContext->isDependentContext();10800 }10801 10802 TemplateArgumentListInfo *ExplicitTemplateArgs =10803 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;10804 if (isDependentSpecialization) {10805 // If it's a dependent specialization, it may not be possible10806 // to determine the primary template (for explicit specializations)10807 // or befriended declaration (for friends) until the enclosing10808 // template is instantiated. In such cases, we store the declarations10809 // found by name lookup and defer resolution until instantiation.10810 if (CheckDependentFunctionTemplateSpecialization(10811 NewFD, ExplicitTemplateArgs, Previous))10812 NewFD->setInvalidDecl();10813 } else if (!NewFD->isInvalidDecl()) {10814 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,10815 Previous))10816 NewFD->setInvalidDecl();10817 }10818 } else if (isMemberSpecialization && !FunctionTemplate) {10819 if (CheckMemberSpecialization(NewFD, Previous))10820 NewFD->setInvalidDecl();10821 }10822 10823 // Perform semantic checking on the function declaration.10824 if (!NewFD->isInvalidDecl() && NewFD->isMain())10825 CheckMain(NewFD, D.getDeclSpec());10826 10827 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())10828 CheckMSVCRTEntryPoint(NewFD);10829 10830 if (!NewFD->isInvalidDecl())10831 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,10832 isMemberSpecialization,10833 D.isFunctionDefinition()));10834 else if (!Previous.empty())10835 // Recover gracefully from an invalid redeclaration.10836 D.setRedeclaration(true);10837 10838 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||10839 !D.isRedeclaration() ||10840 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&10841 "previous declaration set still overloaded");10842 10843 NamedDecl *PrincipalDecl = (FunctionTemplate10844 ? cast<NamedDecl>(FunctionTemplate)10845 : NewFD);10846 10847 if (isFriend && NewFD->getPreviousDecl()) {10848 AccessSpecifier Access = AS_public;10849 if (!NewFD->isInvalidDecl())10850 Access = NewFD->getPreviousDecl()->getAccess();10851 10852 NewFD->setAccess(Access);10853 if (FunctionTemplate) FunctionTemplate->setAccess(Access);10854 }10855 10856 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&10857 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))10858 PrincipalDecl->setNonMemberOperator();10859 10860 // If we have a function template, check the template parameter10861 // list. This will check and merge default template arguments.10862 if (FunctionTemplate) {10863 FunctionTemplateDecl *PrevTemplate =10864 FunctionTemplate->getPreviousDecl();10865 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),10866 PrevTemplate ? PrevTemplate->getTemplateParameters()10867 : nullptr,10868 D.getDeclSpec().isFriendSpecified()10869 ? (D.isFunctionDefinition()10870 ? TPC_FriendFunctionTemplateDefinition10871 : TPC_FriendFunctionTemplate)10872 : (D.getCXXScopeSpec().isSet() &&10873 DC && DC->isRecord() &&10874 DC->isDependentContext())10875 ? TPC_ClassTemplateMember10876 : TPC_FunctionTemplate);10877 }10878 10879 if (NewFD->isInvalidDecl()) {10880 // Ignore all the rest of this.10881 } else if (!D.isRedeclaration()) {10882 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,10883 AddToScope };10884 // Fake up an access specifier if it's supposed to be a class member.10885 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))10886 NewFD->setAccess(AS_public);10887 10888 // Qualified decls generally require a previous declaration.10889 if (D.getCXXScopeSpec().isSet()) {10890 // ...with the major exception of templated-scope or10891 // dependent-scope friend declarations.10892 10893 // TODO: we currently also suppress this check in dependent10894 // contexts because (1) the parameter depth will be off when10895 // matching friend templates and (2) we might actually be10896 // selecting a friend based on a dependent factor. But there10897 // are situations where these conditions don't apply and we10898 // can actually do this check immediately.10899 //10900 // Unless the scope is dependent, it's always an error if qualified10901 // redeclaration lookup found nothing at all. Diagnose that now;10902 // nothing will diagnose that error later.10903 if (isFriend &&10904 (D.getCXXScopeSpec().getScopeRep().isDependent() ||10905 (!Previous.empty() && CurContext->isDependentContext()))) {10906 // ignore these10907 } else if (NewFD->isCPUDispatchMultiVersion() ||10908 NewFD->isCPUSpecificMultiVersion()) {10909 // ignore this, we allow the redeclaration behavior here to create new10910 // versions of the function.10911 } else {10912 // The user tried to provide an out-of-line definition for a10913 // function that is a member of a class or namespace, but there10914 // was no such member function declared (C++ [class.mfct]p2,10915 // C++ [namespace.memdef]p2). For example:10916 //10917 // class X {10918 // void f() const;10919 // };10920 //10921 // void X::f() { } // ill-formed10922 //10923 // Complain about this problem, and attempt to suggest close10924 // matches (e.g., those that differ only in cv-qualifiers and10925 // whether the parameter types are references).10926 10927 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(10928 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {10929 AddToScope = ExtraArgs.AddToScope;10930 return Result;10931 }10932 }10933 10934 // Unqualified local friend declarations are required to resolve10935 // to something.10936 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {10937 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(10938 *this, Previous, NewFD, ExtraArgs, true, S)) {10939 AddToScope = ExtraArgs.AddToScope;10940 return Result;10941 }10942 }10943 } else if (!D.isFunctionDefinition() &&10944 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&10945 !isFriend && !isFunctionTemplateSpecialization &&10946 !isMemberSpecialization) {10947 // An out-of-line member function declaration must also be a10948 // definition (C++ [class.mfct]p2).10949 // Note that this is not the case for explicit specializations of10950 // function templates or member functions of class templates, per10951 // C++ [temp.expl.spec]p2. We also allow these declarations as an10952 // extension for compatibility with old SWIG code which likes to10953 // generate them.10954 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)10955 << D.getCXXScopeSpec().getRange();10956 }10957 }10958 10959 if (getLangOpts().HLSL && D.isFunctionDefinition()) {10960 // Any top level function could potentially be specified as an entry.10961 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())10962 HLSL().ActOnTopLevelFunction(NewFD);10963 10964 if (NewFD->hasAttr<HLSLShaderAttr>())10965 HLSL().CheckEntryPoint(NewFD);10966 }10967 10968 // If this is the first declaration of a library builtin function, add10969 // attributes as appropriate.10970 if (!D.isRedeclaration()) {10971 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {10972 if (unsigned BuiltinID = II->getBuiltinID()) {10973 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);10974 if (!InStdNamespace &&10975 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {10976 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {10977 // Validate the type matches unless this builtin is specified as10978 // matching regardless of its declared type.10979 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {10980 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));10981 } else {10982 ASTContext::GetBuiltinTypeError Error;10983 LookupNecessaryTypesForBuiltin(S, BuiltinID);10984 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);10985 10986 if (!Error && !BuiltinType.isNull() &&10987 Context.hasSameFunctionTypeIgnoringExceptionSpec(10988 NewFD->getType(), BuiltinType))10989 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));10990 }10991 }10992 } else if (InStdNamespace && NewFD->isInStdNamespace() &&10993 isStdBuiltin(Context, NewFD, BuiltinID)) {10994 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));10995 }10996 }10997 }10998 }10999 11000 ProcessPragmaWeak(S, NewFD);11001 checkAttributesAfterMerging(*this, *NewFD);11002 11003 AddKnownFunctionAttributes(NewFD);11004 11005 if (NewFD->hasAttr<OverloadableAttr>() &&11006 !NewFD->getType()->getAs<FunctionProtoType>()) {11007 Diag(NewFD->getLocation(),11008 diag::err_attribute_overloadable_no_prototype)11009 << NewFD;11010 NewFD->dropAttr<OverloadableAttr>();11011 }11012 11013 // If there's a #pragma GCC visibility in scope, and this isn't a class11014 // member, set the visibility of this function.11015 if (!DC->isRecord() && NewFD->isExternallyVisible())11016 AddPushedVisibilityAttribute(NewFD);11017 11018 // If there's a #pragma clang arc_cf_code_audited in scope, consider11019 // marking the function.11020 ObjC().AddCFAuditedAttribute(NewFD);11021 11022 // If this is a function definition, check if we have to apply any11023 // attributes (i.e. optnone and no_builtin) due to a pragma.11024 if (D.isFunctionDefinition()) {11025 AddRangeBasedOptnone(NewFD);11026 AddImplicitMSFunctionNoBuiltinAttr(NewFD);11027 AddSectionMSAllocText(NewFD);11028 ModifyFnAttributesMSPragmaOptimize(NewFD);11029 }11030 11031 // If this is the first declaration of an extern C variable, update11032 // the map of such variables.11033 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&11034 isIncompleteDeclExternC(*this, NewFD))11035 RegisterLocallyScopedExternCDecl(NewFD, S);11036 11037 // Set this FunctionDecl's range up to the right paren.11038 NewFD->setRangeEnd(D.getSourceRange().getEnd());11039 11040 if (D.isRedeclaration() && !Previous.empty()) {11041 NamedDecl *Prev = Previous.getRepresentativeDecl();11042 checkDLLAttributeRedeclaration(*this, Prev, NewFD,11043 isMemberSpecialization ||11044 isFunctionTemplateSpecialization,11045 D.isFunctionDefinition());11046 }11047 11048 if (getLangOpts().CUDA) {11049 if (IdentifierInfo *II = NewFD->getIdentifier()) {11050 if (II->isStr(CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&11051 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {11052 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())11053 Diag(NewFD->getLocation(), diag::err_config_scalar_return)11054 << CUDA().getConfigureFuncName();11055 Context.setcudaConfigureCallDecl(NewFD);11056 }11057 if (II->isStr(CUDA().getGetParameterBufferFuncName()) &&11058 !NewFD->isInvalidDecl() &&11059 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {11060 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())11061 Diag(NewFD->getLocation(), diag::err_config_pointer_return)11062 << CUDA().getConfigureFuncName();11063 Context.setcudaGetParameterBufferDecl(NewFD);11064 }11065 if (II->isStr(CUDA().getLaunchDeviceFuncName()) &&11066 !NewFD->isInvalidDecl() &&11067 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {11068 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())11069 Diag(NewFD->getLocation(), diag::err_config_scalar_return)11070 << CUDA().getConfigureFuncName();11071 Context.setcudaLaunchDeviceDecl(NewFD);11072 }11073 }11074 }11075 11076 MarkUnusedFileScopedDecl(NewFD);11077 11078 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {11079 // OpenCL v1.2 s6.8 static is invalid for kernel functions.11080 if (SC == SC_Static) {11081 Diag(D.getIdentifierLoc(), diag::err_static_kernel);11082 D.setInvalidType();11083 }11084 11085 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.11086 if (!NewFD->getReturnType()->isVoidType()) {11087 SourceRange RTRange = NewFD->getReturnTypeSourceRange();11088 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)11089 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")11090 : FixItHint());11091 D.setInvalidType();11092 }11093 11094 llvm::SmallPtrSet<const Type *, 16> ValidTypes;11095 for (auto *Param : NewFD->parameters())11096 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);11097 11098 if (getLangOpts().OpenCLCPlusPlus) {11099 if (DC->isRecord()) {11100 Diag(D.getIdentifierLoc(), diag::err_method_kernel);11101 D.setInvalidType();11102 }11103 if (FunctionTemplate) {11104 Diag(D.getIdentifierLoc(), diag::err_template_kernel);11105 D.setInvalidType();11106 }11107 }11108 }11109 11110 if (getLangOpts().CPlusPlus) {11111 // Precalculate whether this is a friend function template with a constraint11112 // that depends on an enclosing template, per [temp.friend]p9.11113 if (isFriend && FunctionTemplate &&11114 FriendConstraintsDependOnEnclosingTemplate(NewFD)) {11115 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);11116 11117 // C++ [temp.friend]p9:11118 // A friend function template with a constraint that depends on a11119 // template parameter from an enclosing template shall be a definition.11120 if (!D.isFunctionDefinition()) {11121 Diag(NewFD->getBeginLoc(),11122 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);11123 NewFD->setInvalidDecl();11124 }11125 }11126 11127 if (FunctionTemplate) {11128 if (NewFD->isInvalidDecl())11129 FunctionTemplate->setInvalidDecl();11130 return FunctionTemplate;11131 }11132 11133 if (isMemberSpecialization && !NewFD->isInvalidDecl())11134 CompleteMemberSpecialization(NewFD, Previous);11135 }11136 11137 for (const ParmVarDecl *Param : NewFD->parameters()) {11138 QualType PT = Param->getType();11139 11140 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value11141 // types.11142 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {11143 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {11144 QualType ElemTy = PipeTy->getElementType();11145 if (ElemTy->isPointerOrReferenceType()) {11146 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);11147 D.setInvalidType();11148 }11149 }11150 }11151 // WebAssembly tables can't be used as function parameters.11152 if (Context.getTargetInfo().getTriple().isWasm()) {11153 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {11154 Diag(Param->getTypeSpecStartLoc(),11155 diag::err_wasm_table_as_function_parameter);11156 D.setInvalidType();11157 }11158 }11159 }11160 11161 // Diagnose availability attributes. Availability cannot be used on functions11162 // that are run during load/unload.11163 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {11164 if (NewFD->hasAttr<ConstructorAttr>()) {11165 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)11166 << 1;11167 NewFD->dropAttr<AvailabilityAttr>();11168 }11169 if (NewFD->hasAttr<DestructorAttr>()) {11170 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)11171 << 2;11172 NewFD->dropAttr<AvailabilityAttr>();11173 }11174 }11175 11176 // Diagnose no_builtin attribute on function declaration that are not a11177 // definition.11178 // FIXME: We should really be doing this in11179 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to11180 // the FunctionDecl and at this point of the code11181 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`11182 // because Sema::ActOnStartOfFunctionDef has not been called yet.11183 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())11184 switch (D.getFunctionDefinitionKind()) {11185 case FunctionDefinitionKind::Defaulted:11186 case FunctionDefinitionKind::Deleted:11187 Diag(NBA->getLocation(),11188 diag::err_attribute_no_builtin_on_defaulted_deleted_function)11189 << NBA->getSpelling();11190 break;11191 case FunctionDefinitionKind::Declaration:11192 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)11193 << NBA->getSpelling();11194 break;11195 case FunctionDefinitionKind::Definition:11196 break;11197 }11198 11199 // Similar to no_builtin logic above, at this point of the code11200 // FunctionDecl::isThisDeclarationADefinition() always returns `false`11201 // because Sema::ActOnStartOfFunctionDef has not been called yet.11202 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&11203 !NewFD->isInvalidDecl() &&11204 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)11205 ExternalDeclarations.push_back(NewFD);11206 11207 // Used for a warning on the 'next' declaration when used with a11208 // `routine(name)`.11209 if (getLangOpts().OpenACC)11210 OpenACC().ActOnFunctionDeclarator(NewFD);11211 11212 return NewFD;11213}11214 11215/// Return a CodeSegAttr from a containing class. The Microsoft docs say11216/// when __declspec(code_seg) "is applied to a class, all member functions of11217/// the class and nested classes -- this includes compiler-generated special11218/// member functions -- are put in the specified segment."11219/// The actual behavior is a little more complicated. The Microsoft compiler11220/// won't check outer classes if there is an active value from #pragma code_seg.11221/// The CodeSeg is always applied from the direct parent but only from outer11222/// classes when the #pragma code_seg stack is empty. See:11223/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer11224/// available since MS has removed the page.11225static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {11226 const auto *Method = dyn_cast<CXXMethodDecl>(FD);11227 if (!Method)11228 return nullptr;11229 const CXXRecordDecl *Parent = Method->getParent();11230 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {11231 Attr *NewAttr = SAttr->clone(S.getASTContext());11232 NewAttr->setImplicit(true);11233 return NewAttr;11234 }11235 11236 // The Microsoft compiler won't check outer classes for the CodeSeg11237 // when the #pragma code_seg stack is active.11238 if (S.CodeSegStack.CurrentValue)11239 return nullptr;11240 11241 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {11242 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {11243 Attr *NewAttr = SAttr->clone(S.getASTContext());11244 NewAttr->setImplicit(true);11245 return NewAttr;11246 }11247 }11248 return nullptr;11249}11250 11251Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,11252 bool IsDefinition) {11253 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))11254 return A;11255 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&11256 CodeSegStack.CurrentValue)11257 return SectionAttr::CreateImplicit(11258 getASTContext(), CodeSegStack.CurrentValue->getString(),11259 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);11260 return nullptr;11261}11262 11263bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,11264 QualType NewT, QualType OldT) {11265 if (!NewD->getLexicalDeclContext()->isDependentContext())11266 return true;11267 11268 // For dependently-typed local extern declarations and friends, we can't11269 // perform a correct type check in general until instantiation:11270 //11271 // int f();11272 // template<typename T> void g() { T f(); }11273 //11274 // (valid if g() is only instantiated with T = int).11275 if (NewT->isDependentType() &&11276 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))11277 return false;11278 11279 // Similarly, if the previous declaration was a dependent local extern11280 // declaration, we don't really know its type yet.11281 if (OldT->isDependentType() && OldD->isLocalExternDecl())11282 return false;11283 11284 return true;11285}11286 11287bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {11288 if (!D->getLexicalDeclContext()->isDependentContext())11289 return true;11290 11291 // Don't chain dependent friend function definitions until instantiation, to11292 // permit cases like11293 //11294 // void func();11295 // template<typename T> class C1 { friend void func() {} };11296 // template<typename T> class C2 { friend void func() {} };11297 //11298 // ... which is valid if only one of C1 and C2 is ever instantiated.11299 //11300 // FIXME: This need only apply to function definitions. For now, we proxy11301 // this by checking for a file-scope function. We do not want this to apply11302 // to friend declarations nominating member functions, because that gets in11303 // the way of access checks.11304 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())11305 return false;11306 11307 auto *VD = dyn_cast<ValueDecl>(D);11308 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);11309 return !VD || !PrevVD ||11310 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),11311 PrevVD->getType());11312}11313 11314/// Check the target or target_version attribute of the function for11315/// MultiVersion validity.11316///11317/// Returns true if there was an error, false otherwise.11318static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {11319 const auto *TA = FD->getAttr<TargetAttr>();11320 const auto *TVA = FD->getAttr<TargetVersionAttr>();11321 11322 assert((TA || TVA) && "Expecting target or target_version attribute");11323 11324 const TargetInfo &TargetInfo = S.Context.getTargetInfo();11325 enum ErrType { Feature = 0, Architecture = 1 };11326 11327 if (TA) {11328 ParsedTargetAttr ParseInfo =11329 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());11330 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {11331 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)11332 << Architecture << ParseInfo.CPU;11333 return true;11334 }11335 for (const auto &Feat : ParseInfo.Features) {11336 auto BareFeat = StringRef{Feat}.substr(1);11337 if (Feat[0] == '-') {11338 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)11339 << Feature << ("no-" + BareFeat).str();11340 return true;11341 }11342 11343 if (!TargetInfo.validateCpuSupports(BareFeat) ||11344 !TargetInfo.isValidFeatureName(BareFeat) ||11345 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {11346 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)11347 << Feature << BareFeat;11348 return true;11349 }11350 }11351 }11352 11353 if (TVA) {11354 llvm::SmallVector<StringRef, 8> Feats;11355 ParsedTargetAttr ParseInfo;11356 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {11357 ParseInfo =11358 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());11359 for (auto &Feat : ParseInfo.Features)11360 Feats.push_back(StringRef{Feat}.substr(1));11361 } else {11362 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());11363 TVA->getFeatures(Feats);11364 }11365 for (const auto &Feat : Feats) {11366 if (!TargetInfo.validateCpuSupports(Feat)) {11367 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)11368 << Feature << Feat;11369 return true;11370 }11371 }11372 }11373 return false;11374}11375 11376// Provide a white-list of attributes that are allowed to be combined with11377// multiversion functions.11378static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,11379 MultiVersionKind MVKind) {11380 // Note: this list/diagnosis must match the list in11381 // checkMultiversionAttributesAllSame.11382 switch (Kind) {11383 default:11384 return false;11385 case attr::ArmLocallyStreaming:11386 return MVKind == MultiVersionKind::TargetVersion ||11387 MVKind == MultiVersionKind::TargetClones;11388 case attr::Used:11389 return MVKind == MultiVersionKind::Target;11390 case attr::NonNull:11391 case attr::NoThrow:11392 return true;11393 }11394}11395 11396static bool checkNonMultiVersionCompatAttributes(Sema &S,11397 const FunctionDecl *FD,11398 const FunctionDecl *CausedFD,11399 MultiVersionKind MVKind) {11400 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {11401 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)11402 << static_cast<unsigned>(MVKind) << A;11403 if (CausedFD)11404 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);11405 return true;11406 };11407 11408 for (const Attr *A : FD->attrs()) {11409 switch (A->getKind()) {11410 case attr::CPUDispatch:11411 case attr::CPUSpecific:11412 if (MVKind != MultiVersionKind::CPUDispatch &&11413 MVKind != MultiVersionKind::CPUSpecific)11414 return Diagnose(S, A);11415 break;11416 case attr::Target:11417 if (MVKind != MultiVersionKind::Target)11418 return Diagnose(S, A);11419 break;11420 case attr::TargetVersion:11421 if (MVKind != MultiVersionKind::TargetVersion &&11422 MVKind != MultiVersionKind::TargetClones)11423 return Diagnose(S, A);11424 break;11425 case attr::TargetClones:11426 if (MVKind != MultiVersionKind::TargetClones &&11427 MVKind != MultiVersionKind::TargetVersion)11428 return Diagnose(S, A);11429 break;11430 default:11431 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))11432 return Diagnose(S, A);11433 break;11434 }11435 }11436 return false;11437}11438 11439bool Sema::areMultiversionVariantFunctionsCompatible(11440 const FunctionDecl *OldFD, const FunctionDecl *NewFD,11441 const PartialDiagnostic &NoProtoDiagID,11442 const PartialDiagnosticAt &NoteCausedDiagIDAt,11443 const PartialDiagnosticAt &NoSupportDiagIDAt,11444 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,11445 bool ConstexprSupported, bool CLinkageMayDiffer) {11446 enum DoesntSupport {11447 FuncTemplates = 0,11448 VirtFuncs = 1,11449 DeducedReturn = 2,11450 Constructors = 3,11451 Destructors = 4,11452 DeletedFuncs = 5,11453 DefaultedFuncs = 6,11454 ConstexprFuncs = 7,11455 ConstevalFuncs = 8,11456 Lambda = 9,11457 };11458 enum Different {11459 CallingConv = 0,11460 ReturnType = 1,11461 ConstexprSpec = 2,11462 InlineSpec = 3,11463 Linkage = 4,11464 LanguageLinkage = 5,11465 };11466 11467 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&11468 !OldFD->getType()->getAs<FunctionProtoType>()) {11469 Diag(OldFD->getLocation(), NoProtoDiagID);11470 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);11471 return true;11472 }11473 11474 if (NoProtoDiagID.getDiagID() != 0 &&11475 !NewFD->getType()->getAs<FunctionProtoType>())11476 return Diag(NewFD->getLocation(), NoProtoDiagID);11477 11478 if (!TemplatesSupported &&11479 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)11480 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11481 << FuncTemplates;11482 11483 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {11484 if (NewCXXFD->isVirtual())11485 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11486 << VirtFuncs;11487 11488 if (isa<CXXConstructorDecl>(NewCXXFD))11489 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11490 << Constructors;11491 11492 if (isa<CXXDestructorDecl>(NewCXXFD))11493 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11494 << Destructors;11495 }11496 11497 if (NewFD->isDeleted())11498 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11499 << DeletedFuncs;11500 11501 if (NewFD->isDefaulted())11502 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11503 << DefaultedFuncs;11504 11505 if (!ConstexprSupported && NewFD->isConstexpr())11506 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11507 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);11508 11509 QualType NewQType = Context.getCanonicalType(NewFD->getType());11510 const auto *NewType = cast<FunctionType>(NewQType);11511 QualType NewReturnType = NewType->getReturnType();11512 11513 if (NewReturnType->isUndeducedType())11514 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)11515 << DeducedReturn;11516 11517 // Ensure the return type is identical.11518 if (OldFD) {11519 QualType OldQType = Context.getCanonicalType(OldFD->getType());11520 const auto *OldType = cast<FunctionType>(OldQType);11521 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();11522 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();11523 11524 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();11525 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();11526 11527 bool ArmStreamingCCMismatched = false;11528 if (OldFPT && NewFPT) {11529 unsigned Diff =11530 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();11531 // Arm-streaming, arm-streaming-compatible and non-streaming versions11532 // cannot be mixed.11533 if (Diff & (FunctionType::SME_PStateSMEnabledMask |11534 FunctionType::SME_PStateSMCompatibleMask))11535 ArmStreamingCCMismatched = true;11536 }11537 11538 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)11539 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;11540 11541 QualType OldReturnType = OldType->getReturnType();11542 11543 if (OldReturnType != NewReturnType)11544 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;11545 11546 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())11547 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;11548 11549 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())11550 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;11551 11552 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())11553 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;11554 11555 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())11556 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;11557 11558 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,11559 NewFD->getLocation()))11560 return true;11561 }11562 return false;11563}11564 11565static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,11566 const FunctionDecl *NewFD,11567 bool CausesMV,11568 MultiVersionKind MVKind) {11569 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {11570 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);11571 if (OldFD)11572 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);11573 return true;11574 }11575 11576 bool IsCPUSpecificCPUDispatchMVKind =11577 MVKind == MultiVersionKind::CPUDispatch ||11578 MVKind == MultiVersionKind::CPUSpecific;11579 11580 if (CausesMV && OldFD &&11581 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))11582 return true;11583 11584 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))11585 return true;11586 11587 // Only allow transition to MultiVersion if it hasn't been used.11588 if (OldFD && CausesMV && OldFD->isUsed(false)) {11589 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);11590 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);11591 return true;11592 }11593 11594 return S.areMultiversionVariantFunctionsCompatible(11595 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),11596 PartialDiagnosticAt(NewFD->getLocation(),11597 S.PDiag(diag::note_multiversioning_caused_here)),11598 PartialDiagnosticAt(NewFD->getLocation(),11599 S.PDiag(diag::err_multiversion_doesnt_support)11600 << static_cast<unsigned>(MVKind)),11601 PartialDiagnosticAt(NewFD->getLocation(),11602 S.PDiag(diag::err_multiversion_diff)),11603 /*TemplatesSupported=*/false,11604 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,11605 /*CLinkageMayDiffer=*/false);11606}11607 11608/// Check the validity of a multiversion function declaration that is the11609/// first of its kind. Also sets the multiversion'ness' of the function itself.11610///11611/// This sets NewFD->isInvalidDecl() to true if there was an error.11612///11613/// Returns true if there was an error, false otherwise.11614static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {11615 MultiVersionKind MVKind = FD->getMultiVersionKind();11616 assert(MVKind != MultiVersionKind::None &&11617 "Function lacks multiversion attribute");11618 const auto *TA = FD->getAttr<TargetAttr>();11619 const auto *TVA = FD->getAttr<TargetVersionAttr>();11620 // The target attribute only causes MV if this declaration is the default,11621 // otherwise it is treated as a normal function.11622 if (TA && !TA->isDefaultVersion())11623 return false;11624 11625 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {11626 FD->setInvalidDecl();11627 return true;11628 }11629 11630 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {11631 FD->setInvalidDecl();11632 return true;11633 }11634 11635 FD->setIsMultiVersion();11636 return false;11637}11638 11639static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {11640 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {11641 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)11642 return true;11643 }11644 11645 return false;11646}11647 11648static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {11649 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&11650 !From->getASTContext().getTargetInfo().getTriple().isRISCV())11651 return;11652 11653 MultiVersionKind MVKindFrom = From->getMultiVersionKind();11654 MultiVersionKind MVKindTo = To->getMultiVersionKind();11655 11656 if (MVKindTo == MultiVersionKind::None &&11657 (MVKindFrom == MultiVersionKind::TargetVersion ||11658 MVKindFrom == MultiVersionKind::TargetClones))11659 To->addAttr(TargetVersionAttr::CreateImplicit(11660 To->getASTContext(), "default", To->getSourceRange()));11661}11662 11663static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,11664 FunctionDecl *NewFD,11665 bool &Redeclaration,11666 NamedDecl *&OldDecl,11667 LookupResult &Previous) {11668 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");11669 11670 const auto *NewTA = NewFD->getAttr<TargetAttr>();11671 const auto *OldTA = OldFD->getAttr<TargetAttr>();11672 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();11673 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();11674 11675 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");11676 11677 // The definitions should be allowed in any order. If we have discovered11678 // a new target version and the preceeding was the default, then add the11679 // corresponding attribute to it.11680 patchDefaultTargetVersion(NewFD, OldFD);11681 11682 // If the old decl is NOT MultiVersioned yet, and we don't cause that11683 // to change, this is a simple redeclaration.11684 if (NewTA && !NewTA->isDefaultVersion() &&11685 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))11686 return false;11687 11688 // Otherwise, this decl causes MultiVersioning.11689 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,11690 NewTVA ? MultiVersionKind::TargetVersion11691 : MultiVersionKind::Target)) {11692 NewFD->setInvalidDecl();11693 return true;11694 }11695 11696 if (CheckMultiVersionValue(S, NewFD)) {11697 NewFD->setInvalidDecl();11698 return true;11699 }11700 11701 // If this is 'default', permit the forward declaration.11702 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||11703 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {11704 Redeclaration = true;11705 OldDecl = OldFD;11706 OldFD->setIsMultiVersion();11707 NewFD->setIsMultiVersion();11708 return false;11709 }11710 11711 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {11712 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);11713 NewFD->setInvalidDecl();11714 return true;11715 }11716 11717 if (NewTA) {11718 ParsedTargetAttr OldParsed =11719 S.getASTContext().getTargetInfo().parseTargetAttr(11720 OldTA->getFeaturesStr());11721 llvm::sort(OldParsed.Features);11722 ParsedTargetAttr NewParsed =11723 S.getASTContext().getTargetInfo().parseTargetAttr(11724 NewTA->getFeaturesStr());11725 // Sort order doesn't matter, it just needs to be consistent.11726 llvm::sort(NewParsed.Features);11727 if (OldParsed == NewParsed) {11728 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);11729 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);11730 NewFD->setInvalidDecl();11731 return true;11732 }11733 }11734 11735 for (const auto *FD : OldFD->redecls()) {11736 const auto *CurTA = FD->getAttr<TargetAttr>();11737 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();11738 // We allow forward declarations before ANY multiversioning attributes, but11739 // nothing after the fact.11740 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&11741 ((NewTA && (!CurTA || CurTA->isInherited())) ||11742 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {11743 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)11744 << (NewTA ? 0 : 2);11745 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);11746 NewFD->setInvalidDecl();11747 return true;11748 }11749 }11750 11751 OldFD->setIsMultiVersion();11752 NewFD->setIsMultiVersion();11753 Redeclaration = false;11754 OldDecl = nullptr;11755 Previous.clear();11756 return false;11757}11758 11759static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {11760 MultiVersionKind OldKind = Old->getMultiVersionKind();11761 MultiVersionKind NewKind = New->getMultiVersionKind();11762 11763 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||11764 NewKind == MultiVersionKind::None)11765 return true;11766 11767 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {11768 switch (OldKind) {11769 case MultiVersionKind::TargetVersion:11770 return NewKind == MultiVersionKind::TargetClones;11771 case MultiVersionKind::TargetClones:11772 return NewKind == MultiVersionKind::TargetVersion;11773 default:11774 return false;11775 }11776 } else {11777 switch (OldKind) {11778 case MultiVersionKind::CPUDispatch:11779 return NewKind == MultiVersionKind::CPUSpecific;11780 case MultiVersionKind::CPUSpecific:11781 return NewKind == MultiVersionKind::CPUDispatch;11782 default:11783 return false;11784 }11785 }11786}11787 11788/// Check the validity of a new function declaration being added to an existing11789/// multiversioned declaration collection.11790static bool CheckMultiVersionAdditionalDecl(11791 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,11792 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,11793 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,11794 LookupResult &Previous) {11795 11796 // Disallow mixing of multiversioning types.11797 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {11798 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);11799 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);11800 NewFD->setInvalidDecl();11801 return true;11802 }11803 11804 // Add the default target_version attribute if it's missing.11805 patchDefaultTargetVersion(OldFD, NewFD);11806 patchDefaultTargetVersion(NewFD, OldFD);11807 11808 const auto *NewTA = NewFD->getAttr<TargetAttr>();11809 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();11810 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();11811 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();11812 11813 ParsedTargetAttr NewParsed;11814 if (NewTA) {11815 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(11816 NewTA->getFeaturesStr());11817 llvm::sort(NewParsed.Features);11818 }11819 llvm::SmallVector<StringRef, 8> NewFeats;11820 if (NewTVA) {11821 NewTVA->getFeatures(NewFeats);11822 llvm::sort(NewFeats);11823 }11824 11825 bool UseMemberUsingDeclRules =11826 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();11827 11828 bool MayNeedOverloadableChecks =11829 AllowOverloadingOfFunction(Previous, S.Context, NewFD);11830 11831 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration11832 // of a previous member of the MultiVersion set.11833 for (NamedDecl *ND : Previous) {11834 FunctionDecl *CurFD = ND->getAsFunction();11835 if (!CurFD || CurFD->isInvalidDecl())11836 continue;11837 if (MayNeedOverloadableChecks &&11838 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))11839 continue;11840 11841 switch (NewMVKind) {11842 case MultiVersionKind::None:11843 assert(OldMVKind == MultiVersionKind::TargetClones &&11844 "Only target_clones can be omitted in subsequent declarations");11845 break;11846 case MultiVersionKind::Target: {11847 const auto *CurTA = CurFD->getAttr<TargetAttr>();11848 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {11849 NewFD->setIsMultiVersion();11850 Redeclaration = true;11851 OldDecl = ND;11852 return false;11853 }11854 11855 ParsedTargetAttr CurParsed =11856 S.getASTContext().getTargetInfo().parseTargetAttr(11857 CurTA->getFeaturesStr());11858 llvm::sort(CurParsed.Features);11859 if (CurParsed == NewParsed) {11860 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);11861 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);11862 NewFD->setInvalidDecl();11863 return true;11864 }11865 break;11866 }11867 case MultiVersionKind::TargetVersion: {11868 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {11869 if (CurTVA->getName() == NewTVA->getName()) {11870 NewFD->setIsMultiVersion();11871 Redeclaration = true;11872 OldDecl = ND;11873 return false;11874 }11875 llvm::SmallVector<StringRef, 8> CurFeats;11876 CurTVA->getFeatures(CurFeats);11877 llvm::sort(CurFeats);11878 11879 if (CurFeats == NewFeats) {11880 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);11881 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);11882 NewFD->setInvalidDecl();11883 return true;11884 }11885 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {11886 // Default11887 if (NewFeats.empty())11888 break;11889 11890 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {11891 llvm::SmallVector<StringRef, 8> CurFeats;11892 CurClones->getFeatures(CurFeats, I);11893 llvm::sort(CurFeats);11894 11895 if (CurFeats == NewFeats) {11896 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);11897 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);11898 NewFD->setInvalidDecl();11899 return true;11900 }11901 }11902 }11903 break;11904 }11905 case MultiVersionKind::TargetClones: {11906 assert(NewClones && "MultiVersionKind does not match attribute type");11907 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {11908 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||11909 !std::equal(CurClones->featuresStrs_begin(),11910 CurClones->featuresStrs_end(),11911 NewClones->featuresStrs_begin())) {11912 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);11913 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);11914 NewFD->setInvalidDecl();11915 return true;11916 }11917 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {11918 llvm::SmallVector<StringRef, 8> CurFeats;11919 CurTVA->getFeatures(CurFeats);11920 llvm::sort(CurFeats);11921 11922 // Default11923 if (CurFeats.empty())11924 break;11925 11926 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {11927 NewFeats.clear();11928 NewClones->getFeatures(NewFeats, I);11929 llvm::sort(NewFeats);11930 11931 if (CurFeats == NewFeats) {11932 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);11933 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);11934 NewFD->setInvalidDecl();11935 return true;11936 }11937 }11938 break;11939 }11940 Redeclaration = true;11941 OldDecl = CurFD;11942 NewFD->setIsMultiVersion();11943 return false;11944 }11945 case MultiVersionKind::CPUSpecific:11946 case MultiVersionKind::CPUDispatch: {11947 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();11948 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();11949 // Handle CPUDispatch/CPUSpecific versions.11950 // Only 1 CPUDispatch function is allowed, this will make it go through11951 // the redeclaration errors.11952 if (NewMVKind == MultiVersionKind::CPUDispatch &&11953 CurFD->hasAttr<CPUDispatchAttr>()) {11954 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&11955 std::equal(11956 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),11957 NewCPUDisp->cpus_begin(),11958 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {11959 return Cur->getName() == New->getName();11960 })) {11961 NewFD->setIsMultiVersion();11962 Redeclaration = true;11963 OldDecl = ND;11964 return false;11965 }11966 11967 // If the declarations don't match, this is an error condition.11968 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);11969 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);11970 NewFD->setInvalidDecl();11971 return true;11972 }11973 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {11974 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&11975 std::equal(11976 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),11977 NewCPUSpec->cpus_begin(),11978 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {11979 return Cur->getName() == New->getName();11980 })) {11981 NewFD->setIsMultiVersion();11982 Redeclaration = true;11983 OldDecl = ND;11984 return false;11985 }11986 11987 // Only 1 version of CPUSpecific is allowed for each CPU.11988 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {11989 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {11990 if (CurII == NewII) {11991 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)11992 << NewII;11993 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);11994 NewFD->setInvalidDecl();11995 return true;11996 }11997 }11998 }11999 }12000 break;12001 }12002 }12003 }12004 12005 // Redeclarations of a target_clones function may omit the attribute, in which12006 // case it will be inherited during declaration merging.12007 if (NewMVKind == MultiVersionKind::None &&12008 OldMVKind == MultiVersionKind::TargetClones) {12009 NewFD->setIsMultiVersion();12010 Redeclaration = true;12011 OldDecl = OldFD;12012 return false;12013 }12014 12015 // Else, this is simply a non-redecl case. Checking the 'value' is only12016 // necessary in the Target case, since The CPUSpecific/Dispatch cases are12017 // handled in the attribute adding step.12018 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {12019 NewFD->setInvalidDecl();12020 return true;12021 }12022 12023 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,12024 !OldFD->isMultiVersion(), NewMVKind)) {12025 NewFD->setInvalidDecl();12026 return true;12027 }12028 12029 // Permit forward declarations in the case where these two are compatible.12030 if (!OldFD->isMultiVersion()) {12031 OldFD->setIsMultiVersion();12032 NewFD->setIsMultiVersion();12033 Redeclaration = true;12034 OldDecl = OldFD;12035 return false;12036 }12037 12038 NewFD->setIsMultiVersion();12039 Redeclaration = false;12040 OldDecl = nullptr;12041 Previous.clear();12042 return false;12043}12044 12045/// Check the validity of a mulitversion function declaration.12046/// Also sets the multiversion'ness' of the function itself.12047///12048/// This sets NewFD->isInvalidDecl() to true if there was an error.12049///12050/// Returns true if there was an error, false otherwise.12051static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,12052 bool &Redeclaration, NamedDecl *&OldDecl,12053 LookupResult &Previous) {12054 const TargetInfo &TI = S.getASTContext().getTargetInfo();12055 12056 // Check if FMV is disabled.12057 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))12058 return false;12059 12060 const auto *NewTA = NewFD->getAttr<TargetAttr>();12061 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();12062 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();12063 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();12064 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();12065 MultiVersionKind MVKind = NewFD->getMultiVersionKind();12066 12067 // Main isn't allowed to become a multiversion function, however it IS12068 // permitted to have 'main' be marked with the 'target' optimization hint,12069 // for 'target_version' only default is allowed.12070 if (NewFD->isMain()) {12071 if (MVKind != MultiVersionKind::None &&12072 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&12073 !(MVKind == MultiVersionKind::TargetVersion &&12074 NewTVA->isDefaultVersion())) {12075 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);12076 NewFD->setInvalidDecl();12077 return true;12078 }12079 return false;12080 }12081 12082 // Target attribute on AArch64 is not used for multiversioning12083 if (NewTA && TI.getTriple().isAArch64())12084 return false;12085 12086 // Target attribute on RISCV is not used for multiversioning12087 if (NewTA && TI.getTriple().isRISCV())12088 return false;12089 12090 if (!OldDecl || !OldDecl->getAsFunction() ||12091 !OldDecl->getDeclContext()->getRedeclContext()->Equals(12092 NewFD->getDeclContext()->getRedeclContext())) {12093 // If there's no previous declaration, AND this isn't attempting to cause12094 // multiversioning, this isn't an error condition.12095 if (MVKind == MultiVersionKind::None)12096 return false;12097 return CheckMultiVersionFirstFunction(S, NewFD);12098 }12099 12100 FunctionDecl *OldFD = OldDecl->getAsFunction();12101 12102 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)12103 return false;12104 12105 // Multiversioned redeclarations aren't allowed to omit the attribute, except12106 // for target_clones and target_version.12107 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&12108 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&12109 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {12110 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)12111 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);12112 NewFD->setInvalidDecl();12113 return true;12114 }12115 12116 if (!OldFD->isMultiVersion()) {12117 switch (MVKind) {12118 case MultiVersionKind::Target:12119 case MultiVersionKind::TargetVersion:12120 return CheckDeclarationCausesMultiVersioning(12121 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);12122 case MultiVersionKind::TargetClones:12123 if (OldFD->isUsed(false)) {12124 NewFD->setInvalidDecl();12125 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);12126 }12127 OldFD->setIsMultiVersion();12128 break;12129 12130 case MultiVersionKind::CPUDispatch:12131 case MultiVersionKind::CPUSpecific:12132 case MultiVersionKind::None:12133 break;12134 }12135 }12136 12137 // At this point, we have a multiversion function decl (in OldFD) AND an12138 // appropriate attribute in the current function decl (unless it's allowed to12139 // omit the attribute). Resolve that these are still compatible with previous12140 // declarations.12141 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,12142 NewCPUSpec, NewClones, Redeclaration,12143 OldDecl, Previous);12144}12145 12146static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {12147 bool IsPure = NewFD->hasAttr<PureAttr>();12148 bool IsConst = NewFD->hasAttr<ConstAttr>();12149 12150 // If there are no pure or const attributes, there's nothing to check.12151 if (!IsPure && !IsConst)12152 return;12153 12154 // If the function is marked both pure and const, we retain the const12155 // attribute because it makes stronger guarantees than the pure attribute, and12156 // we drop the pure attribute explicitly to prevent later confusion about12157 // semantics.12158 if (IsPure && IsConst) {12159 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);12160 NewFD->dropAttrs<PureAttr>();12161 }12162 12163 // Constructors and destructors are functions which return void, so are12164 // handled here as well.12165 if (NewFD->getReturnType()->isVoidType()) {12166 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)12167 << IsConst;12168 NewFD->dropAttrs<PureAttr, ConstAttr>();12169 }12170}12171 12172bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,12173 LookupResult &Previous,12174 bool IsMemberSpecialization,12175 bool DeclIsDefn) {12176 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&12177 "Variably modified return types are not handled here");12178 12179 // Determine whether the type of this function should be merged with12180 // a previous visible declaration. This never happens for functions in C++,12181 // and always happens in C if the previous declaration was visible.12182 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&12183 !Previous.isShadowed();12184 12185 bool Redeclaration = false;12186 NamedDecl *OldDecl = nullptr;12187 bool MayNeedOverloadableChecks = false;12188 12189 inferLifetimeCaptureByAttribute(NewFD);12190 // Merge or overload the declaration with an existing declaration of12191 // the same name, if appropriate.12192 if (!Previous.empty()) {12193 // Determine whether NewFD is an overload of PrevDecl or12194 // a declaration that requires merging. If it's an overload,12195 // there's no more work to do here; we'll just add the new12196 // function to the scope.12197 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {12198 NamedDecl *Candidate = Previous.getRepresentativeDecl();12199 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {12200 Redeclaration = true;12201 OldDecl = Candidate;12202 }12203 } else {12204 MayNeedOverloadableChecks = true;12205 switch (CheckOverload(S, NewFD, Previous, OldDecl,12206 /*NewIsUsingDecl*/ false)) {12207 case OverloadKind::Match:12208 Redeclaration = true;12209 break;12210 12211 case OverloadKind::NonFunction:12212 Redeclaration = true;12213 break;12214 12215 case OverloadKind::Overload:12216 Redeclaration = false;12217 break;12218 }12219 }12220 }12221 12222 // Check for a previous extern "C" declaration with this name.12223 if (!Redeclaration &&12224 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {12225 if (!Previous.empty()) {12226 // This is an extern "C" declaration with the same name as a previous12227 // declaration, and thus redeclares that entity...12228 Redeclaration = true;12229 OldDecl = Previous.getFoundDecl();12230 MergeTypeWithPrevious = false;12231 12232 // ... except in the presence of __attribute__((overloadable)).12233 if (OldDecl->hasAttr<OverloadableAttr>() ||12234 NewFD->hasAttr<OverloadableAttr>()) {12235 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {12236 MayNeedOverloadableChecks = true;12237 Redeclaration = false;12238 OldDecl = nullptr;12239 }12240 }12241 }12242 }12243 12244 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))12245 return Redeclaration;12246 12247 // PPC MMA non-pointer types are not allowed as function return types.12248 if (Context.getTargetInfo().getTriple().isPPC64() &&12249 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {12250 NewFD->setInvalidDecl();12251 }12252 12253 CheckConstPureAttributesUsage(*this, NewFD);12254 12255 // C++ [dcl.spec.auto.general]p12:12256 // Return type deduction for a templated function with a placeholder in its12257 // declared type occurs when the definition is instantiated even if the12258 // function body contains a return statement with a non-type-dependent12259 // operand.12260 //12261 // C++ [temp.dep.expr]p3:12262 // An id-expression is type-dependent if it is a template-id that is not a12263 // concept-id and is dependent; or if its terminal name is:12264 // - [...]12265 // - associated by name lookup with one or more declarations of member12266 // functions of a class that is the current instantiation declared with a12267 // return type that contains a placeholder type,12268 // - [...]12269 //12270 // If this is a templated function with a placeholder in its return type,12271 // make the placeholder type dependent since it won't be deduced until the12272 // definition is instantiated. We do this here because it needs to happen12273 // for implicitly instantiated member functions/member function templates.12274 if (getLangOpts().CPlusPlus14 &&12275 (NewFD->isDependentContext() &&12276 NewFD->getReturnType()->isUndeducedType())) {12277 const FunctionProtoType *FPT =12278 NewFD->getType()->castAs<FunctionProtoType>();12279 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());12280 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),12281 FPT->getExtProtoInfo()));12282 }12283 12284 // C++11 [dcl.constexpr]p8:12285 // A constexpr specifier for a non-static member function that is not12286 // a constructor declares that member function to be const.12287 //12288 // This needs to be delayed until we know whether this is an out-of-line12289 // definition of a static member function.12290 //12291 // This rule is not present in C++1y, so we produce a backwards12292 // compatibility warning whenever it happens in C++11.12293 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);12294 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&12295 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&12296 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {12297 CXXMethodDecl *OldMD = nullptr;12298 if (OldDecl)12299 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());12300 if (!OldMD || !OldMD->isStatic()) {12301 const FunctionProtoType *FPT =12302 MD->getType()->castAs<FunctionProtoType>();12303 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();12304 EPI.TypeQuals.addConst();12305 MD->setType(Context.getFunctionType(FPT->getReturnType(),12306 FPT->getParamTypes(), EPI));12307 12308 // Warn that we did this, if we're not performing template instantiation.12309 // In that case, we'll have warned already when the template was defined.12310 if (!inTemplateInstantiation()) {12311 SourceLocation AddConstLoc;12312 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()12313 .IgnoreParens().getAs<FunctionTypeLoc>())12314 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());12315 12316 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)12317 << FixItHint::CreateInsertion(AddConstLoc, " const");12318 }12319 }12320 }12321 12322 if (Redeclaration) {12323 // NewFD and OldDecl represent declarations that need to be12324 // merged.12325 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,12326 DeclIsDefn)) {12327 NewFD->setInvalidDecl();12328 return Redeclaration;12329 }12330 12331 Previous.clear();12332 Previous.addDecl(OldDecl);12333 12334 if (FunctionTemplateDecl *OldTemplateDecl =12335 dyn_cast<FunctionTemplateDecl>(OldDecl)) {12336 auto *OldFD = OldTemplateDecl->getTemplatedDecl();12337 FunctionTemplateDecl *NewTemplateDecl12338 = NewFD->getDescribedFunctionTemplate();12339 assert(NewTemplateDecl && "Template/non-template mismatch");12340 12341 // The call to MergeFunctionDecl above may have created some state in12342 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we12343 // can add it as a redeclaration.12344 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);12345 12346 NewFD->setPreviousDeclaration(OldFD);12347 if (NewFD->isCXXClassMember()) {12348 NewFD->setAccess(OldTemplateDecl->getAccess());12349 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());12350 }12351 12352 // If this is an explicit specialization of a member that is a function12353 // template, mark it as a member specialization.12354 if (IsMemberSpecialization &&12355 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {12356 NewTemplateDecl->setMemberSpecialization();12357 assert(OldTemplateDecl->isMemberSpecialization());12358 // Explicit specializations of a member template do not inherit deleted12359 // status from the parent member template that they are specializing.12360 if (OldFD->isDeleted()) {12361 // FIXME: This assert will not hold in the presence of modules.12362 assert(OldFD->getCanonicalDecl() == OldFD);12363 // FIXME: We need an update record for this AST mutation.12364 OldFD->setDeletedAsWritten(false);12365 }12366 }12367 12368 } else {12369 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {12370 auto *OldFD = cast<FunctionDecl>(OldDecl);12371 // This needs to happen first so that 'inline' propagates.12372 NewFD->setPreviousDeclaration(OldFD);12373 if (NewFD->isCXXClassMember())12374 NewFD->setAccess(OldFD->getAccess());12375 }12376 }12377 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&12378 !NewFD->getAttr<OverloadableAttr>()) {12379 assert((Previous.empty() ||12380 llvm::any_of(Previous,12381 [](const NamedDecl *ND) {12382 return ND->hasAttr<OverloadableAttr>();12383 })) &&12384 "Non-redecls shouldn't happen without overloadable present");12385 12386 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {12387 const auto *FD = dyn_cast<FunctionDecl>(ND);12388 return FD && !FD->hasAttr<OverloadableAttr>();12389 });12390 12391 if (OtherUnmarkedIter != Previous.end()) {12392 Diag(NewFD->getLocation(),12393 diag::err_attribute_overloadable_multiple_unmarked_overloads);12394 Diag((*OtherUnmarkedIter)->getLocation(),12395 diag::note_attribute_overloadable_prev_overload)12396 << false;12397 12398 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));12399 }12400 }12401 12402 if (LangOpts.OpenMP)12403 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);12404 12405 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())12406 SYCL().CheckSYCLEntryPointFunctionDecl(NewFD);12407 12408 if (NewFD->hasAttr<SYCLExternalAttr>())12409 SYCL().CheckSYCLExternalFunctionDecl(NewFD);12410 12411 // Semantic checking for this function declaration (in isolation).12412 12413 if (getLangOpts().CPlusPlus) {12414 // C++-specific checks.12415 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {12416 CheckConstructor(Constructor);12417 } else if (CXXDestructorDecl *Destructor =12418 dyn_cast<CXXDestructorDecl>(NewFD)) {12419 // We check here for invalid destructor names.12420 // If we have a friend destructor declaration that is dependent, we can't12421 // diagnose right away because cases like this are still valid:12422 // template <class T> struct A { friend T::X::~Y(); };12423 // struct B { struct Y { ~Y(); }; using X = Y; };12424 // template struct A<B>;12425 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||12426 !Destructor->getFunctionObjectParameterType()->isDependentType()) {12427 CanQualType ClassType =12428 Context.getCanonicalTagType(Destructor->getParent());12429 12430 DeclarationName Name =12431 Context.DeclarationNames.getCXXDestructorName(ClassType);12432 if (NewFD->getDeclName() != Name) {12433 Diag(NewFD->getLocation(), diag::err_destructor_name);12434 NewFD->setInvalidDecl();12435 return Redeclaration;12436 }12437 }12438 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {12439 if (auto *TD = Guide->getDescribedFunctionTemplate())12440 CheckDeductionGuideTemplate(TD);12441 12442 // A deduction guide is not on the list of entities that can be12443 // explicitly specialized.12444 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)12445 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)12446 << /*explicit specialization*/ 1;12447 }12448 12449 // Find any virtual functions that this function overrides.12450 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {12451 if (!Method->isFunctionTemplateSpecialization() &&12452 !Method->getDescribedFunctionTemplate() &&12453 Method->isCanonicalDecl()) {12454 AddOverriddenMethods(Method->getParent(), Method);12455 }12456 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())12457 // C++2a [class.virtual]p612458 // A virtual method shall not have a requires-clause.12459 Diag(NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),12460 diag::err_constrained_virtual_method);12461 12462 if (Method->isStatic())12463 checkThisInStaticMemberFunctionType(Method);12464 }12465 12466 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))12467 ActOnConversionDeclarator(Conversion);12468 12469 // Extra checking for C++ overloaded operators (C++ [over.oper]).12470 if (NewFD->isOverloadedOperator() &&12471 CheckOverloadedOperatorDeclaration(NewFD)) {12472 NewFD->setInvalidDecl();12473 return Redeclaration;12474 }12475 12476 // Extra checking for C++0x literal operators (C++0x [over.literal]).12477 if (NewFD->getLiteralIdentifier() &&12478 CheckLiteralOperatorDeclaration(NewFD)) {12479 NewFD->setInvalidDecl();12480 return Redeclaration;12481 }12482 12483 // In C++, check default arguments now that we have merged decls. Unless12484 // the lexical context is the class, because in this case this is done12485 // during delayed parsing anyway.12486 if (!CurContext->isRecord())12487 CheckCXXDefaultArguments(NewFD);12488 12489 // If this function is declared as being extern "C", then check to see if12490 // the function returns a UDT (class, struct, or union type) that is not C12491 // compatible, and if it does, warn the user.12492 // But, issue any diagnostic on the first declaration only.12493 if (Previous.empty() && NewFD->isExternC()) {12494 QualType R = NewFD->getReturnType();12495 if (R->isIncompleteType() && !R->isVoidType())12496 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)12497 << NewFD << R;12498 else if (!R.isPODType(Context) && !R->isVoidType() &&12499 !R->isObjCObjectPointerType())12500 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;12501 }12502 12503 // C++1z [dcl.fct]p6:12504 // [...] whether the function has a non-throwing exception-specification12505 // [is] part of the function type12506 //12507 // This results in an ABI break between C++14 and C++17 for functions whose12508 // declared type includes an exception-specification in a parameter or12509 // return type. (Exception specifications on the function itself are OK in12510 // most cases, and exception specifications are not permitted in most other12511 // contexts where they could make it into a mangling.)12512 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {12513 auto HasNoexcept = [&](QualType T) -> bool {12514 // Strip off declarator chunks that could be between us and a function12515 // type. We don't need to look far, exception specifications are very12516 // restricted prior to C++17.12517 if (auto *RT = T->getAs<ReferenceType>())12518 T = RT->getPointeeType();12519 else if (T->isAnyPointerType())12520 T = T->getPointeeType();12521 else if (auto *MPT = T->getAs<MemberPointerType>())12522 T = MPT->getPointeeType();12523 if (auto *FPT = T->getAs<FunctionProtoType>())12524 if (FPT->isNothrow())12525 return true;12526 return false;12527 };12528 12529 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();12530 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());12531 for (QualType T : FPT->param_types())12532 AnyNoexcept |= HasNoexcept(T);12533 if (AnyNoexcept)12534 Diag(NewFD->getLocation(),12535 diag::warn_cxx17_compat_exception_spec_in_signature)12536 << NewFD;12537 }12538 12539 if (!Redeclaration && LangOpts.CUDA) {12540 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();12541 for (auto *Parm : NewFD->parameters()) {12542 if (!Parm->getType()->isDependentType() &&12543 Parm->hasAttr<CUDAGridConstantAttr>() &&12544 !(IsKernel && Parm->getType().isConstQualified()))12545 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),12546 diag::err_cuda_grid_constant_not_allowed);12547 }12548 CUDA().checkTargetOverload(NewFD, Previous);12549 }12550 }12551 12552 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())12553 ARM().CheckSMEFunctionDefAttributes(NewFD);12554 12555 return Redeclaration;12556}12557 12558void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {12559 // [basic.start.main]p312560 // The main function shall not be declared with C linkage-specification.12561 if (FD->isExternCContext())12562 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);12563 12564 // C++11 [basic.start.main]p3:12565 // A program that [...] declares main to be inline, static or12566 // constexpr is ill-formed.12567 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall12568 // appear in a declaration of main.12569 // static main is not an error under C99, but we should warn about it.12570 // We accept _Noreturn main as an extension.12571 if (FD->getStorageClass() == SC_Static)12572 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus12573 ? diag::err_static_main : diag::warn_static_main)12574 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());12575 if (FD->isInlineSpecified())12576 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)12577 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());12578 if (DS.isNoreturnSpecified()) {12579 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();12580 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));12581 Diag(NoreturnLoc, diag::ext_noreturn_main);12582 Diag(NoreturnLoc, diag::note_main_remove_noreturn)12583 << FixItHint::CreateRemoval(NoreturnRange);12584 }12585 if (FD->isConstexpr()) {12586 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)12587 << FD->isConsteval()12588 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());12589 FD->setConstexprKind(ConstexprSpecKind::Unspecified);12590 }12591 12592 if (getLangOpts().OpenCL) {12593 Diag(FD->getLocation(), diag::err_opencl_no_main)12594 << FD->hasAttr<DeviceKernelAttr>();12595 FD->setInvalidDecl();12596 return;12597 }12598 12599 if (FD->hasAttr<SYCLExternalAttr>()) {12600 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)12601 << FD->getAttr<SYCLExternalAttr>();12602 FD->setInvalidDecl();12603 return;12604 }12605 12606 // Functions named main in hlsl are default entries, but don't have specific12607 // signatures they are required to conform to.12608 if (getLangOpts().HLSL)12609 return;12610 12611 QualType T = FD->getType();12612 assert(T->isFunctionType() && "function decl is not of function type");12613 const FunctionType* FT = T->castAs<FunctionType>();12614 12615 // Set default calling convention for main()12616 if (FT->getCallConv() != CC_C) {12617 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));12618 FD->setType(QualType(FT, 0));12619 T = Context.getCanonicalType(FD->getType());12620 }12621 12622 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {12623 // In C with GNU extensions we allow main() to have non-integer return12624 // type, but we should warn about the extension, and we disable the12625 // implicit-return-zero rule.12626 12627 // GCC in C mode accepts qualified 'int'.12628 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))12629 FD->setHasImplicitReturnZero(true);12630 else {12631 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);12632 SourceRange RTRange = FD->getReturnTypeSourceRange();12633 if (RTRange.isValid())12634 Diag(RTRange.getBegin(), diag::note_main_change_return_type)12635 << FixItHint::CreateReplacement(RTRange, "int");12636 }12637 } else {12638 // In C and C++, main magically returns 0 if you fall off the end;12639 // set the flag which tells us that.12640 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.12641 12642 // All the standards say that main() should return 'int'.12643 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))12644 FD->setHasImplicitReturnZero(true);12645 else {12646 // Otherwise, this is just a flat-out error.12647 SourceRange RTRange = FD->getReturnTypeSourceRange();12648 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)12649 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")12650 : FixItHint());12651 FD->setInvalidDecl(true);12652 }12653 12654 // [basic.start.main]p3:12655 // A program that declares a function main that belongs to the global scope12656 // and is attached to a named module is ill-formed.12657 if (FD->isInNamedModule()) {12658 const SourceLocation start = FD->getTypeSpecStartLoc();12659 Diag(start, diag::warn_main_in_named_module)12660 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);12661 }12662 }12663 12664 // Treat protoless main() as nullary.12665 if (isa<FunctionNoProtoType>(FT)) return;12666 12667 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);12668 unsigned nparams = FTP->getNumParams();12669 assert(FD->getNumParams() == nparams);12670 12671 bool HasExtraParameters = (nparams > 3);12672 12673 if (FTP->isVariadic()) {12674 Diag(FD->getLocation(), diag::ext_variadic_main);12675 // FIXME: if we had information about the location of the ellipsis, we12676 // could add a FixIt hint to remove it as a parameter.12677 }12678 12679 // Darwin passes an undocumented fourth argument of type char**. If12680 // other platforms start sprouting these, the logic below will start12681 // getting shifty.12682 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())12683 HasExtraParameters = false;12684 12685 if (HasExtraParameters) {12686 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;12687 FD->setInvalidDecl(true);12688 nparams = 3;12689 }12690 12691 // FIXME: a lot of the following diagnostics would be improved12692 // if we had some location information about types.12693 12694 QualType CharPP =12695 Context.getPointerType(Context.getPointerType(Context.CharTy));12696 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };12697 12698 for (unsigned i = 0; i < nparams; ++i) {12699 QualType AT = FTP->getParamType(i);12700 12701 bool mismatch = true;12702 12703 if (Context.hasSameUnqualifiedType(AT, Expected[i]))12704 mismatch = false;12705 else if (Expected[i] == CharPP) {12706 // As an extension, the following forms are okay:12707 // char const **12708 // char const * const *12709 // char * const *12710 12711 QualifierCollector qs;12712 const PointerType* PT;12713 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&12714 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&12715 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),12716 Context.CharTy)) {12717 qs.removeConst();12718 mismatch = !qs.empty();12719 }12720 }12721 12722 if (mismatch) {12723 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];12724 // TODO: suggest replacing given type with expected type12725 FD->setInvalidDecl(true);12726 }12727 }12728 12729 if (nparams == 1 && !FD->isInvalidDecl()) {12730 Diag(FD->getLocation(), diag::warn_main_one_arg);12731 }12732 12733 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {12734 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;12735 FD->setInvalidDecl();12736 }12737}12738 12739static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {12740 12741 // Default calling convention for main and wmain is __cdecl12742 if (FD->getName() == "main" || FD->getName() == "wmain")12743 return false;12744 12745 // Default calling convention for MinGW and Cygwin is __cdecl12746 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();12747 if (T.isOSCygMing())12748 return false;12749 12750 // Default calling convention for WinMain, wWinMain and DllMain12751 // is __stdcall on 32 bit Windows12752 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)12753 return true;12754 12755 return false;12756}12757 12758void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {12759 QualType T = FD->getType();12760 assert(T->isFunctionType() && "function decl is not of function type");12761 const FunctionType *FT = T->castAs<FunctionType>();12762 12763 // Set an implicit return of 'zero' if the function can return some integral,12764 // enumeration, pointer or nullptr type.12765 if (FT->getReturnType()->isIntegralOrEnumerationType() ||12766 FT->getReturnType()->isAnyPointerType() ||12767 FT->getReturnType()->isNullPtrType())12768 // DllMain is exempt because a return value of zero means it failed.12769 if (FD->getName() != "DllMain")12770 FD->setHasImplicitReturnZero(true);12771 12772 // Explicitly specified calling conventions are applied to MSVC entry points12773 if (!hasExplicitCallingConv(T)) {12774 if (isDefaultStdCall(FD, *this)) {12775 if (FT->getCallConv() != CC_X86StdCall) {12776 FT = Context.adjustFunctionType(12777 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));12778 FD->setType(QualType(FT, 0));12779 }12780 } else if (FT->getCallConv() != CC_C) {12781 FT = Context.adjustFunctionType(FT,12782 FT->getExtInfo().withCallingConv(CC_C));12783 FD->setType(QualType(FT, 0));12784 }12785 }12786 12787 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {12788 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;12789 FD->setInvalidDecl();12790 }12791}12792 12793bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {12794 // FIXME: Need strict checking. In C89, we need to check for12795 // any assignment, increment, decrement, function-calls, or12796 // commas outside of a sizeof. In C99, it's the same list,12797 // except that the aforementioned are allowed in unevaluated12798 // expressions. Everything else falls under the12799 // "may accept other forms of constant expressions" exception.12800 //12801 // Regular C++ code will not end up here (exceptions: language extensions,12802 // OpenCL C++ etc), so the constant expression rules there don't matter.12803 if (Init->isValueDependent()) {12804 assert(Init->containsErrors() &&12805 "Dependent code should only occur in error-recovery path.");12806 return true;12807 }12808 const Expr *Culprit;12809 if (Init->isConstantInitializer(Context, false, &Culprit))12810 return false;12811 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();12812 return true;12813}12814 12815namespace {12816 // Visits an initialization expression to see if OrigDecl is evaluated in12817 // its own initialization and throws a warning if it does.12818 class SelfReferenceChecker12819 : public EvaluatedExprVisitor<SelfReferenceChecker> {12820 Sema &S;12821 Decl *OrigDecl;12822 bool isRecordType;12823 bool isPODType;12824 bool isReferenceType;12825 bool isInCXXOperatorCall;12826 12827 bool isInitList;12828 llvm::SmallVector<unsigned, 4> InitFieldIndex;12829 12830 public:12831 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;12832 12833 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),12834 S(S), OrigDecl(OrigDecl) {12835 isPODType = false;12836 isRecordType = false;12837 isReferenceType = false;12838 isInCXXOperatorCall = false;12839 isInitList = false;12840 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {12841 isPODType = VD->getType().isPODType(S.Context);12842 isRecordType = VD->getType()->isRecordType();12843 isReferenceType = VD->getType()->isReferenceType();12844 }12845 }12846 12847 // For most expressions, just call the visitor. For initializer lists,12848 // track the index of the field being initialized since fields are12849 // initialized in order allowing use of previously initialized fields.12850 void CheckExpr(Expr *E) {12851 InitListExpr *InitList = dyn_cast<InitListExpr>(E);12852 if (!InitList) {12853 Visit(E);12854 return;12855 }12856 12857 // Track and increment the index here.12858 isInitList = true;12859 InitFieldIndex.push_back(0);12860 for (auto *Child : InitList->children()) {12861 CheckExpr(cast<Expr>(Child));12862 ++InitFieldIndex.back();12863 }12864 InitFieldIndex.pop_back();12865 }12866 12867 // Returns true if MemberExpr is checked and no further checking is needed.12868 // Returns false if additional checking is required.12869 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {12870 llvm::SmallVector<FieldDecl*, 4> Fields;12871 Expr *Base = E;12872 bool ReferenceField = false;12873 12874 // Get the field members used.12875 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {12876 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());12877 if (!FD)12878 return false;12879 Fields.push_back(FD);12880 if (FD->getType()->isReferenceType())12881 ReferenceField = true;12882 Base = ME->getBase()->IgnoreParenImpCasts();12883 }12884 12885 // Keep checking only if the base Decl is the same.12886 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);12887 if (!DRE || DRE->getDecl() != OrigDecl)12888 return false;12889 12890 // A reference field can be bound to an unininitialized field.12891 if (CheckReference && !ReferenceField)12892 return true;12893 12894 // Convert FieldDecls to their index number.12895 llvm::SmallVector<unsigned, 4> UsedFieldIndex;12896 for (const FieldDecl *I : llvm::reverse(Fields))12897 UsedFieldIndex.push_back(I->getFieldIndex());12898 12899 // See if a warning is needed by checking the first difference in index12900 // numbers. If field being used has index less than the field being12901 // initialized, then the use is safe.12902 for (auto UsedIter = UsedFieldIndex.begin(),12903 UsedEnd = UsedFieldIndex.end(),12904 OrigIter = InitFieldIndex.begin(),12905 OrigEnd = InitFieldIndex.end();12906 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {12907 if (*UsedIter < *OrigIter)12908 return true;12909 if (*UsedIter > *OrigIter)12910 break;12911 }12912 12913 // TODO: Add a different warning which will print the field names.12914 HandleDeclRefExpr(DRE);12915 return true;12916 }12917 12918 // For most expressions, the cast is directly above the DeclRefExpr.12919 // For conditional operators, the cast can be outside the conditional12920 // operator if both expressions are DeclRefExpr's.12921 void HandleValue(Expr *E) {12922 E = E->IgnoreParens();12923 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {12924 HandleDeclRefExpr(DRE);12925 return;12926 }12927 12928 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {12929 Visit(CO->getCond());12930 HandleValue(CO->getTrueExpr());12931 HandleValue(CO->getFalseExpr());12932 return;12933 }12934 12935 if (BinaryConditionalOperator *BCO =12936 dyn_cast<BinaryConditionalOperator>(E)) {12937 Visit(BCO->getCond());12938 HandleValue(BCO->getFalseExpr());12939 return;12940 }12941 12942 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {12943 if (Expr *SE = OVE->getSourceExpr())12944 HandleValue(SE);12945 return;12946 }12947 12948 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {12949 if (BO->getOpcode() == BO_Comma) {12950 Visit(BO->getLHS());12951 HandleValue(BO->getRHS());12952 return;12953 }12954 }12955 12956 if (isa<MemberExpr>(E)) {12957 if (isInitList) {12958 if (CheckInitListMemberExpr(cast<MemberExpr>(E),12959 false /*CheckReference*/))12960 return;12961 }12962 12963 Expr *Base = E->IgnoreParenImpCasts();12964 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {12965 // Check for static member variables and don't warn on them.12966 if (!isa<FieldDecl>(ME->getMemberDecl()))12967 return;12968 Base = ME->getBase()->IgnoreParenImpCasts();12969 }12970 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))12971 HandleDeclRefExpr(DRE);12972 return;12973 }12974 12975 Visit(E);12976 }12977 12978 // Reference types not handled in HandleValue are handled here since all12979 // uses of references are bad, not just r-value uses.12980 void VisitDeclRefExpr(DeclRefExpr *E) {12981 if (isReferenceType)12982 HandleDeclRefExpr(E);12983 }12984 12985 void VisitImplicitCastExpr(ImplicitCastExpr *E) {12986 if (E->getCastKind() == CK_LValueToRValue) {12987 HandleValue(E->getSubExpr());12988 return;12989 }12990 12991 Inherited::VisitImplicitCastExpr(E);12992 }12993 12994 void VisitMemberExpr(MemberExpr *E) {12995 if (isInitList) {12996 if (CheckInitListMemberExpr(E, true /*CheckReference*/))12997 return;12998 }12999 13000 // Don't warn on arrays since they can be treated as pointers.13001 if (E->getType()->canDecayToPointerType()) return;13002 13003 // Warn when a non-static method call is followed by non-static member13004 // field accesses, which is followed by a DeclRefExpr.13005 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());13006 bool Warn = (MD && !MD->isStatic());13007 Expr *Base = E->getBase()->IgnoreParenImpCasts();13008 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {13009 if (!isa<FieldDecl>(ME->getMemberDecl()))13010 Warn = false;13011 Base = ME->getBase()->IgnoreParenImpCasts();13012 }13013 13014 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {13015 if (Warn)13016 HandleDeclRefExpr(DRE);13017 return;13018 }13019 13020 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.13021 // Visit that expression.13022 Visit(Base);13023 }13024 13025 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {13026 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);13027 Expr *Callee = E->getCallee();13028 13029 if (isa<UnresolvedLookupExpr>(Callee))13030 return Inherited::VisitCXXOperatorCallExpr(E);13031 13032 Visit(Callee);13033 for (auto Arg: E->arguments())13034 HandleValue(Arg->IgnoreParenImpCasts());13035 }13036 13037 void VisitLambdaExpr(LambdaExpr *E) {13038 if (!isInCXXOperatorCall) {13039 Inherited::VisitLambdaExpr(E);13040 return;13041 }13042 13043 for (Expr *Init : E->capture_inits())13044 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))13045 HandleDeclRefExpr(DRE);13046 else if (Init)13047 Visit(Init);13048 }13049 13050 void VisitUnaryOperator(UnaryOperator *E) {13051 // For POD record types, addresses of its own members are well-defined.13052 if (E->getOpcode() == UO_AddrOf && isRecordType &&13053 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {13054 if (!isPODType)13055 HandleValue(E->getSubExpr());13056 return;13057 }13058 13059 if (E->isIncrementDecrementOp()) {13060 HandleValue(E->getSubExpr());13061 return;13062 }13063 13064 Inherited::VisitUnaryOperator(E);13065 }13066 13067 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}13068 13069 void VisitCXXConstructExpr(CXXConstructExpr *E) {13070 if (E->getConstructor()->isCopyConstructor()) {13071 Expr *ArgExpr = E->getArg(0);13072 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))13073 if (ILE->getNumInits() == 1)13074 ArgExpr = ILE->getInit(0);13075 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))13076 if (ICE->getCastKind() == CK_NoOp)13077 ArgExpr = ICE->getSubExpr();13078 HandleValue(ArgExpr);13079 return;13080 }13081 Inherited::VisitCXXConstructExpr(E);13082 }13083 13084 void VisitCallExpr(CallExpr *E) {13085 // Treat std::move as a use.13086 if (E->isCallToStdMove()) {13087 HandleValue(E->getArg(0));13088 return;13089 }13090 13091 Inherited::VisitCallExpr(E);13092 }13093 13094 void VisitBinaryOperator(BinaryOperator *E) {13095 if (E->isCompoundAssignmentOp()) {13096 HandleValue(E->getLHS());13097 Visit(E->getRHS());13098 return;13099 }13100 13101 Inherited::VisitBinaryOperator(E);13102 }13103 13104 // A custom visitor for BinaryConditionalOperator is needed because the13105 // regular visitor would check the condition and true expression separately13106 // but both point to the same place giving duplicate diagnostics.13107 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {13108 Visit(E->getCond());13109 Visit(E->getFalseExpr());13110 }13111 13112 void HandleDeclRefExpr(DeclRefExpr *DRE) {13113 Decl* ReferenceDecl = DRE->getDecl();13114 if (OrigDecl != ReferenceDecl) return;13115 unsigned diag;13116 if (isReferenceType) {13117 diag = diag::warn_uninit_self_reference_in_reference_init;13118 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {13119 diag = diag::warn_static_self_reference_in_init;13120 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||13121 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||13122 DRE->getDecl()->getType()->isRecordType()) {13123 diag = diag::warn_uninit_self_reference_in_init;13124 } else {13125 // Local variables will be handled by the CFG analysis.13126 return;13127 }13128 13129 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,13130 S.PDiag(diag)13131 << DRE->getDecl() << OrigDecl->getLocation()13132 << DRE->getSourceRange());13133 }13134 };13135 13136 /// CheckSelfReference - Warns if OrigDecl is used in expression E.13137 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,13138 bool DirectInit) {13139 // Parameters arguments are occassionially constructed with itself,13140 // for instance, in recursive functions. Skip them.13141 if (isa<ParmVarDecl>(OrigDecl))13142 return;13143 13144 // Skip checking for file-scope constexpr variables - constant evaluation13145 // will produce appropriate errors without needing runtime diagnostics.13146 // Local constexpr should still emit runtime warnings.13147 if (auto *VD = dyn_cast<VarDecl>(OrigDecl);13148 VD && VD->isConstexpr() && VD->isFileVarDecl())13149 return;13150 13151 E = E->IgnoreParens();13152 13153 // Skip checking T a = a where T is not a record or reference type.13154 // Doing so is a way to silence uninitialized warnings.13155 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())13156 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))13157 if (ICE->getCastKind() == CK_LValueToRValue)13158 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))13159 if (DRE->getDecl() == OrigDecl)13160 return;13161 13162 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);13163 }13164} // end anonymous namespace13165 13166namespace {13167 // Simple wrapper to add the name of a variable or (if no variable is13168 // available) a DeclarationName into a diagnostic.13169 struct VarDeclOrName {13170 VarDecl *VDecl;13171 DeclarationName Name;13172 13173 friend const Sema::SemaDiagnosticBuilder &13174 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {13175 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;13176 }13177 };13178} // end anonymous namespace13179 13180QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,13181 DeclarationName Name, QualType Type,13182 TypeSourceInfo *TSI,13183 SourceRange Range, bool DirectInit,13184 Expr *Init) {13185 bool IsInitCapture = !VDecl;13186 assert((!VDecl || !VDecl->isInitCapture()) &&13187 "init captures are expected to be deduced prior to initialization");13188 13189 VarDeclOrName VN{VDecl, Name};13190 13191 DeducedType *Deduced = Type->getContainedDeducedType();13192 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");13193 13194 // Diagnose auto array declarations in C23, unless it's a supported extension.13195 if (getLangOpts().C23 && Type->isArrayType() &&13196 !isa_and_present<StringLiteral, InitListExpr>(Init)) {13197 Diag(Range.getBegin(), diag::err_auto_not_allowed)13198 << (int)Deduced->getContainedAutoType()->getKeyword()13199 << /*in array decl*/ 23 << Range;13200 return QualType();13201 }13202 13203 // C++11 [dcl.spec.auto]p313204 if (!Init) {13205 assert(VDecl && "no init for init capture deduction?");13206 13207 // Except for class argument deduction, and then for an initializing13208 // declaration only, i.e. no static at class scope or extern.13209 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||13210 VDecl->hasExternalStorage() ||13211 VDecl->isStaticDataMember()) {13212 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)13213 << VDecl->getDeclName() << Type;13214 return QualType();13215 }13216 }13217 13218 ArrayRef<Expr*> DeduceInits;13219 if (Init)13220 DeduceInits = Init;13221 13222 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);13223 if (DirectInit && PL)13224 DeduceInits = PL->exprs();13225 13226 if (isa<DeducedTemplateSpecializationType>(Deduced)) {13227 assert(VDecl && "non-auto type for init capture deduction?");13228 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);13229 InitializationKind Kind = InitializationKind::CreateForInit(13230 VDecl->getLocation(), DirectInit, Init);13231 // FIXME: Initialization should not be taking a mutable list of inits.13232 SmallVector<Expr *, 8> InitsCopy(DeduceInits);13233 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,13234 InitsCopy);13235 }13236 13237 if (DirectInit) {13238 if (auto *IL = dyn_cast<InitListExpr>(Init))13239 DeduceInits = IL->inits();13240 }13241 13242 // Deduction only works if we have exactly one source expression.13243 if (DeduceInits.empty()) {13244 // It isn't possible to write this directly, but it is possible to13245 // end up in this situation with "auto x(some_pack...);"13246 Diag(Init->getBeginLoc(), IsInitCapture13247 ? diag::err_init_capture_no_expression13248 : diag::err_auto_var_init_no_expression)13249 << VN << Type << Range;13250 return QualType();13251 }13252 13253 if (DeduceInits.size() > 1) {13254 Diag(DeduceInits[1]->getBeginLoc(),13255 IsInitCapture ? diag::err_init_capture_multiple_expressions13256 : diag::err_auto_var_init_multiple_expressions)13257 << VN << Type << Range;13258 return QualType();13259 }13260 13261 Expr *DeduceInit = DeduceInits[0];13262 if (DirectInit && isa<InitListExpr>(DeduceInit)) {13263 Diag(Init->getBeginLoc(), IsInitCapture13264 ? diag::err_init_capture_paren_braces13265 : diag::err_auto_var_init_paren_braces)13266 << isa<InitListExpr>(Init) << VN << Type << Range;13267 return QualType();13268 }13269 13270 // Expressions default to 'id' when we're in a debugger.13271 bool DefaultedAnyToId = false;13272 if (getLangOpts().DebuggerCastResultToId &&13273 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {13274 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());13275 if (Result.isInvalid()) {13276 return QualType();13277 }13278 Init = Result.get();13279 DefaultedAnyToId = true;13280 }13281 13282 // C++ [dcl.decomp]p1:13283 // If the assignment-expression [...] has array type A and no ref-qualifier13284 // is present, e has type cv A13285 if (VDecl && isa<DecompositionDecl>(VDecl) &&13286 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&13287 DeduceInit->getType()->isConstantArrayType())13288 return Context.getQualifiedType(DeduceInit->getType(),13289 Type.getQualifiers());13290 13291 QualType DeducedType;13292 TemplateDeductionInfo Info(DeduceInit->getExprLoc());13293 TemplateDeductionResult Result =13294 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);13295 if (Result != TemplateDeductionResult::Success &&13296 Result != TemplateDeductionResult::AlreadyDiagnosed) {13297 if (!IsInitCapture)13298 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);13299 else if (isa<InitListExpr>(Init))13300 Diag(Range.getBegin(),13301 diag::err_init_capture_deduction_failure_from_init_list)13302 << VN13303 << (DeduceInit->getType().isNull() ? TSI->getType()13304 : DeduceInit->getType())13305 << DeduceInit->getSourceRange();13306 else13307 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)13308 << VN << TSI->getType()13309 << (DeduceInit->getType().isNull() ? TSI->getType()13310 : DeduceInit->getType())13311 << DeduceInit->getSourceRange();13312 }13313 13314 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using13315 // 'id' instead of a specific object type prevents most of our usual13316 // checks.13317 // We only want to warn outside of template instantiations, though:13318 // inside a template, the 'id' could have come from a parameter.13319 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&13320 !DeducedType.isNull() && DeducedType->isObjCIdType()) {13321 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();13322 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;13323 }13324 13325 return DeducedType;13326}13327 13328bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,13329 Expr *Init) {13330 assert(!Init || !Init->containsErrors());13331 QualType DeducedType = deduceVarTypeFromInitializer(13332 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),13333 VDecl->getSourceRange(), DirectInit, Init);13334 if (DeducedType.isNull()) {13335 VDecl->setInvalidDecl();13336 return true;13337 }13338 13339 VDecl->setType(DeducedType);13340 assert(VDecl->isLinkageValid());13341 13342 // In ARC, infer lifetime.13343 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))13344 VDecl->setInvalidDecl();13345 13346 if (getLangOpts().OpenCL)13347 deduceOpenCLAddressSpace(VDecl);13348 13349 if (getLangOpts().HLSL)13350 HLSL().deduceAddressSpace(VDecl);13351 13352 // If this is a redeclaration, check that the type we just deduced matches13353 // the previously declared type.13354 if (VarDecl *Old = VDecl->getPreviousDecl()) {13355 // We never need to merge the type, because we cannot form an incomplete13356 // array of auto, nor deduce such a type.13357 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);13358 }13359 13360 // Check the deduced type is valid for a variable declaration.13361 CheckVariableDeclarationType(VDecl);13362 return VDecl->isInvalidDecl();13363}13364 13365void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,13366 SourceLocation Loc) {13367 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))13368 Init = EWC->getSubExpr();13369 13370 if (auto *CE = dyn_cast<ConstantExpr>(Init))13371 Init = CE->getSubExpr();13372 13373 QualType InitType = Init->getType();13374 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||13375 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&13376 "shouldn't be called if type doesn't have a non-trivial C struct");13377 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {13378 for (auto *I : ILE->inits()) {13379 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&13380 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())13381 continue;13382 SourceLocation SL = I->getExprLoc();13383 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);13384 }13385 return;13386 }13387 13388 if (isa<ImplicitValueInitExpr>(Init)) {13389 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())13390 checkNonTrivialCUnion(InitType, Loc,13391 NonTrivialCUnionContext::DefaultInitializedObject,13392 NTCUK_Init);13393 } else {13394 // Assume all other explicit initializers involving copying some existing13395 // object.13396 // TODO: ignore any explicit initializers where we can guarantee13397 // copy-elision.13398 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())13399 checkNonTrivialCUnion(InitType, Loc, NonTrivialCUnionContext::CopyInit,13400 NTCUK_Copy);13401 }13402}13403 13404namespace {13405 13406bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {13407 // Ignore unavailable fields. A field can be marked as unavailable explicitly13408 // in the source code or implicitly by the compiler if it is in a union13409 // defined in a system header and has non-trivial ObjC ownership13410 // qualifications. We don't want those fields to participate in determining13411 // whether the containing union is non-trivial.13412 return FD->hasAttr<UnavailableAttr>();13413}13414 13415struct DiagNonTrivalCUnionDefaultInitializeVisitor13416 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,13417 void> {13418 using Super =13419 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,13420 void>;13421 13422 DiagNonTrivalCUnionDefaultInitializeVisitor(13423 QualType OrigTy, SourceLocation OrigLoc,13424 NonTrivialCUnionContext UseContext, Sema &S)13425 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}13426 13427 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,13428 const FieldDecl *FD, bool InNonTrivialUnion) {13429 if (const auto *AT = S.Context.getAsArrayType(QT))13430 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,13431 InNonTrivialUnion);13432 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);13433 }13434 13435 void visitARCStrong(QualType QT, const FieldDecl *FD,13436 bool InNonTrivialUnion) {13437 if (InNonTrivialUnion)13438 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)13439 << 1 << 0 << QT << FD->getName();13440 }13441 13442 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {13443 if (InNonTrivialUnion)13444 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)13445 << 1 << 0 << QT << FD->getName();13446 }13447 13448 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {13449 const auto *RD = QT->castAsRecordDecl();13450 if (RD->isUnion()) {13451 if (OrigLoc.isValid()) {13452 bool IsUnion = false;13453 if (auto *OrigRD = OrigTy->getAsRecordDecl())13454 IsUnion = OrigRD->isUnion();13455 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)13456 << 0 << OrigTy << IsUnion << UseContext;13457 // Reset OrigLoc so that this diagnostic is emitted only once.13458 OrigLoc = SourceLocation();13459 }13460 InNonTrivialUnion = true;13461 }13462 13463 if (InNonTrivialUnion)13464 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)13465 << 0 << 0 << QT.getUnqualifiedType() << "";13466 13467 for (const FieldDecl *FD : RD->fields())13468 if (!shouldIgnoreForRecordTriviality(FD))13469 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);13470 }13471 13472 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}13473 13474 // The non-trivial C union type or the struct/union type that contains a13475 // non-trivial C union.13476 QualType OrigTy;13477 SourceLocation OrigLoc;13478 NonTrivialCUnionContext UseContext;13479 Sema &S;13480};13481 13482struct DiagNonTrivalCUnionDestructedTypeVisitor13483 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {13484 using Super =13485 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;13486 13487 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,13488 SourceLocation OrigLoc,13489 NonTrivialCUnionContext UseContext,13490 Sema &S)13491 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}13492 13493 void visitWithKind(QualType::DestructionKind DK, QualType QT,13494 const FieldDecl *FD, bool InNonTrivialUnion) {13495 if (const auto *AT = S.Context.getAsArrayType(QT))13496 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,13497 InNonTrivialUnion);13498 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);13499 }13500 13501 void visitARCStrong(QualType QT, const FieldDecl *FD,13502 bool InNonTrivialUnion) {13503 if (InNonTrivialUnion)13504 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)13505 << 1 << 1 << QT << FD->getName();13506 }13507 13508 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {13509 if (InNonTrivialUnion)13510 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)13511 << 1 << 1 << QT << FD->getName();13512 }13513 13514 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {13515 const auto *RD = QT->castAsRecordDecl();13516 if (RD->isUnion()) {13517 if (OrigLoc.isValid()) {13518 bool IsUnion = false;13519 if (auto *OrigRD = OrigTy->getAsRecordDecl())13520 IsUnion = OrigRD->isUnion();13521 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)13522 << 1 << OrigTy << IsUnion << UseContext;13523 // Reset OrigLoc so that this diagnostic is emitted only once.13524 OrigLoc = SourceLocation();13525 }13526 InNonTrivialUnion = true;13527 }13528 13529 if (InNonTrivialUnion)13530 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)13531 << 0 << 1 << QT.getUnqualifiedType() << "";13532 13533 for (const FieldDecl *FD : RD->fields())13534 if (!shouldIgnoreForRecordTriviality(FD))13535 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);13536 }13537 13538 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}13539 void visitCXXDestructor(QualType QT, const FieldDecl *FD,13540 bool InNonTrivialUnion) {}13541 13542 // The non-trivial C union type or the struct/union type that contains a13543 // non-trivial C union.13544 QualType OrigTy;13545 SourceLocation OrigLoc;13546 NonTrivialCUnionContext UseContext;13547 Sema &S;13548};13549 13550struct DiagNonTrivalCUnionCopyVisitor13551 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {13552 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;13553 13554 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,13555 NonTrivialCUnionContext UseContext, Sema &S)13556 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}13557 13558 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,13559 const FieldDecl *FD, bool InNonTrivialUnion) {13560 if (const auto *AT = S.Context.getAsArrayType(QT))13561 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,13562 InNonTrivialUnion);13563 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);13564 }13565 13566 void visitARCStrong(QualType QT, const FieldDecl *FD,13567 bool InNonTrivialUnion) {13568 if (InNonTrivialUnion)13569 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)13570 << 1 << 2 << QT << FD->getName();13571 }13572 13573 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {13574 if (InNonTrivialUnion)13575 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)13576 << 1 << 2 << QT << FD->getName();13577 }13578 13579 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {13580 const auto *RD = QT->castAsRecordDecl();13581 if (RD->isUnion()) {13582 if (OrigLoc.isValid()) {13583 bool IsUnion = false;13584 if (auto *OrigRD = OrigTy->getAsRecordDecl())13585 IsUnion = OrigRD->isUnion();13586 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)13587 << 2 << OrigTy << IsUnion << UseContext;13588 // Reset OrigLoc so that this diagnostic is emitted only once.13589 OrigLoc = SourceLocation();13590 }13591 InNonTrivialUnion = true;13592 }13593 13594 if (InNonTrivialUnion)13595 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)13596 << 0 << 2 << QT.getUnqualifiedType() << "";13597 13598 for (const FieldDecl *FD : RD->fields())13599 if (!shouldIgnoreForRecordTriviality(FD))13600 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);13601 }13602 13603 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {13604 if (InNonTrivialUnion)13605 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)13606 << 1 << 2 << QT << FD->getName();13607 }13608 13609 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,13610 const FieldDecl *FD, bool InNonTrivialUnion) {}13611 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}13612 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,13613 bool InNonTrivialUnion) {}13614 13615 // The non-trivial C union type or the struct/union type that contains a13616 // non-trivial C union.13617 QualType OrigTy;13618 SourceLocation OrigLoc;13619 NonTrivialCUnionContext UseContext;13620 Sema &S;13621};13622 13623} // namespace13624 13625void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,13626 NonTrivialCUnionContext UseContext,13627 unsigned NonTrivialKind) {13628 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||13629 QT.hasNonTrivialToPrimitiveDestructCUnion() ||13630 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&13631 "shouldn't be called if type doesn't have a non-trivial C union");13632 13633 if ((NonTrivialKind & NTCUK_Init) &&13634 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())13635 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)13636 .visit(QT, nullptr, false);13637 if ((NonTrivialKind & NTCUK_Destruct) &&13638 QT.hasNonTrivialToPrimitiveDestructCUnion())13639 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)13640 .visit(QT, nullptr, false);13641 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())13642 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)13643 .visit(QT, nullptr, false);13644}13645 13646bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(13647 const VarDecl *Dcl) {13648 if (!getLangOpts().CPlusPlus)13649 return false;13650 13651 // We only need to warn if the definition is in a header file, so wait to13652 // diagnose until we've seen the definition.13653 if (!Dcl->isThisDeclarationADefinition())13654 return false;13655 13656 // If an object is defined in a source file, its definition can't get13657 // duplicated since it will never appear in more than one TU.13658 if (Dcl->getASTContext().getSourceManager().isInMainFile(Dcl->getLocation()))13659 return false;13660 13661 // If the variable we're looking at is a static local, then we actually care13662 // about the properties of the function containing it.13663 const ValueDecl *Target = Dcl;13664 // VarDecls and FunctionDecls have different functions for checking13665 // inline-ness, and whether they were originally templated, so we have to13666 // call the appropriate functions manually.13667 bool TargetIsInline = Dcl->isInline();13668 bool TargetWasTemplated =13669 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;13670 13671 // Update the Target and TargetIsInline property if necessary13672 if (Dcl->isStaticLocal()) {13673 const DeclContext *Ctx = Dcl->getDeclContext();13674 if (!Ctx)13675 return false;13676 13677 const FunctionDecl *FunDcl =13678 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());13679 if (!FunDcl)13680 return false;13681 13682 Target = FunDcl;13683 // IsInlined() checks for the C++ inline property13684 TargetIsInline = FunDcl->isInlined();13685 TargetWasTemplated =13686 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;13687 }13688 13689 // Non-inline functions/variables can only legally appear in one TU13690 // unless they were part of a template. Unfortunately, making complex13691 // template instantiations visible is infeasible in practice, since13692 // everything the template depends on also has to be visible. To avoid13693 // giving impractical-to-fix warnings, don't warn if we're inside13694 // something that was templated, even on inline stuff.13695 if (!TargetIsInline || TargetWasTemplated)13696 return false;13697 13698 // If the object isn't hidden, the dynamic linker will prevent duplication.13699 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();13700 13701 // The target is "hidden" (from the dynamic linker) if:13702 // 1. On posix, it has hidden visibility, or13703 // 2. On windows, it has no import/export annotation, and neither does the13704 // class which directly contains it.13705 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {13706 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())13707 return false;13708 13709 // If the variable isn't directly annotated, check to see if it's a member13710 // of an annotated class.13711 const CXXRecordDecl *Ctx =13712 dyn_cast<CXXRecordDecl>(Target->getDeclContext());13713 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))13714 return false;13715 13716 } else if (Lnk.getVisibility() != HiddenVisibility) {13717 // Posix case13718 return false;13719 }13720 13721 // If the obj doesn't have external linkage, it's supposed to be duplicated.13722 if (!isExternalFormalLinkage(Lnk.getLinkage()))13723 return false;13724 13725 return true;13726}13727 13728// Determine whether the object seems mutable for the purpose of diagnosing13729// possible unique object duplication, i.e. non-const-qualified, and13730// not an always-constant type like a function.13731// Not perfect: doesn't account for mutable members, for example, or13732// elements of container types.13733// For nested pointers, any individual level being non-const is sufficient.13734static bool looksMutable(QualType T, const ASTContext &Ctx) {13735 T = T.getNonReferenceType();13736 if (T->isFunctionType())13737 return false;13738 if (!T.isConstant(Ctx))13739 return true;13740 if (T->isPointerType())13741 return looksMutable(T->getPointeeType(), Ctx);13742 return false;13743}13744 13745void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {13746 // If this object has external linkage and hidden visibility, it might be13747 // duplicated when built into a shared library, which causes problems if it's13748 // mutable (since the copies won't be in sync) or its initialization has side13749 // effects (since it will run once per copy instead of once globally).13750 13751 // Don't diagnose if we're inside a template, because it's not practical to13752 // fix the warning in most cases.13753 if (!VD->isTemplated() &&13754 GloballyUniqueObjectMightBeAccidentallyDuplicated(VD)) {13755 13756 QualType Type = VD->getType();13757 if (looksMutable(Type, VD->getASTContext())) {13758 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)13759 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();13760 }13761 13762 // To keep false positives low, only warn if we're certain that the13763 // initializer has side effects. Don't warn on operator new, since a mutable13764 // pointer will trigger the previous warning, and an immutable pointer13765 // getting duplicated just results in a little extra memory usage.13766 const Expr *Init = VD->getAnyInitializer();13767 if (Init &&13768 Init->HasSideEffects(VD->getASTContext(),13769 /*IncludePossibleEffects=*/false) &&13770 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {13771 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)13772 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();13773 }13774 }13775}13776 13777void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {13778 auto ResetDeclForInitializer = llvm::make_scope_exit([this]() {13779 if (this->ExprEvalContexts.empty())13780 this->ExprEvalContexts.back().DeclForInitializer = nullptr;13781 });13782 13783 // If there is no declaration, there was an error parsing it. Just ignore13784 // the initializer.13785 if (!RealDecl) {13786 return;13787 }13788 13789 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {13790 if (!Method->isInvalidDecl()) {13791 // Pure-specifiers are handled in ActOnPureSpecifier.13792 Diag(Method->getLocation(), diag::err_member_function_initialization)13793 << Method->getDeclName() << Init->getSourceRange();13794 Method->setInvalidDecl();13795 }13796 return;13797 }13798 13799 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);13800 if (!VDecl) {13801 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");13802 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);13803 RealDecl->setInvalidDecl();13804 return;13805 }13806 13807 if (VDecl->isInvalidDecl()) {13808 ExprResult Recovery =13809 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});13810 if (Expr *E = Recovery.get())13811 VDecl->setInit(E);13812 return;13813 }13814 13815 // WebAssembly tables can't be used to initialise a variable.13816 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {13817 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;13818 VDecl->setInvalidDecl();13819 return;13820 }13821 13822 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.13823 if (VDecl->getType()->isUndeducedType()) {13824 if (Init->containsErrors()) {13825 // Invalidate the decl as we don't know the type for recovery-expr yet.13826 RealDecl->setInvalidDecl();13827 VDecl->setInit(Init);13828 return;13829 }13830 13831 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))13832 return;13833 }13834 13835 this->CheckAttributesOnDeducedType(RealDecl);13836 13837 // dllimport cannot be used on variable definitions.13838 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {13839 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);13840 VDecl->setInvalidDecl();13841 return;13842 }13843 13844 // C99 6.7.8p5. If the declaration of an identifier has block scope, and13845 // the identifier has external or internal linkage, the declaration shall13846 // have no initializer for the identifier.13847 // C++14 [dcl.init]p5 is the same restriction for C++.13848 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {13849 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);13850 VDecl->setInvalidDecl();13851 return;13852 }13853 13854 if (!VDecl->getType()->isDependentType()) {13855 // A definition must end up with a complete type, which means it must be13856 // complete with the restriction that an array type might be completed by13857 // the initializer; note that later code assumes this restriction.13858 QualType BaseDeclType = VDecl->getType();13859 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))13860 BaseDeclType = Array->getElementType();13861 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,13862 diag::err_typecheck_decl_incomplete_type)) {13863 RealDecl->setInvalidDecl();13864 return;13865 }13866 13867 // The variable can not have an abstract class type.13868 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),13869 diag::err_abstract_type_in_decl,13870 AbstractVariableType))13871 VDecl->setInvalidDecl();13872 }13873 13874 // C++ [module.import/6]13875 // ...13876 // A header unit shall not contain a definition of a non-inline function or13877 // variable whose name has external linkage.13878 //13879 // We choose to allow weak & selectany definitions, as they are common in13880 // headers, and have semantics similar to inline definitions which are allowed13881 // in header units.13882 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&13883 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&13884 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&13885 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&13886 !VDecl->getInstantiatedFromStaticDataMember() &&13887 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {13888 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);13889 VDecl->setInvalidDecl();13890 }13891 13892 // If adding the initializer will turn this declaration into a definition,13893 // and we already have a definition for this variable, diagnose or otherwise13894 // handle the situation.13895 if (VarDecl *Def = VDecl->getDefinition())13896 if (Def != VDecl &&13897 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&13898 !VDecl->isThisDeclarationADemotedDefinition() &&13899 checkVarDeclRedefinition(Def, VDecl))13900 return;13901 13902 if (getLangOpts().CPlusPlus) {13903 // C++ [class.static.data]p413904 // If a static data member is of const integral or const13905 // enumeration type, its declaration in the class definition can13906 // specify a constant-initializer which shall be an integral13907 // constant expression (5.19). In that case, the member can appear13908 // in integral constant expressions. The member shall still be13909 // defined in a namespace scope if it is used in the program and the13910 // namespace scope definition shall not contain an initializer.13911 //13912 // We already performed a redefinition check above, but for static13913 // data members we also need to check whether there was an in-class13914 // declaration with an initializer.13915 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {13916 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)13917 << VDecl->getDeclName();13918 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),13919 diag::note_previous_initializer)13920 << 0;13921 return;13922 }13923 13924 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {13925 VDecl->setInvalidDecl();13926 return;13927 }13928 }13929 13930 // If the variable has an initializer and local storage, check whether13931 // anything jumps over the initialization.13932 if (VDecl->hasLocalStorage())13933 setFunctionHasBranchProtectedScope();13934 13935 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside13936 // a kernel function cannot be initialized."13937 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {13938 Diag(VDecl->getLocation(), diag::err_local_cant_init);13939 VDecl->setInvalidDecl();13940 return;13941 }13942 13943 // The LoaderUninitialized attribute acts as a definition (of undef).13944 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {13945 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);13946 VDecl->setInvalidDecl();13947 return;13948 }13949 13950 if (getLangOpts().HLSL)13951 if (!HLSL().handleInitialization(VDecl, Init))13952 return;13953 13954 // Get the decls type and save a reference for later, since13955 // CheckInitializerTypes may change it.13956 QualType DclT = VDecl->getType(), SavT = DclT;13957 13958 // Expressions default to 'id' when we're in a debugger13959 // and we are assigning it to a variable of Objective-C pointer type.13960 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&13961 Init->getType() == Context.UnknownAnyTy) {13962 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());13963 if (!Result.isUsable()) {13964 VDecl->setInvalidDecl();13965 return;13966 }13967 Init = Result.get();13968 }13969 13970 // Perform the initialization.13971 bool InitializedFromParenListExpr = false;13972 bool IsParenListInit = false;13973 if (!VDecl->isInvalidDecl()) {13974 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);13975 InitializationKind Kind = InitializationKind::CreateForInit(13976 VDecl->getLocation(), DirectInit, Init);13977 13978 MultiExprArg Args = Init;13979 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {13980 Args =13981 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());13982 InitializedFromParenListExpr = true;13983 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {13984 Args = CXXDirectInit->getInitExprs();13985 InitializedFromParenListExpr = true;13986 }13987 13988 InitializationSequence InitSeq(*this, Entity, Kind, Args,13989 /*TopLevelOfInitList=*/false,13990 /*TreatUnavailableAsInvalid=*/false);13991 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);13992 if (!Result.isUsable()) {13993 // If the provided initializer fails to initialize the var decl,13994 // we attach a recovery expr for better recovery.13995 auto RecoveryExpr =13996 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);13997 if (RecoveryExpr.get())13998 VDecl->setInit(RecoveryExpr.get());13999 // In general, for error recovery purposes, the initializer doesn't play14000 // part in the valid bit of the declaration. There are a few exceptions:14001 // 1) if the var decl has a deduced auto type, and the type cannot be14002 // deduced by an invalid initializer;14003 // 2) if the var decl is a decomposition decl with a non-deduced type,14004 // and the initialization fails (e.g. `int [a] = {1, 2};`);14005 // Case 1) was already handled elsewhere.14006 if (isa<DecompositionDecl>(VDecl)) // Case 2)14007 VDecl->setInvalidDecl();14008 return;14009 }14010 14011 Init = Result.getAs<Expr>();14012 IsParenListInit = !InitSeq.steps().empty() &&14013 InitSeq.step_begin()->Kind ==14014 InitializationSequence::SK_ParenthesizedListInit;14015 QualType VDeclType = VDecl->getType();14016 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&14017 !VDeclType->isDependentType() &&14018 Context.getAsIncompleteArrayType(VDeclType) &&14019 Context.getAsIncompleteArrayType(Init->getType())) {14020 // Bail out if it is not possible to deduce array size from the14021 // initializer.14022 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)14023 << VDeclType;14024 VDecl->setInvalidDecl();14025 return;14026 }14027 }14028 14029 // Check for self-references within variable initializers.14030 // Variables declared within a function/method body (except for references)14031 // are handled by a dataflow analysis.14032 // This is undefined behavior in C++, but valid in C.14033 if (getLangOpts().CPlusPlus)14034 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||14035 VDecl->getType()->isReferenceType())14036 CheckSelfReference(*this, RealDecl, Init, DirectInit);14037 14038 // If the type changed, it means we had an incomplete type that was14039 // completed by the initializer. For example:14040 // int ary[] = { 1, 3, 5 };14041 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.14042 if (!VDecl->isInvalidDecl() && (DclT != SavT))14043 VDecl->setType(DclT);14044 14045 if (!VDecl->isInvalidDecl()) {14046 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);14047 14048 if (VDecl->hasAttr<BlocksAttr>())14049 ObjC().checkRetainCycles(VDecl, Init);14050 14051 // It is safe to assign a weak reference into a strong variable.14052 // Although this code can still have problems:14053 // id x = self.weakProp;14054 // id y = self.weakProp;14055 // we do not warn to warn spuriously when 'x' and 'y' are on separate14056 // paths through the function. This should be revisited if14057 // -Wrepeated-use-of-weak is made flow-sensitive.14058 if (FunctionScopeInfo *FSI = getCurFunction())14059 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||14060 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&14061 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,14062 Init->getBeginLoc()))14063 FSI->markSafeWeakUse(Init);14064 }14065 14066 // The initialization is usually a full-expression.14067 //14068 // FIXME: If this is a braced initialization of an aggregate, it is not14069 // an expression, and each individual field initializer is a separate14070 // full-expression. For instance, in:14071 //14072 // struct Temp { ~Temp(); };14073 // struct S { S(Temp); };14074 // struct T { S a, b; } t = { Temp(), Temp() }14075 //14076 // we should destroy the first Temp before constructing the second.14077 ExprResult Result =14078 ActOnFinishFullExpr(Init, VDecl->getLocation(),14079 /*DiscardedValue*/ false, VDecl->isConstexpr());14080 if (!Result.isUsable()) {14081 VDecl->setInvalidDecl();14082 return;14083 }14084 Init = Result.get();14085 14086 // Attach the initializer to the decl.14087 VDecl->setInit(Init);14088 14089 if (VDecl->isLocalVarDecl()) {14090 // Don't check the initializer if the declaration is malformed.14091 if (VDecl->isInvalidDecl()) {14092 // do nothing14093 14094 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.14095 // This is true even in C++ for OpenCL.14096 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {14097 CheckForConstantInitializer(Init);14098 14099 // Otherwise, C++ does not restrict the initializer.14100 } else if (getLangOpts().CPlusPlus) {14101 // do nothing14102 14103 // C99 6.7.8p4: All the expressions in an initializer for an object that has14104 // static storage duration shall be constant expressions or string literals.14105 } else if (VDecl->getStorageClass() == SC_Static) {14106 CheckForConstantInitializer(Init);14107 14108 // C89 is stricter than C99 for aggregate initializers.14109 // C89 6.5.7p3: All the expressions [...] in an initializer list14110 // for an object that has aggregate or union type shall be14111 // constant expressions.14112 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&14113 isa<InitListExpr>(Init)) {14114 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);14115 }14116 14117 if (auto *E = dyn_cast<ExprWithCleanups>(Init))14118 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))14119 if (VDecl->hasLocalStorage())14120 BE->getBlockDecl()->setCanAvoidCopyToHeap();14121 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&14122 VDecl->getLexicalDeclContext()->isRecord()) {14123 // This is an in-class initialization for a static data member, e.g.,14124 //14125 // struct S {14126 // static const int value = 17;14127 // };14128 14129 // C++ [class.mem]p4:14130 // A member-declarator can contain a constant-initializer only14131 // if it declares a static member (9.4) of const integral or14132 // const enumeration type, see 9.4.2.14133 //14134 // C++11 [class.static.data]p3:14135 // If a non-volatile non-inline const static data member is of integral14136 // or enumeration type, its declaration in the class definition can14137 // specify a brace-or-equal-initializer in which every initializer-clause14138 // that is an assignment-expression is a constant expression. A static14139 // data member of literal type can be declared in the class definition14140 // with the constexpr specifier; if so, its declaration shall specify a14141 // brace-or-equal-initializer in which every initializer-clause that is14142 // an assignment-expression is a constant expression.14143 14144 // Do nothing on dependent types.14145 if (DclT->isDependentType()) {14146 14147 // Allow any 'static constexpr' members, whether or not they are of literal14148 // type. We separately check that every constexpr variable is of literal14149 // type.14150 } else if (VDecl->isConstexpr()) {14151 14152 // Require constness.14153 } else if (!DclT.isConstQualified()) {14154 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)14155 << Init->getSourceRange();14156 VDecl->setInvalidDecl();14157 14158 // We allow integer constant expressions in all cases.14159 } else if (DclT->isIntegralOrEnumerationType()) {14160 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())14161 // In C++11, a non-constexpr const static data member with an14162 // in-class initializer cannot be volatile.14163 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);14164 14165 // We allow foldable floating-point constants as an extension.14166 } else if (DclT->isFloatingType()) { // also permits complex, which is ok14167 // In C++98, this is a GNU extension. In C++11, it is not, but we support14168 // it anyway and provide a fixit to add the 'constexpr'.14169 if (getLangOpts().CPlusPlus11) {14170 Diag(VDecl->getLocation(),14171 diag::ext_in_class_initializer_float_type_cxx11)14172 << DclT << Init->getSourceRange();14173 Diag(VDecl->getBeginLoc(),14174 diag::note_in_class_initializer_float_type_cxx11)14175 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");14176 } else {14177 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)14178 << DclT << Init->getSourceRange();14179 14180 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {14181 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)14182 << Init->getSourceRange();14183 VDecl->setInvalidDecl();14184 }14185 }14186 14187 // Suggest adding 'constexpr' in C++11 for literal types.14188 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {14189 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)14190 << DclT << Init->getSourceRange()14191 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");14192 VDecl->setConstexpr(true);14193 14194 } else {14195 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)14196 << DclT << Init->getSourceRange();14197 VDecl->setInvalidDecl();14198 }14199 } else if (VDecl->isFileVarDecl()) {14200 // In C, extern is typically used to avoid tentative definitions when14201 // declaring variables in headers, but adding an initializer makes it a14202 // definition. This is somewhat confusing, so GCC and Clang both warn on it.14203 // In C++, extern is often used to give implicitly static const variables14204 // external linkage, so don't warn in that case. If selectany is present,14205 // this might be header code intended for C and C++ inclusion, so apply the14206 // C++ rules.14207 if (VDecl->getStorageClass() == SC_Extern &&14208 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||14209 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&14210 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&14211 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))14212 Diag(VDecl->getLocation(), diag::warn_extern_init);14213 14214 // In Microsoft C++ mode, a const variable defined in namespace scope has14215 // external linkage by default if the variable is declared with14216 // __declspec(dllexport).14217 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&14218 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&14219 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())14220 VDecl->setStorageClass(SC_Extern);14221 14222 // C99 6.7.8p4. All file scoped initializers need to be constant.14223 // Avoid duplicate diagnostics for constexpr variables.14224 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&14225 !VDecl->isConstexpr())14226 CheckForConstantInitializer(Init);14227 }14228 14229 QualType InitType = Init->getType();14230 if (!InitType.isNull() &&14231 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||14232 InitType.hasNonTrivialToPrimitiveCopyCUnion()))14233 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());14234 14235 // We will represent direct-initialization similarly to copy-initialization:14236 // int x(1); -as-> int x = 1;14237 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);14238 //14239 // Clients that want to distinguish between the two forms, can check for14240 // direct initializer using VarDecl::getInitStyle().14241 // A major benefit is that clients that don't particularly care about which14242 // exactly form was it (like the CodeGen) can handle both cases without14243 // special case code.14244 14245 // C++ 8.5p11:14246 // The form of initialization (using parentheses or '=') matters14247 // when the entity being initialized has class type.14248 if (InitializedFromParenListExpr) {14249 assert(DirectInit && "Call-style initializer must be direct init.");14250 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit14251 : VarDecl::CallInit);14252 } else if (DirectInit) {14253 // This must be list-initialization. No other way is direct-initialization.14254 VDecl->setInitStyle(VarDecl::ListInit);14255 }14256 14257 if (LangOpts.OpenMP &&14258 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&14259 VDecl->isFileVarDecl())14260 DeclsToCheckForDeferredDiags.insert(VDecl);14261 CheckCompleteVariableDeclaration(VDecl);14262 14263 if (LangOpts.OpenACC && !InitType.isNull())14264 OpenACC().ActOnVariableInit(VDecl, InitType);14265}14266 14267void Sema::ActOnInitializerError(Decl *D) {14268 // Our main concern here is re-establishing invariants like "a14269 // variable's type is either dependent or complete".14270 if (!D || D->isInvalidDecl()) return;14271 14272 VarDecl *VD = dyn_cast<VarDecl>(D);14273 if (!VD) return;14274 14275 // Bindings are not usable if we can't make sense of the initializer.14276 if (auto *DD = dyn_cast<DecompositionDecl>(D))14277 for (auto *BD : DD->bindings())14278 BD->setInvalidDecl();14279 14280 // Auto types are meaningless if we can't make sense of the initializer.14281 if (VD->getType()->isUndeducedType()) {14282 D->setInvalidDecl();14283 return;14284 }14285 14286 QualType Ty = VD->getType();14287 if (Ty->isDependentType()) return;14288 14289 // Require a complete type.14290 if (RequireCompleteType(VD->getLocation(),14291 Context.getBaseElementType(Ty),14292 diag::err_typecheck_decl_incomplete_type)) {14293 VD->setInvalidDecl();14294 return;14295 }14296 14297 // Require a non-abstract type.14298 if (RequireNonAbstractType(VD->getLocation(), Ty,14299 diag::err_abstract_type_in_decl,14300 AbstractVariableType)) {14301 VD->setInvalidDecl();14302 return;14303 }14304 14305 // Don't bother complaining about constructors or destructors,14306 // though.14307}14308 14309void Sema::ActOnUninitializedDecl(Decl *RealDecl) {14310 // If there is no declaration, there was an error parsing it. Just ignore it.14311 if (!RealDecl)14312 return;14313 14314 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {14315 QualType Type = Var->getType();14316 14317 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.14318 if (isa<DecompositionDecl>(RealDecl)) {14319 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;14320 Var->setInvalidDecl();14321 return;14322 }14323 14324 if (Type->isUndeducedType() &&14325 DeduceVariableDeclarationType(Var, false, nullptr))14326 return;14327 14328 this->CheckAttributesOnDeducedType(RealDecl);14329 14330 // C++11 [class.static.data]p3: A static data member can be declared with14331 // the constexpr specifier; if so, its declaration shall specify14332 // a brace-or-equal-initializer.14333 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to14334 // the definition of a variable [...] or the declaration of a static data14335 // member.14336 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&14337 !Var->isThisDeclarationADemotedDefinition()) {14338 if (Var->isStaticDataMember()) {14339 // C++1z removes the relevant rule; the in-class declaration is always14340 // a definition there.14341 if (!getLangOpts().CPlusPlus17 &&14342 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {14343 Diag(Var->getLocation(),14344 diag::err_constexpr_static_mem_var_requires_init)14345 << Var;14346 Var->setInvalidDecl();14347 return;14348 }14349 } else {14350 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);14351 Var->setInvalidDecl();14352 return;14353 }14354 }14355 14356 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must14357 // be initialized.14358 if (!Var->isInvalidDecl() &&14359 Var->getType().getAddressSpace() == LangAS::opencl_constant &&14360 Var->getStorageClass() != SC_Extern && !Var->getInit()) {14361 bool HasConstExprDefaultConstructor = false;14362 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {14363 for (auto *Ctor : RD->ctors()) {14364 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&14365 Ctor->getMethodQualifiers().getAddressSpace() ==14366 LangAS::opencl_constant) {14367 HasConstExprDefaultConstructor = true;14368 }14369 }14370 }14371 if (!HasConstExprDefaultConstructor) {14372 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);14373 Var->setInvalidDecl();14374 return;14375 }14376 }14377 14378 // HLSL variable with the `vk::constant_id` attribute must be initialized.14379 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {14380 Diag(Var->getLocation(), diag::err_specialization_const);14381 Var->setInvalidDecl();14382 return;14383 }14384 14385 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {14386 if (Var->getStorageClass() == SC_Extern) {14387 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)14388 << Var;14389 Var->setInvalidDecl();14390 return;14391 }14392 if (RequireCompleteType(Var->getLocation(), Var->getType(),14393 diag::err_typecheck_decl_incomplete_type)) {14394 Var->setInvalidDecl();14395 return;14396 }14397 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {14398 if (!RD->hasTrivialDefaultConstructor()) {14399 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);14400 Var->setInvalidDecl();14401 return;14402 }14403 }14404 // The declaration is uninitialized, no need for further checks.14405 return;14406 }14407 14408 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();14409 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&14410 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())14411 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),14412 NonTrivialCUnionContext::DefaultInitializedObject,14413 NTCUK_Init);14414 14415 switch (DefKind) {14416 case VarDecl::Definition:14417 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())14418 break;14419 14420 // We have an out-of-line definition of a static data member14421 // that has an in-class initializer, so we type-check this like14422 // a declaration.14423 //14424 [[fallthrough]];14425 14426 case VarDecl::DeclarationOnly:14427 // It's only a declaration.14428 14429 // Block scope. C99 6.7p7: If an identifier for an object is14430 // declared with no linkage (C99 6.2.2p6), the type for the14431 // object shall be complete.14432 if (!Type->isDependentType() && Var->isLocalVarDecl() &&14433 !Var->hasLinkage() && !Var->isInvalidDecl() &&14434 RequireCompleteType(Var->getLocation(), Type,14435 diag::err_typecheck_decl_incomplete_type))14436 Var->setInvalidDecl();14437 14438 // Make sure that the type is not abstract.14439 if (!Type->isDependentType() && !Var->isInvalidDecl() &&14440 RequireNonAbstractType(Var->getLocation(), Type,14441 diag::err_abstract_type_in_decl,14442 AbstractVariableType))14443 Var->setInvalidDecl();14444 if (!Type->isDependentType() && !Var->isInvalidDecl() &&14445 Var->getStorageClass() == SC_PrivateExtern) {14446 Diag(Var->getLocation(), diag::warn_private_extern);14447 Diag(Var->getLocation(), diag::note_private_extern);14448 }14449 14450 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&14451 !Var->isInvalidDecl())14452 ExternalDeclarations.push_back(Var);14453 14454 return;14455 14456 case VarDecl::TentativeDefinition:14457 // File scope. C99 6.9.2p2: A declaration of an identifier for an14458 // object that has file scope without an initializer, and without a14459 // storage-class specifier or with the storage-class specifier "static",14460 // constitutes a tentative definition. Note: A tentative definition with14461 // external linkage is valid (C99 6.2.2p5).14462 if (!Var->isInvalidDecl()) {14463 if (const IncompleteArrayType *ArrayT14464 = Context.getAsIncompleteArrayType(Type)) {14465 if (RequireCompleteSizedType(14466 Var->getLocation(), ArrayT->getElementType(),14467 diag::err_array_incomplete_or_sizeless_type))14468 Var->setInvalidDecl();14469 }14470 if (Var->getStorageClass() == SC_Static) {14471 // C99 6.9.2p3: If the declaration of an identifier for an object is14472 // a tentative definition and has internal linkage (C99 6.2.2p3), the14473 // declared type shall not be an incomplete type.14474 // NOTE: code such as the following14475 // static struct s;14476 // struct s { int a; };14477 // is accepted by gcc. Hence here we issue a warning instead of14478 // an error and we do not invalidate the static declaration.14479 // NOTE: to avoid multiple warnings, only check the first declaration.14480 if (Var->isFirstDecl())14481 RequireCompleteType(Var->getLocation(), Type,14482 diag::ext_typecheck_decl_incomplete_type,14483 Type->isArrayType());14484 }14485 }14486 14487 // Record the tentative definition; we're done.14488 if (!Var->isInvalidDecl())14489 TentativeDefinitions.push_back(Var);14490 return;14491 }14492 14493 // Provide a specific diagnostic for uninitialized variable definitions14494 // with incomplete array type, unless it is a global unbounded HLSL resource14495 // array.14496 if (Type->isIncompleteArrayType() &&14497 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&14498 Type->isHLSLResourceRecordArray())) {14499 if (Var->isConstexpr())14500 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)14501 << Var;14502 else14503 Diag(Var->getLocation(),14504 diag::err_typecheck_incomplete_array_needs_initializer);14505 Var->setInvalidDecl();14506 return;14507 }14508 14509 // Provide a specific diagnostic for uninitialized variable14510 // definitions with reference type.14511 if (Type->isReferenceType()) {14512 Diag(Var->getLocation(), diag::err_reference_var_requires_init)14513 << Var << SourceRange(Var->getLocation(), Var->getLocation());14514 return;14515 }14516 14517 // Do not attempt to type-check the default initializer for a14518 // variable with dependent type.14519 if (Type->isDependentType())14520 return;14521 14522 if (Var->isInvalidDecl())14523 return;14524 14525 if (!Var->hasAttr<AliasAttr>()) {14526 if (RequireCompleteType(Var->getLocation(),14527 Context.getBaseElementType(Type),14528 diag::err_typecheck_decl_incomplete_type)) {14529 Var->setInvalidDecl();14530 return;14531 }14532 } else {14533 return;14534 }14535 14536 // The variable can not have an abstract class type.14537 if (RequireNonAbstractType(Var->getLocation(), Type,14538 diag::err_abstract_type_in_decl,14539 AbstractVariableType)) {14540 Var->setInvalidDecl();14541 return;14542 }14543 14544 // In C, if the definition is const-qualified and has no initializer, it14545 // is left uninitialized unless it has static or thread storage duration.14546 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {14547 unsigned DiagID = diag::warn_default_init_const_unsafe;14548 if (Var->getStorageDuration() == SD_Static ||14549 Var->getStorageDuration() == SD_Thread)14550 DiagID = diag::warn_default_init_const;14551 14552 bool EmitCppCompat = !Diags.isIgnored(14553 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,14554 Var->getLocation());14555 14556 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;14557 }14558 14559 // Check for jumps past the implicit initializer. C++0x14560 // clarifies that this applies to a "variable with automatic14561 // storage duration", not a "local variable".14562 // C++11 [stmt.dcl]p314563 // A program that jumps from a point where a variable with automatic14564 // storage duration is not in scope to a point where it is in scope is14565 // ill-formed unless the variable has scalar type, class type with a14566 // trivial default constructor and a trivial destructor, a cv-qualified14567 // version of one of these types, or an array of one of the preceding14568 // types and is declared without an initializer.14569 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {14570 if (const auto *CXXRecord =14571 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {14572 // Mark the function (if we're in one) for further checking even if the14573 // looser rules of C++11 do not require such checks, so that we can14574 // diagnose incompatibilities with C++98.14575 if (!CXXRecord->isPOD())14576 setFunctionHasBranchProtectedScope();14577 }14578 }14579 // In OpenCL, we can't initialize objects in the __local address space,14580 // even implicitly, so don't synthesize an implicit initializer.14581 if (getLangOpts().OpenCL &&14582 Var->getType().getAddressSpace() == LangAS::opencl_local)14583 return;14584 14585 // Handle HLSL uninitialized decls14586 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))14587 return;14588 14589 // HLSL input variables are expected to be externally initialized, even14590 // when marked `static`.14591 if (getLangOpts().HLSL &&14592 Var->getType().getAddressSpace() == LangAS::hlsl_input)14593 return;14594 14595 // C++03 [dcl.init]p9:14596 // If no initializer is specified for an object, and the14597 // object is of (possibly cv-qualified) non-POD class type (or14598 // array thereof), the object shall be default-initialized; if14599 // the object is of const-qualified type, the underlying class14600 // type shall have a user-declared default14601 // constructor. Otherwise, if no initializer is specified for14602 // a non- static object, the object and its subobjects, if14603 // any, have an indeterminate initial value); if the object14604 // or any of its subobjects are of const-qualified type, the14605 // program is ill-formed.14606 // C++0x [dcl.init]p11:14607 // If no initializer is specified for an object, the object is14608 // default-initialized; [...].14609 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);14610 InitializationKind Kind14611 = InitializationKind::CreateDefault(Var->getLocation());14612 14613 InitializationSequence InitSeq(*this, Entity, Kind, {});14614 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});14615 14616 if (Init.get()) {14617 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));14618 // This is important for template substitution.14619 Var->setInitStyle(VarDecl::CallInit);14620 } else if (Init.isInvalid()) {14621 // If default-init fails, attach a recovery-expr initializer to track14622 // that initialization was attempted and failed.14623 auto RecoveryExpr =14624 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});14625 if (RecoveryExpr.get())14626 Var->setInit(RecoveryExpr.get());14627 }14628 14629 CheckCompleteVariableDeclaration(Var);14630 }14631}14632 14633void Sema::ActOnCXXForRangeDecl(Decl *D) {14634 // If there is no declaration, there was an error parsing it. Ignore it.14635 if (!D)14636 return;14637 14638 VarDecl *VD = dyn_cast<VarDecl>(D);14639 if (!VD) {14640 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);14641 D->setInvalidDecl();14642 return;14643 }14644 14645 VD->setCXXForRangeDecl(true);14646 14647 // for-range-declaration cannot be given a storage class specifier.14648 int Error = -1;14649 switch (VD->getStorageClass()) {14650 case SC_None:14651 break;14652 case SC_Extern:14653 Error = 0;14654 break;14655 case SC_Static:14656 Error = 1;14657 break;14658 case SC_PrivateExtern:14659 Error = 2;14660 break;14661 case SC_Auto:14662 Error = 3;14663 break;14664 case SC_Register:14665 Error = 4;14666 break;14667 }14668 14669 // for-range-declaration cannot be given a storage class specifier con't.14670 switch (VD->getTSCSpec()) {14671 case TSCS_thread_local:14672 Error = 6;14673 break;14674 case TSCS___thread:14675 case TSCS__Thread_local:14676 case TSCS_unspecified:14677 break;14678 }14679 14680 if (Error != -1) {14681 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)14682 << VD << Error;14683 D->setInvalidDecl();14684 }14685}14686 14687StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,14688 IdentifierInfo *Ident,14689 ParsedAttributes &Attrs) {14690 // C++1y [stmt.iter]p1:14691 // A range-based for statement of the form14692 // for ( for-range-identifier : for-range-initializer ) statement14693 // is equivalent to14694 // for ( auto&& for-range-identifier : for-range-initializer ) statement14695 DeclSpec DS(Attrs.getPool().getFactory());14696 14697 const char *PrevSpec;14698 unsigned DiagID;14699 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,14700 getPrintingPolicy());14701 14702 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);14703 D.SetIdentifier(Ident, IdentLoc);14704 D.takeAttributesAppending(Attrs);14705 14706 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),14707 IdentLoc);14708 Decl *Var = ActOnDeclarator(S, D);14709 cast<VarDecl>(Var)->setCXXForRangeDecl(true);14710 FinalizeDeclaration(Var);14711 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,14712 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()14713 : IdentLoc);14714}14715 14716void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {14717 if (var->isInvalidDecl()) return;14718 14719 CUDA().MaybeAddConstantAttr(var);14720 14721 if (getLangOpts().OpenCL) {14722 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an14723 // initialiser14724 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&14725 !var->hasInit()) {14726 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)14727 << 1 /*Init*/;14728 var->setInvalidDecl();14729 return;14730 }14731 }14732 14733 // In Objective-C, don't allow jumps past the implicit initialization of a14734 // local retaining variable.14735 if (getLangOpts().ObjC &&14736 var->hasLocalStorage()) {14737 switch (var->getType().getObjCLifetime()) {14738 case Qualifiers::OCL_None:14739 case Qualifiers::OCL_ExplicitNone:14740 case Qualifiers::OCL_Autoreleasing:14741 break;14742 14743 case Qualifiers::OCL_Weak:14744 case Qualifiers::OCL_Strong:14745 setFunctionHasBranchProtectedScope();14746 break;14747 }14748 }14749 14750 if (var->hasLocalStorage() &&14751 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)14752 setFunctionHasBranchProtectedScope();14753 14754 // Warn about externally-visible variables being defined without a14755 // prior declaration. We only want to do this for global14756 // declarations, but we also specifically need to avoid doing it for14757 // class members because the linkage of an anonymous class can14758 // change if it's later given a typedef name.14759 if (var->isThisDeclarationADefinition() &&14760 var->getDeclContext()->getRedeclContext()->isFileContext() &&14761 var->isExternallyVisible() && var->hasLinkage() &&14762 !var->isInline() && !var->getDescribedVarTemplate() &&14763 var->getStorageClass() != SC_Register &&14764 !isa<VarTemplatePartialSpecializationDecl>(var) &&14765 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&14766 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,14767 var->getLocation())) {14768 // Find a previous declaration that's not a definition.14769 VarDecl *prev = var->getPreviousDecl();14770 while (prev && prev->isThisDeclarationADefinition())14771 prev = prev->getPreviousDecl();14772 14773 if (!prev) {14774 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;14775 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)14776 << /* variable */ 0;14777 }14778 }14779 14780 // Cache the result of checking for constant initialization.14781 std::optional<bool> CacheHasConstInit;14782 const Expr *CacheCulprit = nullptr;14783 auto checkConstInit = [&]() mutable {14784 const Expr *Init = var->getInit();14785 if (Init->isInstantiationDependent())14786 return true;14787 14788 if (!CacheHasConstInit)14789 CacheHasConstInit = var->getInit()->isConstantInitializer(14790 Context, var->getType()->isReferenceType(), &CacheCulprit);14791 return *CacheHasConstInit;14792 };14793 14794 if (var->getTLSKind() == VarDecl::TLS_Static) {14795 if (var->getType().isDestructedType()) {14796 // GNU C++98 edits for __thread, [basic.start.term]p3:14797 // The type of an object with thread storage duration shall not14798 // have a non-trivial destructor.14799 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);14800 if (getLangOpts().CPlusPlus11)14801 Diag(var->getLocation(), diag::note_use_thread_local);14802 } else if (getLangOpts().CPlusPlus && var->hasInit()) {14803 if (!checkConstInit()) {14804 // GNU C++98 edits for __thread, [basic.start.init]p4:14805 // An object of thread storage duration shall not require dynamic14806 // initialization.14807 // FIXME: Need strict checking here.14808 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)14809 << CacheCulprit->getSourceRange();14810 if (getLangOpts().CPlusPlus11)14811 Diag(var->getLocation(), diag::note_use_thread_local);14812 }14813 }14814 }14815 14816 14817 if (!var->getType()->isStructureType() && var->hasInit() &&14818 isa<InitListExpr>(var->getInit())) {14819 const auto *ILE = cast<InitListExpr>(var->getInit());14820 unsigned NumInits = ILE->getNumInits();14821 if (NumInits > 2)14822 for (unsigned I = 0; I < NumInits; ++I) {14823 const auto *Init = ILE->getInit(I);14824 if (!Init)14825 break;14826 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());14827 if (!SL)14828 break;14829 14830 unsigned NumConcat = SL->getNumConcatenated();14831 // Diagnose missing comma in string array initialization.14832 // Do not warn when all the elements in the initializer are concatenated14833 // together. Do not warn for macros too.14834 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {14835 bool OnlyOneMissingComma = true;14836 for (unsigned J = I + 1; J < NumInits; ++J) {14837 const auto *Init = ILE->getInit(J);14838 if (!Init)14839 break;14840 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());14841 if (!SLJ || SLJ->getNumConcatenated() > 1) {14842 OnlyOneMissingComma = false;14843 break;14844 }14845 }14846 14847 if (OnlyOneMissingComma) {14848 SmallVector<FixItHint, 1> Hints;14849 for (unsigned i = 0; i < NumConcat - 1; ++i)14850 Hints.push_back(FixItHint::CreateInsertion(14851 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));14852 14853 Diag(SL->getStrTokenLoc(1),14854 diag::warn_concatenated_literal_array_init)14855 << Hints;14856 Diag(SL->getBeginLoc(),14857 diag::note_concatenated_string_literal_silence);14858 }14859 // In any case, stop now.14860 break;14861 }14862 }14863 }14864 14865 14866 QualType type = var->getType();14867 14868 if (var->hasAttr<BlocksAttr>())14869 getCurFunction()->addByrefBlockVar(var);14870 14871 Expr *Init = var->getInit();14872 bool GlobalStorage = var->hasGlobalStorage();14873 bool IsGlobal = GlobalStorage && !var->isStaticLocal();14874 QualType baseType = Context.getBaseElementType(type);14875 bool HasConstInit = true;14876 14877 if (getLangOpts().C23 && var->isConstexpr() && !Init)14878 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)14879 << var;14880 14881 // Check whether the initializer is sufficiently constant.14882 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&14883 !type->isDependentType() && Init && !Init->isValueDependent() &&14884 (GlobalStorage || var->isConstexpr() ||14885 var->mightBeUsableInConstantExpressions(Context))) {14886 // If this variable might have a constant initializer or might be usable in14887 // constant expressions, check whether or not it actually is now. We can't14888 // do this lazily, because the result might depend on things that change14889 // later, such as which constexpr functions happen to be defined.14890 SmallVector<PartialDiagnosticAt, 8> Notes;14891 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {14892 // Prior to C++11, in contexts where a constant initializer is required,14893 // the set of valid constant initializers is described by syntactic rules14894 // in [expr.const]p2-6.14895 // FIXME: Stricter checking for these rules would be useful for constinit /14896 // -Wglobal-constructors.14897 HasConstInit = checkConstInit();14898 14899 // Compute and cache the constant value, and remember that we have a14900 // constant initializer.14901 if (HasConstInit) {14902 if (var->isStaticDataMember() && !var->isInline() &&14903 var->getLexicalDeclContext()->isRecord() &&14904 type->isIntegralOrEnumerationType()) {14905 // In C++98, in-class initialization for a static data member must14906 // be an integer constant expression.14907 if (!Init->isIntegerConstantExpr(Context)) {14908 Diag(Init->getExprLoc(),14909 diag::ext_in_class_initializer_non_constant)14910 << Init->getSourceRange();14911 }14912 }14913 (void)var->checkForConstantInitialization(Notes);14914 Notes.clear();14915 } else if (CacheCulprit) {14916 Notes.emplace_back(CacheCulprit->getExprLoc(),14917 PDiag(diag::note_invalid_subexpr_in_const_expr));14918 Notes.back().second << CacheCulprit->getSourceRange();14919 }14920 } else {14921 // Evaluate the initializer to see if it's a constant initializer.14922 HasConstInit = var->checkForConstantInitialization(Notes);14923 }14924 14925 if (HasConstInit) {14926 // FIXME: Consider replacing the initializer with a ConstantExpr.14927 } else if (var->isConstexpr()) {14928 SourceLocation DiagLoc = var->getLocation();14929 // If the note doesn't add any useful information other than a source14930 // location, fold it into the primary diagnostic.14931 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==14932 diag::note_invalid_subexpr_in_const_expr) {14933 DiagLoc = Notes[0].first;14934 Notes.clear();14935 }14936 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)14937 << var << Init->getSourceRange();14938 for (unsigned I = 0, N = Notes.size(); I != N; ++I)14939 Diag(Notes[I].first, Notes[I].second);14940 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {14941 auto *Attr = var->getAttr<ConstInitAttr>();14942 Diag(var->getLocation(), diag::err_require_constant_init_failed)14943 << Init->getSourceRange();14944 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)14945 << Attr->getRange() << Attr->isConstinit();14946 for (auto &it : Notes)14947 Diag(it.first, it.second);14948 } else if (var->isStaticDataMember() && !var->isInline() &&14949 var->getLexicalDeclContext()->isRecord()) {14950 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)14951 << Init->getSourceRange();14952 for (auto &it : Notes)14953 Diag(it.first, it.second);14954 var->setInvalidDecl();14955 } else if (IsGlobal &&14956 !getDiagnostics().isIgnored(diag::warn_global_constructor,14957 var->getLocation())) {14958 // Warn about globals which don't have a constant initializer. Don't14959 // warn about globals with a non-trivial destructor because we already14960 // warned about them.14961 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();14962 if (!(RD && !RD->hasTrivialDestructor())) {14963 // checkConstInit() here permits trivial default initialization even in14964 // C++11 onwards, where such an initializer is not a constant initializer14965 // but nonetheless doesn't require a global constructor.14966 if (!checkConstInit())14967 Diag(var->getLocation(), diag::warn_global_constructor)14968 << Init->getSourceRange();14969 }14970 }14971 }14972 14973 // Apply section attributes and pragmas to global variables.14974 if (GlobalStorage && var->isThisDeclarationADefinition() &&14975 !inTemplateInstantiation()) {14976 PragmaStack<StringLiteral *> *Stack = nullptr;14977 int SectionFlags = ASTContext::PSF_Read;14978 bool MSVCEnv =14979 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();14980 std::optional<QualType::NonConstantStorageReason> Reason;14981 if (HasConstInit &&14982 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {14983 Stack = &ConstSegStack;14984 } else {14985 SectionFlags |= ASTContext::PSF_Write;14986 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;14987 }14988 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {14989 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)14990 SectionFlags |= ASTContext::PSF_Implicit;14991 UnifySection(SA->getName(), SectionFlags, var);14992 } else if (Stack->CurrentValue) {14993 if (Stack != &ConstSegStack && MSVCEnv &&14994 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&14995 var->getType().isConstQualified()) {14996 assert((!Reason || Reason != QualType::NonConstantStorageReason::14997 NonConstNonReferenceType) &&14998 "This case should've already been handled elsewhere");14999 Diag(var->getLocation(), diag::warn_section_msvc_compat)15000 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit15001 ? QualType::NonConstantStorageReason::NonTrivialCtor15002 : *Reason);15003 }15004 SectionFlags |= ASTContext::PSF_Implicit;15005 auto SectionName = Stack->CurrentValue->getString();15006 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,15007 Stack->CurrentPragmaLocation,15008 SectionAttr::Declspec_allocate));15009 if (UnifySection(SectionName, SectionFlags, var))15010 var->dropAttr<SectionAttr>();15011 }15012 15013 // Apply the init_seg attribute if this has an initializer. If the15014 // initializer turns out to not be dynamic, we'll end up ignoring this15015 // attribute.15016 if (CurInitSeg && var->getInit())15017 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),15018 CurInitSegLoc));15019 }15020 15021 // All the following checks are C++ only.15022 if (!getLangOpts().CPlusPlus) {15023 // If this variable must be emitted, add it as an initializer for the15024 // current module.15025 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())15026 Context.addModuleInitializer(ModuleScopes.back().Module, var);15027 return;15028 }15029 15030 DiagnoseUniqueObjectDuplication(var);15031 15032 // Require the destructor.15033 if (!type->isDependentType())15034 if (auto *RD = baseType->getAsCXXRecordDecl())15035 FinalizeVarWithDestructor(var, RD);15036 15037 // If this variable must be emitted, add it as an initializer for the current15038 // module.15039 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())15040 Context.addModuleInitializer(ModuleScopes.back().Module, var);15041 15042 // Build the bindings if this is a structured binding declaration.15043 if (auto *DD = dyn_cast<DecompositionDecl>(var))15044 CheckCompleteDecompositionDeclaration(DD);15045}15046 15047void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {15048 assert(VD->isStaticLocal());15049 15050 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());15051 15052 // Find outermost function when VD is in lambda function.15053 while (FD && !getDLLAttr(FD) &&15054 !FD->hasAttr<DLLExportStaticLocalAttr>() &&15055 !FD->hasAttr<DLLImportStaticLocalAttr>()) {15056 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());15057 }15058 15059 if (!FD)15060 return;15061 15062 // Static locals inherit dll attributes from their function.15063 if (Attr *A = getDLLAttr(FD)) {15064 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));15065 NewAttr->setInherited(true);15066 VD->addAttr(NewAttr);15067 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {15068 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);15069 NewAttr->setInherited(true);15070 VD->addAttr(NewAttr);15071 15072 // Export this function to enforce exporting this static variable even15073 // if it is not used in this compilation unit.15074 if (!FD->hasAttr<DLLExportAttr>())15075 FD->addAttr(NewAttr);15076 15077 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {15078 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);15079 NewAttr->setInherited(true);15080 VD->addAttr(NewAttr);15081 }15082}15083 15084void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {15085 assert(VD->getTLSKind());15086 15087 // Perform TLS alignment check here after attributes attached to the variable15088 // which may affect the alignment have been processed. Only perform the check15089 // if the target has a maximum TLS alignment (zero means no constraints).15090 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {15091 // Protect the check so that it's not performed on dependent types and15092 // dependent alignments (we can't determine the alignment in that case).15093 if (!VD->hasDependentAlignment()) {15094 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);15095 if (Context.getDeclAlign(VD) > MaxAlignChars) {15096 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)15097 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD15098 << (unsigned)MaxAlignChars.getQuantity();15099 }15100 }15101 }15102}15103 15104void Sema::FinalizeDeclaration(Decl *ThisDecl) {15105 // Note that we are no longer parsing the initializer for this declaration.15106 ParsingInitForAutoVars.erase(ThisDecl);15107 15108 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);15109 if (!VD)15110 return;15111 15112 // Emit any deferred warnings for the variable's initializer, even if the15113 // variable is invalid15114 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);15115 15116 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active15117 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&15118 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {15119 if (PragmaClangBSSSection.Valid)15120 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(15121 Context, PragmaClangBSSSection.SectionName,15122 PragmaClangBSSSection.PragmaLocation));15123 if (PragmaClangDataSection.Valid)15124 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(15125 Context, PragmaClangDataSection.SectionName,15126 PragmaClangDataSection.PragmaLocation));15127 if (PragmaClangRodataSection.Valid)15128 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(15129 Context, PragmaClangRodataSection.SectionName,15130 PragmaClangRodataSection.PragmaLocation));15131 if (PragmaClangRelroSection.Valid)15132 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(15133 Context, PragmaClangRelroSection.SectionName,15134 PragmaClangRelroSection.PragmaLocation));15135 }15136 15137 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {15138 for (auto *BD : DD->bindings()) {15139 FinalizeDeclaration(BD);15140 }15141 }15142 15143 CheckInvalidBuiltinCountedByRef(VD->getInit(),15144 BuiltinCountedByRefKind::Initializer);15145 15146 checkAttributesAfterMerging(*this, *VD);15147 15148 if (VD->isStaticLocal())15149 CheckStaticLocalForDllExport(VD);15150 15151 if (VD->getTLSKind())15152 CheckThreadLocalForLargeAlignment(VD);15153 15154 // Perform check for initializers of device-side global variables.15155 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA15156 // 7.5). We must also apply the same checks to all __shared__15157 // variables whether they are local or not. CUDA also allows15158 // constant initializers for __constant__ and __device__ variables.15159 if (getLangOpts().CUDA)15160 CUDA().checkAllowedInitializer(VD);15161 15162 // Grab the dllimport or dllexport attribute off of the VarDecl.15163 const InheritableAttr *DLLAttr = getDLLAttr(VD);15164 15165 // Imported static data members cannot be defined out-of-line.15166 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {15167 if (VD->isStaticDataMember() && VD->isOutOfLine() &&15168 VD->isThisDeclarationADefinition()) {15169 // We allow definitions of dllimport class template static data members15170 // with a warning.15171 CXXRecordDecl *Context =15172 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());15173 bool IsClassTemplateMember =15174 isa<ClassTemplatePartialSpecializationDecl>(Context) ||15175 Context->getDescribedClassTemplate();15176 15177 Diag(VD->getLocation(),15178 IsClassTemplateMember15179 ? diag::warn_attribute_dllimport_static_field_definition15180 : diag::err_attribute_dllimport_static_field_definition);15181 Diag(IA->getLocation(), diag::note_attribute);15182 if (!IsClassTemplateMember)15183 VD->setInvalidDecl();15184 }15185 }15186 15187 // dllimport/dllexport variables cannot be thread local, their TLS index15188 // isn't exported with the variable.15189 if (DLLAttr && VD->getTLSKind()) {15190 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());15191 if (F && getDLLAttr(F)) {15192 assert(VD->isStaticLocal());15193 // But if this is a static local in a dlimport/dllexport function, the15194 // function will never be inlined, which means the var would never be15195 // imported, so having it marked import/export is safe.15196 } else {15197 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD15198 << DLLAttr;15199 VD->setInvalidDecl();15200 }15201 }15202 15203 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {15204 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {15205 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)15206 << Attr;15207 VD->dropAttr<UsedAttr>();15208 }15209 }15210 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {15211 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {15212 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)15213 << Attr;15214 VD->dropAttr<RetainAttr>();15215 }15216 }15217 15218 const DeclContext *DC = VD->getDeclContext();15219 // If there's a #pragma GCC visibility in scope, and this isn't a class15220 // member, set the visibility of this variable.15221 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())15222 AddPushedVisibilityAttribute(VD);15223 15224 // FIXME: Warn on unused var template partial specializations.15225 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))15226 MarkUnusedFileScopedDecl(VD);15227 15228 // Now we have parsed the initializer and can update the table of magic15229 // tag values.15230 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||15231 !VD->getType()->isIntegralOrEnumerationType())15232 return;15233 15234 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {15235 const Expr *MagicValueExpr = VD->getInit();15236 if (!MagicValueExpr) {15237 continue;15238 }15239 std::optional<llvm::APSInt> MagicValueInt;15240 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {15241 Diag(I->getRange().getBegin(),15242 diag::err_type_tag_for_datatype_not_ice)15243 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();15244 continue;15245 }15246 if (MagicValueInt->getActiveBits() > 64) {15247 Diag(I->getRange().getBegin(),15248 diag::err_type_tag_for_datatype_too_large)15249 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();15250 continue;15251 }15252 uint64_t MagicValue = MagicValueInt->getZExtValue();15253 RegisterTypeTagForDatatype(I->getArgumentKind(),15254 MagicValue,15255 I->getMatchingCType(),15256 I->getLayoutCompatible(),15257 I->getMustBeNull());15258 }15259}15260 15261static bool hasDeducedAuto(DeclaratorDecl *DD) {15262 auto *VD = dyn_cast<VarDecl>(DD);15263 return VD && !VD->getType()->hasAutoForTrailingReturnType();15264}15265 15266Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,15267 ArrayRef<Decl *> Group) {15268 SmallVector<Decl*, 8> Decls;15269 15270 if (DS.isTypeSpecOwned())15271 Decls.push_back(DS.getRepAsDecl());15272 15273 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;15274 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;15275 bool DiagnosedMultipleDecomps = false;15276 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;15277 bool DiagnosedNonDeducedAuto = false;15278 15279 for (Decl *D : Group) {15280 if (!D)15281 continue;15282 // Check if the Decl has been declared in '#pragma omp declare target'15283 // directive and has static storage duration.15284 if (auto *VD = dyn_cast<VarDecl>(D);15285 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&15286 VD->hasGlobalStorage())15287 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);15288 // For declarators, there are some additional syntactic-ish checks we need15289 // to perform.15290 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {15291 if (!FirstDeclaratorInGroup)15292 FirstDeclaratorInGroup = DD;15293 if (!FirstDecompDeclaratorInGroup)15294 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);15295 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&15296 !hasDeducedAuto(DD))15297 FirstNonDeducedAutoInGroup = DD;15298 15299 if (FirstDeclaratorInGroup != DD) {15300 // A decomposition declaration cannot be combined with any other15301 // declaration in the same group.15302 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {15303 Diag(FirstDecompDeclaratorInGroup->getLocation(),15304 diag::err_decomp_decl_not_alone)15305 << FirstDeclaratorInGroup->getSourceRange()15306 << DD->getSourceRange();15307 DiagnosedMultipleDecomps = true;15308 }15309 15310 // A declarator that uses 'auto' in any way other than to declare a15311 // variable with a deduced type cannot be combined with any other15312 // declarator in the same group.15313 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {15314 Diag(FirstNonDeducedAutoInGroup->getLocation(),15315 diag::err_auto_non_deduced_not_alone)15316 << FirstNonDeducedAutoInGroup->getType()15317 ->hasAutoForTrailingReturnType()15318 << FirstDeclaratorInGroup->getSourceRange()15319 << DD->getSourceRange();15320 DiagnosedNonDeducedAuto = true;15321 }15322 }15323 }15324 15325 Decls.push_back(D);15326 }15327 15328 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {15329 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {15330 handleTagNumbering(Tag, S);15331 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&15332 getLangOpts().CPlusPlus)15333 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);15334 }15335 }15336 15337 return BuildDeclaratorGroup(Decls);15338}15339 15340Sema::DeclGroupPtrTy15341Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {15342 // C++14 [dcl.spec.auto]p7: (DR1347)15343 // If the type that replaces the placeholder type is not the same in each15344 // deduction, the program is ill-formed.15345 if (Group.size() > 1) {15346 QualType Deduced;15347 VarDecl *DeducedDecl = nullptr;15348 for (unsigned i = 0, e = Group.size(); i != e; ++i) {15349 VarDecl *D = dyn_cast<VarDecl>(Group[i]);15350 if (!D || D->isInvalidDecl())15351 break;15352 DeducedType *DT = D->getType()->getContainedDeducedType();15353 if (!DT || DT->getDeducedType().isNull())15354 continue;15355 if (Deduced.isNull()) {15356 Deduced = DT->getDeducedType();15357 DeducedDecl = D;15358 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {15359 auto *AT = dyn_cast<AutoType>(DT);15360 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),15361 diag::err_auto_different_deductions)15362 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced15363 << DeducedDecl->getDeclName() << DT->getDeducedType()15364 << D->getDeclName();15365 if (DeducedDecl->hasInit())15366 Dia << DeducedDecl->getInit()->getSourceRange();15367 if (D->getInit())15368 Dia << D->getInit()->getSourceRange();15369 D->setInvalidDecl();15370 break;15371 }15372 }15373 }15374 15375 ActOnDocumentableDecls(Group);15376 15377 return DeclGroupPtrTy::make(15378 DeclGroupRef::Create(Context, Group.data(), Group.size()));15379}15380 15381void Sema::ActOnDocumentableDecl(Decl *D) {15382 ActOnDocumentableDecls(D);15383}15384 15385void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {15386 // Don't parse the comment if Doxygen diagnostics are ignored.15387 if (Group.empty() || !Group[0])15388 return;15389 15390 if (Diags.isIgnored(diag::warn_doc_param_not_found,15391 Group[0]->getLocation()) &&15392 Diags.isIgnored(diag::warn_unknown_comment_command_name,15393 Group[0]->getLocation()))15394 return;15395 15396 if (Group.size() >= 2) {15397 // This is a decl group. Normally it will contain only declarations15398 // produced from declarator list. But in case we have any definitions or15399 // additional declaration references:15400 // 'typedef struct S {} S;'15401 // 'typedef struct S *S;'15402 // 'struct S *pS;'15403 // FinalizeDeclaratorGroup adds these as separate declarations.15404 Decl *MaybeTagDecl = Group[0];15405 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {15406 Group = Group.slice(1);15407 }15408 }15409 15410 // FIMXE: We assume every Decl in the group is in the same file.15411 // This is false when preprocessor constructs the group from decls in15412 // different files (e. g. macros or #include).15413 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());15414}15415 15416void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {15417 // Check that there are no default arguments inside the type of this15418 // parameter.15419 if (getLangOpts().CPlusPlus)15420 CheckExtraCXXDefaultArguments(D);15421 15422 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).15423 if (D.getCXXScopeSpec().isSet()) {15424 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)15425 << D.getCXXScopeSpec().getRange();15426 }15427 15428 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a15429 // simple identifier except [...irrelevant cases...].15430 switch (D.getName().getKind()) {15431 case UnqualifiedIdKind::IK_Identifier:15432 break;15433 15434 case UnqualifiedIdKind::IK_OperatorFunctionId:15435 case UnqualifiedIdKind::IK_ConversionFunctionId:15436 case UnqualifiedIdKind::IK_LiteralOperatorId:15437 case UnqualifiedIdKind::IK_ConstructorName:15438 case UnqualifiedIdKind::IK_DestructorName:15439 case UnqualifiedIdKind::IK_ImplicitSelfParam:15440 case UnqualifiedIdKind::IK_DeductionGuideName:15441 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)15442 << GetNameForDeclarator(D).getName();15443 break;15444 15445 case UnqualifiedIdKind::IK_TemplateId:15446 case UnqualifiedIdKind::IK_ConstructorTemplateId:15447 // GetNameForDeclarator would not produce a useful name in this case.15448 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);15449 break;15450 }15451}15452 15453void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {15454 // This only matters in C.15455 if (getLangOpts().CPlusPlus)15456 return;15457 15458 // This only matters if the declaration has a type.15459 const auto *VD = dyn_cast<ValueDecl>(D);15460 if (!VD)15461 return;15462 15463 // Get the type, this only matters for tag types.15464 QualType QT = VD->getType();15465 const auto *TD = QT->getAsTagDecl();15466 if (!TD)15467 return;15468 15469 // Check if the tag declaration is lexically declared somewhere different15470 // from the lexical declaration of the given object, then it will be hidden15471 // in C++ and we should warn on it.15472 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {15473 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;15474 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;15475 Diag(TD->getLocation(), diag::note_declared_at);15476 }15477}15478 15479static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,15480 SourceLocation ExplicitThisLoc) {15481 if (!ExplicitThisLoc.isValid())15482 return;15483 assert(S.getLangOpts().CPlusPlus &&15484 "explicit parameter in non-cplusplus mode");15485 if (!S.getLangOpts().CPlusPlus23)15486 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)15487 << P->getSourceRange();15488 15489 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function15490 // parameter pack.15491 if (P->isParameterPack()) {15492 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)15493 << P->getSourceRange();15494 return;15495 }15496 P->setExplicitObjectParameterLoc(ExplicitThisLoc);15497 if (LambdaScopeInfo *LSI = S.getCurLambda())15498 LSI->ExplicitObjectParameter = P;15499}15500 15501Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,15502 SourceLocation ExplicitThisLoc) {15503 const DeclSpec &DS = D.getDeclSpec();15504 15505 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.15506 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,15507 // except for the special case of a single unnamed parameter of type void15508 // with no storage class specifier, no type qualifier, and no following15509 // ellipsis terminator.15510 // Clang applies the C2y rules for 'register void' in all C language modes,15511 // same as GCC, because it's questionable what that could possibly mean.15512 15513 // C++03 [dcl.stc]p2 also permits 'auto'.15514 StorageClass SC = SC_None;15515 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {15516 SC = SC_Register;15517 // In C++11, the 'register' storage class specifier is deprecated.15518 // In C++17, it is not allowed, but we tolerate it as an extension.15519 if (getLangOpts().CPlusPlus11) {15520 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus1715521 ? diag::ext_register_storage_class15522 : diag::warn_deprecated_register)15523 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());15524 } else if (!getLangOpts().CPlusPlus &&15525 DS.getTypeSpecType() == DeclSpec::TST_void &&15526 D.getNumTypeObjects() == 0) {15527 Diag(DS.getStorageClassSpecLoc(),15528 diag::err_invalid_storage_class_in_func_decl)15529 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());15530 D.getMutableDeclSpec().ClearStorageClassSpecs();15531 }15532 } else if (getLangOpts().CPlusPlus &&15533 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {15534 SC = SC_Auto;15535 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {15536 Diag(DS.getStorageClassSpecLoc(),15537 diag::err_invalid_storage_class_in_func_decl);15538 D.getMutableDeclSpec().ClearStorageClassSpecs();15539 }15540 15541 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())15542 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)15543 << DeclSpec::getSpecifierName(TSCS);15544 if (DS.isInlineSpecified())15545 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)15546 << getLangOpts().CPlusPlus17;15547 if (DS.hasConstexprSpecifier())15548 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)15549 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());15550 15551 DiagnoseFunctionSpecifiers(DS);15552 15553 CheckFunctionOrTemplateParamDeclarator(S, D);15554 15555 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);15556 QualType parmDeclType = TInfo->getType();15557 15558 // Check for redeclaration of parameters, e.g. int foo(int x, int x);15559 const IdentifierInfo *II = D.getIdentifier();15560 if (II) {15561 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,15562 RedeclarationKind::ForVisibleRedeclaration);15563 LookupName(R, S);15564 if (!R.empty()) {15565 NamedDecl *PrevDecl = *R.begin();15566 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {15567 // Maybe we will complain about the shadowed template parameter.15568 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);15569 // Just pretend that we didn't see the previous declaration.15570 PrevDecl = nullptr;15571 }15572 if (PrevDecl && S->isDeclScope(PrevDecl)) {15573 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;15574 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);15575 // Recover by removing the name15576 II = nullptr;15577 D.SetIdentifier(nullptr, D.getIdentifierLoc());15578 D.setInvalidType(true);15579 }15580 }15581 }15582 15583 // Incomplete resource arrays are not allowed as function parameters in HLSL15584 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&15585 parmDeclType->isHLSLResourceRecordArray()) {15586 Diag(D.getIdentifierLoc(),15587 diag::err_hlsl_incomplete_resource_array_in_function_param);15588 D.setInvalidType(true);15589 }15590 15591 // Temporarily put parameter variables in the translation unit, not15592 // the enclosing context. This prevents them from accidentally15593 // looking like class members in C++.15594 ParmVarDecl *New =15595 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),15596 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);15597 15598 if (D.isInvalidType())15599 New->setInvalidDecl();15600 15601 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);15602 15603 assert(S->isFunctionPrototypeScope());15604 assert(S->getFunctionPrototypeDepth() >= 1);15605 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,15606 S->getNextFunctionPrototypeIndex());15607 15608 warnOnCTypeHiddenInCPlusPlus(New);15609 15610 // Add the parameter declaration into this scope.15611 S->AddDecl(New);15612 if (II)15613 IdResolver.AddDecl(New);15614 15615 ProcessDeclAttributes(S, New, D);15616 15617 if (D.getDeclSpec().isModulePrivateSpecified())15618 Diag(New->getLocation(), diag::err_module_private_local)15619 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())15620 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());15621 15622 if (New->hasAttr<BlocksAttr>()) {15623 Diag(New->getLocation(), diag::err_block_on_nonlocal);15624 }15625 15626 if (getLangOpts().OpenCL)15627 deduceOpenCLAddressSpace(New);15628 15629 return New;15630}15631 15632ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,15633 SourceLocation Loc,15634 QualType T) {15635 /* FIXME: setting StartLoc == Loc.15636 Would it be worth to modify callers so as to provide proper source15637 location for the unnamed parameters, embedding the parameter's type? */15638 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,15639 T, Context.getTrivialTypeSourceInfo(T, Loc),15640 SC_None, nullptr);15641 Param->setImplicit();15642 return Param;15643}15644 15645void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {15646 // Don't diagnose unused-parameter errors in template instantiations; we15647 // will already have done so in the template itself.15648 if (inTemplateInstantiation())15649 return;15650 15651 for (const ParmVarDecl *Parameter : Parameters) {15652 if (!Parameter->isReferenced() && Parameter->getDeclName() &&15653 !Parameter->hasAttr<UnusedAttr>() &&15654 !Parameter->getIdentifier()->isPlaceholder()) {15655 Diag(Parameter->getLocation(), diag::warn_unused_parameter)15656 << Parameter->getDeclName();15657 }15658 }15659}15660 15661void Sema::DiagnoseSizeOfParametersAndReturnValue(15662 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {15663 if (LangOpts.NumLargeByValueCopy == 0) // No check.15664 return;15665 15666 // Warn if the return value is pass-by-value and larger than the specified15667 // threshold.15668 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {15669 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();15670 if (Size > LangOpts.NumLargeByValueCopy)15671 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;15672 }15673 15674 // Warn if any parameter is pass-by-value and larger than the specified15675 // threshold.15676 for (const ParmVarDecl *Parameter : Parameters) {15677 QualType T = Parameter->getType();15678 if (T->isDependentType() || !T.isPODType(Context))15679 continue;15680 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();15681 if (Size > LangOpts.NumLargeByValueCopy)15682 Diag(Parameter->getLocation(), diag::warn_parameter_size)15683 << Parameter << Size;15684 }15685}15686 15687ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,15688 SourceLocation NameLoc,15689 const IdentifierInfo *Name, QualType T,15690 TypeSourceInfo *TSInfo, StorageClass SC) {15691 // In ARC, infer a lifetime qualifier for appropriate parameter types.15692 if (getLangOpts().ObjCAutoRefCount &&15693 T.getObjCLifetime() == Qualifiers::OCL_None &&15694 T->isObjCLifetimeType()) {15695 15696 Qualifiers::ObjCLifetime lifetime;15697 15698 // Special cases for arrays:15699 // - if it's const, use __unsafe_unretained15700 // - otherwise, it's an error15701 if (T->isArrayType()) {15702 if (!T.isConstQualified()) {15703 if (DelayedDiagnostics.shouldDelayDiagnostics())15704 DelayedDiagnostics.add(15705 sema::DelayedDiagnostic::makeForbiddenType(15706 NameLoc, diag::err_arc_array_param_no_ownership, T, false));15707 else15708 Diag(NameLoc, diag::err_arc_array_param_no_ownership)15709 << TSInfo->getTypeLoc().getSourceRange();15710 }15711 lifetime = Qualifiers::OCL_ExplicitNone;15712 } else {15713 lifetime = T->getObjCARCImplicitLifetime();15714 }15715 T = Context.getLifetimeQualifiedType(T, lifetime);15716 }15717 15718 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,15719 Context.getAdjustedParameterType(T),15720 TSInfo, SC, nullptr);15721 15722 // Make a note if we created a new pack in the scope of a lambda, so that15723 // we know that references to that pack must also be expanded within the15724 // lambda scope.15725 if (New->isParameterPack())15726 if (auto *CSI = getEnclosingLambdaOrBlock())15727 CSI->LocalPacks.push_back(New);15728 15729 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||15730 New->getType().hasNonTrivialToPrimitiveCopyCUnion())15731 checkNonTrivialCUnion(New->getType(), New->getLocation(),15732 NonTrivialCUnionContext::FunctionParam,15733 NTCUK_Destruct | NTCUK_Copy);15734 15735 // Parameter declarators cannot be interface types. All ObjC objects are15736 // passed by reference.15737 if (T->isObjCObjectType()) {15738 SourceLocation TypeEndLoc =15739 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());15740 Diag(NameLoc,15741 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T15742 << FixItHint::CreateInsertion(TypeEndLoc, "*");15743 T = Context.getObjCObjectPointerType(T);15744 New->setType(T);15745 }15746 15747 // __ptrauth is forbidden on parameters.15748 if (T.getPointerAuth()) {15749 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;15750 New->setInvalidDecl();15751 }15752 15753 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage15754 // duration shall not be qualified by an address-space qualifier."15755 // Since all parameters have automatic store duration, they can not have15756 // an address space.15757 if (T.getAddressSpace() != LangAS::Default &&15758 // OpenCL allows function arguments declared to be an array of a type15759 // to be qualified with an address space.15760 !(getLangOpts().OpenCL &&15761 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&15762 // WebAssembly allows reference types as parameters. Funcref in particular15763 // lives in a different address space.15764 !(T->isFunctionPointerType() &&15765 T.getAddressSpace() == LangAS::wasm_funcref)) {15766 Diag(NameLoc, diag::err_arg_with_address_space);15767 New->setInvalidDecl();15768 }15769 15770 // PPC MMA non-pointer types are not allowed as function argument types.15771 if (Context.getTargetInfo().getTriple().isPPC64() &&15772 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {15773 New->setInvalidDecl();15774 }15775 15776 return New;15777}15778 15779void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,15780 SourceLocation LocAfterDecls) {15781 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();15782 15783 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration15784 // in the declaration list shall have at least one declarator, those15785 // declarators shall only declare identifiers from the identifier list, and15786 // every identifier in the identifier list shall be declared.15787 //15788 // C89 3.7.1p5 "If a declarator includes an identifier list, only the15789 // identifiers it names shall be declared in the declaration list."15790 //15791 // This is why we only diagnose in C99 and later. Note, the other conditions15792 // listed are checked elsewhere.15793 if (!FTI.hasPrototype) {15794 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {15795 --i;15796 if (FTI.Params[i].Param == nullptr) {15797 if (getLangOpts().C99) {15798 SmallString<256> Code;15799 llvm::raw_svector_ostream(Code)15800 << " int " << FTI.Params[i].Ident->getName() << ";\n";15801 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)15802 << FTI.Params[i].Ident15803 << FixItHint::CreateInsertion(LocAfterDecls, Code);15804 }15805 15806 // Implicitly declare the argument as type 'int' for lack of a better15807 // type.15808 AttributeFactory attrs;15809 DeclSpec DS(attrs);15810 const char* PrevSpec; // unused15811 unsigned DiagID; // unused15812 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,15813 DiagID, Context.getPrintingPolicy());15814 // Use the identifier location for the type source range.15815 DS.SetRangeStart(FTI.Params[i].IdentLoc);15816 DS.SetRangeEnd(FTI.Params[i].IdentLoc);15817 Declarator ParamD(DS, ParsedAttributesView::none(),15818 DeclaratorContext::KNRTypeList);15819 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);15820 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);15821 }15822 }15823 }15824}15825 15826Decl *15827Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,15828 MultiTemplateParamsArg TemplateParameterLists,15829 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {15830 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");15831 assert(D.isFunctionDeclarator() && "Not a function declarator!");15832 Scope *ParentScope = FnBodyScope->getParent();15833 15834 // Check if we are in an `omp begin/end declare variant` scope. If we are, and15835 // we define a non-templated function definition, we will create a declaration15836 // instead (=BaseFD), and emit the definition with a mangled name afterwards.15837 // The base function declaration will have the equivalent of an `omp declare15838 // variant` annotation which specifies the mangled definition as a15839 // specialization function under the OpenMP context defined as part of the15840 // `omp begin declare variant`.15841 SmallVector<FunctionDecl *, 4> Bases;15842 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())15843 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(15844 ParentScope, D, TemplateParameterLists, Bases);15845 15846 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);15847 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);15848 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);15849 15850 if (!Bases.empty())15851 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl,15852 Bases);15853 15854 return Dcl;15855}15856 15857void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {15858 Consumer.HandleInlineFunctionDefinition(D);15859}15860 15861static bool FindPossiblePrototype(const FunctionDecl *FD,15862 const FunctionDecl *&PossiblePrototype) {15863 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;15864 Prev = Prev->getPreviousDecl()) {15865 // Ignore any declarations that occur in function or method15866 // scope, because they aren't visible from the header.15867 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())15868 continue;15869 15870 PossiblePrototype = Prev;15871 return Prev->getType()->isFunctionProtoType();15872 }15873 return false;15874}15875 15876static bool15877ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,15878 const FunctionDecl *&PossiblePrototype) {15879 // Don't warn about invalid declarations.15880 if (FD->isInvalidDecl())15881 return false;15882 15883 // Or declarations that aren't global.15884 if (!FD->isGlobal())15885 return false;15886 15887 // Don't warn about C++ member functions.15888 if (isa<CXXMethodDecl>(FD))15889 return false;15890 15891 // Don't warn about 'main'.15892 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))15893 if (IdentifierInfo *II = FD->getIdentifier())15894 if (II->isStr("main") || II->isStr("efi_main"))15895 return false;15896 15897 if (FD->isMSVCRTEntryPoint())15898 return false;15899 15900 // Don't warn about inline functions.15901 if (FD->isInlined())15902 return false;15903 15904 // Don't warn about function templates.15905 if (FD->getDescribedFunctionTemplate())15906 return false;15907 15908 // Don't warn about function template specializations.15909 if (FD->isFunctionTemplateSpecialization())15910 return false;15911 15912 // Don't warn for OpenCL kernels.15913 if (FD->hasAttr<DeviceKernelAttr>())15914 return false;15915 15916 // Don't warn on explicitly deleted functions.15917 if (FD->isDeleted())15918 return false;15919 15920 // Don't warn on implicitly local functions (such as having local-typed15921 // parameters).15922 if (!FD->isExternallyVisible())15923 return false;15924 15925 // If we were able to find a potential prototype, don't warn.15926 if (FindPossiblePrototype(FD, PossiblePrototype))15927 return false;15928 15929 return true;15930}15931 15932void15933Sema::CheckForFunctionRedefinition(FunctionDecl *FD,15934 const FunctionDecl *EffectiveDefinition,15935 SkipBodyInfo *SkipBody) {15936 const FunctionDecl *Definition = EffectiveDefinition;15937 if (!Definition &&15938 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))15939 return;15940 15941 if (Definition->getFriendObjectKind() != Decl::FOK_None) {15942 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {15943 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {15944 // A merged copy of the same function, instantiated as a member of15945 // the same class, is OK.15946 if (declaresSameEntity(OrigFD, OrigDef) &&15947 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),15948 cast<Decl>(FD->getLexicalDeclContext())))15949 return;15950 }15951 }15952 }15953 15954 if (canRedefineFunction(Definition, getLangOpts()))15955 return;15956 15957 // Don't emit an error when this is redefinition of a typo-corrected15958 // definition.15959 if (TypoCorrectedFunctionDefinitions.count(Definition))15960 return;15961 15962 bool DefinitionVisible = false;15963 if (SkipBody && isRedefinitionAllowedFor(Definition, DefinitionVisible) &&15964 (Definition->getFormalLinkage() == Linkage::Internal ||15965 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||15966 Definition->getNumTemplateParameterLists())) {15967 SkipBody->ShouldSkip = true;15968 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);15969 if (!DefinitionVisible) {15970 if (auto *TD = Definition->getDescribedFunctionTemplate())15971 makeMergedDefinitionVisible(TD);15972 makeMergedDefinitionVisible(const_cast<FunctionDecl *>(Definition));15973 }15974 return;15975 }15976 15977 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&15978 Definition->getStorageClass() == SC_Extern)15979 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)15980 << FD << getLangOpts().CPlusPlus;15981 else15982 Diag(FD->getLocation(), diag::err_redefinition) << FD;15983 15984 Diag(Definition->getLocation(), diag::note_previous_definition);15985 FD->setInvalidDecl();15986}15987 15988LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {15989 CXXRecordDecl *LambdaClass = CallOperator->getParent();15990 15991 LambdaScopeInfo *LSI = PushLambdaScope();15992 LSI->CallOperator = CallOperator;15993 LSI->Lambda = LambdaClass;15994 LSI->ReturnType = CallOperator->getReturnType();15995 // When this function is called in situation where the context of the call15996 // operator is not entered, we set AfterParameterList to false, so that15997 // `tryCaptureVariable` finds explicit captures in the appropriate context.15998 // There is also at least a situation as in FinishTemplateArgumentDeduction(),15999 // where we would set the CurContext to the lambda operator before16000 // substituting into it. In this case the flag needs to be true such that16001 // tryCaptureVariable can correctly handle potential captures thereof.16002 LSI->AfterParameterList = CurContext == CallOperator;16003 16004 // GLTemplateParameterList is necessary for getCurGenericLambda() which is16005 // used at the point of dealing with potential captures.16006 //16007 // We don't use LambdaClass->isGenericLambda() because this value doesn't16008 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are16009 // associated. (Technically, we could recover that list from their16010 // instantiation patterns, but for now, the GLTemplateParameterList seems16011 // unnecessary in these cases.)16012 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())16013 LSI->GLTemplateParameterList = FTD->getTemplateParameters();16014 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();16015 16016 if (LCD == LCD_None)16017 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;16018 else if (LCD == LCD_ByCopy)16019 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;16020 else if (LCD == LCD_ByRef)16021 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;16022 DeclarationNameInfo DNI = CallOperator->getNameInfo();16023 16024 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();16025 LSI->Mutable = !CallOperator->isConst();16026 if (CallOperator->isExplicitObjectMemberFunction())16027 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);16028 16029 // Add the captures to the LSI so they can be noted as already16030 // captured within tryCaptureVar.16031 auto I = LambdaClass->field_begin();16032 for (const auto &C : LambdaClass->captures()) {16033 if (C.capturesVariable()) {16034 ValueDecl *VD = C.getCapturedVar();16035 if (VD->isInitCapture())16036 CurrentInstantiationScope->InstantiatedLocal(VD, VD);16037 const bool ByRef = C.getCaptureKind() == LCK_ByRef;16038 LSI->addCapture(VD, /*IsBlock*/false, ByRef,16039 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),16040 /*EllipsisLoc*/C.isPackExpansion()16041 ? C.getEllipsisLoc() : SourceLocation(),16042 I->getType(), /*Invalid*/false);16043 16044 } else if (C.capturesThis()) {16045 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),16046 C.getCaptureKind() == LCK_StarThis);16047 } else {16048 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),16049 I->getType());16050 }16051 ++I;16052 }16053 return LSI;16054}16055 16056Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,16057 SkipBodyInfo *SkipBody,16058 FnBodyKind BodyKind) {16059 if (!D) {16060 // Parsing the function declaration failed in some way. Push on a fake scope16061 // anyway so we can try to parse the function body.16062 PushFunctionScope();16063 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);16064 return D;16065 }16066 16067 FunctionDecl *FD = nullptr;16068 16069 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))16070 FD = FunTmpl->getTemplatedDecl();16071 else16072 FD = cast<FunctionDecl>(D);16073 16074 // Do not push if it is a lambda because one is already pushed when building16075 // the lambda in ActOnStartOfLambdaDefinition().16076 if (!isLambdaCallOperator(FD))16077 PushExpressionEvaluationContextForFunction(ExprEvalContexts.back().Context,16078 FD);16079 16080 // Check for defining attributes before the check for redefinition.16081 if (const auto *Attr = FD->getAttr<AliasAttr>()) {16082 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;16083 FD->dropAttr<AliasAttr>();16084 FD->setInvalidDecl();16085 }16086 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {16087 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;16088 FD->dropAttr<IFuncAttr>();16089 FD->setInvalidDecl();16090 }16091 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {16092 if (Context.getTargetInfo().getTriple().isAArch64() &&16093 !Context.getTargetInfo().hasFeature("fmv") &&16094 !Attr->isDefaultVersion()) {16095 // If function multi versioning disabled skip parsing function body16096 // defined with non-default target_version attribute16097 if (SkipBody)16098 SkipBody->ShouldSkip = true;16099 return nullptr;16100 }16101 }16102 16103 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {16104 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&16105 Ctor->isDefaultConstructor() &&16106 Context.getTargetInfo().getCXXABI().isMicrosoft()) {16107 // If this is an MS ABI dllexport default constructor, instantiate any16108 // default arguments.16109 InstantiateDefaultCtorDefaultArgs(Ctor);16110 }16111 }16112 16113 // See if this is a redefinition. If 'will have body' (or similar) is already16114 // set, then these checks were already performed when it was set.16115 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&16116 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {16117 CheckForFunctionRedefinition(FD, nullptr, SkipBody);16118 16119 // If we're skipping the body, we're done. Don't enter the scope.16120 if (SkipBody && SkipBody->ShouldSkip)16121 return D;16122 }16123 16124 // Mark this function as "will have a body eventually". This lets users to16125 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing16126 // this function.16127 FD->setWillHaveBody();16128 16129 // If we are instantiating a generic lambda call operator, push16130 // a LambdaScopeInfo onto the function stack. But use the information16131 // that's already been calculated (ActOnLambdaExpr) to prime the current16132 // LambdaScopeInfo.16133 // When the template operator is being specialized, the LambdaScopeInfo,16134 // has to be properly restored so that tryCaptureVariable doesn't try16135 // and capture any new variables. In addition when calculating potential16136 // captures during transformation of nested lambdas, it is necessary to16137 // have the LSI properly restored.16138 if (isGenericLambdaCallOperatorSpecialization(FD)) {16139 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly16140 // instantiated, explicitly specialized.16141 if (FD->getTemplateSpecializationInfo()16142 ->isExplicitInstantiationOrSpecialization()) {16143 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);16144 FD->setInvalidDecl();16145 PushFunctionScope();16146 } else {16147 assert(inTemplateInstantiation() &&16148 "There should be an active template instantiation on the stack "16149 "when instantiating a generic lambda!");16150 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));16151 }16152 } else {16153 // Enter a new function scope16154 PushFunctionScope();16155 }16156 16157 // Builtin functions cannot be defined.16158 if (unsigned BuiltinID = FD->getBuiltinID()) {16159 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&16160 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {16161 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;16162 FD->setInvalidDecl();16163 }16164 }16165 16166 // The return type of a function definition must be complete (C99 6.9.1p3).16167 // C++23 [dcl.fct.def.general]/p216168 // The type of [...] the return for a function definition16169 // shall not be a (possibly cv-qualified) class type that is incomplete16170 // or abstract within the function body unless the function is deleted.16171 QualType ResultType = FD->getReturnType();16172 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&16173 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&16174 (RequireCompleteType(FD->getLocation(), ResultType,16175 diag::err_func_def_incomplete_result) ||16176 RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),16177 diag::err_abstract_type_in_decl,16178 AbstractReturnType)))16179 FD->setInvalidDecl();16180 16181 if (FnBodyScope)16182 PushDeclContext(FnBodyScope, FD);16183 16184 // Check the validity of our function parameters16185 if (BodyKind != FnBodyKind::Delete)16186 CheckParmsForFunctionDef(FD->parameters(),16187 /*CheckParameterNames=*/true);16188 16189 // Add non-parameter declarations already in the function to the current16190 // scope.16191 if (FnBodyScope) {16192 for (Decl *NPD : FD->decls()) {16193 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);16194 if (!NonParmDecl)16195 continue;16196 assert(!isa<ParmVarDecl>(NonParmDecl) &&16197 "parameters should not be in newly created FD yet");16198 16199 // If the decl has a name, make it accessible in the current scope.16200 if (NonParmDecl->getDeclName())16201 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);16202 16203 // Similarly, dive into enums and fish their constants out, making them16204 // accessible in this scope.16205 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {16206 for (auto *EI : ED->enumerators())16207 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);16208 }16209 }16210 }16211 16212 // Introduce our parameters into the function scope16213 for (auto *Param : FD->parameters()) {16214 Param->setOwningFunction(FD);16215 16216 // If this has an identifier, add it to the scope stack.16217 if (Param->getIdentifier() && FnBodyScope) {16218 CheckShadow(FnBodyScope, Param);16219 16220 PushOnScopeChains(Param, FnBodyScope);16221 }16222 }16223 16224 // C++ [module.import/6]16225 // ...16226 // A header unit shall not contain a definition of a non-inline function or16227 // variable whose name has external linkage.16228 //16229 // Deleted and Defaulted functions are implicitly inline (but the16230 // inline state is not set at this point, so check the BodyKind explicitly).16231 // We choose to allow weak & selectany definitions, as they are common in16232 // headers, and have semantics similar to inline definitions which are allowed16233 // in header units.16234 // FIXME: Consider an alternate location for the test where the inlined()16235 // state is complete.16236 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&16237 !FD->isInvalidDecl() && !FD->isInlined() &&16238 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&16239 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&16240 !FD->isTemplateInstantiation() &&16241 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {16242 assert(FD->isThisDeclarationADefinition());16243 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);16244 FD->setInvalidDecl();16245 }16246 16247 // Ensure that the function's exception specification is instantiated.16248 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())16249 ResolveExceptionSpec(D->getLocation(), FPT);16250 16251 // dllimport cannot be applied to non-inline function definitions.16252 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&16253 !FD->isTemplateInstantiation()) {16254 assert(!FD->hasAttr<DLLExportAttr>());16255 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);16256 FD->setInvalidDecl();16257 return D;16258 }16259 16260 // Some function attributes (like OptimizeNoneAttr) need actions before16261 // parsing body started.16262 applyFunctionAttributesBeforeParsingBody(D);16263 16264 // We want to attach documentation to original Decl (which might be16265 // a function template).16266 ActOnDocumentableDecl(D);16267 if (getCurLexicalContext()->isObjCContainer() &&16268 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&16269 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)16270 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);16271 16272 maybeAddDeclWithEffects(FD);16273 16274 return D;16275}16276 16277void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {16278 if (!FD || FD->isInvalidDecl())16279 return;16280 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))16281 FD = TD->getTemplatedDecl();16282 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {16283 FPOptionsOverride FPO;16284 FPO.setDisallowOptimizations();16285 CurFPFeatures.applyChanges(FPO);16286 FpPragmaStack.CurrentValue =16287 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));16288 }16289}16290 16291void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {16292 ReturnStmt **Returns = Scope->Returns.data();16293 16294 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {16295 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {16296 if (!NRVOCandidate->isNRVOVariable()) {16297 Diag(Returns[I]->getRetValue()->getExprLoc(),16298 diag::warn_not_eliding_copy_on_return);16299 Returns[I]->setNRVOCandidate(nullptr);16300 }16301 }16302 }16303}16304 16305bool Sema::canDelayFunctionBody(const Declarator &D) {16306 // We can't delay parsing the body of a constexpr function template (yet).16307 if (D.getDeclSpec().hasConstexprSpecifier())16308 return false;16309 16310 // We can't delay parsing the body of a function template with a deduced16311 // return type (yet).16312 if (D.getDeclSpec().hasAutoTypeSpec()) {16313 // If the placeholder introduces a non-deduced trailing return type,16314 // we can still delay parsing it.16315 if (D.getNumTypeObjects()) {16316 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);16317 if (Outer.Kind == DeclaratorChunk::Function &&16318 Outer.Fun.hasTrailingReturnType()) {16319 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());16320 return Ty.isNull() || !Ty->isUndeducedType();16321 }16322 }16323 return false;16324 }16325 16326 return true;16327}16328 16329bool Sema::canSkipFunctionBody(Decl *D) {16330 // We cannot skip the body of a function (or function template) which is16331 // constexpr, since we may need to evaluate its body in order to parse the16332 // rest of the file.16333 // We cannot skip the body of a function with an undeduced return type,16334 // because any callers of that function need to know the type.16335 if (const FunctionDecl *FD = D->getAsFunction()) {16336 if (FD->isConstexpr())16337 return false;16338 // We can't simply call Type::isUndeducedType here, because inside template16339 // auto can be deduced to a dependent type, which is not considered16340 // "undeduced".16341 if (FD->getReturnType()->getContainedDeducedType())16342 return false;16343 }16344 return Consumer.shouldSkipFunctionBody(D);16345}16346 16347Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {16348 if (!Decl)16349 return nullptr;16350 if (FunctionDecl *FD = Decl->getAsFunction())16351 FD->setHasSkippedBody();16352 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))16353 MD->setHasSkippedBody();16354 return Decl;16355}16356 16357/// RAII object that pops an ExpressionEvaluationContext when exiting a function16358/// body.16359class ExitFunctionBodyRAII {16360public:16361 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}16362 ~ExitFunctionBodyRAII() {16363 if (!IsLambda)16364 S.PopExpressionEvaluationContext();16365 }16366 16367private:16368 Sema &S;16369 bool IsLambda = false;16370};16371 16372static void diagnoseImplicitlyRetainedSelf(Sema &S) {16373 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;16374 16375 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {16376 auto [It, Inserted] = EscapeInfo.try_emplace(BD);16377 if (!Inserted)16378 return It->second;16379 16380 bool R = false;16381 const BlockDecl *CurBD = BD;16382 16383 do {16384 R = !CurBD->doesNotEscape();16385 if (R)16386 break;16387 CurBD = CurBD->getParent()->getInnermostBlockDecl();16388 } while (CurBD);16389 16390 return It->second = R;16391 };16392 16393 // If the location where 'self' is implicitly retained is inside a escaping16394 // block, emit a diagnostic.16395 for (const std::pair<SourceLocation, const BlockDecl *> &P :16396 S.ImplicitlyRetainedSelfLocs)16397 if (IsOrNestedInEscapingBlock(P.second))16398 S.Diag(P.first, diag::warn_implicitly_retains_self)16399 << FixItHint::CreateInsertion(P.first, "self->");16400}16401 16402static bool methodHasName(const FunctionDecl *FD, StringRef Name) {16403 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&16404 FD->getDeclName().isIdentifier() && FD->getName() == Name;16405}16406 16407bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {16408 return methodHasName(FD, "get_return_object");16409}16410 16411bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {16412 return FD->isStatic() &&16413 methodHasName(FD, "get_return_object_on_allocation_failure");16414}16415 16416void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {16417 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();16418 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())16419 return;16420 // Allow some_promise_type::get_return_object().16421 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))16422 return;16423 if (!FD->hasAttr<CoroWrapperAttr>())16424 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;16425}16426 16427Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,16428 bool RetainFunctionScopeInfo) {16429 FunctionScopeInfo *FSI = getCurFunction();16430 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;16431 16432 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())16433 FD->addAttr(StrictFPAttr::CreateImplicit(Context));16434 16435 SourceLocation AnalysisLoc;16436 if (Body)16437 AnalysisLoc = Body->getEndLoc();16438 else if (FD)16439 AnalysisLoc = FD->getEndLoc();16440 sema::AnalysisBasedWarnings::Policy WP =16441 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);16442 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;16443 16444 // If we skip function body, we can't tell if a function is a coroutine.16445 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {16446 if (FSI->isCoroutine())16447 CheckCompletedCoroutineBody(FD, Body);16448 else16449 CheckCoroutineWrapper(FD);16450 }16451 16452 // Diagnose invalid SYCL kernel entry point function declarations16453 // and build SYCLKernelCallStmts for valid ones.16454 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {16455 SYCLKernelEntryPointAttr *SKEPAttr =16456 FD->getAttr<SYCLKernelEntryPointAttr>();16457 if (FD->isDefaulted()) {16458 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)16459 << SKEPAttr << /*defaulted function*/ 3;16460 SKEPAttr->setInvalidAttr();16461 } else if (FD->isDeleted()) {16462 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)16463 << SKEPAttr << /*deleted function*/ 2;16464 SKEPAttr->setInvalidAttr();16465 } else if (FSI->isCoroutine()) {16466 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)16467 << SKEPAttr << /*coroutine*/ 7;16468 SKEPAttr->setInvalidAttr();16469 } else if (Body && isa<CXXTryStmt>(Body)) {16470 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)16471 << SKEPAttr << /*function defined with a function try block*/ 8;16472 SKEPAttr->setInvalidAttr();16473 }16474 16475 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {16476 StmtResult SR =16477 SYCL().BuildSYCLKernelCallStmt(FD, cast<CompoundStmt>(Body));16478 if (SR.isInvalid())16479 return nullptr;16480 Body = SR.get();16481 }16482 }16483 16484 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {16485 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();16486 if (FD->isDeletedAsWritten())16487 Diag(SEAttr->getLocation(),16488 diag::err_sycl_external_invalid_deleted_function)16489 << SEAttr;16490 }16491 16492 {16493 // Do not call PopExpressionEvaluationContext() if it is a lambda because16494 // one is already popped when finishing the lambda in BuildLambdaExpr().16495 // This is meant to pop the context added in ActOnStartOfFunctionDef().16496 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));16497 if (FD) {16498 // The function body and the DefaultedOrDeletedInfo, if present, use16499 // the same storage; don't overwrite the latter if the former is null16500 // (the body is initialised to null anyway, so even if the latter isn't16501 // present, this would still be a no-op).16502 if (Body)16503 FD->setBody(Body);16504 FD->setWillHaveBody(false);16505 16506 if (getLangOpts().CPlusPlus14) {16507 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&16508 FD->getReturnType()->isUndeducedType()) {16509 // For a function with a deduced result type to return void,16510 // the result type as written must be 'auto' or 'decltype(auto)',16511 // possibly cv-qualified or constrained, but not ref-qualified.16512 if (!FD->getReturnType()->getAs<AutoType>()) {16513 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)16514 << FD->getReturnType();16515 FD->setInvalidDecl();16516 } else {16517 // Falling off the end of the function is the same as 'return;'.16518 Expr *Dummy = nullptr;16519 if (DeduceFunctionTypeFromReturnExpr(16520 FD, dcl->getLocation(), Dummy,16521 FD->getReturnType()->getAs<AutoType>()))16522 FD->setInvalidDecl();16523 }16524 }16525 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {16526 // In C++11, we don't use 'auto' deduction rules for lambda call16527 // operators because we don't support return type deduction.16528 auto *LSI = getCurLambda();16529 if (LSI->HasImplicitReturnType) {16530 deduceClosureReturnType(*LSI);16531 16532 // C++11 [expr.prim.lambda]p4:16533 // [...] if there are no return statements in the compound-statement16534 // [the deduced type is] the type void16535 QualType RetType =16536 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;16537 16538 // Update the return type to the deduced type.16539 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();16540 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),16541 Proto->getExtProtoInfo()));16542 }16543 }16544 16545 // If the function implicitly returns zero (like 'main') or is naked,16546 // don't complain about missing return statements.16547 // Clang implicitly returns 0 in C89 mode, but that's considered an16548 // extension. The check is necessary to ensure the expected extension16549 // warning is emitted in C89 mode.16550 if ((FD->hasImplicitReturnZero() &&16551 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||16552 FD->hasAttr<NakedAttr>())16553 WP.disableCheckFallThrough();16554 16555 // MSVC permits the use of pure specifier (=0) on function definition,16556 // defined at class scope, warn about this non-standard construct.16557 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&16558 !FD->isOutOfLine())16559 Diag(FD->getLocation(), diag::ext_pure_function_definition);16560 16561 if (!FD->isInvalidDecl()) {16562 // Don't diagnose unused parameters of defaulted, deleted or naked16563 // functions.16564 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&16565 !FD->hasAttr<NakedAttr>())16566 DiagnoseUnusedParameters(FD->parameters());16567 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),16568 FD->getReturnType(), FD);16569 16570 // If this is a structor, we need a vtable.16571 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))16572 MarkVTableUsed(FD->getLocation(), Constructor->getParent());16573 else if (CXXDestructorDecl *Destructor =16574 dyn_cast<CXXDestructorDecl>(FD))16575 MarkVTableUsed(FD->getLocation(), Destructor->getParent());16576 16577 // Try to apply the named return value optimization. We have to check16578 // if we can do this here because lambdas keep return statements around16579 // to deduce an implicit return type.16580 if (FD->getReturnType()->isRecordType() &&16581 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))16582 computeNRVO(Body, FSI);16583 }16584 16585 // GNU warning -Wmissing-prototypes:16586 // Warn if a global function is defined without a previous16587 // prototype declaration. This warning is issued even if the16588 // definition itself provides a prototype. The aim is to detect16589 // global functions that fail to be declared in header files.16590 const FunctionDecl *PossiblePrototype = nullptr;16591 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {16592 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;16593 16594 if (PossiblePrototype) {16595 // We found a declaration that is not a prototype,16596 // but that could be a zero-parameter prototype16597 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {16598 TypeLoc TL = TI->getTypeLoc();16599 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())16600 Diag(PossiblePrototype->getLocation(),16601 diag::note_declaration_not_a_prototype)16602 << (FD->getNumParams() != 0)16603 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(16604 FTL.getRParenLoc(), "void")16605 : FixItHint{});16606 }16607 } else {16608 // Returns true if the token beginning at this Loc is `const`.16609 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,16610 const LangOptions &LangOpts) {16611 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);16612 if (LocInfo.first.isInvalid())16613 return false;16614 16615 bool Invalid = false;16616 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);16617 if (Invalid)16618 return false;16619 16620 if (LocInfo.second > Buffer.size())16621 return false;16622 16623 const char *LexStart = Buffer.data() + LocInfo.second;16624 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);16625 16626 return StartTok.consume_front("const") &&16627 (StartTok.empty() || isWhitespace(StartTok[0]) ||16628 StartTok.starts_with("/*") || StartTok.starts_with("//"));16629 };16630 16631 auto findBeginLoc = [&]() {16632 // If the return type has `const` qualifier, we want to insert16633 // `static` before `const` (and not before the typename).16634 if ((FD->getReturnType()->isAnyPointerType() &&16635 FD->getReturnType()->getPointeeType().isConstQualified()) ||16636 FD->getReturnType().isConstQualified()) {16637 // But only do this if we can determine where the `const` is.16638 16639 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),16640 getLangOpts()))16641 16642 return FD->getBeginLoc();16643 }16644 return FD->getTypeSpecStartLoc();16645 };16646 Diag(FD->getTypeSpecStartLoc(),16647 diag::note_static_for_internal_linkage)16648 << /* function */ 116649 << (FD->getStorageClass() == SC_None16650 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")16651 : FixItHint{});16652 }16653 }16654 16655 // We might not have found a prototype because we didn't wish to warn on16656 // the lack of a missing prototype. Try again without the checks for16657 // whether we want to warn on the missing prototype.16658 if (!PossiblePrototype)16659 (void)FindPossiblePrototype(FD, PossiblePrototype);16660 16661 // If the function being defined does not have a prototype, then we may16662 // need to diagnose it as changing behavior in C23 because we now know16663 // whether the function accepts arguments or not. This only handles the16664 // case where the definition has no prototype but does have parameters16665 // and either there is no previous potential prototype, or the previous16666 // potential prototype also has no actual prototype. This handles cases16667 // like:16668 // void f(); void f(a) int a; {}16669 // void g(a) int a; {}16670 // See MergeFunctionDecl() for other cases of the behavior change16671 // diagnostic. See GetFullTypeForDeclarator() for handling of a function16672 // type without a prototype.16673 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&16674 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&16675 !PossiblePrototype->isImplicit()))) {16676 // The function definition has parameters, so this will change behavior16677 // in C23. If there is a possible prototype, it comes before the16678 // function definition.16679 // FIXME: The declaration may have already been diagnosed as being16680 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but16681 // there's no way to test for the "changes behavior" condition in16682 // SemaType.cpp when forming the declaration's function type. So, we do16683 // this awkward dance instead.16684 //16685 // If we have a possible prototype and it declares a function with a16686 // prototype, we don't want to diagnose it; if we have a possible16687 // prototype and it has no prototype, it may have already been16688 // diagnosed in SemaType.cpp as deprecated depending on whether16689 // -Wstrict-prototypes is enabled. If we already warned about it being16690 // deprecated, add a note that it also changes behavior. If we didn't16691 // warn about it being deprecated (because the diagnostic is not16692 // enabled), warn now that it is deprecated and changes behavior.16693 16694 // This K&R C function definition definitely changes behavior in C23,16695 // so diagnose it.16696 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)16697 << /*definition*/ 1 << /* not supported in C23 */ 0;16698 16699 // If we have a possible prototype for the function which is a user-16700 // visible declaration, we already tested that it has no prototype.16701 // This will change behavior in C23. This gets a warning rather than a16702 // note because it's the same behavior-changing problem as with the16703 // definition.16704 if (PossiblePrototype)16705 Diag(PossiblePrototype->getLocation(),16706 diag::warn_non_prototype_changes_behavior)16707 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 116708 << /*definition*/ 1;16709 }16710 16711 // Warn on CPUDispatch with an actual body.16712 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)16713 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))16714 if (!CmpndBody->body_empty())16715 Diag(CmpndBody->body_front()->getBeginLoc(),16716 diag::warn_dispatch_body_ignored);16717 16718 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {16719 const CXXMethodDecl *KeyFunction;16720 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&16721 MD->isVirtual() &&16722 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&16723 MD == KeyFunction->getCanonicalDecl()) {16724 // Update the key-function state if necessary for this ABI.16725 if (FD->isInlined() &&16726 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {16727 Context.setNonKeyFunction(MD);16728 16729 // If the newly-chosen key function is already defined, then we16730 // need to mark the vtable as used retroactively.16731 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());16732 const FunctionDecl *Definition;16733 if (KeyFunction && KeyFunction->isDefined(Definition))16734 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);16735 } else {16736 // We just defined they key function; mark the vtable as used.16737 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);16738 }16739 }16740 }16741 16742 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&16743 "Function parsing confused");16744 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {16745 assert(MD == getCurMethodDecl() && "Method parsing confused");16746 MD->setBody(Body);16747 if (!MD->isInvalidDecl()) {16748 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),16749 MD->getReturnType(), MD);16750 16751 if (Body)16752 computeNRVO(Body, FSI);16753 }16754 if (FSI->ObjCShouldCallSuper) {16755 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)16756 << MD->getSelector().getAsString();16757 FSI->ObjCShouldCallSuper = false;16758 }16759 if (FSI->ObjCWarnForNoDesignatedInitChain) {16760 const ObjCMethodDecl *InitMethod = nullptr;16761 bool isDesignated =16762 MD->isDesignatedInitializerForTheInterface(&InitMethod);16763 assert(isDesignated && InitMethod);16764 (void)isDesignated;16765 16766 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {16767 auto IFace = MD->getClassInterface();16768 if (!IFace)16769 return false;16770 auto SuperD = IFace->getSuperClass();16771 if (!SuperD)16772 return false;16773 return SuperD->getIdentifier() ==16774 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);16775 };16776 // Don't issue this warning for unavailable inits or direct subclasses16777 // of NSObject.16778 if (!MD->isUnavailable() && !superIsNSObject(MD)) {16779 Diag(MD->getLocation(),16780 diag::warn_objc_designated_init_missing_super_call);16781 Diag(InitMethod->getLocation(),16782 diag::note_objc_designated_init_marked_here);16783 }16784 FSI->ObjCWarnForNoDesignatedInitChain = false;16785 }16786 if (FSI->ObjCWarnForNoInitDelegation) {16787 // Don't issue this warning for unavailable inits.16788 if (!MD->isUnavailable())16789 Diag(MD->getLocation(),16790 diag::warn_objc_secondary_init_missing_init_call);16791 FSI->ObjCWarnForNoInitDelegation = false;16792 }16793 16794 diagnoseImplicitlyRetainedSelf(*this);16795 } else {16796 // Parsing the function declaration failed in some way. Pop the fake scope16797 // we pushed on.16798 PopFunctionScopeInfo(ActivePolicy, dcl);16799 return nullptr;16800 }16801 16802 if (Body && FSI->HasPotentialAvailabilityViolations)16803 DiagnoseUnguardedAvailabilityViolations(dcl);16804 16805 assert(!FSI->ObjCShouldCallSuper &&16806 "This should only be set for ObjC methods, which should have been "16807 "handled in the block above.");16808 16809 // Verify and clean out per-function state.16810 if (Body && (!FD || !FD->isDefaulted())) {16811 // C++ constructors that have function-try-blocks can't have return16812 // statements in the handlers of that block. (C++ [except.handle]p14)16813 // Verify this.16814 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))16815 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));16816 16817 // Verify that gotos and switch cases don't jump into scopes illegally.16818 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())16819 DiagnoseInvalidJumps(Body);16820 16821 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {16822 if (!Destructor->getParent()->isDependentType())16823 CheckDestructor(Destructor);16824 16825 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),16826 Destructor->getParent());16827 }16828 16829 // If any errors have occurred, clear out any temporaries that may have16830 // been leftover. This ensures that these temporaries won't be picked up16831 // for deletion in some later function.16832 if (hasUncompilableErrorOccurred() ||16833 hasAnyUnrecoverableErrorsInThisFunction() ||16834 getDiagnostics().getSuppressAllDiagnostics()) {16835 DiscardCleanupsInEvaluationContext();16836 }16837 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {16838 // Since the body is valid, issue any analysis-based warnings that are16839 // enabled.16840 ActivePolicy = &WP;16841 }16842 16843 if (!IsInstantiation && FD &&16844 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&16845 !FD->isInvalidDecl() &&16846 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))16847 FD->setInvalidDecl();16848 16849 if (FD && FD->hasAttr<NakedAttr>()) {16850 for (const Stmt *S : Body->children()) {16851 // Allow local register variables without initializer as they don't16852 // require prologue.16853 bool RegisterVariables = false;16854 if (auto *DS = dyn_cast<DeclStmt>(S)) {16855 for (const auto *Decl : DS->decls()) {16856 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {16857 RegisterVariables =16858 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();16859 if (!RegisterVariables)16860 break;16861 }16862 }16863 }16864 if (RegisterVariables)16865 continue;16866 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {16867 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);16868 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);16869 FD->setInvalidDecl();16870 break;16871 }16872 }16873 }16874 16875 assert(ExprCleanupObjects.size() ==16876 ExprEvalContexts.back().NumCleanupObjects &&16877 "Leftover temporaries in function");16878 assert(!Cleanup.exprNeedsCleanups() &&16879 "Unaccounted cleanups in function");16880 assert(MaybeODRUseExprs.empty() &&16881 "Leftover expressions for odr-use checking");16882 }16883 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop16884 // the declaration context below. Otherwise, we're unable to transform16885 // 'this' expressions when transforming immediate context functions.16886 16887 if (FD)16888 CheckImmediateEscalatingFunctionDefinition(FD, getCurFunction());16889 16890 if (!IsInstantiation)16891 PopDeclContext();16892 16893 if (!RetainFunctionScopeInfo)16894 PopFunctionScopeInfo(ActivePolicy, dcl);16895 // If any errors have occurred, clear out any temporaries that may have16896 // been leftover. This ensures that these temporaries won't be picked up for16897 // deletion in some later function.16898 if (hasUncompilableErrorOccurred()) {16899 DiscardCleanupsInEvaluationContext();16900 }16901 16902 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||16903 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {16904 auto ES = getEmissionStatus(FD);16905 if (ES == Sema::FunctionEmissionStatus::Emitted ||16906 ES == Sema::FunctionEmissionStatus::Unknown)16907 DeclsToCheckForDeferredDiags.insert(FD);16908 }16909 16910 if (FD && !FD->isDeleted())16911 checkTypeSupport(FD->getType(), FD->getLocation(), FD);16912 16913 return dcl;16914}16915 16916/// When we finish delayed parsing of an attribute, we must attach it to the16917/// relevant Decl.16918void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,16919 ParsedAttributes &Attrs) {16920 // Always attach attributes to the underlying decl.16921 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))16922 D = TD->getTemplatedDecl();16923 ProcessDeclAttributeList(S, D, Attrs);16924 ProcessAPINotes(D);16925 16926 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))16927 if (Method->isStatic())16928 checkThisInStaticMemberFunctionAttributes(Method);16929}16930 16931NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,16932 IdentifierInfo &II, Scope *S) {16933 // It is not valid to implicitly define a function in C23.16934 assert(LangOpts.implicitFunctionsAllowed() &&16935 "Implicit function declarations aren't allowed in this language mode");16936 16937 // Find the scope in which the identifier is injected and the corresponding16938 // DeclContext.16939 // FIXME: C89 does not say what happens if there is no enclosing block scope.16940 // In that case, we inject the declaration into the translation unit scope16941 // instead.16942 Scope *BlockScope = S;16943 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())16944 BlockScope = BlockScope->getParent();16945 16946 // Loop until we find a DeclContext that is either a function/method or the16947 // translation unit, which are the only two valid places to implicitly define16948 // a function. This avoids accidentally defining the function within a tag16949 // declaration, for example.16950 Scope *ContextScope = BlockScope;16951 while (!ContextScope->getEntity() ||16952 (!ContextScope->getEntity()->isFunctionOrMethod() &&16953 !ContextScope->getEntity()->isTranslationUnit()))16954 ContextScope = ContextScope->getParent();16955 ContextRAII SavedContext(*this, ContextScope->getEntity());16956 16957 // Before we produce a declaration for an implicitly defined16958 // function, see whether there was a locally-scoped declaration of16959 // this name as a function or variable. If so, use that16960 // (non-visible) declaration, and complain about it.16961 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);16962 if (ExternCPrev) {16963 // We still need to inject the function into the enclosing block scope so16964 // that later (non-call) uses can see it.16965 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);16966 16967 // C89 footnote 38:16968 // If in fact it is not defined as having type "function returning int",16969 // the behavior is undefined.16970 if (!isa<FunctionDecl>(ExternCPrev) ||16971 !Context.typesAreCompatible(16972 cast<FunctionDecl>(ExternCPrev)->getType(),16973 Context.getFunctionNoProtoType(Context.IntTy))) {16974 Diag(Loc, diag::ext_use_out_of_scope_declaration)16975 << ExternCPrev << !getLangOpts().C99;16976 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);16977 return ExternCPrev;16978 }16979 }16980 16981 // Extension in C99 (defaults to error). Legal in C89, but warn about it.16982 unsigned diag_id;16983 if (II.getName().starts_with("__builtin_"))16984 diag_id = diag::warn_builtin_unknown;16985 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.16986 else if (getLangOpts().C99)16987 diag_id = diag::ext_implicit_function_decl_c99;16988 else16989 diag_id = diag::warn_implicit_function_decl;16990 16991 TypoCorrection Corrected;16992 // Because typo correction is expensive, only do it if the implicit16993 // function declaration is going to be treated as an error.16994 //16995 // Perform the correction before issuing the main diagnostic, as some16996 // consumers use typo-correction callbacks to enhance the main diagnostic.16997 if (S && !ExternCPrev &&16998 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {16999 DeclFilterCCC<FunctionDecl> CCC{};17000 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,17001 S, nullptr, CCC, CorrectTypoKind::NonError);17002 }17003 17004 Diag(Loc, diag_id) << &II;17005 if (Corrected) {17006 // If the correction is going to suggest an implicitly defined function,17007 // skip the correction as not being a particularly good idea.17008 bool Diagnose = true;17009 if (const auto *D = Corrected.getCorrectionDecl())17010 Diagnose = !D->isImplicit();17011 if (Diagnose)17012 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),17013 /*ErrorRecovery*/ false);17014 }17015 17016 // If we found a prior declaration of this function, don't bother building17017 // another one. We've already pushed that one into scope, so there's nothing17018 // more to do.17019 if (ExternCPrev)17020 return ExternCPrev;17021 17022 // Set a Declarator for the implicit definition: int foo();17023 const char *Dummy;17024 AttributeFactory attrFactory;17025 DeclSpec DS(attrFactory);17026 unsigned DiagID;17027 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,17028 Context.getPrintingPolicy());17029 (void)Error; // Silence warning.17030 assert(!Error && "Error setting up implicit decl!");17031 SourceLocation NoLoc;17032 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);17033 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,17034 /*IsAmbiguous=*/false,17035 /*LParenLoc=*/NoLoc,17036 /*Params=*/nullptr,17037 /*NumParams=*/0,17038 /*EllipsisLoc=*/NoLoc,17039 /*RParenLoc=*/NoLoc,17040 /*RefQualifierIsLvalueRef=*/true,17041 /*RefQualifierLoc=*/NoLoc,17042 /*MutableLoc=*/NoLoc, EST_None,17043 /*ESpecRange=*/SourceRange(),17044 /*Exceptions=*/nullptr,17045 /*ExceptionRanges=*/nullptr,17046 /*NumExceptions=*/0,17047 /*NoexceptExpr=*/nullptr,17048 /*ExceptionSpecTokens=*/nullptr,17049 /*DeclsInPrototype=*/{}, Loc, Loc,17050 D),17051 std::move(DS.getAttributes()), SourceLocation());17052 D.SetIdentifier(&II, Loc);17053 17054 // Insert this function into the enclosing block scope.17055 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));17056 FD->setImplicit();17057 17058 AddKnownFunctionAttributes(FD);17059 17060 return FD;17061}17062 17063void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(17064 FunctionDecl *FD) {17065 if (FD->isInvalidDecl())17066 return;17067 17068 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&17069 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)17070 return;17071 17072 UnsignedOrNone AlignmentParam = std::nullopt;17073 bool IsNothrow = false;17074 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))17075 return;17076 17077 // C++2a [basic.stc.dynamic.allocation]p4:17078 // An allocation function that has a non-throwing exception specification17079 // indicates failure by returning a null pointer value. Any other allocation17080 // function never returns a null pointer value and indicates failure only by17081 // throwing an exception [...]17082 //17083 // However, -fcheck-new invalidates this possible assumption, so don't add17084 // NonNull when that is enabled.17085 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&17086 !getLangOpts().CheckNew)17087 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));17088 17089 // C++2a [basic.stc.dynamic.allocation]p2:17090 // An allocation function attempts to allocate the requested amount of17091 // storage. [...] If the request succeeds, the value returned by a17092 // replaceable allocation function is a [...] pointer value p0 different17093 // from any previously returned value p1 [...]17094 //17095 // However, this particular information is being added in codegen,17096 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)17097 17098 // C++2a [basic.stc.dynamic.allocation]p2:17099 // An allocation function attempts to allocate the requested amount of17100 // storage. If it is successful, it returns the address of the start of a17101 // block of storage whose length in bytes is at least as large as the17102 // requested size.17103 if (!FD->hasAttr<AllocSizeAttr>()) {17104 FD->addAttr(AllocSizeAttr::CreateImplicit(17105 Context, /*ElemSizeParam=*/ParamIdx(1, FD),17106 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));17107 }17108 17109 // C++2a [basic.stc.dynamic.allocation]p3:17110 // For an allocation function [...], the pointer returned on a successful17111 // call shall represent the address of storage that is aligned as follows:17112 // (3.1) If the allocation function takes an argument of type17113 // std::align_val_t, the storage will have the alignment17114 // specified by the value of this argument.17115 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {17116 FD->addAttr(AllocAlignAttr::CreateImplicit(17117 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));17118 }17119 17120 // FIXME:17121 // C++2a [basic.stc.dynamic.allocation]p3:17122 // For an allocation function [...], the pointer returned on a successful17123 // call shall represent the address of storage that is aligned as follows:17124 // (3.2) Otherwise, if the allocation function is named operator new[],17125 // the storage is aligned for any object that does not have17126 // new-extended alignment ([basic.align]) and is no larger than the17127 // requested size.17128 // (3.3) Otherwise, the storage is aligned for any object that does not17129 // have new-extended alignment and is of the requested size.17130}17131 17132void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {17133 if (FD->isInvalidDecl())17134 return;17135 17136 // If this is a built-in function, map its builtin attributes to17137 // actual attributes.17138 if (unsigned BuiltinID = FD->getBuiltinID()) {17139 // Handle printf-formatting attributes.17140 unsigned FormatIdx;17141 bool HasVAListArg;17142 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {17143 if (!FD->hasAttr<FormatAttr>()) {17144 const char *fmt = "printf";17145 unsigned int NumParams = FD->getNumParams();17146 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)17147 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())17148 fmt = "NSString";17149 FD->addAttr(FormatAttr::CreateImplicit(Context,17150 &Context.Idents.get(fmt),17151 FormatIdx+1,17152 HasVAListArg ? 0 : FormatIdx+2,17153 FD->getLocation()));17154 }17155 }17156 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,17157 HasVAListArg)) {17158 if (!FD->hasAttr<FormatAttr>())17159 FD->addAttr(FormatAttr::CreateImplicit(Context,17160 &Context.Idents.get("scanf"),17161 FormatIdx+1,17162 HasVAListArg ? 0 : FormatIdx+2,17163 FD->getLocation()));17164 }17165 17166 // Handle automatically recognized callbacks.17167 SmallVector<int, 4> Encoding;17168 if (!FD->hasAttr<CallbackAttr>() &&17169 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))17170 FD->addAttr(CallbackAttr::CreateImplicit(17171 Context, Encoding.data(), Encoding.size(), FD->getLocation()));17172 17173 // Mark const if we don't care about errno and/or floating point exceptions17174 // that are the only thing preventing the function from being const. This17175 // allows IRgen to use LLVM intrinsics for such functions.17176 bool NoExceptions =17177 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;17178 bool ConstWithoutErrnoAndExceptions =17179 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);17180 bool ConstWithoutExceptions =17181 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);17182 if (!FD->hasAttr<ConstAttr>() &&17183 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&17184 (!ConstWithoutErrnoAndExceptions ||17185 (!getLangOpts().MathErrno && NoExceptions)) &&17186 (!ConstWithoutExceptions || NoExceptions))17187 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));17188 17189 // We make "fma" on GNU or Windows const because we know it does not set17190 // errno in those environments even though it could set errno based on the17191 // C standard.17192 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();17193 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&17194 !FD->hasAttr<ConstAttr>()) {17195 switch (BuiltinID) {17196 case Builtin::BI__builtin_fma:17197 case Builtin::BI__builtin_fmaf:17198 case Builtin::BI__builtin_fmal:17199 case Builtin::BIfma:17200 case Builtin::BIfmaf:17201 case Builtin::BIfmal:17202 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));17203 break;17204 default:17205 break;17206 }17207 }17208 17209 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&17210 !FD->hasAttr<ReturnsTwiceAttr>())17211 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,17212 FD->getLocation()));17213 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())17214 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));17215 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())17216 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));17217 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())17218 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));17219 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&17220 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {17221 // Add the appropriate attribute, depending on the CUDA compilation mode17222 // and which target the builtin belongs to. For example, during host17223 // compilation, aux builtins are __device__, while the rest are __host__.17224 if (getLangOpts().CUDAIsDevice !=17225 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))17226 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));17227 else17228 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));17229 }17230 17231 // Add known guaranteed alignment for allocation functions.17232 switch (BuiltinID) {17233 case Builtin::BImemalign:17234 case Builtin::BIaligned_alloc:17235 if (!FD->hasAttr<AllocAlignAttr>())17236 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),17237 FD->getLocation()));17238 break;17239 default:17240 break;17241 }17242 17243 // Add allocsize attribute for allocation functions.17244 switch (BuiltinID) {17245 case Builtin::BIcalloc:17246 FD->addAttr(AllocSizeAttr::CreateImplicit(17247 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));17248 break;17249 case Builtin::BImemalign:17250 case Builtin::BIaligned_alloc:17251 case Builtin::BIrealloc:17252 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),17253 ParamIdx(), FD->getLocation()));17254 break;17255 case Builtin::BImalloc:17256 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),17257 ParamIdx(), FD->getLocation()));17258 break;17259 default:17260 break;17261 }17262 }17263 17264 LazyProcessLifetimeCaptureByParams(FD);17265 inferLifetimeBoundAttribute(FD);17266 inferLifetimeCaptureByAttribute(FD);17267 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);17268 17269 // If C++ exceptions are enabled but we are told extern "C" functions cannot17270 // throw, add an implicit nothrow attribute to any extern "C" function we come17271 // across.17272 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&17273 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {17274 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();17275 if (!FPT || FPT->getExceptionSpecType() == EST_None)17276 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));17277 }17278 17279 IdentifierInfo *Name = FD->getIdentifier();17280 if (!Name)17281 return;17282 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||17283 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&17284 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==17285 LinkageSpecLanguageIDs::C)) {17286 // Okay: this could be a libc/libm/Objective-C function we know17287 // about.17288 } else17289 return;17290 17291 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {17292 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be17293 // target-specific builtins, perhaps?17294 if (!FD->hasAttr<FormatAttr>())17295 FD->addAttr(FormatAttr::CreateImplicit(Context,17296 &Context.Idents.get("printf"), 2,17297 Name->isStr("vasprintf") ? 0 : 3,17298 FD->getLocation()));17299 }17300 17301 if (Name->isStr("__CFStringMakeConstantString")) {17302 // We already have a __builtin___CFStringMakeConstantString,17303 // but builds that use -fno-constant-cfstrings don't go through that.17304 if (!FD->hasAttr<FormatArgAttr>())17305 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),17306 FD->getLocation()));17307 }17308}17309 17310TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,17311 TypeSourceInfo *TInfo) {17312 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");17313 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");17314 17315 if (!TInfo) {17316 assert(D.isInvalidType() && "no declarator info for valid type");17317 TInfo = Context.getTrivialTypeSourceInfo(T);17318 }17319 17320 // Scope manipulation handled by caller.17321 TypedefDecl *NewTD =17322 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),17323 D.getIdentifierLoc(), D.getIdentifier(), TInfo);17324 17325 // Bail out immediately if we have an invalid declaration.17326 if (D.isInvalidType()) {17327 NewTD->setInvalidDecl();17328 return NewTD;17329 }17330 17331 if (D.getDeclSpec().isModulePrivateSpecified()) {17332 if (CurContext->isFunctionOrMethod())17333 Diag(NewTD->getLocation(), diag::err_module_private_local)17334 << 2 << NewTD17335 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())17336 << FixItHint::CreateRemoval(17337 D.getDeclSpec().getModulePrivateSpecLoc());17338 else17339 NewTD->setModulePrivate();17340 }17341 17342 // C++ [dcl.typedef]p8:17343 // If the typedef declaration defines an unnamed class (or17344 // enum), the first typedef-name declared by the declaration17345 // to be that class type (or enum type) is used to denote the17346 // class type (or enum type) for linkage purposes only.17347 // We need to check whether the type was declared in the declaration.17348 switch (D.getDeclSpec().getTypeSpecType()) {17349 case TST_enum:17350 case TST_struct:17351 case TST_interface:17352 case TST_union:17353 case TST_class: {17354 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());17355 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);17356 break;17357 }17358 17359 default:17360 break;17361 }17362 17363 return NewTD;17364}17365 17366bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {17367 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();17368 QualType T = TI->getType();17369 17370 if (T->isDependentType())17371 return false;17372 17373 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an17374 // integral type; any cv-qualification is ignored.17375 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,17376 // non-atomic version of the type specified by the type specifiers in the17377 // specifier qualifier list.17378 // Because of how odd C's rule is, we'll let the user know that operations17379 // involving the enumeration type will be non-atomic.17380 if (T->isAtomicType())17381 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);17382 17383 Qualifiers Q = T.getQualifiers();17384 std::optional<unsigned> QualSelect;17385 if (Q.hasConst() && Q.hasVolatile())17386 QualSelect = diag::CVQualList::Both;17387 else if (Q.hasConst())17388 QualSelect = diag::CVQualList::Const;17389 else if (Q.hasVolatile())17390 QualSelect = diag::CVQualList::Volatile;17391 17392 if (QualSelect)17393 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;17394 17395 T = T.getAtomicUnqualifiedType();17396 17397 // This doesn't use 'isIntegralType' despite the error message mentioning17398 // integral type because isIntegralType would also allow enum types in C.17399 if (const BuiltinType *BT = T->getAs<BuiltinType>())17400 if (BT->isInteger())17401 return false;17402 17403 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)17404 << T << T->isBitIntType();17405}17406 17407bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,17408 QualType EnumUnderlyingTy, bool IsFixed,17409 const EnumDecl *Prev) {17410 if (IsScoped != Prev->isScoped()) {17411 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)17412 << Prev->isScoped();17413 Diag(Prev->getLocation(), diag::note_previous_declaration);17414 return true;17415 }17416 17417 if (IsFixed && Prev->isFixed()) {17418 if (!EnumUnderlyingTy->isDependentType() &&17419 !Prev->getIntegerType()->isDependentType() &&17420 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,17421 Prev->getIntegerType())) {17422 // TODO: Highlight the underlying type of the redeclaration.17423 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)17424 << EnumUnderlyingTy << Prev->getIntegerType();17425 Diag(Prev->getLocation(), diag::note_previous_declaration)17426 << Prev->getIntegerTypeRange();17427 return true;17428 }17429 } else if (IsFixed != Prev->isFixed()) {17430 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)17431 << Prev->isFixed();17432 Diag(Prev->getLocation(), diag::note_previous_declaration);17433 return true;17434 }17435 17436 return false;17437}17438 17439/// Get diagnostic %select index for tag kind for17440/// redeclaration diagnostic message.17441/// WARNING: Indexes apply to particular diagnostics only!17442///17443/// \returns diagnostic %select index.17444static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {17445 switch (Tag) {17446 case TagTypeKind::Struct:17447 return 0;17448 case TagTypeKind::Interface:17449 return 1;17450 case TagTypeKind::Class:17451 return 2;17452 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");17453 }17454}17455 17456/// Determine if tag kind is a class-key compatible with17457/// class for redeclaration (class, struct, or __interface).17458///17459/// \returns true iff the tag kind is compatible.17460static bool isClassCompatTagKind(TagTypeKind Tag)17461{17462 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||17463 Tag == TagTypeKind::Interface;17464}17465 17466NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {17467 if (isa<TypedefDecl>(PrevDecl))17468 return NonTagKind::Typedef;17469 else if (isa<TypeAliasDecl>(PrevDecl))17470 return NonTagKind::TypeAlias;17471 else if (isa<ClassTemplateDecl>(PrevDecl))17472 return NonTagKind::Template;17473 else if (isa<TypeAliasTemplateDecl>(PrevDecl))17474 return NonTagKind::TypeAliasTemplate;17475 else if (isa<TemplateTemplateParmDecl>(PrevDecl))17476 return NonTagKind::TemplateTemplateArgument;17477 switch (TTK) {17478 case TagTypeKind::Struct:17479 case TagTypeKind::Interface:17480 case TagTypeKind::Class:17481 return getLangOpts().CPlusPlus ? NonTagKind::NonClass17482 : NonTagKind::NonStruct;17483 case TagTypeKind::Union:17484 return NonTagKind::NonUnion;17485 case TagTypeKind::Enum:17486 return NonTagKind::NonEnum;17487 }17488 llvm_unreachable("invalid TTK");17489}17490 17491bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,17492 TagTypeKind NewTag, bool isDefinition,17493 SourceLocation NewTagLoc,17494 const IdentifierInfo *Name) {17495 // C++ [dcl.type.elab]p3:17496 // The class-key or enum keyword present in the17497 // elaborated-type-specifier shall agree in kind with the17498 // declaration to which the name in the elaborated-type-specifier17499 // refers. This rule also applies to the form of17500 // elaborated-type-specifier that declares a class-name or17501 // friend class since it can be construed as referring to the17502 // definition of the class. Thus, in any17503 // elaborated-type-specifier, the enum keyword shall be used to17504 // refer to an enumeration (7.2), the union class-key shall be17505 // used to refer to a union (clause 9), and either the class or17506 // struct class-key shall be used to refer to a class (clause 9)17507 // declared using the class or struct class-key.17508 TagTypeKind OldTag = Previous->getTagKind();17509 if (OldTag != NewTag &&17510 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))17511 return false;17512 17513 // Tags are compatible, but we might still want to warn on mismatched tags.17514 // Non-class tags can't be mismatched at this point.17515 if (!isClassCompatTagKind(NewTag))17516 return true;17517 17518 // Declarations for which -Wmismatched-tags is disabled are entirely ignored17519 // by our warning analysis. We don't want to warn about mismatches with (eg)17520 // declarations in system headers that are designed to be specialized, but if17521 // a user asks us to warn, we should warn if their code contains mismatched17522 // declarations.17523 auto IsIgnoredLoc = [&](SourceLocation Loc) {17524 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,17525 Loc);17526 };17527 if (IsIgnoredLoc(NewTagLoc))17528 return true;17529 17530 auto IsIgnored = [&](const TagDecl *Tag) {17531 return IsIgnoredLoc(Tag->getLocation());17532 };17533 while (IsIgnored(Previous)) {17534 Previous = Previous->getPreviousDecl();17535 if (!Previous)17536 return true;17537 OldTag = Previous->getTagKind();17538 }17539 17540 bool isTemplate = false;17541 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))17542 isTemplate = Record->getDescribedClassTemplate();17543 17544 if (inTemplateInstantiation()) {17545 if (OldTag != NewTag) {17546 // In a template instantiation, do not offer fix-its for tag mismatches17547 // since they usually mess up the template instead of fixing the problem.17548 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)17549 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name17550 << getRedeclDiagFromTagKind(OldTag);17551 // FIXME: Note previous location?17552 }17553 return true;17554 }17555 17556 if (isDefinition) {17557 // On definitions, check all previous tags and issue a fix-it for each17558 // one that doesn't match the current tag.17559 if (Previous->getDefinition()) {17560 // Don't suggest fix-its for redefinitions.17561 return true;17562 }17563 17564 bool previousMismatch = false;17565 for (const TagDecl *I : Previous->redecls()) {17566 if (I->getTagKind() != NewTag) {17567 // Ignore previous declarations for which the warning was disabled.17568 if (IsIgnored(I))17569 continue;17570 17571 if (!previousMismatch) {17572 previousMismatch = true;17573 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)17574 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name17575 << getRedeclDiagFromTagKind(I->getTagKind());17576 }17577 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)17578 << getRedeclDiagFromTagKind(NewTag)17579 << FixItHint::CreateReplacement(I->getInnerLocStart(),17580 TypeWithKeyword::getTagTypeKindName(NewTag));17581 }17582 }17583 return true;17584 }17585 17586 // Identify the prevailing tag kind: this is the kind of the definition (if17587 // there is a non-ignored definition), or otherwise the kind of the prior17588 // (non-ignored) declaration.17589 const TagDecl *PrevDef = Previous->getDefinition();17590 if (PrevDef && IsIgnored(PrevDef))17591 PrevDef = nullptr;17592 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;17593 if (Redecl->getTagKind() != NewTag) {17594 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)17595 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name17596 << getRedeclDiagFromTagKind(OldTag);17597 Diag(Redecl->getLocation(), diag::note_previous_use);17598 17599 // If there is a previous definition, suggest a fix-it.17600 if (PrevDef) {17601 Diag(NewTagLoc, diag::note_struct_class_suggestion)17602 << getRedeclDiagFromTagKind(Redecl->getTagKind())17603 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),17604 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));17605 }17606 }17607 17608 return true;17609}17610 17611/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name17612/// from an outer enclosing namespace or file scope inside a friend declaration.17613/// This should provide the commented out code in the following snippet:17614/// namespace N {17615/// struct X;17616/// namespace M {17617/// struct Y { friend struct /*N::*/ X; };17618/// }17619/// }17620static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,17621 SourceLocation NameLoc) {17622 // While the decl is in a namespace, do repeated lookup of that name and see17623 // if we get the same namespace back. If we do not, continue until17624 // translation unit scope, at which point we have a fully qualified NNS.17625 SmallVector<IdentifierInfo *, 4> Namespaces;17626 DeclContext *DC = ND->getDeclContext()->getRedeclContext();17627 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {17628 // This tag should be declared in a namespace, which can only be enclosed by17629 // other namespaces. Bail if there's an anonymous namespace in the chain.17630 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);17631 if (!Namespace || Namespace->isAnonymousNamespace())17632 return FixItHint();17633 IdentifierInfo *II = Namespace->getIdentifier();17634 Namespaces.push_back(II);17635 NamedDecl *Lookup = SemaRef.LookupSingleName(17636 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);17637 if (Lookup == Namespace)17638 break;17639 }17640 17641 // Once we have all the namespaces, reverse them to go outermost first, and17642 // build an NNS.17643 SmallString<64> Insertion;17644 llvm::raw_svector_ostream OS(Insertion);17645 if (DC->isTranslationUnit())17646 OS << "::";17647 std::reverse(Namespaces.begin(), Namespaces.end());17648 for (auto *II : Namespaces)17649 OS << II->getName() << "::";17650 return FixItHint::CreateInsertion(NameLoc, Insertion);17651}17652 17653/// Determine whether a tag originally declared in context \p OldDC can17654/// be redeclared with an unqualified name in \p NewDC (assuming name lookup17655/// found a declaration in \p OldDC as a previous decl, perhaps through a17656/// using-declaration).17657static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,17658 DeclContext *NewDC) {17659 OldDC = OldDC->getRedeclContext();17660 NewDC = NewDC->getRedeclContext();17661 17662 if (OldDC->Equals(NewDC))17663 return true;17664 17665 // In MSVC mode, we allow a redeclaration if the contexts are related (either17666 // encloses the other).17667 if (S.getLangOpts().MSVCCompat &&17668 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))17669 return true;17670 17671 return false;17672}17673 17674DeclResult17675Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,17676 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,17677 const ParsedAttributesView &Attrs, AccessSpecifier AS,17678 SourceLocation ModulePrivateLoc,17679 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,17680 bool &IsDependent, SourceLocation ScopedEnumKWLoc,17681 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,17682 bool IsTypeSpecifier, bool IsTemplateParamOrArg,17683 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {17684 // If this is not a definition, it must have a name.17685 IdentifierInfo *OrigName = Name;17686 assert((Name != nullptr || TUK == TagUseKind::Definition) &&17687 "Nameless record must be a definition!");17688 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);17689 17690 OwnedDecl = false;17691 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);17692 bool ScopedEnum = ScopedEnumKWLoc.isValid();17693 17694 // FIXME: Check member specializations more carefully.17695 bool isMemberSpecialization = false;17696 bool IsInjectedClassName = false;17697 bool Invalid = false;17698 17699 // We only need to do this matching if we have template parameters17700 // or a scope specifier, which also conveniently avoids this work17701 // for non-C++ cases.17702 if (TemplateParameterLists.size() > 0 ||17703 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {17704 TemplateParameterList *TemplateParams =17705 MatchTemplateParametersToScopeSpecifier(17706 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,17707 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);17708 17709 // C++23 [dcl.type.elab] p2:17710 // If an elaborated-type-specifier is the sole constituent of a17711 // declaration, the declaration is ill-formed unless it is an explicit17712 // specialization, an explicit instantiation or it has one of the17713 // following forms: [...]17714 // C++23 [dcl.enum] p1:17715 // If the enum-head-name of an opaque-enum-declaration contains a17716 // nested-name-specifier, the declaration shall be an explicit17717 // specialization.17718 //17719 // FIXME: Class template partial specializations can be forward declared17720 // per CWG2213, but the resolution failed to allow qualified forward17721 // declarations. This is almost certainly unintentional, so we allow them.17722 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&17723 !isMemberSpecialization)17724 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)17725 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();17726 17727 if (TemplateParams) {17728 if (Kind == TagTypeKind::Enum) {17729 Diag(KWLoc, diag::err_enum_template);17730 return true;17731 }17732 17733 if (TemplateParams->size() > 0) {17734 // This is a declaration or definition of a class template (which may17735 // be a member of another template).17736 17737 if (Invalid)17738 return true;17739 17740 OwnedDecl = false;17741 DeclResult Result = CheckClassTemplate(17742 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,17743 AS, ModulePrivateLoc,17744 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,17745 TemplateParameterLists.data(), SkipBody);17746 return Result.get();17747 } else {17748 // The "template<>" header is extraneous.17749 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)17750 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;17751 isMemberSpecialization = true;17752 }17753 }17754 17755 if (!TemplateParameterLists.empty() && isMemberSpecialization &&17756 CheckTemplateDeclScope(S, TemplateParameterLists.back()))17757 return true;17758 }17759 17760 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {17761 // C++23 [dcl.type.elab]p4:17762 // If an elaborated-type-specifier appears with the friend specifier as17763 // an entire member-declaration, the member-declaration shall have one17764 // of the following forms:17765 // friend class-key nested-name-specifier(opt) identifier ;17766 // friend class-key simple-template-id ;17767 // friend class-key nested-name-specifier template(opt)17768 // simple-template-id ;17769 //17770 // Since enum is not a class-key, so declarations like "friend enum E;"17771 // are ill-formed. Although CWG2363 reaffirms that such declarations are17772 // invalid, most implementations accept so we issue a pedantic warning.17773 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(17774 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);17775 assert(ScopedEnum || !ScopedEnumUsesClassTag);17776 Diag(KWLoc, diag::note_enum_friend)17777 << (ScopedEnum + ScopedEnumUsesClassTag);17778 }17779 17780 // Figure out the underlying type if this a enum declaration. We need to do17781 // this early, because it's needed to detect if this is an incompatible17782 // redeclaration.17783 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;17784 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;17785 17786 if (Kind == TagTypeKind::Enum) {17787 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {17788 // No underlying type explicitly specified, or we failed to parse the17789 // type, default to int.17790 EnumUnderlying = Context.IntTy.getTypePtr();17791 } else if (UnderlyingType.get()) {17792 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an17793 // integral type; any cv-qualification is ignored.17794 // C23 6.7.3.3p5: The underlying type of the enumeration is the17795 // unqualified, non-atomic version of the type specified by the type17796 // specifiers in the specifier qualifier list.17797 TypeSourceInfo *TI = nullptr;17798 GetTypeFromParser(UnderlyingType.get(), &TI);17799 EnumUnderlying = TI;17800 17801 if (CheckEnumUnderlyingType(TI))17802 // Recover by falling back to int.17803 EnumUnderlying = Context.IntTy.getTypePtr();17804 17805 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,17806 UPPC_FixedUnderlyingType))17807 EnumUnderlying = Context.IntTy.getTypePtr();17808 17809 // If the underlying type is atomic, we need to adjust the type before17810 // continuing. This only happens in the case we stored a TypeSourceInfo17811 // into EnumUnderlying because the other cases are error recovery up to17812 // this point. But because it's not possible to gin up a TypeSourceInfo17813 // for a non-atomic type from an atomic one, we'll store into the Type17814 // field instead. FIXME: it would be nice to have an easy way to get a17815 // derived TypeSourceInfo which strips qualifiers including the weird17816 // ones like _Atomic where it forms a different type.17817 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);17818 TI && TI->getType()->isAtomicType())17819 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();17820 17821 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {17822 // For MSVC ABI compatibility, unfixed enums must use an underlying type17823 // of 'int'. However, if this is an unfixed forward declaration, don't set17824 // the underlying type unless the user enables -fms-compatibility. This17825 // makes unfixed forward declared enums incomplete and is more conforming.17826 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)17827 EnumUnderlying = Context.IntTy.getTypePtr();17828 }17829 }17830 17831 DeclContext *SearchDC = CurContext;17832 DeclContext *DC = CurContext;17833 bool isStdBadAlloc = false;17834 bool isStdAlignValT = false;17835 17836 RedeclarationKind Redecl = forRedeclarationInCurContext();17837 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)17838 Redecl = RedeclarationKind::NotForRedeclaration;17839 17840 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C17841 /// implemented asks for structural equivalence checking, the returned decl17842 /// here is passed back to the parser, allowing the tag body to be parsed.17843 auto createTagFromNewDecl = [&]() -> TagDecl * {17844 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");17845 // If there is an identifier, use the location of the identifier as the17846 // location of the decl, otherwise use the location of the struct/union17847 // keyword.17848 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;17849 TagDecl *New = nullptr;17850 17851 if (Kind == TagTypeKind::Enum) {17852 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,17853 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);17854 // If this is an undefined enum, bail.17855 if (TUK != TagUseKind::Definition && !Invalid)17856 return nullptr;17857 if (EnumUnderlying) {17858 EnumDecl *ED = cast<EnumDecl>(New);17859 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))17860 ED->setIntegerTypeSourceInfo(TI);17861 else17862 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));17863 QualType EnumTy = ED->getIntegerType();17864 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)17865 ? Context.getPromotedIntegerType(EnumTy)17866 : EnumTy);17867 }17868 } else { // struct/union17869 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,17870 nullptr);17871 }17872 17873 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {17874 // Add alignment attributes if necessary; these attributes are checked17875 // when the ASTContext lays out the structure.17876 //17877 // It is important for implementing the correct semantics that this17878 // happen here (in ActOnTag). The #pragma pack stack is17879 // maintained as a result of parser callbacks which can occur at17880 // many points during the parsing of a struct declaration (because17881 // the #pragma tokens are effectively skipped over during the17882 // parsing of the struct).17883 if (TUK == TagUseKind::Definition &&17884 (!SkipBody || !SkipBody->ShouldSkip)) {17885 if (LangOpts.HLSL)17886 RD->addAttr(PackedAttr::CreateImplicit(Context));17887 AddAlignmentAttributesForRecord(RD);17888 AddMsStructLayoutForRecord(RD);17889 }17890 }17891 New->setLexicalDeclContext(CurContext);17892 return New;17893 };17894 17895 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);17896 if (Name && SS.isNotEmpty()) {17897 // We have a nested-name tag ('struct foo::bar').17898 17899 // Check for invalid 'foo::'.17900 if (SS.isInvalid()) {17901 Name = nullptr;17902 goto CreateNewDecl;17903 }17904 17905 // If this is a friend or a reference to a class in a dependent17906 // context, don't try to make a decl for it.17907 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {17908 DC = computeDeclContext(SS, false);17909 if (!DC) {17910 IsDependent = true;17911 return true;17912 }17913 } else {17914 DC = computeDeclContext(SS, true);17915 if (!DC) {17916 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)17917 << SS.getRange();17918 return true;17919 }17920 }17921 17922 if (RequireCompleteDeclContext(SS, DC))17923 return true;17924 17925 SearchDC = DC;17926 // Look-up name inside 'foo::'.17927 LookupQualifiedName(Previous, DC);17928 17929 if (Previous.isAmbiguous())17930 return true;17931 17932 if (Previous.empty()) {17933 // Name lookup did not find anything. However, if the17934 // nested-name-specifier refers to the current instantiation,17935 // and that current instantiation has any dependent base17936 // classes, we might find something at instantiation time: treat17937 // this as a dependent elaborated-type-specifier.17938 // But this only makes any sense for reference-like lookups.17939 if (Previous.wasNotFoundInCurrentInstantiation() &&17940 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {17941 IsDependent = true;17942 return true;17943 }17944 17945 // A tag 'foo::bar' must already exist.17946 Diag(NameLoc, diag::err_not_tag_in_scope)17947 << Kind << Name << DC << SS.getRange();17948 Name = nullptr;17949 Invalid = true;17950 goto CreateNewDecl;17951 }17952 } else if (Name) {17953 // C++14 [class.mem]p14:17954 // If T is the name of a class, then each of the following shall have a17955 // name different from T:17956 // -- every member of class T that is itself a type17957 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&17958 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))17959 return true;17960 17961 // If this is a named struct, check to see if there was a previous forward17962 // declaration or definition.17963 // FIXME: We're looking into outer scopes here, even when we17964 // shouldn't be. Doing so can result in ambiguities that we17965 // shouldn't be diagnosing.17966 LookupName(Previous, S);17967 17968 // When declaring or defining a tag, ignore ambiguities introduced17969 // by types using'ed into this scope.17970 if (Previous.isAmbiguous() &&17971 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {17972 LookupResult::Filter F = Previous.makeFilter();17973 while (F.hasNext()) {17974 NamedDecl *ND = F.next();17975 if (!ND->getDeclContext()->getRedeclContext()->Equals(17976 SearchDC->getRedeclContext()))17977 F.erase();17978 }17979 F.done();17980 }17981 17982 // C++11 [namespace.memdef]p3:17983 // If the name in a friend declaration is neither qualified nor17984 // a template-id and the declaration is a function or an17985 // elaborated-type-specifier, the lookup to determine whether17986 // the entity has been previously declared shall not consider17987 // any scopes outside the innermost enclosing namespace.17988 //17989 // MSVC doesn't implement the above rule for types, so a friend tag17990 // declaration may be a redeclaration of a type declared in an enclosing17991 // scope. They do implement this rule for friend functions.17992 //17993 // Does it matter that this should be by scope instead of by17994 // semantic context?17995 if (!Previous.empty() && TUK == TagUseKind::Friend) {17996 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();17997 LookupResult::Filter F = Previous.makeFilter();17998 bool FriendSawTagOutsideEnclosingNamespace = false;17999 while (F.hasNext()) {18000 NamedDecl *ND = F.next();18001 DeclContext *DC = ND->getDeclContext()->getRedeclContext();18002 if (DC->isFileContext() &&18003 !EnclosingNS->Encloses(ND->getDeclContext())) {18004 if (getLangOpts().MSVCCompat)18005 FriendSawTagOutsideEnclosingNamespace = true;18006 else18007 F.erase();18008 }18009 }18010 F.done();18011 18012 // Diagnose this MSVC extension in the easy case where lookup would have18013 // unambiguously found something outside the enclosing namespace.18014 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {18015 NamedDecl *ND = Previous.getFoundDecl();18016 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)18017 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);18018 }18019 }18020 18021 // Note: there used to be some attempt at recovery here.18022 if (Previous.isAmbiguous())18023 return true;18024 18025 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {18026 // FIXME: This makes sure that we ignore the contexts associated18027 // with C structs, unions, and enums when looking for a matching18028 // tag declaration or definition. See the similar lookup tweak18029 // in Sema::LookupName; is there a better way to deal with this?18030 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))18031 SearchDC = SearchDC->getParent();18032 } else if (getLangOpts().CPlusPlus) {18033 // Inside ObjCContainer want to keep it as a lexical decl context but go18034 // past it (most often to TranslationUnit) to find the semantic decl18035 // context.18036 while (isa<ObjCContainerDecl>(SearchDC))18037 SearchDC = SearchDC->getParent();18038 }18039 } else if (getLangOpts().CPlusPlus) {18040 // Don't use ObjCContainerDecl as the semantic decl context for anonymous18041 // TagDecl the same way as we skip it for named TagDecl.18042 while (isa<ObjCContainerDecl>(SearchDC))18043 SearchDC = SearchDC->getParent();18044 }18045 18046 if (Previous.isSingleResult() &&18047 Previous.getFoundDecl()->isTemplateParameter()) {18048 // Maybe we will complain about the shadowed template parameter.18049 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());18050 // Just pretend that we didn't see the previous declaration.18051 Previous.clear();18052 }18053 18054 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&18055 DC->Equals(getStdNamespace())) {18056 if (Name->isStr("bad_alloc")) {18057 // This is a declaration of or a reference to "std::bad_alloc".18058 isStdBadAlloc = true;18059 18060 // If std::bad_alloc has been implicitly declared (but made invisible to18061 // name lookup), fill in this implicit declaration as the previous18062 // declaration, so that the declarations get chained appropriately.18063 if (Previous.empty() && StdBadAlloc)18064 Previous.addDecl(getStdBadAlloc());18065 } else if (Name->isStr("align_val_t")) {18066 isStdAlignValT = true;18067 if (Previous.empty() && StdAlignValT)18068 Previous.addDecl(getStdAlignValT());18069 }18070 }18071 18072 // If we didn't find a previous declaration, and this is a reference18073 // (or friend reference), move to the correct scope. In C++, we18074 // also need to do a redeclaration lookup there, just in case18075 // there's a shadow friend decl.18076 if (Name && Previous.empty() &&18077 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||18078 IsTemplateParamOrArg)) {18079 if (Invalid) goto CreateNewDecl;18080 assert(SS.isEmpty());18081 18082 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {18083 // C++ [basic.scope.pdecl]p5:18084 // -- for an elaborated-type-specifier of the form18085 //18086 // class-key identifier18087 //18088 // if the elaborated-type-specifier is used in the18089 // decl-specifier-seq or parameter-declaration-clause of a18090 // function defined in namespace scope, the identifier is18091 // declared as a class-name in the namespace that contains18092 // the declaration; otherwise, except as a friend18093 // declaration, the identifier is declared in the smallest18094 // non-class, non-function-prototype scope that contains the18095 // declaration.18096 //18097 // C99 6.7.2.3p8 has a similar (but not identical!) provision for18098 // C structs and unions.18099 //18100 // It is an error in C++ to declare (rather than define) an enum18101 // type, including via an elaborated type specifier. We'll18102 // diagnose that later; for now, declare the enum in the same18103 // scope as we would have picked for any other tag type.18104 //18105 // GNU C also supports this behavior as part of its incomplete18106 // enum types extension, while GNU C++ does not.18107 //18108 // Find the context where we'll be declaring the tag.18109 // FIXME: We would like to maintain the current DeclContext as the18110 // lexical context,18111 SearchDC = getTagInjectionContext(SearchDC);18112 18113 // Find the scope where we'll be declaring the tag.18114 S = getTagInjectionScope(S, getLangOpts());18115 } else {18116 assert(TUK == TagUseKind::Friend);18117 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);18118 18119 // C++ [namespace.memdef]p3:18120 // If a friend declaration in a non-local class first declares a18121 // class or function, the friend class or function is a member of18122 // the innermost enclosing namespace.18123 SearchDC = RD->isLocalClass() ? RD->isLocalClass()18124 : SearchDC->getEnclosingNamespaceContext();18125 }18126 18127 // In C++, we need to do a redeclaration lookup to properly18128 // diagnose some problems.18129 // FIXME: redeclaration lookup is also used (with and without C++) to find a18130 // hidden declaration so that we don't get ambiguity errors when using a18131 // type declared by an elaborated-type-specifier. In C that is not correct18132 // and we should instead merge compatible types found by lookup.18133 if (getLangOpts().CPlusPlus) {18134 // FIXME: This can perform qualified lookups into function contexts,18135 // which are meaningless.18136 Previous.setRedeclarationKind(forRedeclarationInCurContext());18137 LookupQualifiedName(Previous, SearchDC);18138 } else {18139 Previous.setRedeclarationKind(forRedeclarationInCurContext());18140 LookupName(Previous, S);18141 }18142 }18143 18144 // If we have a known previous declaration to use, then use it.18145 if (Previous.empty() && SkipBody && SkipBody->Previous)18146 Previous.addDecl(SkipBody->Previous);18147 18148 if (!Previous.empty()) {18149 NamedDecl *PrevDecl = Previous.getFoundDecl();18150 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();18151 18152 // It's okay to have a tag decl in the same scope as a typedef18153 // which hides a tag decl in the same scope. Finding this18154 // with a redeclaration lookup can only actually happen in C++.18155 //18156 // This is also okay for elaborated-type-specifiers, which is18157 // technically forbidden by the current standard but which is18158 // okay according to the likely resolution of an open issue;18159 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#40718160 if (getLangOpts().CPlusPlus) {18161 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {18162 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {18163 if (Tag->getDeclName() == Name &&18164 Tag->getDeclContext()->getRedeclContext()18165 ->Equals(TD->getDeclContext()->getRedeclContext())) {18166 PrevDecl = Tag;18167 Previous.clear();18168 Previous.addDecl(Tag);18169 Previous.resolveKind();18170 }18171 }18172 } else if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);18173 TUK == TagUseKind::Reference && RD &&18174 RD->isInjectedClassName()) {18175 // If lookup found the injected class name, the previous declaration is18176 // the class being injected into.18177 PrevDecl = cast<TagDecl>(RD->getDeclContext());18178 Previous.clear();18179 Previous.addDecl(PrevDecl);18180 Previous.resolveKind();18181 IsInjectedClassName = true;18182 }18183 }18184 18185 // If this is a redeclaration of a using shadow declaration, it must18186 // declare a tag in the same context. In MSVC mode, we allow a18187 // redefinition if either context is within the other.18188 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {18189 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);18190 if (SS.isEmpty() && TUK != TagUseKind::Reference &&18191 TUK != TagUseKind::Friend &&18192 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&18193 !(OldTag && isAcceptableTagRedeclContext(18194 *this, OldTag->getDeclContext(), SearchDC))) {18195 Diag(KWLoc, diag::err_using_decl_conflict_reverse);18196 Diag(Shadow->getTargetDecl()->getLocation(),18197 diag::note_using_decl_target);18198 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)18199 << 0;18200 // Recover by ignoring the old declaration.18201 Previous.clear();18202 goto CreateNewDecl;18203 }18204 }18205 18206 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {18207 // If this is a use of a previous tag, or if the tag is already declared18208 // in the same scope (so that the definition/declaration completes or18209 // rementions the tag), reuse the decl.18210 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||18211 isDeclInScope(DirectPrevDecl, SearchDC, S,18212 SS.isNotEmpty() || isMemberSpecialization)) {18213 // Make sure that this wasn't declared as an enum and now used as a18214 // struct or something similar.18215 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,18216 TUK == TagUseKind::Definition, KWLoc,18217 Name)) {18218 bool SafeToContinue =18219 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&18220 Kind != TagTypeKind::Enum);18221 if (SafeToContinue)18222 Diag(KWLoc, diag::err_use_with_wrong_tag)18223 << Name18224 << FixItHint::CreateReplacement(SourceRange(KWLoc),18225 PrevTagDecl->getKindName());18226 else18227 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;18228 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);18229 18230 if (SafeToContinue)18231 Kind = PrevTagDecl->getTagKind();18232 else {18233 // Recover by making this an anonymous redefinition.18234 Name = nullptr;18235 Previous.clear();18236 Invalid = true;18237 }18238 }18239 18240 if (Kind == TagTypeKind::Enum &&18241 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {18242 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);18243 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)18244 return PrevTagDecl;18245 18246 QualType EnumUnderlyingTy;18247 if (TypeSourceInfo *TI =18248 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))18249 EnumUnderlyingTy = TI->getType().getUnqualifiedType();18250 else if (const Type *T =18251 dyn_cast_if_present<const Type *>(EnumUnderlying))18252 EnumUnderlyingTy = QualType(T, 0);18253 18254 // All conflicts with previous declarations are recovered by18255 // returning the previous declaration, unless this is a definition,18256 // in which case we want the caller to bail out.18257 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,18258 ScopedEnum, EnumUnderlyingTy,18259 IsFixed, PrevEnum))18260 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;18261 }18262 18263 // C++11 [class.mem]p1:18264 // A member shall not be declared twice in the member-specification,18265 // except that a nested class or member class template can be declared18266 // and then later defined.18267 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&18268 S->isDeclScope(PrevDecl)) {18269 Diag(NameLoc, diag::ext_member_redeclared);18270 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);18271 }18272 18273 if (!Invalid) {18274 // If this is a use, just return the declaration we found, unless18275 // we have attributes.18276 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {18277 if (!Attrs.empty()) {18278 // FIXME: Diagnose these attributes. For now, we create a new18279 // declaration to hold them.18280 } else if (TUK == TagUseKind::Reference &&18281 (PrevTagDecl->getFriendObjectKind() ==18282 Decl::FOK_Undeclared ||18283 PrevDecl->getOwningModule() != getCurrentModule()) &&18284 SS.isEmpty()) {18285 // This declaration is a reference to an existing entity, but18286 // has different visibility from that entity: it either makes18287 // a friend visible or it makes a type visible in a new module.18288 // In either case, create a new declaration. We only do this if18289 // the declaration would have meant the same thing if no prior18290 // declaration were found, that is, if it was found in the same18291 // scope where we would have injected a declaration.18292 if (!getTagInjectionContext(CurContext)->getRedeclContext()18293 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))18294 return PrevTagDecl;18295 // This is in the injected scope, create a new declaration in18296 // that scope.18297 S = getTagInjectionScope(S, getLangOpts());18298 } else {18299 return PrevTagDecl;18300 }18301 }18302 18303 // Diagnose attempts to redefine a tag.18304 if (TUK == TagUseKind::Definition) {18305 if (TagDecl *Def = PrevTagDecl->getDefinition()) {18306 // If the type is currently being defined, complain18307 // about a nested redefinition.18308 if (Def->isBeingDefined()) {18309 Diag(NameLoc, diag::err_nested_redefinition) << Name;18310 Diag(PrevTagDecl->getLocation(),18311 diag::note_previous_definition);18312 Name = nullptr;18313 Previous.clear();18314 Invalid = true;18315 } else {18316 // If we're defining a specialization and the previous18317 // definition is from an implicit instantiation, don't emit an18318 // error here; we'll catch this in the general case below.18319 bool IsExplicitSpecializationAfterInstantiation = false;18320 if (isMemberSpecialization) {18321 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))18322 IsExplicitSpecializationAfterInstantiation =18323 RD->getTemplateSpecializationKind() !=18324 TSK_ExplicitSpecialization;18325 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))18326 IsExplicitSpecializationAfterInstantiation =18327 ED->getTemplateSpecializationKind() !=18328 TSK_ExplicitSpecialization;18329 }18330 18331 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,18332 // do not keep more that one definition around (merge them).18333 // However, ensure the decl passes the structural compatibility18334 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).18335 NamedDecl *Hidden = nullptr;18336 bool HiddenDefVisible = false;18337 if (SkipBody &&18338 (isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible) ||18339 getLangOpts().C23)) {18340 // There is a definition of this tag, but it is not visible.18341 // We explicitly make use of C++'s one definition rule here,18342 // and assume that this definition is identical to the hidden18343 // one we already have. Make the existing definition visible18344 // and use it in place of this one.18345 if (!getLangOpts().CPlusPlus) {18346 // Postpone making the old definition visible until after we18347 // complete parsing the new one and do the structural18348 // comparison.18349 SkipBody->CheckSameAsPrevious = true;18350 SkipBody->New = createTagFromNewDecl();18351 SkipBody->Previous = Def;18352 18353 ProcessDeclAttributeList(S, SkipBody->New, Attrs);18354 return Def;18355 }18356 18357 SkipBody->ShouldSkip = true;18358 SkipBody->Previous = Def;18359 if (!HiddenDefVisible && Hidden)18360 makeMergedDefinitionVisible(Hidden);18361 // Carry on and handle it like a normal definition. We'll18362 // skip starting the definition later.18363 18364 } else if (!IsExplicitSpecializationAfterInstantiation) {18365 // A redeclaration in function prototype scope in C isn't18366 // visible elsewhere, so merely issue a warning.18367 if (!getLangOpts().CPlusPlus &&18368 S->containedInPrototypeScope())18369 Diag(NameLoc, diag::warn_redefinition_in_param_list)18370 << Name;18371 else18372 Diag(NameLoc, diag::err_redefinition) << Name;18373 notePreviousDefinition(Def,18374 NameLoc.isValid() ? NameLoc : KWLoc);18375 // If this is a redefinition, recover by making this18376 // struct be anonymous, which will make any later18377 // references get the previous definition.18378 Name = nullptr;18379 Previous.clear();18380 Invalid = true;18381 }18382 }18383 }18384 18385 // Okay, this is definition of a previously declared or referenced18386 // tag. We're going to create a new Decl for it.18387 }18388 18389 // Okay, we're going to make a redeclaration. If this is some kind18390 // of reference, make sure we build the redeclaration in the same DC18391 // as the original, and ignore the current access specifier.18392 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {18393 SearchDC = PrevTagDecl->getDeclContext();18394 AS = AS_none;18395 }18396 }18397 // If we get here we have (another) forward declaration or we18398 // have a definition. Just create a new decl.18399 18400 } else {18401 // If we get here, this is a definition of a new tag type in a nested18402 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a18403 // new decl/type. We set PrevDecl to NULL so that the entities18404 // have distinct types.18405 Previous.clear();18406 }18407 // If we get here, we're going to create a new Decl. If PrevDecl18408 // is non-NULL, it's a definition of the tag declared by18409 // PrevDecl. If it's NULL, we have a new definition.18410 18411 // Otherwise, PrevDecl is not a tag, but was found with tag18412 // lookup. This is only actually possible in C++, where a few18413 // things like templates still live in the tag namespace.18414 } else {18415 // Use a better diagnostic if an elaborated-type-specifier18416 // found the wrong kind of type on the first18417 // (non-redeclaration) lookup.18418 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&18419 !Previous.isForRedeclaration()) {18420 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);18421 Diag(NameLoc, diag::err_tag_reference_non_tag)18422 << PrevDecl << NTK << Kind;18423 Diag(PrevDecl->getLocation(), diag::note_declared_at);18424 Invalid = true;18425 18426 // Otherwise, only diagnose if the declaration is in scope.18427 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,18428 SS.isNotEmpty() || isMemberSpecialization)) {18429 // do nothing18430 18431 // Diagnose implicit declarations introduced by elaborated types.18432 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {18433 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);18434 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;18435 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;18436 Invalid = true;18437 18438 // Otherwise it's a declaration. Call out a particularly common18439 // case here.18440 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {18441 unsigned Kind = 0;18442 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;18443 Diag(NameLoc, diag::err_tag_definition_of_typedef)18444 << Name << Kind << TND->getUnderlyingType();18445 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;18446 Invalid = true;18447 18448 // Otherwise, diagnose.18449 } else {18450 // The tag name clashes with something else in the target scope,18451 // issue an error and recover by making this tag be anonymous.18452 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;18453 notePreviousDefinition(PrevDecl, NameLoc);18454 Name = nullptr;18455 Invalid = true;18456 }18457 18458 // The existing declaration isn't relevant to us; we're in a18459 // new scope, so clear out the previous declaration.18460 Previous.clear();18461 }18462 }18463 18464CreateNewDecl:18465 18466 TagDecl *PrevDecl = nullptr;18467 if (Previous.isSingleResult())18468 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());18469 18470 // If there is an identifier, use the location of the identifier as the18471 // location of the decl, otherwise use the location of the struct/union18472 // keyword.18473 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;18474 18475 // Otherwise, create a new declaration. If there is a previous18476 // declaration of the same entity, the two will be linked via18477 // PrevDecl.18478 TagDecl *New;18479 18480 if (Kind == TagTypeKind::Enum) {18481 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:18482 // enum X { A, B, C } D; D should chain to X.18483 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,18484 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,18485 ScopedEnumUsesClassTag, IsFixed);18486 18487 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))18488 StdAlignValT = cast<EnumDecl>(New);18489 18490 // If this is an undefined enum, warn.18491 if (TUK != TagUseKind::Definition && !Invalid) {18492 TagDecl *Def;18493 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {18494 // C++0x: 7.2p2: opaque-enum-declaration.18495 // Conflicts are diagnosed above. Do nothing.18496 }18497 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {18498 Diag(Loc, diag::ext_forward_ref_enum_def)18499 << New;18500 Diag(Def->getLocation(), diag::note_previous_definition);18501 } else {18502 unsigned DiagID = diag::ext_forward_ref_enum;18503 if (getLangOpts().MSVCCompat)18504 DiagID = diag::ext_ms_forward_ref_enum;18505 else if (getLangOpts().CPlusPlus)18506 DiagID = diag::err_forward_ref_enum;18507 Diag(Loc, DiagID);18508 }18509 }18510 18511 if (EnumUnderlying) {18512 EnumDecl *ED = cast<EnumDecl>(New);18513 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))18514 ED->setIntegerTypeSourceInfo(TI);18515 else18516 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));18517 QualType EnumTy = ED->getIntegerType();18518 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)18519 ? Context.getPromotedIntegerType(EnumTy)18520 : EnumTy);18521 assert(ED->isComplete() && "enum with type should be complete");18522 }18523 } else {18524 // struct/union/class18525 18526 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:18527 // struct X { int A; } D; D should chain to X.18528 if (getLangOpts().CPlusPlus) {18529 // FIXME: Look for a way to use RecordDecl for simple structs.18530 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,18531 cast_or_null<CXXRecordDecl>(PrevDecl));18532 18533 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))18534 StdBadAlloc = cast<CXXRecordDecl>(New);18535 } else18536 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,18537 cast_or_null<RecordDecl>(PrevDecl));18538 }18539 18540 // Only C23 and later allow defining new types in 'offsetof()'.18541 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&18542 !getLangOpts().CPlusPlus && !getLangOpts().C23)18543 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)18544 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();18545 18546 // C++11 [dcl.type]p3:18547 // A type-specifier-seq shall not define a class or enumeration [...].18548 if (!Invalid && getLangOpts().CPlusPlus &&18549 (IsTypeSpecifier || IsTemplateParamOrArg) &&18550 TUK == TagUseKind::Definition) {18551 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)18552 << Context.getCanonicalTagType(New);18553 Invalid = true;18554 }18555 18556 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&18557 DC->getDeclKind() == Decl::Enum) {18558 Diag(New->getLocation(), diag::err_type_defined_in_enum)18559 << Context.getCanonicalTagType(New);18560 Invalid = true;18561 }18562 18563 // Maybe add qualifier info.18564 if (SS.isNotEmpty()) {18565 if (SS.isSet()) {18566 // If this is either a declaration or a definition, check the18567 // nested-name-specifier against the current context.18568 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&18569 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,18570 /*TemplateId=*/nullptr,18571 isMemberSpecialization))18572 Invalid = true;18573 18574 New->setQualifierInfo(SS.getWithLocInContext(Context));18575 if (TemplateParameterLists.size() > 0) {18576 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);18577 }18578 }18579 else18580 Invalid = true;18581 }18582 18583 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {18584 // Add alignment attributes if necessary; these attributes are checked when18585 // the ASTContext lays out the structure.18586 //18587 // It is important for implementing the correct semantics that this18588 // happen here (in ActOnTag). The #pragma pack stack is18589 // maintained as a result of parser callbacks which can occur at18590 // many points during the parsing of a struct declaration (because18591 // the #pragma tokens are effectively skipped over during the18592 // parsing of the struct).18593 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {18594 if (LangOpts.HLSL)18595 RD->addAttr(PackedAttr::CreateImplicit(Context));18596 AddAlignmentAttributesForRecord(RD);18597 AddMsStructLayoutForRecord(RD);18598 }18599 }18600 18601 if (ModulePrivateLoc.isValid()) {18602 if (isMemberSpecialization)18603 Diag(New->getLocation(), diag::err_module_private_specialization)18604 << 218605 << FixItHint::CreateRemoval(ModulePrivateLoc);18606 // __module_private__ does not apply to local classes. However, we only18607 // diagnose this as an error when the declaration specifiers are18608 // freestanding. Here, we just ignore the __module_private__.18609 else if (!SearchDC->isFunctionOrMethod())18610 New->setModulePrivate();18611 }18612 18613 // If this is a specialization of a member class (of a class template),18614 // check the specialization.18615 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))18616 Invalid = true;18617 18618 // If we're declaring or defining a tag in function prototype scope in C,18619 // note that this type can only be used within the function and add it to18620 // the list of decls to inject into the function definition scope. However,18621 // in C23 and later, while the type is only visible within the function, the18622 // function can be called with a compatible type defined in the same TU, so18623 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.18624 if ((Name || Kind == TagTypeKind::Enum) &&18625 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {18626 if (getLangOpts().CPlusPlus) {18627 // C++ [dcl.fct]p6:18628 // Types shall not be defined in return or parameter types.18629 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {18630 Diag(Loc, diag::err_type_defined_in_param_type)18631 << Name;18632 Invalid = true;18633 }18634 if (TUK == TagUseKind::Declaration)18635 Invalid = true;18636 } else if (!PrevDecl) {18637 // In C23 mode, if the declaration is complete, we do not want to18638 // diagnose.18639 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)18640 Diag(Loc, diag::warn_decl_in_param_list)18641 << Context.getCanonicalTagType(New);18642 }18643 }18644 18645 if (Invalid)18646 New->setInvalidDecl();18647 18648 // Set the lexical context. If the tag has a C++ scope specifier, the18649 // lexical context will be different from the semantic context.18650 New->setLexicalDeclContext(CurContext);18651 18652 // Mark this as a friend decl if applicable.18653 // In Microsoft mode, a friend declaration also acts as a forward18654 // declaration so we always pass true to setObjectOfFriendDecl to make18655 // the tag name visible.18656 if (TUK == TagUseKind::Friend)18657 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);18658 18659 // Set the access specifier.18660 if (!Invalid && SearchDC->isRecord())18661 SetMemberAccessSpecifier(New, PrevDecl, AS);18662 18663 if (PrevDecl)18664 CheckRedeclarationInModule(New, PrevDecl);18665 18666 if (TUK == TagUseKind::Definition) {18667 if (!SkipBody || !SkipBody->ShouldSkip) {18668 New->startDefinition();18669 } else {18670 New->setCompleteDefinition();18671 New->demoteThisDefinitionToDeclaration();18672 }18673 }18674 18675 ProcessDeclAttributeList(S, New, Attrs);18676 AddPragmaAttributes(S, New);18677 18678 // If this has an identifier, add it to the scope stack.18679 if (TUK == TagUseKind::Friend || IsInjectedClassName) {18680 // We might be replacing an existing declaration in the lookup tables;18681 // if so, borrow its access specifier.18682 if (PrevDecl)18683 New->setAccess(PrevDecl->getAccess());18684 18685 DeclContext *DC = New->getDeclContext()->getRedeclContext();18686 DC->makeDeclVisibleInContext(New);18687 if (Name) // can be null along some error paths18688 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))18689 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);18690 } else if (Name) {18691 S = getNonFieldDeclScope(S);18692 PushOnScopeChains(New, S, true);18693 } else {18694 CurContext->addDecl(New);18695 }18696 18697 // If this is the C FILE type, notify the AST context.18698 if (IdentifierInfo *II = New->getIdentifier())18699 if (!New->isInvalidDecl() &&18700 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&18701 II->isStr("FILE"))18702 Context.setFILEDecl(New);18703 18704 if (PrevDecl)18705 mergeDeclAttributes(New, PrevDecl);18706 18707 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {18708 inferGslOwnerPointerAttribute(CXXRD);18709 inferNullableClassAttribute(CXXRD);18710 }18711 18712 // If there's a #pragma GCC visibility in scope, set the visibility of this18713 // record.18714 AddPushedVisibilityAttribute(New);18715 18716 // If this is not a definition, process API notes for it now.18717 if (TUK != TagUseKind::Definition)18718 ProcessAPINotes(New);18719 18720 if (isMemberSpecialization && !New->isInvalidDecl())18721 CompleteMemberSpecialization(New, Previous);18722 18723 OwnedDecl = true;18724 // In C++, don't return an invalid declaration. We can't recover well from18725 // the cases where we make the type anonymous.18726 if (Invalid && getLangOpts().CPlusPlus) {18727 if (New->isBeingDefined())18728 if (auto RD = dyn_cast<RecordDecl>(New))18729 RD->completeDefinition();18730 return true;18731 } else if (SkipBody && SkipBody->ShouldSkip) {18732 return SkipBody->Previous;18733 } else {18734 return New;18735 }18736}18737 18738void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {18739 AdjustDeclIfTemplate(TagD);18740 TagDecl *Tag = cast<TagDecl>(TagD);18741 18742 // Enter the tag context.18743 PushDeclContext(S, Tag);18744 18745 ActOnDocumentableDecl(TagD);18746 18747 // If there's a #pragma GCC visibility in scope, set the visibility of this18748 // record.18749 AddPushedVisibilityAttribute(Tag);18750}18751 18752bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,18753 SkipBodyInfo &SkipBody) {18754 if (!hasStructuralCompatLayout(Prev, SkipBody.New))18755 return false;18756 18757 // Make the previous decl visible.18758 makeMergedDefinitionVisible(SkipBody.Previous);18759 CleanupMergedEnum(S, SkipBody.New);18760 return true;18761}18762 18763void Sema::ActOnStartCXXMemberDeclarations(18764 Scope *S, Decl *TagD, SourceLocation FinalLoc, bool IsFinalSpelledSealed,18765 bool IsAbstract, SourceLocation TriviallyRelocatable,18766 SourceLocation Replaceable, SourceLocation LBraceLoc) {18767 AdjustDeclIfTemplate(TagD);18768 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);18769 18770 FieldCollector->StartClass();18771 18772 if (!Record->getIdentifier())18773 return;18774 18775 if (IsAbstract)18776 Record->markAbstract();18777 18778 if (FinalLoc.isValid()) {18779 Record->addAttr(FinalAttr::Create(Context, FinalLoc,18780 IsFinalSpelledSealed18781 ? FinalAttr::Keyword_sealed18782 : FinalAttr::Keyword_final));18783 }18784 18785 if (TriviallyRelocatable.isValid())18786 Record->addAttr(18787 TriviallyRelocatableAttr::Create(Context, TriviallyRelocatable));18788 18789 if (Replaceable.isValid())18790 Record->addAttr(ReplaceableAttr::Create(Context, Replaceable));18791 18792 // C++ [class]p2:18793 // [...] The class-name is also inserted into the scope of the18794 // class itself; this is known as the injected-class-name. For18795 // purposes of access checking, the injected-class-name is treated18796 // as if it were a public member name.18797 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(18798 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),18799 Record->getLocation(), Record->getIdentifier());18800 InjectedClassName->setImplicit();18801 InjectedClassName->setAccess(AS_public);18802 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())18803 InjectedClassName->setDescribedClassTemplate(Template);18804 18805 PushOnScopeChains(InjectedClassName, S);18806 assert(InjectedClassName->isInjectedClassName() &&18807 "Broken injected-class-name");18808}18809 18810void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,18811 SourceRange BraceRange) {18812 AdjustDeclIfTemplate(TagD);18813 TagDecl *Tag = cast<TagDecl>(TagD);18814 Tag->setBraceRange(BraceRange);18815 18816 // Make sure we "complete" the definition even it is invalid.18817 if (Tag->isBeingDefined()) {18818 assert(Tag->isInvalidDecl() && "We should already have completed it");18819 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))18820 RD->completeDefinition();18821 }18822 18823 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {18824 FieldCollector->FinishClass();18825 if (RD->hasAttr<SYCLSpecialClassAttr>()) {18826 auto *Def = RD->getDefinition();18827 assert(Def && "The record is expected to have a completed definition");18828 unsigned NumInitMethods = 0;18829 for (auto *Method : Def->methods()) {18830 if (!Method->getIdentifier())18831 continue;18832 if (Method->getName() == "__init")18833 NumInitMethods++;18834 }18835 if (NumInitMethods > 1 || !Def->hasInitMethod())18836 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);18837 }18838 18839 // If we're defining a dynamic class in a module interface unit, we always18840 // need to produce the vtable for it, even if the vtable is not used in the18841 // current TU.18842 //18843 // The case where the current class is not dynamic is handled in18844 // MarkVTableUsed.18845 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())18846 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);18847 }18848 18849 // Exit this scope of this tag's definition.18850 PopDeclContext();18851 18852 if (getCurLexicalContext()->isObjCContainer() &&18853 Tag->getDeclContext()->isFileContext())18854 Tag->setTopLevelDeclInObjCContainer();18855 18856 // Notify the consumer that we've defined a tag.18857 if (!Tag->isInvalidDecl())18858 Consumer.HandleTagDeclDefinition(Tag);18859 18860 // Clangs implementation of #pragma align(packed) differs in bitfield layout18861 // from XLs and instead matches the XL #pragma pack(1) behavior.18862 if (Context.getTargetInfo().getTriple().isOSAIX() &&18863 AlignPackStack.hasValue()) {18864 AlignPackInfo APInfo = AlignPackStack.CurrentValue;18865 // Only diagnose #pragma align(packed).18866 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)18867 return;18868 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);18869 if (!RD)18870 return;18871 // Only warn if there is at least 1 bitfield member.18872 if (llvm::any_of(RD->fields(),18873 [](const FieldDecl *FD) { return FD->isBitField(); }))18874 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);18875 }18876}18877 18878void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {18879 AdjustDeclIfTemplate(TagD);18880 TagDecl *Tag = cast<TagDecl>(TagD);18881 Tag->setInvalidDecl();18882 18883 // Make sure we "complete" the definition even it is invalid.18884 if (Tag->isBeingDefined()) {18885 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))18886 RD->completeDefinition();18887 }18888 18889 // We're undoing ActOnTagStartDefinition here, not18890 // ActOnStartCXXMemberDeclarations, so we don't have to mess with18891 // the FieldCollector.18892 18893 PopDeclContext();18894}18895 18896// Note that FieldName may be null for anonymous bitfields.18897ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,18898 const IdentifierInfo *FieldName,18899 QualType FieldTy, bool IsMsStruct,18900 Expr *BitWidth) {18901 assert(BitWidth);18902 if (BitWidth->containsErrors())18903 return ExprError();18904 18905 // C99 6.7.2.1p4 - verify the field type.18906 // C++ 9.6p3: A bit-field shall have integral or enumeration type.18907 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {18908 // Handle incomplete and sizeless types with a specific error.18909 if (RequireCompleteSizedType(FieldLoc, FieldTy,18910 diag::err_field_incomplete_or_sizeless))18911 return ExprError();18912 if (FieldName)18913 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)18914 << FieldName << FieldTy << BitWidth->getSourceRange();18915 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)18916 << FieldTy << BitWidth->getSourceRange();18917 } else if (DiagnoseUnexpandedParameterPack(BitWidth, UPPC_BitFieldWidth))18918 return ExprError();18919 18920 // If the bit-width is type- or value-dependent, don't try to check18921 // it now.18922 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())18923 return BitWidth;18924 18925 llvm::APSInt Value;18926 ExprResult ICE =18927 VerifyIntegerConstantExpression(BitWidth, &Value, AllowFoldKind::Allow);18928 if (ICE.isInvalid())18929 return ICE;18930 BitWidth = ICE.get();18931 18932 // Zero-width bitfield is ok for anonymous field.18933 if (Value == 0 && FieldName)18934 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)18935 << FieldName << BitWidth->getSourceRange();18936 18937 if (Value.isSigned() && Value.isNegative()) {18938 if (FieldName)18939 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)18940 << FieldName << toString(Value, 10);18941 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)18942 << toString(Value, 10);18943 }18944 18945 // The size of the bit-field must not exceed our maximum permitted object18946 // size.18947 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {18948 return Diag(FieldLoc, diag::err_bitfield_too_wide)18949 << !FieldName << FieldName << toString(Value, 10);18950 }18951 18952 if (!FieldTy->isDependentType()) {18953 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);18954 uint64_t TypeWidth = Context.getIntWidth(FieldTy);18955 bool BitfieldIsOverwide = Value.ugt(TypeWidth);18956 18957 // Over-wide bitfields are an error in C or when using the MSVC bitfield18958 // ABI.18959 bool CStdConstraintViolation =18960 BitfieldIsOverwide && !getLangOpts().CPlusPlus;18961 bool MSBitfieldViolation =18962 Value.ugt(TypeStorageSize) &&18963 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());18964 if (CStdConstraintViolation || MSBitfieldViolation) {18965 unsigned DiagWidth =18966 CStdConstraintViolation ? TypeWidth : TypeStorageSize;18967 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)18968 << (bool)FieldName << FieldName << toString(Value, 10)18969 << !CStdConstraintViolation << DiagWidth;18970 }18971 18972 // Warn on types where the user might conceivably expect to get all18973 // specified bits as value bits: that's all integral types other than18974 // 'bool'.18975 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {18976 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)18977 << FieldName << Value << (unsigned)TypeWidth;18978 }18979 }18980 18981 if (isa<ConstantExpr>(BitWidth))18982 return BitWidth;18983 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});18984}18985 18986Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,18987 Declarator &D, Expr *BitfieldWidth) {18988 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,18989 D, BitfieldWidth,18990 /*InitStyle=*/ICIS_NoInit, AS_public);18991 return Res;18992}18993 18994FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,18995 SourceLocation DeclStart,18996 Declarator &D, Expr *BitWidth,18997 InClassInitStyle InitStyle,18998 AccessSpecifier AS) {18999 if (D.isDecompositionDeclarator()) {19000 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();19001 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)19002 << Decomp.getSourceRange();19003 return nullptr;19004 }19005 19006 const IdentifierInfo *II = D.getIdentifier();19007 SourceLocation Loc = DeclStart;19008 if (II) Loc = D.getIdentifierLoc();19009 19010 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);19011 QualType T = TInfo->getType();19012 if (getLangOpts().CPlusPlus) {19013 CheckExtraCXXDefaultArguments(D);19014 19015 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,19016 UPPC_DataMemberType)) {19017 D.setInvalidType();19018 T = Context.IntTy;19019 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);19020 }19021 }19022 19023 DiagnoseFunctionSpecifiers(D.getDeclSpec());19024 19025 if (D.getDeclSpec().isInlineSpecified())19026 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)19027 << getLangOpts().CPlusPlus17;19028 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())19029 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),19030 diag::err_invalid_thread)19031 << DeclSpec::getSpecifierName(TSCS);19032 19033 // Check to see if this name was declared as a member previously19034 NamedDecl *PrevDecl = nullptr;19035 LookupResult Previous(*this, II, Loc, LookupMemberName,19036 RedeclarationKind::ForVisibleRedeclaration);19037 LookupName(Previous, S);19038 switch (Previous.getResultKind()) {19039 case LookupResultKind::Found:19040 case LookupResultKind::FoundUnresolvedValue:19041 PrevDecl = Previous.getAsSingle<NamedDecl>();19042 break;19043 19044 case LookupResultKind::FoundOverloaded:19045 PrevDecl = Previous.getRepresentativeDecl();19046 break;19047 19048 case LookupResultKind::NotFound:19049 case LookupResultKind::NotFoundInCurrentInstantiation:19050 case LookupResultKind::Ambiguous:19051 break;19052 }19053 Previous.suppressDiagnostics();19054 19055 if (PrevDecl && PrevDecl->isTemplateParameter()) {19056 // Maybe we will complain about the shadowed template parameter.19057 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);19058 // Just pretend that we didn't see the previous declaration.19059 PrevDecl = nullptr;19060 }19061 19062 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))19063 PrevDecl = nullptr;19064 19065 bool Mutable19066 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);19067 SourceLocation TSSL = D.getBeginLoc();19068 FieldDecl *NewFD19069 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,19070 TSSL, AS, PrevDecl, &D);19071 19072 if (NewFD->isInvalidDecl())19073 Record->setInvalidDecl();19074 19075 if (D.getDeclSpec().isModulePrivateSpecified())19076 NewFD->setModulePrivate();19077 19078 if (NewFD->isInvalidDecl() && PrevDecl) {19079 // Don't introduce NewFD into scope; there's already something19080 // with the same name in the same scope.19081 } else if (II) {19082 PushOnScopeChains(NewFD, S);19083 } else19084 Record->addDecl(NewFD);19085 19086 return NewFD;19087}19088 19089FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,19090 TypeSourceInfo *TInfo,19091 RecordDecl *Record, SourceLocation Loc,19092 bool Mutable, Expr *BitWidth,19093 InClassInitStyle InitStyle,19094 SourceLocation TSSL,19095 AccessSpecifier AS, NamedDecl *PrevDecl,19096 Declarator *D) {19097 const IdentifierInfo *II = Name.getAsIdentifierInfo();19098 bool InvalidDecl = false;19099 if (D) InvalidDecl = D->isInvalidType();19100 19101 // If we receive a broken type, recover by assuming 'int' and19102 // marking this declaration as invalid.19103 if (T.isNull() || T->containsErrors()) {19104 InvalidDecl = true;19105 T = Context.IntTy;19106 }19107 19108 QualType EltTy = Context.getBaseElementType(T);19109 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {19110 bool isIncomplete =19111 LangOpts.HLSL // HLSL allows sizeless builtin types19112 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)19113 : RequireCompleteSizedType(Loc, EltTy,19114 diag::err_field_incomplete_or_sizeless);19115 if (isIncomplete) {19116 // Fields of incomplete type force their record to be invalid.19117 Record->setInvalidDecl();19118 InvalidDecl = true;19119 } else {19120 NamedDecl *Def;19121 EltTy->isIncompleteType(&Def);19122 if (Def && Def->isInvalidDecl()) {19123 Record->setInvalidDecl();19124 InvalidDecl = true;19125 }19126 }19127 }19128 19129 // TR 18037 does not allow fields to be declared with address space19130 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||19131 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {19132 Diag(Loc, diag::err_field_with_address_space);19133 Record->setInvalidDecl();19134 InvalidDecl = true;19135 }19136 19137 if (LangOpts.OpenCL) {19138 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be19139 // used as structure or union field: image, sampler, event or block types.19140 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||19141 T->isBlockPointerType()) {19142 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;19143 Record->setInvalidDecl();19144 InvalidDecl = true;19145 }19146 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension19147 // is enabled.19148 if (BitWidth && !getOpenCLOptions().isAvailableOption(19149 "__cl_clang_bitfields", LangOpts)) {19150 Diag(Loc, diag::err_opencl_bitfields);19151 InvalidDecl = true;19152 }19153 }19154 19155 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).19156 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&19157 T.hasQualifiers()) {19158 InvalidDecl = true;19159 Diag(Loc, diag::err_anon_bitfield_qualifiers);19160 }19161 19162 // C99 6.7.2.1p8: A member of a structure or union may have any type other19163 // than a variably modified type.19164 if (!InvalidDecl && T->isVariablyModifiedType()) {19165 if (!tryToFixVariablyModifiedVarType(19166 TInfo, T, Loc, diag::err_typecheck_field_variable_size))19167 InvalidDecl = true;19168 }19169 19170 // Fields can not have abstract class types19171 if (!InvalidDecl && RequireNonAbstractType(Loc, T,19172 diag::err_abstract_type_in_decl,19173 AbstractFieldType))19174 InvalidDecl = true;19175 19176 if (InvalidDecl)19177 BitWidth = nullptr;19178 // If this is declared as a bit-field, check the bit-field.19179 if (BitWidth) {19180 BitWidth =19181 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();19182 if (!BitWidth) {19183 InvalidDecl = true;19184 BitWidth = nullptr;19185 }19186 }19187 19188 // Check that 'mutable' is consistent with the type of the declaration.19189 if (!InvalidDecl && Mutable) {19190 unsigned DiagID = 0;19191 if (T->isReferenceType())19192 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference19193 : diag::err_mutable_reference;19194 else if (T.isConstQualified())19195 DiagID = diag::err_mutable_const;19196 19197 if (DiagID) {19198 SourceLocation ErrLoc = Loc;19199 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())19200 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();19201 Diag(ErrLoc, DiagID);19202 if (DiagID != diag::ext_mutable_reference) {19203 Mutable = false;19204 InvalidDecl = true;19205 }19206 }19207 }19208 19209 // C++11 [class.union]p8 (DR1460):19210 // At most one variant member of a union may have a19211 // brace-or-equal-initializer.19212 if (InitStyle != ICIS_NoInit)19213 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);19214 19215 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,19216 BitWidth, Mutable, InitStyle);19217 if (InvalidDecl)19218 NewFD->setInvalidDecl();19219 19220 if (!InvalidDecl)19221 warnOnCTypeHiddenInCPlusPlus(NewFD);19222 19223 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&19224 !PrevDecl->isPlaceholderVar(getLangOpts())) {19225 Diag(Loc, diag::err_duplicate_member) << II;19226 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);19227 NewFD->setInvalidDecl();19228 }19229 19230 if (!InvalidDecl && getLangOpts().CPlusPlus) {19231 if (Record->isUnion()) {19232 if (const auto *RD = EltTy->getAsCXXRecordDecl();19233 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {19234 19235 // C++ [class.union]p1: An object of a class with a non-trivial19236 // constructor, a non-trivial copy constructor, a non-trivial19237 // destructor, or a non-trivial copy assignment operator19238 // cannot be a member of a union, nor can an array of such19239 // objects.19240 if (CheckNontrivialField(NewFD))19241 NewFD->setInvalidDecl();19242 }19243 19244 // C++ [class.union]p1: If a union contains a member of reference type,19245 // the program is ill-formed, except when compiling with MSVC extensions19246 // enabled.19247 if (EltTy->isReferenceType()) {19248 const bool HaveMSExt =19249 getLangOpts().MicrosoftExt &&19250 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);19251 19252 Diag(NewFD->getLocation(),19253 HaveMSExt ? diag::ext_union_member_of_reference_type19254 : diag::err_union_member_of_reference_type)19255 << NewFD->getDeclName() << EltTy;19256 if (!HaveMSExt)19257 NewFD->setInvalidDecl();19258 }19259 }19260 }19261 19262 // FIXME: We need to pass in the attributes given an AST19263 // representation, not a parser representation.19264 if (D) {19265 // FIXME: The current scope is almost... but not entirely... correct here.19266 ProcessDeclAttributes(getCurScope(), NewFD, *D);19267 19268 if (NewFD->hasAttrs())19269 CheckAlignasUnderalignment(NewFD);19270 }19271 19272 // In auto-retain/release, infer strong retension for fields of19273 // retainable type.19274 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))19275 NewFD->setInvalidDecl();19276 19277 if (T.isObjCGCWeak())19278 Diag(Loc, diag::warn_attribute_weak_on_field);19279 19280 // PPC MMA non-pointer types are not allowed as field types.19281 if (Context.getTargetInfo().getTriple().isPPC64() &&19282 PPC().CheckPPCMMAType(T, NewFD->getLocation()))19283 NewFD->setInvalidDecl();19284 19285 NewFD->setAccess(AS);19286 return NewFD;19287}19288 19289bool Sema::CheckNontrivialField(FieldDecl *FD) {19290 assert(FD);19291 assert(getLangOpts().CPlusPlus && "valid check only for C++");19292 19293 if (FD->isInvalidDecl() || FD->getType()->isDependentType())19294 return false;19295 19296 QualType EltTy = Context.getBaseElementType(FD->getType());19297 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();19298 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {19299 // We check for copy constructors before constructors19300 // because otherwise we'll never get complaints about19301 // copy constructors.19302 19303 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;19304 // We're required to check for any non-trivial constructors. Since the19305 // implicit default constructor is suppressed if there are any19306 // user-declared constructors, we just need to check that there is a19307 // trivial default constructor and a trivial copy constructor. (We don't19308 // worry about move constructors here, since this is a C++98 check.)19309 if (RDecl->hasNonTrivialCopyConstructor())19310 member = CXXSpecialMemberKind::CopyConstructor;19311 else if (!RDecl->hasTrivialDefaultConstructor())19312 member = CXXSpecialMemberKind::DefaultConstructor;19313 else if (RDecl->hasNonTrivialCopyAssignment())19314 member = CXXSpecialMemberKind::CopyAssignment;19315 else if (RDecl->hasNonTrivialDestructor())19316 member = CXXSpecialMemberKind::Destructor;19317 19318 if (member != CXXSpecialMemberKind::Invalid) {19319 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&19320 RDecl->hasObjectMember()) {19321 // Objective-C++ ARC: it is an error to have a non-trivial field of19322 // a union. However, system headers in Objective-C programs19323 // occasionally have Objective-C lifetime objects within unions,19324 // and rather than cause the program to fail, we make those19325 // members unavailable.19326 SourceLocation Loc = FD->getLocation();19327 if (getSourceManager().isInSystemHeader(Loc)) {19328 if (!FD->hasAttr<UnavailableAttr>())19329 FD->addAttr(UnavailableAttr::CreateImplicit(19330 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));19331 return false;19332 }19333 }19334 19335 Diag(FD->getLocation(),19336 getLangOpts().CPlusPlus1119337 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member19338 : diag::err_illegal_union_or_anon_struct_member)19339 << FD->getParent()->isUnion() << FD->getDeclName() << member;19340 DiagnoseNontrivial(RDecl, member);19341 return !getLangOpts().CPlusPlus11;19342 }19343 }19344 19345 return false;19346}19347 19348void Sema::ActOnLastBitfield(SourceLocation DeclLoc,19349 SmallVectorImpl<Decl *> &AllIvarDecls) {19350 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())19351 return;19352 19353 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];19354 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);19355 19356 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())19357 return;19358 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);19359 if (!ID) {19360 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {19361 if (!CD->IsClassExtension())19362 return;19363 }19364 // No need to add this to end of @implementation.19365 else19366 return;19367 }19368 // All conditions are met. Add a new bitfield to the tail end of ivars.19369 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);19370 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);19371 Expr *BitWidth =19372 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));19373 19374 Ivar = ObjCIvarDecl::Create(19375 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,19376 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),19377 ObjCIvarDecl::Private, BitWidth, true);19378 AllIvarDecls.push_back(Ivar);19379}19380 19381/// [class.dtor]p4:19382/// At the end of the definition of a class, overload resolution is19383/// performed among the prospective destructors declared in that class with19384/// an empty argument list to select the destructor for the class, also19385/// known as the selected destructor.19386///19387/// We do the overload resolution here, then mark the selected constructor in the AST.19388/// Later CXXRecordDecl::getDestructor() will return the selected constructor.19389static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {19390 if (!Record->hasUserDeclaredDestructor()) {19391 return;19392 }19393 19394 SourceLocation Loc = Record->getLocation();19395 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);19396 19397 for (auto *Decl : Record->decls()) {19398 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {19399 if (DD->isInvalidDecl())19400 continue;19401 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},19402 OCS);19403 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");19404 }19405 }19406 19407 if (OCS.empty()) {19408 return;19409 }19410 OverloadCandidateSet::iterator Best;19411 unsigned Msg = 0;19412 OverloadCandidateDisplayKind DisplayKind;19413 19414 switch (OCS.BestViableFunction(S, Loc, Best)) {19415 case OR_Success:19416 case OR_Deleted:19417 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));19418 break;19419 19420 case OR_Ambiguous:19421 Msg = diag::err_ambiguous_destructor;19422 DisplayKind = OCD_AmbiguousCandidates;19423 break;19424 19425 case OR_No_Viable_Function:19426 Msg = diag::err_no_viable_destructor;19427 DisplayKind = OCD_AllCandidates;19428 break;19429 }19430 19431 if (Msg) {19432 // OpenCL have got their own thing going with destructors. It's slightly broken,19433 // but we allow it.19434 if (!S.LangOpts.OpenCL) {19435 PartialDiagnostic Diag = S.PDiag(Msg) << Record;19436 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});19437 Record->setInvalidDecl();19438 }19439 // It's a bit hacky: At this point we've raised an error but we want the19440 // rest of the compiler to continue somehow working. However almost19441 // everything we'll try to do with the class will depend on there being a19442 // destructor. So let's pretend the first one is selected and hope for the19443 // best.19444 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));19445 }19446}19447 19448/// [class.mem.special]p519449/// Two special member functions are of the same kind if:19450/// - they are both default constructors,19451/// - they are both copy or move constructors with the same first parameter19452/// type, or19453/// - they are both copy or move assignment operators with the same first19454/// parameter type and the same cv-qualifiers and ref-qualifier, if any.19455static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,19456 CXXMethodDecl *M1,19457 CXXMethodDecl *M2,19458 CXXSpecialMemberKind CSM) {19459 // We don't want to compare templates to non-templates: See19460 // https://github.com/llvm/llvm-project/issues/5920619461 if (CSM == CXXSpecialMemberKind::DefaultConstructor)19462 return bool(M1->getDescribedFunctionTemplate()) ==19463 bool(M2->getDescribedFunctionTemplate());19464 // FIXME: better resolve CWG19465 // https://cplusplus.github.io/CWG/issues/2787.html19466 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),19467 M2->getNonObjectParameter(0)->getType()))19468 return false;19469 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),19470 M2->getFunctionObjectParameterReferenceType()))19471 return false;19472 19473 return true;19474}19475 19476/// [class.mem.special]p6:19477/// An eligible special member function is a special member function for which:19478/// - the function is not deleted,19479/// - the associated constraints, if any, are satisfied, and19480/// - no special member function of the same kind whose associated constraints19481/// [CWG2595], if any, are satisfied is more constrained.19482static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,19483 ArrayRef<CXXMethodDecl *> Methods,19484 CXXSpecialMemberKind CSM) {19485 SmallVector<bool, 4> SatisfactionStatus;19486 19487 for (CXXMethodDecl *Method : Methods) {19488 if (!Method->getTrailingRequiresClause())19489 SatisfactionStatus.push_back(true);19490 else {19491 ConstraintSatisfaction Satisfaction;19492 if (S.CheckFunctionConstraints(Method, Satisfaction))19493 SatisfactionStatus.push_back(false);19494 else19495 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);19496 }19497 }19498 19499 for (size_t i = 0; i < Methods.size(); i++) {19500 if (!SatisfactionStatus[i])19501 continue;19502 CXXMethodDecl *Method = Methods[i];19503 CXXMethodDecl *OrigMethod = Method;19504 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())19505 OrigMethod = cast<CXXMethodDecl>(MF);19506 19507 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();19508 bool AnotherMethodIsMoreConstrained = false;19509 for (size_t j = 0; j < Methods.size(); j++) {19510 if (i == j || !SatisfactionStatus[j])19511 continue;19512 CXXMethodDecl *OtherMethod = Methods[j];19513 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())19514 OtherMethod = cast<CXXMethodDecl>(MF);19515 19516 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,19517 CSM))19518 continue;19519 19520 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();19521 if (!Other)19522 continue;19523 if (!Orig) {19524 AnotherMethodIsMoreConstrained = true;19525 break;19526 }19527 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},19528 AnotherMethodIsMoreConstrained)) {19529 // There was an error with the constraints comparison. Exit the loop19530 // and don't consider this function eligible.19531 AnotherMethodIsMoreConstrained = true;19532 }19533 if (AnotherMethodIsMoreConstrained)19534 break;19535 }19536 // FIXME: Do not consider deleted methods as eligible after implementing19537 // DR1734 and DR1496.19538 if (!AnotherMethodIsMoreConstrained) {19539 Method->setIneligibleOrNotSelected(false);19540 Record->addedEligibleSpecialMemberFunction(Method,19541 1 << llvm::to_underlying(CSM));19542 }19543 }19544}19545 19546static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,19547 CXXRecordDecl *Record) {19548 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;19549 SmallVector<CXXMethodDecl *, 4> CopyConstructors;19550 SmallVector<CXXMethodDecl *, 4> MoveConstructors;19551 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;19552 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;19553 19554 for (auto *Decl : Record->decls()) {19555 auto *MD = dyn_cast<CXXMethodDecl>(Decl);19556 if (!MD) {19557 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);19558 if (FTD)19559 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());19560 }19561 if (!MD)19562 continue;19563 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {19564 if (CD->isInvalidDecl())19565 continue;19566 if (CD->isDefaultConstructor())19567 DefaultConstructors.push_back(MD);19568 else if (CD->isCopyConstructor())19569 CopyConstructors.push_back(MD);19570 else if (CD->isMoveConstructor())19571 MoveConstructors.push_back(MD);19572 } else if (MD->isCopyAssignmentOperator()) {19573 CopyAssignmentOperators.push_back(MD);19574 } else if (MD->isMoveAssignmentOperator()) {19575 MoveAssignmentOperators.push_back(MD);19576 }19577 }19578 19579 SetEligibleMethods(S, Record, DefaultConstructors,19580 CXXSpecialMemberKind::DefaultConstructor);19581 SetEligibleMethods(S, Record, CopyConstructors,19582 CXXSpecialMemberKind::CopyConstructor);19583 SetEligibleMethods(S, Record, MoveConstructors,19584 CXXSpecialMemberKind::MoveConstructor);19585 SetEligibleMethods(S, Record, CopyAssignmentOperators,19586 CXXSpecialMemberKind::CopyAssignment);19587 SetEligibleMethods(S, Record, MoveAssignmentOperators,19588 CXXSpecialMemberKind::MoveAssignment);19589}19590 19591bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {19592 // Check to see if a FieldDecl is a pointer to a function.19593 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {19594 const FieldDecl *FD = dyn_cast<FieldDecl>(D);19595 if (!FD) {19596 // Check whether this is a forward declaration that was inserted by19597 // Clang. This happens when a non-forward declared / defined type is19598 // used, e.g.:19599 //19600 // struct foo {19601 // struct bar *(*f)();19602 // struct bar *(*g)();19603 // };19604 //19605 // "struct bar" shows up in the decl AST as a "RecordDecl" with an19606 // incomplete definition.19607 if (const auto *TD = dyn_cast<TagDecl>(D))19608 return !TD->isCompleteDefinition();19609 return false;19610 }19611 QualType FieldType = FD->getType().getDesugaredType(Context);19612 if (isa<PointerType>(FieldType)) {19613 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();19614 return PointeeType.getDesugaredType(Context)->isFunctionType();19615 }19616 // If a member is a struct entirely of function pointers, that counts too.19617 if (const auto *Record = FieldType->getAsRecordDecl();19618 Record && Record->isStruct() && EntirelyFunctionPointers(Record))19619 return true;19620 return false;19621 };19622 19623 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);19624}19625 19626void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,19627 ArrayRef<Decl *> Fields, SourceLocation LBrac,19628 SourceLocation RBrac,19629 const ParsedAttributesView &Attrs) {19630 assert(EnclosingDecl && "missing record or interface decl");19631 19632 // If this is an Objective-C @implementation or category and we have19633 // new fields here we should reset the layout of the interface since19634 // it will now change.19635 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {19636 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);19637 switch (DC->getKind()) {19638 default: break;19639 case Decl::ObjCCategory:19640 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());19641 break;19642 case Decl::ObjCImplementation:19643 Context.19644 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());19645 break;19646 }19647 }19648 19649 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);19650 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);19651 19652 // Start counting up the number of named members; make sure to include19653 // members of anonymous structs and unions in the total.19654 unsigned NumNamedMembers = 0;19655 if (Record) {19656 for (const auto *I : Record->decls()) {19657 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))19658 if (IFD->getDeclName())19659 ++NumNamedMembers;19660 }19661 }19662 19663 // Verify that all the fields are okay.19664 SmallVector<FieldDecl*, 32> RecFields;19665 const FieldDecl *PreviousField = nullptr;19666 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();19667 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {19668 FieldDecl *FD = cast<FieldDecl>(*i);19669 19670 // Get the type for the field.19671 const Type *FDTy = FD->getType().getTypePtr();19672 19673 if (!FD->isAnonymousStructOrUnion()) {19674 // Remember all fields written by the user.19675 RecFields.push_back(FD);19676 }19677 19678 // If the field is already invalid for some reason, don't emit more19679 // diagnostics about it.19680 if (FD->isInvalidDecl()) {19681 EnclosingDecl->setInvalidDecl();19682 continue;19683 }19684 19685 // C99 6.7.2.1p2:19686 // A structure or union shall not contain a member with19687 // incomplete or function type (hence, a structure shall not19688 // contain an instance of itself, but may contain a pointer to19689 // an instance of itself), except that the last member of a19690 // structure with more than one named member may have incomplete19691 // array type; such a structure (and any union containing,19692 // possibly recursively, a member that is such a structure)19693 // shall not be a member of a structure or an element of an19694 // array.19695 bool IsLastField = (i + 1 == Fields.end());19696 if (FDTy->isFunctionType()) {19697 // Field declared as a function.19698 Diag(FD->getLocation(), diag::err_field_declared_as_function)19699 << FD->getDeclName();19700 FD->setInvalidDecl();19701 EnclosingDecl->setInvalidDecl();19702 continue;19703 } else if (FDTy->isIncompleteArrayType() &&19704 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {19705 if (Record) {19706 // Flexible array member.19707 // Microsoft and g++ is more permissive regarding flexible array.19708 // It will accept flexible array in union and also19709 // as the sole element of a struct/class.19710 unsigned DiagID = 0;19711 if (!Record->isUnion() && !IsLastField) {19712 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)19713 << FD->getDeclName() << FD->getType() << Record->getTagKind();19714 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);19715 FD->setInvalidDecl();19716 EnclosingDecl->setInvalidDecl();19717 continue;19718 } else if (Record->isUnion())19719 DiagID = getLangOpts().MicrosoftExt19720 ? diag::ext_flexible_array_union_ms19721 : diag::ext_flexible_array_union_gnu;19722 else if (NumNamedMembers < 1)19723 DiagID = getLangOpts().MicrosoftExt19724 ? diag::ext_flexible_array_empty_aggregate_ms19725 : diag::ext_flexible_array_empty_aggregate_gnu;19726 19727 if (DiagID)19728 Diag(FD->getLocation(), DiagID)19729 << FD->getDeclName() << Record->getTagKind();19730 // While the layout of types that contain virtual bases is not specified19731 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place19732 // virtual bases after the derived members. This would make a flexible19733 // array member declared at the end of an object not adjacent to the end19734 // of the type.19735 if (CXXRecord && CXXRecord->getNumVBases() != 0)19736 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)19737 << FD->getDeclName() << Record->getTagKind();19738 if (!getLangOpts().C99)19739 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)19740 << FD->getDeclName() << Record->getTagKind();19741 19742 // If the element type has a non-trivial destructor, we would not19743 // implicitly destroy the elements, so disallow it for now.19744 //19745 // FIXME: GCC allows this. We should probably either implicitly delete19746 // the destructor of the containing class, or just allow this.19747 QualType BaseElem = Context.getBaseElementType(FD->getType());19748 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {19749 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)19750 << FD->getDeclName() << FD->getType();19751 FD->setInvalidDecl();19752 EnclosingDecl->setInvalidDecl();19753 continue;19754 }19755 // Okay, we have a legal flexible array member at the end of the struct.19756 Record->setHasFlexibleArrayMember(true);19757 } else {19758 // In ObjCContainerDecl ivars with incomplete array type are accepted,19759 // unless they are followed by another ivar. That check is done19760 // elsewhere, after synthesized ivars are known.19761 }19762 } else if (!FDTy->isDependentType() &&19763 (LangOpts.HLSL // HLSL allows sizeless builtin types19764 ? RequireCompleteType(FD->getLocation(), FD->getType(),19765 diag::err_incomplete_type)19766 : RequireCompleteSizedType(19767 FD->getLocation(), FD->getType(),19768 diag::err_field_incomplete_or_sizeless))) {19769 // Incomplete type19770 FD->setInvalidDecl();19771 EnclosingDecl->setInvalidDecl();19772 continue;19773 } else if (const auto *RD = FDTy->getAsRecordDecl()) {19774 if (Record && RD->hasFlexibleArrayMember()) {19775 // A type which contains a flexible array member is considered to be a19776 // flexible array member.19777 Record->setHasFlexibleArrayMember(true);19778 if (!Record->isUnion()) {19779 // If this is a struct/class and this is not the last element, reject19780 // it. Note that GCC supports variable sized arrays in the middle of19781 // structures.19782 if (!IsLastField)19783 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)19784 << FD->getDeclName() << FD->getType();19785 else {19786 // We support flexible arrays at the end of structs in19787 // other structs as an extension.19788 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)19789 << FD->getDeclName();19790 }19791 }19792 }19793 if (isa<ObjCContainerDecl>(EnclosingDecl) &&19794 RequireNonAbstractType(FD->getLocation(), FD->getType(),19795 diag::err_abstract_type_in_decl,19796 AbstractIvarType)) {19797 // Ivars can not have abstract class types19798 FD->setInvalidDecl();19799 }19800 if (Record && RD->hasObjectMember())19801 Record->setHasObjectMember(true);19802 if (Record && RD->hasVolatileMember())19803 Record->setHasVolatileMember(true);19804 } else if (FDTy->isObjCObjectType()) {19805 /// A field cannot be an Objective-c object19806 Diag(FD->getLocation(), diag::err_statically_allocated_object)19807 << FixItHint::CreateInsertion(FD->getLocation(), "*");19808 QualType T = Context.getObjCObjectPointerType(FD->getType());19809 FD->setType(T);19810 } else if (Record && Record->isUnion() &&19811 FD->getType().hasNonTrivialObjCLifetime() &&19812 getSourceManager().isInSystemHeader(FD->getLocation()) &&19813 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&19814 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||19815 !Context.hasDirectOwnershipQualifier(FD->getType()))) {19816 // For backward compatibility, fields of C unions declared in system19817 // headers that have non-trivial ObjC ownership qualifications are marked19818 // as unavailable unless the qualifier is explicit and __strong. This can19819 // break ABI compatibility between programs compiled with ARC and MRR, but19820 // is a better option than rejecting programs using those unions under19821 // ARC.19822 FD->addAttr(UnavailableAttr::CreateImplicit(19823 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,19824 FD->getLocation()));19825 } else if (getLangOpts().ObjC &&19826 getLangOpts().getGC() != LangOptions::NonGC && Record &&19827 !Record->hasObjectMember()) {19828 if (FD->getType()->isObjCObjectPointerType() ||19829 FD->getType().isObjCGCStrong())19830 Record->setHasObjectMember(true);19831 else if (Context.getAsArrayType(FD->getType())) {19832 QualType BaseType = Context.getBaseElementType(FD->getType());19833 if (const auto *RD = BaseType->getAsRecordDecl();19834 RD && RD->hasObjectMember())19835 Record->setHasObjectMember(true);19836 else if (BaseType->isObjCObjectPointerType() ||19837 BaseType.isObjCGCStrong())19838 Record->setHasObjectMember(true);19839 }19840 }19841 19842 if (Record && !getLangOpts().CPlusPlus &&19843 !shouldIgnoreForRecordTriviality(FD)) {19844 QualType FT = FD->getType();19845 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {19846 Record->setNonTrivialToPrimitiveDefaultInitialize(true);19847 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||19848 Record->isUnion())19849 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);19850 }19851 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();19852 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {19853 Record->setNonTrivialToPrimitiveCopy(true);19854 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())19855 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);19856 }19857 if (FD->hasAttr<ExplicitInitAttr>())19858 Record->setHasUninitializedExplicitInitFields(true);19859 if (FT.isDestructedType()) {19860 Record->setNonTrivialToPrimitiveDestroy(true);19861 Record->setParamDestroyedInCallee(true);19862 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())19863 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);19864 }19865 19866 if (const auto *RD = FT->getAsRecordDecl()) {19867 if (RD->getArgPassingRestrictions() ==19868 RecordArgPassingKind::CanNeverPassInRegs)19869 Record->setArgPassingRestrictions(19870 RecordArgPassingKind::CanNeverPassInRegs);19871 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {19872 Record->setArgPassingRestrictions(19873 RecordArgPassingKind::CanNeverPassInRegs);19874 } else if (PointerAuthQualifier Q = FT.getPointerAuth();19875 Q && Q.isAddressDiscriminated()) {19876 Record->setArgPassingRestrictions(19877 RecordArgPassingKind::CanNeverPassInRegs);19878 Record->setNonTrivialToPrimitiveCopy(true);19879 }19880 }19881 19882 if (Record && FD->getType().isVolatileQualified())19883 Record->setHasVolatileMember(true);19884 bool ReportMSBitfieldStoragePacking =19885 Record && PreviousField &&19886 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,19887 Record->getLocation());19888 auto IsNonDependentBitField = [](const FieldDecl *FD) {19889 return FD->isBitField() && !FD->getType()->isDependentType();19890 };19891 19892 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&19893 IsNonDependentBitField(PreviousField)) {19894 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());19895 CharUnits PreviousFieldStorageSize =19896 Context.getTypeSizeInChars(PreviousField->getType());19897 if (FDStorageSize != PreviousFieldStorageSize) {19898 Diag(FD->getLocation(),19899 diag::warn_ms_bitfield_mismatched_storage_packing)19900 << FD << FD->getType() << FDStorageSize.getQuantity()19901 << PreviousFieldStorageSize.getQuantity();19902 Diag(PreviousField->getLocation(),19903 diag::note_ms_bitfield_mismatched_storage_size_previous)19904 << PreviousField << PreviousField->getType();19905 }19906 }19907 // Keep track of the number of named members.19908 if (FD->getIdentifier())19909 ++NumNamedMembers;19910 }19911 19912 // Okay, we successfully defined 'Record'.19913 if (Record) {19914 bool Completed = false;19915 if (S) {19916 Scope *Parent = S->getParent();19917 if (Parent && Parent->isTypeAliasScope() &&19918 Parent->isTemplateParamScope())19919 Record->setInvalidDecl();19920 }19921 19922 if (CXXRecord) {19923 if (!CXXRecord->isInvalidDecl()) {19924 // Set access bits correctly on the directly-declared conversions.19925 for (CXXRecordDecl::conversion_iterator19926 I = CXXRecord->conversion_begin(),19927 E = CXXRecord->conversion_end(); I != E; ++I)19928 I.setAccess((*I)->getAccess());19929 }19930 19931 // Add any implicitly-declared members to this class.19932 AddImplicitlyDeclaredMembersToClass(CXXRecord);19933 19934 if (!CXXRecord->isDependentType()) {19935 if (!CXXRecord->isInvalidDecl()) {19936 // If we have virtual base classes, we may end up finding multiple19937 // final overriders for a given virtual function. Check for this19938 // problem now.19939 if (CXXRecord->getNumVBases()) {19940 CXXFinalOverriderMap FinalOverriders;19941 CXXRecord->getFinalOverriders(FinalOverriders);19942 19943 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),19944 MEnd = FinalOverriders.end();19945 M != MEnd; ++M) {19946 for (OverridingMethods::iterator SO = M->second.begin(),19947 SOEnd = M->second.end();19948 SO != SOEnd; ++SO) {19949 assert(SO->second.size() > 0 &&19950 "Virtual function without overriding functions?");19951 if (SO->second.size() == 1)19952 continue;19953 19954 // C++ [class.virtual]p2:19955 // In a derived class, if a virtual member function of a base19956 // class subobject has more than one final overrider the19957 // program is ill-formed.19958 Diag(Record->getLocation(), diag::err_multiple_final_overriders)19959 << (const NamedDecl *)M->first << Record;19960 Diag(M->first->getLocation(),19961 diag::note_overridden_virtual_function);19962 for (OverridingMethods::overriding_iterator19963 OM = SO->second.begin(),19964 OMEnd = SO->second.end();19965 OM != OMEnd; ++OM)19966 Diag(OM->Method->getLocation(), diag::note_final_overrider)19967 << (const NamedDecl *)M->first << OM->Method->getParent();19968 19969 Record->setInvalidDecl();19970 }19971 }19972 CXXRecord->completeDefinition(&FinalOverriders);19973 Completed = true;19974 }19975 }19976 ComputeSelectedDestructor(*this, CXXRecord);19977 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);19978 }19979 }19980 19981 if (!Completed)19982 Record->completeDefinition();19983 19984 // Handle attributes before checking the layout.19985 ProcessDeclAttributeList(S, Record, Attrs);19986 19987 // Maybe randomize the record's decls. We automatically randomize a record19988 // of function pointers, unless it has the "no_randomize_layout" attribute.19989 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&19990 !Record->isRandomized() && !Record->isUnion() &&19991 (Record->hasAttr<RandomizeLayoutAttr>() ||19992 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&19993 EntirelyFunctionPointers(Record)))) {19994 SmallVector<Decl *, 32> NewDeclOrdering;19995 if (randstruct::randomizeStructureLayout(Context, Record,19996 NewDeclOrdering))19997 Record->reorderDecls(NewDeclOrdering);19998 }19999 20000 // We may have deferred checking for a deleted destructor. Check now.20001 if (CXXRecord) {20002 auto *Dtor = CXXRecord->getDestructor();20003 if (Dtor && Dtor->isImplicit() &&20004 ShouldDeleteSpecialMember(Dtor, CXXSpecialMemberKind::Destructor)) {20005 CXXRecord->setImplicitDestructorIsDeleted();20006 SetDeclDeleted(Dtor, CXXRecord->getLocation());20007 }20008 }20009 20010 if (Record->hasAttrs()) {20011 CheckAlignasUnderalignment(Record);20012 20013 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())20014 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),20015 IA->getRange(), IA->getBestCase(),20016 IA->getInheritanceModel());20017 }20018 20019 // Check if the structure/union declaration is a type that can have zero20020 // size in C. For C this is a language extension, for C++ it may cause20021 // compatibility problems.20022 bool CheckForZeroSize;20023 if (!getLangOpts().CPlusPlus) {20024 CheckForZeroSize = true;20025 } else {20026 // For C++ filter out types that cannot be referenced in C code.20027 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);20028 CheckForZeroSize =20029 CXXRecord->getLexicalDeclContext()->isExternCContext() &&20030 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&20031 CXXRecord->isCLike();20032 }20033 if (CheckForZeroSize) {20034 bool ZeroSize = true;20035 bool IsEmpty = true;20036 unsigned NonBitFields = 0;20037 for (RecordDecl::field_iterator I = Record->field_begin(),20038 E = Record->field_end();20039 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {20040 IsEmpty = false;20041 if (I->isUnnamedBitField()) {20042 if (!I->isZeroLengthBitField())20043 ZeroSize = false;20044 } else {20045 ++NonBitFields;20046 QualType FieldType = I->getType();20047 if (FieldType->isIncompleteType() ||20048 !Context.getTypeSizeInChars(FieldType).isZero())20049 ZeroSize = false;20050 }20051 }20052 20053 // Empty structs are an extension in C (C99 6.7.2.1p7). They are20054 // allowed in C++, but warn if its declaration is inside20055 // extern "C" block.20056 if (ZeroSize) {20057 Diag(RecLoc, getLangOpts().CPlusPlus ?20058 diag::warn_zero_size_struct_union_in_extern_c :20059 diag::warn_zero_size_struct_union_compat)20060 << IsEmpty << Record->isUnion() << (NonBitFields > 1);20061 }20062 20063 // Structs without named members are extension in C (C99 6.7.2.1p7),20064 // but are accepted by GCC. In C2y, this became implementation-defined20065 // (C2y 6.7.3.2p10).20066 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {20067 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union20068 : diag::ext_no_named_members_in_struct_union)20069 << Record->isUnion();20070 }20071 }20072 } else {20073 ObjCIvarDecl **ClsFields =20074 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());20075 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {20076 ID->setEndOfDefinitionLoc(RBrac);20077 // Add ivar's to class's DeclContext.20078 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {20079 ClsFields[i]->setLexicalDeclContext(ID);20080 ID->addDecl(ClsFields[i]);20081 }20082 // Must enforce the rule that ivars in the base classes may not be20083 // duplicates.20084 if (ID->getSuperClass())20085 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());20086 } else if (ObjCImplementationDecl *IMPDecl =20087 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {20088 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");20089 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)20090 // Ivar declared in @implementation never belongs to the implementation.20091 // Only it is in implementation's lexical context.20092 ClsFields[I]->setLexicalDeclContext(IMPDecl);20093 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),20094 RBrac);20095 IMPDecl->setIvarLBraceLoc(LBrac);20096 IMPDecl->setIvarRBraceLoc(RBrac);20097 } else if (ObjCCategoryDecl *CDecl =20098 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {20099 // case of ivars in class extension; all other cases have been20100 // reported as errors elsewhere.20101 // FIXME. Class extension does not have a LocEnd field.20102 // CDecl->setLocEnd(RBrac);20103 // Add ivar's to class extension's DeclContext.20104 // Diagnose redeclaration of private ivars.20105 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();20106 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {20107 if (IDecl) {20108 if (const ObjCIvarDecl *ClsIvar =20109 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {20110 Diag(ClsFields[i]->getLocation(),20111 diag::err_duplicate_ivar_declaration);20112 Diag(ClsIvar->getLocation(), diag::note_previous_definition);20113 continue;20114 }20115 for (const auto *Ext : IDecl->known_extensions()) {20116 if (const ObjCIvarDecl *ClsExtIvar20117 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {20118 Diag(ClsFields[i]->getLocation(),20119 diag::err_duplicate_ivar_declaration);20120 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);20121 continue;20122 }20123 }20124 }20125 ClsFields[i]->setLexicalDeclContext(CDecl);20126 CDecl->addDecl(ClsFields[i]);20127 }20128 CDecl->setIvarLBraceLoc(LBrac);20129 CDecl->setIvarRBraceLoc(RBrac);20130 }20131 }20132 ProcessAPINotes(Record);20133}20134 20135// Given an integral type, return the next larger integral type20136// (or a NULL type of no such type exists).20137static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {20138 // FIXME: Int128/UInt128 support, which also needs to be introduced into20139 // enum checking below.20140 assert((T->isIntegralType(Context) ||20141 T->isEnumeralType()) && "Integral type required!");20142 const unsigned NumTypes = 4;20143 QualType SignedIntegralTypes[NumTypes] = {20144 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy20145 };20146 QualType UnsignedIntegralTypes[NumTypes] = {20147 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,20148 Context.UnsignedLongLongTy20149 };20150 20151 unsigned BitWidth = Context.getTypeSize(T);20152 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes20153 : UnsignedIntegralTypes;20154 for (unsigned I = 0; I != NumTypes; ++I)20155 if (Context.getTypeSize(Types[I]) > BitWidth)20156 return Types[I];20157 20158 return QualType();20159}20160 20161EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,20162 EnumConstantDecl *LastEnumConst,20163 SourceLocation IdLoc,20164 IdentifierInfo *Id,20165 Expr *Val) {20166 unsigned IntWidth = Context.getTargetInfo().getIntWidth();20167 llvm::APSInt EnumVal(IntWidth);20168 QualType EltTy;20169 20170 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))20171 Val = nullptr;20172 20173 if (Val)20174 Val = DefaultLvalueConversion(Val).get();20175 20176 if (Val) {20177 if (Enum->isDependentType() || Val->isTypeDependent() ||20178 Val->containsErrors())20179 EltTy = Context.DependentTy;20180 else {20181 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed20182 // underlying type, but do allow it in all other contexts.20183 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {20184 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the20185 // constant-expression in the enumerator-definition shall be a converted20186 // constant expression of the underlying type.20187 EltTy = Enum->getIntegerType();20188 ExprResult Converted = CheckConvertedConstantExpression(20189 Val, EltTy, EnumVal, CCEKind::Enumerator);20190 if (Converted.isInvalid())20191 Val = nullptr;20192 else20193 Val = Converted.get();20194 } else if (!Val->isValueDependent() &&20195 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,20196 AllowFoldKind::Allow)20197 .get())) {20198 // C99 6.7.2.2p2: Make sure we have an integer constant expression.20199 } else {20200 if (Enum->isComplete()) {20201 EltTy = Enum->getIntegerType();20202 20203 // In Obj-C and Microsoft mode, require the enumeration value to be20204 // representable in the underlying type of the enumeration. In C++11,20205 // we perform a non-narrowing conversion as part of converted constant20206 // expression checking.20207 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {20208 if (Context.getTargetInfo()20209 .getTriple()20210 .isWindowsMSVCEnvironment()) {20211 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;20212 } else {20213 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;20214 }20215 }20216 20217 // Cast to the underlying type.20218 Val = ImpCastExprToType(Val, EltTy,20219 EltTy->isBooleanType() ? CK_IntegralToBoolean20220 : CK_IntegralCast)20221 .get();20222 } else if (getLangOpts().CPlusPlus) {20223 // C++11 [dcl.enum]p5:20224 // If the underlying type is not fixed, the type of each enumerator20225 // is the type of its initializing value:20226 // - If an initializer is specified for an enumerator, the20227 // initializing value has the same type as the expression.20228 EltTy = Val->getType();20229 } else {20230 // C99 6.7.2.2p2:20231 // The expression that defines the value of an enumeration constant20232 // shall be an integer constant expression that has a value20233 // representable as an int.20234 20235 // Complain if the value is not representable in an int.20236 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {20237 Diag(IdLoc, getLangOpts().C2320238 ? diag::warn_c17_compat_enum_value_not_int20239 : diag::ext_c23_enum_value_not_int)20240 << 0 << toString(EnumVal, 10) << Val->getSourceRange()20241 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());20242 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {20243 // Force the type of the expression to 'int'.20244 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();20245 }20246 EltTy = Val->getType();20247 }20248 }20249 }20250 }20251 20252 if (!Val) {20253 if (Enum->isDependentType())20254 EltTy = Context.DependentTy;20255 else if (!LastEnumConst) {20256 // C++0x [dcl.enum]p5:20257 // If the underlying type is not fixed, the type of each enumerator20258 // is the type of its initializing value:20259 // - If no initializer is specified for the first enumerator, the20260 // initializing value has an unspecified integral type.20261 //20262 // GCC uses 'int' for its unspecified integral type, as does20263 // C99 6.7.2.2p3.20264 if (Enum->isFixed()) {20265 EltTy = Enum->getIntegerType();20266 }20267 else {20268 EltTy = Context.IntTy;20269 }20270 } else {20271 // Assign the last value + 1.20272 EnumVal = LastEnumConst->getInitVal();20273 ++EnumVal;20274 EltTy = LastEnumConst->getType();20275 20276 // Check for overflow on increment.20277 if (EnumVal < LastEnumConst->getInitVal()) {20278 // C++0x [dcl.enum]p5:20279 // If the underlying type is not fixed, the type of each enumerator20280 // is the type of its initializing value:20281 //20282 // - Otherwise the type of the initializing value is the same as20283 // the type of the initializing value of the preceding enumerator20284 // unless the incremented value is not representable in that type,20285 // in which case the type is an unspecified integral type20286 // sufficient to contain the incremented value. If no such type20287 // exists, the program is ill-formed.20288 QualType T = getNextLargerIntegralType(Context, EltTy);20289 if (T.isNull() || Enum->isFixed()) {20290 // There is no integral type larger enough to represent this20291 // value. Complain, then allow the value to wrap around.20292 EnumVal = LastEnumConst->getInitVal();20293 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);20294 ++EnumVal;20295 if (Enum->isFixed())20296 // When the underlying type is fixed, this is ill-formed.20297 Diag(IdLoc, diag::err_enumerator_wrapped)20298 << toString(EnumVal, 10)20299 << EltTy;20300 else20301 Diag(IdLoc, diag::ext_enumerator_increment_too_large)20302 << toString(EnumVal, 10);20303 } else {20304 EltTy = T;20305 }20306 20307 // Retrieve the last enumerator's value, extent that type to the20308 // type that is supposed to be large enough to represent the incremented20309 // value, then increment.20310 EnumVal = LastEnumConst->getInitVal();20311 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());20312 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));20313 ++EnumVal;20314 20315 // If we're not in C++, diagnose the overflow of enumerator values,20316 // which in C99 means that the enumerator value is not representable in20317 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that20318 // are representable in some larger integral type and we allow it in20319 // older language modes as an extension.20320 // Exclude fixed enumerators since they are diagnosed with an error for20321 // this case.20322 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())20323 Diag(IdLoc, getLangOpts().C2320324 ? diag::warn_c17_compat_enum_value_not_int20325 : diag::ext_c23_enum_value_not_int)20326 << 1 << toString(EnumVal, 10) << 1;20327 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&20328 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {20329 // Enforce C99 6.7.2.2p2 even when we compute the next value.20330 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int20331 : diag::ext_c23_enum_value_not_int)20332 << 1 << toString(EnumVal, 10) << 1;20333 }20334 }20335 }20336 20337 if (!EltTy->isDependentType()) {20338 // Make the enumerator value match the signedness and size of the20339 // enumerator's type.20340 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));20341 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());20342 }20343 20344 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,20345 Val, EnumVal);20346}20347 20348SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,20349 SourceLocation IILoc) {20350 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||20351 !getLangOpts().CPlusPlus)20352 return SkipBodyInfo();20353 20354 // We have an anonymous enum definition. Look up the first enumerator to20355 // determine if we should merge the definition with an existing one and20356 // skip the body.20357 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,20358 forRedeclarationInCurContext());20359 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);20360 if (!PrevECD)20361 return SkipBodyInfo();20362 20363 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());20364 NamedDecl *Hidden;20365 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {20366 SkipBodyInfo Skip;20367 Skip.Previous = Hidden;20368 return Skip;20369 }20370 20371 return SkipBodyInfo();20372}20373 20374Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,20375 SourceLocation IdLoc, IdentifierInfo *Id,20376 const ParsedAttributesView &Attrs,20377 SourceLocation EqualLoc, Expr *Val,20378 SkipBodyInfo *SkipBody) {20379 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);20380 EnumConstantDecl *LastEnumConst =20381 cast_or_null<EnumConstantDecl>(lastEnumConst);20382 20383 // The scope passed in may not be a decl scope. Zip up the scope tree until20384 // we find one that is.20385 S = getNonFieldDeclScope(S);20386 20387 // Verify that there isn't already something declared with this name in this20388 // scope.20389 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,20390 RedeclarationKind::ForVisibleRedeclaration);20391 LookupName(R, S);20392 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();20393 20394 if (PrevDecl && PrevDecl->isTemplateParameter()) {20395 // Maybe we will complain about the shadowed template parameter.20396 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);20397 // Just pretend that we didn't see the previous declaration.20398 PrevDecl = nullptr;20399 }20400 20401 // C++ [class.mem]p15:20402 // If T is the name of a class, then each of the following shall have a name20403 // different from T:20404 // - every enumerator of every member of class T that is an unscoped20405 // enumerated type20406 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&20407 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),20408 DeclarationNameInfo(Id, IdLoc)))20409 return nullptr;20410 20411 EnumConstantDecl *New =20412 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);20413 if (!New)20414 return nullptr;20415 20416 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {20417 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {20418 // Check for other kinds of shadowing not already handled.20419 CheckShadow(New, PrevDecl, R);20420 }20421 20422 // When in C++, we may get a TagDecl with the same name; in this case the20423 // enum constant will 'hide' the tag.20424 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&20425 "Received TagDecl when not in C++!");20426 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {20427 if (isa<EnumConstantDecl>(PrevDecl))20428 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;20429 else20430 Diag(IdLoc, diag::err_redefinition) << Id;20431 notePreviousDefinition(PrevDecl, IdLoc);20432 return nullptr;20433 }20434 }20435 20436 // Process attributes.20437 ProcessDeclAttributeList(S, New, Attrs);20438 AddPragmaAttributes(S, New);20439 ProcessAPINotes(New);20440 20441 // Register this decl in the current scope stack.20442 New->setAccess(TheEnumDecl->getAccess());20443 PushOnScopeChains(New, S);20444 20445 ActOnDocumentableDecl(New);20446 20447 return New;20448}20449 20450// Returns true when the enum initial expression does not trigger the20451// duplicate enum warning. A few common cases are exempted as follows:20452// Element2 = Element120453// Element2 = Element1 + 120454// Element2 = Element1 - 120455// Where Element2 and Element1 are from the same enum.20456static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {20457 Expr *InitExpr = ECD->getInitExpr();20458 if (!InitExpr)20459 return true;20460 InitExpr = InitExpr->IgnoreImpCasts();20461 20462 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {20463 if (!BO->isAdditiveOp())20464 return true;20465 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());20466 if (!IL)20467 return true;20468 if (IL->getValue() != 1)20469 return true;20470 20471 InitExpr = BO->getLHS();20472 }20473 20474 // This checks if the elements are from the same enum.20475 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);20476 if (!DRE)20477 return true;20478 20479 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());20480 if (!EnumConstant)20481 return true;20482 20483 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=20484 Enum)20485 return true;20486 20487 return false;20488}20489 20490// Emits a warning when an element is implicitly set a value that20491// a previous element has already been set to.20492static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,20493 EnumDecl *Enum, QualType EnumType) {20494 // Avoid anonymous enums20495 if (!Enum->getIdentifier())20496 return;20497 20498 // Only check for small enums.20499 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)20500 return;20501 20502 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))20503 return;20504 20505 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;20506 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;20507 20508 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;20509 20510 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.20511 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;20512 20513 // Use int64_t as a key to avoid needing special handling for map keys.20514 auto EnumConstantToKey = [](const EnumConstantDecl *D) {20515 llvm::APSInt Val = D->getInitVal();20516 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();20517 };20518 20519 DuplicatesVector DupVector;20520 ValueToVectorMap EnumMap;20521 20522 // Populate the EnumMap with all values represented by enum constants without20523 // an initializer.20524 for (auto *Element : Elements) {20525 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);20526 20527 // Null EnumConstantDecl means a previous diagnostic has been emitted for20528 // this constant. Skip this enum since it may be ill-formed.20529 if (!ECD) {20530 return;20531 }20532 20533 // Constants with initializers are handled in the next loop.20534 if (ECD->getInitExpr())20535 continue;20536 20537 // Duplicate values are handled in the next loop.20538 EnumMap.insert({EnumConstantToKey(ECD), ECD});20539 }20540 20541 if (EnumMap.size() == 0)20542 return;20543 20544 // Create vectors for any values that has duplicates.20545 for (auto *Element : Elements) {20546 // The last loop returned if any constant was null.20547 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);20548 if (!ValidDuplicateEnum(ECD, Enum))20549 continue;20550 20551 auto Iter = EnumMap.find(EnumConstantToKey(ECD));20552 if (Iter == EnumMap.end())20553 continue;20554 20555 DeclOrVector& Entry = Iter->second;20556 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {20557 // Ensure constants are different.20558 if (D == ECD)20559 continue;20560 20561 // Create new vector and push values onto it.20562 auto Vec = std::make_unique<ECDVector>();20563 Vec->push_back(D);20564 Vec->push_back(ECD);20565 20566 // Update entry to point to the duplicates vector.20567 Entry = Vec.get();20568 20569 // Store the vector somewhere we can consult later for quick emission of20570 // diagnostics.20571 DupVector.emplace_back(std::move(Vec));20572 continue;20573 }20574 20575 ECDVector *Vec = cast<ECDVector *>(Entry);20576 // Make sure constants are not added more than once.20577 if (*Vec->begin() == ECD)20578 continue;20579 20580 Vec->push_back(ECD);20581 }20582 20583 // Emit diagnostics.20584 for (const auto &Vec : DupVector) {20585 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");20586 20587 // Emit warning for one enum constant.20588 auto *FirstECD = Vec->front();20589 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)20590 << FirstECD << toString(FirstECD->getInitVal(), 10)20591 << FirstECD->getSourceRange();20592 20593 // Emit one note for each of the remaining enum constants with20594 // the same value.20595 for (auto *ECD : llvm::drop_begin(*Vec))20596 S.Diag(ECD->getLocation(), diag::note_duplicate_element)20597 << ECD << toString(ECD->getInitVal(), 10)20598 << ECD->getSourceRange();20599 }20600}20601 20602bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,20603 bool AllowMask) const {20604 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");20605 assert(ED->isCompleteDefinition() && "expected enum definition");20606 20607 auto R = FlagBitsCache.try_emplace(ED);20608 llvm::APInt &FlagBits = R.first->second;20609 20610 if (R.second) {20611 for (auto *E : ED->enumerators()) {20612 const auto &EVal = E->getInitVal();20613 // Only single-bit enumerators introduce new flag values.20614 if (EVal.isPowerOf2())20615 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;20616 }20617 }20618 20619 // A value is in a flag enum if either its bits are a subset of the enum's20620 // flag bits (the first condition) or we are allowing masks and the same is20621 // true of its complement (the second condition). When masks are allowed, we20622 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.20623 //20624 // While it's true that any value could be used as a mask, the assumption is20625 // that a mask will have all of the insignificant bits set. Anything else is20626 // likely a logic error.20627 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());20628 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));20629}20630 20631// Emits a warning when a suspicious comparison operator is used along side20632// binary operators in enum initializers.20633static void CheckForComparisonInEnumInitializer(SemaBase &Sema,20634 const EnumDecl *Enum) {20635 bool HasBitwiseOp = false;20636 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;20637 20638 // Iterate over all the enum values, gather suspisious comparison ops and20639 // whether any enum initialisers contain a binary operator.20640 for (const auto *ECD : Enum->enumerators()) {20641 const Expr *InitExpr = ECD->getInitExpr();20642 if (!InitExpr)20643 continue;20644 20645 const Expr *E = InitExpr->IgnoreParenImpCasts();20646 20647 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {20648 BinaryOperatorKind Op = BinOp->getOpcode();20649 20650 // Check for bitwise ops (<<, >>, &, |)20651 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {20652 HasBitwiseOp = true;20653 } else if (Op == BO_LT || Op == BO_GT) {20654 // Check for the typo pattern (Comparison < or >)20655 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();20656 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(LHS)) {20657 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"20658 if (IntLiteral->getValue() == 1)20659 SuspiciousCompares.push_back(BinOp);20660 }20661 }20662 }20663 }20664 20665 // If we found a bitwise op and some sus compares, iterate over the compares20666 // and warn.20667 if (HasBitwiseOp) {20668 for (const auto *BinOp : SuspiciousCompares) {20669 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)20670 ? BinaryOperator::getOpcodeStr(BO_Shl)20671 : BinaryOperator::getOpcodeStr(BO_Shr);20672 SourceLocation OperatorLoc = BinOp->getOperatorLoc();20673 20674 Sema.Diag(OperatorLoc, diag::warn_comparison_in_enum_initializer)20675 << BinOp->getOpcodeStr() << SuggestedOp;20676 20677 Sema.Diag(OperatorLoc, diag::note_enum_compare_typo_suggest)20678 << SuggestedOp20679 << FixItHint::CreateReplacement(OperatorLoc, SuggestedOp);20680 }20681 }20682}20683 20684void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,20685 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,20686 const ParsedAttributesView &Attrs) {20687 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);20688 CanQualType EnumType = Context.getCanonicalTagType(Enum);20689 20690 ProcessDeclAttributeList(S, Enum, Attrs);20691 ProcessAPINotes(Enum);20692 20693 if (Enum->isDependentType()) {20694 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {20695 EnumConstantDecl *ECD =20696 cast_or_null<EnumConstantDecl>(Elements[i]);20697 if (!ECD) continue;20698 20699 ECD->setType(EnumType);20700 }20701 20702 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);20703 return;20704 }20705 20706 // Verify that all the values are okay, compute the size of the values, and20707 // reverse the list.20708 unsigned NumNegativeBits = 0;20709 unsigned NumPositiveBits = 0;20710 bool MembersRepresentableByInt =20711 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);20712 20713 // Figure out the type that should be used for this enum.20714 QualType BestType;20715 unsigned BestWidth;20716 20717 // C++0x N3000 [conv.prom]p3:20718 // An rvalue of an unscoped enumeration type whose underlying20719 // type is not fixed can be converted to an rvalue of the first20720 // of the following types that can represent all the values of20721 // the enumeration: int, unsigned int, long int, unsigned long20722 // int, long long int, or unsigned long long int.20723 // C99 6.4.4.3p2:20724 // An identifier declared as an enumeration constant has type int.20725 // The C99 rule is modified by C23.20726 QualType BestPromotionType;20727 20728 bool Packed = Enum->hasAttr<PackedAttr>();20729 // -fshort-enums is the equivalent to specifying the packed attribute on all20730 // enum definitions.20731 if (LangOpts.ShortEnums)20732 Packed = true;20733 20734 // If the enum already has a type because it is fixed or dictated by the20735 // target, promote that type instead of analyzing the enumerators.20736 if (Enum->isComplete()) {20737 BestType = Enum->getIntegerType();20738 if (Context.isPromotableIntegerType(BestType))20739 BestPromotionType = Context.getPromotedIntegerType(BestType);20740 else20741 BestPromotionType = BestType;20742 20743 BestWidth = Context.getIntWidth(BestType);20744 } else {20745 bool EnumTooLarge = Context.computeBestEnumTypes(20746 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);20747 BestWidth = Context.getIntWidth(BestType);20748 if (EnumTooLarge)20749 Diag(Enum->getLocation(), diag::ext_enum_too_large);20750 }20751 20752 // Loop over all of the enumerator constants, changing their types to match20753 // the type of the enum if needed.20754 for (auto *D : Elements) {20755 auto *ECD = cast_or_null<EnumConstantDecl>(D);20756 if (!ECD) continue; // Already issued a diagnostic.20757 20758 // C99 says the enumerators have int type, but we allow, as an20759 // extension, the enumerators to be larger than int size. If each20760 // enumerator value fits in an int, type it as an int, otherwise type it the20761 // same as the enumerator decl itself. This means that in "enum { X = 1U }"20762 // that X has type 'int', not 'unsigned'.20763 20764 // Determine whether the value fits into an int.20765 llvm::APSInt InitVal = ECD->getInitVal();20766 20767 // If it fits into an integer type, force it. Otherwise force it to match20768 // the enum decl type.20769 QualType NewTy;20770 unsigned NewWidth;20771 bool NewSign;20772 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&20773 MembersRepresentableByInt) {20774 // C23 6.7.3.3.3p15:20775 // The enumeration member type for an enumerated type without fixed20776 // underlying type upon completion is:20777 // - int if all the values of the enumeration are representable as an20778 // int; or,20779 // - the enumerated type20780 NewTy = Context.IntTy;20781 NewWidth = Context.getTargetInfo().getIntWidth();20782 NewSign = true;20783 } else if (ECD->getType() == BestType) {20784 // Already the right type!20785 if (getLangOpts().CPlusPlus)20786 // C++ [dcl.enum]p4: Following the closing brace of an20787 // enum-specifier, each enumerator has the type of its20788 // enumeration.20789 ECD->setType(EnumType);20790 continue;20791 } else {20792 NewTy = BestType;20793 NewWidth = BestWidth;20794 NewSign = BestType->isSignedIntegerOrEnumerationType();20795 }20796 20797 // Adjust the APSInt value.20798 InitVal = InitVal.extOrTrunc(NewWidth);20799 InitVal.setIsSigned(NewSign);20800 ECD->setInitVal(Context, InitVal);20801 20802 // Adjust the Expr initializer and type.20803 if (ECD->getInitExpr() &&20804 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))20805 ECD->setInitExpr(ImplicitCastExpr::Create(20806 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),20807 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));20808 if (getLangOpts().CPlusPlus)20809 // C++ [dcl.enum]p4: Following the closing brace of an20810 // enum-specifier, each enumerator has the type of its20811 // enumeration.20812 ECD->setType(EnumType);20813 else20814 ECD->setType(NewTy);20815 }20816 20817 Enum->completeDefinition(BestType, BestPromotionType,20818 NumPositiveBits, NumNegativeBits);20819 20820 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);20821 CheckForComparisonInEnumInitializer(*this, Enum);20822 20823 if (Enum->isClosedFlag()) {20824 for (Decl *D : Elements) {20825 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);20826 if (!ECD) continue; // Already issued a diagnostic.20827 20828 llvm::APSInt InitVal = ECD->getInitVal();20829 if (InitVal != 0 && !InitVal.isPowerOf2() &&20830 !IsValueInFlagEnum(Enum, InitVal, true))20831 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)20832 << ECD << Enum;20833 }20834 }20835 20836 // Now that the enum type is defined, ensure it's not been underaligned.20837 if (Enum->hasAttrs())20838 CheckAlignasUnderalignment(Enum);20839}20840 20841Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,20842 SourceLocation EndLoc) {20843 20844 FileScopeAsmDecl *New =20845 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);20846 CurContext->addDecl(New);20847 return New;20848}20849 20850TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {20851 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);20852 CurContext->addDecl(New);20853 PushDeclContext(S, New);20854 PushFunctionScope();20855 PushCompoundScope(false);20856 return New;20857}20858 20859void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {20860 if (Statement)20861 D->setStmt(Statement);20862 PopCompoundScope();20863 PopFunctionScopeInfo();20864 PopDeclContext();20865}20866 20867void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,20868 IdentifierInfo* AliasName,20869 SourceLocation PragmaLoc,20870 SourceLocation NameLoc,20871 SourceLocation AliasNameLoc) {20872 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,20873 LookupOrdinaryName);20874 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),20875 AttributeCommonInfo::Form::Pragma());20876 AsmLabelAttr *Attr =20877 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);20878 20879 // If a declaration that:20880 // 1) declares a function or a variable20881 // 2) has external linkage20882 // already exists, add a label attribute to it.20883 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {20884 if (isDeclExternC(PrevDecl))20885 PrevDecl->addAttr(Attr);20886 else20887 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)20888 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;20889 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.20890 } else20891 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));20892}20893 20894void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,20895 SourceLocation PragmaLoc,20896 SourceLocation NameLoc) {20897 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);20898 20899 if (PrevDecl) {20900 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));20901 } else {20902 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));20903 }20904}20905 20906void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,20907 IdentifierInfo* AliasName,20908 SourceLocation PragmaLoc,20909 SourceLocation NameLoc,20910 SourceLocation AliasNameLoc) {20911 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,20912 LookupOrdinaryName);20913 WeakInfo W = WeakInfo(Name, NameLoc);20914 20915 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {20916 if (!PrevDecl->hasAttr<AliasAttr>())20917 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))20918 DeclApplyPragmaWeak(TUScope, ND, W);20919 } else {20920 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);20921 }20922}20923 20924Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,20925 bool Final) {20926 assert(FD && "Expected non-null FunctionDecl");20927 20928 // SYCL functions can be template, so we check if they have appropriate20929 // attribute prior to checking if it is a template.20930 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())20931 return FunctionEmissionStatus::Emitted;20932 20933 // Templates are emitted when they're instantiated.20934 if (FD->isDependentContext())20935 return FunctionEmissionStatus::TemplateDiscarded;20936 20937 // Check whether this function is an externally visible definition.20938 auto IsEmittedForExternalSymbol = [this, FD]() {20939 // We have to check the GVA linkage of the function's *definition* -- if we20940 // only have a declaration, we don't know whether or not the function will20941 // be emitted, because (say) the definition could include "inline".20942 const FunctionDecl *Def = FD->getDefinition();20943 20944 // We can't compute linkage when we skip function bodies.20945 return Def && !Def->hasSkippedBody() &&20946 !isDiscardableGVALinkage(20947 getASTContext().GetGVALinkageForFunction(Def));20948 };20949 20950 if (LangOpts.OpenMPIsTargetDevice) {20951 // In OpenMP device mode we will not emit host only functions, or functions20952 // we don't need due to their linkage.20953 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =20954 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());20955 // DevTy may be changed later by20956 // #pragma omp declare target to(*) device_type(*).20957 // Therefore DevTy having no value does not imply host. The emission status20958 // will be checked again at the end of compilation unit with Final = true.20959 if (DevTy)20960 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)20961 return FunctionEmissionStatus::OMPDiscarded;20962 // If we have an explicit value for the device type, or we are in a target20963 // declare context, we need to emit all extern and used symbols.20964 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)20965 if (IsEmittedForExternalSymbol())20966 return FunctionEmissionStatus::Emitted;20967 // Device mode only emits what it must, if it wasn't tagged yet and needed,20968 // we'll omit it.20969 if (Final)20970 return FunctionEmissionStatus::OMPDiscarded;20971 } else if (LangOpts.OpenMP > 45) {20972 // In OpenMP host compilation prior to 5.0 everything was an emitted host20973 // function. In 5.0, no_host was introduced which might cause a function to20974 // be omitted.20975 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =20976 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());20977 if (DevTy)20978 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)20979 return FunctionEmissionStatus::OMPDiscarded;20980 }20981 20982 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)20983 return FunctionEmissionStatus::Emitted;20984 20985 if (LangOpts.CUDA) {20986 // When compiling for device, host functions are never emitted. Similarly,20987 // when compiling for host, device and global functions are never emitted.20988 // (Technically, we do emit a host-side stub for global functions, but this20989 // doesn't count for our purposes here.)20990 CUDAFunctionTarget T = CUDA().IdentifyTarget(FD);20991 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)20992 return FunctionEmissionStatus::CUDADiscarded;20993 if (!LangOpts.CUDAIsDevice &&20994 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))20995 return FunctionEmissionStatus::CUDADiscarded;20996 20997 if (IsEmittedForExternalSymbol())20998 return FunctionEmissionStatus::Emitted;20999 21000 // If FD is a virtual destructor of an explicit instantiation21001 // of a template class, return Emitted.21002 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(FD)) {21003 if (Destructor->isVirtual()) {21004 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(21005 Destructor->getParent())) {21006 TemplateSpecializationKind TSK =21007 Spec->getTemplateSpecializationKind();21008 if (TSK == TSK_ExplicitInstantiationDeclaration ||21009 TSK == TSK_ExplicitInstantiationDefinition)21010 return FunctionEmissionStatus::Emitted;21011 }21012 }21013 }21014 }21015 21016 // Otherwise, the function is known-emitted if it's in our set of21017 // known-emitted functions.21018 return FunctionEmissionStatus::Unknown;21019}21020 21021bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {21022 // Host-side references to a __global__ function refer to the stub, so the21023 // function itself is never emitted and therefore should not be marked.21024 // If we have host fn calls kernel fn calls host+device, the HD function21025 // does not get instantiated on the host. We model this by omitting at the21026 // call to the kernel from the callgraph. This ensures that, when compiling21027 // for host, only HD functions actually called from the host get marked as21028 // known-emitted.21029 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&21030 CUDA().IdentifyTarget(Callee) == CUDAFunctionTarget::Global;21031}21032 21033bool Sema::isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,21034 bool &Visible) {21035 Visible = hasVisibleDefinition(D, Suggested);21036 // The redefinition of D in the **current** TU is allowed if D is invisible or21037 // D is defined in the global module of other module units. We didn't check if21038 // it is in global module as, we'll check the redefinition in named module21039 // later with better diagnostic message.21040 return D->isInAnotherModuleUnit() || !Visible;21041}21042