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-exception 6 // 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 Lex 37 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 38 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 39 #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/SemaOpenMP.h" 54 #include "clang/Sema/SemaPPC.h" 55 #include "clang/Sema/SemaRISCV.h" 56 #include "clang/Sema/SemaSYCL.h" 57 #include "clang/Sema/SemaSwift.h" 58 #include "clang/Sema/SemaWasm.h" 59 #include "clang/Sema/Template.h" 60 #include "llvm/ADT/STLForwardCompat.h" 61 #include "llvm/ADT/SmallString.h" 62 #include "llvm/ADT/StringExtras.h" 63 #include "llvm/TargetParser/Triple.h" 64 #include <algorithm> 65 #include <cstring> 66 #include <optional> 67 #include <unordered_map> 68 69 using namespace clang; 70 using namespace sema; 71 72 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 73 if (OwnedType) { 74 Decl *Group[2] = { OwnedType, Ptr }; 75 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 76 } 77 78 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 79 } 80 81 namespace { 82 83 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 84 public: 85 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 86 bool AllowTemplates = false, 87 bool AllowNonTemplates = true) 88 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 89 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 90 WantExpressionKeywords = false; 91 WantCXXNamedCasts = false; 92 WantRemainingKeywords = false; 93 } 94 95 bool ValidateCandidate(const TypoCorrection &candidate) override { 96 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 97 if (!AllowInvalidDecl && ND->isInvalidDecl()) 98 return false; 99 100 if (getAsTypeTemplateDecl(ND)) 101 return AllowTemplates; 102 103 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 104 if (!IsType) 105 return false; 106 107 if (AllowNonTemplates) 108 return true; 109 110 // An injected-class-name of a class template (specialization) is valid 111 // as a template or as a non-template. 112 if (AllowTemplates) { 113 auto *RD = dyn_cast<CXXRecordDecl>(ND); 114 if (!RD || !RD->isInjectedClassName()) 115 return false; 116 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 117 return RD->getDescribedClassTemplate() || 118 isa<ClassTemplateSpecializationDecl>(RD); 119 } 120 121 return false; 122 } 123 124 return !WantClassName && candidate.isKeyword(); 125 } 126 127 std::unique_ptr<CorrectionCandidateCallback> clone() override { 128 return std::make_unique<TypeNameValidatorCCC>(*this); 129 } 130 131 private: 132 bool AllowInvalidDecl; 133 bool WantClassName; 134 bool AllowTemplates; 135 bool AllowNonTemplates; 136 }; 137 138 } // end anonymous namespace 139 140 namespace { 141 enum class UnqualifiedTypeNameLookupResult { 142 NotFound, 143 FoundNonType, 144 FoundType 145 }; 146 } // end anonymous namespace 147 148 /// Tries to perform unqualified lookup of the type decls in bases for 149 /// dependent class. 150 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 151 /// type decl, \a FoundType if only type decls are found. 152 static UnqualifiedTypeNameLookupResult 153 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 154 SourceLocation NameLoc, 155 const CXXRecordDecl *RD) { 156 if (!RD->hasDefinition()) 157 return UnqualifiedTypeNameLookupResult::NotFound; 158 // Look for type decls in base classes. 159 UnqualifiedTypeNameLookupResult FoundTypeDecl = 160 UnqualifiedTypeNameLookupResult::NotFound; 161 for (const auto &Base : RD->bases()) { 162 const CXXRecordDecl *BaseRD = nullptr; 163 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 164 BaseRD = BaseTT->getAsCXXRecordDecl(); 165 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 166 // Look for type decls in dependent base classes that have known primary 167 // templates. 168 if (!TST || !TST->isDependentType()) 169 continue; 170 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 171 if (!TD) 172 continue; 173 if (auto *BasePrimaryTemplate = 174 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 175 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 176 BaseRD = BasePrimaryTemplate; 177 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 178 if (const ClassTemplatePartialSpecializationDecl *PS = 179 CTD->findPartialSpecialization(Base.getType())) 180 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 181 BaseRD = PS; 182 } 183 } 184 } 185 if (BaseRD) { 186 for (NamedDecl *ND : BaseRD->lookup(&II)) { 187 if (!isa<TypeDecl>(ND)) 188 return UnqualifiedTypeNameLookupResult::FoundNonType; 189 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 190 } 191 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 192 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 193 case UnqualifiedTypeNameLookupResult::FoundNonType: 194 return UnqualifiedTypeNameLookupResult::FoundNonType; 195 case UnqualifiedTypeNameLookupResult::FoundType: 196 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 197 break; 198 case UnqualifiedTypeNameLookupResult::NotFound: 199 break; 200 } 201 } 202 } 203 } 204 205 return FoundTypeDecl; 206 } 207 208 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 209 const IdentifierInfo &II, 210 SourceLocation NameLoc) { 211 // Lookup in the parent class template context, if any. 212 const CXXRecordDecl *RD = nullptr; 213 UnqualifiedTypeNameLookupResult FoundTypeDecl = 214 UnqualifiedTypeNameLookupResult::NotFound; 215 for (DeclContext *DC = S.CurContext; 216 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 217 DC = DC->getParent()) { 218 // Look for type decls in dependent base classes that have known primary 219 // templates. 220 RD = dyn_cast<CXXRecordDecl>(DC); 221 if (RD && RD->getDescribedClassTemplate()) 222 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 223 } 224 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 225 return nullptr; 226 227 // We found some types in dependent base classes. Recover as if the user 228 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 229 // lookup during template instantiation. 230 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 231 232 ASTContext &Context = S.Context; 233 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 234 cast<Type>(Context.getRecordType(RD))); 235 QualType T = 236 Context.getDependentNameType(ElaboratedTypeKeyword::Typename, NNS, &II); 237 238 CXXScopeSpec SS; 239 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 240 241 TypeLocBuilder Builder; 242 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 243 DepTL.setNameLoc(NameLoc); 244 DepTL.setElaboratedKeywordLoc(SourceLocation()); 245 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 246 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 247 } 248 249 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 250 static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T, 251 SourceLocation NameLoc, 252 bool WantNontrivialTypeSourceInfo = true) { 253 switch (T->getTypeClass()) { 254 case Type::DeducedTemplateSpecialization: 255 case Type::Enum: 256 case Type::InjectedClassName: 257 case Type::Record: 258 case Type::Typedef: 259 case Type::UnresolvedUsing: 260 case Type::Using: 261 break; 262 // These can never be qualified so an ElaboratedType node 263 // would carry no additional meaning. 264 case Type::ObjCInterface: 265 case Type::ObjCTypeParam: 266 case Type::TemplateTypeParm: 267 return ParsedType::make(T); 268 default: 269 llvm_unreachable("Unexpected Type Class"); 270 } 271 272 if (!SS || SS->isEmpty()) 273 return ParsedType::make(S.Context.getElaboratedType( 274 ElaboratedTypeKeyword::None, nullptr, T, nullptr)); 275 276 QualType ElTy = S.getElaboratedType(ElaboratedTypeKeyword::None, *SS, T); 277 if (!WantNontrivialTypeSourceInfo) 278 return ParsedType::make(ElTy); 279 280 TypeLocBuilder Builder; 281 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 282 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy); 283 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 284 ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context)); 285 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy)); 286 } 287 288 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 289 Scope *S, CXXScopeSpec *SS, bool isClassName, 290 bool HasTrailingDot, ParsedType ObjectTypePtr, 291 bool IsCtorOrDtorName, 292 bool WantNontrivialTypeSourceInfo, 293 bool IsClassTemplateDeductionContext, 294 ImplicitTypenameContext AllowImplicitTypename, 295 IdentifierInfo **CorrectedII) { 296 // FIXME: Consider allowing this outside C++1z mode as an extension. 297 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 298 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 299 !isClassName && !HasTrailingDot; 300 301 // Determine where we will perform name lookup. 302 DeclContext *LookupCtx = nullptr; 303 if (ObjectTypePtr) { 304 QualType ObjectType = ObjectTypePtr.get(); 305 if (ObjectType->isRecordType()) 306 LookupCtx = computeDeclContext(ObjectType); 307 } else if (SS && SS->isNotEmpty()) { 308 LookupCtx = computeDeclContext(*SS, false); 309 310 if (!LookupCtx) { 311 if (isDependentScopeSpecifier(*SS)) { 312 // C++ [temp.res]p3: 313 // A qualified-id that refers to a type and in which the 314 // nested-name-specifier depends on a template-parameter (14.6.2) 315 // shall be prefixed by the keyword typename to indicate that the 316 // qualified-id denotes a type, forming an 317 // elaborated-type-specifier (7.1.5.3). 318 // 319 // We therefore do not perform any name lookup if the result would 320 // refer to a member of an unknown specialization. 321 // In C++2a, in several contexts a 'typename' is not required. Also 322 // allow this as an extension. 323 if (AllowImplicitTypename == ImplicitTypenameContext::No && 324 !isClassName && !IsCtorOrDtorName) 325 return nullptr; 326 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName; 327 if (IsImplicitTypename) { 328 SourceLocation QualifiedLoc = SS->getRange().getBegin(); 329 if (getLangOpts().CPlusPlus20) 330 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename); 331 else 332 Diag(QualifiedLoc, diag::ext_implicit_typename) 333 << SS->getScopeRep() << II.getName() 334 << FixItHint::CreateInsertion(QualifiedLoc, "typename "); 335 } 336 337 // We know from the grammar that this name refers to a type, 338 // so build a dependent node to describe the type. 339 if (WantNontrivialTypeSourceInfo) 340 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc, 341 (ImplicitTypenameContext)IsImplicitTypename) 342 .get(); 343 344 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 345 QualType T = CheckTypenameType( 346 IsImplicitTypename ? ElaboratedTypeKeyword::Typename 347 : ElaboratedTypeKeyword::None, 348 SourceLocation(), QualifierLoc, II, NameLoc); 349 return ParsedType::make(T); 350 } 351 352 return nullptr; 353 } 354 355 if (!LookupCtx->isDependentContext() && 356 RequireCompleteDeclContext(*SS, LookupCtx)) 357 return nullptr; 358 } 359 360 // In the case where we know that the identifier is a class name, we know that 361 // it is a type declaration (struct, class, union or enum) so we can use tag 362 // name lookup. 363 // 364 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for 365 // the component name of the type-name or simple-template-id is type-only. 366 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName; 367 LookupResult Result(*this, &II, NameLoc, Kind); 368 if (LookupCtx) { 369 // Perform "qualified" name lookup into the declaration context we 370 // computed, which is either the type of the base of a member access 371 // expression or the declaration context associated with a prior 372 // nested-name-specifier. 373 LookupQualifiedName(Result, LookupCtx); 374 375 if (ObjectTypePtr && Result.empty()) { 376 // C++ [basic.lookup.classref]p3: 377 // If the unqualified-id is ~type-name, the type-name is looked up 378 // in the context of the entire postfix-expression. If the type T of 379 // the object expression is of a class type C, the type-name is also 380 // looked up in the scope of class C. At least one of the lookups shall 381 // find a name that refers to (possibly cv-qualified) T. 382 LookupName(Result, S); 383 } 384 } else { 385 // Perform unqualified name lookup. 386 LookupName(Result, S); 387 388 // For unqualified lookup in a class template in MSVC mode, look into 389 // dependent base classes where the primary class template is known. 390 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 391 if (ParsedType TypeInBase = 392 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 393 return TypeInBase; 394 } 395 } 396 397 NamedDecl *IIDecl = nullptr; 398 UsingShadowDecl *FoundUsingShadow = nullptr; 399 switch (Result.getResultKind()) { 400 case LookupResult::NotFound: 401 if (CorrectedII) { 402 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 403 AllowDeducedTemplate); 404 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 405 S, SS, CCC, CTK_ErrorRecovery); 406 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 407 TemplateTy Template; 408 bool MemberOfUnknownSpecialization; 409 UnqualifiedId TemplateName; 410 TemplateName.setIdentifier(NewII, NameLoc); 411 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 412 CXXScopeSpec NewSS, *NewSSPtr = SS; 413 if (SS && NNS) { 414 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 415 NewSSPtr = &NewSS; 416 } 417 if (Correction && (NNS || NewII != &II) && 418 // Ignore a correction to a template type as the to-be-corrected 419 // identifier is not a template (typo correction for template names 420 // is handled elsewhere). 421 !(getLangOpts().CPlusPlus && NewSSPtr && 422 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 423 Template, MemberOfUnknownSpecialization))) { 424 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 425 isClassName, HasTrailingDot, ObjectTypePtr, 426 IsCtorOrDtorName, 427 WantNontrivialTypeSourceInfo, 428 IsClassTemplateDeductionContext); 429 if (Ty) { 430 diagnoseTypo(Correction, 431 PDiag(diag::err_unknown_type_or_class_name_suggest) 432 << Result.getLookupName() << isClassName); 433 if (SS && NNS) 434 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 435 *CorrectedII = NewII; 436 return Ty; 437 } 438 } 439 } 440 Result.suppressDiagnostics(); 441 return nullptr; 442 case LookupResult::NotFoundInCurrentInstantiation: 443 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) { 444 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None, 445 SS->getScopeRep(), &II); 446 TypeLocBuilder TLB; 447 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T); 448 TL.setElaboratedKeywordLoc(SourceLocation()); 449 TL.setQualifierLoc(SS->getWithLocInContext(Context)); 450 TL.setNameLoc(NameLoc); 451 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 452 } 453 [[fallthrough]]; 454 case LookupResult::FoundOverloaded: 455 case LookupResult::FoundUnresolvedValue: 456 Result.suppressDiagnostics(); 457 return nullptr; 458 459 case LookupResult::Ambiguous: 460 // Recover from type-hiding ambiguities by hiding the type. We'll 461 // do the lookup again when looking for an object, and we can 462 // diagnose the error then. If we don't do this, then the error 463 // about hiding the type will be immediately followed by an error 464 // that only makes sense if the identifier was treated like a type. 465 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 466 Result.suppressDiagnostics(); 467 return nullptr; 468 } 469 470 // Look to see if we have a type anywhere in the list of results. 471 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 472 Res != ResEnd; ++Res) { 473 NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); 474 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( 475 RealRes) || 476 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { 477 if (!IIDecl || 478 // Make the selection of the recovery decl deterministic. 479 RealRes->getLocation() < IIDecl->getLocation()) { 480 IIDecl = RealRes; 481 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res); 482 } 483 } 484 } 485 486 if (!IIDecl) { 487 // None of the entities we found is a type, so there is no way 488 // to even assume that the result is a type. In this case, don't 489 // complain about the ambiguity. The parser will either try to 490 // perform this lookup again (e.g., as an object name), which 491 // will produce the ambiguity, or will complain that it expected 492 // a type name. 493 Result.suppressDiagnostics(); 494 return nullptr; 495 } 496 497 // We found a type within the ambiguous lookup; diagnose the 498 // ambiguity and then return that type. This might be the right 499 // answer, or it might not be, but it suppresses any attempt to 500 // perform the name lookup again. 501 break; 502 503 case LookupResult::Found: 504 IIDecl = Result.getFoundDecl(); 505 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin()); 506 break; 507 } 508 509 assert(IIDecl && "Didn't find decl"); 510 511 QualType T; 512 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 513 // C++ [class.qual]p2: A lookup that would find the injected-class-name 514 // instead names the constructors of the class, except when naming a class. 515 // This is ill-formed when we're not actually forming a ctor or dtor name. 516 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 517 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 518 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 519 FoundRD->isInjectedClassName() && 520 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 521 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 522 << &II << /*Type*/1; 523 524 DiagnoseUseOfDecl(IIDecl, NameLoc); 525 526 T = Context.getTypeDeclType(TD); 527 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 528 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 529 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 530 if (!HasTrailingDot) 531 T = Context.getObjCInterfaceType(IDecl); 532 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl. 533 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { 534 (void)DiagnoseUseOfDecl(UD, NameLoc); 535 // Recover with 'int' 536 return ParsedType::make(Context.IntTy); 537 } else if (AllowDeducedTemplate) { 538 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) { 539 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD); 540 TemplateName Template = Context.getQualifiedTemplateName( 541 SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false, 542 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD)); 543 T = Context.getDeducedTemplateSpecializationType(Template, QualType(), 544 false); 545 // Don't wrap in a further UsingType. 546 FoundUsingShadow = nullptr; 547 } 548 } 549 550 if (T.isNull()) { 551 // If it's not plausibly a type, suppress diagnostics. 552 Result.suppressDiagnostics(); 553 return nullptr; 554 } 555 556 if (FoundUsingShadow) 557 T = Context.getUsingType(FoundUsingShadow, T); 558 559 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo); 560 } 561 562 // Builds a fake NNS for the given decl context. 563 static NestedNameSpecifier * 564 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 565 for (;; DC = DC->getLookupParent()) { 566 DC = DC->getPrimaryContext(); 567 auto *ND = dyn_cast<NamespaceDecl>(DC); 568 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 569 return NestedNameSpecifier::Create(Context, nullptr, ND); 570 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 571 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 572 RD->getTypeForDecl()); 573 else if (isa<TranslationUnitDecl>(DC)) 574 return NestedNameSpecifier::GlobalSpecifier(Context); 575 } 576 llvm_unreachable("something isn't in TU scope?"); 577 } 578 579 /// Find the parent class with dependent bases of the innermost enclosing method 580 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 581 /// up allowing unqualified dependent type names at class-level, which MSVC 582 /// correctly rejects. 583 static const CXXRecordDecl * 584 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 585 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 586 DC = DC->getPrimaryContext(); 587 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 588 if (MD->getParent()->hasAnyDependentBases()) 589 return MD->getParent(); 590 } 591 return nullptr; 592 } 593 594 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 595 SourceLocation NameLoc, 596 bool IsTemplateTypeArg) { 597 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 598 599 NestedNameSpecifier *NNS = nullptr; 600 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 601 // If we weren't able to parse a default template argument, delay lookup 602 // until instantiation time by making a non-dependent DependentTypeName. We 603 // pretend we saw a NestedNameSpecifier referring to the current scope, and 604 // lookup is retried. 605 // FIXME: This hurts our diagnostic quality, since we get errors like "no 606 // type named 'Foo' in 'current_namespace'" when the user didn't write any 607 // name specifiers. 608 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 609 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 610 } else if (const CXXRecordDecl *RD = 611 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 612 // Build a DependentNameType that will perform lookup into RD at 613 // instantiation time. 614 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 615 RD->getTypeForDecl()); 616 617 // Diagnose that this identifier was undeclared, and retry the lookup during 618 // template instantiation. 619 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 620 << RD; 621 } else { 622 // This is not a situation that we should recover from. 623 return ParsedType(); 624 } 625 626 QualType T = 627 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II); 628 629 // Build type location information. We synthesized the qualifier, so we have 630 // to build a fake NestedNameSpecifierLoc. 631 NestedNameSpecifierLocBuilder NNSLocBuilder; 632 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 633 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 634 635 TypeLocBuilder Builder; 636 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 637 DepTL.setNameLoc(NameLoc); 638 DepTL.setElaboratedKeywordLoc(SourceLocation()); 639 DepTL.setQualifierLoc(QualifierLoc); 640 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 641 } 642 643 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 644 // Do a tag name lookup in this scope. 645 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 646 LookupName(R, S, false); 647 R.suppressDiagnostics(); 648 if (R.getResultKind() == LookupResult::Found) 649 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 650 switch (TD->getTagKind()) { 651 case TagTypeKind::Struct: 652 return DeclSpec::TST_struct; 653 case TagTypeKind::Interface: 654 return DeclSpec::TST_interface; 655 case TagTypeKind::Union: 656 return DeclSpec::TST_union; 657 case TagTypeKind::Class: 658 return DeclSpec::TST_class; 659 case TagTypeKind::Enum: 660 return DeclSpec::TST_enum; 661 } 662 } 663 664 return DeclSpec::TST_unspecified; 665 } 666 667 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 668 if (CurContext->isRecord()) { 669 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 670 return true; 671 672 const Type *Ty = SS->getScopeRep()->getAsType(); 673 674 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 675 for (const auto &Base : RD->bases()) 676 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 677 return true; 678 return S->isFunctionPrototypeScope(); 679 } 680 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 681 } 682 683 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 684 SourceLocation IILoc, 685 Scope *S, 686 CXXScopeSpec *SS, 687 ParsedType &SuggestedType, 688 bool IsTemplateName) { 689 // Don't report typename errors for editor placeholders. 690 if (II->isEditorPlaceholder()) 691 return; 692 // We don't have anything to suggest (yet). 693 SuggestedType = nullptr; 694 695 // There may have been a typo in the name of the type. Look up typo 696 // results, in case we have something that we can suggest. 697 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 698 /*AllowTemplates=*/IsTemplateName, 699 /*AllowNonTemplates=*/!IsTemplateName); 700 if (TypoCorrection Corrected = 701 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 702 CCC, CTK_ErrorRecovery)) { 703 // FIXME: Support error recovery for the template-name case. 704 bool CanRecover = !IsTemplateName; 705 if (Corrected.isKeyword()) { 706 // We corrected to a keyword. 707 diagnoseTypo(Corrected, 708 PDiag(IsTemplateName ? diag::err_no_template_suggest 709 : diag::err_unknown_typename_suggest) 710 << II); 711 II = Corrected.getCorrectionAsIdentifierInfo(); 712 } else { 713 // We found a similarly-named type or interface; suggest that. 714 if (!SS || !SS->isSet()) { 715 diagnoseTypo(Corrected, 716 PDiag(IsTemplateName ? diag::err_no_template_suggest 717 : diag::err_unknown_typename_suggest) 718 << II, CanRecover); 719 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 720 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 721 bool DroppedSpecifier = 722 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr; 723 diagnoseTypo(Corrected, 724 PDiag(IsTemplateName 725 ? diag::err_no_member_template_suggest 726 : diag::err_unknown_nested_typename_suggest) 727 << II << DC << DroppedSpecifier << SS->getRange(), 728 CanRecover); 729 } else { 730 llvm_unreachable("could not have corrected a typo here"); 731 } 732 733 if (!CanRecover) 734 return; 735 736 CXXScopeSpec tmpSS; 737 if (Corrected.getCorrectionSpecifier()) 738 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 739 SourceRange(IILoc)); 740 // FIXME: Support class template argument deduction here. 741 SuggestedType = 742 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 743 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 744 /*IsCtorOrDtorName=*/false, 745 /*WantNontrivialTypeSourceInfo=*/true); 746 } 747 return; 748 } 749 750 if (getLangOpts().CPlusPlus && !IsTemplateName) { 751 // See if II is a class template that the user forgot to pass arguments to. 752 UnqualifiedId Name; 753 Name.setIdentifier(II, IILoc); 754 CXXScopeSpec EmptySS; 755 TemplateTy TemplateResult; 756 bool MemberOfUnknownSpecialization; 757 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 758 Name, nullptr, true, TemplateResult, 759 MemberOfUnknownSpecialization) == TNK_Type_template) { 760 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 761 return; 762 } 763 } 764 765 // FIXME: Should we move the logic that tries to recover from a missing tag 766 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 767 768 if (!SS || (!SS->isSet() && !SS->isInvalid())) 769 Diag(IILoc, IsTemplateName ? diag::err_no_template 770 : diag::err_unknown_typename) 771 << II; 772 else if (DeclContext *DC = computeDeclContext(*SS, false)) 773 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 774 : diag::err_typename_nested_not_found) 775 << II << DC << SS->getRange(); 776 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 777 SuggestedType = 778 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 779 } else if (isDependentScopeSpecifier(*SS)) { 780 unsigned DiagID = diag::err_typename_missing; 781 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 782 DiagID = diag::ext_typename_missing; 783 784 Diag(SS->getRange().getBegin(), DiagID) 785 << SS->getScopeRep() << II->getName() 786 << SourceRange(SS->getRange().getBegin(), IILoc) 787 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 788 SuggestedType = ActOnTypenameType(S, SourceLocation(), 789 *SS, *II, IILoc).get(); 790 } else { 791 assert(SS && SS->isInvalid() && 792 "Invalid scope specifier has already been diagnosed"); 793 } 794 } 795 796 /// Determine whether the given result set contains either a type name 797 /// or 798 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 799 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 800 NextToken.is(tok::less); 801 802 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 803 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 804 return true; 805 806 if (CheckTemplate && isa<TemplateDecl>(*I)) 807 return true; 808 } 809 810 return false; 811 } 812 813 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 814 Scope *S, CXXScopeSpec &SS, 815 IdentifierInfo *&Name, 816 SourceLocation NameLoc) { 817 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 818 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType()); 819 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 820 StringRef FixItTagName; 821 switch (Tag->getTagKind()) { 822 case TagTypeKind::Class: 823 FixItTagName = "class "; 824 break; 825 826 case TagTypeKind::Enum: 827 FixItTagName = "enum "; 828 break; 829 830 case TagTypeKind::Struct: 831 FixItTagName = "struct "; 832 break; 833 834 case TagTypeKind::Interface: 835 FixItTagName = "__interface "; 836 break; 837 838 case TagTypeKind::Union: 839 FixItTagName = "union "; 840 break; 841 } 842 843 StringRef TagName = FixItTagName.drop_back(); 844 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 845 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 846 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 847 848 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 849 I != IEnd; ++I) 850 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 851 << Name << TagName; 852 853 // Replace lookup results with just the tag decl. 854 Result.clear(Sema::LookupTagName); 855 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType()); 856 return true; 857 } 858 859 return false; 860 } 861 862 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 863 IdentifierInfo *&Name, 864 SourceLocation NameLoc, 865 const Token &NextToken, 866 CorrectionCandidateCallback *CCC) { 867 DeclarationNameInfo NameInfo(Name, NameLoc); 868 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 869 870 assert(NextToken.isNot(tok::coloncolon) && 871 "parse nested name specifiers before calling ClassifyName"); 872 if (getLangOpts().CPlusPlus && SS.isSet() && 873 isCurrentClassName(*Name, S, &SS)) { 874 // Per [class.qual]p2, this names the constructors of SS, not the 875 // injected-class-name. We don't have a classification for that. 876 // There's not much point caching this result, since the parser 877 // will reject it later. 878 return NameClassification::Unknown(); 879 } 880 881 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 882 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(), 883 /*AllowBuiltinCreation=*/!CurMethod); 884 885 if (SS.isInvalid()) 886 return NameClassification::Error(); 887 888 // For unqualified lookup in a class template in MSVC mode, look into 889 // dependent base classes where the primary class template is known. 890 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 891 if (ParsedType TypeInBase = 892 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 893 return TypeInBase; 894 } 895 896 // Perform lookup for Objective-C instance variables (including automatically 897 // synthesized instance variables), if we're in an Objective-C method. 898 // FIXME: This lookup really, really needs to be folded in to the normal 899 // unqualified lookup mechanism. 900 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 901 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name); 902 if (Ivar.isInvalid()) 903 return NameClassification::Error(); 904 if (Ivar.isUsable()) 905 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 906 907 // We defer builtin creation until after ivar lookup inside ObjC methods. 908 if (Result.empty()) 909 LookupBuiltin(Result); 910 } 911 912 bool SecondTry = false; 913 bool IsFilteredTemplateName = false; 914 915 Corrected: 916 switch (Result.getResultKind()) { 917 case LookupResult::NotFound: 918 // If an unqualified-id is followed by a '(', then we have a function 919 // call. 920 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 921 // In C++, this is an ADL-only call. 922 // FIXME: Reference? 923 if (getLangOpts().CPlusPlus) 924 return NameClassification::UndeclaredNonType(); 925 926 // C90 6.3.2.2: 927 // If the expression that precedes the parenthesized argument list in a 928 // function call consists solely of an identifier, and if no 929 // declaration is visible for this identifier, the identifier is 930 // implicitly declared exactly as if, in the innermost block containing 931 // the function call, the declaration 932 // 933 // extern int identifier (); 934 // 935 // appeared. 936 // 937 // We also allow this in C99 as an extension. However, this is not 938 // allowed in all language modes as functions without prototypes may not 939 // be supported. 940 if (getLangOpts().implicitFunctionsAllowed()) { 941 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 942 return NameClassification::NonType(D); 943 } 944 } 945 946 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 947 // In C++20 onwards, this could be an ADL-only call to a function 948 // template, and we're required to assume that this is a template name. 949 // 950 // FIXME: Find a way to still do typo correction in this case. 951 TemplateName Template = 952 Context.getAssumedTemplateName(NameInfo.getName()); 953 return NameClassification::UndeclaredTemplate(Template); 954 } 955 956 // In C, we first see whether there is a tag type by the same name, in 957 // which case it's likely that the user just forgot to write "enum", 958 // "struct", or "union". 959 if (!getLangOpts().CPlusPlus && !SecondTry && 960 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 961 break; 962 } 963 964 // Perform typo correction to determine if there is another name that is 965 // close to this name. 966 if (!SecondTry && CCC) { 967 SecondTry = true; 968 if (TypoCorrection Corrected = 969 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 970 &SS, *CCC, CTK_ErrorRecovery)) { 971 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 972 unsigned QualifiedDiag = diag::err_no_member_suggest; 973 974 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 975 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 976 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 977 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 978 UnqualifiedDiag = diag::err_no_template_suggest; 979 QualifiedDiag = diag::err_no_member_template_suggest; 980 } else if (UnderlyingFirstDecl && 981 (isa<TypeDecl>(UnderlyingFirstDecl) || 982 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 983 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 984 UnqualifiedDiag = diag::err_unknown_typename_suggest; 985 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 986 } 987 988 if (SS.isEmpty()) { 989 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 990 } else {// FIXME: is this even reachable? Test it. 991 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 992 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 993 Name->getName() == CorrectedStr; 994 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 995 << Name << computeDeclContext(SS, false) 996 << DroppedSpecifier << SS.getRange()); 997 } 998 999 // Update the name, so that the caller has the new name. 1000 Name = Corrected.getCorrectionAsIdentifierInfo(); 1001 1002 // Typo correction corrected to a keyword. 1003 if (Corrected.isKeyword()) 1004 return Name; 1005 1006 // Also update the LookupResult... 1007 // FIXME: This should probably go away at some point 1008 Result.clear(); 1009 Result.setLookupName(Corrected.getCorrection()); 1010 if (FirstDecl) 1011 Result.addDecl(FirstDecl); 1012 1013 // If we found an Objective-C instance variable, let 1014 // LookupInObjCMethod build the appropriate expression to 1015 // reference the ivar. 1016 // FIXME: This is a gross hack. 1017 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1018 DeclResult R = 1019 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1020 if (R.isInvalid()) 1021 return NameClassification::Error(); 1022 if (R.isUsable()) 1023 return NameClassification::NonType(Ivar); 1024 } 1025 1026 goto Corrected; 1027 } 1028 } 1029 1030 // We failed to correct; just fall through and let the parser deal with it. 1031 Result.suppressDiagnostics(); 1032 return NameClassification::Unknown(); 1033 1034 case LookupResult::NotFoundInCurrentInstantiation: { 1035 // We performed name lookup into the current instantiation, and there were 1036 // dependent bases, so we treat this result the same way as any other 1037 // dependent nested-name-specifier. 1038 1039 // C++ [temp.res]p2: 1040 // A name used in a template declaration or definition and that is 1041 // dependent on a template-parameter is assumed not to name a type 1042 // unless the applicable name lookup finds a type name or the name is 1043 // qualified by the keyword typename. 1044 // 1045 // FIXME: If the next token is '<', we might want to ask the parser to 1046 // perform some heroics to see if we actually have a 1047 // template-argument-list, which would indicate a missing 'template' 1048 // keyword here. 1049 return NameClassification::DependentNonType(); 1050 } 1051 1052 case LookupResult::Found: 1053 case LookupResult::FoundOverloaded: 1054 case LookupResult::FoundUnresolvedValue: 1055 break; 1056 1057 case LookupResult::Ambiguous: 1058 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1059 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1060 /*AllowDependent=*/false)) { 1061 // C++ [temp.local]p3: 1062 // A lookup that finds an injected-class-name (10.2) can result in an 1063 // ambiguity in certain cases (for example, if it is found in more than 1064 // one base class). If all of the injected-class-names that are found 1065 // refer to specializations of the same class template, and if the name 1066 // is followed by a template-argument-list, the reference refers to the 1067 // class template itself and not a specialization thereof, and is not 1068 // ambiguous. 1069 // 1070 // This filtering can make an ambiguous result into an unambiguous one, 1071 // so try again after filtering out template names. 1072 FilterAcceptableTemplateNames(Result); 1073 if (!Result.isAmbiguous()) { 1074 IsFilteredTemplateName = true; 1075 break; 1076 } 1077 } 1078 1079 // Diagnose the ambiguity and return an error. 1080 return NameClassification::Error(); 1081 } 1082 1083 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1084 (IsFilteredTemplateName || 1085 hasAnyAcceptableTemplateNames( 1086 Result, /*AllowFunctionTemplates=*/true, 1087 /*AllowDependent=*/false, 1088 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1089 getLangOpts().CPlusPlus20))) { 1090 // C++ [temp.names]p3: 1091 // After name lookup (3.4) finds that a name is a template-name or that 1092 // an operator-function-id or a literal- operator-id refers to a set of 1093 // overloaded functions any member of which is a function template if 1094 // this is followed by a <, the < is always taken as the delimiter of a 1095 // template-argument-list and never as the less-than operator. 1096 // C++2a [temp.names]p2: 1097 // A name is also considered to refer to a template if it is an 1098 // unqualified-id followed by a < and name lookup finds either one 1099 // or more functions or finds nothing. 1100 if (!IsFilteredTemplateName) 1101 FilterAcceptableTemplateNames(Result); 1102 1103 bool IsFunctionTemplate; 1104 bool IsVarTemplate; 1105 TemplateName Template; 1106 if (Result.end() - Result.begin() > 1) { 1107 IsFunctionTemplate = true; 1108 Template = Context.getOverloadedTemplateName(Result.begin(), 1109 Result.end()); 1110 } else if (!Result.empty()) { 1111 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1112 *Result.begin(), /*AllowFunctionTemplates=*/true, 1113 /*AllowDependent=*/false)); 1114 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1115 IsVarTemplate = isa<VarTemplateDecl>(TD); 1116 1117 UsingShadowDecl *FoundUsingShadow = 1118 dyn_cast<UsingShadowDecl>(*Result.begin()); 1119 assert(!FoundUsingShadow || 1120 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl())); 1121 Template = Context.getQualifiedTemplateName( 1122 SS.getScopeRep(), 1123 /*TemplateKeyword=*/false, 1124 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD)); 1125 } else { 1126 // All results were non-template functions. This is a function template 1127 // name. 1128 IsFunctionTemplate = true; 1129 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1130 } 1131 1132 if (IsFunctionTemplate) { 1133 // Function templates always go through overload resolution, at which 1134 // point we'll perform the various checks (e.g., accessibility) we need 1135 // to based on which function we selected. 1136 Result.suppressDiagnostics(); 1137 1138 return NameClassification::FunctionTemplate(Template); 1139 } 1140 1141 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1142 : NameClassification::TypeTemplate(Template); 1143 } 1144 1145 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) { 1146 QualType T = Context.getTypeDeclType(Type); 1147 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) 1148 T = Context.getUsingType(USD, T); 1149 return buildNamedType(*this, &SS, T, NameLoc); 1150 }; 1151 1152 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1153 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1154 DiagnoseUseOfDecl(Type, NameLoc); 1155 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1156 return BuildTypeFor(Type, *Result.begin()); 1157 } 1158 1159 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1160 if (!Class) { 1161 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1162 if (ObjCCompatibleAliasDecl *Alias = 1163 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1164 Class = Alias->getClassInterface(); 1165 } 1166 1167 if (Class) { 1168 DiagnoseUseOfDecl(Class, NameLoc); 1169 1170 if (NextToken.is(tok::period)) { 1171 // Interface. <something> is parsed as a property reference expression. 1172 // Just return "unknown" as a fall-through for now. 1173 Result.suppressDiagnostics(); 1174 return NameClassification::Unknown(); 1175 } 1176 1177 QualType T = Context.getObjCInterfaceType(Class); 1178 return ParsedType::make(T); 1179 } 1180 1181 if (isa<ConceptDecl>(FirstDecl)) { 1182 // We want to preserve the UsingShadowDecl for concepts. 1183 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl())) 1184 return NameClassification::Concept(TemplateName(USD)); 1185 return NameClassification::Concept( 1186 TemplateName(cast<TemplateDecl>(FirstDecl))); 1187 } 1188 1189 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { 1190 (void)DiagnoseUseOfDecl(EmptyD, NameLoc); 1191 return NameClassification::Error(); 1192 } 1193 1194 // We can have a type template here if we're classifying a template argument. 1195 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1196 !isa<VarTemplateDecl>(FirstDecl)) 1197 return NameClassification::TypeTemplate( 1198 TemplateName(cast<TemplateDecl>(FirstDecl))); 1199 1200 // Check for a tag type hidden by a non-type decl in a few cases where it 1201 // seems likely a type is wanted instead of the non-type that was found. 1202 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1203 if ((NextToken.is(tok::identifier) || 1204 (NextIsOp && 1205 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1206 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1207 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1208 DiagnoseUseOfDecl(Type, NameLoc); 1209 return BuildTypeFor(Type, *Result.begin()); 1210 } 1211 1212 // If we already know which single declaration is referenced, just annotate 1213 // that declaration directly. Defer resolving even non-overloaded class 1214 // member accesses, as we need to defer certain access checks until we know 1215 // the context. 1216 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1217 if (Result.isSingleResult() && !ADL && 1218 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl))) 1219 return NameClassification::NonType(Result.getRepresentativeDecl()); 1220 1221 // Otherwise, this is an overload set that we will need to resolve later. 1222 Result.suppressDiagnostics(); 1223 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1224 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1225 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(), 1226 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false)); 1227 } 1228 1229 ExprResult 1230 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1231 SourceLocation NameLoc) { 1232 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1233 CXXScopeSpec SS; 1234 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1235 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1236 } 1237 1238 ExprResult 1239 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1240 IdentifierInfo *Name, 1241 SourceLocation NameLoc, 1242 bool IsAddressOfOperand) { 1243 DeclarationNameInfo NameInfo(Name, NameLoc); 1244 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1245 NameInfo, IsAddressOfOperand, 1246 /*TemplateArgs=*/nullptr); 1247 } 1248 1249 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1250 NamedDecl *Found, 1251 SourceLocation NameLoc, 1252 const Token &NextToken) { 1253 if (getCurMethodDecl() && SS.isEmpty()) 1254 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1255 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar); 1256 1257 // Reconstruct the lookup result. 1258 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1259 Result.addDecl(Found); 1260 Result.resolveKind(); 1261 1262 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1263 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true); 1264 } 1265 1266 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1267 // For an implicit class member access, transform the result into a member 1268 // access expression if necessary. 1269 auto *ULE = cast<UnresolvedLookupExpr>(E); 1270 if ((*ULE->decls_begin())->isCXXClassMember()) { 1271 CXXScopeSpec SS; 1272 SS.Adopt(ULE->getQualifierLoc()); 1273 1274 // Reconstruct the lookup result. 1275 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1276 LookupOrdinaryName); 1277 Result.setNamingClass(ULE->getNamingClass()); 1278 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1279 Result.addDecl(*I, I.getAccess()); 1280 Result.resolveKind(); 1281 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1282 nullptr, S); 1283 } 1284 1285 // Otherwise, this is already in the form we needed, and no further checks 1286 // are necessary. 1287 return ULE; 1288 } 1289 1290 Sema::TemplateNameKindForDiagnostics 1291 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1292 auto *TD = Name.getAsTemplateDecl(); 1293 if (!TD) 1294 return TemplateNameKindForDiagnostics::DependentTemplate; 1295 if (isa<ClassTemplateDecl>(TD)) 1296 return TemplateNameKindForDiagnostics::ClassTemplate; 1297 if (isa<FunctionTemplateDecl>(TD)) 1298 return TemplateNameKindForDiagnostics::FunctionTemplate; 1299 if (isa<VarTemplateDecl>(TD)) 1300 return TemplateNameKindForDiagnostics::VarTemplate; 1301 if (isa<TypeAliasTemplateDecl>(TD)) 1302 return TemplateNameKindForDiagnostics::AliasTemplate; 1303 if (isa<TemplateTemplateParmDecl>(TD)) 1304 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1305 if (isa<ConceptDecl>(TD)) 1306 return TemplateNameKindForDiagnostics::Concept; 1307 return TemplateNameKindForDiagnostics::DependentTemplate; 1308 } 1309 1310 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1311 assert(DC->getLexicalParent() == CurContext && 1312 "The next DeclContext should be lexically contained in the current one."); 1313 CurContext = DC; 1314 S->setEntity(DC); 1315 } 1316 1317 void Sema::PopDeclContext() { 1318 assert(CurContext && "DeclContext imbalance!"); 1319 1320 CurContext = CurContext->getLexicalParent(); 1321 assert(CurContext && "Popped translation unit!"); 1322 } 1323 1324 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1325 Decl *D) { 1326 // Unlike PushDeclContext, the context to which we return is not necessarily 1327 // the containing DC of TD, because the new context will be some pre-existing 1328 // TagDecl definition instead of a fresh one. 1329 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1330 CurContext = cast<TagDecl>(D)->getDefinition(); 1331 assert(CurContext && "skipping definition of undefined tag"); 1332 // Start lookups from the parent of the current context; we don't want to look 1333 // into the pre-existing complete definition. 1334 S->setEntity(CurContext->getLookupParent()); 1335 return Result; 1336 } 1337 1338 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1339 CurContext = static_cast<decltype(CurContext)>(Context); 1340 } 1341 1342 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1343 // C++0x [basic.lookup.unqual]p13: 1344 // A name used in the definition of a static data member of class 1345 // X (after the qualified-id of the static member) is looked up as 1346 // if the name was used in a member function of X. 1347 // C++0x [basic.lookup.unqual]p14: 1348 // If a variable member of a namespace is defined outside of the 1349 // scope of its namespace then any name used in the definition of 1350 // the variable member (after the declarator-id) is looked up as 1351 // if the definition of the variable member occurred in its 1352 // namespace. 1353 // Both of these imply that we should push a scope whose context 1354 // is the semantic context of the declaration. We can't use 1355 // PushDeclContext here because that context is not necessarily 1356 // lexically contained in the current context. Fortunately, 1357 // the containing scope should have the appropriate information. 1358 1359 assert(!S->getEntity() && "scope already has entity"); 1360 1361 #ifndef NDEBUG 1362 Scope *Ancestor = S->getParent(); 1363 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1364 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1365 #endif 1366 1367 CurContext = DC; 1368 S->setEntity(DC); 1369 1370 if (S->getParent()->isTemplateParamScope()) { 1371 // Also set the corresponding entities for all immediately-enclosing 1372 // template parameter scopes. 1373 EnterTemplatedContext(S->getParent(), DC); 1374 } 1375 } 1376 1377 void Sema::ExitDeclaratorContext(Scope *S) { 1378 assert(S->getEntity() == CurContext && "Context imbalance!"); 1379 1380 // Switch back to the lexical context. The safety of this is 1381 // enforced by an assert in EnterDeclaratorContext. 1382 Scope *Ancestor = S->getParent(); 1383 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1384 CurContext = Ancestor->getEntity(); 1385 1386 // We don't need to do anything with the scope, which is going to 1387 // disappear. 1388 } 1389 1390 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1391 assert(S->isTemplateParamScope() && 1392 "expected to be initializing a template parameter scope"); 1393 1394 // C++20 [temp.local]p7: 1395 // In the definition of a member of a class template that appears outside 1396 // of the class template definition, the name of a member of the class 1397 // template hides the name of a template-parameter of any enclosing class 1398 // templates (but not a template-parameter of the member if the member is a 1399 // class or function template). 1400 // C++20 [temp.local]p9: 1401 // In the definition of a class template or in the definition of a member 1402 // of such a template that appears outside of the template definition, for 1403 // each non-dependent base class (13.8.2.1), if the name of the base class 1404 // or the name of a member of the base class is the same as the name of a 1405 // template-parameter, the base class name or member name hides the 1406 // template-parameter name (6.4.10). 1407 // 1408 // This means that a template parameter scope should be searched immediately 1409 // after searching the DeclContext for which it is a template parameter 1410 // scope. For example, for 1411 // template<typename T> template<typename U> template<typename V> 1412 // void N::A<T>::B<U>::f(...) 1413 // we search V then B<U> (and base classes) then U then A<T> (and base 1414 // classes) then T then N then ::. 1415 unsigned ScopeDepth = getTemplateDepth(S); 1416 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1417 DeclContext *SearchDCAfterScope = DC; 1418 for (; DC; DC = DC->getLookupParent()) { 1419 if (const TemplateParameterList *TPL = 1420 cast<Decl>(DC)->getDescribedTemplateParams()) { 1421 unsigned DCDepth = TPL->getDepth() + 1; 1422 if (DCDepth > ScopeDepth) 1423 continue; 1424 if (ScopeDepth == DCDepth) 1425 SearchDCAfterScope = DC = DC->getLookupParent(); 1426 break; 1427 } 1428 } 1429 S->setLookupEntity(SearchDCAfterScope); 1430 } 1431 } 1432 1433 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1434 // We assume that the caller has already called 1435 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1436 FunctionDecl *FD = D->getAsFunction(); 1437 if (!FD) 1438 return; 1439 1440 // Same implementation as PushDeclContext, but enters the context 1441 // from the lexical parent, rather than the top-level class. 1442 assert(CurContext == FD->getLexicalParent() && 1443 "The next DeclContext should be lexically contained in the current one."); 1444 CurContext = FD; 1445 S->setEntity(CurContext); 1446 1447 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1448 ParmVarDecl *Param = FD->getParamDecl(P); 1449 // If the parameter has an identifier, then add it to the scope 1450 if (Param->getIdentifier()) { 1451 S->AddDecl(Param); 1452 IdResolver.AddDecl(Param); 1453 } 1454 } 1455 } 1456 1457 void Sema::ActOnExitFunctionContext() { 1458 // Same implementation as PopDeclContext, but returns to the lexical parent, 1459 // rather than the top-level class. 1460 assert(CurContext && "DeclContext imbalance!"); 1461 CurContext = CurContext->getLexicalParent(); 1462 assert(CurContext && "Popped translation unit!"); 1463 } 1464 1465 /// Determine whether overloading is allowed for a new function 1466 /// declaration considering prior declarations of the same name. 1467 /// 1468 /// This routine determines whether overloading is possible, not 1469 /// whether a new declaration actually overloads a previous one. 1470 /// It will return true in C++ (where overloads are always permitted) 1471 /// or, as a C extension, when either the new declaration or a 1472 /// previous one is declared with the 'overloadable' attribute. 1473 static bool AllowOverloadingOfFunction(const LookupResult &Previous, 1474 ASTContext &Context, 1475 const FunctionDecl *New) { 1476 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>()) 1477 return true; 1478 1479 // Multiversion function declarations are not overloads in the 1480 // usual sense of that term, but lookup will report that an 1481 // overload set was found if more than one multiversion function 1482 // declaration is present for the same name. It is therefore 1483 // inadequate to assume that some prior declaration(s) had 1484 // the overloadable attribute; checking is required. Since one 1485 // declaration is permitted to omit the attribute, it is necessary 1486 // to check at least two; hence the 'any_of' check below. Note that 1487 // the overloadable attribute is implicitly added to declarations 1488 // that were required to have it but did not. 1489 if (Previous.getResultKind() == LookupResult::FoundOverloaded) { 1490 return llvm::any_of(Previous, [](const NamedDecl *ND) { 1491 return ND->hasAttr<OverloadableAttr>(); 1492 }); 1493 } else if (Previous.getResultKind() == LookupResult::Found) 1494 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>(); 1495 1496 return false; 1497 } 1498 1499 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1500 // Move up the scope chain until we find the nearest enclosing 1501 // non-transparent context. The declaration will be introduced into this 1502 // scope. 1503 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1504 S = S->getParent(); 1505 1506 // Add scoped declarations into their context, so that they can be 1507 // found later. Declarations without a context won't be inserted 1508 // into any context. 1509 if (AddToContext) 1510 CurContext->addDecl(D); 1511 1512 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1513 // are function-local declarations. 1514 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1515 return; 1516 1517 // Template instantiations should also not be pushed into scope. 1518 if (isa<FunctionDecl>(D) && 1519 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1520 return; 1521 1522 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) { 1523 S->AddDecl(D); 1524 return; 1525 } 1526 // If this replaces anything in the current scope, 1527 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1528 IEnd = IdResolver.end(); 1529 for (; I != IEnd; ++I) { 1530 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1531 S->RemoveDecl(*I); 1532 IdResolver.RemoveDecl(*I); 1533 1534 // Should only need to replace one decl. 1535 break; 1536 } 1537 } 1538 1539 S->AddDecl(D); 1540 1541 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1542 // Implicitly-generated labels may end up getting generated in an order that 1543 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1544 // the label at the appropriate place in the identifier chain. 1545 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1546 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1547 if (IDC == CurContext) { 1548 if (!S->isDeclScope(*I)) 1549 continue; 1550 } else if (IDC->Encloses(CurContext)) 1551 break; 1552 } 1553 1554 IdResolver.InsertDeclAfter(I, D); 1555 } else { 1556 IdResolver.AddDecl(D); 1557 } 1558 warnOnReservedIdentifier(D); 1559 } 1560 1561 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1562 bool AllowInlineNamespace) const { 1563 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1564 } 1565 1566 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1567 DeclContext *TargetDC = DC->getPrimaryContext(); 1568 do { 1569 if (DeclContext *ScopeDC = S->getEntity()) 1570 if (ScopeDC->getPrimaryContext() == TargetDC) 1571 return S; 1572 } while ((S = S->getParent())); 1573 1574 return nullptr; 1575 } 1576 1577 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1578 DeclContext*, 1579 ASTContext&); 1580 1581 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1582 bool ConsiderLinkage, 1583 bool AllowInlineNamespace) { 1584 LookupResult::Filter F = R.makeFilter(); 1585 while (F.hasNext()) { 1586 NamedDecl *D = F.next(); 1587 1588 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1589 continue; 1590 1591 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1592 continue; 1593 1594 F.erase(); 1595 } 1596 1597 F.done(); 1598 } 1599 1600 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1601 // [module.interface]p7: 1602 // A declaration is attached to a module as follows: 1603 // - If the declaration is a non-dependent friend declaration that nominates a 1604 // function with a declarator-id that is a qualified-id or template-id or that 1605 // nominates a class other than with an elaborated-type-specifier with neither 1606 // a nested-name-specifier nor a simple-template-id, it is attached to the 1607 // module to which the friend is attached ([basic.link]). 1608 if (New->getFriendObjectKind() && 1609 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1610 New->setLocalOwningModule(Old->getOwningModule()); 1611 makeMergedDefinitionVisible(New); 1612 return false; 1613 } 1614 1615 Module *NewM = New->getOwningModule(); 1616 Module *OldM = Old->getOwningModule(); 1617 1618 if (NewM && NewM->isPrivateModule()) 1619 NewM = NewM->Parent; 1620 if (OldM && OldM->isPrivateModule()) 1621 OldM = OldM->Parent; 1622 1623 if (NewM == OldM) 1624 return false; 1625 1626 if (NewM && OldM) { 1627 // A module implementation unit has visibility of the decls in its 1628 // implicitly imported interface. 1629 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface) 1630 return false; 1631 1632 // Partitions are part of the module, but a partition could import another 1633 // module, so verify that the PMIs agree. 1634 if ((NewM->isModulePartition() || OldM->isModulePartition()) && 1635 getASTContext().isInSameModule(NewM, OldM)) 1636 return false; 1637 } 1638 1639 bool NewIsModuleInterface = NewM && NewM->isNamedModule(); 1640 bool OldIsModuleInterface = OldM && OldM->isNamedModule(); 1641 if (NewIsModuleInterface || OldIsModuleInterface) { 1642 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1643 // if a declaration of D [...] appears in the purview of a module, all 1644 // other such declarations shall appear in the purview of the same module 1645 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1646 << New 1647 << NewIsModuleInterface 1648 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1649 << OldIsModuleInterface 1650 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1651 Diag(Old->getLocation(), diag::note_previous_declaration); 1652 New->setInvalidDecl(); 1653 return true; 1654 } 1655 1656 return false; 1657 } 1658 1659 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) { 1660 // [module.interface]p1: 1661 // An export-declaration shall inhabit a namespace scope. 1662 // 1663 // So it is meaningless to talk about redeclaration which is not at namespace 1664 // scope. 1665 if (!New->getLexicalDeclContext() 1666 ->getNonTransparentContext() 1667 ->isFileContext() || 1668 !Old->getLexicalDeclContext() 1669 ->getNonTransparentContext() 1670 ->isFileContext()) 1671 return false; 1672 1673 bool IsNewExported = New->isInExportDeclContext(); 1674 bool IsOldExported = Old->isInExportDeclContext(); 1675 1676 // It should be irrevelant if both of them are not exported. 1677 if (!IsNewExported && !IsOldExported) 1678 return false; 1679 1680 if (IsOldExported) 1681 return false; 1682 1683 // If the Old declaration are not attached to named modules 1684 // and the New declaration are attached to global module. 1685 // It should be fine to allow the export since it doesn't change 1686 // the linkage of declarations. See 1687 // https://github.com/llvm/llvm-project/issues/98583 for details. 1688 if (!Old->isInNamedModule() && New->getOwningModule() && 1689 New->getOwningModule()->isImplicitGlobalModule()) 1690 return false; 1691 1692 assert(IsNewExported); 1693 1694 auto Lk = Old->getFormalLinkage(); 1695 int S = 0; 1696 if (Lk == Linkage::Internal) 1697 S = 1; 1698 else if (Lk == Linkage::Module) 1699 S = 2; 1700 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S; 1701 Diag(Old->getLocation(), diag::note_previous_declaration); 1702 return true; 1703 } 1704 1705 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) { 1706 if (CheckRedeclarationModuleOwnership(New, Old)) 1707 return true; 1708 1709 if (CheckRedeclarationExported(New, Old)) 1710 return true; 1711 1712 return false; 1713 } 1714 1715 bool Sema::IsRedefinitionInModule(const NamedDecl *New, 1716 const NamedDecl *Old) const { 1717 assert(getASTContext().isSameEntity(New, Old) && 1718 "New and Old are not the same definition, we should diagnostic it " 1719 "immediately instead of checking it."); 1720 assert(const_cast<Sema *>(this)->isReachable(New) && 1721 const_cast<Sema *>(this)->isReachable(Old) && 1722 "We shouldn't see unreachable definitions here."); 1723 1724 Module *NewM = New->getOwningModule(); 1725 Module *OldM = Old->getOwningModule(); 1726 1727 // We only checks for named modules here. The header like modules is skipped. 1728 // FIXME: This is not right if we import the header like modules in the module 1729 // purview. 1730 // 1731 // For example, assuming "header.h" provides definition for `D`. 1732 // ```C++ 1733 // //--- M.cppm 1734 // export module M; 1735 // import "header.h"; // or #include "header.h" but import it by clang modules 1736 // actually. 1737 // 1738 // //--- Use.cpp 1739 // import M; 1740 // import "header.h"; // or uses clang modules. 1741 // ``` 1742 // 1743 // In this case, `D` has multiple definitions in multiple TU (M.cppm and 1744 // Use.cpp) and `D` is attached to a named module `M`. The compiler should 1745 // reject it. But the current implementation couldn't detect the case since we 1746 // don't record the information about the importee modules. 1747 // 1748 // But this might not be painful in practice. Since the design of C++20 Named 1749 // Modules suggests us to use headers in global module fragment instead of 1750 // module purview. 1751 if (NewM && NewM->isHeaderLikeModule()) 1752 NewM = nullptr; 1753 if (OldM && OldM->isHeaderLikeModule()) 1754 OldM = nullptr; 1755 1756 if (!NewM && !OldM) 1757 return true; 1758 1759 // [basic.def.odr]p14.3 1760 // Each such definition shall not be attached to a named module 1761 // ([module.unit]). 1762 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule())) 1763 return true; 1764 1765 // Then New and Old lives in the same TU if their share one same module unit. 1766 if (NewM) 1767 NewM = NewM->getTopLevelModule(); 1768 if (OldM) 1769 OldM = OldM->getTopLevelModule(); 1770 return OldM == NewM; 1771 } 1772 1773 static bool isUsingDeclNotAtClassScope(NamedDecl *D) { 1774 if (D->getDeclContext()->isFileContext()) 1775 return false; 1776 1777 return isa<UsingShadowDecl>(D) || 1778 isa<UnresolvedUsingTypenameDecl>(D) || 1779 isa<UnresolvedUsingValueDecl>(D); 1780 } 1781 1782 /// Removes using shadow declarations not at class scope from the lookup 1783 /// results. 1784 static void RemoveUsingDecls(LookupResult &R) { 1785 LookupResult::Filter F = R.makeFilter(); 1786 while (F.hasNext()) 1787 if (isUsingDeclNotAtClassScope(F.next())) 1788 F.erase(); 1789 1790 F.done(); 1791 } 1792 1793 /// Check for this common pattern: 1794 /// @code 1795 /// class S { 1796 /// S(const S&); // DO NOT IMPLEMENT 1797 /// void operator=(const S&); // DO NOT IMPLEMENT 1798 /// }; 1799 /// @endcode 1800 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1801 // FIXME: Should check for private access too but access is set after we get 1802 // the decl here. 1803 if (D->doesThisDeclarationHaveABody()) 1804 return false; 1805 1806 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1807 return CD->isCopyConstructor(); 1808 return D->isCopyAssignmentOperator(); 1809 } 1810 1811 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1812 const DeclContext *DC = D->getDeclContext(); 1813 while (!DC->isTranslationUnit()) { 1814 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1815 if (!RD->hasNameForLinkage()) 1816 return true; 1817 } 1818 DC = DC->getParent(); 1819 } 1820 1821 return !D->isExternallyVisible(); 1822 } 1823 1824 // FIXME: This needs to be refactored; some other isInMainFile users want 1825 // these semantics. 1826 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1827 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile) 1828 return false; 1829 return S.SourceMgr.isInMainFile(Loc); 1830 } 1831 1832 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1833 assert(D); 1834 1835 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1836 return false; 1837 1838 // Ignore all entities declared within templates, and out-of-line definitions 1839 // of members of class templates. 1840 if (D->getDeclContext()->isDependentContext() || 1841 D->getLexicalDeclContext()->isDependentContext()) 1842 return false; 1843 1844 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1845 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1846 return false; 1847 // A non-out-of-line declaration of a member specialization was implicitly 1848 // instantiated; it's the out-of-line declaration that we're interested in. 1849 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1850 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1851 return false; 1852 1853 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1854 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1855 return false; 1856 } else { 1857 // 'static inline' functions are defined in headers; don't warn. 1858 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1859 return false; 1860 } 1861 1862 if (FD->doesThisDeclarationHaveABody() && 1863 Context.DeclMustBeEmitted(FD)) 1864 return false; 1865 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1866 // Constants and utility variables are defined in headers with internal 1867 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1868 // like "inline".) 1869 if (!isMainFileLoc(*this, VD->getLocation())) 1870 return false; 1871 1872 if (Context.DeclMustBeEmitted(VD)) 1873 return false; 1874 1875 if (VD->isStaticDataMember() && 1876 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1877 return false; 1878 if (VD->isStaticDataMember() && 1879 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1880 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1881 return false; 1882 1883 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1884 return false; 1885 } else { 1886 return false; 1887 } 1888 1889 // Only warn for unused decls internal to the translation unit. 1890 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1891 // for inline functions defined in the main source file, for instance. 1892 return mightHaveNonExternalLinkage(D); 1893 } 1894 1895 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1896 if (!D) 1897 return; 1898 1899 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1900 const FunctionDecl *First = FD->getFirstDecl(); 1901 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1902 return; // First should already be in the vector. 1903 } 1904 1905 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1906 const VarDecl *First = VD->getFirstDecl(); 1907 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1908 return; // First should already be in the vector. 1909 } 1910 1911 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1912 UnusedFileScopedDecls.push_back(D); 1913 } 1914 1915 static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, 1916 const NamedDecl *D) { 1917 if (D->isInvalidDecl()) 1918 return false; 1919 1920 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) { 1921 // For a decomposition declaration, warn if none of the bindings are 1922 // referenced, instead of if the variable itself is referenced (which 1923 // it is, by the bindings' expressions). 1924 bool IsAllPlaceholders = true; 1925 for (const auto *BD : DD->bindings()) { 1926 if (BD->isReferenced() || BD->hasAttr<UnusedAttr>()) 1927 return false; 1928 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts); 1929 } 1930 if (IsAllPlaceholders) 1931 return false; 1932 } else if (!D->getDeclName()) { 1933 return false; 1934 } else if (D->isReferenced() || D->isUsed()) { 1935 return false; 1936 } 1937 1938 if (D->isPlaceholderVar(LangOpts)) 1939 return false; 1940 1941 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() || 1942 D->hasAttr<CleanupAttr>()) 1943 return false; 1944 1945 if (isa<LabelDecl>(D)) 1946 return true; 1947 1948 // Except for labels, we only care about unused decls that are local to 1949 // functions. 1950 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1951 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1952 // For dependent types, the diagnostic is deferred. 1953 WithinFunction = 1954 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1955 if (!WithinFunction) 1956 return false; 1957 1958 if (isa<TypedefNameDecl>(D)) 1959 return true; 1960 1961 // White-list anything that isn't a local variable. 1962 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1963 return false; 1964 1965 // Types of valid local variables should be complete, so this should succeed. 1966 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1967 1968 const Expr *Init = VD->getInit(); 1969 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init)) 1970 Init = Cleanups->getSubExpr(); 1971 1972 const auto *Ty = VD->getType().getTypePtr(); 1973 1974 // Only look at the outermost level of typedef. 1975 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1976 // Allow anything marked with __attribute__((unused)). 1977 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1978 return false; 1979 } 1980 1981 // Warn for reference variables whose initializtion performs lifetime 1982 // extension. 1983 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init); 1984 MTE && MTE->getExtendingDecl()) { 1985 Ty = VD->getType().getNonReferenceType().getTypePtr(); 1986 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten(); 1987 } 1988 1989 // If we failed to complete the type for some reason, or if the type is 1990 // dependent, don't diagnose the variable. 1991 if (Ty->isIncompleteType() || Ty->isDependentType()) 1992 return false; 1993 1994 // Look at the element type to ensure that the warning behaviour is 1995 // consistent for both scalars and arrays. 1996 Ty = Ty->getBaseElementTypeUnsafe(); 1997 1998 if (const TagType *TT = Ty->getAs<TagType>()) { 1999 const TagDecl *Tag = TT->getDecl(); 2000 if (Tag->hasAttr<UnusedAttr>()) 2001 return false; 2002 2003 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 2004 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 2005 return false; 2006 2007 if (Init) { 2008 const auto *Construct = 2009 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts()); 2010 if (Construct && !Construct->isElidable()) { 2011 const CXXConstructorDecl *CD = Construct->getConstructor(); 2012 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 2013 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 2014 return false; 2015 } 2016 2017 // Suppress the warning if we don't know how this is constructed, and 2018 // it could possibly be non-trivial constructor. 2019 if (Init->isTypeDependent()) { 2020 for (const CXXConstructorDecl *Ctor : RD->ctors()) 2021 if (!Ctor->isTrivial()) 2022 return false; 2023 } 2024 2025 // Suppress the warning if the constructor is unresolved because 2026 // its arguments are dependent. 2027 if (isa<CXXUnresolvedConstructExpr>(Init)) 2028 return false; 2029 } 2030 } 2031 } 2032 2033 // TODO: __attribute__((unused)) templates? 2034 } 2035 2036 return true; 2037 } 2038 2039 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 2040 FixItHint &Hint) { 2041 if (isa<LabelDecl>(D)) { 2042 SourceLocation AfterColon = Lexer::findLocationAfterToken( 2043 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 2044 /*SkipTrailingWhitespaceAndNewline=*/false); 2045 if (AfterColon.isInvalid()) 2046 return; 2047 Hint = FixItHint::CreateRemoval( 2048 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 2049 } 2050 } 2051 2052 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 2053 DiagnoseUnusedNestedTypedefs( 2054 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); }); 2055 } 2056 2057 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D, 2058 DiagReceiverTy DiagReceiver) { 2059 if (D->getTypeForDecl()->isDependentType()) 2060 return; 2061 2062 for (auto *TmpD : D->decls()) { 2063 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 2064 DiagnoseUnusedDecl(T, DiagReceiver); 2065 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 2066 DiagnoseUnusedNestedTypedefs(R, DiagReceiver); 2067 } 2068 } 2069 2070 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 2071 DiagnoseUnusedDecl( 2072 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); }); 2073 } 2074 2075 void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) { 2076 if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D)) 2077 return; 2078 2079 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2080 // typedefs can be referenced later on, so the diagnostics are emitted 2081 // at end-of-translation-unit. 2082 UnusedLocalTypedefNameCandidates.insert(TD); 2083 return; 2084 } 2085 2086 FixItHint Hint; 2087 GenerateFixForUnusedDecl(D, Context, Hint); 2088 2089 unsigned DiagID; 2090 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 2091 DiagID = diag::warn_unused_exception_param; 2092 else if (isa<LabelDecl>(D)) 2093 DiagID = diag::warn_unused_label; 2094 else 2095 DiagID = diag::warn_unused_variable; 2096 2097 SourceLocation DiagLoc = D->getLocation(); 2098 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc)); 2099 } 2100 2101 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD, 2102 DiagReceiverTy DiagReceiver) { 2103 // If it's not referenced, it can't be set. If it has the Cleanup attribute, 2104 // it's not really unused. 2105 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>()) 2106 return; 2107 2108 // In C++, `_` variables behave as if they were maybe_unused 2109 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts())) 2110 return; 2111 2112 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 2113 2114 if (Ty->isReferenceType() || Ty->isDependentType()) 2115 return; 2116 2117 if (const TagType *TT = Ty->getAs<TagType>()) { 2118 const TagDecl *Tag = TT->getDecl(); 2119 if (Tag->hasAttr<UnusedAttr>()) 2120 return; 2121 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 2122 // mimic gcc's behavior. 2123 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag); 2124 RD && !RD->hasAttr<WarnUnusedAttr>()) 2125 return; 2126 } 2127 2128 // Don't warn about __block Objective-C pointer variables, as they might 2129 // be assigned in the block but not used elsewhere for the purpose of lifetime 2130 // extension. 2131 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) 2132 return; 2133 2134 // Don't warn about Objective-C pointer variables with precise lifetime 2135 // semantics; they can be used to ensure ARC releases the object at a known 2136 // time, which may mean assignment but no other references. 2137 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType()) 2138 return; 2139 2140 auto iter = RefsMinusAssignments.find(VD); 2141 if (iter == RefsMinusAssignments.end()) 2142 return; 2143 2144 assert(iter->getSecond() >= 0 && 2145 "Found a negative number of references to a VarDecl"); 2146 if (int RefCnt = iter->getSecond(); RefCnt > 0) { 2147 // Assume the given VarDecl is "used" if its ref count stored in 2148 // `RefMinusAssignments` is positive, with one exception. 2149 // 2150 // For a C++ variable whose decl (with initializer) entirely consist the 2151 // condition expression of a if/while/for construct, 2152 // Clang creates a DeclRefExpr for the condition expression rather than a 2153 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref 2154 // count stored in `RefMinusAssignment` equals 1 when the variable is never 2155 // used in the body of the if/while/for construct. 2156 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1); 2157 if (!UnusedCXXCondDecl) 2158 return; 2159 } 2160 2161 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 2162 : diag::warn_unused_but_set_variable; 2163 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD); 2164 } 2165 2166 static void CheckPoppedLabel(LabelDecl *L, Sema &S, 2167 Sema::DiagReceiverTy DiagReceiver) { 2168 // Verify that we have no forward references left. If so, there was a goto 2169 // or address of a label taken, but no definition of it. Label fwd 2170 // definitions are indicated with a null substmt which is also not a resolved 2171 // MS inline assembly label name. 2172 bool Diagnose = false; 2173 if (L->isMSAsmLabel()) 2174 Diagnose = !L->isResolvedMSAsmLabel(); 2175 else 2176 Diagnose = L->getStmt() == nullptr; 2177 if (Diagnose) 2178 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use) 2179 << L); 2180 } 2181 2182 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 2183 S->applyNRVO(); 2184 2185 if (S->decl_empty()) return; 2186 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 2187 "Scope shouldn't contain decls!"); 2188 2189 /// We visit the decls in non-deterministic order, but we want diagnostics 2190 /// emitted in deterministic order. Collect any diagnostic that may be emitted 2191 /// and sort the diagnostics before emitting them, after we visited all decls. 2192 struct LocAndDiag { 2193 SourceLocation Loc; 2194 std::optional<SourceLocation> PreviousDeclLoc; 2195 PartialDiagnostic PD; 2196 }; 2197 SmallVector<LocAndDiag, 16> DeclDiags; 2198 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) { 2199 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)}); 2200 }; 2201 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc, 2202 SourceLocation PreviousDeclLoc, 2203 PartialDiagnostic PD) { 2204 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)}); 2205 }; 2206 2207 for (auto *TmpD : S->decls()) { 2208 assert(TmpD && "This decl didn't get pushed??"); 2209 2210 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 2211 NamedDecl *D = cast<NamedDecl>(TmpD); 2212 2213 // Diagnose unused variables in this scope. 2214 if (!S->hasUnrecoverableErrorOccurred()) { 2215 DiagnoseUnusedDecl(D, addDiag); 2216 if (const auto *RD = dyn_cast<RecordDecl>(D)) 2217 DiagnoseUnusedNestedTypedefs(RD, addDiag); 2218 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2219 DiagnoseUnusedButSetDecl(VD, addDiag); 2220 RefsMinusAssignments.erase(VD); 2221 } 2222 } 2223 2224 if (!D->getDeclName()) continue; 2225 2226 // If this was a forward reference to a label, verify it was defined. 2227 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 2228 CheckPoppedLabel(LD, *this, addDiag); 2229 2230 // Partial translation units that are created in incremental processing must 2231 // not clean up the IdResolver because PTUs should take into account the 2232 // declarations that came from previous PTUs. 2233 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC || 2234 getLangOpts().CPlusPlus) 2235 IdResolver.RemoveDecl(D); 2236 2237 // Warn on it if we are shadowing a declaration. 2238 auto ShadowI = ShadowingDecls.find(D); 2239 if (ShadowI != ShadowingDecls.end()) { 2240 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2241 addDiagWithPrev(D->getLocation(), FD->getLocation(), 2242 PDiag(diag::warn_ctor_parm_shadows_field) 2243 << D << FD << FD->getParent()); 2244 } 2245 ShadowingDecls.erase(ShadowI); 2246 } 2247 } 2248 2249 llvm::sort(DeclDiags, 2250 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool { 2251 // The particular order for diagnostics is not important, as long 2252 // as the order is deterministic. Using the raw location is going 2253 // to generally be in source order unless there are macro 2254 // expansions involved. 2255 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding(); 2256 }); 2257 for (const LocAndDiag &D : DeclDiags) { 2258 Diag(D.Loc, D.PD); 2259 if (D.PreviousDeclLoc) 2260 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration); 2261 } 2262 } 2263 2264 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2265 while (((S->getFlags() & Scope::DeclScope) == 0) || 2266 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2267 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2268 S = S->getParent(); 2269 return S; 2270 } 2271 2272 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2273 ASTContext::GetBuiltinTypeError Error) { 2274 switch (Error) { 2275 case ASTContext::GE_None: 2276 return ""; 2277 case ASTContext::GE_Missing_type: 2278 return BuiltinInfo.getHeaderName(ID); 2279 case ASTContext::GE_Missing_stdio: 2280 return "stdio.h"; 2281 case ASTContext::GE_Missing_setjmp: 2282 return "setjmp.h"; 2283 case ASTContext::GE_Missing_ucontext: 2284 return "ucontext.h"; 2285 } 2286 llvm_unreachable("unhandled error kind"); 2287 } 2288 2289 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2290 unsigned ID, SourceLocation Loc) { 2291 DeclContext *Parent = Context.getTranslationUnitDecl(); 2292 2293 if (getLangOpts().CPlusPlus) { 2294 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2295 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false); 2296 CLinkageDecl->setImplicit(); 2297 Parent->addDecl(CLinkageDecl); 2298 Parent = CLinkageDecl; 2299 } 2300 2301 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified; 2302 if (Context.BuiltinInfo.isImmediate(ID)) { 2303 assert(getLangOpts().CPlusPlus20 && 2304 "consteval builtins should only be available in C++20 mode"); 2305 ConstexprKind = ConstexprSpecKind::Consteval; 2306 } 2307 2308 FunctionDecl *New = FunctionDecl::Create( 2309 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern, 2310 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false, 2311 Type->isFunctionProtoType(), ConstexprKind); 2312 New->setImplicit(); 2313 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2314 2315 // Create Decl objects for each parameter, adding them to the 2316 // FunctionDecl. 2317 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2318 SmallVector<ParmVarDecl *, 16> Params; 2319 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2320 ParmVarDecl *parm = ParmVarDecl::Create( 2321 Context, New, SourceLocation(), SourceLocation(), nullptr, 2322 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2323 parm->setScopeInfo(0, i); 2324 Params.push_back(parm); 2325 } 2326 New->setParams(Params); 2327 } 2328 2329 AddKnownFunctionAttributes(New); 2330 return New; 2331 } 2332 2333 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2334 Scope *S, bool ForRedeclaration, 2335 SourceLocation Loc) { 2336 LookupNecessaryTypesForBuiltin(S, ID); 2337 2338 ASTContext::GetBuiltinTypeError Error; 2339 QualType R = Context.GetBuiltinType(ID, Error); 2340 if (Error) { 2341 if (!ForRedeclaration) 2342 return nullptr; 2343 2344 // If we have a builtin without an associated type we should not emit a 2345 // warning when we were not able to find a type for it. 2346 if (Error == ASTContext::GE_Missing_type || 2347 Context.BuiltinInfo.allowTypeMismatch(ID)) 2348 return nullptr; 2349 2350 // If we could not find a type for setjmp it is because the jmp_buf type was 2351 // not defined prior to the setjmp declaration. 2352 if (Error == ASTContext::GE_Missing_setjmp) { 2353 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2354 << Context.BuiltinInfo.getName(ID); 2355 return nullptr; 2356 } 2357 2358 // Generally, we emit a warning that the declaration requires the 2359 // appropriate header. 2360 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2361 << getHeaderName(Context.BuiltinInfo, ID, Error) 2362 << Context.BuiltinInfo.getName(ID); 2363 return nullptr; 2364 } 2365 2366 if (!ForRedeclaration && 2367 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2368 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2369 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99 2370 : diag::ext_implicit_lib_function_decl) 2371 << Context.BuiltinInfo.getName(ID) << R; 2372 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2373 Diag(Loc, diag::note_include_header_or_declare) 2374 << Header << Context.BuiltinInfo.getName(ID); 2375 } 2376 2377 if (R.isNull()) 2378 return nullptr; 2379 2380 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2381 RegisterLocallyScopedExternCDecl(New, S); 2382 2383 // TUScope is the translation-unit scope to insert this function into. 2384 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2385 // relate Scopes to DeclContexts, and probably eliminate CurContext 2386 // entirely, but we're not there yet. 2387 DeclContext *SavedContext = CurContext; 2388 CurContext = New->getDeclContext(); 2389 PushOnScopeChains(New, TUScope); 2390 CurContext = SavedContext; 2391 return New; 2392 } 2393 2394 /// Typedef declarations don't have linkage, but they still denote the same 2395 /// entity if their types are the same. 2396 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2397 /// isSameEntity. 2398 static void 2399 filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl, 2400 LookupResult &Previous) { 2401 // This is only interesting when modules are enabled. 2402 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2403 return; 2404 2405 // Empty sets are uninteresting. 2406 if (Previous.empty()) 2407 return; 2408 2409 LookupResult::Filter Filter = Previous.makeFilter(); 2410 while (Filter.hasNext()) { 2411 NamedDecl *Old = Filter.next(); 2412 2413 // Non-hidden declarations are never ignored. 2414 if (S.isVisible(Old)) 2415 continue; 2416 2417 // Declarations of the same entity are not ignored, even if they have 2418 // different linkages. 2419 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2420 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2421 Decl->getUnderlyingType())) 2422 continue; 2423 2424 // If both declarations give a tag declaration a typedef name for linkage 2425 // purposes, then they declare the same entity. 2426 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2427 Decl->getAnonDeclWithTypedefName()) 2428 continue; 2429 } 2430 2431 Filter.erase(); 2432 } 2433 2434 Filter.done(); 2435 } 2436 2437 bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) { 2438 QualType OldType; 2439 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2440 OldType = OldTypedef->getUnderlyingType(); 2441 else 2442 OldType = Context.getTypeDeclType(Old); 2443 QualType NewType = New->getUnderlyingType(); 2444 2445 if (NewType->isVariablyModifiedType()) { 2446 // Must not redefine a typedef with a variably-modified type. 2447 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2448 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2449 << Kind << NewType; 2450 if (Old->getLocation().isValid()) 2451 notePreviousDefinition(Old, New->getLocation()); 2452 New->setInvalidDecl(); 2453 return true; 2454 } 2455 2456 if (OldType != NewType && 2457 !OldType->isDependentType() && 2458 !NewType->isDependentType() && 2459 !Context.hasSameType(OldType, NewType)) { 2460 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2461 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2462 << Kind << NewType << OldType; 2463 if (Old->getLocation().isValid()) 2464 notePreviousDefinition(Old, New->getLocation()); 2465 New->setInvalidDecl(); 2466 return true; 2467 } 2468 return false; 2469 } 2470 2471 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2472 LookupResult &OldDecls) { 2473 // If the new decl is known invalid already, don't bother doing any 2474 // merging checks. 2475 if (New->isInvalidDecl()) return; 2476 2477 // Allow multiple definitions for ObjC built-in typedefs. 2478 // FIXME: Verify the underlying types are equivalent! 2479 if (getLangOpts().ObjC) { 2480 const IdentifierInfo *TypeID = New->getIdentifier(); 2481 switch (TypeID->getLength()) { 2482 default: break; 2483 case 2: 2484 { 2485 if (!TypeID->isStr("id")) 2486 break; 2487 QualType T = New->getUnderlyingType(); 2488 if (!T->isPointerType()) 2489 break; 2490 if (!T->isVoidPointerType()) { 2491 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2492 if (!PT->isStructureType()) 2493 break; 2494 } 2495 Context.setObjCIdRedefinitionType(T); 2496 // Install the built-in type for 'id', ignoring the current definition. 2497 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2498 return; 2499 } 2500 case 5: 2501 if (!TypeID->isStr("Class")) 2502 break; 2503 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2504 // Install the built-in type for 'Class', ignoring the current definition. 2505 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2506 return; 2507 case 3: 2508 if (!TypeID->isStr("SEL")) 2509 break; 2510 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2511 // Install the built-in type for 'SEL', ignoring the current definition. 2512 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2513 return; 2514 } 2515 // Fall through - the typedef name was not a builtin type. 2516 } 2517 2518 // Verify the old decl was also a type. 2519 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2520 if (!Old) { 2521 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2522 << New->getDeclName(); 2523 2524 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2525 if (OldD->getLocation().isValid()) 2526 notePreviousDefinition(OldD, New->getLocation()); 2527 2528 return New->setInvalidDecl(); 2529 } 2530 2531 // If the old declaration is invalid, just give up here. 2532 if (Old->isInvalidDecl()) 2533 return New->setInvalidDecl(); 2534 2535 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2536 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2537 auto *NewTag = New->getAnonDeclWithTypedefName(); 2538 NamedDecl *Hidden = nullptr; 2539 if (OldTag && NewTag && 2540 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2541 !hasVisibleDefinition(OldTag, &Hidden)) { 2542 // There is a definition of this tag, but it is not visible. Use it 2543 // instead of our tag. 2544 New->setTypeForDecl(OldTD->getTypeForDecl()); 2545 if (OldTD->isModed()) 2546 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2547 OldTD->getUnderlyingType()); 2548 else 2549 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2550 2551 // Make the old tag definition visible. 2552 makeMergedDefinitionVisible(Hidden); 2553 2554 // If this was an unscoped enumeration, yank all of its enumerators 2555 // out of the scope. 2556 if (isa<EnumDecl>(NewTag)) { 2557 Scope *EnumScope = getNonFieldDeclScope(S); 2558 for (auto *D : NewTag->decls()) { 2559 auto *ED = cast<EnumConstantDecl>(D); 2560 assert(EnumScope->isDeclScope(ED)); 2561 EnumScope->RemoveDecl(ED); 2562 IdResolver.RemoveDecl(ED); 2563 ED->getLexicalDeclContext()->removeDecl(ED); 2564 } 2565 } 2566 } 2567 } 2568 2569 // If the typedef types are not identical, reject them in all languages and 2570 // with any extensions enabled. 2571 if (isIncompatibleTypedef(Old, New)) 2572 return; 2573 2574 // The types match. Link up the redeclaration chain and merge attributes if 2575 // the old declaration was a typedef. 2576 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2577 New->setPreviousDecl(Typedef); 2578 mergeDeclAttributes(New, Old); 2579 } 2580 2581 if (getLangOpts().MicrosoftExt) 2582 return; 2583 2584 if (getLangOpts().CPlusPlus) { 2585 // C++ [dcl.typedef]p2: 2586 // In a given non-class scope, a typedef specifier can be used to 2587 // redefine the name of any type declared in that scope to refer 2588 // to the type to which it already refers. 2589 if (!isa<CXXRecordDecl>(CurContext)) 2590 return; 2591 2592 // C++0x [dcl.typedef]p4: 2593 // In a given class scope, a typedef specifier can be used to redefine 2594 // any class-name declared in that scope that is not also a typedef-name 2595 // to refer to the type to which it already refers. 2596 // 2597 // This wording came in via DR424, which was a correction to the 2598 // wording in DR56, which accidentally banned code like: 2599 // 2600 // struct S { 2601 // typedef struct A { } A; 2602 // }; 2603 // 2604 // in the C++03 standard. We implement the C++0x semantics, which 2605 // allow the above but disallow 2606 // 2607 // struct S { 2608 // typedef int I; 2609 // typedef int I; 2610 // }; 2611 // 2612 // since that was the intent of DR56. 2613 if (!isa<TypedefNameDecl>(Old)) 2614 return; 2615 2616 Diag(New->getLocation(), diag::err_redefinition) 2617 << New->getDeclName(); 2618 notePreviousDefinition(Old, New->getLocation()); 2619 return New->setInvalidDecl(); 2620 } 2621 2622 // Modules always permit redefinition of typedefs, as does C11. 2623 if (getLangOpts().Modules || getLangOpts().C11) 2624 return; 2625 2626 // If we have a redefinition of a typedef in C, emit a warning. This warning 2627 // is normally mapped to an error, but can be controlled with 2628 // -Wtypedef-redefinition. If either the original or the redefinition is 2629 // in a system header, don't emit this for compatibility with GCC. 2630 if (getDiagnostics().getSuppressSystemWarnings() && 2631 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2632 (Old->isImplicit() || 2633 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2634 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2635 return; 2636 2637 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2638 << New->getDeclName(); 2639 notePreviousDefinition(Old, New->getLocation()); 2640 } 2641 2642 /// DeclhasAttr - returns true if decl Declaration already has the target 2643 /// attribute. 2644 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2645 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2646 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2647 for (const auto *i : D->attrs()) 2648 if (i->getKind() == A->getKind()) { 2649 if (Ann) { 2650 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2651 return true; 2652 continue; 2653 } 2654 // FIXME: Don't hardcode this check 2655 if (OA && isa<OwnershipAttr>(i)) 2656 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2657 return true; 2658 } 2659 2660 return false; 2661 } 2662 2663 static bool isAttributeTargetADefinition(Decl *D) { 2664 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2665 return VD->isThisDeclarationADefinition(); 2666 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2667 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2668 return true; 2669 } 2670 2671 /// Merge alignment attributes from \p Old to \p New, taking into account the 2672 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2673 /// 2674 /// \return \c true if any attributes were added to \p New. 2675 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2676 // Look for alignas attributes on Old, and pick out whichever attribute 2677 // specifies the strictest alignment requirement. 2678 AlignedAttr *OldAlignasAttr = nullptr; 2679 AlignedAttr *OldStrictestAlignAttr = nullptr; 2680 unsigned OldAlign = 0; 2681 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2682 // FIXME: We have no way of representing inherited dependent alignments 2683 // in a case like: 2684 // template<int A, int B> struct alignas(A) X; 2685 // template<int A, int B> struct alignas(B) X {}; 2686 // For now, we just ignore any alignas attributes which are not on the 2687 // definition in such a case. 2688 if (I->isAlignmentDependent()) 2689 return false; 2690 2691 if (I->isAlignas()) 2692 OldAlignasAttr = I; 2693 2694 unsigned Align = I->getAlignment(S.Context); 2695 if (Align > OldAlign) { 2696 OldAlign = Align; 2697 OldStrictestAlignAttr = I; 2698 } 2699 } 2700 2701 // Look for alignas attributes on New. 2702 AlignedAttr *NewAlignasAttr = nullptr; 2703 unsigned NewAlign = 0; 2704 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2705 if (I->isAlignmentDependent()) 2706 return false; 2707 2708 if (I->isAlignas()) 2709 NewAlignasAttr = I; 2710 2711 unsigned Align = I->getAlignment(S.Context); 2712 if (Align > NewAlign) 2713 NewAlign = Align; 2714 } 2715 2716 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2717 // Both declarations have 'alignas' attributes. We require them to match. 2718 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2719 // fall short. (If two declarations both have alignas, they must both match 2720 // every definition, and so must match each other if there is a definition.) 2721 2722 // If either declaration only contains 'alignas(0)' specifiers, then it 2723 // specifies the natural alignment for the type. 2724 if (OldAlign == 0 || NewAlign == 0) { 2725 QualType Ty; 2726 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2727 Ty = VD->getType(); 2728 else 2729 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2730 2731 if (OldAlign == 0) 2732 OldAlign = S.Context.getTypeAlign(Ty); 2733 if (NewAlign == 0) 2734 NewAlign = S.Context.getTypeAlign(Ty); 2735 } 2736 2737 if (OldAlign != NewAlign) { 2738 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2739 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2740 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2741 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2742 } 2743 } 2744 2745 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2746 // C++11 [dcl.align]p6: 2747 // if any declaration of an entity has an alignment-specifier, 2748 // every defining declaration of that entity shall specify an 2749 // equivalent alignment. 2750 // C11 6.7.5/7: 2751 // If the definition of an object does not have an alignment 2752 // specifier, any other declaration of that object shall also 2753 // have no alignment specifier. 2754 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2755 << OldAlignasAttr; 2756 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2757 << OldAlignasAttr; 2758 } 2759 2760 bool AnyAdded = false; 2761 2762 // Ensure we have an attribute representing the strictest alignment. 2763 if (OldAlign > NewAlign) { 2764 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2765 Clone->setInherited(true); 2766 New->addAttr(Clone); 2767 AnyAdded = true; 2768 } 2769 2770 // Ensure we have an alignas attribute if the old declaration had one. 2771 if (OldAlignasAttr && !NewAlignasAttr && 2772 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2773 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2774 Clone->setInherited(true); 2775 New->addAttr(Clone); 2776 AnyAdded = true; 2777 } 2778 2779 return AnyAdded; 2780 } 2781 2782 #define WANT_DECL_MERGE_LOGIC 2783 #include "clang/Sema/AttrParsedAttrImpl.inc" 2784 #undef WANT_DECL_MERGE_LOGIC 2785 2786 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2787 const InheritableAttr *Attr, 2788 Sema::AvailabilityMergeKind AMK) { 2789 // Diagnose any mutual exclusions between the attribute that we want to add 2790 // and attributes that already exist on the declaration. 2791 if (!DiagnoseMutualExclusions(S, D, Attr)) 2792 return false; 2793 2794 // This function copies an attribute Attr from a previous declaration to the 2795 // new declaration D if the new declaration doesn't itself have that attribute 2796 // yet or if that attribute allows duplicates. 2797 // If you're adding a new attribute that requires logic different from 2798 // "use explicit attribute on decl if present, else use attribute from 2799 // previous decl", for example if the attribute needs to be consistent 2800 // between redeclarations, you need to call a custom merge function here. 2801 InheritableAttr *NewAttr = nullptr; 2802 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2803 NewAttr = S.mergeAvailabilityAttr( 2804 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2805 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2806 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2807 AA->getPriority(), AA->getEnvironment()); 2808 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2809 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2810 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2811 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2812 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2813 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2814 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2815 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2816 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2817 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2818 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2819 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2820 FA->getFirstArg()); 2821 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2822 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2823 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2824 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2825 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2826 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2827 IA->getInheritanceModel()); 2828 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2829 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2830 &S.Context.Idents.get(AA->getSpelling())); 2831 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2832 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2833 isa<CUDAGlobalAttr>(Attr))) { 2834 // CUDA target attributes are part of function signature for 2835 // overloading purposes and must not be merged. 2836 return false; 2837 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2838 NewAttr = S.mergeMinSizeAttr(D, *MA); 2839 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2840 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName()); 2841 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2842 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2843 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2844 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2845 else if (isa<AlignedAttr>(Attr)) 2846 // AlignedAttrs are handled separately, because we need to handle all 2847 // such attributes on a declaration at the same time. 2848 NewAttr = nullptr; 2849 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2850 (AMK == Sema::AMK_Override || 2851 AMK == Sema::AMK_ProtocolImplementation || 2852 AMK == Sema::AMK_OptionalProtocolImplementation)) 2853 NewAttr = nullptr; 2854 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2855 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2856 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2857 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA); 2858 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2859 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA); 2860 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2861 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2862 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2863 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2864 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) 2865 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); 2866 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr)) 2867 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), 2868 NT->getZ()); 2869 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr)) 2870 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(), 2871 WS->getPreferred(), 2872 WS->getSpelledArgsCount()); 2873 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr)) 2874 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType()); 2875 else if (isa<SuppressAttr>(Attr)) 2876 // Do nothing. Each redeclaration should be suppressed separately. 2877 NewAttr = nullptr; 2878 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2879 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2880 2881 if (NewAttr) { 2882 NewAttr->setInherited(true); 2883 D->addAttr(NewAttr); 2884 if (isa<MSInheritanceAttr>(NewAttr)) 2885 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2886 return true; 2887 } 2888 2889 return false; 2890 } 2891 2892 static const NamedDecl *getDefinition(const Decl *D) { 2893 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2894 return TD->getDefinition(); 2895 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2896 const VarDecl *Def = VD->getDefinition(); 2897 if (Def) 2898 return Def; 2899 return VD->getActingDefinition(); 2900 } 2901 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2902 const FunctionDecl *Def = nullptr; 2903 if (FD->isDefined(Def, true)) 2904 return Def; 2905 } 2906 return nullptr; 2907 } 2908 2909 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2910 for (const auto *Attribute : D->attrs()) 2911 if (Attribute->getKind() == Kind) 2912 return true; 2913 return false; 2914 } 2915 2916 /// checkNewAttributesAfterDef - If we already have a definition, check that 2917 /// there are no new attributes in this declaration. 2918 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2919 if (!New->hasAttrs()) 2920 return; 2921 2922 const NamedDecl *Def = getDefinition(Old); 2923 if (!Def || Def == New) 2924 return; 2925 2926 AttrVec &NewAttributes = New->getAttrs(); 2927 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2928 Attr *NewAttribute = NewAttributes[I]; 2929 2930 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2931 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2932 SkipBodyInfo SkipBody; 2933 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2934 2935 // If we're skipping this definition, drop the "alias" attribute. 2936 if (SkipBody.ShouldSkip) { 2937 NewAttributes.erase(NewAttributes.begin() + I); 2938 --E; 2939 continue; 2940 } 2941 } else { 2942 VarDecl *VD = cast<VarDecl>(New); 2943 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2944 VarDecl::TentativeDefinition 2945 ? diag::err_alias_after_tentative 2946 : diag::err_redefinition; 2947 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2948 if (Diag == diag::err_redefinition) 2949 S.notePreviousDefinition(Def, VD->getLocation()); 2950 else 2951 S.Diag(Def->getLocation(), diag::note_previous_definition); 2952 VD->setInvalidDecl(); 2953 } 2954 ++I; 2955 continue; 2956 } 2957 2958 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2959 // Tentative definitions are only interesting for the alias check above. 2960 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2961 ++I; 2962 continue; 2963 } 2964 } 2965 2966 if (hasAttribute(Def, NewAttribute->getKind())) { 2967 ++I; 2968 continue; // regular attr merging will take care of validating this. 2969 } 2970 2971 if (isa<C11NoReturnAttr>(NewAttribute)) { 2972 // C's _Noreturn is allowed to be added to a function after it is defined. 2973 ++I; 2974 continue; 2975 } else if (isa<UuidAttr>(NewAttribute)) { 2976 // msvc will allow a subsequent definition to add an uuid to a class 2977 ++I; 2978 continue; 2979 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2980 if (AA->isAlignas()) { 2981 // C++11 [dcl.align]p6: 2982 // if any declaration of an entity has an alignment-specifier, 2983 // every defining declaration of that entity shall specify an 2984 // equivalent alignment. 2985 // C11 6.7.5/7: 2986 // If the definition of an object does not have an alignment 2987 // specifier, any other declaration of that object shall also 2988 // have no alignment specifier. 2989 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2990 << AA; 2991 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2992 << AA; 2993 NewAttributes.erase(NewAttributes.begin() + I); 2994 --E; 2995 continue; 2996 } 2997 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2998 // If there is a C definition followed by a redeclaration with this 2999 // attribute then there are two different definitions. In C++, prefer the 3000 // standard diagnostics. 3001 if (!S.getLangOpts().CPlusPlus) { 3002 S.Diag(NewAttribute->getLocation(), 3003 diag::err_loader_uninitialized_redeclaration); 3004 S.Diag(Def->getLocation(), diag::note_previous_definition); 3005 NewAttributes.erase(NewAttributes.begin() + I); 3006 --E; 3007 continue; 3008 } 3009 } else if (isa<SelectAnyAttr>(NewAttribute) && 3010 cast<VarDecl>(New)->isInline() && 3011 !cast<VarDecl>(New)->isInlineSpecified()) { 3012 // Don't warn about applying selectany to implicitly inline variables. 3013 // Older compilers and language modes would require the use of selectany 3014 // to make such variables inline, and it would have no effect if we 3015 // honored it. 3016 ++I; 3017 continue; 3018 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 3019 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 3020 // declarations after definitions. 3021 ++I; 3022 continue; 3023 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) { 3024 // Elevate latent uses of the sycl_kernel_entry_point attribute to an 3025 // error since the definition will have already been created without 3026 // the semantic effects of the attribute having been applied. 3027 S.Diag(NewAttribute->getLocation(), 3028 diag::err_sycl_entry_point_after_definition); 3029 S.Diag(Def->getLocation(), diag::note_previous_definition); 3030 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr(); 3031 ++I; 3032 continue; 3033 } 3034 3035 S.Diag(NewAttribute->getLocation(), 3036 diag::warn_attribute_precede_definition); 3037 S.Diag(Def->getLocation(), diag::note_previous_definition); 3038 NewAttributes.erase(NewAttributes.begin() + I); 3039 --E; 3040 } 3041 } 3042 3043 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 3044 const ConstInitAttr *CIAttr, 3045 bool AttrBeforeInit) { 3046 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 3047 3048 // Figure out a good way to write this specifier on the old declaration. 3049 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 3050 // enough of the attribute list spelling information to extract that without 3051 // heroics. 3052 std::string SuitableSpelling; 3053 if (S.getLangOpts().CPlusPlus20) 3054 SuitableSpelling = std::string( 3055 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 3056 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 3057 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 3058 InsertLoc, {tok::l_square, tok::l_square, 3059 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 3060 S.PP.getIdentifierInfo("require_constant_initialization"), 3061 tok::r_square, tok::r_square})); 3062 if (SuitableSpelling.empty()) 3063 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 3064 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 3065 S.PP.getIdentifierInfo("require_constant_initialization"), 3066 tok::r_paren, tok::r_paren})); 3067 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 3068 SuitableSpelling = "constinit"; 3069 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 3070 SuitableSpelling = "[[clang::require_constant_initialization]]"; 3071 if (SuitableSpelling.empty()) 3072 SuitableSpelling = "__attribute__((require_constant_initialization))"; 3073 SuitableSpelling += " "; 3074 3075 if (AttrBeforeInit) { 3076 // extern constinit int a; 3077 // int a = 0; // error (missing 'constinit'), accepted as extension 3078 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 3079 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 3080 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3081 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 3082 } else { 3083 // int a = 0; 3084 // constinit extern int a; // error (missing 'constinit') 3085 S.Diag(CIAttr->getLocation(), 3086 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 3087 : diag::warn_require_const_init_added_too_late) 3088 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 3089 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 3090 << CIAttr->isConstinit() 3091 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3092 } 3093 } 3094 3095 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 3096 AvailabilityMergeKind AMK) { 3097 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 3098 UsedAttr *NewAttr = OldAttr->clone(Context); 3099 NewAttr->setInherited(true); 3100 New->addAttr(NewAttr); 3101 } 3102 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 3103 RetainAttr *NewAttr = OldAttr->clone(Context); 3104 NewAttr->setInherited(true); 3105 New->addAttr(NewAttr); 3106 } 3107 3108 if (!Old->hasAttrs() && !New->hasAttrs()) 3109 return; 3110 3111 // [dcl.constinit]p1: 3112 // If the [constinit] specifier is applied to any declaration of a 3113 // variable, it shall be applied to the initializing declaration. 3114 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 3115 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 3116 if (bool(OldConstInit) != bool(NewConstInit)) { 3117 const auto *OldVD = cast<VarDecl>(Old); 3118 auto *NewVD = cast<VarDecl>(New); 3119 3120 // Find the initializing declaration. Note that we might not have linked 3121 // the new declaration into the redeclaration chain yet. 3122 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 3123 if (!InitDecl && 3124 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 3125 InitDecl = NewVD; 3126 3127 if (InitDecl == NewVD) { 3128 // This is the initializing declaration. If it would inherit 'constinit', 3129 // that's ill-formed. (Note that we do not apply this to the attribute 3130 // form). 3131 if (OldConstInit && OldConstInit->isConstinit()) 3132 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 3133 /*AttrBeforeInit=*/true); 3134 } else if (NewConstInit) { 3135 // This is the first time we've been told that this declaration should 3136 // have a constant initializer. If we already saw the initializing 3137 // declaration, this is too late. 3138 if (InitDecl && InitDecl != NewVD) { 3139 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 3140 /*AttrBeforeInit=*/false); 3141 NewVD->dropAttr<ConstInitAttr>(); 3142 } 3143 } 3144 } 3145 3146 // Attributes declared post-definition are currently ignored. 3147 checkNewAttributesAfterDef(*this, New, Old); 3148 3149 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 3150 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 3151 if (!OldA->isEquivalent(NewA)) { 3152 // This redeclaration changes __asm__ label. 3153 Diag(New->getLocation(), diag::err_different_asm_label); 3154 Diag(OldA->getLocation(), diag::note_previous_declaration); 3155 } 3156 } else if (Old->isUsed()) { 3157 // This redeclaration adds an __asm__ label to a declaration that has 3158 // already been ODR-used. 3159 Diag(New->getLocation(), diag::err_late_asm_label_name) 3160 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 3161 } 3162 } 3163 3164 // Re-declaration cannot add abi_tag's. 3165 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 3166 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 3167 for (const auto &NewTag : NewAbiTagAttr->tags()) { 3168 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { 3169 Diag(NewAbiTagAttr->getLocation(), 3170 diag::err_new_abi_tag_on_redeclaration) 3171 << NewTag; 3172 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 3173 } 3174 } 3175 } else { 3176 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 3177 Diag(Old->getLocation(), diag::note_previous_declaration); 3178 } 3179 } 3180 3181 // This redeclaration adds a section attribute. 3182 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 3183 if (auto *VD = dyn_cast<VarDecl>(New)) { 3184 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 3185 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 3186 Diag(Old->getLocation(), diag::note_previous_declaration); 3187 } 3188 } 3189 } 3190 3191 // Redeclaration adds code-seg attribute. 3192 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 3193 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 3194 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 3195 Diag(New->getLocation(), diag::warn_mismatched_section) 3196 << 0 /*codeseg*/; 3197 Diag(Old->getLocation(), diag::note_previous_declaration); 3198 } 3199 3200 if (!Old->hasAttrs()) 3201 return; 3202 3203 bool foundAny = New->hasAttrs(); 3204 3205 // Ensure that any moving of objects within the allocated map is done before 3206 // we process them. 3207 if (!foundAny) New->setAttrs(AttrVec()); 3208 3209 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3210 // Ignore deprecated/unavailable/availability attributes if requested. 3211 AvailabilityMergeKind LocalAMK = AMK_None; 3212 if (isa<DeprecatedAttr>(I) || 3213 isa<UnavailableAttr>(I) || 3214 isa<AvailabilityAttr>(I)) { 3215 switch (AMK) { 3216 case AMK_None: 3217 continue; 3218 3219 case AMK_Redeclaration: 3220 case AMK_Override: 3221 case AMK_ProtocolImplementation: 3222 case AMK_OptionalProtocolImplementation: 3223 LocalAMK = AMK; 3224 break; 3225 } 3226 } 3227 3228 // Already handled. 3229 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3230 continue; 3231 3232 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3233 foundAny = true; 3234 } 3235 3236 if (mergeAlignedAttrs(*this, New, Old)) 3237 foundAny = true; 3238 3239 if (!foundAny) New->dropAttrs(); 3240 } 3241 3242 // Returns the number of added attributes. 3243 template <class T> 3244 static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From, 3245 Sema &S) { 3246 unsigned found = 0; 3247 for (const auto *I : From->specific_attrs<T>()) { 3248 if (!DeclHasAttr(To, I)) { 3249 T *newAttr = cast<T>(I->clone(S.Context)); 3250 newAttr->setInherited(true); 3251 To->addAttr(newAttr); 3252 ++found; 3253 } 3254 } 3255 return found; 3256 } 3257 3258 template <class F> 3259 static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From, 3260 F &&propagator) { 3261 if (!From->hasAttrs()) { 3262 return; 3263 } 3264 3265 bool foundAny = To->hasAttrs(); 3266 3267 // Ensure that any moving of objects within the allocated map is 3268 // done before we process them. 3269 if (!foundAny) 3270 To->setAttrs(AttrVec()); 3271 3272 foundAny |= std::forward<F>(propagator)(To, From) != 0; 3273 3274 if (!foundAny) 3275 To->dropAttrs(); 3276 } 3277 3278 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3279 /// to the new one. 3280 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3281 const ParmVarDecl *oldDecl, 3282 Sema &S) { 3283 // C++11 [dcl.attr.depend]p2: 3284 // The first declaration of a function shall specify the 3285 // carries_dependency attribute for its declarator-id if any declaration 3286 // of the function specifies the carries_dependency attribute. 3287 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3288 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3289 S.Diag(CDA->getLocation(), 3290 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3291 // Find the first declaration of the parameter. 3292 // FIXME: Should we build redeclaration chains for function parameters? 3293 const FunctionDecl *FirstFD = 3294 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3295 const ParmVarDecl *FirstVD = 3296 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3297 S.Diag(FirstVD->getLocation(), 3298 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3299 } 3300 3301 propagateAttributes( 3302 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) { 3303 unsigned found = 0; 3304 found += propagateAttribute<InheritableParamAttr>(To, From, S); 3305 // Propagate the lifetimebound attribute from parameters to the 3306 // most recent declaration. Note that this doesn't include the implicit 3307 // 'this' parameter, as the attribute is applied to the function type in 3308 // that case. 3309 found += propagateAttribute<LifetimeBoundAttr>(To, From, S); 3310 return found; 3311 }); 3312 } 3313 3314 static bool EquivalentArrayTypes(QualType Old, QualType New, 3315 const ASTContext &Ctx) { 3316 3317 auto NoSizeInfo = [&Ctx](QualType Ty) { 3318 if (Ty->isIncompleteArrayType() || Ty->isPointerType()) 3319 return true; 3320 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty)) 3321 return VAT->getSizeModifier() == ArraySizeModifier::Star; 3322 return false; 3323 }; 3324 3325 // `type[]` is equivalent to `type *` and `type[*]`. 3326 if (NoSizeInfo(Old) && NoSizeInfo(New)) 3327 return true; 3328 3329 // Don't try to compare VLA sizes, unless one of them has the star modifier. 3330 if (Old->isVariableArrayType() && New->isVariableArrayType()) { 3331 const auto *OldVAT = Ctx.getAsVariableArrayType(Old); 3332 const auto *NewVAT = Ctx.getAsVariableArrayType(New); 3333 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^ 3334 (NewVAT->getSizeModifier() == ArraySizeModifier::Star)) 3335 return false; 3336 return true; 3337 } 3338 3339 // Only compare size, ignore Size modifiers and CVR. 3340 if (Old->isConstantArrayType() && New->isConstantArrayType()) { 3341 return Ctx.getAsConstantArrayType(Old)->getSize() == 3342 Ctx.getAsConstantArrayType(New)->getSize(); 3343 } 3344 3345 // Don't try to compare dependent sized array 3346 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) { 3347 return true; 3348 } 3349 3350 return Old == New; 3351 } 3352 3353 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3354 const ParmVarDecl *OldParam, 3355 Sema &S) { 3356 if (auto Oldnullability = OldParam->getType()->getNullability()) { 3357 if (auto Newnullability = NewParam->getType()->getNullability()) { 3358 if (*Oldnullability != *Newnullability) { 3359 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3360 << DiagNullabilityKind( 3361 *Newnullability, 3362 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3363 != 0)) 3364 << DiagNullabilityKind( 3365 *Oldnullability, 3366 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3367 != 0)); 3368 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3369 } 3370 } else { 3371 QualType NewT = NewParam->getType(); 3372 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT); 3373 NewParam->setType(NewT); 3374 } 3375 } 3376 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType()); 3377 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType()); 3378 if (OldParamDT && NewParamDT && 3379 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) { 3380 QualType OldParamOT = OldParamDT->getOriginalType(); 3381 QualType NewParamOT = NewParamDT->getOriginalType(); 3382 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) { 3383 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form) 3384 << NewParam << NewParamOT; 3385 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as) 3386 << OldParamOT; 3387 } 3388 } 3389 } 3390 3391 namespace { 3392 3393 /// Used in MergeFunctionDecl to keep track of function parameters in 3394 /// C. 3395 struct GNUCompatibleParamWarning { 3396 ParmVarDecl *OldParm; 3397 ParmVarDecl *NewParm; 3398 QualType PromotedType; 3399 }; 3400 3401 } // end anonymous namespace 3402 3403 // Determine whether the previous declaration was a definition, implicit 3404 // declaration, or a declaration. 3405 template <typename T> 3406 static std::pair<diag::kind, SourceLocation> 3407 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3408 diag::kind PrevDiag; 3409 SourceLocation OldLocation = Old->getLocation(); 3410 if (Old->isThisDeclarationADefinition()) 3411 PrevDiag = diag::note_previous_definition; 3412 else if (Old->isImplicit()) { 3413 PrevDiag = diag::note_previous_implicit_declaration; 3414 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) { 3415 if (FD->getBuiltinID()) 3416 PrevDiag = diag::note_previous_builtin_declaration; 3417 } 3418 if (OldLocation.isInvalid()) 3419 OldLocation = New->getLocation(); 3420 } else 3421 PrevDiag = diag::note_previous_declaration; 3422 return std::make_pair(PrevDiag, OldLocation); 3423 } 3424 3425 /// canRedefineFunction - checks if a function can be redefined. Currently, 3426 /// only extern inline functions can be redefined, and even then only in 3427 /// GNU89 mode. 3428 static bool canRedefineFunction(const FunctionDecl *FD, 3429 const LangOptions& LangOpts) { 3430 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3431 !LangOpts.CPlusPlus && 3432 FD->isInlineSpecified() && 3433 FD->getStorageClass() == SC_Extern); 3434 } 3435 3436 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3437 const AttributedType *AT = T->getAs<AttributedType>(); 3438 while (AT && !AT->isCallingConv()) 3439 AT = AT->getModifiedType()->getAs<AttributedType>(); 3440 return AT; 3441 } 3442 3443 template <typename T> 3444 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3445 const DeclContext *DC = Old->getDeclContext(); 3446 if (DC->isRecord()) 3447 return false; 3448 3449 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3450 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3451 return true; 3452 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3453 return true; 3454 return false; 3455 } 3456 3457 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3458 static bool isExternC(VarTemplateDecl *) { return false; } 3459 static bool isExternC(FunctionTemplateDecl *) { return false; } 3460 3461 /// Check whether a redeclaration of an entity introduced by a 3462 /// using-declaration is valid, given that we know it's not an overload 3463 /// (nor a hidden tag declaration). 3464 template<typename ExpectedDecl> 3465 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3466 ExpectedDecl *New) { 3467 // C++11 [basic.scope.declarative]p4: 3468 // Given a set of declarations in a single declarative region, each of 3469 // which specifies the same unqualified name, 3470 // -- they shall all refer to the same entity, or all refer to functions 3471 // and function templates; or 3472 // -- exactly one declaration shall declare a class name or enumeration 3473 // name that is not a typedef name and the other declarations shall all 3474 // refer to the same variable or enumerator, or all refer to functions 3475 // and function templates; in this case the class name or enumeration 3476 // name is hidden (3.3.10). 3477 3478 // C++11 [namespace.udecl]p14: 3479 // If a function declaration in namespace scope or block scope has the 3480 // same name and the same parameter-type-list as a function introduced 3481 // by a using-declaration, and the declarations do not declare the same 3482 // function, the program is ill-formed. 3483 3484 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3485 if (Old && 3486 !Old->getDeclContext()->getRedeclContext()->Equals( 3487 New->getDeclContext()->getRedeclContext()) && 3488 !(isExternC(Old) && isExternC(New))) 3489 Old = nullptr; 3490 3491 if (!Old) { 3492 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3493 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3494 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3495 return true; 3496 } 3497 return false; 3498 } 3499 3500 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3501 const FunctionDecl *B) { 3502 assert(A->getNumParams() == B->getNumParams()); 3503 3504 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3505 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3506 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3507 if (AttrA == AttrB) 3508 return true; 3509 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3510 AttrA->isDynamic() == AttrB->isDynamic(); 3511 }; 3512 3513 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3514 } 3515 3516 /// If necessary, adjust the semantic declaration context for a qualified 3517 /// declaration to name the correct inline namespace within the qualifier. 3518 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3519 DeclaratorDecl *OldD) { 3520 // The only case where we need to update the DeclContext is when 3521 // redeclaration lookup for a qualified name finds a declaration 3522 // in an inline namespace within the context named by the qualifier: 3523 // 3524 // inline namespace N { int f(); } 3525 // int ::f(); // Sema DC needs adjusting from :: to N::. 3526 // 3527 // For unqualified declarations, the semantic context *can* change 3528 // along the redeclaration chain (for local extern declarations, 3529 // extern "C" declarations, and friend declarations in particular). 3530 if (!NewD->getQualifier()) 3531 return; 3532 3533 // NewD is probably already in the right context. 3534 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3535 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3536 if (NamedDC->Equals(SemaDC)) 3537 return; 3538 3539 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3540 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3541 "unexpected context for redeclaration"); 3542 3543 auto *LexDC = NewD->getLexicalDeclContext(); 3544 auto FixSemaDC = [=](NamedDecl *D) { 3545 if (!D) 3546 return; 3547 D->setDeclContext(SemaDC); 3548 D->setLexicalDeclContext(LexDC); 3549 }; 3550 3551 FixSemaDC(NewD); 3552 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3553 FixSemaDC(FD->getDescribedFunctionTemplate()); 3554 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3555 FixSemaDC(VD->getDescribedVarTemplate()); 3556 } 3557 3558 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S, 3559 bool MergeTypeWithOld, bool NewDeclIsDefn) { 3560 // Verify the old decl was also a function. 3561 FunctionDecl *Old = OldD->getAsFunction(); 3562 if (!Old) { 3563 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3564 if (New->getFriendObjectKind()) { 3565 Diag(New->getLocation(), diag::err_using_decl_friend); 3566 Diag(Shadow->getTargetDecl()->getLocation(), 3567 diag::note_using_decl_target); 3568 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3569 << 0; 3570 return true; 3571 } 3572 3573 // Check whether the two declarations might declare the same function or 3574 // function template. 3575 if (FunctionTemplateDecl *NewTemplate = 3576 New->getDescribedFunctionTemplate()) { 3577 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3578 NewTemplate)) 3579 return true; 3580 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3581 ->getAsFunction(); 3582 } else { 3583 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3584 return true; 3585 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3586 } 3587 } else { 3588 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3589 << New->getDeclName(); 3590 notePreviousDefinition(OldD, New->getLocation()); 3591 return true; 3592 } 3593 } 3594 3595 // If the old declaration was found in an inline namespace and the new 3596 // declaration was qualified, update the DeclContext to match. 3597 adjustDeclContextForDeclaratorDecl(New, Old); 3598 3599 // If the old declaration is invalid, just give up here. 3600 if (Old->isInvalidDecl()) 3601 return true; 3602 3603 // Disallow redeclaration of some builtins. 3604 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3605 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3606 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3607 << Old << Old->getType(); 3608 return true; 3609 } 3610 3611 diag::kind PrevDiag; 3612 SourceLocation OldLocation; 3613 std::tie(PrevDiag, OldLocation) = 3614 getNoteDiagForInvalidRedeclaration(Old, New); 3615 3616 // Don't complain about this if we're in GNU89 mode and the old function 3617 // is an extern inline function. 3618 // Don't complain about specializations. They are not supposed to have 3619 // storage classes. 3620 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3621 New->getStorageClass() == SC_Static && 3622 Old->hasExternalFormalLinkage() && 3623 !New->getTemplateSpecializationInfo() && 3624 !canRedefineFunction(Old, getLangOpts())) { 3625 if (getLangOpts().MicrosoftExt) { 3626 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3627 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3628 } else { 3629 Diag(New->getLocation(), diag::err_static_non_static) << New; 3630 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3631 return true; 3632 } 3633 } 3634 3635 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3636 if (!Old->hasAttr<InternalLinkageAttr>()) { 3637 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3638 << ILA; 3639 Diag(Old->getLocation(), diag::note_previous_declaration); 3640 New->dropAttr<InternalLinkageAttr>(); 3641 } 3642 3643 if (auto *EA = New->getAttr<ErrorAttr>()) { 3644 if (!Old->hasAttr<ErrorAttr>()) { 3645 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3646 Diag(Old->getLocation(), diag::note_previous_declaration); 3647 New->dropAttr<ErrorAttr>(); 3648 } 3649 } 3650 3651 if (CheckRedeclarationInModule(New, Old)) 3652 return true; 3653 3654 if (!getLangOpts().CPlusPlus) { 3655 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3656 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3657 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3658 << New << OldOvl; 3659 3660 // Try our best to find a decl that actually has the overloadable 3661 // attribute for the note. In most cases (e.g. programs with only one 3662 // broken declaration/definition), this won't matter. 3663 // 3664 // FIXME: We could do this if we juggled some extra state in 3665 // OverloadableAttr, rather than just removing it. 3666 const Decl *DiagOld = Old; 3667 if (OldOvl) { 3668 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3669 const auto *A = D->getAttr<OverloadableAttr>(); 3670 return A && !A->isImplicit(); 3671 }); 3672 // If we've implicitly added *all* of the overloadable attrs to this 3673 // chain, emitting a "previous redecl" note is pointless. 3674 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3675 } 3676 3677 if (DiagOld) 3678 Diag(DiagOld->getLocation(), 3679 diag::note_attribute_overloadable_prev_overload) 3680 << OldOvl; 3681 3682 if (OldOvl) 3683 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3684 else 3685 New->dropAttr<OverloadableAttr>(); 3686 } 3687 } 3688 3689 // It is not permitted to redeclare an SME function with different SME 3690 // attributes. 3691 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) { 3692 Diag(New->getLocation(), diag::err_sme_attr_mismatch) 3693 << New->getType() << Old->getType(); 3694 Diag(OldLocation, diag::note_previous_declaration); 3695 return true; 3696 } 3697 3698 // If a function is first declared with a calling convention, but is later 3699 // declared or defined without one, all following decls assume the calling 3700 // convention of the first. 3701 // 3702 // It's OK if a function is first declared without a calling convention, 3703 // but is later declared or defined with the default calling convention. 3704 // 3705 // To test if either decl has an explicit calling convention, we look for 3706 // AttributedType sugar nodes on the type as written. If they are missing or 3707 // were canonicalized away, we assume the calling convention was implicit. 3708 // 3709 // Note also that we DO NOT return at this point, because we still have 3710 // other tests to run. 3711 QualType OldQType = Context.getCanonicalType(Old->getType()); 3712 QualType NewQType = Context.getCanonicalType(New->getType()); 3713 const FunctionType *OldType = cast<FunctionType>(OldQType); 3714 const FunctionType *NewType = cast<FunctionType>(NewQType); 3715 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3716 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3717 bool RequiresAdjustment = false; 3718 3719 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3720 FunctionDecl *First = Old->getFirstDecl(); 3721 const FunctionType *FT = 3722 First->getType().getCanonicalType()->castAs<FunctionType>(); 3723 FunctionType::ExtInfo FI = FT->getExtInfo(); 3724 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3725 if (!NewCCExplicit) { 3726 // Inherit the CC from the previous declaration if it was specified 3727 // there but not here. 3728 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3729 RequiresAdjustment = true; 3730 } else if (Old->getBuiltinID()) { 3731 // Builtin attribute isn't propagated to the new one yet at this point, 3732 // so we check if the old one is a builtin. 3733 3734 // Calling Conventions on a Builtin aren't really useful and setting a 3735 // default calling convention and cdecl'ing some builtin redeclarations is 3736 // common, so warn and ignore the calling convention on the redeclaration. 3737 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3738 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3739 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3740 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3741 RequiresAdjustment = true; 3742 } else { 3743 // Calling conventions aren't compatible, so complain. 3744 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3745 Diag(New->getLocation(), diag::err_cconv_change) 3746 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3747 << !FirstCCExplicit 3748 << (!FirstCCExplicit ? "" : 3749 FunctionType::getNameForCallConv(FI.getCC())); 3750 3751 // Put the note on the first decl, since it is the one that matters. 3752 Diag(First->getLocation(), diag::note_previous_declaration); 3753 return true; 3754 } 3755 } 3756 3757 // FIXME: diagnose the other way around? 3758 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3759 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3760 RequiresAdjustment = true; 3761 } 3762 3763 // Merge regparm attribute. 3764 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3765 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3766 if (NewTypeInfo.getHasRegParm()) { 3767 Diag(New->getLocation(), diag::err_regparm_mismatch) 3768 << NewType->getRegParmType() 3769 << OldType->getRegParmType(); 3770 Diag(OldLocation, diag::note_previous_declaration); 3771 return true; 3772 } 3773 3774 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3775 RequiresAdjustment = true; 3776 } 3777 3778 // Merge ns_returns_retained attribute. 3779 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3780 if (NewTypeInfo.getProducesResult()) { 3781 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3782 << "'ns_returns_retained'"; 3783 Diag(OldLocation, diag::note_previous_declaration); 3784 return true; 3785 } 3786 3787 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3788 RequiresAdjustment = true; 3789 } 3790 3791 if (OldTypeInfo.getNoCallerSavedRegs() != 3792 NewTypeInfo.getNoCallerSavedRegs()) { 3793 if (NewTypeInfo.getNoCallerSavedRegs()) { 3794 AnyX86NoCallerSavedRegistersAttr *Attr = 3795 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3796 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3797 Diag(OldLocation, diag::note_previous_declaration); 3798 return true; 3799 } 3800 3801 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3802 RequiresAdjustment = true; 3803 } 3804 3805 if (RequiresAdjustment) { 3806 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3807 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3808 New->setType(QualType(AdjustedType, 0)); 3809 NewQType = Context.getCanonicalType(New->getType()); 3810 } 3811 3812 // If this redeclaration makes the function inline, we may need to add it to 3813 // UndefinedButUsed. 3814 if (!Old->isInlined() && New->isInlined() && 3815 !New->hasAttr<GNUInlineAttr>() && 3816 !getLangOpts().GNUInline && 3817 Old->isUsed(false) && 3818 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3819 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3820 SourceLocation())); 3821 3822 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3823 // about it. 3824 if (New->hasAttr<GNUInlineAttr>() && 3825 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3826 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3827 } 3828 3829 // If pass_object_size params don't match up perfectly, this isn't a valid 3830 // redeclaration. 3831 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3832 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3833 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3834 << New->getDeclName(); 3835 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3836 return true; 3837 } 3838 3839 QualType OldQTypeForComparison = OldQType; 3840 if (Context.hasAnyFunctionEffects()) { 3841 const auto OldFX = Old->getFunctionEffects(); 3842 const auto NewFX = New->getFunctionEffects(); 3843 if (OldFX != NewFX) { 3844 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX); 3845 for (const auto &Diff : Diffs) { 3846 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) { 3847 Diag(New->getLocation(), 3848 diag::warn_mismatched_func_effect_redeclaration) 3849 << Diff.effectName(); 3850 Diag(Old->getLocation(), diag::note_previous_declaration); 3851 } 3852 } 3853 // Following a warning, we could skip merging effects from the previous 3854 // declaration, but that would trigger an additional "conflicting types" 3855 // error. 3856 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) { 3857 FunctionEffectSet::Conflicts MergeErrs; 3858 FunctionEffectSet MergedFX = 3859 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs); 3860 if (!MergeErrs.empty()) 3861 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(), 3862 Old->getLocation()); 3863 3864 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo(); 3865 EPI.FunctionEffects = FunctionEffectsRef(MergedFX); 3866 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(), 3867 NewFPT->getParamTypes(), EPI); 3868 3869 New->setType(ModQT); 3870 NewQType = New->getType(); 3871 3872 // Revise OldQTForComparison to include the merged effects, 3873 // so as not to fail due to differences later. 3874 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) { 3875 EPI = OldFPT->getExtProtoInfo(); 3876 EPI.FunctionEffects = FunctionEffectsRef(MergedFX); 3877 OldQTypeForComparison = Context.getFunctionType( 3878 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI); 3879 } 3880 if (OldFX.empty()) { 3881 // A redeclaration may add the attribute to a previously seen function 3882 // body which needs to be verified. 3883 maybeAddDeclWithEffects(Old, MergedFX); 3884 } 3885 } 3886 } 3887 } 3888 3889 if (getLangOpts().CPlusPlus) { 3890 OldQType = Context.getCanonicalType(Old->getType()); 3891 NewQType = Context.getCanonicalType(New->getType()); 3892 3893 // Go back to the type source info to compare the declared return types, 3894 // per C++1y [dcl.type.auto]p13: 3895 // Redeclarations or specializations of a function or function template 3896 // with a declared return type that uses a placeholder type shall also 3897 // use that placeholder, not a deduced type. 3898 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3899 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3900 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3901 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3902 OldDeclaredReturnType)) { 3903 QualType ResQT; 3904 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3905 OldDeclaredReturnType->isObjCObjectPointerType()) 3906 // FIXME: This does the wrong thing for a deduced return type. 3907 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3908 if (ResQT.isNull()) { 3909 if (New->isCXXClassMember() && New->isOutOfLine()) 3910 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3911 << New << New->getReturnTypeSourceRange(); 3912 else if (Old->isExternC() && New->isExternC() && 3913 !Old->hasAttr<OverloadableAttr>() && 3914 !New->hasAttr<OverloadableAttr>()) 3915 Diag(New->getLocation(), diag::err_conflicting_types) << New; 3916 else 3917 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3918 << New->getReturnTypeSourceRange(); 3919 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3920 << Old->getReturnTypeSourceRange(); 3921 return true; 3922 } 3923 else 3924 NewQType = ResQT; 3925 } 3926 3927 QualType OldReturnType = OldType->getReturnType(); 3928 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3929 if (OldReturnType != NewReturnType) { 3930 // If this function has a deduced return type and has already been 3931 // defined, copy the deduced value from the old declaration. 3932 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3933 if (OldAT && OldAT->isDeduced()) { 3934 QualType DT = OldAT->getDeducedType(); 3935 if (DT.isNull()) { 3936 New->setType(SubstAutoTypeDependent(New->getType())); 3937 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); 3938 } else { 3939 New->setType(SubstAutoType(New->getType(), DT)); 3940 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); 3941 } 3942 } 3943 } 3944 3945 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3946 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3947 if (OldMethod && NewMethod) { 3948 // Preserve triviality. 3949 NewMethod->setTrivial(OldMethod->isTrivial()); 3950 3951 // MSVC allows explicit template specialization at class scope: 3952 // 2 CXXMethodDecls referring to the same function will be injected. 3953 // We don't want a redeclaration error. 3954 bool IsClassScopeExplicitSpecialization = 3955 OldMethod->isFunctionTemplateSpecialization() && 3956 NewMethod->isFunctionTemplateSpecialization(); 3957 bool isFriend = NewMethod->getFriendObjectKind(); 3958 3959 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3960 !IsClassScopeExplicitSpecialization) { 3961 // -- Member function declarations with the same name and the 3962 // same parameter types cannot be overloaded if any of them 3963 // is a static member function declaration. 3964 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3965 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3966 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3967 return true; 3968 } 3969 3970 // C++ [class.mem]p1: 3971 // [...] A member shall not be declared twice in the 3972 // member-specification, except that a nested class or member 3973 // class template can be declared and then later defined. 3974 if (!inTemplateInstantiation()) { 3975 unsigned NewDiag; 3976 if (isa<CXXConstructorDecl>(OldMethod)) 3977 NewDiag = diag::err_constructor_redeclared; 3978 else if (isa<CXXDestructorDecl>(NewMethod)) 3979 NewDiag = diag::err_destructor_redeclared; 3980 else if (isa<CXXConversionDecl>(NewMethod)) 3981 NewDiag = diag::err_conv_function_redeclared; 3982 else 3983 NewDiag = diag::err_member_redeclared; 3984 3985 Diag(New->getLocation(), NewDiag); 3986 } else { 3987 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3988 << New << New->getType(); 3989 } 3990 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3991 return true; 3992 3993 // Complain if this is an explicit declaration of a special 3994 // member that was initially declared implicitly. 3995 // 3996 // As an exception, it's okay to befriend such methods in order 3997 // to permit the implicit constructor/destructor/operator calls. 3998 } else if (OldMethod->isImplicit()) { 3999 if (isFriend) { 4000 NewMethod->setImplicit(); 4001 } else { 4002 Diag(NewMethod->getLocation(), 4003 diag::err_definition_of_implicitly_declared_member) 4004 << New << llvm::to_underlying(getSpecialMember(OldMethod)); 4005 return true; 4006 } 4007 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 4008 Diag(NewMethod->getLocation(), 4009 diag::err_definition_of_explicitly_defaulted_member) 4010 << llvm::to_underlying(getSpecialMember(OldMethod)); 4011 return true; 4012 } 4013 } 4014 4015 // C++1z [over.load]p2 4016 // Certain function declarations cannot be overloaded: 4017 // -- Function declarations that differ only in the return type, 4018 // the exception specification, or both cannot be overloaded. 4019 4020 // Check the exception specifications match. This may recompute the type of 4021 // both Old and New if it resolved exception specifications, so grab the 4022 // types again after this. Because this updates the type, we do this before 4023 // any of the other checks below, which may update the "de facto" NewQType 4024 // but do not necessarily update the type of New. 4025 if (CheckEquivalentExceptionSpec(Old, New)) 4026 return true; 4027 4028 // C++11 [dcl.attr.noreturn]p1: 4029 // The first declaration of a function shall specify the noreturn 4030 // attribute if any declaration of that function specifies the noreturn 4031 // attribute. 4032 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 4033 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 4034 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 4035 << NRA; 4036 Diag(Old->getLocation(), diag::note_previous_declaration); 4037 } 4038 4039 // C++11 [dcl.attr.depend]p2: 4040 // The first declaration of a function shall specify the 4041 // carries_dependency attribute for its declarator-id if any declaration 4042 // of the function specifies the carries_dependency attribute. 4043 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 4044 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 4045 Diag(CDA->getLocation(), 4046 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 4047 Diag(Old->getFirstDecl()->getLocation(), 4048 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 4049 } 4050 4051 // (C++98 8.3.5p3): 4052 // All declarations for a function shall agree exactly in both the 4053 // return type and the parameter-type-list. 4054 // We also want to respect all the extended bits except noreturn. 4055 4056 // noreturn should now match unless the old type info didn't have it. 4057 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 4058 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>(); 4059 const FunctionType *OldTypeForComparison 4060 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 4061 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 4062 assert(OldQTypeForComparison.isCanonical()); 4063 } 4064 4065 if (haveIncompatibleLanguageLinkages(Old, New)) { 4066 // As a special case, retain the language linkage from previous 4067 // declarations of a friend function as an extension. 4068 // 4069 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 4070 // and is useful because there's otherwise no way to specify language 4071 // linkage within class scope. 4072 // 4073 // Check cautiously as the friend object kind isn't yet complete. 4074 if (New->getFriendObjectKind() != Decl::FOK_None) { 4075 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 4076 Diag(OldLocation, PrevDiag); 4077 } else { 4078 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4079 Diag(OldLocation, PrevDiag); 4080 return true; 4081 } 4082 } 4083 4084 // HLSL check parameters for matching ABI specifications. 4085 if (getLangOpts().HLSL) { 4086 if (HLSL().CheckCompatibleParameterABI(New, Old)) 4087 return true; 4088 4089 // If no errors are generated when checking parameter ABIs we can check if 4090 // the two declarations have the same type ignoring the ABIs and if so, 4091 // the declarations can be merged. This case for merging is only valid in 4092 // HLSL because there are no valid cases of merging mismatched parameter 4093 // ABIs except the HLSL implicit in and explicit in. 4094 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison, 4095 NewQType)) 4096 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4097 // Fall through for conflicting redeclarations and redefinitions. 4098 } 4099 4100 // If the function types are compatible, merge the declarations. Ignore the 4101 // exception specifier because it was already checked above in 4102 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 4103 // about incompatible types under -fms-compatibility. 4104 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 4105 NewQType)) 4106 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4107 4108 // If the types are imprecise (due to dependent constructs in friends or 4109 // local extern declarations), it's OK if they differ. We'll check again 4110 // during instantiation. 4111 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 4112 return false; 4113 4114 // Fall through for conflicting redeclarations and redefinitions. 4115 } 4116 4117 // C: Function types need to be compatible, not identical. This handles 4118 // duplicate function decls like "void f(int); void f(enum X);" properly. 4119 if (!getLangOpts().CPlusPlus) { 4120 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other 4121 // type is specified by a function definition that contains a (possibly 4122 // empty) identifier list, both shall agree in the number of parameters 4123 // and the type of each parameter shall be compatible with the type that 4124 // results from the application of default argument promotions to the 4125 // type of the corresponding identifier. ... 4126 // This cannot be handled by ASTContext::typesAreCompatible() because that 4127 // doesn't know whether the function type is for a definition or not when 4128 // eventually calling ASTContext::mergeFunctionTypes(). The only situation 4129 // we need to cover here is that the number of arguments agree as the 4130 // default argument promotion rules were already checked by 4131 // ASTContext::typesAreCompatible(). 4132 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn && 4133 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) { 4134 if (Old->hasInheritedPrototype()) 4135 Old = Old->getCanonicalDecl(); 4136 Diag(New->getLocation(), diag::err_conflicting_types) << New; 4137 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 4138 return true; 4139 } 4140 4141 // If we are merging two functions where only one of them has a prototype, 4142 // we may have enough information to decide to issue a diagnostic that the 4143 // function without a prototype will change behavior in C23. This handles 4144 // cases like: 4145 // void i(); void i(int j); 4146 // void i(int j); void i(); 4147 // void i(); void i(int j) {} 4148 // See ActOnFinishFunctionBody() for other cases of the behavior change 4149 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 4150 // type without a prototype. 4151 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() && 4152 !New->isImplicit() && !Old->isImplicit()) { 4153 const FunctionDecl *WithProto, *WithoutProto; 4154 if (New->hasWrittenPrototype()) { 4155 WithProto = New; 4156 WithoutProto = Old; 4157 } else { 4158 WithProto = Old; 4159 WithoutProto = New; 4160 } 4161 4162 if (WithProto->getNumParams() != 0) { 4163 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) { 4164 // The one without the prototype will be changing behavior in C23, so 4165 // warn about that one so long as it's a user-visible declaration. 4166 bool IsWithoutProtoADef = false, IsWithProtoADef = false; 4167 if (WithoutProto == New) 4168 IsWithoutProtoADef = NewDeclIsDefn; 4169 else 4170 IsWithProtoADef = NewDeclIsDefn; 4171 Diag(WithoutProto->getLocation(), 4172 diag::warn_non_prototype_changes_behavior) 4173 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1) 4174 << (WithoutProto == Old) << IsWithProtoADef; 4175 4176 // The reason the one without the prototype will be changing behavior 4177 // is because of the one with the prototype, so note that so long as 4178 // it's a user-visible declaration. There is one exception to this: 4179 // when the new declaration is a definition without a prototype, the 4180 // old declaration with a prototype is not the cause of the issue, 4181 // and that does not need to be noted because the one with a 4182 // prototype will not change behavior in C23. 4183 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() && 4184 !IsWithoutProtoADef) 4185 Diag(WithProto->getLocation(), diag::note_conflicting_prototype); 4186 } 4187 } 4188 } 4189 4190 if (Context.typesAreCompatible(OldQType, NewQType)) { 4191 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 4192 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 4193 const FunctionProtoType *OldProto = nullptr; 4194 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 4195 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 4196 // The old declaration provided a function prototype, but the 4197 // new declaration does not. Merge in the prototype. 4198 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 4199 NewQType = Context.getFunctionType(NewFuncType->getReturnType(), 4200 OldProto->getParamTypes(), 4201 OldProto->getExtProtoInfo()); 4202 New->setType(NewQType); 4203 New->setHasInheritedPrototype(); 4204 4205 // Synthesize parameters with the same types. 4206 SmallVector<ParmVarDecl *, 16> Params; 4207 for (const auto &ParamType : OldProto->param_types()) { 4208 ParmVarDecl *Param = ParmVarDecl::Create( 4209 Context, New, SourceLocation(), SourceLocation(), nullptr, 4210 ParamType, /*TInfo=*/nullptr, SC_None, nullptr); 4211 Param->setScopeInfo(0, Params.size()); 4212 Param->setImplicit(); 4213 Params.push_back(Param); 4214 } 4215 4216 New->setParams(Params); 4217 } 4218 4219 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4220 } 4221 } 4222 4223 // Check if the function types are compatible when pointer size address 4224 // spaces are ignored. 4225 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 4226 return false; 4227 4228 // GNU C permits a K&R definition to follow a prototype declaration 4229 // if the declared types of the parameters in the K&R definition 4230 // match the types in the prototype declaration, even when the 4231 // promoted types of the parameters from the K&R definition differ 4232 // from the types in the prototype. GCC then keeps the types from 4233 // the prototype. 4234 // 4235 // If a variadic prototype is followed by a non-variadic K&R definition, 4236 // the K&R definition becomes variadic. This is sort of an edge case, but 4237 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 4238 // C99 6.9.1p8. 4239 if (!getLangOpts().CPlusPlus && 4240 Old->hasPrototype() && !New->hasPrototype() && 4241 New->getType()->getAs<FunctionProtoType>() && 4242 Old->getNumParams() == New->getNumParams()) { 4243 SmallVector<QualType, 16> ArgTypes; 4244 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 4245 const FunctionProtoType *OldProto 4246 = Old->getType()->getAs<FunctionProtoType>(); 4247 const FunctionProtoType *NewProto 4248 = New->getType()->getAs<FunctionProtoType>(); 4249 4250 // Determine whether this is the GNU C extension. 4251 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 4252 NewProto->getReturnType()); 4253 bool LooseCompatible = !MergedReturn.isNull(); 4254 for (unsigned Idx = 0, End = Old->getNumParams(); 4255 LooseCompatible && Idx != End; ++Idx) { 4256 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 4257 ParmVarDecl *NewParm = New->getParamDecl(Idx); 4258 if (Context.typesAreCompatible(OldParm->getType(), 4259 NewProto->getParamType(Idx))) { 4260 ArgTypes.push_back(NewParm->getType()); 4261 } else if (Context.typesAreCompatible(OldParm->getType(), 4262 NewParm->getType(), 4263 /*CompareUnqualified=*/true)) { 4264 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 4265 NewProto->getParamType(Idx) }; 4266 Warnings.push_back(Warn); 4267 ArgTypes.push_back(NewParm->getType()); 4268 } else 4269 LooseCompatible = false; 4270 } 4271 4272 if (LooseCompatible) { 4273 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 4274 Diag(Warnings[Warn].NewParm->getLocation(), 4275 diag::ext_param_promoted_not_compatible_with_prototype) 4276 << Warnings[Warn].PromotedType 4277 << Warnings[Warn].OldParm->getType(); 4278 if (Warnings[Warn].OldParm->getLocation().isValid()) 4279 Diag(Warnings[Warn].OldParm->getLocation(), 4280 diag::note_previous_declaration); 4281 } 4282 4283 if (MergeTypeWithOld) 4284 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 4285 OldProto->getExtProtoInfo())); 4286 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4287 } 4288 4289 // Fall through to diagnose conflicting types. 4290 } 4291 4292 // A function that has already been declared has been redeclared or 4293 // defined with a different type; show an appropriate diagnostic. 4294 4295 // If the previous declaration was an implicitly-generated builtin 4296 // declaration, then at the very least we should use a specialized note. 4297 unsigned BuiltinID; 4298 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 4299 // If it's actually a library-defined builtin function like 'malloc' 4300 // or 'printf', just warn about the incompatible redeclaration. 4301 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 4302 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 4303 Diag(OldLocation, diag::note_previous_builtin_declaration) 4304 << Old << Old->getType(); 4305 return false; 4306 } 4307 4308 PrevDiag = diag::note_previous_builtin_declaration; 4309 } 4310 4311 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 4312 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4313 return true; 4314 } 4315 4316 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 4317 Scope *S, bool MergeTypeWithOld) { 4318 // Merge the attributes 4319 mergeDeclAttributes(New, Old); 4320 4321 // Merge "pure" flag. 4322 if (Old->isPureVirtual()) 4323 New->setIsPureVirtual(); 4324 4325 // Merge "used" flag. 4326 if (Old->getMostRecentDecl()->isUsed(false)) 4327 New->setIsUsed(); 4328 4329 // Merge attributes from the parameters. These can mismatch with K&R 4330 // declarations. 4331 if (New->getNumParams() == Old->getNumParams()) 4332 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 4333 ParmVarDecl *NewParam = New->getParamDecl(i); 4334 ParmVarDecl *OldParam = Old->getParamDecl(i); 4335 mergeParamDeclAttributes(NewParam, OldParam, *this); 4336 mergeParamDeclTypes(NewParam, OldParam, *this); 4337 } 4338 4339 if (getLangOpts().CPlusPlus) 4340 return MergeCXXFunctionDecl(New, Old, S); 4341 4342 // Merge the function types so the we get the composite types for the return 4343 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 4344 // was visible. 4345 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 4346 if (!Merged.isNull() && MergeTypeWithOld) 4347 New->setType(Merged); 4348 4349 return false; 4350 } 4351 4352 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 4353 ObjCMethodDecl *oldMethod) { 4354 // Merge the attributes, including deprecated/unavailable 4355 AvailabilityMergeKind MergeKind = 4356 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 4357 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 4358 : AMK_ProtocolImplementation) 4359 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 4360 : AMK_Override; 4361 4362 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 4363 4364 // Merge attributes from the parameters. 4365 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 4366 oe = oldMethod->param_end(); 4367 for (ObjCMethodDecl::param_iterator 4368 ni = newMethod->param_begin(), ne = newMethod->param_end(); 4369 ni != ne && oi != oe; ++ni, ++oi) 4370 mergeParamDeclAttributes(*ni, *oi, *this); 4371 4372 ObjC().CheckObjCMethodOverride(newMethod, oldMethod); 4373 } 4374 4375 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 4376 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 4377 4378 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 4379 ? diag::err_redefinition_different_type 4380 : diag::err_redeclaration_different_type) 4381 << New->getDeclName() << New->getType() << Old->getType(); 4382 4383 diag::kind PrevDiag; 4384 SourceLocation OldLocation; 4385 std::tie(PrevDiag, OldLocation) 4386 = getNoteDiagForInvalidRedeclaration(Old, New); 4387 S.Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4388 New->setInvalidDecl(); 4389 } 4390 4391 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 4392 bool MergeTypeWithOld) { 4393 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors()) 4394 return; 4395 4396 QualType MergedT; 4397 if (getLangOpts().CPlusPlus) { 4398 if (New->getType()->isUndeducedType()) { 4399 // We don't know what the new type is until the initializer is attached. 4400 return; 4401 } else if (Context.hasSameType(New->getType(), Old->getType())) { 4402 // These could still be something that needs exception specs checked. 4403 return MergeVarDeclExceptionSpecs(New, Old); 4404 } 4405 // C++ [basic.link]p10: 4406 // [...] the types specified by all declarations referring to a given 4407 // object or function shall be identical, except that declarations for an 4408 // array object can specify array types that differ by the presence or 4409 // absence of a major array bound (8.3.4). 4410 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4411 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4412 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4413 4414 // We are merging a variable declaration New into Old. If it has an array 4415 // bound, and that bound differs from Old's bound, we should diagnose the 4416 // mismatch. 4417 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4418 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4419 PrevVD = PrevVD->getPreviousDecl()) { 4420 QualType PrevVDTy = PrevVD->getType(); 4421 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4422 continue; 4423 4424 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4425 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4426 } 4427 } 4428 4429 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4430 if (Context.hasSameType(OldArray->getElementType(), 4431 NewArray->getElementType())) 4432 MergedT = New->getType(); 4433 } 4434 // FIXME: Check visibility. New is hidden but has a complete type. If New 4435 // has no array bound, it should not inherit one from Old, if Old is not 4436 // visible. 4437 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4438 if (Context.hasSameType(OldArray->getElementType(), 4439 NewArray->getElementType())) 4440 MergedT = Old->getType(); 4441 } 4442 } 4443 else if (New->getType()->isObjCObjectPointerType() && 4444 Old->getType()->isObjCObjectPointerType()) { 4445 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4446 Old->getType()); 4447 } 4448 } else { 4449 // C 6.2.7p2: 4450 // All declarations that refer to the same object or function shall have 4451 // compatible type. 4452 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4453 } 4454 if (MergedT.isNull()) { 4455 // It's OK if we couldn't merge types if either type is dependent, for a 4456 // block-scope variable. In other cases (static data members of class 4457 // templates, variable templates, ...), we require the types to be 4458 // equivalent. 4459 // FIXME: The C++ standard doesn't say anything about this. 4460 if ((New->getType()->isDependentType() || 4461 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4462 // If the old type was dependent, we can't merge with it, so the new type 4463 // becomes dependent for now. We'll reproduce the original type when we 4464 // instantiate the TypeSourceInfo for the variable. 4465 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4466 New->setType(Context.DependentTy); 4467 return; 4468 } 4469 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4470 } 4471 4472 // Don't actually update the type on the new declaration if the old 4473 // declaration was an extern declaration in a different scope. 4474 if (MergeTypeWithOld) 4475 New->setType(MergedT); 4476 } 4477 4478 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4479 LookupResult &Previous) { 4480 // C11 6.2.7p4: 4481 // For an identifier with internal or external linkage declared 4482 // in a scope in which a prior declaration of that identifier is 4483 // visible, if the prior declaration specifies internal or 4484 // external linkage, the type of the identifier at the later 4485 // declaration becomes the composite type. 4486 // 4487 // If the variable isn't visible, we do not merge with its type. 4488 if (Previous.isShadowed()) 4489 return false; 4490 4491 if (S.getLangOpts().CPlusPlus) { 4492 // C++11 [dcl.array]p3: 4493 // If there is a preceding declaration of the entity in the same 4494 // scope in which the bound was specified, an omitted array bound 4495 // is taken to be the same as in that earlier declaration. 4496 return NewVD->isPreviousDeclInSameBlockScope() || 4497 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4498 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4499 } else { 4500 // If the old declaration was function-local, don't merge with its 4501 // type unless we're in the same function. 4502 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4503 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4504 } 4505 } 4506 4507 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4508 // If the new decl is already invalid, don't do any other checking. 4509 if (New->isInvalidDecl()) 4510 return; 4511 4512 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4513 return; 4514 4515 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4516 4517 // Verify the old decl was also a variable or variable template. 4518 VarDecl *Old = nullptr; 4519 VarTemplateDecl *OldTemplate = nullptr; 4520 if (Previous.isSingleResult()) { 4521 if (NewTemplate) { 4522 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4523 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4524 4525 if (auto *Shadow = 4526 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4527 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4528 return New->setInvalidDecl(); 4529 } else { 4530 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4531 4532 if (auto *Shadow = 4533 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4534 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4535 return New->setInvalidDecl(); 4536 } 4537 } 4538 if (!Old) { 4539 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4540 << New->getDeclName(); 4541 notePreviousDefinition(Previous.getRepresentativeDecl(), 4542 New->getLocation()); 4543 return New->setInvalidDecl(); 4544 } 4545 4546 // If the old declaration was found in an inline namespace and the new 4547 // declaration was qualified, update the DeclContext to match. 4548 adjustDeclContextForDeclaratorDecl(New, Old); 4549 4550 // Ensure the template parameters are compatible. 4551 if (NewTemplate && 4552 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4553 OldTemplate->getTemplateParameters(), 4554 /*Complain=*/true, TPL_TemplateMatch)) 4555 return New->setInvalidDecl(); 4556 4557 // C++ [class.mem]p1: 4558 // A member shall not be declared twice in the member-specification [...] 4559 // 4560 // Here, we need only consider static data members. 4561 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4562 Diag(New->getLocation(), diag::err_duplicate_member) 4563 << New->getIdentifier(); 4564 Diag(Old->getLocation(), diag::note_previous_declaration); 4565 New->setInvalidDecl(); 4566 } 4567 4568 mergeDeclAttributes(New, Old); 4569 // Warn if an already-defined variable is made a weak_import in a subsequent 4570 // declaration 4571 if (New->hasAttr<WeakImportAttr>()) 4572 for (auto *D = Old; D; D = D->getPreviousDecl()) { 4573 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) { 4574 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4575 Diag(D->getLocation(), diag::note_previous_definition); 4576 // Remove weak_import attribute on new declaration. 4577 New->dropAttr<WeakImportAttr>(); 4578 break; 4579 } 4580 } 4581 4582 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4583 if (!Old->hasAttr<InternalLinkageAttr>()) { 4584 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4585 << ILA; 4586 Diag(Old->getLocation(), diag::note_previous_declaration); 4587 New->dropAttr<InternalLinkageAttr>(); 4588 } 4589 4590 // Merge the types. 4591 VarDecl *MostRecent = Old->getMostRecentDecl(); 4592 if (MostRecent != Old) { 4593 MergeVarDeclTypes(New, MostRecent, 4594 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4595 if (New->isInvalidDecl()) 4596 return; 4597 } 4598 4599 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4600 if (New->isInvalidDecl()) 4601 return; 4602 4603 diag::kind PrevDiag; 4604 SourceLocation OldLocation; 4605 std::tie(PrevDiag, OldLocation) = 4606 getNoteDiagForInvalidRedeclaration(Old, New); 4607 4608 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4609 if (New->getStorageClass() == SC_Static && 4610 !New->isStaticDataMember() && 4611 Old->hasExternalFormalLinkage()) { 4612 if (getLangOpts().MicrosoftExt) { 4613 Diag(New->getLocation(), diag::ext_static_non_static) 4614 << New->getDeclName(); 4615 Diag(OldLocation, PrevDiag); 4616 } else { 4617 Diag(New->getLocation(), diag::err_static_non_static) 4618 << New->getDeclName(); 4619 Diag(OldLocation, PrevDiag); 4620 return New->setInvalidDecl(); 4621 } 4622 } 4623 // C99 6.2.2p4: 4624 // For an identifier declared with the storage-class specifier 4625 // extern in a scope in which a prior declaration of that 4626 // identifier is visible,23) if the prior declaration specifies 4627 // internal or external linkage, the linkage of the identifier at 4628 // the later declaration is the same as the linkage specified at 4629 // the prior declaration. If no prior declaration is visible, or 4630 // if the prior declaration specifies no linkage, then the 4631 // identifier has external linkage. 4632 if (New->hasExternalStorage() && Old->hasLinkage()) 4633 /* Okay */; 4634 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4635 !New->isStaticDataMember() && 4636 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4637 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4638 Diag(OldLocation, PrevDiag); 4639 return New->setInvalidDecl(); 4640 } 4641 4642 // Check if extern is followed by non-extern and vice-versa. 4643 if (New->hasExternalStorage() && 4644 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4645 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4646 Diag(OldLocation, PrevDiag); 4647 return New->setInvalidDecl(); 4648 } 4649 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4650 !New->hasExternalStorage()) { 4651 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4652 Diag(OldLocation, PrevDiag); 4653 return New->setInvalidDecl(); 4654 } 4655 4656 if (CheckRedeclarationInModule(New, Old)) 4657 return; 4658 4659 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4660 4661 // FIXME: The test for external storage here seems wrong? We still 4662 // need to check for mismatches. 4663 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4664 // Don't complain about out-of-line definitions of static members. 4665 !(Old->getLexicalDeclContext()->isRecord() && 4666 !New->getLexicalDeclContext()->isRecord())) { 4667 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4668 Diag(OldLocation, PrevDiag); 4669 return New->setInvalidDecl(); 4670 } 4671 4672 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4673 if (VarDecl *Def = Old->getDefinition()) { 4674 // C++1z [dcl.fcn.spec]p4: 4675 // If the definition of a variable appears in a translation unit before 4676 // its first declaration as inline, the program is ill-formed. 4677 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4678 Diag(Def->getLocation(), diag::note_previous_definition); 4679 } 4680 } 4681 4682 // If this redeclaration makes the variable inline, we may need to add it to 4683 // UndefinedButUsed. 4684 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4685 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4686 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4687 SourceLocation())); 4688 4689 if (New->getTLSKind() != Old->getTLSKind()) { 4690 if (!Old->getTLSKind()) { 4691 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4692 Diag(OldLocation, PrevDiag); 4693 } else if (!New->getTLSKind()) { 4694 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4695 Diag(OldLocation, PrevDiag); 4696 } else { 4697 // Do not allow redeclaration to change the variable between requiring 4698 // static and dynamic initialization. 4699 // FIXME: GCC allows this, but uses the TLS keyword on the first 4700 // declaration to determine the kind. Do we need to be compatible here? 4701 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4702 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4703 Diag(OldLocation, PrevDiag); 4704 } 4705 } 4706 4707 // C++ doesn't have tentative definitions, so go right ahead and check here. 4708 if (getLangOpts().CPlusPlus) { 4709 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4710 Old->getCanonicalDecl()->isConstexpr()) { 4711 // This definition won't be a definition any more once it's been merged. 4712 Diag(New->getLocation(), 4713 diag::warn_deprecated_redundant_constexpr_static_def); 4714 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) { 4715 VarDecl *Def = Old->getDefinition(); 4716 if (Def && checkVarDeclRedefinition(Def, New)) 4717 return; 4718 } 4719 } 4720 4721 if (haveIncompatibleLanguageLinkages(Old, New)) { 4722 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4723 Diag(OldLocation, PrevDiag); 4724 New->setInvalidDecl(); 4725 return; 4726 } 4727 4728 // Merge "used" flag. 4729 if (Old->getMostRecentDecl()->isUsed(false)) 4730 New->setIsUsed(); 4731 4732 // Keep a chain of previous declarations. 4733 New->setPreviousDecl(Old); 4734 if (NewTemplate) 4735 NewTemplate->setPreviousDecl(OldTemplate); 4736 4737 // Inherit access appropriately. 4738 New->setAccess(Old->getAccess()); 4739 if (NewTemplate) 4740 NewTemplate->setAccess(New->getAccess()); 4741 4742 if (Old->isInline()) 4743 New->setImplicitlyInline(); 4744 } 4745 4746 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4747 SourceManager &SrcMgr = getSourceManager(); 4748 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4749 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4750 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4751 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first); 4752 auto &HSI = PP.getHeaderSearchInfo(); 4753 StringRef HdrFilename = 4754 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4755 4756 auto noteFromModuleOrInclude = [&](Module *Mod, 4757 SourceLocation IncLoc) -> bool { 4758 // Redefinition errors with modules are common with non modular mapped 4759 // headers, example: a non-modular header H in module A that also gets 4760 // included directly in a TU. Pointing twice to the same header/definition 4761 // is confusing, try to get better diagnostics when modules is on. 4762 if (IncLoc.isValid()) { 4763 if (Mod) { 4764 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4765 << HdrFilename.str() << Mod->getFullModuleName(); 4766 if (!Mod->DefinitionLoc.isInvalid()) 4767 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4768 << Mod->getFullModuleName(); 4769 } else { 4770 Diag(IncLoc, diag::note_redefinition_include_same_file) 4771 << HdrFilename.str(); 4772 } 4773 return true; 4774 } 4775 4776 return false; 4777 }; 4778 4779 // Is it the same file and same offset? Provide more information on why 4780 // this leads to a redefinition error. 4781 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4782 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4783 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4784 bool EmittedDiag = 4785 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4786 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4787 4788 // If the header has no guards, emit a note suggesting one. 4789 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld)) 4790 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4791 4792 if (EmittedDiag) 4793 return; 4794 } 4795 4796 // Redefinition coming from different files or couldn't do better above. 4797 if (Old->getLocation().isValid()) 4798 Diag(Old->getLocation(), diag::note_previous_definition); 4799 } 4800 4801 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4802 if (!hasVisibleDefinition(Old) && 4803 (New->getFormalLinkage() == Linkage::Internal || New->isInline() || 4804 isa<VarTemplateSpecializationDecl>(New) || 4805 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() || 4806 New->getDeclContext()->isDependentContext())) { 4807 // The previous definition is hidden, and multiple definitions are 4808 // permitted (in separate TUs). Demote this to a declaration. 4809 New->demoteThisDefinitionToDeclaration(); 4810 4811 // Make the canonical definition visible. 4812 if (auto *OldTD = Old->getDescribedVarTemplate()) 4813 makeMergedDefinitionVisible(OldTD); 4814 makeMergedDefinitionVisible(Old); 4815 return false; 4816 } else { 4817 Diag(New->getLocation(), diag::err_redefinition) << New; 4818 notePreviousDefinition(Old, New->getLocation()); 4819 New->setInvalidDecl(); 4820 return true; 4821 } 4822 } 4823 4824 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 4825 DeclSpec &DS, 4826 const ParsedAttributesView &DeclAttrs, 4827 RecordDecl *&AnonRecord) { 4828 return ParsedFreeStandingDeclSpec( 4829 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord); 4830 } 4831 4832 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4833 // disambiguate entities defined in different scopes. 4834 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4835 // compatibility. 4836 // We will pick our mangling number depending on which version of MSVC is being 4837 // targeted. 4838 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4839 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4840 ? S->getMSCurManglingNumber() 4841 : S->getMSLastManglingNumber(); 4842 } 4843 4844 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4845 if (!Context.getLangOpts().CPlusPlus) 4846 return; 4847 4848 if (isa<CXXRecordDecl>(Tag->getParent())) { 4849 // If this tag is the direct child of a class, number it if 4850 // it is anonymous. 4851 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4852 return; 4853 MangleNumberingContext &MCtx = 4854 Context.getManglingNumberContext(Tag->getParent()); 4855 Context.setManglingNumber( 4856 Tag, MCtx.getManglingNumber( 4857 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4858 return; 4859 } 4860 4861 // If this tag isn't a direct child of a class, number it if it is local. 4862 MangleNumberingContext *MCtx; 4863 Decl *ManglingContextDecl; 4864 std::tie(MCtx, ManglingContextDecl) = 4865 getCurrentMangleNumberContext(Tag->getDeclContext()); 4866 if (MCtx) { 4867 Context.setManglingNumber( 4868 Tag, MCtx->getManglingNumber( 4869 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4870 } 4871 } 4872 4873 namespace { 4874 struct NonCLikeKind { 4875 enum { 4876 None, 4877 BaseClass, 4878 DefaultMemberInit, 4879 Lambda, 4880 Friend, 4881 OtherMember, 4882 Invalid, 4883 } Kind = None; 4884 SourceRange Range; 4885 4886 explicit operator bool() { return Kind != None; } 4887 }; 4888 } 4889 4890 /// Determine whether a class is C-like, according to the rules of C++ 4891 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4892 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4893 if (RD->isInvalidDecl()) 4894 return {NonCLikeKind::Invalid, {}}; 4895 4896 // C++ [dcl.typedef]p9: [P1766R1] 4897 // An unnamed class with a typedef name for linkage purposes shall not 4898 // 4899 // -- have any base classes 4900 if (RD->getNumBases()) 4901 return {NonCLikeKind::BaseClass, 4902 SourceRange(RD->bases_begin()->getBeginLoc(), 4903 RD->bases_end()[-1].getEndLoc())}; 4904 bool Invalid = false; 4905 for (Decl *D : RD->decls()) { 4906 // Don't complain about things we already diagnosed. 4907 if (D->isInvalidDecl()) { 4908 Invalid = true; 4909 continue; 4910 } 4911 4912 // -- have any [...] default member initializers 4913 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4914 if (FD->hasInClassInitializer()) { 4915 auto *Init = FD->getInClassInitializer(); 4916 return {NonCLikeKind::DefaultMemberInit, 4917 Init ? Init->getSourceRange() : D->getSourceRange()}; 4918 } 4919 continue; 4920 } 4921 4922 // FIXME: We don't allow friend declarations. This violates the wording of 4923 // P1766, but not the intent. 4924 if (isa<FriendDecl>(D)) 4925 return {NonCLikeKind::Friend, D->getSourceRange()}; 4926 4927 // -- declare any members other than non-static data members, member 4928 // enumerations, or member classes, 4929 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4930 isa<EnumDecl>(D)) 4931 continue; 4932 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4933 if (!MemberRD) { 4934 if (D->isImplicit()) 4935 continue; 4936 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4937 } 4938 4939 // -- contain a lambda-expression, 4940 if (MemberRD->isLambda()) 4941 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4942 4943 // and all member classes shall also satisfy these requirements 4944 // (recursively). 4945 if (MemberRD->isThisDeclarationADefinition()) { 4946 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4947 return Kind; 4948 } 4949 } 4950 4951 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4952 } 4953 4954 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4955 TypedefNameDecl *NewTD) { 4956 if (TagFromDeclSpec->isInvalidDecl()) 4957 return; 4958 4959 // Do nothing if the tag already has a name for linkage purposes. 4960 if (TagFromDeclSpec->hasNameForLinkage()) 4961 return; 4962 4963 // A well-formed anonymous tag must always be a TagUseKind::Definition. 4964 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4965 4966 // The type must match the tag exactly; no qualifiers allowed. 4967 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4968 Context.getTagDeclType(TagFromDeclSpec))) { 4969 if (getLangOpts().CPlusPlus) 4970 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4971 return; 4972 } 4973 4974 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4975 // An unnamed class with a typedef name for linkage purposes shall [be 4976 // C-like]. 4977 // 4978 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4979 // shouldn't happen, but there are constructs that the language rule doesn't 4980 // disallow for which we can't reasonably avoid computing linkage early. 4981 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4982 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4983 : NonCLikeKind(); 4984 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4985 if (NonCLike || ChangesLinkage) { 4986 if (NonCLike.Kind == NonCLikeKind::Invalid) 4987 return; 4988 4989 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4990 if (ChangesLinkage) { 4991 // If the linkage changes, we can't accept this as an extension. 4992 if (NonCLike.Kind == NonCLikeKind::None) 4993 DiagID = diag::err_typedef_changes_linkage; 4994 else 4995 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4996 } 4997 4998 SourceLocation FixitLoc = 4999 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 5000 llvm::SmallString<40> TextToInsert; 5001 TextToInsert += ' '; 5002 TextToInsert += NewTD->getIdentifier()->getName(); 5003 5004 Diag(FixitLoc, DiagID) 5005 << isa<TypeAliasDecl>(NewTD) 5006 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 5007 if (NonCLike.Kind != NonCLikeKind::None) { 5008 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 5009 << NonCLike.Kind - 1 << NonCLike.Range; 5010 } 5011 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 5012 << NewTD << isa<TypeAliasDecl>(NewTD); 5013 5014 if (ChangesLinkage) 5015 return; 5016 } 5017 5018 // Otherwise, set this as the anon-decl typedef for the tag. 5019 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 5020 5021 // Now that we have a name for the tag, process API notes again. 5022 ProcessAPINotes(TagFromDeclSpec); 5023 } 5024 5025 static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) { 5026 DeclSpec::TST T = DS.getTypeSpecType(); 5027 switch (T) { 5028 case DeclSpec::TST_class: 5029 return 0; 5030 case DeclSpec::TST_struct: 5031 return 1; 5032 case DeclSpec::TST_interface: 5033 return 2; 5034 case DeclSpec::TST_union: 5035 return 3; 5036 case DeclSpec::TST_enum: 5037 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) { 5038 if (ED->isScopedUsingClassTag()) 5039 return 5; 5040 if (ED->isScoped()) 5041 return 6; 5042 } 5043 return 4; 5044 default: 5045 llvm_unreachable("unexpected type specifier"); 5046 } 5047 } 5048 5049 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 5050 DeclSpec &DS, 5051 const ParsedAttributesView &DeclAttrs, 5052 MultiTemplateParamsArg TemplateParams, 5053 bool IsExplicitInstantiation, 5054 RecordDecl *&AnonRecord, 5055 SourceLocation EllipsisLoc) { 5056 Decl *TagD = nullptr; 5057 TagDecl *Tag = nullptr; 5058 if (DS.getTypeSpecType() == DeclSpec::TST_class || 5059 DS.getTypeSpecType() == DeclSpec::TST_struct || 5060 DS.getTypeSpecType() == DeclSpec::TST_interface || 5061 DS.getTypeSpecType() == DeclSpec::TST_union || 5062 DS.getTypeSpecType() == DeclSpec::TST_enum) { 5063 TagD = DS.getRepAsDecl(); 5064 5065 if (!TagD) // We probably had an error 5066 return nullptr; 5067 5068 // Note that the above type specs guarantee that the 5069 // type rep is a Decl, whereas in many of the others 5070 // it's a Type. 5071 if (isa<TagDecl>(TagD)) 5072 Tag = cast<TagDecl>(TagD); 5073 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 5074 Tag = CTD->getTemplatedDecl(); 5075 } 5076 5077 if (Tag) { 5078 handleTagNumbering(Tag, S); 5079 Tag->setFreeStanding(); 5080 if (Tag->isInvalidDecl()) 5081 return Tag; 5082 } 5083 5084 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 5085 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 5086 // or incomplete types shall not be restrict-qualified." 5087 if (TypeQuals & DeclSpec::TQ_restrict) 5088 Diag(DS.getRestrictSpecLoc(), 5089 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 5090 << DS.getSourceRange(); 5091 } 5092 5093 if (DS.isInlineSpecified()) 5094 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 5095 << getLangOpts().CPlusPlus17; 5096 5097 if (DS.hasConstexprSpecifier()) { 5098 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 5099 // and definitions of functions and variables. 5100 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 5101 // the declaration of a function or function template 5102 if (Tag) 5103 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 5104 << GetDiagnosticTypeSpecifierID(DS) 5105 << static_cast<int>(DS.getConstexprSpecifier()); 5106 else if (getLangOpts().C23) 5107 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable); 5108 else 5109 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 5110 << static_cast<int>(DS.getConstexprSpecifier()); 5111 // Don't emit warnings after this error. 5112 return TagD; 5113 } 5114 5115 DiagnoseFunctionSpecifiers(DS); 5116 5117 if (DS.isFriendSpecified()) { 5118 // If we're dealing with a decl but not a TagDecl, assume that 5119 // whatever routines created it handled the friendship aspect. 5120 if (TagD && !Tag) 5121 return nullptr; 5122 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc); 5123 } 5124 5125 assert(EllipsisLoc.isInvalid() && 5126 "Friend ellipsis but not friend-specified?"); 5127 5128 // Track whether this decl-specifier declares anything. 5129 bool DeclaresAnything = true; 5130 5131 // Handle anonymous struct definitions. 5132 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 5133 if (!Record->getDeclName() && Record->isCompleteDefinition() && 5134 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 5135 if (getLangOpts().CPlusPlus || 5136 Record->getDeclContext()->isRecord()) { 5137 // If CurContext is a DeclContext that can contain statements, 5138 // RecursiveASTVisitor won't visit the decls that 5139 // BuildAnonymousStructOrUnion() will put into CurContext. 5140 // Also store them here so that they can be part of the 5141 // DeclStmt that gets created in this case. 5142 // FIXME: Also return the IndirectFieldDecls created by 5143 // BuildAnonymousStructOr union, for the same reason? 5144 if (CurContext->isFunctionOrMethod()) 5145 AnonRecord = Record; 5146 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 5147 Context.getPrintingPolicy()); 5148 } 5149 5150 DeclaresAnything = false; 5151 } 5152 } 5153 5154 // C11 6.7.2.1p2: 5155 // A struct-declaration that does not declare an anonymous structure or 5156 // anonymous union shall contain a struct-declarator-list. 5157 // 5158 // This rule also existed in C89 and C99; the grammar for struct-declaration 5159 // did not permit a struct-declaration without a struct-declarator-list. 5160 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 5161 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 5162 // Check for Microsoft C extension: anonymous struct/union member. 5163 // Handle 2 kinds of anonymous struct/union: 5164 // struct STRUCT; 5165 // union UNION; 5166 // and 5167 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 5168 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 5169 if ((Tag && Tag->getDeclName()) || 5170 DS.getTypeSpecType() == DeclSpec::TST_typename) { 5171 RecordDecl *Record = nullptr; 5172 if (Tag) 5173 Record = dyn_cast<RecordDecl>(Tag); 5174 else if (const RecordType *RT = 5175 DS.getRepAsType().get()->getAsStructureType()) 5176 Record = RT->getDecl(); 5177 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 5178 Record = UT->getDecl(); 5179 5180 if (Record && getLangOpts().MicrosoftExt) { 5181 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 5182 << Record->isUnion() << DS.getSourceRange(); 5183 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 5184 } 5185 5186 DeclaresAnything = false; 5187 } 5188 } 5189 5190 // Skip all the checks below if we have a type error. 5191 if (DS.getTypeSpecType() == DeclSpec::TST_error || 5192 (TagD && TagD->isInvalidDecl())) 5193 return TagD; 5194 5195 if (getLangOpts().CPlusPlus && 5196 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 5197 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 5198 if (Enum->enumerator_begin() == Enum->enumerator_end() && 5199 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 5200 DeclaresAnything = false; 5201 5202 if (!DS.isMissingDeclaratorOk()) { 5203 // Customize diagnostic for a typedef missing a name. 5204 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 5205 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 5206 << DS.getSourceRange(); 5207 else 5208 DeclaresAnything = false; 5209 } 5210 5211 if (DS.isModulePrivateSpecified() && 5212 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 5213 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 5214 << llvm::to_underlying(Tag->getTagKind()) 5215 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 5216 5217 ActOnDocumentableDecl(TagD); 5218 5219 // C 6.7/2: 5220 // A declaration [...] shall declare at least a declarator [...], a tag, 5221 // or the members of an enumeration. 5222 // C++ [dcl.dcl]p3: 5223 // [If there are no declarators], and except for the declaration of an 5224 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5225 // names into the program, or shall redeclare a name introduced by a 5226 // previous declaration. 5227 if (!DeclaresAnything) { 5228 // In C, we allow this as a (popular) extension / bug. Don't bother 5229 // producing further diagnostics for redundant qualifiers after this. 5230 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 5231 ? diag::err_no_declarators 5232 : diag::ext_no_declarators) 5233 << DS.getSourceRange(); 5234 return TagD; 5235 } 5236 5237 // C++ [dcl.stc]p1: 5238 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 5239 // init-declarator-list of the declaration shall not be empty. 5240 // C++ [dcl.fct.spec]p1: 5241 // If a cv-qualifier appears in a decl-specifier-seq, the 5242 // init-declarator-list of the declaration shall not be empty. 5243 // 5244 // Spurious qualifiers here appear to be valid in C. 5245 unsigned DiagID = diag::warn_standalone_specifier; 5246 if (getLangOpts().CPlusPlus) 5247 DiagID = diag::ext_standalone_specifier; 5248 5249 // Note that a linkage-specification sets a storage class, but 5250 // 'extern "C" struct foo;' is actually valid and not theoretically 5251 // useless. 5252 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 5253 if (SCS == DeclSpec::SCS_mutable) 5254 // Since mutable is not a viable storage class specifier in C, there is 5255 // no reason to treat it as an extension. Instead, diagnose as an error. 5256 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 5257 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 5258 Diag(DS.getStorageClassSpecLoc(), DiagID) 5259 << DeclSpec::getSpecifierName(SCS); 5260 } 5261 5262 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 5263 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 5264 << DeclSpec::getSpecifierName(TSCS); 5265 if (DS.getTypeQualifiers()) { 5266 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5267 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 5268 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5269 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 5270 // Restrict is covered above. 5271 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5272 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 5273 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5274 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 5275 } 5276 5277 // Warn about ignored type attributes, for example: 5278 // __attribute__((aligned)) struct A; 5279 // Attributes should be placed after tag to apply to type declaration. 5280 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) { 5281 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 5282 if (TypeSpecType == DeclSpec::TST_class || 5283 TypeSpecType == DeclSpec::TST_struct || 5284 TypeSpecType == DeclSpec::TST_interface || 5285 TypeSpecType == DeclSpec::TST_union || 5286 TypeSpecType == DeclSpec::TST_enum) { 5287 5288 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) { 5289 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored; 5290 if (AL.isAlignas() && !getLangOpts().CPlusPlus) 5291 DiagnosticId = diag::warn_attribute_ignored; 5292 else if (AL.isRegularKeywordAttribute()) 5293 DiagnosticId = diag::err_declspec_keyword_has_no_effect; 5294 else 5295 DiagnosticId = diag::warn_declspec_attribute_ignored; 5296 Diag(AL.getLoc(), DiagnosticId) 5297 << AL << GetDiagnosticTypeSpecifierID(DS); 5298 }; 5299 5300 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic); 5301 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic); 5302 } 5303 } 5304 5305 return TagD; 5306 } 5307 5308 /// We are trying to inject an anonymous member into the given scope; 5309 /// check if there's an existing declaration that can't be overloaded. 5310 /// 5311 /// \return true if this is a forbidden redeclaration 5312 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, 5313 DeclContext *Owner, 5314 DeclarationName Name, 5315 SourceLocation NameLoc, bool IsUnion, 5316 StorageClass SC) { 5317 LookupResult R(SemaRef, Name, NameLoc, 5318 Owner->isRecord() ? Sema::LookupMemberName 5319 : Sema::LookupOrdinaryName, 5320 RedeclarationKind::ForVisibleRedeclaration); 5321 if (!SemaRef.LookupName(R, S)) return false; 5322 5323 // Pick a representative declaration. 5324 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 5325 assert(PrevDecl && "Expected a non-null Decl"); 5326 5327 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 5328 return false; 5329 5330 if (SC == StorageClass::SC_None && 5331 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) && 5332 (Owner->isFunctionOrMethod() || Owner->isRecord())) { 5333 if (!Owner->isRecord()) 5334 SemaRef.DiagPlaceholderVariableDefinition(NameLoc); 5335 return false; 5336 } 5337 5338 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 5339 << IsUnion << Name; 5340 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 5341 5342 return true; 5343 } 5344 5345 void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) { 5346 if (auto *RD = dyn_cast_if_present<RecordDecl>(D)) 5347 DiagPlaceholderFieldDeclDefinitions(RD); 5348 } 5349 5350 void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) { 5351 if (!getLangOpts().CPlusPlus) 5352 return; 5353 5354 // This function can be parsed before we have validated the 5355 // structure as an anonymous struct 5356 if (Record->isAnonymousStructOrUnion()) 5357 return; 5358 5359 const NamedDecl *First = 0; 5360 for (const Decl *D : Record->decls()) { 5361 const NamedDecl *ND = dyn_cast<NamedDecl>(D); 5362 if (!ND || !ND->isPlaceholderVar(getLangOpts())) 5363 continue; 5364 if (!First) 5365 First = ND; 5366 else 5367 DiagPlaceholderVariableDefinition(ND->getLocation()); 5368 } 5369 } 5370 5371 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 5372 /// anonymous struct or union AnonRecord into the owning context Owner 5373 /// and scope S. This routine will be invoked just after we realize 5374 /// that an unnamed union or struct is actually an anonymous union or 5375 /// struct, e.g., 5376 /// 5377 /// @code 5378 /// union { 5379 /// int i; 5380 /// float f; 5381 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 5382 /// // f into the surrounding scope.x 5383 /// @endcode 5384 /// 5385 /// This routine is recursive, injecting the names of nested anonymous 5386 /// structs/unions into the owning context and scope as well. 5387 static bool 5388 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 5389 RecordDecl *AnonRecord, AccessSpecifier AS, 5390 StorageClass SC, 5391 SmallVectorImpl<NamedDecl *> &Chaining) { 5392 bool Invalid = false; 5393 5394 // Look every FieldDecl and IndirectFieldDecl with a name. 5395 for (auto *D : AnonRecord->decls()) { 5396 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 5397 cast<NamedDecl>(D)->getDeclName()) { 5398 ValueDecl *VD = cast<ValueDecl>(D); 5399 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 5400 VD->getLocation(), AnonRecord->isUnion(), 5401 SC)) { 5402 // C++ [class.union]p2: 5403 // The names of the members of an anonymous union shall be 5404 // distinct from the names of any other entity in the 5405 // scope in which the anonymous union is declared. 5406 Invalid = true; 5407 } else { 5408 // C++ [class.union]p2: 5409 // For the purpose of name lookup, after the anonymous union 5410 // definition, the members of the anonymous union are 5411 // considered to have been defined in the scope in which the 5412 // anonymous union is declared. 5413 unsigned OldChainingSize = Chaining.size(); 5414 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 5415 Chaining.append(IF->chain_begin(), IF->chain_end()); 5416 else 5417 Chaining.push_back(VD); 5418 5419 assert(Chaining.size() >= 2); 5420 NamedDecl **NamedChain = 5421 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 5422 for (unsigned i = 0; i < Chaining.size(); i++) 5423 NamedChain[i] = Chaining[i]; 5424 5425 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 5426 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 5427 VD->getType(), {NamedChain, Chaining.size()}); 5428 5429 for (const auto *Attr : VD->attrs()) 5430 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 5431 5432 IndirectField->setAccess(AS); 5433 IndirectField->setImplicit(); 5434 SemaRef.PushOnScopeChains(IndirectField, S); 5435 5436 // That includes picking up the appropriate access specifier. 5437 if (AS != AS_none) IndirectField->setAccess(AS); 5438 5439 Chaining.resize(OldChainingSize); 5440 } 5441 } 5442 } 5443 5444 return Invalid; 5445 } 5446 5447 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5448 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5449 /// illegal input values are mapped to SC_None. 5450 static StorageClass 5451 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5452 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5453 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5454 "Parser allowed 'typedef' as storage class VarDecl."); 5455 switch (StorageClassSpec) { 5456 case DeclSpec::SCS_unspecified: return SC_None; 5457 case DeclSpec::SCS_extern: 5458 if (DS.isExternInLinkageSpec()) 5459 return SC_None; 5460 return SC_Extern; 5461 case DeclSpec::SCS_static: return SC_Static; 5462 case DeclSpec::SCS_auto: return SC_Auto; 5463 case DeclSpec::SCS_register: return SC_Register; 5464 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5465 // Illegal SCSs map to None: error reporting is up to the caller. 5466 case DeclSpec::SCS_mutable: // Fall through. 5467 case DeclSpec::SCS_typedef: return SC_None; 5468 } 5469 llvm_unreachable("unknown storage class specifier"); 5470 } 5471 5472 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5473 assert(Record->hasInClassInitializer()); 5474 5475 for (const auto *I : Record->decls()) { 5476 const auto *FD = dyn_cast<FieldDecl>(I); 5477 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5478 FD = IFD->getAnonField(); 5479 if (FD && FD->hasInClassInitializer()) 5480 return FD->getLocation(); 5481 } 5482 5483 llvm_unreachable("couldn't find in-class initializer"); 5484 } 5485 5486 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5487 SourceLocation DefaultInitLoc) { 5488 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5489 return; 5490 5491 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5492 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5493 } 5494 5495 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5496 CXXRecordDecl *AnonUnion) { 5497 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5498 return; 5499 5500 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5501 } 5502 5503 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5504 AccessSpecifier AS, 5505 RecordDecl *Record, 5506 const PrintingPolicy &Policy) { 5507 DeclContext *Owner = Record->getDeclContext(); 5508 5509 // Diagnose whether this anonymous struct/union is an extension. 5510 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5511 Diag(Record->getLocation(), diag::ext_anonymous_union); 5512 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5513 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5514 else if (!Record->isUnion() && !getLangOpts().C11) 5515 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5516 5517 // C and C++ require different kinds of checks for anonymous 5518 // structs/unions. 5519 bool Invalid = false; 5520 if (getLangOpts().CPlusPlus) { 5521 const char *PrevSpec = nullptr; 5522 if (Record->isUnion()) { 5523 // C++ [class.union]p6: 5524 // C++17 [class.union.anon]p2: 5525 // Anonymous unions declared in a named namespace or in the 5526 // global namespace shall be declared static. 5527 unsigned DiagID; 5528 DeclContext *OwnerScope = Owner->getRedeclContext(); 5529 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5530 (OwnerScope->isTranslationUnit() || 5531 (OwnerScope->isNamespace() && 5532 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5533 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5534 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5535 5536 // Recover by adding 'static'. 5537 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5538 PrevSpec, DiagID, Policy); 5539 } 5540 // C++ [class.union]p6: 5541 // A storage class is not allowed in a declaration of an 5542 // anonymous union in a class scope. 5543 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5544 isa<RecordDecl>(Owner)) { 5545 Diag(DS.getStorageClassSpecLoc(), 5546 diag::err_anonymous_union_with_storage_spec) 5547 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5548 5549 // Recover by removing the storage specifier. 5550 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5551 SourceLocation(), 5552 PrevSpec, DiagID, Context.getPrintingPolicy()); 5553 } 5554 } 5555 5556 // Ignore const/volatile/restrict qualifiers. 5557 if (DS.getTypeQualifiers()) { 5558 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5559 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5560 << Record->isUnion() << "const" 5561 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5562 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5563 Diag(DS.getVolatileSpecLoc(), 5564 diag::ext_anonymous_struct_union_qualified) 5565 << Record->isUnion() << "volatile" 5566 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5567 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5568 Diag(DS.getRestrictSpecLoc(), 5569 diag::ext_anonymous_struct_union_qualified) 5570 << Record->isUnion() << "restrict" 5571 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5572 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5573 Diag(DS.getAtomicSpecLoc(), 5574 diag::ext_anonymous_struct_union_qualified) 5575 << Record->isUnion() << "_Atomic" 5576 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5577 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5578 Diag(DS.getUnalignedSpecLoc(), 5579 diag::ext_anonymous_struct_union_qualified) 5580 << Record->isUnion() << "__unaligned" 5581 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5582 5583 DS.ClearTypeQualifiers(); 5584 } 5585 5586 // C++ [class.union]p2: 5587 // The member-specification of an anonymous union shall only 5588 // define non-static data members. [Note: nested types and 5589 // functions cannot be declared within an anonymous union. ] 5590 for (auto *Mem : Record->decls()) { 5591 // Ignore invalid declarations; we already diagnosed them. 5592 if (Mem->isInvalidDecl()) 5593 continue; 5594 5595 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5596 // C++ [class.union]p3: 5597 // An anonymous union shall not have private or protected 5598 // members (clause 11). 5599 assert(FD->getAccess() != AS_none); 5600 if (FD->getAccess() != AS_public) { 5601 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5602 << Record->isUnion() << (FD->getAccess() == AS_protected); 5603 Invalid = true; 5604 } 5605 5606 // C++ [class.union]p1 5607 // An object of a class with a non-trivial constructor, a non-trivial 5608 // copy constructor, a non-trivial destructor, or a non-trivial copy 5609 // assignment operator cannot be a member of a union, nor can an 5610 // array of such objects. 5611 if (CheckNontrivialField(FD)) 5612 Invalid = true; 5613 } else if (Mem->isImplicit()) { 5614 // Any implicit members are fine. 5615 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5616 // This is a type that showed up in an 5617 // elaborated-type-specifier inside the anonymous struct or 5618 // union, but which actually declares a type outside of the 5619 // anonymous struct or union. It's okay. 5620 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5621 if (!MemRecord->isAnonymousStructOrUnion() && 5622 MemRecord->getDeclName()) { 5623 // Visual C++ allows type definition in anonymous struct or union. 5624 if (getLangOpts().MicrosoftExt) 5625 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5626 << Record->isUnion(); 5627 else { 5628 // This is a nested type declaration. 5629 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5630 << Record->isUnion(); 5631 Invalid = true; 5632 } 5633 } else { 5634 // This is an anonymous type definition within another anonymous type. 5635 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5636 // not part of standard C++. 5637 Diag(MemRecord->getLocation(), 5638 diag::ext_anonymous_record_with_anonymous_type) 5639 << Record->isUnion(); 5640 } 5641 } else if (isa<AccessSpecDecl>(Mem)) { 5642 // Any access specifier is fine. 5643 } else if (isa<StaticAssertDecl>(Mem)) { 5644 // In C++1z, static_assert declarations are also fine. 5645 } else { 5646 // We have something that isn't a non-static data 5647 // member. Complain about it. 5648 unsigned DK = diag::err_anonymous_record_bad_member; 5649 if (isa<TypeDecl>(Mem)) 5650 DK = diag::err_anonymous_record_with_type; 5651 else if (isa<FunctionDecl>(Mem)) 5652 DK = diag::err_anonymous_record_with_function; 5653 else if (isa<VarDecl>(Mem)) 5654 DK = diag::err_anonymous_record_with_static; 5655 5656 // Visual C++ allows type definition in anonymous struct or union. 5657 if (getLangOpts().MicrosoftExt && 5658 DK == diag::err_anonymous_record_with_type) 5659 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5660 << Record->isUnion(); 5661 else { 5662 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5663 Invalid = true; 5664 } 5665 } 5666 } 5667 5668 // C++11 [class.union]p8 (DR1460): 5669 // At most one variant member of a union may have a 5670 // brace-or-equal-initializer. 5671 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5672 Owner->isRecord()) 5673 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5674 cast<CXXRecordDecl>(Record)); 5675 } 5676 5677 if (!Record->isUnion() && !Owner->isRecord()) { 5678 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5679 << getLangOpts().CPlusPlus; 5680 Invalid = true; 5681 } 5682 5683 // C++ [dcl.dcl]p3: 5684 // [If there are no declarators], and except for the declaration of an 5685 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5686 // names into the program 5687 // C++ [class.mem]p2: 5688 // each such member-declaration shall either declare at least one member 5689 // name of the class or declare at least one unnamed bit-field 5690 // 5691 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5692 if (getLangOpts().CPlusPlus && Record->field_empty()) 5693 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5694 5695 // Mock up a declarator. 5696 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member); 5697 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5698 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc); 5699 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5700 5701 // Create a declaration for this anonymous struct/union. 5702 NamedDecl *Anon = nullptr; 5703 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5704 Anon = FieldDecl::Create( 5705 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5706 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5707 /*BitWidth=*/nullptr, /*Mutable=*/false, 5708 /*InitStyle=*/ICIS_NoInit); 5709 Anon->setAccess(AS); 5710 ProcessDeclAttributes(S, Anon, Dc); 5711 5712 if (getLangOpts().CPlusPlus) 5713 FieldCollector->Add(cast<FieldDecl>(Anon)); 5714 } else { 5715 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5716 if (SCSpec == DeclSpec::SCS_mutable) { 5717 // mutable can only appear on non-static class members, so it's always 5718 // an error here 5719 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5720 Invalid = true; 5721 SC = SC_None; 5722 } 5723 5724 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5725 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5726 Context.getTypeDeclType(Record), TInfo, SC); 5727 if (Invalid) 5728 Anon->setInvalidDecl(); 5729 5730 ProcessDeclAttributes(S, Anon, Dc); 5731 5732 // Default-initialize the implicit variable. This initialization will be 5733 // trivial in almost all cases, except if a union member has an in-class 5734 // initializer: 5735 // union { int n = 0; }; 5736 ActOnUninitializedDecl(Anon); 5737 } 5738 Anon->setImplicit(); 5739 5740 // Mark this as an anonymous struct/union type. 5741 Record->setAnonymousStructOrUnion(true); 5742 5743 // Add the anonymous struct/union object to the current 5744 // context. We'll be referencing this object when we refer to one of 5745 // its members. 5746 Owner->addDecl(Anon); 5747 5748 // Inject the members of the anonymous struct/union into the owning 5749 // context and into the identifier resolver chain for name lookup 5750 // purposes. 5751 SmallVector<NamedDecl*, 2> Chain; 5752 Chain.push_back(Anon); 5753 5754 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC, 5755 Chain)) 5756 Invalid = true; 5757 5758 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5759 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5760 MangleNumberingContext *MCtx; 5761 Decl *ManglingContextDecl; 5762 std::tie(MCtx, ManglingContextDecl) = 5763 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5764 if (MCtx) { 5765 Context.setManglingNumber( 5766 NewVD, MCtx->getManglingNumber( 5767 NewVD, getMSManglingNumber(getLangOpts(), S))); 5768 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5769 } 5770 } 5771 } 5772 5773 if (Invalid) 5774 Anon->setInvalidDecl(); 5775 5776 return Anon; 5777 } 5778 5779 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5780 RecordDecl *Record) { 5781 assert(Record && "expected a record!"); 5782 5783 // Mock up a declarator. 5784 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName); 5785 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc); 5786 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5787 5788 auto *ParentDecl = cast<RecordDecl>(CurContext); 5789 QualType RecTy = Context.getTypeDeclType(Record); 5790 5791 // Create a declaration for this anonymous struct. 5792 NamedDecl *Anon = 5793 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5794 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5795 /*BitWidth=*/nullptr, /*Mutable=*/false, 5796 /*InitStyle=*/ICIS_NoInit); 5797 Anon->setImplicit(); 5798 5799 // Add the anonymous struct object to the current context. 5800 CurContext->addDecl(Anon); 5801 5802 // Inject the members of the anonymous struct into the current 5803 // context and into the identifier resolver chain for name lookup 5804 // purposes. 5805 SmallVector<NamedDecl*, 2> Chain; 5806 Chain.push_back(Anon); 5807 5808 RecordDecl *RecordDef = Record->getDefinition(); 5809 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5810 diag::err_field_incomplete_or_sizeless) || 5811 InjectAnonymousStructOrUnionMembers( 5812 *this, S, CurContext, RecordDef, AS_none, 5813 StorageClassSpecToVarDeclStorageClass(DS), Chain)) { 5814 Anon->setInvalidDecl(); 5815 ParentDecl->setInvalidDecl(); 5816 } 5817 5818 return Anon; 5819 } 5820 5821 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5822 return GetNameFromUnqualifiedId(D.getName()); 5823 } 5824 5825 DeclarationNameInfo 5826 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5827 DeclarationNameInfo NameInfo; 5828 NameInfo.setLoc(Name.StartLocation); 5829 5830 switch (Name.getKind()) { 5831 5832 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5833 case UnqualifiedIdKind::IK_Identifier: 5834 NameInfo.setName(Name.Identifier); 5835 return NameInfo; 5836 5837 case UnqualifiedIdKind::IK_DeductionGuideName: { 5838 // C++ [temp.deduct.guide]p3: 5839 // The simple-template-id shall name a class template specialization. 5840 // The template-name shall be the same identifier as the template-name 5841 // of the simple-template-id. 5842 // These together intend to imply that the template-name shall name a 5843 // class template. 5844 // FIXME: template<typename T> struct X {}; 5845 // template<typename T> using Y = X<T>; 5846 // Y(int) -> Y<int>; 5847 // satisfies these rules but does not name a class template. 5848 TemplateName TN = Name.TemplateName.get().get(); 5849 auto *Template = TN.getAsTemplateDecl(); 5850 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5851 Diag(Name.StartLocation, 5852 diag::err_deduction_guide_name_not_class_template) 5853 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5854 if (Template) 5855 NoteTemplateLocation(*Template); 5856 return DeclarationNameInfo(); 5857 } 5858 5859 NameInfo.setName( 5860 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5861 return NameInfo; 5862 } 5863 5864 case UnqualifiedIdKind::IK_OperatorFunctionId: 5865 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5866 Name.OperatorFunctionId.Operator)); 5867 NameInfo.setCXXOperatorNameRange(SourceRange( 5868 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5869 return NameInfo; 5870 5871 case UnqualifiedIdKind::IK_LiteralOperatorId: 5872 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5873 Name.Identifier)); 5874 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5875 return NameInfo; 5876 5877 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5878 TypeSourceInfo *TInfo; 5879 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5880 if (Ty.isNull()) 5881 return DeclarationNameInfo(); 5882 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5883 Context.getCanonicalType(Ty))); 5884 NameInfo.setNamedTypeInfo(TInfo); 5885 return NameInfo; 5886 } 5887 5888 case UnqualifiedIdKind::IK_ConstructorName: { 5889 TypeSourceInfo *TInfo; 5890 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5891 if (Ty.isNull()) 5892 return DeclarationNameInfo(); 5893 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5894 Context.getCanonicalType(Ty))); 5895 NameInfo.setNamedTypeInfo(TInfo); 5896 return NameInfo; 5897 } 5898 5899 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5900 // In well-formed code, we can only have a constructor 5901 // template-id that refers to the current context, so go there 5902 // to find the actual type being constructed. 5903 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5904 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5905 return DeclarationNameInfo(); 5906 5907 // Determine the type of the class being constructed. 5908 QualType CurClassType = Context.getTypeDeclType(CurClass); 5909 5910 // FIXME: Check two things: that the template-id names the same type as 5911 // CurClassType, and that the template-id does not occur when the name 5912 // was qualified. 5913 5914 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5915 Context.getCanonicalType(CurClassType))); 5916 // FIXME: should we retrieve TypeSourceInfo? 5917 NameInfo.setNamedTypeInfo(nullptr); 5918 return NameInfo; 5919 } 5920 5921 case UnqualifiedIdKind::IK_DestructorName: { 5922 TypeSourceInfo *TInfo; 5923 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5924 if (Ty.isNull()) 5925 return DeclarationNameInfo(); 5926 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5927 Context.getCanonicalType(Ty))); 5928 NameInfo.setNamedTypeInfo(TInfo); 5929 return NameInfo; 5930 } 5931 5932 case UnqualifiedIdKind::IK_TemplateId: { 5933 TemplateName TName = Name.TemplateId->Template.get(); 5934 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5935 return Context.getNameForTemplate(TName, TNameLoc); 5936 } 5937 5938 } // switch (Name.getKind()) 5939 5940 llvm_unreachable("Unknown name kind"); 5941 } 5942 5943 static QualType getCoreType(QualType Ty) { 5944 do { 5945 if (Ty->isPointerOrReferenceType()) 5946 Ty = Ty->getPointeeType(); 5947 else if (Ty->isArrayType()) 5948 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5949 else 5950 return Ty.withoutLocalFastQualifiers(); 5951 } while (true); 5952 } 5953 5954 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5955 /// and Definition have "nearly" matching parameters. This heuristic is 5956 /// used to improve diagnostics in the case where an out-of-line function 5957 /// definition doesn't match any declaration within the class or namespace. 5958 /// Also sets Params to the list of indices to the parameters that differ 5959 /// between the declaration and the definition. If hasSimilarParameters 5960 /// returns true and Params is empty, then all of the parameters match. 5961 static bool hasSimilarParameters(ASTContext &Context, 5962 FunctionDecl *Declaration, 5963 FunctionDecl *Definition, 5964 SmallVectorImpl<unsigned> &Params) { 5965 Params.clear(); 5966 if (Declaration->param_size() != Definition->param_size()) 5967 return false; 5968 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5969 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5970 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5971 5972 // The parameter types are identical 5973 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5974 continue; 5975 5976 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5977 QualType DefParamBaseTy = getCoreType(DefParamTy); 5978 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5979 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5980 5981 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5982 (DeclTyName && DeclTyName == DefTyName)) 5983 Params.push_back(Idx); 5984 else // The two parameters aren't even close 5985 return false; 5986 } 5987 5988 return true; 5989 } 5990 5991 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given 5992 /// declarator needs to be rebuilt in the current instantiation. 5993 /// Any bits of declarator which appear before the name are valid for 5994 /// consideration here. That's specifically the type in the decl spec 5995 /// and the base type in any member-pointer chunks. 5996 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5997 DeclarationName Name) { 5998 // The types we specifically need to rebuild are: 5999 // - typenames, typeofs, and decltypes 6000 // - types which will become injected class names 6001 // Of course, we also need to rebuild any type referencing such a 6002 // type. It's safest to just say "dependent", but we call out a 6003 // few cases here. 6004 6005 DeclSpec &DS = D.getMutableDeclSpec(); 6006 switch (DS.getTypeSpecType()) { 6007 case DeclSpec::TST_typename: 6008 case DeclSpec::TST_typeofType: 6009 case DeclSpec::TST_typeof_unqualType: 6010 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait: 6011 #include "clang/Basic/TransformTypeTraits.def" 6012 case DeclSpec::TST_atomic: { 6013 // Grab the type from the parser. 6014 TypeSourceInfo *TSI = nullptr; 6015 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 6016 if (T.isNull() || !T->isInstantiationDependentType()) break; 6017 6018 // Make sure there's a type source info. This isn't really much 6019 // of a waste; most dependent types should have type source info 6020 // attached already. 6021 if (!TSI) 6022 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 6023 6024 // Rebuild the type in the current instantiation. 6025 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 6026 if (!TSI) return true; 6027 6028 // Store the new type back in the decl spec. 6029 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 6030 DS.UpdateTypeRep(LocType); 6031 break; 6032 } 6033 6034 case DeclSpec::TST_decltype: 6035 case DeclSpec::TST_typeof_unqualExpr: 6036 case DeclSpec::TST_typeofExpr: { 6037 Expr *E = DS.getRepAsExpr(); 6038 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 6039 if (Result.isInvalid()) return true; 6040 DS.UpdateExprRep(Result.get()); 6041 break; 6042 } 6043 6044 default: 6045 // Nothing to do for these decl specs. 6046 break; 6047 } 6048 6049 // It doesn't matter what order we do this in. 6050 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 6051 DeclaratorChunk &Chunk = D.getTypeObject(I); 6052 6053 // The only type information in the declarator which can come 6054 // before the declaration name is the base type of a member 6055 // pointer. 6056 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 6057 continue; 6058 6059 // Rebuild the scope specifier in-place. 6060 CXXScopeSpec &SS = Chunk.Mem.Scope(); 6061 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 6062 return true; 6063 } 6064 6065 return false; 6066 } 6067 6068 /// Returns true if the declaration is declared in a system header or from a 6069 /// system macro. 6070 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) { 6071 return SM.isInSystemHeader(D->getLocation()) || 6072 SM.isInSystemMacro(D->getLocation()); 6073 } 6074 6075 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 6076 // Avoid warning twice on the same identifier, and don't warn on redeclaration 6077 // of system decl. 6078 if (D->getPreviousDecl() || D->isImplicit()) 6079 return; 6080 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 6081 if (Status != ReservedIdentifierStatus::NotReserved && 6082 !isFromSystemHeader(Context.getSourceManager(), D)) { 6083 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 6084 << D << static_cast<int>(Status); 6085 } 6086 } 6087 6088 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 6089 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 6090 6091 // Check if we are in an `omp begin/end declare variant` scope. Handle this 6092 // declaration only if the `bind_to_declaration` extension is set. 6093 SmallVector<FunctionDecl *, 4> Bases; 6094 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope()) 6095 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive( 6096 llvm::omp::TraitProperty:: 6097 implementation_extension_bind_to_declaration)) 6098 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 6099 S, D, MultiTemplateParamsArg(), Bases); 6100 6101 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 6102 6103 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 6104 Dcl && Dcl->getDeclContext()->isFileContext()) 6105 Dcl->setTopLevelDeclInObjCContainer(); 6106 6107 if (!Bases.empty()) 6108 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, 6109 Bases); 6110 6111 return Dcl; 6112 } 6113 6114 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 6115 DeclarationNameInfo NameInfo) { 6116 DeclarationName Name = NameInfo.getName(); 6117 6118 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 6119 while (Record && Record->isAnonymousStructOrUnion()) 6120 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 6121 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 6122 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 6123 return true; 6124 } 6125 6126 return false; 6127 } 6128 6129 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 6130 DeclarationName Name, 6131 SourceLocation Loc, 6132 TemplateIdAnnotation *TemplateId, 6133 bool IsMemberSpecialization) { 6134 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration " 6135 "without nested-name-specifier"); 6136 DeclContext *Cur = CurContext; 6137 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 6138 Cur = Cur->getParent(); 6139 6140 // If the user provided a superfluous scope specifier that refers back to the 6141 // class in which the entity is already declared, diagnose and ignore it. 6142 // 6143 // class X { 6144 // void X::f(); 6145 // }; 6146 // 6147 // Note, it was once ill-formed to give redundant qualification in all 6148 // contexts, but that rule was removed by DR482. 6149 if (Cur->Equals(DC)) { 6150 if (Cur->isRecord()) { 6151 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 6152 : diag::err_member_extra_qualification) 6153 << Name << FixItHint::CreateRemoval(SS.getRange()); 6154 SS.clear(); 6155 } else { 6156 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 6157 } 6158 return false; 6159 } 6160 6161 // Check whether the qualifying scope encloses the scope of the original 6162 // declaration. For a template-id, we perform the checks in 6163 // CheckTemplateSpecializationScope. 6164 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) { 6165 if (Cur->isRecord()) 6166 Diag(Loc, diag::err_member_qualification) 6167 << Name << SS.getRange(); 6168 else if (isa<TranslationUnitDecl>(DC)) 6169 Diag(Loc, diag::err_invalid_declarator_global_scope) 6170 << Name << SS.getRange(); 6171 else if (isa<FunctionDecl>(Cur)) 6172 Diag(Loc, diag::err_invalid_declarator_in_function) 6173 << Name << SS.getRange(); 6174 else if (isa<BlockDecl>(Cur)) 6175 Diag(Loc, diag::err_invalid_declarator_in_block) 6176 << Name << SS.getRange(); 6177 else if (isa<ExportDecl>(Cur)) { 6178 if (!isa<NamespaceDecl>(DC)) 6179 Diag(Loc, diag::err_export_non_namespace_scope_name) 6180 << Name << SS.getRange(); 6181 else 6182 // The cases that DC is not NamespaceDecl should be handled in 6183 // CheckRedeclarationExported. 6184 return false; 6185 } else 6186 Diag(Loc, diag::err_invalid_declarator_scope) 6187 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 6188 6189 return true; 6190 } 6191 6192 if (Cur->isRecord()) { 6193 // Cannot qualify members within a class. 6194 Diag(Loc, diag::err_member_qualification) 6195 << Name << SS.getRange(); 6196 SS.clear(); 6197 6198 // C++ constructors and destructors with incorrect scopes can break 6199 // our AST invariants by having the wrong underlying types. If 6200 // that's the case, then drop this declaration entirely. 6201 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 6202 Name.getNameKind() == DeclarationName::CXXDestructorName) && 6203 !Context.hasSameType(Name.getCXXNameType(), 6204 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 6205 return true; 6206 6207 return false; 6208 } 6209 6210 // C++23 [temp.names]p5: 6211 // The keyword template shall not appear immediately after a declarative 6212 // nested-name-specifier. 6213 // 6214 // First check the template-id (if any), and then check each component of the 6215 // nested-name-specifier in reverse order. 6216 // 6217 // FIXME: nested-name-specifiers in friend declarations are declarative, 6218 // but we don't call diagnoseQualifiedDeclaration for them. We should. 6219 if (TemplateId && TemplateId->TemplateKWLoc.isValid()) 6220 Diag(Loc, diag::ext_template_after_declarative_nns) 6221 << FixItHint::CreateRemoval(TemplateId->TemplateKWLoc); 6222 6223 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 6224 do { 6225 if (SpecLoc.getNestedNameSpecifier()->getKind() == 6226 NestedNameSpecifier::TypeSpecWithTemplate) 6227 Diag(Loc, diag::ext_template_after_declarative_nns) 6228 << FixItHint::CreateRemoval( 6229 SpecLoc.getTypeLoc().getTemplateKeywordLoc()); 6230 6231 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) { 6232 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) { 6233 // C++23 [expr.prim.id.qual]p3: 6234 // [...] If a nested-name-specifier N is declarative and has a 6235 // simple-template-id with a template argument list A that involves a 6236 // template parameter, let T be the template nominated by N without A. 6237 // T shall be a class template. 6238 if (TST->isDependentType() && TST->isTypeAlias()) 6239 Diag(Loc, diag::ext_alias_template_in_declarative_nns) 6240 << SpecLoc.getLocalSourceRange(); 6241 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) { 6242 // C++23 [expr.prim.id.qual]p2: 6243 // [...] A declarative nested-name-specifier shall not have a 6244 // computed-type-specifier. 6245 // 6246 // CWG2858 changed this from 'decltype-specifier' to 6247 // 'computed-type-specifier'. 6248 Diag(Loc, diag::err_computed_type_in_declarative_nns) 6249 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange(); 6250 } 6251 } 6252 } while ((SpecLoc = SpecLoc.getPrefix())); 6253 6254 return false; 6255 } 6256 6257 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 6258 MultiTemplateParamsArg TemplateParamLists) { 6259 // TODO: consider using NameInfo for diagnostic. 6260 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6261 DeclarationName Name = NameInfo.getName(); 6262 6263 // All of these full declarators require an identifier. If it doesn't have 6264 // one, the ParsedFreeStandingDeclSpec action should be used. 6265 if (D.isDecompositionDeclarator()) { 6266 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 6267 } else if (!Name) { 6268 if (!D.isInvalidType()) // Reject this if we think it is valid. 6269 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 6270 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 6271 return nullptr; 6272 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 6273 return nullptr; 6274 6275 DeclContext *DC = CurContext; 6276 if (D.getCXXScopeSpec().isInvalid()) 6277 D.setInvalidType(); 6278 else if (D.getCXXScopeSpec().isSet()) { 6279 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 6280 UPPC_DeclarationQualifier)) 6281 return nullptr; 6282 6283 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 6284 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 6285 if (!DC || isa<EnumDecl>(DC)) { 6286 // If we could not compute the declaration context, it's because the 6287 // declaration context is dependent but does not refer to a class, 6288 // class template, or class template partial specialization. Complain 6289 // and return early, to avoid the coming semantic disaster. 6290 Diag(D.getIdentifierLoc(), 6291 diag::err_template_qualified_declarator_no_match) 6292 << D.getCXXScopeSpec().getScopeRep() 6293 << D.getCXXScopeSpec().getRange(); 6294 return nullptr; 6295 } 6296 bool IsDependentContext = DC->isDependentContext(); 6297 6298 if (!IsDependentContext && 6299 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 6300 return nullptr; 6301 6302 // If a class is incomplete, do not parse entities inside it. 6303 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 6304 Diag(D.getIdentifierLoc(), 6305 diag::err_member_def_undefined_record) 6306 << Name << DC << D.getCXXScopeSpec().getRange(); 6307 return nullptr; 6308 } 6309 if (!D.getDeclSpec().isFriendSpecified()) { 6310 TemplateIdAnnotation *TemplateId = 6311 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6312 ? D.getName().TemplateId 6313 : nullptr; 6314 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, Name, 6315 D.getIdentifierLoc(), TemplateId, 6316 /*IsMemberSpecialization=*/false)) { 6317 if (DC->isRecord()) 6318 return nullptr; 6319 6320 D.setInvalidType(); 6321 } 6322 } 6323 6324 // Check whether we need to rebuild the type of the given 6325 // declaration in the current instantiation. 6326 if (EnteringContext && IsDependentContext && 6327 TemplateParamLists.size() != 0) { 6328 ContextRAII SavedContext(*this, DC); 6329 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 6330 D.setInvalidType(); 6331 } 6332 } 6333 6334 TypeSourceInfo *TInfo = GetTypeForDeclarator(D); 6335 QualType R = TInfo->getType(); 6336 6337 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 6338 UPPC_DeclarationType)) 6339 D.setInvalidType(); 6340 6341 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 6342 forRedeclarationInCurContext()); 6343 6344 // See if this is a redefinition of a variable in the same scope. 6345 if (!D.getCXXScopeSpec().isSet()) { 6346 bool IsLinkageLookup = false; 6347 bool CreateBuiltins = false; 6348 6349 // If the declaration we're planning to build will be a function 6350 // or object with linkage, then look for another declaration with 6351 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 6352 // 6353 // If the declaration we're planning to build will be declared with 6354 // external linkage in the translation unit, create any builtin with 6355 // the same name. 6356 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 6357 /* Do nothing*/; 6358 else if (CurContext->isFunctionOrMethod() && 6359 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 6360 R->isFunctionType())) { 6361 IsLinkageLookup = true; 6362 CreateBuiltins = 6363 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 6364 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 6365 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 6366 CreateBuiltins = true; 6367 6368 if (IsLinkageLookup) { 6369 Previous.clear(LookupRedeclarationWithLinkage); 6370 Previous.setRedeclarationKind( 6371 RedeclarationKind::ForExternalRedeclaration); 6372 } 6373 6374 LookupName(Previous, S, CreateBuiltins); 6375 } else { // Something like "int foo::x;" 6376 LookupQualifiedName(Previous, DC); 6377 6378 // C++ [dcl.meaning]p1: 6379 // When the declarator-id is qualified, the declaration shall refer to a 6380 // previously declared member of the class or namespace to which the 6381 // qualifier refers (or, in the case of a namespace, of an element of the 6382 // inline namespace set of that namespace (7.3.1)) or to a specialization 6383 // thereof; [...] 6384 // 6385 // Note that we already checked the context above, and that we do not have 6386 // enough information to make sure that Previous contains the declaration 6387 // we want to match. For example, given: 6388 // 6389 // class X { 6390 // void f(); 6391 // void f(float); 6392 // }; 6393 // 6394 // void X::f(int) { } // ill-formed 6395 // 6396 // In this case, Previous will point to the overload set 6397 // containing the two f's declared in X, but neither of them 6398 // matches. 6399 6400 RemoveUsingDecls(Previous); 6401 } 6402 6403 if (auto *TPD = Previous.getAsSingle<NamedDecl>(); 6404 TPD && TPD->isTemplateParameter()) { 6405 // Older versions of clang allowed the names of function/variable templates 6406 // to shadow the names of their template parameters. For the compatibility 6407 // purposes we detect such cases and issue a default-to-error warning that 6408 // can be disabled with -Wno-strict-primary-template-shadow. 6409 if (!D.isInvalidType()) { 6410 bool AllowForCompatibility = false; 6411 if (Scope *DeclParent = S->getDeclParent(); 6412 Scope *TemplateParamParent = S->getTemplateParamParent()) { 6413 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) && 6414 TemplateParamParent->isDeclScope(TPD); 6415 } 6416 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD, 6417 AllowForCompatibility); 6418 } 6419 6420 // Just pretend that we didn't see the previous declaration. 6421 Previous.clear(); 6422 } 6423 6424 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 6425 // Forget that the previous declaration is the injected-class-name. 6426 Previous.clear(); 6427 6428 // In C++, the previous declaration we find might be a tag type 6429 // (class or enum). In this case, the new declaration will hide the 6430 // tag type. Note that this applies to functions, function templates, and 6431 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 6432 if (Previous.isSingleTagDecl() && 6433 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6434 (TemplateParamLists.size() == 0 || R->isFunctionType())) 6435 Previous.clear(); 6436 6437 // Check that there are no default arguments other than in the parameters 6438 // of a function declaration (C++ only). 6439 if (getLangOpts().CPlusPlus) 6440 CheckExtraCXXDefaultArguments(D); 6441 6442 /// Get the innermost enclosing declaration scope. 6443 S = S->getDeclParent(); 6444 6445 NamedDecl *New; 6446 6447 bool AddToScope = true; 6448 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 6449 if (TemplateParamLists.size()) { 6450 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 6451 return nullptr; 6452 } 6453 6454 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 6455 } else if (R->isFunctionType()) { 6456 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 6457 TemplateParamLists, 6458 AddToScope); 6459 } else { 6460 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 6461 AddToScope); 6462 } 6463 6464 if (!New) 6465 return nullptr; 6466 6467 // If this has an identifier and is not a function template specialization, 6468 // add it to the scope stack. 6469 if (New->getDeclName() && AddToScope) 6470 PushOnScopeChains(New, S); 6471 6472 if (OpenMP().isInOpenMPDeclareTargetContext()) 6473 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New); 6474 6475 return New; 6476 } 6477 6478 /// Helper method to turn variable array types into constant array 6479 /// types in certain situations which would otherwise be errors (for 6480 /// GCC compatibility). 6481 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6482 ASTContext &Context, 6483 bool &SizeIsNegative, 6484 llvm::APSInt &Oversized) { 6485 // This method tries to turn a variable array into a constant 6486 // array even when the size isn't an ICE. This is necessary 6487 // for compatibility with code that depends on gcc's buggy 6488 // constant expression folding, like struct {char x[(int)(char*)2];} 6489 SizeIsNegative = false; 6490 Oversized = 0; 6491 6492 if (T->isDependentType()) 6493 return QualType(); 6494 6495 QualifierCollector Qs; 6496 const Type *Ty = Qs.strip(T); 6497 6498 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6499 QualType Pointee = PTy->getPointeeType(); 6500 QualType FixedType = 6501 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6502 Oversized); 6503 if (FixedType.isNull()) return FixedType; 6504 FixedType = Context.getPointerType(FixedType); 6505 return Qs.apply(Context, FixedType); 6506 } 6507 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6508 QualType Inner = PTy->getInnerType(); 6509 QualType FixedType = 6510 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6511 Oversized); 6512 if (FixedType.isNull()) return FixedType; 6513 FixedType = Context.getParenType(FixedType); 6514 return Qs.apply(Context, FixedType); 6515 } 6516 6517 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6518 if (!VLATy) 6519 return QualType(); 6520 6521 QualType ElemTy = VLATy->getElementType(); 6522 if (ElemTy->isVariablyModifiedType()) { 6523 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6524 SizeIsNegative, Oversized); 6525 if (ElemTy.isNull()) 6526 return QualType(); 6527 } 6528 6529 Expr::EvalResult Result; 6530 if (!VLATy->getSizeExpr() || 6531 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6532 return QualType(); 6533 6534 llvm::APSInt Res = Result.Val.getInt(); 6535 6536 // Check whether the array size is negative. 6537 if (Res.isSigned() && Res.isNegative()) { 6538 SizeIsNegative = true; 6539 return QualType(); 6540 } 6541 6542 // Check whether the array is too large to be addressed. 6543 unsigned ActiveSizeBits = 6544 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6545 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6546 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6547 : Res.getActiveBits(); 6548 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6549 Oversized = Res; 6550 return QualType(); 6551 } 6552 6553 QualType FoldedArrayType = Context.getConstantArrayType( 6554 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0); 6555 return Qs.apply(Context, FoldedArrayType); 6556 } 6557 6558 static void 6559 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6560 SrcTL = SrcTL.getUnqualifiedLoc(); 6561 DstTL = DstTL.getUnqualifiedLoc(); 6562 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6563 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6564 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6565 DstPTL.getPointeeLoc()); 6566 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6567 return; 6568 } 6569 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6570 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6571 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6572 DstPTL.getInnerLoc()); 6573 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6574 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6575 return; 6576 } 6577 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6578 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6579 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6580 TypeLoc DstElemTL = DstATL.getElementLoc(); 6581 if (VariableArrayTypeLoc SrcElemATL = 6582 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6583 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6584 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6585 } else { 6586 DstElemTL.initializeFullCopy(SrcElemTL); 6587 } 6588 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6589 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6590 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6591 } 6592 6593 /// Helper method to turn variable array types into constant array 6594 /// types in certain situations which would otherwise be errors (for 6595 /// GCC compatibility). 6596 static TypeSourceInfo* 6597 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6598 ASTContext &Context, 6599 bool &SizeIsNegative, 6600 llvm::APSInt &Oversized) { 6601 QualType FixedTy 6602 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6603 SizeIsNegative, Oversized); 6604 if (FixedTy.isNull()) 6605 return nullptr; 6606 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6607 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6608 FixedTInfo->getTypeLoc()); 6609 return FixedTInfo; 6610 } 6611 6612 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6613 QualType &T, SourceLocation Loc, 6614 unsigned FailedFoldDiagID) { 6615 bool SizeIsNegative; 6616 llvm::APSInt Oversized; 6617 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6618 TInfo, Context, SizeIsNegative, Oversized); 6619 if (FixedTInfo) { 6620 Diag(Loc, diag::ext_vla_folded_to_constant); 6621 TInfo = FixedTInfo; 6622 T = FixedTInfo->getType(); 6623 return true; 6624 } 6625 6626 if (SizeIsNegative) 6627 Diag(Loc, diag::err_typecheck_negative_array_size); 6628 else if (Oversized.getBoolValue()) 6629 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6630 else if (FailedFoldDiagID) 6631 Diag(Loc, FailedFoldDiagID); 6632 return false; 6633 } 6634 6635 void 6636 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6637 if (!getLangOpts().CPlusPlus && 6638 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6639 // Don't need to track declarations in the TU in C. 6640 return; 6641 6642 // Note that we have a locally-scoped external with this name. 6643 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6644 } 6645 6646 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6647 // FIXME: We can have multiple results via __attribute__((overloadable)). 6648 auto Result = Context.getExternCContextDecl()->lookup(Name); 6649 return Result.empty() ? nullptr : *Result.begin(); 6650 } 6651 6652 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6653 // FIXME: We should probably indicate the identifier in question to avoid 6654 // confusion for constructs like "virtual int a(), b;" 6655 if (DS.isVirtualSpecified()) 6656 Diag(DS.getVirtualSpecLoc(), 6657 diag::err_virtual_non_function); 6658 6659 if (DS.hasExplicitSpecifier()) 6660 Diag(DS.getExplicitSpecLoc(), 6661 diag::err_explicit_non_function); 6662 6663 if (DS.isNoreturnSpecified()) 6664 Diag(DS.getNoreturnSpecLoc(), 6665 diag::err_noreturn_non_function); 6666 } 6667 6668 NamedDecl* 6669 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6670 TypeSourceInfo *TInfo, LookupResult &Previous) { 6671 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6672 if (D.getCXXScopeSpec().isSet()) { 6673 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6674 << D.getCXXScopeSpec().getRange(); 6675 D.setInvalidType(); 6676 // Pretend we didn't see the scope specifier. 6677 DC = CurContext; 6678 Previous.clear(); 6679 } 6680 6681 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6682 6683 if (D.getDeclSpec().isInlineSpecified()) 6684 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6685 << getLangOpts().CPlusPlus17; 6686 if (D.getDeclSpec().hasConstexprSpecifier()) 6687 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6688 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6689 6690 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) { 6691 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) 6692 Diag(D.getName().StartLocation, 6693 diag::err_deduction_guide_invalid_specifier) 6694 << "typedef"; 6695 else 6696 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6697 << D.getName().getSourceRange(); 6698 return nullptr; 6699 } 6700 6701 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6702 if (!NewTD) return nullptr; 6703 6704 // Handle attributes prior to checking for duplicates in MergeVarDecl 6705 ProcessDeclAttributes(S, NewTD, D); 6706 6707 CheckTypedefForVariablyModifiedType(S, NewTD); 6708 6709 bool Redeclaration = D.isRedeclaration(); 6710 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6711 D.setRedeclaration(Redeclaration); 6712 return ND; 6713 } 6714 6715 void 6716 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6717 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6718 // then it shall have block scope. 6719 // Note that variably modified types must be fixed before merging the decl so 6720 // that redeclarations will match. 6721 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6722 QualType T = TInfo->getType(); 6723 if (T->isVariablyModifiedType()) { 6724 setFunctionHasBranchProtectedScope(); 6725 6726 if (S->getFnParent() == nullptr) { 6727 bool SizeIsNegative; 6728 llvm::APSInt Oversized; 6729 TypeSourceInfo *FixedTInfo = 6730 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6731 SizeIsNegative, 6732 Oversized); 6733 if (FixedTInfo) { 6734 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6735 NewTD->setTypeSourceInfo(FixedTInfo); 6736 } else { 6737 if (SizeIsNegative) 6738 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6739 else if (T->isVariableArrayType()) 6740 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6741 else if (Oversized.getBoolValue()) 6742 Diag(NewTD->getLocation(), diag::err_array_too_large) 6743 << toString(Oversized, 10); 6744 else 6745 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6746 NewTD->setInvalidDecl(); 6747 } 6748 } 6749 } 6750 } 6751 6752 NamedDecl* 6753 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6754 LookupResult &Previous, bool &Redeclaration) { 6755 6756 // Find the shadowed declaration before filtering for scope. 6757 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6758 6759 // Merge the decl with the existing one if appropriate. If the decl is 6760 // in an outer scope, it isn't the same thing. 6761 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6762 /*AllowInlineNamespace*/false); 6763 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6764 if (!Previous.empty()) { 6765 Redeclaration = true; 6766 MergeTypedefNameDecl(S, NewTD, Previous); 6767 } else { 6768 inferGslPointerAttribute(NewTD); 6769 } 6770 6771 if (ShadowedDecl && !Redeclaration) 6772 CheckShadow(NewTD, ShadowedDecl, Previous); 6773 6774 // If this is the C FILE type, notify the AST context. 6775 if (IdentifierInfo *II = NewTD->getIdentifier()) 6776 if (!NewTD->isInvalidDecl() && 6777 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6778 switch (II->getNotableIdentifierID()) { 6779 case tok::NotableIdentifierKind::FILE: 6780 Context.setFILEDecl(NewTD); 6781 break; 6782 case tok::NotableIdentifierKind::jmp_buf: 6783 Context.setjmp_bufDecl(NewTD); 6784 break; 6785 case tok::NotableIdentifierKind::sigjmp_buf: 6786 Context.setsigjmp_bufDecl(NewTD); 6787 break; 6788 case tok::NotableIdentifierKind::ucontext_t: 6789 Context.setucontext_tDecl(NewTD); 6790 break; 6791 case tok::NotableIdentifierKind::float_t: 6792 case tok::NotableIdentifierKind::double_t: 6793 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context)); 6794 break; 6795 default: 6796 break; 6797 } 6798 } 6799 6800 return NewTD; 6801 } 6802 6803 /// Determines whether the given declaration is an out-of-scope 6804 /// previous declaration. 6805 /// 6806 /// This routine should be invoked when name lookup has found a 6807 /// previous declaration (PrevDecl) that is not in the scope where a 6808 /// new declaration by the same name is being introduced. If the new 6809 /// declaration occurs in a local scope, previous declarations with 6810 /// linkage may still be considered previous declarations (C99 6811 /// 6.2.2p4-5, C++ [basic.link]p6). 6812 /// 6813 /// \param PrevDecl the previous declaration found by name 6814 /// lookup 6815 /// 6816 /// \param DC the context in which the new declaration is being 6817 /// declared. 6818 /// 6819 /// \returns true if PrevDecl is an out-of-scope previous declaration 6820 /// for a new delcaration with the same name. 6821 static bool 6822 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6823 ASTContext &Context) { 6824 if (!PrevDecl) 6825 return false; 6826 6827 if (!PrevDecl->hasLinkage()) 6828 return false; 6829 6830 if (Context.getLangOpts().CPlusPlus) { 6831 // C++ [basic.link]p6: 6832 // If there is a visible declaration of an entity with linkage 6833 // having the same name and type, ignoring entities declared 6834 // outside the innermost enclosing namespace scope, the block 6835 // scope declaration declares that same entity and receives the 6836 // linkage of the previous declaration. 6837 DeclContext *OuterContext = DC->getRedeclContext(); 6838 if (!OuterContext->isFunctionOrMethod()) 6839 // This rule only applies to block-scope declarations. 6840 return false; 6841 6842 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6843 if (PrevOuterContext->isRecord()) 6844 // We found a member function: ignore it. 6845 return false; 6846 6847 // Find the innermost enclosing namespace for the new and 6848 // previous declarations. 6849 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6850 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6851 6852 // The previous declaration is in a different namespace, so it 6853 // isn't the same function. 6854 if (!OuterContext->Equals(PrevOuterContext)) 6855 return false; 6856 } 6857 6858 return true; 6859 } 6860 6861 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6862 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6863 if (!SS.isSet()) return; 6864 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6865 } 6866 6867 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6868 if (Decl->getType().hasAddressSpace()) 6869 return; 6870 if (Decl->getType()->isDependentType()) 6871 return; 6872 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6873 QualType Type = Var->getType(); 6874 if (Type->isSamplerT() || Type->isVoidType()) 6875 return; 6876 LangAS ImplAS = LangAS::opencl_private; 6877 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 6878 // __opencl_c_program_scope_global_variables feature, the address space 6879 // for a variable at program scope or a static or extern variable inside 6880 // a function are inferred to be __global. 6881 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 6882 Var->hasGlobalStorage()) 6883 ImplAS = LangAS::opencl_global; 6884 // If the original type from a decayed type is an array type and that array 6885 // type has no address space yet, deduce it now. 6886 if (auto DT = dyn_cast<DecayedType>(Type)) { 6887 auto OrigTy = DT->getOriginalType(); 6888 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6889 // Add the address space to the original array type and then propagate 6890 // that to the element type through `getAsArrayType`. 6891 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6892 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6893 // Re-generate the decayed type. 6894 Type = Context.getDecayedType(OrigTy); 6895 } 6896 } 6897 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6898 // Apply any qualifiers (including address space) from the array type to 6899 // the element type. This implements C99 6.7.3p8: "If the specification of 6900 // an array type includes any type qualifiers, the element type is so 6901 // qualified, not the array type." 6902 if (Type->isArrayType()) 6903 Type = QualType(Context.getAsArrayType(Type), 0); 6904 Decl->setType(Type); 6905 } 6906 } 6907 6908 static void checkWeakAttr(Sema &S, NamedDecl &ND) { 6909 // 'weak' only applies to declarations with external linkage. 6910 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6911 if (!ND.isExternallyVisible()) { 6912 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6913 ND.dropAttr<WeakAttr>(); 6914 } 6915 } 6916 } 6917 6918 static void checkWeakRefAttr(Sema &S, NamedDecl &ND) { 6919 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6920 if (ND.isExternallyVisible()) { 6921 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6922 ND.dropAttrs<WeakRefAttr, AliasAttr>(); 6923 } 6924 } 6925 } 6926 6927 static void checkAliasAttr(Sema &S, NamedDecl &ND) { 6928 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6929 if (VD->hasInit()) { 6930 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6931 assert(VD->isThisDeclarationADefinition() && 6932 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6933 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6934 VD->dropAttr<AliasAttr>(); 6935 } 6936 } 6937 } 6938 } 6939 6940 static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) { 6941 // 'selectany' only applies to externally visible variable declarations. 6942 // It does not apply to functions. 6943 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6944 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6945 S.Diag(Attr->getLocation(), 6946 diag::err_attribute_selectany_non_extern_data); 6947 ND.dropAttr<SelectAnyAttr>(); 6948 } 6949 } 6950 } 6951 6952 static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) { 6953 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) { 6954 if (!ND.isExternallyVisible()) 6955 S.Diag(Attr->getLocation(), 6956 diag::warn_attribute_hybrid_patchable_non_extern); 6957 } 6958 } 6959 6960 static void checkInheritableAttr(Sema &S, NamedDecl &ND) { 6961 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6962 auto *VD = dyn_cast<VarDecl>(&ND); 6963 bool IsAnonymousNS = false; 6964 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6965 if (VD) { 6966 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6967 while (NS && !IsAnonymousNS) { 6968 IsAnonymousNS = NS->isAnonymousNamespace(); 6969 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6970 } 6971 } 6972 // dll attributes require external linkage. Static locals may have external 6973 // linkage but still cannot be explicitly imported or exported. 6974 // In Microsoft mode, a variable defined in anonymous namespace must have 6975 // external linkage in order to be exported. 6976 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6977 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6978 (!AnonNSInMicrosoftMode && 6979 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6980 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6981 << &ND << Attr; 6982 ND.setInvalidDecl(); 6983 } 6984 } 6985 } 6986 6987 static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) { 6988 // Check the attributes on the function type and function params, if any. 6989 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6990 FD = FD->getMostRecentDecl(); 6991 // Don't declare this variable in the second operand of the for-statement; 6992 // GCC miscompiles that by ending its lifetime before evaluating the 6993 // third operand. See gcc.gnu.org/PR86769. 6994 AttributedTypeLoc ATL; 6995 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6996 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6997 TL = ATL.getModifiedLoc()) { 6998 // The [[lifetimebound]] attribute can be applied to the implicit object 6999 // parameter of a non-static member function (other than a ctor or dtor) 7000 // by applying it to the function type. 7001 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 7002 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 7003 int NoImplicitObjectError = -1; 7004 if (!MD) 7005 NoImplicitObjectError = 0; 7006 else if (MD->isStatic()) 7007 NoImplicitObjectError = 1; 7008 else if (MD->isExplicitObjectMemberFunction()) 7009 NoImplicitObjectError = 2; 7010 if (NoImplicitObjectError != -1) { 7011 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 7012 << NoImplicitObjectError << A->getRange(); 7013 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 7014 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 7015 << isa<CXXDestructorDecl>(MD) << A->getRange(); 7016 } else if (MD->getReturnType()->isVoidType()) { 7017 S.Diag( 7018 MD->getLocation(), 7019 diag:: 7020 err_lifetimebound_implicit_object_parameter_void_return_type); 7021 } 7022 } 7023 } 7024 7025 for (unsigned int I = 0; I < FD->getNumParams(); ++I) { 7026 const ParmVarDecl *P = FD->getParamDecl(I); 7027 7028 // The [[lifetimebound]] attribute can be applied to a function parameter 7029 // only if the function returns a value. 7030 if (auto *A = P->getAttr<LifetimeBoundAttr>()) { 7031 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) { 7032 S.Diag(A->getLocation(), 7033 diag::err_lifetimebound_parameter_void_return_type); 7034 } 7035 } 7036 } 7037 } 7038 } 7039 7040 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 7041 // Ensure that an auto decl is deduced otherwise the checks below might cache 7042 // the wrong linkage. 7043 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 7044 7045 checkWeakAttr(S, ND); 7046 checkWeakRefAttr(S, ND); 7047 checkAliasAttr(S, ND); 7048 checkSelectAnyAttr(S, ND); 7049 checkHybridPatchableAttr(S, ND); 7050 checkInheritableAttr(S, ND); 7051 checkLifetimeBoundAttr(S, ND); 7052 } 7053 7054 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 7055 NamedDecl *NewDecl, 7056 bool IsSpecialization, 7057 bool IsDefinition) { 7058 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 7059 return; 7060 7061 bool IsTemplate = false; 7062 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 7063 OldDecl = OldTD->getTemplatedDecl(); 7064 IsTemplate = true; 7065 if (!IsSpecialization) 7066 IsDefinition = false; 7067 } 7068 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 7069 NewDecl = NewTD->getTemplatedDecl(); 7070 IsTemplate = true; 7071 } 7072 7073 if (!OldDecl || !NewDecl) 7074 return; 7075 7076 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 7077 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 7078 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 7079 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 7080 7081 // dllimport and dllexport are inheritable attributes so we have to exclude 7082 // inherited attribute instances. 7083 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 7084 (NewExportAttr && !NewExportAttr->isInherited()); 7085 7086 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 7087 // the only exception being explicit specializations. 7088 // Implicitly generated declarations are also excluded for now because there 7089 // is no other way to switch these to use dllimport or dllexport. 7090 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 7091 7092 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 7093 // Allow with a warning for free functions and global variables. 7094 bool JustWarn = false; 7095 if (!OldDecl->isCXXClassMember()) { 7096 auto *VD = dyn_cast<VarDecl>(OldDecl); 7097 if (VD && !VD->getDescribedVarTemplate()) 7098 JustWarn = true; 7099 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 7100 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 7101 JustWarn = true; 7102 } 7103 7104 // We cannot change a declaration that's been used because IR has already 7105 // been emitted. Dllimported functions will still work though (modulo 7106 // address equality) as they can use the thunk. 7107 if (OldDecl->isUsed()) 7108 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 7109 JustWarn = false; 7110 7111 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 7112 : diag::err_attribute_dll_redeclaration; 7113 S.Diag(NewDecl->getLocation(), DiagID) 7114 << NewDecl 7115 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 7116 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 7117 if (!JustWarn) { 7118 NewDecl->setInvalidDecl(); 7119 return; 7120 } 7121 } 7122 7123 // A redeclaration is not allowed to drop a dllimport attribute, the only 7124 // exceptions being inline function definitions (except for function 7125 // templates), local extern declarations, qualified friend declarations or 7126 // special MSVC extension: in the last case, the declaration is treated as if 7127 // it were marked dllexport. 7128 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 7129 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 7130 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 7131 // Ignore static data because out-of-line definitions are diagnosed 7132 // separately. 7133 IsStaticDataMember = VD->isStaticDataMember(); 7134 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 7135 VarDecl::DeclarationOnly; 7136 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 7137 IsInline = FD->isInlined(); 7138 IsQualifiedFriend = FD->getQualifier() && 7139 FD->getFriendObjectKind() == Decl::FOK_Declared; 7140 } 7141 7142 if (OldImportAttr && !HasNewAttr && 7143 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 7144 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 7145 if (IsMicrosoftABI && IsDefinition) { 7146 if (IsSpecialization) { 7147 S.Diag( 7148 NewDecl->getLocation(), 7149 diag::err_attribute_dllimport_function_specialization_definition); 7150 S.Diag(OldImportAttr->getLocation(), diag::note_attribute); 7151 NewDecl->dropAttr<DLLImportAttr>(); 7152 } else { 7153 S.Diag(NewDecl->getLocation(), 7154 diag::warn_redeclaration_without_import_attribute) 7155 << NewDecl; 7156 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 7157 NewDecl->dropAttr<DLLImportAttr>(); 7158 NewDecl->addAttr(DLLExportAttr::CreateImplicit( 7159 S.Context, NewImportAttr->getRange())); 7160 } 7161 } else if (IsMicrosoftABI && IsSpecialization) { 7162 assert(!IsDefinition); 7163 // MSVC allows this. Keep the inherited attribute. 7164 } else { 7165 S.Diag(NewDecl->getLocation(), 7166 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 7167 << NewDecl << OldImportAttr; 7168 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 7169 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 7170 OldDecl->dropAttr<DLLImportAttr>(); 7171 NewDecl->dropAttr<DLLImportAttr>(); 7172 } 7173 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 7174 // In MinGW, seeing a function declared inline drops the dllimport 7175 // attribute. 7176 OldDecl->dropAttr<DLLImportAttr>(); 7177 NewDecl->dropAttr<DLLImportAttr>(); 7178 S.Diag(NewDecl->getLocation(), 7179 diag::warn_dllimport_dropped_from_inline_function) 7180 << NewDecl << OldImportAttr; 7181 } 7182 7183 // A specialization of a class template member function is processed here 7184 // since it's a redeclaration. If the parent class is dllexport, the 7185 // specialization inherits that attribute. This doesn't happen automatically 7186 // since the parent class isn't instantiated until later. 7187 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 7188 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 7189 !NewImportAttr && !NewExportAttr) { 7190 if (const DLLExportAttr *ParentExportAttr = 7191 MD->getParent()->getAttr<DLLExportAttr>()) { 7192 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 7193 NewAttr->setInherited(true); 7194 NewDecl->addAttr(NewAttr); 7195 } 7196 } 7197 } 7198 } 7199 7200 /// Given that we are within the definition of the given function, 7201 /// will that definition behave like C99's 'inline', where the 7202 /// definition is discarded except for optimization purposes? 7203 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 7204 // Try to avoid calling GetGVALinkageForFunction. 7205 7206 // All cases of this require the 'inline' keyword. 7207 if (!FD->isInlined()) return false; 7208 7209 // This is only possible in C++ with the gnu_inline attribute. 7210 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 7211 return false; 7212 7213 // Okay, go ahead and call the relatively-more-expensive function. 7214 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 7215 } 7216 7217 /// Determine whether a variable is extern "C" prior to attaching 7218 /// an initializer. We can't just call isExternC() here, because that 7219 /// will also compute and cache whether the declaration is externally 7220 /// visible, which might change when we attach the initializer. 7221 /// 7222 /// This can only be used if the declaration is known to not be a 7223 /// redeclaration of an internal linkage declaration. 7224 /// 7225 /// For instance: 7226 /// 7227 /// auto x = []{}; 7228 /// 7229 /// Attaching the initializer here makes this declaration not externally 7230 /// visible, because its type has internal linkage. 7231 /// 7232 /// FIXME: This is a hack. 7233 template<typename T> 7234 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 7235 if (S.getLangOpts().CPlusPlus) { 7236 // In C++, the overloadable attribute negates the effects of extern "C". 7237 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 7238 return false; 7239 7240 // So do CUDA's host/device attributes. 7241 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 7242 D->template hasAttr<CUDAHostAttr>())) 7243 return false; 7244 } 7245 return D->isExternC(); 7246 } 7247 7248 static bool shouldConsiderLinkage(const VarDecl *VD) { 7249 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 7250 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 7251 isa<OMPDeclareMapperDecl>(DC)) 7252 return VD->hasExternalStorage(); 7253 if (DC->isFileContext()) 7254 return true; 7255 if (DC->isRecord()) 7256 return false; 7257 if (DC->getDeclKind() == Decl::HLSLBuffer) 7258 return false; 7259 7260 if (isa<RequiresExprBodyDecl>(DC)) 7261 return false; 7262 llvm_unreachable("Unexpected context"); 7263 } 7264 7265 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 7266 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 7267 if (DC->isFileContext() || DC->isFunctionOrMethod() || 7268 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 7269 return true; 7270 if (DC->isRecord()) 7271 return false; 7272 llvm_unreachable("Unexpected context"); 7273 } 7274 7275 static bool hasParsedAttr(Scope *S, const Declarator &PD, 7276 ParsedAttr::Kind Kind) { 7277 // Check decl attributes on the DeclSpec. 7278 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 7279 return true; 7280 7281 // Walk the declarator structure, checking decl attributes that were in a type 7282 // position to the decl itself. 7283 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 7284 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 7285 return true; 7286 } 7287 7288 // Finally, check attributes on the decl itself. 7289 return PD.getAttributes().hasAttribute(Kind) || 7290 PD.getDeclarationAttributes().hasAttribute(Kind); 7291 } 7292 7293 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 7294 if (!DC->isFunctionOrMethod()) 7295 return false; 7296 7297 // If this is a local extern function or variable declared within a function 7298 // template, don't add it into the enclosing namespace scope until it is 7299 // instantiated; it might have a dependent type right now. 7300 if (DC->isDependentContext()) 7301 return true; 7302 7303 // C++11 [basic.link]p7: 7304 // When a block scope declaration of an entity with linkage is not found to 7305 // refer to some other declaration, then that entity is a member of the 7306 // innermost enclosing namespace. 7307 // 7308 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 7309 // semantically-enclosing namespace, not a lexically-enclosing one. 7310 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 7311 DC = DC->getParent(); 7312 return true; 7313 } 7314 7315 /// Returns true if given declaration has external C language linkage. 7316 static bool isDeclExternC(const Decl *D) { 7317 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 7318 return FD->isExternC(); 7319 if (const auto *VD = dyn_cast<VarDecl>(D)) 7320 return VD->isExternC(); 7321 7322 llvm_unreachable("Unknown type of decl!"); 7323 } 7324 7325 /// Returns true if there hasn't been any invalid type diagnosed. 7326 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 7327 DeclContext *DC = NewVD->getDeclContext(); 7328 QualType R = NewVD->getType(); 7329 7330 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 7331 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 7332 // argument. 7333 if (R->isImageType() || R->isPipeType()) { 7334 Se.Diag(NewVD->getLocation(), 7335 diag::err_opencl_type_can_only_be_used_as_function_parameter) 7336 << R; 7337 NewVD->setInvalidDecl(); 7338 return false; 7339 } 7340 7341 // OpenCL v1.2 s6.9.r: 7342 // The event type cannot be used to declare a program scope variable. 7343 // OpenCL v2.0 s6.9.q: 7344 // The clk_event_t and reserve_id_t types cannot be declared in program 7345 // scope. 7346 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 7347 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 7348 Se.Diag(NewVD->getLocation(), 7349 diag::err_invalid_type_for_program_scope_var) 7350 << R; 7351 NewVD->setInvalidDecl(); 7352 return false; 7353 } 7354 } 7355 7356 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 7357 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 7358 Se.getLangOpts())) { 7359 QualType NR = R.getCanonicalType(); 7360 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 7361 NR->isReferenceType()) { 7362 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 7363 NR->isFunctionReferenceType()) { 7364 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 7365 << NR->isReferenceType(); 7366 NewVD->setInvalidDecl(); 7367 return false; 7368 } 7369 NR = NR->getPointeeType(); 7370 } 7371 } 7372 7373 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 7374 Se.getLangOpts())) { 7375 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 7376 // half array type (unless the cl_khr_fp16 extension is enabled). 7377 if (Se.Context.getBaseElementType(R)->isHalfType()) { 7378 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 7379 NewVD->setInvalidDecl(); 7380 return false; 7381 } 7382 } 7383 7384 // OpenCL v1.2 s6.9.r: 7385 // The event type cannot be used with the __local, __constant and __global 7386 // address space qualifiers. 7387 if (R->isEventT()) { 7388 if (R.getAddressSpace() != LangAS::opencl_private) { 7389 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 7390 NewVD->setInvalidDecl(); 7391 return false; 7392 } 7393 } 7394 7395 if (R->isSamplerT()) { 7396 // OpenCL v1.2 s6.9.b p4: 7397 // The sampler type cannot be used with the __local and __global address 7398 // space qualifiers. 7399 if (R.getAddressSpace() == LangAS::opencl_local || 7400 R.getAddressSpace() == LangAS::opencl_global) { 7401 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 7402 NewVD->setInvalidDecl(); 7403 } 7404 7405 // OpenCL v1.2 s6.12.14.1: 7406 // A global sampler must be declared with either the constant address 7407 // space qualifier or with the const qualifier. 7408 if (DC->isTranslationUnit() && 7409 !(R.getAddressSpace() == LangAS::opencl_constant || 7410 R.isConstQualified())) { 7411 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 7412 NewVD->setInvalidDecl(); 7413 } 7414 if (NewVD->isInvalidDecl()) 7415 return false; 7416 } 7417 7418 return true; 7419 } 7420 7421 template <typename AttrTy> 7422 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 7423 const TypedefNameDecl *TND = TT->getDecl(); 7424 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 7425 AttrTy *Clone = Attribute->clone(S.Context); 7426 Clone->setInherited(true); 7427 D->addAttr(Clone); 7428 } 7429 } 7430 7431 // This function emits warning and a corresponding note based on the 7432 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable 7433 // declarations of an annotated type must be const qualified. 7434 static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) { 7435 QualType VarType = VD->getType().getCanonicalType(); 7436 7437 // Ignore local declarations (for now) and those with const qualification. 7438 // TODO: Local variables should not be allowed if their type declaration has 7439 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch. 7440 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified()) 7441 return; 7442 7443 if (VarType->isArrayType()) { 7444 // Retrieve element type for array declarations. 7445 VarType = S.getASTContext().getBaseElementType(VarType); 7446 } 7447 7448 const RecordDecl *RD = VarType->getAsRecordDecl(); 7449 7450 // Check if the record declaration is present and if it has any attributes. 7451 if (RD == nullptr) 7452 return; 7453 7454 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) { 7455 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD; 7456 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement); 7457 return; 7458 } 7459 } 7460 7461 // Checks if VD is declared at global scope or with C language linkage. 7462 static bool isMainVar(DeclarationName Name, VarDecl *VD) { 7463 return Name.getAsIdentifierInfo() && 7464 Name.getAsIdentifierInfo()->isStr("main") && 7465 !VD->getDescribedVarTemplate() && 7466 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() || 7467 VD->isExternC()); 7468 } 7469 7470 NamedDecl *Sema::ActOnVariableDeclarator( 7471 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 7472 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 7473 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 7474 QualType R = TInfo->getType(); 7475 DeclarationName Name = GetNameForDeclarator(D).getName(); 7476 7477 IdentifierInfo *II = Name.getAsIdentifierInfo(); 7478 bool IsPlaceholderVariable = false; 7479 7480 if (D.isDecompositionDeclarator()) { 7481 // Take the name of the first declarator as our name for diagnostic 7482 // purposes. 7483 auto &Decomp = D.getDecompositionDeclarator(); 7484 if (!Decomp.bindings().empty()) { 7485 II = Decomp.bindings()[0].Name; 7486 Name = II; 7487 } 7488 } else if (!II) { 7489 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 7490 return nullptr; 7491 } 7492 7493 7494 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 7495 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 7496 7497 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) && 7498 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) { 7499 IsPlaceholderVariable = true; 7500 if (!Previous.empty()) { 7501 NamedDecl *PrevDecl = *Previous.begin(); 7502 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals( 7503 DC->getRedeclContext()); 7504 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) 7505 DiagPlaceholderVariableDefinition(D.getIdentifierLoc()); 7506 } 7507 } 7508 7509 // dllimport globals without explicit storage class are treated as extern. We 7510 // have to change the storage class this early to get the right DeclContext. 7511 if (SC == SC_None && !DC->isRecord() && 7512 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 7513 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 7514 SC = SC_Extern; 7515 7516 DeclContext *OriginalDC = DC; 7517 bool IsLocalExternDecl = SC == SC_Extern && 7518 adjustContextForLocalExternDecl(DC); 7519 7520 if (SCSpec == DeclSpec::SCS_mutable) { 7521 // mutable can only appear on non-static class members, so it's always 7522 // an error here 7523 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 7524 D.setInvalidType(); 7525 SC = SC_None; 7526 } 7527 7528 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 7529 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 7530 D.getDeclSpec().getStorageClassSpecLoc())) { 7531 // In C++11, the 'register' storage class specifier is deprecated. 7532 // Suppress the warning in system macros, it's used in macros in some 7533 // popular C system headers, such as in glibc's htonl() macro. 7534 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7535 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 7536 : diag::warn_deprecated_register) 7537 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7538 } 7539 7540 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 7541 7542 if (!DC->isRecord() && S->getFnParent() == nullptr) { 7543 // C99 6.9p2: The storage-class specifiers auto and register shall not 7544 // appear in the declaration specifiers in an external declaration. 7545 // Global Register+Asm is a GNU extension we support. 7546 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 7547 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 7548 D.setInvalidType(); 7549 } 7550 } 7551 7552 // If this variable has a VLA type and an initializer, try to 7553 // fold to a constant-sized type. This is otherwise invalid. 7554 if (D.hasInitializer() && R->isVariableArrayType()) 7555 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7556 /*DiagID=*/0); 7557 7558 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) { 7559 const AutoType *AT = TL.getTypePtr(); 7560 CheckConstrainedAuto(AT, TL.getConceptNameLoc()); 7561 } 7562 7563 bool IsMemberSpecialization = false; 7564 bool IsVariableTemplateSpecialization = false; 7565 bool IsPartialSpecialization = false; 7566 bool IsVariableTemplate = false; 7567 VarDecl *NewVD = nullptr; 7568 VarTemplateDecl *NewTemplate = nullptr; 7569 TemplateParameterList *TemplateParams = nullptr; 7570 if (!getLangOpts().CPlusPlus) { 7571 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7572 II, R, TInfo, SC); 7573 7574 if (R->getContainedDeducedType()) 7575 ParsingInitForAutoVars.insert(NewVD); 7576 7577 if (D.isInvalidType()) 7578 NewVD->setInvalidDecl(); 7579 7580 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7581 NewVD->hasLocalStorage()) 7582 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7583 NTCUC_AutoVar, NTCUK_Destruct); 7584 } else { 7585 bool Invalid = false; 7586 // Match up the template parameter lists with the scope specifier, then 7587 // determine whether we have a template or a template specialization. 7588 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7589 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7590 D.getCXXScopeSpec(), 7591 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7592 ? D.getName().TemplateId 7593 : nullptr, 7594 TemplateParamLists, 7595 /*never a friend*/ false, IsMemberSpecialization, Invalid); 7596 7597 if (TemplateParams) { 7598 if (DC->isDependentContext()) { 7599 ContextRAII SavedContext(*this, DC); 7600 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7601 Invalid = true; 7602 } 7603 7604 if (!TemplateParams->size() && 7605 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7606 // There is an extraneous 'template<>' for this variable. Complain 7607 // about it, but allow the declaration of the variable. 7608 Diag(TemplateParams->getTemplateLoc(), 7609 diag::err_template_variable_noparams) 7610 << II 7611 << SourceRange(TemplateParams->getTemplateLoc(), 7612 TemplateParams->getRAngleLoc()); 7613 TemplateParams = nullptr; 7614 } else { 7615 // Check that we can declare a template here. 7616 if (CheckTemplateDeclScope(S, TemplateParams)) 7617 return nullptr; 7618 7619 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7620 // This is an explicit specialization or a partial specialization. 7621 IsVariableTemplateSpecialization = true; 7622 IsPartialSpecialization = TemplateParams->size() > 0; 7623 } else { // if (TemplateParams->size() > 0) 7624 // This is a template declaration. 7625 IsVariableTemplate = true; 7626 7627 // Only C++1y supports variable templates (N3651). 7628 Diag(D.getIdentifierLoc(), 7629 getLangOpts().CPlusPlus14 7630 ? diag::warn_cxx11_compat_variable_template 7631 : diag::ext_variable_template); 7632 } 7633 } 7634 } else { 7635 // Check that we can declare a member specialization here. 7636 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7637 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7638 return nullptr; 7639 assert((Invalid || 7640 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7641 "should have a 'template<>' for this decl"); 7642 } 7643 7644 bool IsExplicitSpecialization = 7645 IsVariableTemplateSpecialization && !IsPartialSpecialization; 7646 7647 // C++ [temp.expl.spec]p2: 7648 // The declaration in an explicit-specialization shall not be an 7649 // export-declaration. An explicit specialization shall not use a 7650 // storage-class-specifier other than thread_local. 7651 // 7652 // We use the storage-class-specifier from DeclSpec because we may have 7653 // added implicit 'extern' for declarations with __declspec(dllimport)! 7654 if (SCSpec != DeclSpec::SCS_unspecified && 7655 (IsExplicitSpecialization || IsMemberSpecialization)) { 7656 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7657 diag::ext_explicit_specialization_storage_class) 7658 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7659 } 7660 7661 if (CurContext->isRecord()) { 7662 if (SC == SC_Static) { 7663 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7664 // Walk up the enclosing DeclContexts to check for any that are 7665 // incompatible with static data members. 7666 const DeclContext *FunctionOrMethod = nullptr; 7667 const CXXRecordDecl *AnonStruct = nullptr; 7668 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7669 if (Ctxt->isFunctionOrMethod()) { 7670 FunctionOrMethod = Ctxt; 7671 break; 7672 } 7673 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7674 if (ParentDecl && !ParentDecl->getDeclName()) { 7675 AnonStruct = ParentDecl; 7676 break; 7677 } 7678 } 7679 if (FunctionOrMethod) { 7680 // C++ [class.static.data]p5: A local class shall not have static 7681 // data members. 7682 Diag(D.getIdentifierLoc(), 7683 diag::err_static_data_member_not_allowed_in_local_class) 7684 << Name << RD->getDeclName() 7685 << llvm::to_underlying(RD->getTagKind()); 7686 } else if (AnonStruct) { 7687 // C++ [class.static.data]p4: Unnamed classes and classes contained 7688 // directly or indirectly within unnamed classes shall not contain 7689 // static data members. 7690 Diag(D.getIdentifierLoc(), 7691 diag::err_static_data_member_not_allowed_in_anon_struct) 7692 << Name << llvm::to_underlying(AnonStruct->getTagKind()); 7693 Invalid = true; 7694 } else if (RD->isUnion()) { 7695 // C++98 [class.union]p1: If a union contains a static data member, 7696 // the program is ill-formed. C++11 drops this restriction. 7697 Diag(D.getIdentifierLoc(), 7698 getLangOpts().CPlusPlus11 7699 ? diag::warn_cxx98_compat_static_data_member_in_union 7700 : diag::ext_static_data_member_in_union) 7701 << Name; 7702 } 7703 } 7704 } else if (IsVariableTemplate || IsPartialSpecialization) { 7705 // There is no such thing as a member field template. 7706 Diag(D.getIdentifierLoc(), diag::err_template_member) 7707 << II << TemplateParams->getSourceRange(); 7708 // Recover by pretending this is a static data member template. 7709 SC = SC_Static; 7710 } 7711 } else if (DC->isRecord()) { 7712 // This is an out-of-line definition of a static data member. 7713 switch (SC) { 7714 case SC_None: 7715 break; 7716 case SC_Static: 7717 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7718 diag::err_static_out_of_line) 7719 << FixItHint::CreateRemoval( 7720 D.getDeclSpec().getStorageClassSpecLoc()); 7721 break; 7722 case SC_Auto: 7723 case SC_Register: 7724 case SC_Extern: 7725 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7726 // to names of variables declared in a block or to function parameters. 7727 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7728 // of class members 7729 7730 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7731 diag::err_storage_class_for_static_member) 7732 << FixItHint::CreateRemoval( 7733 D.getDeclSpec().getStorageClassSpecLoc()); 7734 break; 7735 case SC_PrivateExtern: 7736 llvm_unreachable("C storage class in c++!"); 7737 } 7738 } 7739 7740 if (IsVariableTemplateSpecialization) { 7741 SourceLocation TemplateKWLoc = 7742 TemplateParamLists.size() > 0 7743 ? TemplateParamLists[0]->getTemplateLoc() 7744 : SourceLocation(); 7745 DeclResult Res = ActOnVarTemplateSpecialization( 7746 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC, 7747 IsPartialSpecialization); 7748 if (Res.isInvalid()) 7749 return nullptr; 7750 NewVD = cast<VarDecl>(Res.get()); 7751 AddToScope = false; 7752 } else if (D.isDecompositionDeclarator()) { 7753 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7754 D.getIdentifierLoc(), R, TInfo, SC, 7755 Bindings); 7756 } else 7757 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7758 D.getIdentifierLoc(), II, R, TInfo, SC); 7759 7760 // If this is supposed to be a variable template, create it as such. 7761 if (IsVariableTemplate) { 7762 NewTemplate = 7763 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7764 TemplateParams, NewVD); 7765 NewVD->setDescribedVarTemplate(NewTemplate); 7766 } 7767 7768 // If this decl has an auto type in need of deduction, make a note of the 7769 // Decl so we can diagnose uses of it in its own initializer. 7770 if (R->getContainedDeducedType()) 7771 ParsingInitForAutoVars.insert(NewVD); 7772 7773 if (D.isInvalidType() || Invalid) { 7774 NewVD->setInvalidDecl(); 7775 if (NewTemplate) 7776 NewTemplate->setInvalidDecl(); 7777 } 7778 7779 SetNestedNameSpecifier(*this, NewVD, D); 7780 7781 // If we have any template parameter lists that don't directly belong to 7782 // the variable (matching the scope specifier), store them. 7783 // An explicit variable template specialization does not own any template 7784 // parameter lists. 7785 unsigned VDTemplateParamLists = 7786 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0; 7787 if (TemplateParamLists.size() > VDTemplateParamLists) 7788 NewVD->setTemplateParameterListsInfo( 7789 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7790 } 7791 7792 if (D.getDeclSpec().isInlineSpecified()) { 7793 if (!getLangOpts().CPlusPlus) { 7794 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7795 << 0; 7796 } else if (CurContext->isFunctionOrMethod()) { 7797 // 'inline' is not allowed on block scope variable declaration. 7798 Diag(D.getDeclSpec().getInlineSpecLoc(), 7799 diag::err_inline_declaration_block_scope) << Name 7800 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7801 } else { 7802 Diag(D.getDeclSpec().getInlineSpecLoc(), 7803 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7804 : diag::ext_inline_variable); 7805 NewVD->setInlineSpecified(); 7806 } 7807 } 7808 7809 // Set the lexical context. If the declarator has a C++ scope specifier, the 7810 // lexical context will be different from the semantic context. 7811 NewVD->setLexicalDeclContext(CurContext); 7812 if (NewTemplate) 7813 NewTemplate->setLexicalDeclContext(CurContext); 7814 7815 if (IsLocalExternDecl) { 7816 if (D.isDecompositionDeclarator()) 7817 for (auto *B : Bindings) 7818 B->setLocalExternDecl(); 7819 else 7820 NewVD->setLocalExternDecl(); 7821 } 7822 7823 bool EmitTLSUnsupportedError = false; 7824 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7825 // C++11 [dcl.stc]p4: 7826 // When thread_local is applied to a variable of block scope the 7827 // storage-class-specifier static is implied if it does not appear 7828 // explicitly. 7829 // Core issue: 'static' is not implied if the variable is declared 7830 // 'extern'. 7831 if (NewVD->hasLocalStorage() && 7832 (SCSpec != DeclSpec::SCS_unspecified || 7833 TSCS != DeclSpec::TSCS_thread_local || 7834 !DC->isFunctionOrMethod())) 7835 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7836 diag::err_thread_non_global) 7837 << DeclSpec::getSpecifierName(TSCS); 7838 else if (!Context.getTargetInfo().isTLSSupported()) { 7839 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice || 7840 getLangOpts().SYCLIsDevice) { 7841 // Postpone error emission until we've collected attributes required to 7842 // figure out whether it's a host or device variable and whether the 7843 // error should be ignored. 7844 EmitTLSUnsupportedError = true; 7845 // We still need to mark the variable as TLS so it shows up in AST with 7846 // proper storage class for other tools to use even if we're not going 7847 // to emit any code for it. 7848 NewVD->setTSCSpec(TSCS); 7849 } else 7850 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7851 diag::err_thread_unsupported); 7852 } else 7853 NewVD->setTSCSpec(TSCS); 7854 } 7855 7856 switch (D.getDeclSpec().getConstexprSpecifier()) { 7857 case ConstexprSpecKind::Unspecified: 7858 break; 7859 7860 case ConstexprSpecKind::Consteval: 7861 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7862 diag::err_constexpr_wrong_decl_kind) 7863 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7864 [[fallthrough]]; 7865 7866 case ConstexprSpecKind::Constexpr: 7867 NewVD->setConstexpr(true); 7868 // C++1z [dcl.spec.constexpr]p1: 7869 // A static data member declared with the constexpr specifier is 7870 // implicitly an inline variable. 7871 if (NewVD->isStaticDataMember() && 7872 (getLangOpts().CPlusPlus17 || 7873 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7874 NewVD->setImplicitlyInline(); 7875 break; 7876 7877 case ConstexprSpecKind::Constinit: 7878 if (!NewVD->hasGlobalStorage()) 7879 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7880 diag::err_constinit_local_variable); 7881 else 7882 NewVD->addAttr( 7883 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(), 7884 ConstInitAttr::Keyword_constinit)); 7885 break; 7886 } 7887 7888 // C99 6.7.4p3 7889 // An inline definition of a function with external linkage shall 7890 // not contain a definition of a modifiable object with static or 7891 // thread storage duration... 7892 // We only apply this when the function is required to be defined 7893 // elsewhere, i.e. when the function is not 'extern inline'. Note 7894 // that a local variable with thread storage duration still has to 7895 // be marked 'static'. Also note that it's possible to get these 7896 // semantics in C++ using __attribute__((gnu_inline)). 7897 if (SC == SC_Static && S->getFnParent() != nullptr && 7898 !NewVD->getType().isConstQualified()) { 7899 FunctionDecl *CurFD = getCurFunctionDecl(); 7900 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7901 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7902 diag::warn_static_local_in_extern_inline); 7903 MaybeSuggestAddingStaticToDecl(CurFD); 7904 } 7905 } 7906 7907 if (D.getDeclSpec().isModulePrivateSpecified()) { 7908 if (IsVariableTemplateSpecialization) 7909 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7910 << (IsPartialSpecialization ? 1 : 0) 7911 << FixItHint::CreateRemoval( 7912 D.getDeclSpec().getModulePrivateSpecLoc()); 7913 else if (IsMemberSpecialization) 7914 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7915 << 2 7916 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7917 else if (NewVD->hasLocalStorage()) 7918 Diag(NewVD->getLocation(), diag::err_module_private_local) 7919 << 0 << NewVD 7920 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7921 << FixItHint::CreateRemoval( 7922 D.getDeclSpec().getModulePrivateSpecLoc()); 7923 else { 7924 NewVD->setModulePrivate(); 7925 if (NewTemplate) 7926 NewTemplate->setModulePrivate(); 7927 for (auto *B : Bindings) 7928 B->setModulePrivate(); 7929 } 7930 } 7931 7932 if (getLangOpts().OpenCL) { 7933 deduceOpenCLAddressSpace(NewVD); 7934 7935 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7936 if (TSC != TSCS_unspecified) { 7937 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7938 diag::err_opencl_unknown_type_specifier) 7939 << getLangOpts().getOpenCLVersionString() 7940 << DeclSpec::getSpecifierName(TSC) << 1; 7941 NewVD->setInvalidDecl(); 7942 } 7943 } 7944 7945 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply 7946 // address space if the table has local storage (semantic checks elsewhere 7947 // will produce an error anyway). 7948 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) { 7949 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() && 7950 !NewVD->hasLocalStorage()) { 7951 QualType Type = Context.getAddrSpaceQualType( 7952 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1)); 7953 NewVD->setType(Type); 7954 } 7955 } 7956 7957 // Handle attributes prior to checking for duplicates in MergeVarDecl 7958 ProcessDeclAttributes(S, NewVD, D); 7959 7960 if (getLangOpts().HLSL) 7961 HLSL().ActOnVariableDeclarator(NewVD); 7962 7963 // FIXME: This is probably the wrong location to be doing this and we should 7964 // probably be doing this for more attributes (especially for function 7965 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7966 // the code to copy attributes would be generated by TableGen. 7967 if (R->isFunctionPointerType()) 7968 if (const auto *TT = R->getAs<TypedefType>()) 7969 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7970 7971 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice || 7972 getLangOpts().SYCLIsDevice) { 7973 if (EmitTLSUnsupportedError && 7974 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7975 (getLangOpts().OpenMPIsTargetDevice && 7976 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7977 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7978 diag::err_thread_unsupported); 7979 7980 if (EmitTLSUnsupportedError && 7981 (LangOpts.SYCLIsDevice || 7982 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice))) 7983 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7984 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7985 // storage [duration]." 7986 if (SC == SC_None && S->getFnParent() != nullptr && 7987 (NewVD->hasAttr<CUDASharedAttr>() || 7988 NewVD->hasAttr<CUDAConstantAttr>())) { 7989 NewVD->setStorageClass(SC_Static); 7990 } 7991 } 7992 7993 // Ensure that dllimport globals without explicit storage class are treated as 7994 // extern. The storage class is set above using parsed attributes. Now we can 7995 // check the VarDecl itself. 7996 assert(!NewVD->hasAttr<DLLImportAttr>() || 7997 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7998 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7999 8000 // In auto-retain/release, infer strong retension for variables of 8001 // retainable type. 8002 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD)) 8003 NewVD->setInvalidDecl(); 8004 8005 // Handle GNU asm-label extension (encoded as an attribute). 8006 if (Expr *E = (Expr*)D.getAsmLabel()) { 8007 // The parser guarantees this is a string. 8008 StringLiteral *SE = cast<StringLiteral>(E); 8009 StringRef Label = SE->getString(); 8010 if (S->getFnParent() != nullptr) { 8011 switch (SC) { 8012 case SC_None: 8013 case SC_Auto: 8014 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 8015 break; 8016 case SC_Register: 8017 // Local Named register 8018 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 8019 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 8020 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 8021 break; 8022 case SC_Static: 8023 case SC_Extern: 8024 case SC_PrivateExtern: 8025 break; 8026 } 8027 } else if (SC == SC_Register) { 8028 // Global Named register 8029 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 8030 const auto &TI = Context.getTargetInfo(); 8031 bool HasSizeMismatch; 8032 8033 if (!TI.isValidGCCRegisterName(Label)) 8034 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 8035 else if (!TI.validateGlobalRegisterVariable(Label, 8036 Context.getTypeSize(R), 8037 HasSizeMismatch)) 8038 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 8039 else if (HasSizeMismatch) 8040 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 8041 } 8042 8043 if (!R->isIntegralType(Context) && !R->isPointerType()) { 8044 Diag(TInfo->getTypeLoc().getBeginLoc(), 8045 diag::err_asm_unsupported_register_type) 8046 << TInfo->getTypeLoc().getSourceRange(); 8047 NewVD->setInvalidDecl(true); 8048 } 8049 } 8050 8051 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 8052 /*IsLiteralLabel=*/true, 8053 SE->getStrTokenLoc(0))); 8054 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8055 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8056 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 8057 if (I != ExtnameUndeclaredIdentifiers.end()) { 8058 if (isDeclExternC(NewVD)) { 8059 NewVD->addAttr(I->second); 8060 ExtnameUndeclaredIdentifiers.erase(I); 8061 } else 8062 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 8063 << /*Variable*/1 << NewVD; 8064 } 8065 } 8066 8067 // Find the shadowed declaration before filtering for scope. 8068 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 8069 ? getShadowedDeclaration(NewVD, Previous) 8070 : nullptr; 8071 8072 // Don't consider existing declarations that are in a different 8073 // scope and are out-of-semantic-context declarations (if the new 8074 // declaration has linkage). 8075 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 8076 D.getCXXScopeSpec().isNotEmpty() || 8077 IsMemberSpecialization || 8078 IsVariableTemplateSpecialization); 8079 8080 // Check whether the previous declaration is in the same block scope. This 8081 // affects whether we merge types with it, per C++11 [dcl.array]p3. 8082 if (getLangOpts().CPlusPlus && 8083 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 8084 NewVD->setPreviousDeclInSameBlockScope( 8085 Previous.isSingleResult() && !Previous.isShadowed() && 8086 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 8087 8088 if (!getLangOpts().CPlusPlus) { 8089 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 8090 } else { 8091 // If this is an explicit specialization of a static data member, check it. 8092 if (IsMemberSpecialization && !IsVariableTemplate && 8093 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() && 8094 CheckMemberSpecialization(NewVD, Previous)) 8095 NewVD->setInvalidDecl(); 8096 8097 // Merge the decl with the existing one if appropriate. 8098 if (!Previous.empty()) { 8099 if (Previous.isSingleResult() && 8100 isa<FieldDecl>(Previous.getFoundDecl()) && 8101 D.getCXXScopeSpec().isSet()) { 8102 // The user tried to define a non-static data member 8103 // out-of-line (C++ [dcl.meaning]p1). 8104 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 8105 << D.getCXXScopeSpec().getRange(); 8106 Previous.clear(); 8107 NewVD->setInvalidDecl(); 8108 } 8109 } else if (D.getCXXScopeSpec().isSet() && 8110 !IsVariableTemplateSpecialization) { 8111 // No previous declaration in the qualifying scope. 8112 Diag(D.getIdentifierLoc(), diag::err_no_member) 8113 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 8114 << D.getCXXScopeSpec().getRange(); 8115 NewVD->setInvalidDecl(); 8116 } 8117 8118 if (!IsPlaceholderVariable) 8119 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 8120 8121 // CheckVariableDeclaration will set NewVD as invalid if something is in 8122 // error like WebAssembly tables being declared as arrays with a non-zero 8123 // size, but then parsing continues and emits further errors on that line. 8124 // To avoid that we check here if it happened and return nullptr. 8125 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl()) 8126 return nullptr; 8127 8128 if (NewTemplate) { 8129 VarTemplateDecl *PrevVarTemplate = 8130 NewVD->getPreviousDecl() 8131 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 8132 : nullptr; 8133 8134 // Check the template parameter list of this declaration, possibly 8135 // merging in the template parameter list from the previous variable 8136 // template declaration. 8137 if (CheckTemplateParameterList( 8138 TemplateParams, 8139 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 8140 : nullptr, 8141 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 8142 DC->isDependentContext()) 8143 ? TPC_ClassTemplateMember 8144 : TPC_VarTemplate)) 8145 NewVD->setInvalidDecl(); 8146 8147 // If we are providing an explicit specialization of a static variable 8148 // template, make a note of that. 8149 if (PrevVarTemplate && 8150 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 8151 PrevVarTemplate->setMemberSpecialization(); 8152 } 8153 } 8154 8155 // Diagnose shadowed variables iff this isn't a redeclaration. 8156 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration()) 8157 CheckShadow(NewVD, ShadowedDecl, Previous); 8158 8159 ProcessPragmaWeak(S, NewVD); 8160 8161 // If this is the first declaration of an extern C variable, update 8162 // the map of such variables. 8163 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 8164 isIncompleteDeclExternC(*this, NewVD)) 8165 RegisterLocallyScopedExternCDecl(NewVD, S); 8166 8167 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 8168 MangleNumberingContext *MCtx; 8169 Decl *ManglingContextDecl; 8170 std::tie(MCtx, ManglingContextDecl) = 8171 getCurrentMangleNumberContext(NewVD->getDeclContext()); 8172 if (MCtx) { 8173 Context.setManglingNumber( 8174 NewVD, MCtx->getManglingNumber( 8175 NewVD, getMSManglingNumber(getLangOpts(), S))); 8176 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 8177 } 8178 } 8179 8180 // Special handling of variable named 'main'. 8181 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) { 8182 // C++ [basic.start.main]p3: 8183 // A program that declares 8184 // - a variable main at global scope, or 8185 // - an entity named main with C language linkage (in any namespace) 8186 // is ill-formed 8187 if (getLangOpts().CPlusPlus) 8188 Diag(D.getBeginLoc(), diag::err_main_global_variable) 8189 << NewVD->isExternC(); 8190 8191 // In C, and external-linkage variable named main results in undefined 8192 // behavior. 8193 else if (NewVD->hasExternalFormalLinkage()) 8194 Diag(D.getBeginLoc(), diag::warn_main_redefined); 8195 } 8196 8197 if (D.isRedeclaration() && !Previous.empty()) { 8198 NamedDecl *Prev = Previous.getRepresentativeDecl(); 8199 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 8200 D.isFunctionDefinition()); 8201 } 8202 8203 if (NewTemplate) { 8204 if (NewVD->isInvalidDecl()) 8205 NewTemplate->setInvalidDecl(); 8206 ActOnDocumentableDecl(NewTemplate); 8207 return NewTemplate; 8208 } 8209 8210 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 8211 CompleteMemberSpecialization(NewVD, Previous); 8212 8213 emitReadOnlyPlacementAttrWarning(*this, NewVD); 8214 8215 return NewVD; 8216 } 8217 8218 /// Enum describing the %select options in diag::warn_decl_shadow. 8219 enum ShadowedDeclKind { 8220 SDK_Local, 8221 SDK_Global, 8222 SDK_StaticMember, 8223 SDK_Field, 8224 SDK_Typedef, 8225 SDK_Using, 8226 SDK_StructuredBinding 8227 }; 8228 8229 /// Determine what kind of declaration we're shadowing. 8230 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 8231 const DeclContext *OldDC) { 8232 if (isa<TypeAliasDecl>(ShadowedDecl)) 8233 return SDK_Using; 8234 else if (isa<TypedefDecl>(ShadowedDecl)) 8235 return SDK_Typedef; 8236 else if (isa<BindingDecl>(ShadowedDecl)) 8237 return SDK_StructuredBinding; 8238 else if (isa<RecordDecl>(OldDC)) 8239 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 8240 8241 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 8242 } 8243 8244 /// Return the location of the capture if the given lambda captures the given 8245 /// variable \p VD, or an invalid source location otherwise. 8246 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 8247 const VarDecl *VD) { 8248 for (const Capture &Capture : LSI->Captures) { 8249 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 8250 return Capture.getLocation(); 8251 } 8252 return SourceLocation(); 8253 } 8254 8255 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 8256 const LookupResult &R) { 8257 // Only diagnose if we're shadowing an unambiguous field or variable. 8258 if (R.getResultKind() != LookupResult::Found) 8259 return false; 8260 8261 // Return false if warning is ignored. 8262 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 8263 } 8264 8265 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 8266 const LookupResult &R) { 8267 if (!shouldWarnIfShadowedDecl(Diags, R)) 8268 return nullptr; 8269 8270 // Don't diagnose declarations at file scope. 8271 if (D->hasGlobalStorage() && !D->isStaticLocal()) 8272 return nullptr; 8273 8274 NamedDecl *ShadowedDecl = R.getFoundDecl(); 8275 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 8276 : nullptr; 8277 } 8278 8279 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 8280 const LookupResult &R) { 8281 // Don't warn if typedef declaration is part of a class 8282 if (D->getDeclContext()->isRecord()) 8283 return nullptr; 8284 8285 if (!shouldWarnIfShadowedDecl(Diags, R)) 8286 return nullptr; 8287 8288 NamedDecl *ShadowedDecl = R.getFoundDecl(); 8289 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 8290 } 8291 8292 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 8293 const LookupResult &R) { 8294 if (!shouldWarnIfShadowedDecl(Diags, R)) 8295 return nullptr; 8296 8297 NamedDecl *ShadowedDecl = R.getFoundDecl(); 8298 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 8299 : nullptr; 8300 } 8301 8302 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 8303 const LookupResult &R) { 8304 DeclContext *NewDC = D->getDeclContext(); 8305 8306 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 8307 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) { 8308 // Fields are not shadowed by variables in C++ static methods. 8309 if (MD->isStatic()) 8310 return; 8311 8312 if (!MD->getParent()->isLambda() && MD->isExplicitObjectMemberFunction()) 8313 return; 8314 } 8315 // Fields shadowed by constructor parameters are a special case. Usually 8316 // the constructor initializes the field with the parameter. 8317 if (isa<CXXConstructorDecl>(NewDC)) 8318 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 8319 // Remember that this was shadowed so we can either warn about its 8320 // modification or its existence depending on warning settings. 8321 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 8322 return; 8323 } 8324 } 8325 8326 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 8327 if (shadowedVar->isExternC()) { 8328 // For shadowing external vars, make sure that we point to the global 8329 // declaration, not a locally scoped extern declaration. 8330 for (auto *I : shadowedVar->redecls()) 8331 if (I->isFileVarDecl()) { 8332 ShadowedDecl = I; 8333 break; 8334 } 8335 } 8336 8337 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 8338 8339 unsigned WarningDiag = diag::warn_decl_shadow; 8340 SourceLocation CaptureLoc; 8341 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) { 8342 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 8343 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 8344 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) { 8345 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 8346 if (RD->getLambdaCaptureDefault() == LCD_None) { 8347 // Try to avoid warnings for lambdas with an explicit capture 8348 // list. Warn only when the lambda captures the shadowed decl 8349 // explicitly. 8350 CaptureLoc = getCaptureLocation(LSI, VD); 8351 if (CaptureLoc.isInvalid()) 8352 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 8353 } else { 8354 // Remember that this was shadowed so we can avoid the warning if 8355 // the shadowed decl isn't captured and the warning settings allow 8356 // it. 8357 cast<LambdaScopeInfo>(getCurFunction()) 8358 ->ShadowingDecls.push_back({D, VD}); 8359 return; 8360 } 8361 } 8362 if (isa<FieldDecl>(ShadowedDecl)) { 8363 // If lambda can capture this, then emit default shadowing warning, 8364 // Otherwise it is not really a shadowing case since field is not 8365 // available in lambda's body. 8366 // At this point we don't know that lambda can capture this, so 8367 // remember that this was shadowed and delay until we know. 8368 cast<LambdaScopeInfo>(getCurFunction()) 8369 ->ShadowingDecls.push_back({D, ShadowedDecl}); 8370 return; 8371 } 8372 } 8373 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl); 8374 VD && VD->hasLocalStorage()) { 8375 // A variable can't shadow a local variable in an enclosing scope, if 8376 // they are separated by a non-capturing declaration context. 8377 for (DeclContext *ParentDC = NewDC; 8378 ParentDC && !ParentDC->Equals(OldDC); 8379 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 8380 // Only block literals, captured statements, and lambda expressions 8381 // can capture; other scopes don't. 8382 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 8383 !isLambdaCallOperator(ParentDC)) { 8384 return; 8385 } 8386 } 8387 } 8388 } 8389 } 8390 8391 // Never warn about shadowing a placeholder variable. 8392 if (ShadowedDecl->isPlaceholderVar(getLangOpts())) 8393 return; 8394 8395 // Only warn about certain kinds of shadowing for class members. 8396 if (NewDC) { 8397 // In particular, don't warn about shadowing non-class members. 8398 if (NewDC->isRecord() && !OldDC->isRecord()) 8399 return; 8400 8401 // Skip shadowing check if we're in a class scope, dealing with an enum 8402 // constant in a different context. 8403 DeclContext *ReDC = NewDC->getRedeclContext(); 8404 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC)) 8405 return; 8406 8407 // TODO: should we warn about static data members shadowing 8408 // static data members from base classes? 8409 8410 // TODO: don't diagnose for inaccessible shadowed members. 8411 // This is hard to do perfectly because we might friend the 8412 // shadowing context, but that's just a false negative. 8413 } 8414 8415 DeclarationName Name = R.getLookupName(); 8416 8417 // Emit warning and note. 8418 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 8419 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 8420 if (!CaptureLoc.isInvalid()) 8421 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8422 << Name << /*explicitly*/ 1; 8423 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8424 } 8425 8426 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 8427 for (const auto &Shadow : LSI->ShadowingDecls) { 8428 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl; 8429 // Try to avoid the warning when the shadowed decl isn't captured. 8430 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8431 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) { 8432 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD); 8433 Diag(Shadow.VD->getLocation(), 8434 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local 8435 : diag::warn_decl_shadow) 8436 << Shadow.VD->getDeclName() 8437 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 8438 if (CaptureLoc.isValid()) 8439 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8440 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 8441 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8442 } else if (isa<FieldDecl>(ShadowedDecl)) { 8443 Diag(Shadow.VD->getLocation(), 8444 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow 8445 : diag::warn_decl_shadow_uncaptured_local) 8446 << Shadow.VD->getDeclName() 8447 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 8448 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8449 } 8450 } 8451 } 8452 8453 void Sema::CheckShadow(Scope *S, VarDecl *D) { 8454 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 8455 return; 8456 8457 LookupResult R(*this, D->getDeclName(), D->getLocation(), 8458 Sema::LookupOrdinaryName, 8459 RedeclarationKind::ForVisibleRedeclaration); 8460 LookupName(R, S); 8461 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 8462 CheckShadow(D, ShadowedDecl, R); 8463 } 8464 8465 /// Check if 'E', which is an expression that is about to be modified, refers 8466 /// to a constructor parameter that shadows a field. 8467 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 8468 // Quickly ignore expressions that can't be shadowing ctor parameters. 8469 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 8470 return; 8471 E = E->IgnoreParenImpCasts(); 8472 auto *DRE = dyn_cast<DeclRefExpr>(E); 8473 if (!DRE) 8474 return; 8475 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 8476 auto I = ShadowingDecls.find(D); 8477 if (I == ShadowingDecls.end()) 8478 return; 8479 const NamedDecl *ShadowedDecl = I->second; 8480 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8481 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 8482 Diag(D->getLocation(), diag::note_var_declared_here) << D; 8483 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8484 8485 // Avoid issuing multiple warnings about the same decl. 8486 ShadowingDecls.erase(I); 8487 } 8488 8489 /// Check for conflict between this global or extern "C" declaration and 8490 /// previous global or extern "C" declarations. This is only used in C++. 8491 template<typename T> 8492 static bool checkGlobalOrExternCConflict( 8493 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 8494 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 8495 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 8496 8497 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 8498 // The common case: this global doesn't conflict with any extern "C" 8499 // declaration. 8500 return false; 8501 } 8502 8503 if (Prev) { 8504 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 8505 // Both the old and new declarations have C language linkage. This is a 8506 // redeclaration. 8507 Previous.clear(); 8508 Previous.addDecl(Prev); 8509 return true; 8510 } 8511 8512 // This is a global, non-extern "C" declaration, and there is a previous 8513 // non-global extern "C" declaration. Diagnose if this is a variable 8514 // declaration. 8515 if (!isa<VarDecl>(ND)) 8516 return false; 8517 } else { 8518 // The declaration is extern "C". Check for any declaration in the 8519 // translation unit which might conflict. 8520 if (IsGlobal) { 8521 // We have already performed the lookup into the translation unit. 8522 IsGlobal = false; 8523 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8524 I != E; ++I) { 8525 if (isa<VarDecl>(*I)) { 8526 Prev = *I; 8527 break; 8528 } 8529 } 8530 } else { 8531 DeclContext::lookup_result R = 8532 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 8533 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 8534 I != E; ++I) { 8535 if (isa<VarDecl>(*I)) { 8536 Prev = *I; 8537 break; 8538 } 8539 // FIXME: If we have any other entity with this name in global scope, 8540 // the declaration is ill-formed, but that is a defect: it breaks the 8541 // 'stat' hack, for instance. Only variables can have mangled name 8542 // clashes with extern "C" declarations, so only they deserve a 8543 // diagnostic. 8544 } 8545 } 8546 8547 if (!Prev) 8548 return false; 8549 } 8550 8551 // Use the first declaration's location to ensure we point at something which 8552 // is lexically inside an extern "C" linkage-spec. 8553 assert(Prev && "should have found a previous declaration to diagnose"); 8554 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 8555 Prev = FD->getFirstDecl(); 8556 else 8557 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 8558 8559 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 8560 << IsGlobal << ND; 8561 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 8562 << IsGlobal; 8563 return false; 8564 } 8565 8566 /// Apply special rules for handling extern "C" declarations. Returns \c true 8567 /// if we have found that this is a redeclaration of some prior entity. 8568 /// 8569 /// Per C++ [dcl.link]p6: 8570 /// Two declarations [for a function or variable] with C language linkage 8571 /// with the same name that appear in different scopes refer to the same 8572 /// [entity]. An entity with C language linkage shall not be declared with 8573 /// the same name as an entity in global scope. 8574 template<typename T> 8575 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 8576 LookupResult &Previous) { 8577 if (!S.getLangOpts().CPlusPlus) { 8578 // In C, when declaring a global variable, look for a corresponding 'extern' 8579 // variable declared in function scope. We don't need this in C++, because 8580 // we find local extern decls in the surrounding file-scope DeclContext. 8581 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8582 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 8583 Previous.clear(); 8584 Previous.addDecl(Prev); 8585 return true; 8586 } 8587 } 8588 return false; 8589 } 8590 8591 // A declaration in the translation unit can conflict with an extern "C" 8592 // declaration. 8593 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 8594 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 8595 8596 // An extern "C" declaration can conflict with a declaration in the 8597 // translation unit or can be a redeclaration of an extern "C" declaration 8598 // in another scope. 8599 if (isIncompleteDeclExternC(S,ND)) 8600 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 8601 8602 // Neither global nor extern "C": nothing to do. 8603 return false; 8604 } 8605 8606 static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, 8607 QualType T) { 8608 QualType CanonT = SemaRef.Context.getCanonicalType(T); 8609 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or 8610 // any of its members, even recursively, shall not have an atomic type, or a 8611 // variably modified type, or a type that is volatile or restrict qualified. 8612 if (CanonT->isVariablyModifiedType()) { 8613 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T; 8614 return true; 8615 } 8616 8617 // Arrays are qualified by their element type, so get the base type (this 8618 // works on non-arrays as well). 8619 CanonT = SemaRef.Context.getBaseElementType(CanonT); 8620 8621 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() || 8622 CanonT.isRestrictQualified()) { 8623 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T; 8624 return true; 8625 } 8626 8627 if (CanonT->isRecordType()) { 8628 const RecordDecl *RD = CanonT->getAsRecordDecl(); 8629 if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) { 8630 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType()); 8631 })) 8632 return true; 8633 } 8634 8635 return false; 8636 } 8637 8638 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 8639 // If the decl is already known invalid, don't check it. 8640 if (NewVD->isInvalidDecl()) 8641 return; 8642 8643 QualType T = NewVD->getType(); 8644 8645 // Defer checking an 'auto' type until its initializer is attached. 8646 if (T->isUndeducedType()) 8647 return; 8648 8649 if (NewVD->hasAttrs()) 8650 CheckAlignasUnderalignment(NewVD); 8651 8652 if (T->isObjCObjectType()) { 8653 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 8654 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 8655 T = Context.getObjCObjectPointerType(T); 8656 NewVD->setType(T); 8657 } 8658 8659 // Emit an error if an address space was applied to decl with local storage. 8660 // This includes arrays of objects with address space qualifiers, but not 8661 // automatic variables that point to other address spaces. 8662 // ISO/IEC TR 18037 S5.1.2 8663 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 8664 T.getAddressSpace() != LangAS::Default) { 8665 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 8666 NewVD->setInvalidDecl(); 8667 return; 8668 } 8669 8670 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8671 // scope. 8672 if (getLangOpts().OpenCLVersion == 120 && 8673 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8674 getLangOpts()) && 8675 NewVD->isStaticLocal()) { 8676 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8677 NewVD->setInvalidDecl(); 8678 return; 8679 } 8680 8681 if (getLangOpts().OpenCL) { 8682 if (!diagnoseOpenCLTypes(*this, NewVD)) 8683 return; 8684 8685 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8686 if (NewVD->hasAttr<BlocksAttr>()) { 8687 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8688 return; 8689 } 8690 8691 if (T->isBlockPointerType()) { 8692 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8693 // can't use 'extern' storage class. 8694 if (!T.isConstQualified()) { 8695 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8696 << 0 /*const*/; 8697 NewVD->setInvalidDecl(); 8698 return; 8699 } 8700 if (NewVD->hasExternalStorage()) { 8701 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8702 NewVD->setInvalidDecl(); 8703 return; 8704 } 8705 } 8706 8707 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8708 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8709 NewVD->hasExternalStorage()) { 8710 if (!T->isSamplerT() && !T->isDependentType() && 8711 !(T.getAddressSpace() == LangAS::opencl_constant || 8712 (T.getAddressSpace() == LangAS::opencl_global && 8713 getOpenCLOptions().areProgramScopeVariablesSupported( 8714 getLangOpts())))) { 8715 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8716 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8717 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8718 << Scope << "global or constant"; 8719 else 8720 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8721 << Scope << "constant"; 8722 NewVD->setInvalidDecl(); 8723 return; 8724 } 8725 } else { 8726 if (T.getAddressSpace() == LangAS::opencl_global) { 8727 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8728 << 1 /*is any function*/ << "global"; 8729 NewVD->setInvalidDecl(); 8730 return; 8731 } 8732 if (T.getAddressSpace() == LangAS::opencl_constant || 8733 T.getAddressSpace() == LangAS::opencl_local) { 8734 FunctionDecl *FD = getCurFunctionDecl(); 8735 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8736 // in functions. 8737 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8738 if (T.getAddressSpace() == LangAS::opencl_constant) 8739 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8740 << 0 /*non-kernel only*/ << "constant"; 8741 else 8742 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8743 << 0 /*non-kernel only*/ << "local"; 8744 NewVD->setInvalidDecl(); 8745 return; 8746 } 8747 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8748 // in the outermost scope of a kernel function. 8749 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8750 if (!getCurScope()->isFunctionScope()) { 8751 if (T.getAddressSpace() == LangAS::opencl_constant) 8752 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8753 << "constant"; 8754 else 8755 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8756 << "local"; 8757 NewVD->setInvalidDecl(); 8758 return; 8759 } 8760 } 8761 } else if (T.getAddressSpace() != LangAS::opencl_private && 8762 // If we are parsing a template we didn't deduce an addr 8763 // space yet. 8764 T.getAddressSpace() != LangAS::Default) { 8765 // Do not allow other address spaces on automatic variable. 8766 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8767 NewVD->setInvalidDecl(); 8768 return; 8769 } 8770 } 8771 } 8772 8773 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8774 && !NewVD->hasAttr<BlocksAttr>()) { 8775 if (getLangOpts().getGC() != LangOptions::NonGC) 8776 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8777 else { 8778 assert(!getLangOpts().ObjCAutoRefCount); 8779 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8780 } 8781 } 8782 8783 // WebAssembly tables must be static with a zero length and can't be 8784 // declared within functions. 8785 if (T->isWebAssemblyTableType()) { 8786 if (getCurScope()->getParent()) { // Parent is null at top-level 8787 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function); 8788 NewVD->setInvalidDecl(); 8789 return; 8790 } 8791 if (NewVD->getStorageClass() != SC_Static) { 8792 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static); 8793 NewVD->setInvalidDecl(); 8794 return; 8795 } 8796 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr()); 8797 if (!ATy || ATy->getZExtSize() != 0) { 8798 Diag(NewVD->getLocation(), 8799 diag::err_typecheck_wasm_table_must_have_zero_length); 8800 NewVD->setInvalidDecl(); 8801 return; 8802 } 8803 } 8804 8805 // zero sized static arrays are not allowed in HIP device functions 8806 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) { 8807 if (FunctionDecl *FD = getCurFunctionDecl(); 8808 FD && 8809 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) { 8810 if (const ConstantArrayType *ArrayT = 8811 getASTContext().getAsConstantArrayType(T); 8812 ArrayT && ArrayT->isZeroSize()) { 8813 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2; 8814 } 8815 } 8816 } 8817 8818 bool isVM = T->isVariablyModifiedType(); 8819 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8820 NewVD->hasAttr<BlocksAttr>()) 8821 setFunctionHasBranchProtectedScope(); 8822 8823 if ((isVM && NewVD->hasLinkage()) || 8824 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8825 bool SizeIsNegative; 8826 llvm::APSInt Oversized; 8827 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8828 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8829 QualType FixedT; 8830 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8831 FixedT = FixedTInfo->getType(); 8832 else if (FixedTInfo) { 8833 // Type and type-as-written are canonically different. We need to fix up 8834 // both types separately. 8835 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8836 Oversized); 8837 } 8838 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8839 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8840 // FIXME: This won't give the correct result for 8841 // int a[10][n]; 8842 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8843 8844 if (NewVD->isFileVarDecl()) 8845 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8846 << SizeRange; 8847 else if (NewVD->isStaticLocal()) 8848 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8849 << SizeRange; 8850 else 8851 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8852 << SizeRange; 8853 NewVD->setInvalidDecl(); 8854 return; 8855 } 8856 8857 if (!FixedTInfo) { 8858 if (NewVD->isFileVarDecl()) 8859 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8860 else 8861 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8862 NewVD->setInvalidDecl(); 8863 return; 8864 } 8865 8866 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8867 NewVD->setType(FixedT); 8868 NewVD->setTypeSourceInfo(FixedTInfo); 8869 } 8870 8871 if (T->isVoidType()) { 8872 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8873 // of objects and functions. 8874 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8875 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8876 << T; 8877 NewVD->setInvalidDecl(); 8878 return; 8879 } 8880 } 8881 8882 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8883 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8884 NewVD->setInvalidDecl(); 8885 return; 8886 } 8887 8888 if (!NewVD->hasLocalStorage() && T->isSizelessType() && 8889 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) { 8890 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8891 NewVD->setInvalidDecl(); 8892 return; 8893 } 8894 8895 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8896 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8897 NewVD->setInvalidDecl(); 8898 return; 8899 } 8900 8901 if (getLangOpts().C23 && NewVD->isConstexpr() && 8902 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) { 8903 NewVD->setInvalidDecl(); 8904 return; 8905 } 8906 8907 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() && 8908 !T->isDependentType() && 8909 RequireLiteralType(NewVD->getLocation(), T, 8910 diag::err_constexpr_var_non_literal)) { 8911 NewVD->setInvalidDecl(); 8912 return; 8913 } 8914 8915 // PPC MMA non-pointer types are not allowed as non-local variable types. 8916 if (Context.getTargetInfo().getTriple().isPPC64() && 8917 !NewVD->isLocalVarDecl() && 8918 PPC().CheckPPCMMAType(T, NewVD->getLocation())) { 8919 NewVD->setInvalidDecl(); 8920 return; 8921 } 8922 8923 // Check that SVE types are only used in functions with SVE available. 8924 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) { 8925 const FunctionDecl *FD = cast<FunctionDecl>(CurContext); 8926 llvm::StringMap<bool> CallerFeatureMap; 8927 Context.getFunctionFeatureMap(CallerFeatureMap, FD); 8928 8929 if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) { 8930 if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) { 8931 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T; 8932 NewVD->setInvalidDecl(); 8933 return; 8934 } else if (!IsArmStreamingFunction(FD, 8935 /*IncludeLocallyStreaming=*/true)) { 8936 Diag(NewVD->getLocation(), 8937 diag::err_sve_vector_in_non_streaming_function) 8938 << T; 8939 NewVD->setInvalidDecl(); 8940 return; 8941 } 8942 } 8943 } 8944 8945 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) { 8946 const FunctionDecl *FD = cast<FunctionDecl>(CurContext); 8947 llvm::StringMap<bool> CallerFeatureMap; 8948 Context.getFunctionFeatureMap(CallerFeatureMap, FD); 8949 RISCV().checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext), 8950 CallerFeatureMap); 8951 } 8952 } 8953 8954 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8955 CheckVariableDeclarationType(NewVD); 8956 8957 // If the decl is already known invalid, don't check it. 8958 if (NewVD->isInvalidDecl()) 8959 return false; 8960 8961 // If we did not find anything by this name, look for a non-visible 8962 // extern "C" declaration with the same name. 8963 if (Previous.empty() && 8964 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8965 Previous.setShadowed(); 8966 8967 if (!Previous.empty()) { 8968 MergeVarDecl(NewVD, Previous); 8969 return true; 8970 } 8971 return false; 8972 } 8973 8974 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8975 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8976 8977 // Look for methods in base classes that this method might override. 8978 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8979 /*DetectVirtual=*/false); 8980 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8981 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8982 DeclarationName Name = MD->getDeclName(); 8983 8984 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8985 // We really want to find the base class destructor here. 8986 QualType T = Context.getTypeDeclType(BaseRecord); 8987 CanQualType CT = Context.getCanonicalType(T); 8988 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8989 } 8990 8991 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8992 CXXMethodDecl *BaseMD = 8993 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8994 if (!BaseMD || !BaseMD->isVirtual() || 8995 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8996 /*ConsiderCudaAttrs=*/true)) 8997 continue; 8998 if (!CheckExplicitObjectOverride(MD, BaseMD)) 8999 continue; 9000 if (Overridden.insert(BaseMD).second) { 9001 MD->addOverriddenMethod(BaseMD); 9002 CheckOverridingFunctionReturnType(MD, BaseMD); 9003 CheckOverridingFunctionAttributes(MD, BaseMD); 9004 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 9005 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 9006 } 9007 9008 // A method can only override one function from each base class. We 9009 // don't track indirectly overridden methods from bases of bases. 9010 return true; 9011 } 9012 9013 return false; 9014 }; 9015 9016 DC->lookupInBases(VisitBase, Paths); 9017 return !Overridden.empty(); 9018 } 9019 9020 namespace { 9021 // Struct for holding all of the extra arguments needed by 9022 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 9023 struct ActOnFDArgs { 9024 Scope *S; 9025 Declarator &D; 9026 MultiTemplateParamsArg TemplateParamLists; 9027 bool AddToScope; 9028 }; 9029 } // end anonymous namespace 9030 9031 namespace { 9032 9033 // Callback to only accept typo corrections that have a non-zero edit distance. 9034 // Also only accept corrections that have the same parent decl. 9035 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 9036 public: 9037 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 9038 CXXRecordDecl *Parent) 9039 : Context(Context), OriginalFD(TypoFD), 9040 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 9041 9042 bool ValidateCandidate(const TypoCorrection &candidate) override { 9043 if (candidate.getEditDistance() == 0) 9044 return false; 9045 9046 SmallVector<unsigned, 1> MismatchedParams; 9047 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 9048 CDeclEnd = candidate.end(); 9049 CDecl != CDeclEnd; ++CDecl) { 9050 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 9051 9052 if (FD && !FD->hasBody() && 9053 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 9054 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 9055 CXXRecordDecl *Parent = MD->getParent(); 9056 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 9057 return true; 9058 } else if (!ExpectedParent) { 9059 return true; 9060 } 9061 } 9062 } 9063 9064 return false; 9065 } 9066 9067 std::unique_ptr<CorrectionCandidateCallback> clone() override { 9068 return std::make_unique<DifferentNameValidatorCCC>(*this); 9069 } 9070 9071 private: 9072 ASTContext &Context; 9073 FunctionDecl *OriginalFD; 9074 CXXRecordDecl *ExpectedParent; 9075 }; 9076 9077 } // end anonymous namespace 9078 9079 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 9080 TypoCorrectedFunctionDefinitions.insert(F); 9081 } 9082 9083 /// Generate diagnostics for an invalid function redeclaration. 9084 /// 9085 /// This routine handles generating the diagnostic messages for an invalid 9086 /// function redeclaration, including finding possible similar declarations 9087 /// or performing typo correction if there are no previous declarations with 9088 /// the same name. 9089 /// 9090 /// Returns a NamedDecl iff typo correction was performed and substituting in 9091 /// the new declaration name does not cause new errors. 9092 static NamedDecl *DiagnoseInvalidRedeclaration( 9093 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 9094 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 9095 DeclarationName Name = NewFD->getDeclName(); 9096 DeclContext *NewDC = NewFD->getDeclContext(); 9097 SmallVector<unsigned, 1> MismatchedParams; 9098 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 9099 TypoCorrection Correction; 9100 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 9101 unsigned DiagMsg = 9102 IsLocalFriend ? diag::err_no_matching_local_friend : 9103 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 9104 diag::err_member_decl_does_not_match; 9105 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 9106 IsLocalFriend ? Sema::LookupLocalFriendName 9107 : Sema::LookupOrdinaryName, 9108 RedeclarationKind::ForVisibleRedeclaration); 9109 9110 NewFD->setInvalidDecl(); 9111 if (IsLocalFriend) 9112 SemaRef.LookupName(Prev, S); 9113 else 9114 SemaRef.LookupQualifiedName(Prev, NewDC); 9115 assert(!Prev.isAmbiguous() && 9116 "Cannot have an ambiguity in previous-declaration lookup"); 9117 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9118 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 9119 MD ? MD->getParent() : nullptr); 9120 if (!Prev.empty()) { 9121 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 9122 Func != FuncEnd; ++Func) { 9123 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 9124 if (FD && 9125 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 9126 // Add 1 to the index so that 0 can mean the mismatch didn't 9127 // involve a parameter 9128 unsigned ParamNum = 9129 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 9130 NearMatches.push_back(std::make_pair(FD, ParamNum)); 9131 } 9132 } 9133 // If the qualified name lookup yielded nothing, try typo correction 9134 } else if ((Correction = SemaRef.CorrectTypo( 9135 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 9136 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 9137 IsLocalFriend ? nullptr : NewDC))) { 9138 // Set up everything for the call to ActOnFunctionDeclarator 9139 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 9140 ExtraArgs.D.getIdentifierLoc()); 9141 Previous.clear(); 9142 Previous.setLookupName(Correction.getCorrection()); 9143 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 9144 CDeclEnd = Correction.end(); 9145 CDecl != CDeclEnd; ++CDecl) { 9146 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 9147 if (FD && !FD->hasBody() && 9148 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 9149 Previous.addDecl(FD); 9150 } 9151 } 9152 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 9153 9154 NamedDecl *Result; 9155 // Retry building the function declaration with the new previous 9156 // declarations, and with errors suppressed. 9157 { 9158 // Trap errors. 9159 Sema::SFINAETrap Trap(SemaRef); 9160 9161 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 9162 // pieces need to verify the typo-corrected C++ declaration and hopefully 9163 // eliminate the need for the parameter pack ExtraArgs. 9164 Result = SemaRef.ActOnFunctionDeclarator( 9165 ExtraArgs.S, ExtraArgs.D, 9166 Correction.getCorrectionDecl()->getDeclContext(), 9167 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 9168 ExtraArgs.AddToScope); 9169 9170 if (Trap.hasErrorOccurred()) 9171 Result = nullptr; 9172 } 9173 9174 if (Result) { 9175 // Determine which correction we picked. 9176 Decl *Canonical = Result->getCanonicalDecl(); 9177 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9178 I != E; ++I) 9179 if ((*I)->getCanonicalDecl() == Canonical) 9180 Correction.setCorrectionDecl(*I); 9181 9182 // Let Sema know about the correction. 9183 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 9184 SemaRef.diagnoseTypo( 9185 Correction, 9186 SemaRef.PDiag(IsLocalFriend 9187 ? diag::err_no_matching_local_friend_suggest 9188 : diag::err_member_decl_does_not_match_suggest) 9189 << Name << NewDC << IsDefinition); 9190 return Result; 9191 } 9192 9193 // Pretend the typo correction never occurred 9194 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 9195 ExtraArgs.D.getIdentifierLoc()); 9196 ExtraArgs.D.setRedeclaration(wasRedeclaration); 9197 Previous.clear(); 9198 Previous.setLookupName(Name); 9199 } 9200 9201 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 9202 << Name << NewDC << IsDefinition << NewFD->getLocation(); 9203 9204 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD); 9205 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) { 9206 CXXRecordDecl *RD = NewMD->getParent(); 9207 SemaRef.Diag(RD->getLocation(), diag::note_defined_here) 9208 << RD->getName() << RD->getLocation(); 9209 } 9210 9211 bool NewFDisConst = NewMD && NewMD->isConst(); 9212 9213 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 9214 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 9215 NearMatch != NearMatchEnd; ++NearMatch) { 9216 FunctionDecl *FD = NearMatch->first; 9217 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 9218 bool FDisConst = MD && MD->isConst(); 9219 bool IsMember = MD || !IsLocalFriend; 9220 9221 // FIXME: These notes are poorly worded for the local friend case. 9222 if (unsigned Idx = NearMatch->second) { 9223 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 9224 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 9225 if (Loc.isInvalid()) Loc = FD->getLocation(); 9226 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 9227 : diag::note_local_decl_close_param_match) 9228 << Idx << FDParam->getType() 9229 << NewFD->getParamDecl(Idx - 1)->getType(); 9230 } else if (FDisConst != NewFDisConst) { 9231 auto DB = SemaRef.Diag(FD->getLocation(), 9232 diag::note_member_def_close_const_match) 9233 << NewFDisConst << FD->getSourceRange().getEnd(); 9234 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst) 9235 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1), 9236 " const"); 9237 else if (FTI.hasMethodTypeQualifiers() && 9238 FTI.getConstQualifierLoc().isValid()) 9239 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc()); 9240 } else { 9241 SemaRef.Diag(FD->getLocation(), 9242 IsMember ? diag::note_member_def_close_match 9243 : diag::note_local_decl_close_match); 9244 } 9245 } 9246 return nullptr; 9247 } 9248 9249 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 9250 switch (D.getDeclSpec().getStorageClassSpec()) { 9251 default: llvm_unreachable("Unknown storage class!"); 9252 case DeclSpec::SCS_auto: 9253 case DeclSpec::SCS_register: 9254 case DeclSpec::SCS_mutable: 9255 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9256 diag::err_typecheck_sclass_func); 9257 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9258 D.setInvalidType(); 9259 break; 9260 case DeclSpec::SCS_unspecified: break; 9261 case DeclSpec::SCS_extern: 9262 if (D.getDeclSpec().isExternInLinkageSpec()) 9263 return SC_None; 9264 return SC_Extern; 9265 case DeclSpec::SCS_static: { 9266 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 9267 // C99 6.7.1p5: 9268 // The declaration of an identifier for a function that has 9269 // block scope shall have no explicit storage-class specifier 9270 // other than extern 9271 // See also (C++ [dcl.stc]p4). 9272 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9273 diag::err_static_block_func); 9274 break; 9275 } else 9276 return SC_Static; 9277 } 9278 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 9279 } 9280 9281 // No explicit storage class has already been returned 9282 return SC_None; 9283 } 9284 9285 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 9286 DeclContext *DC, QualType &R, 9287 TypeSourceInfo *TInfo, 9288 StorageClass SC, 9289 bool &IsVirtualOkay) { 9290 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 9291 DeclarationName Name = NameInfo.getName(); 9292 9293 FunctionDecl *NewFD = nullptr; 9294 bool isInline = D.getDeclSpec().isInlineSpecified(); 9295 9296 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9297 if (ConstexprKind == ConstexprSpecKind::Constinit || 9298 (SemaRef.getLangOpts().C23 && 9299 ConstexprKind == ConstexprSpecKind::Constexpr)) { 9300 9301 if (SemaRef.getLangOpts().C23) 9302 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 9303 diag::err_c23_constexpr_not_variable); 9304 else 9305 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 9306 diag::err_constexpr_wrong_decl_kind) 9307 << static_cast<int>(ConstexprKind); 9308 ConstexprKind = ConstexprSpecKind::Unspecified; 9309 D.getMutableDeclSpec().ClearConstexprSpec(); 9310 } 9311 9312 if (!SemaRef.getLangOpts().CPlusPlus) { 9313 // Determine whether the function was written with a prototype. This is 9314 // true when: 9315 // - there is a prototype in the declarator, or 9316 // - the type R of the function is some kind of typedef or other non- 9317 // attributed reference to a type name (which eventually refers to a 9318 // function type). Note, we can't always look at the adjusted type to 9319 // check this case because attributes may cause a non-function 9320 // declarator to still have a function type. e.g., 9321 // typedef void func(int a); 9322 // __attribute__((noreturn)) func other_func; // This has a prototype 9323 bool HasPrototype = 9324 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 9325 (D.getDeclSpec().isTypeRep() && 9326 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr) 9327 ->isFunctionProtoType()) || 9328 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 9329 assert( 9330 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) && 9331 "Strict prototypes are required"); 9332 9333 NewFD = FunctionDecl::Create( 9334 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 9335 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 9336 ConstexprSpecKind::Unspecified, 9337 /*TrailingRequiresClause=*/nullptr); 9338 if (D.isInvalidType()) 9339 NewFD->setInvalidDecl(); 9340 9341 return NewFD; 9342 } 9343 9344 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 9345 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 9346 9347 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R); 9348 9349 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 9350 // This is a C++ constructor declaration. 9351 assert(DC->isRecord() && 9352 "Constructors can only be declared in a member context"); 9353 9354 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 9355 return CXXConstructorDecl::Create( 9356 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 9357 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 9358 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 9359 InheritedConstructor(), TrailingRequiresClause); 9360 9361 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9362 // This is a C++ destructor declaration. 9363 if (DC->isRecord()) { 9364 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 9365 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 9366 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 9367 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 9368 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9369 /*isImplicitlyDeclared=*/false, ConstexprKind, 9370 TrailingRequiresClause); 9371 // User defined destructors start as not selected if the class definition is still 9372 // not done. 9373 if (Record->isBeingDefined()) 9374 NewDD->setIneligibleOrNotSelected(true); 9375 9376 // If the destructor needs an implicit exception specification, set it 9377 // now. FIXME: It'd be nice to be able to create the right type to start 9378 // with, but the type needs to reference the destructor declaration. 9379 if (SemaRef.getLangOpts().CPlusPlus11) 9380 SemaRef.AdjustDestructorExceptionSpec(NewDD); 9381 9382 IsVirtualOkay = true; 9383 return NewDD; 9384 9385 } else { 9386 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 9387 D.setInvalidType(); 9388 9389 // Create a FunctionDecl to satisfy the function definition parsing 9390 // code path. 9391 return FunctionDecl::Create( 9392 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 9393 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9394 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 9395 } 9396 9397 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 9398 if (!DC->isRecord()) { 9399 SemaRef.Diag(D.getIdentifierLoc(), 9400 diag::err_conv_function_not_member); 9401 return nullptr; 9402 } 9403 9404 SemaRef.CheckConversionDeclarator(D, R, SC); 9405 if (D.isInvalidType()) 9406 return nullptr; 9407 9408 IsVirtualOkay = true; 9409 return CXXConversionDecl::Create( 9410 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 9411 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9412 ExplicitSpecifier, ConstexprKind, SourceLocation(), 9413 TrailingRequiresClause); 9414 9415 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 9416 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC)) 9417 return nullptr; 9418 return CXXDeductionGuideDecl::Create( 9419 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R, 9420 TInfo, D.getEndLoc(), /*Ctor=*/nullptr, 9421 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause); 9422 } else if (DC->isRecord()) { 9423 // If the name of the function is the same as the name of the record, 9424 // then this must be an invalid constructor that has a return type. 9425 // (The parser checks for a return type and makes the declarator a 9426 // constructor if it has no return type). 9427 if (Name.getAsIdentifierInfo() && 9428 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 9429 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 9430 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 9431 << SourceRange(D.getIdentifierLoc()); 9432 return nullptr; 9433 } 9434 9435 // This is a C++ method declaration. 9436 CXXMethodDecl *Ret = CXXMethodDecl::Create( 9437 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 9438 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9439 ConstexprKind, SourceLocation(), TrailingRequiresClause); 9440 IsVirtualOkay = !Ret->isStatic(); 9441 return Ret; 9442 } else { 9443 bool isFriend = 9444 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 9445 if (!isFriend && SemaRef.CurContext->isRecord()) 9446 return nullptr; 9447 9448 // Determine whether the function was written with a 9449 // prototype. This true when: 9450 // - we're in C++ (where every function has a prototype), 9451 return FunctionDecl::Create( 9452 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 9453 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9454 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 9455 } 9456 } 9457 9458 enum OpenCLParamType { 9459 ValidKernelParam, 9460 PtrPtrKernelParam, 9461 PtrKernelParam, 9462 InvalidAddrSpacePtrKernelParam, 9463 InvalidKernelParam, 9464 RecordKernelParam 9465 }; 9466 9467 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 9468 // Size dependent types are just typedefs to normal integer types 9469 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 9470 // integers other than by their names. 9471 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 9472 9473 // Remove typedefs one by one until we reach a typedef 9474 // for a size dependent type. 9475 QualType DesugaredTy = Ty; 9476 do { 9477 ArrayRef<StringRef> Names(SizeTypeNames); 9478 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 9479 if (Names.end() != Match) 9480 return true; 9481 9482 Ty = DesugaredTy; 9483 DesugaredTy = Ty.getSingleStepDesugaredType(C); 9484 } while (DesugaredTy != Ty); 9485 9486 return false; 9487 } 9488 9489 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 9490 if (PT->isDependentType()) 9491 return InvalidKernelParam; 9492 9493 if (PT->isPointerOrReferenceType()) { 9494 QualType PointeeType = PT->getPointeeType(); 9495 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 9496 PointeeType.getAddressSpace() == LangAS::opencl_private || 9497 PointeeType.getAddressSpace() == LangAS::Default) 9498 return InvalidAddrSpacePtrKernelParam; 9499 9500 if (PointeeType->isPointerType()) { 9501 // This is a pointer to pointer parameter. 9502 // Recursively check inner type. 9503 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 9504 if (ParamKind == InvalidAddrSpacePtrKernelParam || 9505 ParamKind == InvalidKernelParam) 9506 return ParamKind; 9507 9508 // OpenCL v3.0 s6.11.a: 9509 // A restriction to pass pointers to pointers only applies to OpenCL C 9510 // v1.2 or below. 9511 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120) 9512 return ValidKernelParam; 9513 9514 return PtrPtrKernelParam; 9515 } 9516 9517 // C++ for OpenCL v1.0 s2.4: 9518 // Moreover the types used in parameters of the kernel functions must be: 9519 // Standard layout types for pointer parameters. The same applies to 9520 // reference if an implementation supports them in kernel parameters. 9521 if (S.getLangOpts().OpenCLCPlusPlus && 9522 !S.getOpenCLOptions().isAvailableOption( 9523 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) { 9524 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl(); 9525 bool IsStandardLayoutType = true; 9526 if (CXXRec) { 9527 // If template type is not ODR-used its definition is only available 9528 // in the template definition not its instantiation. 9529 // FIXME: This logic doesn't work for types that depend on template 9530 // parameter (PR58590). 9531 if (!CXXRec->hasDefinition()) 9532 CXXRec = CXXRec->getTemplateInstantiationPattern(); 9533 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout()) 9534 IsStandardLayoutType = false; 9535 } 9536 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() && 9537 !IsStandardLayoutType) 9538 return InvalidKernelParam; 9539 } 9540 9541 // OpenCL v1.2 s6.9.p: 9542 // A restriction to pass pointers only applies to OpenCL C v1.2 or below. 9543 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120) 9544 return ValidKernelParam; 9545 9546 return PtrKernelParam; 9547 } 9548 9549 // OpenCL v1.2 s6.9.k: 9550 // Arguments to kernel functions in a program cannot be declared with the 9551 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9552 // uintptr_t or a struct and/or union that contain fields declared to be one 9553 // of these built-in scalar types. 9554 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 9555 return InvalidKernelParam; 9556 9557 if (PT->isImageType()) 9558 return PtrKernelParam; 9559 9560 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 9561 return InvalidKernelParam; 9562 9563 // OpenCL extension spec v1.2 s9.5: 9564 // This extension adds support for half scalar and vector types as built-in 9565 // types that can be used for arithmetic operations, conversions etc. 9566 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 9567 PT->isHalfType()) 9568 return InvalidKernelParam; 9569 9570 // Look into an array argument to check if it has a forbidden type. 9571 if (PT->isArrayType()) { 9572 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 9573 // Call ourself to check an underlying type of an array. Since the 9574 // getPointeeOrArrayElementType returns an innermost type which is not an 9575 // array, this recursive call only happens once. 9576 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 9577 } 9578 9579 // C++ for OpenCL v1.0 s2.4: 9580 // Moreover the types used in parameters of the kernel functions must be: 9581 // Trivial and standard-layout types C++17 [basic.types] (plain old data 9582 // types) for parameters passed by value; 9583 if (S.getLangOpts().OpenCLCPlusPlus && 9584 !S.getOpenCLOptions().isAvailableOption( 9585 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 9586 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 9587 return InvalidKernelParam; 9588 9589 if (PT->isRecordType()) 9590 return RecordKernelParam; 9591 9592 return ValidKernelParam; 9593 } 9594 9595 static void checkIsValidOpenCLKernelParameter( 9596 Sema &S, 9597 Declarator &D, 9598 ParmVarDecl *Param, 9599 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 9600 QualType PT = Param->getType(); 9601 9602 // Cache the valid types we encounter to avoid rechecking structs that are 9603 // used again 9604 if (ValidTypes.count(PT.getTypePtr())) 9605 return; 9606 9607 switch (getOpenCLKernelParameterType(S, PT)) { 9608 case PtrPtrKernelParam: 9609 // OpenCL v3.0 s6.11.a: 9610 // A kernel function argument cannot be declared as a pointer to a pointer 9611 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 9612 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 9613 D.setInvalidType(); 9614 return; 9615 9616 case InvalidAddrSpacePtrKernelParam: 9617 // OpenCL v1.0 s6.5: 9618 // __kernel function arguments declared to be a pointer of a type can point 9619 // to one of the following address spaces only : __global, __local or 9620 // __constant. 9621 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 9622 D.setInvalidType(); 9623 return; 9624 9625 // OpenCL v1.2 s6.9.k: 9626 // Arguments to kernel functions in a program cannot be declared with the 9627 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9628 // uintptr_t or a struct and/or union that contain fields declared to be 9629 // one of these built-in scalar types. 9630 9631 case InvalidKernelParam: 9632 // OpenCL v1.2 s6.8 n: 9633 // A kernel function argument cannot be declared 9634 // of event_t type. 9635 // Do not diagnose half type since it is diagnosed as invalid argument 9636 // type for any function elsewhere. 9637 if (!PT->isHalfType()) { 9638 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9639 9640 // Explain what typedefs are involved. 9641 const TypedefType *Typedef = nullptr; 9642 while ((Typedef = PT->getAs<TypedefType>())) { 9643 SourceLocation Loc = Typedef->getDecl()->getLocation(); 9644 // SourceLocation may be invalid for a built-in type. 9645 if (Loc.isValid()) 9646 S.Diag(Loc, diag::note_entity_declared_at) << PT; 9647 PT = Typedef->desugar(); 9648 } 9649 } 9650 9651 D.setInvalidType(); 9652 return; 9653 9654 case PtrKernelParam: 9655 case ValidKernelParam: 9656 ValidTypes.insert(PT.getTypePtr()); 9657 return; 9658 9659 case RecordKernelParam: 9660 break; 9661 } 9662 9663 // Track nested structs we will inspect 9664 SmallVector<const Decl *, 4> VisitStack; 9665 9666 // Track where we are in the nested structs. Items will migrate from 9667 // VisitStack to HistoryStack as we do the DFS for bad field. 9668 SmallVector<const FieldDecl *, 4> HistoryStack; 9669 HistoryStack.push_back(nullptr); 9670 9671 // At this point we already handled everything except of a RecordType or 9672 // an ArrayType of a RecordType. 9673 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 9674 const RecordType *RecTy = 9675 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 9676 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 9677 9678 VisitStack.push_back(RecTy->getDecl()); 9679 assert(VisitStack.back() && "First decl null?"); 9680 9681 do { 9682 const Decl *Next = VisitStack.pop_back_val(); 9683 if (!Next) { 9684 assert(!HistoryStack.empty()); 9685 // Found a marker, we have gone up a level 9686 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 9687 ValidTypes.insert(Hist->getType().getTypePtr()); 9688 9689 continue; 9690 } 9691 9692 // Adds everything except the original parameter declaration (which is not a 9693 // field itself) to the history stack. 9694 const RecordDecl *RD; 9695 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 9696 HistoryStack.push_back(Field); 9697 9698 QualType FieldTy = Field->getType(); 9699 // Other field types (known to be valid or invalid) are handled while we 9700 // walk around RecordDecl::fields(). 9701 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 9702 "Unexpected type."); 9703 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 9704 9705 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 9706 } else { 9707 RD = cast<RecordDecl>(Next); 9708 } 9709 9710 // Add a null marker so we know when we've gone back up a level 9711 VisitStack.push_back(nullptr); 9712 9713 for (const auto *FD : RD->fields()) { 9714 QualType QT = FD->getType(); 9715 9716 if (ValidTypes.count(QT.getTypePtr())) 9717 continue; 9718 9719 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 9720 if (ParamType == ValidKernelParam) 9721 continue; 9722 9723 if (ParamType == RecordKernelParam) { 9724 VisitStack.push_back(FD); 9725 continue; 9726 } 9727 9728 // OpenCL v1.2 s6.9.p: 9729 // Arguments to kernel functions that are declared to be a struct or union 9730 // do not allow OpenCL objects to be passed as elements of the struct or 9731 // union. This restriction was lifted in OpenCL v2.0 with the introduction 9732 // of SVM. 9733 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 9734 ParamType == InvalidAddrSpacePtrKernelParam) { 9735 S.Diag(Param->getLocation(), 9736 diag::err_record_with_pointers_kernel_param) 9737 << PT->isUnionType() 9738 << PT; 9739 } else { 9740 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9741 } 9742 9743 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 9744 << OrigRecDecl->getDeclName(); 9745 9746 // We have an error, now let's go back up through history and show where 9747 // the offending field came from 9748 for (ArrayRef<const FieldDecl *>::const_iterator 9749 I = HistoryStack.begin() + 1, 9750 E = HistoryStack.end(); 9751 I != E; ++I) { 9752 const FieldDecl *OuterField = *I; 9753 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 9754 << OuterField->getType(); 9755 } 9756 9757 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 9758 << QT->isPointerType() 9759 << QT; 9760 D.setInvalidType(); 9761 return; 9762 } 9763 } while (!VisitStack.empty()); 9764 } 9765 9766 /// Find the DeclContext in which a tag is implicitly declared if we see an 9767 /// elaborated type specifier in the specified context, and lookup finds 9768 /// nothing. 9769 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9770 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9771 DC = DC->getParent(); 9772 return DC; 9773 } 9774 9775 /// Find the Scope in which a tag is implicitly declared if we see an 9776 /// elaborated type specifier in the specified context, and lookup finds 9777 /// nothing. 9778 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9779 while (S->isClassScope() || 9780 (LangOpts.CPlusPlus && 9781 S->isFunctionPrototypeScope()) || 9782 ((S->getFlags() & Scope::DeclScope) == 0) || 9783 (S->getEntity() && S->getEntity()->isTransparentContext())) 9784 S = S->getParent(); 9785 return S; 9786 } 9787 9788 /// Determine whether a declaration matches a known function in namespace std. 9789 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, 9790 unsigned BuiltinID) { 9791 switch (BuiltinID) { 9792 case Builtin::BI__GetExceptionInfo: 9793 // No type checking whatsoever. 9794 return Ctx.getTargetInfo().getCXXABI().isMicrosoft(); 9795 9796 case Builtin::BIaddressof: 9797 case Builtin::BI__addressof: 9798 case Builtin::BIforward: 9799 case Builtin::BIforward_like: 9800 case Builtin::BImove: 9801 case Builtin::BImove_if_noexcept: 9802 case Builtin::BIas_const: { 9803 // Ensure that we don't treat the algorithm 9804 // OutputIt std::move(InputIt, InputIt, OutputIt) 9805 // as the builtin std::move. 9806 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 9807 return FPT->getNumParams() == 1 && !FPT->isVariadic(); 9808 } 9809 9810 default: 9811 return false; 9812 } 9813 } 9814 9815 NamedDecl* 9816 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9817 TypeSourceInfo *TInfo, LookupResult &Previous, 9818 MultiTemplateParamsArg TemplateParamListsRef, 9819 bool &AddToScope) { 9820 QualType R = TInfo->getType(); 9821 9822 assert(R->isFunctionType()); 9823 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9824 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9825 9826 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9827 llvm::append_range(TemplateParamLists, TemplateParamListsRef); 9828 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9829 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() && 9830 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9831 TemplateParamLists.back() = Invented; 9832 else 9833 TemplateParamLists.push_back(Invented); 9834 } 9835 9836 // TODO: consider using NameInfo for diagnostic. 9837 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9838 DeclarationName Name = NameInfo.getName(); 9839 StorageClass SC = getFunctionStorageClass(*this, D); 9840 9841 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9842 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9843 diag::err_invalid_thread) 9844 << DeclSpec::getSpecifierName(TSCS); 9845 9846 if (D.isFirstDeclarationOfMember()) 9847 adjustMemberFunctionCC( 9848 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()), 9849 D.isCtorOrDtor(), D.getIdentifierLoc()); 9850 9851 bool isFriend = false; 9852 FunctionTemplateDecl *FunctionTemplate = nullptr; 9853 bool isMemberSpecialization = false; 9854 bool isFunctionTemplateSpecialization = false; 9855 9856 bool HasExplicitTemplateArgs = false; 9857 TemplateArgumentListInfo TemplateArgs; 9858 9859 bool isVirtualOkay = false; 9860 9861 DeclContext *OriginalDC = DC; 9862 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9863 9864 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9865 isVirtualOkay); 9866 if (!NewFD) return nullptr; 9867 9868 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9869 NewFD->setTopLevelDeclInObjCContainer(); 9870 9871 // Set the lexical context. If this is a function-scope declaration, or has a 9872 // C++ scope specifier, or is the object of a friend declaration, the lexical 9873 // context will be different from the semantic context. 9874 NewFD->setLexicalDeclContext(CurContext); 9875 9876 if (IsLocalExternDecl) 9877 NewFD->setLocalExternDecl(); 9878 9879 if (getLangOpts().CPlusPlus) { 9880 // The rules for implicit inlines changed in C++20 for methods and friends 9881 // with an in-class definition (when such a definition is not attached to 9882 // the global module). This does not affect declarations that are already 9883 // inline (whether explicitly or implicitly by being declared constexpr, 9884 // consteval, etc). 9885 // FIXME: We need a better way to separate C++ standard and clang modules. 9886 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules || 9887 !NewFD->getOwningModule() || 9888 NewFD->isFromGlobalModule() || 9889 NewFD->getOwningModule()->isHeaderLikeModule(); 9890 bool isInline = D.getDeclSpec().isInlineSpecified(); 9891 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9892 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9893 isFriend = D.getDeclSpec().isFriendSpecified(); 9894 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) { 9895 // Pre-C++20 [class.friend]p5 9896 // A function can be defined in a friend declaration of a 9897 // class . . . . Such a function is implicitly inline. 9898 // Post C++20 [class.friend]p7 9899 // Such a function is implicitly an inline function if it is attached 9900 // to the global module. 9901 NewFD->setImplicitlyInline(); 9902 } 9903 9904 // If this is a method defined in an __interface, and is not a constructor 9905 // or an overloaded operator, then set the pure flag (isVirtual will already 9906 // return true). 9907 if (const CXXRecordDecl *Parent = 9908 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9909 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9910 NewFD->setIsPureVirtual(true); 9911 9912 // C++ [class.union]p2 9913 // A union can have member functions, but not virtual functions. 9914 if (isVirtual && Parent->isUnion()) { 9915 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9916 NewFD->setInvalidDecl(); 9917 } 9918 if ((Parent->isClass() || Parent->isStruct()) && 9919 Parent->hasAttr<SYCLSpecialClassAttr>() && 9920 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() && 9921 NewFD->getName() == "__init" && D.isFunctionDefinition()) { 9922 if (auto *Def = Parent->getDefinition()) 9923 Def->setInitMethod(true); 9924 } 9925 } 9926 9927 SetNestedNameSpecifier(*this, NewFD, D); 9928 isMemberSpecialization = false; 9929 isFunctionTemplateSpecialization = false; 9930 if (D.isInvalidType()) 9931 NewFD->setInvalidDecl(); 9932 9933 // Match up the template parameter lists with the scope specifier, then 9934 // determine whether we have a template or a template specialization. 9935 bool Invalid = false; 9936 TemplateIdAnnotation *TemplateId = 9937 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9938 ? D.getName().TemplateId 9939 : nullptr; 9940 TemplateParameterList *TemplateParams = 9941 MatchTemplateParametersToScopeSpecifier( 9942 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9943 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend, 9944 isMemberSpecialization, Invalid); 9945 if (TemplateParams) { 9946 // Check that we can declare a template here. 9947 if (CheckTemplateDeclScope(S, TemplateParams)) 9948 NewFD->setInvalidDecl(); 9949 9950 if (TemplateParams->size() > 0) { 9951 // This is a function template 9952 9953 // A destructor cannot be a template. 9954 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9955 Diag(NewFD->getLocation(), diag::err_destructor_template); 9956 NewFD->setInvalidDecl(); 9957 // Function template with explicit template arguments. 9958 } else if (TemplateId) { 9959 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9960 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9961 NewFD->setInvalidDecl(); 9962 } 9963 9964 // If we're adding a template to a dependent context, we may need to 9965 // rebuilding some of the types used within the template parameter list, 9966 // now that we know what the current instantiation is. 9967 if (DC->isDependentContext()) { 9968 ContextRAII SavedContext(*this, DC); 9969 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9970 Invalid = true; 9971 } 9972 9973 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9974 NewFD->getLocation(), 9975 Name, TemplateParams, 9976 NewFD); 9977 FunctionTemplate->setLexicalDeclContext(CurContext); 9978 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9979 9980 // For source fidelity, store the other template param lists. 9981 if (TemplateParamLists.size() > 1) { 9982 NewFD->setTemplateParameterListsInfo(Context, 9983 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9984 .drop_back(1)); 9985 } 9986 } else { 9987 // This is a function template specialization. 9988 isFunctionTemplateSpecialization = true; 9989 // For source fidelity, store all the template param lists. 9990 if (TemplateParamLists.size() > 0) 9991 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9992 9993 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9994 if (isFriend) { 9995 // We want to remove the "template<>", found here. 9996 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9997 9998 // If we remove the template<> and the name is not a 9999 // template-id, we're actually silently creating a problem: 10000 // the friend declaration will refer to an untemplated decl, 10001 // and clearly the user wants a template specialization. So 10002 // we need to insert '<>' after the name. 10003 SourceLocation InsertLoc; 10004 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 10005 InsertLoc = D.getName().getSourceRange().getEnd(); 10006 InsertLoc = getLocForEndOfToken(InsertLoc); 10007 } 10008 10009 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 10010 << Name << RemoveRange 10011 << FixItHint::CreateRemoval(RemoveRange) 10012 << FixItHint::CreateInsertion(InsertLoc, "<>"); 10013 Invalid = true; 10014 10015 // Recover by faking up an empty template argument list. 10016 HasExplicitTemplateArgs = true; 10017 TemplateArgs.setLAngleLoc(InsertLoc); 10018 TemplateArgs.setRAngleLoc(InsertLoc); 10019 } 10020 } 10021 } else { 10022 // Check that we can declare a template here. 10023 if (!TemplateParamLists.empty() && isMemberSpecialization && 10024 CheckTemplateDeclScope(S, TemplateParamLists.back())) 10025 NewFD->setInvalidDecl(); 10026 10027 // All template param lists were matched against the scope specifier: 10028 // this is NOT (an explicit specialization of) a template. 10029 if (TemplateParamLists.size() > 0) 10030 // For source fidelity, store all the template param lists. 10031 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 10032 10033 // "friend void foo<>(int);" is an implicit specialization decl. 10034 if (isFriend && TemplateId) 10035 isFunctionTemplateSpecialization = true; 10036 } 10037 10038 // If this is a function template specialization and the unqualified-id of 10039 // the declarator-id is a template-id, convert the template argument list 10040 // into our AST format and check for unexpanded packs. 10041 if (isFunctionTemplateSpecialization && TemplateId) { 10042 HasExplicitTemplateArgs = true; 10043 10044 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 10045 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 10046 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 10047 TemplateId->NumArgs); 10048 translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 10049 10050 // FIXME: Should we check for unexpanded packs if this was an (invalid) 10051 // declaration of a function template partial specialization? Should we 10052 // consider the unexpanded pack context to be a partial specialization? 10053 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) { 10054 if (DiagnoseUnexpandedParameterPack( 10055 ArgLoc, isFriend ? UPPC_FriendDeclaration 10056 : UPPC_ExplicitSpecialization)) 10057 NewFD->setInvalidDecl(); 10058 } 10059 } 10060 10061 if (Invalid) { 10062 NewFD->setInvalidDecl(); 10063 if (FunctionTemplate) 10064 FunctionTemplate->setInvalidDecl(); 10065 } 10066 10067 // C++ [dcl.fct.spec]p5: 10068 // The virtual specifier shall only be used in declarations of 10069 // nonstatic class member functions that appear within a 10070 // member-specification of a class declaration; see 10.3. 10071 // 10072 if (isVirtual && !NewFD->isInvalidDecl()) { 10073 if (!isVirtualOkay) { 10074 Diag(D.getDeclSpec().getVirtualSpecLoc(), 10075 diag::err_virtual_non_function); 10076 } else if (!CurContext->isRecord()) { 10077 // 'virtual' was specified outside of the class. 10078 Diag(D.getDeclSpec().getVirtualSpecLoc(), 10079 diag::err_virtual_out_of_class) 10080 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 10081 } else if (NewFD->getDescribedFunctionTemplate()) { 10082 // C++ [temp.mem]p3: 10083 // A member function template shall not be virtual. 10084 Diag(D.getDeclSpec().getVirtualSpecLoc(), 10085 diag::err_virtual_member_function_template) 10086 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 10087 } else { 10088 // Okay: Add virtual to the method. 10089 NewFD->setVirtualAsWritten(true); 10090 } 10091 10092 if (getLangOpts().CPlusPlus14 && 10093 NewFD->getReturnType()->isUndeducedType()) 10094 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 10095 } 10096 10097 // C++ [dcl.fct.spec]p3: 10098 // The inline specifier shall not appear on a block scope function 10099 // declaration. 10100 if (isInline && !NewFD->isInvalidDecl()) { 10101 if (CurContext->isFunctionOrMethod()) { 10102 // 'inline' is not allowed on block scope function declaration. 10103 Diag(D.getDeclSpec().getInlineSpecLoc(), 10104 diag::err_inline_declaration_block_scope) << Name 10105 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 10106 } 10107 } 10108 10109 // C++ [dcl.fct.spec]p6: 10110 // The explicit specifier shall be used only in the declaration of a 10111 // constructor or conversion function within its class definition; 10112 // see 12.3.1 and 12.3.2. 10113 if (hasExplicit && !NewFD->isInvalidDecl() && 10114 !isa<CXXDeductionGuideDecl>(NewFD)) { 10115 if (!CurContext->isRecord()) { 10116 // 'explicit' was specified outside of the class. 10117 Diag(D.getDeclSpec().getExplicitSpecLoc(), 10118 diag::err_explicit_out_of_class) 10119 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 10120 } else if (!isa<CXXConstructorDecl>(NewFD) && 10121 !isa<CXXConversionDecl>(NewFD)) { 10122 // 'explicit' was specified on a function that wasn't a constructor 10123 // or conversion function. 10124 Diag(D.getDeclSpec().getExplicitSpecLoc(), 10125 diag::err_explicit_non_ctor_or_conv_function) 10126 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 10127 } 10128 } 10129 10130 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 10131 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 10132 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 10133 // are implicitly inline. 10134 NewFD->setImplicitlyInline(); 10135 10136 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 10137 // be either constructors or to return a literal type. Therefore, 10138 // destructors cannot be declared constexpr. 10139 if (isa<CXXDestructorDecl>(NewFD) && 10140 (!getLangOpts().CPlusPlus20 || 10141 ConstexprKind == ConstexprSpecKind::Consteval)) { 10142 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 10143 << static_cast<int>(ConstexprKind); 10144 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 10145 ? ConstexprSpecKind::Unspecified 10146 : ConstexprSpecKind::Constexpr); 10147 } 10148 // C++20 [dcl.constexpr]p2: An allocation function, or a 10149 // deallocation function shall not be declared with the consteval 10150 // specifier. 10151 if (ConstexprKind == ConstexprSpecKind::Consteval && 10152 (NewFD->getOverloadedOperator() == OO_New || 10153 NewFD->getOverloadedOperator() == OO_Array_New || 10154 NewFD->getOverloadedOperator() == OO_Delete || 10155 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 10156 Diag(D.getDeclSpec().getConstexprSpecLoc(), 10157 diag::err_invalid_consteval_decl_kind) 10158 << NewFD; 10159 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 10160 } 10161 } 10162 10163 // If __module_private__ was specified, mark the function accordingly. 10164 if (D.getDeclSpec().isModulePrivateSpecified()) { 10165 if (isFunctionTemplateSpecialization) { 10166 SourceLocation ModulePrivateLoc 10167 = D.getDeclSpec().getModulePrivateSpecLoc(); 10168 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 10169 << 0 10170 << FixItHint::CreateRemoval(ModulePrivateLoc); 10171 } else { 10172 NewFD->setModulePrivate(); 10173 if (FunctionTemplate) 10174 FunctionTemplate->setModulePrivate(); 10175 } 10176 } 10177 10178 if (isFriend) { 10179 if (FunctionTemplate) { 10180 FunctionTemplate->setObjectOfFriendDecl(); 10181 FunctionTemplate->setAccess(AS_public); 10182 } 10183 NewFD->setObjectOfFriendDecl(); 10184 NewFD->setAccess(AS_public); 10185 } 10186 10187 // If a function is defined as defaulted or deleted, mark it as such now. 10188 // We'll do the relevant checks on defaulted / deleted functions later. 10189 switch (D.getFunctionDefinitionKind()) { 10190 case FunctionDefinitionKind::Declaration: 10191 case FunctionDefinitionKind::Definition: 10192 break; 10193 10194 case FunctionDefinitionKind::Defaulted: 10195 NewFD->setDefaulted(); 10196 break; 10197 10198 case FunctionDefinitionKind::Deleted: 10199 NewFD->setDeletedAsWritten(); 10200 break; 10201 } 10202 10203 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext && 10204 D.isFunctionDefinition()) { 10205 // Pre C++20 [class.mfct]p2: 10206 // A member function may be defined (8.4) in its class definition, in 10207 // which case it is an inline member function (7.1.2) 10208 // Post C++20 [class.mfct]p1: 10209 // If a member function is attached to the global module and is defined 10210 // in its class definition, it is inline. 10211 NewFD->setImplicitlyInline(); 10212 } 10213 10214 if (!isFriend && SC != SC_None) { 10215 // C++ [temp.expl.spec]p2: 10216 // The declaration in an explicit-specialization shall not be an 10217 // export-declaration. An explicit specialization shall not use a 10218 // storage-class-specifier other than thread_local. 10219 // 10220 // We diagnose friend declarations with storage-class-specifiers 10221 // elsewhere. 10222 if (isFunctionTemplateSpecialization || isMemberSpecialization) { 10223 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 10224 diag::ext_explicit_specialization_storage_class) 10225 << FixItHint::CreateRemoval( 10226 D.getDeclSpec().getStorageClassSpecLoc()); 10227 } 10228 10229 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) { 10230 assert(isa<CXXMethodDecl>(NewFD) && 10231 "Out-of-line member function should be a CXXMethodDecl"); 10232 // C++ [class.static]p1: 10233 // A data or function member of a class may be declared static 10234 // in a class definition, in which case it is a static member of 10235 // the class. 10236 10237 // Complain about the 'static' specifier if it's on an out-of-line 10238 // member function definition. 10239 10240 // MSVC permits the use of a 'static' storage specifier on an 10241 // out-of-line member function template declaration and class member 10242 // template declaration (MSVC versions before 2015), warn about this. 10243 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 10244 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 10245 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 10246 (getLangOpts().MSVCCompat && 10247 NewFD->getDescribedFunctionTemplate())) 10248 ? diag::ext_static_out_of_line 10249 : diag::err_static_out_of_line) 10250 << FixItHint::CreateRemoval( 10251 D.getDeclSpec().getStorageClassSpecLoc()); 10252 } 10253 } 10254 10255 // C++11 [except.spec]p15: 10256 // A deallocation function with no exception-specification is treated 10257 // as if it were specified with noexcept(true). 10258 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 10259 if ((Name.getCXXOverloadedOperator() == OO_Delete || 10260 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 10261 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 10262 NewFD->setType(Context.getFunctionType( 10263 FPT->getReturnType(), FPT->getParamTypes(), 10264 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 10265 10266 // C++20 [dcl.inline]/7 10267 // If an inline function or variable that is attached to a named module 10268 // is declared in a definition domain, it shall be defined in that 10269 // domain. 10270 // So, if the current declaration does not have a definition, we must 10271 // check at the end of the TU (or when the PMF starts) to see that we 10272 // have a definition at that point. 10273 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 && 10274 NewFD->isInNamedModule()) { 10275 PendingInlineFuncDecls.insert(NewFD); 10276 } 10277 } 10278 10279 // Filter out previous declarations that don't match the scope. 10280 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 10281 D.getCXXScopeSpec().isNotEmpty() || 10282 isMemberSpecialization || 10283 isFunctionTemplateSpecialization); 10284 10285 // Handle GNU asm-label extension (encoded as an attribute). 10286 if (Expr *E = (Expr*) D.getAsmLabel()) { 10287 // The parser guarantees this is a string. 10288 StringLiteral *SE = cast<StringLiteral>(E); 10289 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 10290 /*IsLiteralLabel=*/true, 10291 SE->getStrTokenLoc(0))); 10292 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 10293 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 10294 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 10295 if (I != ExtnameUndeclaredIdentifiers.end()) { 10296 if (isDeclExternC(NewFD)) { 10297 NewFD->addAttr(I->second); 10298 ExtnameUndeclaredIdentifiers.erase(I); 10299 } else 10300 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 10301 << /*Variable*/0 << NewFD; 10302 } 10303 } 10304 10305 // Copy the parameter declarations from the declarator D to the function 10306 // declaration NewFD, if they are available. First scavenge them into Params. 10307 SmallVector<ParmVarDecl*, 16> Params; 10308 unsigned FTIIdx; 10309 if (D.isFunctionDeclarator(FTIIdx)) { 10310 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 10311 10312 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 10313 // function that takes no arguments, not a function that takes a 10314 // single void argument. 10315 // We let through "const void" here because Sema::GetTypeForDeclarator 10316 // already checks for that case. 10317 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 10318 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 10319 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 10320 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 10321 Param->setDeclContext(NewFD); 10322 Params.push_back(Param); 10323 10324 if (Param->isInvalidDecl()) 10325 NewFD->setInvalidDecl(); 10326 } 10327 } 10328 10329 if (!getLangOpts().CPlusPlus) { 10330 // In C, find all the tag declarations from the prototype and move them 10331 // into the function DeclContext. Remove them from the surrounding tag 10332 // injection context of the function, which is typically but not always 10333 // the TU. 10334 DeclContext *PrototypeTagContext = 10335 getTagInjectionContext(NewFD->getLexicalDeclContext()); 10336 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 10337 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 10338 10339 // We don't want to reparent enumerators. Look at their parent enum 10340 // instead. 10341 if (!TD) { 10342 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 10343 TD = cast<EnumDecl>(ECD->getDeclContext()); 10344 } 10345 if (!TD) 10346 continue; 10347 DeclContext *TagDC = TD->getLexicalDeclContext(); 10348 if (!TagDC->containsDecl(TD)) 10349 continue; 10350 TagDC->removeDecl(TD); 10351 TD->setDeclContext(NewFD); 10352 NewFD->addDecl(TD); 10353 10354 // Preserve the lexical DeclContext if it is not the surrounding tag 10355 // injection context of the FD. In this example, the semantic context of 10356 // E will be f and the lexical context will be S, while both the 10357 // semantic and lexical contexts of S will be f: 10358 // void f(struct S { enum E { a } f; } s); 10359 if (TagDC != PrototypeTagContext) 10360 TD->setLexicalDeclContext(TagDC); 10361 } 10362 } 10363 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 10364 // When we're declaring a function with a typedef, typeof, etc as in the 10365 // following example, we'll need to synthesize (unnamed) 10366 // parameters for use in the declaration. 10367 // 10368 // @code 10369 // typedef void fn(int); 10370 // fn f; 10371 // @endcode 10372 10373 // Synthesize a parameter for each argument type. 10374 for (const auto &AI : FT->param_types()) { 10375 ParmVarDecl *Param = 10376 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 10377 Param->setScopeInfo(0, Params.size()); 10378 Params.push_back(Param); 10379 } 10380 } else { 10381 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 10382 "Should not need args for typedef of non-prototype fn"); 10383 } 10384 10385 // Finally, we know we have the right number of parameters, install them. 10386 NewFD->setParams(Params); 10387 10388 if (D.getDeclSpec().isNoreturnSpecified()) 10389 NewFD->addAttr( 10390 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc())); 10391 10392 // Functions returning a variably modified type violate C99 6.7.5.2p2 10393 // because all functions have linkage. 10394 if (!NewFD->isInvalidDecl() && 10395 NewFD->getReturnType()->isVariablyModifiedType()) { 10396 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 10397 NewFD->setInvalidDecl(); 10398 } 10399 10400 // Apply an implicit SectionAttr if '#pragma clang section text' is active 10401 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 10402 !NewFD->hasAttr<SectionAttr>()) 10403 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 10404 Context, PragmaClangTextSection.SectionName, 10405 PragmaClangTextSection.PragmaLocation)); 10406 10407 // Apply an implicit SectionAttr if #pragma code_seg is active. 10408 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 10409 !NewFD->hasAttr<SectionAttr>()) { 10410 NewFD->addAttr(SectionAttr::CreateImplicit( 10411 Context, CodeSegStack.CurrentValue->getString(), 10412 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate)); 10413 if (UnifySection(CodeSegStack.CurrentValue->getString(), 10414 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 10415 ASTContext::PSF_Read, 10416 NewFD)) 10417 NewFD->dropAttr<SectionAttr>(); 10418 } 10419 10420 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is 10421 // active. 10422 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() && 10423 !NewFD->hasAttr<StrictGuardStackCheckAttr>()) 10424 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit( 10425 Context, PragmaClangTextSection.PragmaLocation)); 10426 10427 // Apply an implicit CodeSegAttr from class declspec or 10428 // apply an implicit SectionAttr from #pragma code_seg if active. 10429 if (!NewFD->hasAttr<CodeSegAttr>()) { 10430 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 10431 D.isFunctionDefinition())) { 10432 NewFD->addAttr(SAttr); 10433 } 10434 } 10435 10436 // Handle attributes. 10437 ProcessDeclAttributes(S, NewFD, D); 10438 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 10439 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA && 10440 !NewTVA->isDefaultVersion() && 10441 !Context.getTargetInfo().hasFeature("fmv")) { 10442 // Don't add to scope fmv functions declarations if fmv disabled 10443 AddToScope = false; 10444 return NewFD; 10445 } 10446 10447 if (getLangOpts().OpenCL || getLangOpts().HLSL) { 10448 // Neither OpenCL nor HLSL allow an address space qualifyer on a return 10449 // type. 10450 // 10451 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 10452 // type declaration will generate a compilation error. 10453 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 10454 if (AddressSpace != LangAS::Default) { 10455 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space); 10456 NewFD->setInvalidDecl(); 10457 } 10458 } 10459 10460 if (!getLangOpts().CPlusPlus) { 10461 // Perform semantic checking on the function declaration. 10462 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 10463 CheckMain(NewFD, D.getDeclSpec()); 10464 10465 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 10466 CheckMSVCRTEntryPoint(NewFD); 10467 10468 if (!NewFD->isInvalidDecl()) 10469 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 10470 isMemberSpecialization, 10471 D.isFunctionDefinition())); 10472 else if (!Previous.empty()) 10473 // Recover gracefully from an invalid redeclaration. 10474 D.setRedeclaration(true); 10475 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 10476 Previous.getResultKind() != LookupResult::FoundOverloaded) && 10477 "previous declaration set still overloaded"); 10478 10479 // Diagnose no-prototype function declarations with calling conventions that 10480 // don't support variadic calls. Only do this in C and do it after merging 10481 // possibly prototyped redeclarations. 10482 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 10483 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 10484 CallingConv CC = FT->getExtInfo().getCC(); 10485 if (!supportsVariadicCall(CC)) { 10486 // Windows system headers sometimes accidentally use stdcall without 10487 // (void) parameters, so we relax this to a warning. 10488 int DiagID = 10489 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 10490 Diag(NewFD->getLocation(), DiagID) 10491 << FunctionType::getNameForCallConv(CC); 10492 } 10493 } 10494 10495 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 10496 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 10497 checkNonTrivialCUnion(NewFD->getReturnType(), 10498 NewFD->getReturnTypeSourceRange().getBegin(), 10499 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 10500 } else { 10501 // C++11 [replacement.functions]p3: 10502 // The program's definitions shall not be specified as inline. 10503 // 10504 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 10505 // 10506 // Suppress the diagnostic if the function is __attribute__((used)), since 10507 // that forces an external definition to be emitted. 10508 if (D.getDeclSpec().isInlineSpecified() && 10509 NewFD->isReplaceableGlobalAllocationFunction() && 10510 !NewFD->hasAttr<UsedAttr>()) 10511 Diag(D.getDeclSpec().getInlineSpecLoc(), 10512 diag::ext_operator_new_delete_declared_inline) 10513 << NewFD->getDeclName(); 10514 10515 if (Expr *TRC = NewFD->getTrailingRequiresClause()) { 10516 // C++20 [dcl.decl.general]p4: 10517 // The optional requires-clause in an init-declarator or 10518 // member-declarator shall be present only if the declarator declares a 10519 // templated function. 10520 // 10521 // C++20 [temp.pre]p8: 10522 // An entity is templated if it is 10523 // - a template, 10524 // - an entity defined or created in a templated entity, 10525 // - a member of a templated entity, 10526 // - an enumerator for an enumeration that is a templated entity, or 10527 // - the closure type of a lambda-expression appearing in the 10528 // declaration of a templated entity. 10529 // 10530 // [Note 6: A local class, a local or block variable, or a friend 10531 // function defined in a templated entity is a templated entity. 10532 // — end note] 10533 // 10534 // A templated function is a function template or a function that is 10535 // templated. A templated class is a class template or a class that is 10536 // templated. A templated variable is a variable template or a variable 10537 // that is templated. 10538 if (!FunctionTemplate) { 10539 if (isFunctionTemplateSpecialization || isMemberSpecialization) { 10540 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847): 10541 // An explicit specialization shall not have a trailing 10542 // requires-clause unless it declares a function template. 10543 // 10544 // Since a friend function template specialization cannot be 10545 // definition, and since a non-template friend declaration with a 10546 // trailing requires-clause must be a definition, we diagnose 10547 // friend function template specializations with trailing 10548 // requires-clauses on the same path as explicit specializations 10549 // even though they aren't necessarily prohibited by the same 10550 // language rule. 10551 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause) 10552 << isFriend; 10553 } else if (isFriend && NewFD->isTemplated() && 10554 !D.isFunctionDefinition()) { 10555 // C++ [temp.friend]p9: 10556 // A non-template friend declaration with a requires-clause shall be 10557 // a definition. 10558 Diag(NewFD->getBeginLoc(), 10559 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def); 10560 NewFD->setInvalidDecl(); 10561 } else if (!NewFD->isTemplated() || 10562 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) { 10563 Diag(TRC->getBeginLoc(), 10564 diag::err_constrained_non_templated_function); 10565 } 10566 } 10567 } 10568 10569 // We do not add HD attributes to specializations here because 10570 // they may have different constexpr-ness compared to their 10571 // templates and, after maybeAddHostDeviceAttrs() is applied, 10572 // may end up with different effective targets. Instead, a 10573 // specialization inherits its target attributes from its template 10574 // in the CheckFunctionTemplateSpecialization() call below. 10575 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 10576 CUDA().maybeAddHostDeviceAttrs(NewFD, Previous); 10577 10578 // Handle explicit specializations of function templates 10579 // and friend function declarations with an explicit 10580 // template argument list. 10581 if (isFunctionTemplateSpecialization) { 10582 bool isDependentSpecialization = false; 10583 if (isFriend) { 10584 // For friend function specializations, this is a dependent 10585 // specialization if its semantic context is dependent, its 10586 // type is dependent, or if its template-id is dependent. 10587 isDependentSpecialization = 10588 DC->isDependentContext() || NewFD->getType()->isDependentType() || 10589 (HasExplicitTemplateArgs && 10590 TemplateSpecializationType:: 10591 anyInstantiationDependentTemplateArguments( 10592 TemplateArgs.arguments())); 10593 assert((!isDependentSpecialization || 10594 (HasExplicitTemplateArgs == isDependentSpecialization)) && 10595 "dependent friend function specialization without template " 10596 "args"); 10597 } else { 10598 // For class-scope explicit specializations of function templates, 10599 // if the lexical context is dependent, then the specialization 10600 // is dependent. 10601 isDependentSpecialization = 10602 CurContext->isRecord() && CurContext->isDependentContext(); 10603 } 10604 10605 TemplateArgumentListInfo *ExplicitTemplateArgs = 10606 HasExplicitTemplateArgs ? &TemplateArgs : nullptr; 10607 if (isDependentSpecialization) { 10608 // If it's a dependent specialization, it may not be possible 10609 // to determine the primary template (for explicit specializations) 10610 // or befriended declaration (for friends) until the enclosing 10611 // template is instantiated. In such cases, we store the declarations 10612 // found by name lookup and defer resolution until instantiation. 10613 if (CheckDependentFunctionTemplateSpecialization( 10614 NewFD, ExplicitTemplateArgs, Previous)) 10615 NewFD->setInvalidDecl(); 10616 } else if (!NewFD->isInvalidDecl()) { 10617 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs, 10618 Previous)) 10619 NewFD->setInvalidDecl(); 10620 } 10621 } else if (isMemberSpecialization && !FunctionTemplate) { 10622 if (CheckMemberSpecialization(NewFD, Previous)) 10623 NewFD->setInvalidDecl(); 10624 } 10625 10626 // Perform semantic checking on the function declaration. 10627 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 10628 CheckMain(NewFD, D.getDeclSpec()); 10629 10630 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 10631 CheckMSVCRTEntryPoint(NewFD); 10632 10633 if (!NewFD->isInvalidDecl()) 10634 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 10635 isMemberSpecialization, 10636 D.isFunctionDefinition())); 10637 else if (!Previous.empty()) 10638 // Recover gracefully from an invalid redeclaration. 10639 D.setRedeclaration(true); 10640 10641 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() || 10642 !D.isRedeclaration() || 10643 Previous.getResultKind() != LookupResult::FoundOverloaded) && 10644 "previous declaration set still overloaded"); 10645 10646 NamedDecl *PrincipalDecl = (FunctionTemplate 10647 ? cast<NamedDecl>(FunctionTemplate) 10648 : NewFD); 10649 10650 if (isFriend && NewFD->getPreviousDecl()) { 10651 AccessSpecifier Access = AS_public; 10652 if (!NewFD->isInvalidDecl()) 10653 Access = NewFD->getPreviousDecl()->getAccess(); 10654 10655 NewFD->setAccess(Access); 10656 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 10657 } 10658 10659 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 10660 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 10661 PrincipalDecl->setNonMemberOperator(); 10662 10663 // If we have a function template, check the template parameter 10664 // list. This will check and merge default template arguments. 10665 if (FunctionTemplate) { 10666 FunctionTemplateDecl *PrevTemplate = 10667 FunctionTemplate->getPreviousDecl(); 10668 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 10669 PrevTemplate ? PrevTemplate->getTemplateParameters() 10670 : nullptr, 10671 D.getDeclSpec().isFriendSpecified() 10672 ? (D.isFunctionDefinition() 10673 ? TPC_FriendFunctionTemplateDefinition 10674 : TPC_FriendFunctionTemplate) 10675 : (D.getCXXScopeSpec().isSet() && 10676 DC && DC->isRecord() && 10677 DC->isDependentContext()) 10678 ? TPC_ClassTemplateMember 10679 : TPC_FunctionTemplate); 10680 } 10681 10682 if (NewFD->isInvalidDecl()) { 10683 // Ignore all the rest of this. 10684 } else if (!D.isRedeclaration()) { 10685 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 10686 AddToScope }; 10687 // Fake up an access specifier if it's supposed to be a class member. 10688 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 10689 NewFD->setAccess(AS_public); 10690 10691 // Qualified decls generally require a previous declaration. 10692 if (D.getCXXScopeSpec().isSet()) { 10693 // ...with the major exception of templated-scope or 10694 // dependent-scope friend declarations. 10695 10696 // TODO: we currently also suppress this check in dependent 10697 // contexts because (1) the parameter depth will be off when 10698 // matching friend templates and (2) we might actually be 10699 // selecting a friend based on a dependent factor. But there 10700 // are situations where these conditions don't apply and we 10701 // can actually do this check immediately. 10702 // 10703 // Unless the scope is dependent, it's always an error if qualified 10704 // redeclaration lookup found nothing at all. Diagnose that now; 10705 // nothing will diagnose that error later. 10706 if (isFriend && 10707 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 10708 (!Previous.empty() && CurContext->isDependentContext()))) { 10709 // ignore these 10710 } else if (NewFD->isCPUDispatchMultiVersion() || 10711 NewFD->isCPUSpecificMultiVersion()) { 10712 // ignore this, we allow the redeclaration behavior here to create new 10713 // versions of the function. 10714 } else { 10715 // The user tried to provide an out-of-line definition for a 10716 // function that is a member of a class or namespace, but there 10717 // was no such member function declared (C++ [class.mfct]p2, 10718 // C++ [namespace.memdef]p2). For example: 10719 // 10720 // class X { 10721 // void f() const; 10722 // }; 10723 // 10724 // void X::f() { } // ill-formed 10725 // 10726 // Complain about this problem, and attempt to suggest close 10727 // matches (e.g., those that differ only in cv-qualifiers and 10728 // whether the parameter types are references). 10729 10730 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10731 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 10732 AddToScope = ExtraArgs.AddToScope; 10733 return Result; 10734 } 10735 } 10736 10737 // Unqualified local friend declarations are required to resolve 10738 // to something. 10739 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 10740 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10741 *this, Previous, NewFD, ExtraArgs, true, S)) { 10742 AddToScope = ExtraArgs.AddToScope; 10743 return Result; 10744 } 10745 } 10746 } else if (!D.isFunctionDefinition() && 10747 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 10748 !isFriend && !isFunctionTemplateSpecialization && 10749 !isMemberSpecialization) { 10750 // An out-of-line member function declaration must also be a 10751 // definition (C++ [class.mfct]p2). 10752 // Note that this is not the case for explicit specializations of 10753 // function templates or member functions of class templates, per 10754 // C++ [temp.expl.spec]p2. We also allow these declarations as an 10755 // extension for compatibility with old SWIG code which likes to 10756 // generate them. 10757 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 10758 << D.getCXXScopeSpec().getRange(); 10759 } 10760 } 10761 10762 if (getLangOpts().HLSL && D.isFunctionDefinition()) { 10763 // Any top level function could potentially be specified as an entry. 10764 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier()) 10765 HLSL().ActOnTopLevelFunction(NewFD); 10766 10767 if (NewFD->hasAttr<HLSLShaderAttr>()) 10768 HLSL().CheckEntryPoint(NewFD); 10769 } 10770 10771 // If this is the first declaration of a library builtin function, add 10772 // attributes as appropriate. 10773 if (!D.isRedeclaration()) { 10774 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 10775 if (unsigned BuiltinID = II->getBuiltinID()) { 10776 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID); 10777 if (!InStdNamespace && 10778 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 10779 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 10780 // Validate the type matches unless this builtin is specified as 10781 // matching regardless of its declared type. 10782 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 10783 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10784 } else { 10785 ASTContext::GetBuiltinTypeError Error; 10786 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10787 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 10788 10789 if (!Error && !BuiltinType.isNull() && 10790 Context.hasSameFunctionTypeIgnoringExceptionSpec( 10791 NewFD->getType(), BuiltinType)) 10792 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10793 } 10794 } 10795 } else if (InStdNamespace && NewFD->isInStdNamespace() && 10796 isStdBuiltin(Context, NewFD, BuiltinID)) { 10797 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10798 } 10799 } 10800 } 10801 } 10802 10803 ProcessPragmaWeak(S, NewFD); 10804 checkAttributesAfterMerging(*this, *NewFD); 10805 10806 AddKnownFunctionAttributes(NewFD); 10807 10808 if (NewFD->hasAttr<OverloadableAttr>() && 10809 !NewFD->getType()->getAs<FunctionProtoType>()) { 10810 Diag(NewFD->getLocation(), 10811 diag::err_attribute_overloadable_no_prototype) 10812 << NewFD; 10813 NewFD->dropAttr<OverloadableAttr>(); 10814 } 10815 10816 // If there's a #pragma GCC visibility in scope, and this isn't a class 10817 // member, set the visibility of this function. 10818 if (!DC->isRecord() && NewFD->isExternallyVisible()) 10819 AddPushedVisibilityAttribute(NewFD); 10820 10821 // If there's a #pragma clang arc_cf_code_audited in scope, consider 10822 // marking the function. 10823 ObjC().AddCFAuditedAttribute(NewFD); 10824 10825 // If this is a function definition, check if we have to apply any 10826 // attributes (i.e. optnone and no_builtin) due to a pragma. 10827 if (D.isFunctionDefinition()) { 10828 AddRangeBasedOptnone(NewFD); 10829 AddImplicitMSFunctionNoBuiltinAttr(NewFD); 10830 AddSectionMSAllocText(NewFD); 10831 ModifyFnAttributesMSPragmaOptimize(NewFD); 10832 } 10833 10834 // If this is the first declaration of an extern C variable, update 10835 // the map of such variables. 10836 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 10837 isIncompleteDeclExternC(*this, NewFD)) 10838 RegisterLocallyScopedExternCDecl(NewFD, S); 10839 10840 // Set this FunctionDecl's range up to the right paren. 10841 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 10842 10843 if (D.isRedeclaration() && !Previous.empty()) { 10844 NamedDecl *Prev = Previous.getRepresentativeDecl(); 10845 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 10846 isMemberSpecialization || 10847 isFunctionTemplateSpecialization, 10848 D.isFunctionDefinition()); 10849 } 10850 10851 if (getLangOpts().CUDA) { 10852 IdentifierInfo *II = NewFD->getIdentifier(); 10853 if (II && II->isStr(CUDA().getConfigureFuncName()) && 10854 !NewFD->isInvalidDecl() && 10855 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 10856 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 10857 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 10858 << CUDA().getConfigureFuncName(); 10859 Context.setcudaConfigureCallDecl(NewFD); 10860 } 10861 10862 // Variadic functions, other than a *declaration* of printf, are not allowed 10863 // in device-side CUDA code, unless someone passed 10864 // -fcuda-allow-variadic-functions. 10865 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 10866 (NewFD->hasAttr<CUDADeviceAttr>() || 10867 NewFD->hasAttr<CUDAGlobalAttr>()) && 10868 !(II && II->isStr("printf") && NewFD->isExternC() && 10869 !D.isFunctionDefinition())) { 10870 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 10871 } 10872 } 10873 10874 MarkUnusedFileScopedDecl(NewFD); 10875 10876 10877 10878 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 10879 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 10880 if (SC == SC_Static) { 10881 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 10882 D.setInvalidType(); 10883 } 10884 10885 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 10886 if (!NewFD->getReturnType()->isVoidType()) { 10887 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 10888 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 10889 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 10890 : FixItHint()); 10891 D.setInvalidType(); 10892 } 10893 10894 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 10895 for (auto *Param : NewFD->parameters()) 10896 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 10897 10898 if (getLangOpts().OpenCLCPlusPlus) { 10899 if (DC->isRecord()) { 10900 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 10901 D.setInvalidType(); 10902 } 10903 if (FunctionTemplate) { 10904 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10905 D.setInvalidType(); 10906 } 10907 } 10908 } 10909 10910 if (getLangOpts().CPlusPlus) { 10911 // Precalculate whether this is a friend function template with a constraint 10912 // that depends on an enclosing template, per [temp.friend]p9. 10913 if (isFriend && FunctionTemplate && 10914 FriendConstraintsDependOnEnclosingTemplate(NewFD)) { 10915 NewFD->setFriendConstraintRefersToEnclosingTemplate(true); 10916 10917 // C++ [temp.friend]p9: 10918 // A friend function template with a constraint that depends on a 10919 // template parameter from an enclosing template shall be a definition. 10920 if (!D.isFunctionDefinition()) { 10921 Diag(NewFD->getBeginLoc(), 10922 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def); 10923 NewFD->setInvalidDecl(); 10924 } 10925 } 10926 10927 if (FunctionTemplate) { 10928 if (NewFD->isInvalidDecl()) 10929 FunctionTemplate->setInvalidDecl(); 10930 return FunctionTemplate; 10931 } 10932 10933 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10934 CompleteMemberSpecialization(NewFD, Previous); 10935 } 10936 10937 for (const ParmVarDecl *Param : NewFD->parameters()) { 10938 QualType PT = Param->getType(); 10939 10940 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10941 // types. 10942 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10943 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10944 QualType ElemTy = PipeTy->getElementType(); 10945 if (ElemTy->isPointerOrReferenceType()) { 10946 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type); 10947 D.setInvalidType(); 10948 } 10949 } 10950 } 10951 // WebAssembly tables can't be used as function parameters. 10952 if (Context.getTargetInfo().getTriple().isWasm()) { 10953 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) { 10954 Diag(Param->getTypeSpecStartLoc(), 10955 diag::err_wasm_table_as_function_parameter); 10956 D.setInvalidType(); 10957 } 10958 } 10959 } 10960 10961 // Diagnose availability attributes. Availability cannot be used on functions 10962 // that are run during load/unload. 10963 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10964 if (NewFD->hasAttr<ConstructorAttr>()) { 10965 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10966 << 1; 10967 NewFD->dropAttr<AvailabilityAttr>(); 10968 } 10969 if (NewFD->hasAttr<DestructorAttr>()) { 10970 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10971 << 2; 10972 NewFD->dropAttr<AvailabilityAttr>(); 10973 } 10974 } 10975 10976 // Diagnose no_builtin attribute on function declaration that are not a 10977 // definition. 10978 // FIXME: We should really be doing this in 10979 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10980 // the FunctionDecl and at this point of the code 10981 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10982 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10983 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10984 switch (D.getFunctionDefinitionKind()) { 10985 case FunctionDefinitionKind::Defaulted: 10986 case FunctionDefinitionKind::Deleted: 10987 Diag(NBA->getLocation(), 10988 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10989 << NBA->getSpelling(); 10990 break; 10991 case FunctionDefinitionKind::Declaration: 10992 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10993 << NBA->getSpelling(); 10994 break; 10995 case FunctionDefinitionKind::Definition: 10996 break; 10997 } 10998 10999 // Similar to no_builtin logic above, at this point of the code 11000 // FunctionDecl::isThisDeclarationADefinition() always returns `false` 11001 // because Sema::ActOnStartOfFunctionDef has not been called yet. 11002 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 11003 !NewFD->isInvalidDecl() && 11004 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration) 11005 ExternalDeclarations.push_back(NewFD); 11006 11007 return NewFD; 11008 } 11009 11010 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 11011 /// when __declspec(code_seg) "is applied to a class, all member functions of 11012 /// the class and nested classes -- this includes compiler-generated special 11013 /// member functions -- are put in the specified segment." 11014 /// The actual behavior is a little more complicated. The Microsoft compiler 11015 /// won't check outer classes if there is an active value from #pragma code_seg. 11016 /// The CodeSeg is always applied from the direct parent but only from outer 11017 /// classes when the #pragma code_seg stack is empty. See: 11018 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 11019 /// available since MS has removed the page. 11020 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 11021 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 11022 if (!Method) 11023 return nullptr; 11024 const CXXRecordDecl *Parent = Method->getParent(); 11025 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 11026 Attr *NewAttr = SAttr->clone(S.getASTContext()); 11027 NewAttr->setImplicit(true); 11028 return NewAttr; 11029 } 11030 11031 // The Microsoft compiler won't check outer classes for the CodeSeg 11032 // when the #pragma code_seg stack is active. 11033 if (S.CodeSegStack.CurrentValue) 11034 return nullptr; 11035 11036 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 11037 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 11038 Attr *NewAttr = SAttr->clone(S.getASTContext()); 11039 NewAttr->setImplicit(true); 11040 return NewAttr; 11041 } 11042 } 11043 return nullptr; 11044 } 11045 11046 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 11047 bool IsDefinition) { 11048 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 11049 return A; 11050 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 11051 CodeSegStack.CurrentValue) 11052 return SectionAttr::CreateImplicit( 11053 getASTContext(), CodeSegStack.CurrentValue->getString(), 11054 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate); 11055 return nullptr; 11056 } 11057 11058 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 11059 QualType NewT, QualType OldT) { 11060 if (!NewD->getLexicalDeclContext()->isDependentContext()) 11061 return true; 11062 11063 // For dependently-typed local extern declarations and friends, we can't 11064 // perform a correct type check in general until instantiation: 11065 // 11066 // int f(); 11067 // template<typename T> void g() { T f(); } 11068 // 11069 // (valid if g() is only instantiated with T = int). 11070 if (NewT->isDependentType() && 11071 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 11072 return false; 11073 11074 // Similarly, if the previous declaration was a dependent local extern 11075 // declaration, we don't really know its type yet. 11076 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 11077 return false; 11078 11079 return true; 11080 } 11081 11082 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 11083 if (!D->getLexicalDeclContext()->isDependentContext()) 11084 return true; 11085 11086 // Don't chain dependent friend function definitions until instantiation, to 11087 // permit cases like 11088 // 11089 // void func(); 11090 // template<typename T> class C1 { friend void func() {} }; 11091 // template<typename T> class C2 { friend void func() {} }; 11092 // 11093 // ... which is valid if only one of C1 and C2 is ever instantiated. 11094 // 11095 // FIXME: This need only apply to function definitions. For now, we proxy 11096 // this by checking for a file-scope function. We do not want this to apply 11097 // to friend declarations nominating member functions, because that gets in 11098 // the way of access checks. 11099 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 11100 return false; 11101 11102 auto *VD = dyn_cast<ValueDecl>(D); 11103 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 11104 return !VD || !PrevVD || 11105 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 11106 PrevVD->getType()); 11107 } 11108 11109 /// Check the target or target_version attribute of the function for 11110 /// MultiVersion validity. 11111 /// 11112 /// Returns true if there was an error, false otherwise. 11113 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 11114 const auto *TA = FD->getAttr<TargetAttr>(); 11115 const auto *TVA = FD->getAttr<TargetVersionAttr>(); 11116 11117 assert((TA || TVA) && "Expecting target or target_version attribute"); 11118 11119 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 11120 enum ErrType { Feature = 0, Architecture = 1 }; 11121 11122 if (TA) { 11123 ParsedTargetAttr ParseInfo = 11124 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr()); 11125 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) { 11126 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11127 << Architecture << ParseInfo.CPU; 11128 return true; 11129 } 11130 for (const auto &Feat : ParseInfo.Features) { 11131 auto BareFeat = StringRef{Feat}.substr(1); 11132 if (Feat[0] == '-') { 11133 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11134 << Feature << ("no-" + BareFeat).str(); 11135 return true; 11136 } 11137 11138 if (!TargetInfo.validateCpuSupports(BareFeat) || 11139 !TargetInfo.isValidFeatureName(BareFeat) || 11140 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) { 11141 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11142 << Feature << BareFeat; 11143 return true; 11144 } 11145 } 11146 } 11147 11148 if (TVA) { 11149 llvm::SmallVector<StringRef, 8> Feats; 11150 ParsedTargetAttr ParseInfo; 11151 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) { 11152 ParseInfo = 11153 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName()); 11154 for (auto &Feat : ParseInfo.Features) 11155 Feats.push_back(StringRef{Feat}.substr(1)); 11156 } else { 11157 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64()); 11158 TVA->getFeatures(Feats); 11159 } 11160 for (const auto &Feat : Feats) { 11161 if (!TargetInfo.validateCpuSupports(Feat)) { 11162 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11163 << Feature << Feat; 11164 return true; 11165 } 11166 } 11167 } 11168 return false; 11169 } 11170 11171 // Provide a white-list of attributes that are allowed to be combined with 11172 // multiversion functions. 11173 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 11174 MultiVersionKind MVKind) { 11175 // Note: this list/diagnosis must match the list in 11176 // checkMultiversionAttributesAllSame. 11177 switch (Kind) { 11178 default: 11179 return false; 11180 case attr::ArmLocallyStreaming: 11181 return MVKind == MultiVersionKind::TargetVersion || 11182 MVKind == MultiVersionKind::TargetClones; 11183 case attr::Used: 11184 return MVKind == MultiVersionKind::Target; 11185 case attr::NonNull: 11186 case attr::NoThrow: 11187 return true; 11188 } 11189 } 11190 11191 static bool checkNonMultiVersionCompatAttributes(Sema &S, 11192 const FunctionDecl *FD, 11193 const FunctionDecl *CausedFD, 11194 MultiVersionKind MVKind) { 11195 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) { 11196 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 11197 << static_cast<unsigned>(MVKind) << A; 11198 if (CausedFD) 11199 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 11200 return true; 11201 }; 11202 11203 for (const Attr *A : FD->attrs()) { 11204 switch (A->getKind()) { 11205 case attr::CPUDispatch: 11206 case attr::CPUSpecific: 11207 if (MVKind != MultiVersionKind::CPUDispatch && 11208 MVKind != MultiVersionKind::CPUSpecific) 11209 return Diagnose(S, A); 11210 break; 11211 case attr::Target: 11212 if (MVKind != MultiVersionKind::Target) 11213 return Diagnose(S, A); 11214 break; 11215 case attr::TargetVersion: 11216 if (MVKind != MultiVersionKind::TargetVersion && 11217 MVKind != MultiVersionKind::TargetClones) 11218 return Diagnose(S, A); 11219 break; 11220 case attr::TargetClones: 11221 if (MVKind != MultiVersionKind::TargetClones && 11222 MVKind != MultiVersionKind::TargetVersion) 11223 return Diagnose(S, A); 11224 break; 11225 default: 11226 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind)) 11227 return Diagnose(S, A); 11228 break; 11229 } 11230 } 11231 return false; 11232 } 11233 11234 bool Sema::areMultiversionVariantFunctionsCompatible( 11235 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 11236 const PartialDiagnostic &NoProtoDiagID, 11237 const PartialDiagnosticAt &NoteCausedDiagIDAt, 11238 const PartialDiagnosticAt &NoSupportDiagIDAt, 11239 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 11240 bool ConstexprSupported, bool CLinkageMayDiffer) { 11241 enum DoesntSupport { 11242 FuncTemplates = 0, 11243 VirtFuncs = 1, 11244 DeducedReturn = 2, 11245 Constructors = 3, 11246 Destructors = 4, 11247 DeletedFuncs = 5, 11248 DefaultedFuncs = 6, 11249 ConstexprFuncs = 7, 11250 ConstevalFuncs = 8, 11251 Lambda = 9, 11252 }; 11253 enum Different { 11254 CallingConv = 0, 11255 ReturnType = 1, 11256 ConstexprSpec = 2, 11257 InlineSpec = 3, 11258 Linkage = 4, 11259 LanguageLinkage = 5, 11260 }; 11261 11262 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 11263 !OldFD->getType()->getAs<FunctionProtoType>()) { 11264 Diag(OldFD->getLocation(), NoProtoDiagID); 11265 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 11266 return true; 11267 } 11268 11269 if (NoProtoDiagID.getDiagID() != 0 && 11270 !NewFD->getType()->getAs<FunctionProtoType>()) 11271 return Diag(NewFD->getLocation(), NoProtoDiagID); 11272 11273 if (!TemplatesSupported && 11274 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11275 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11276 << FuncTemplates; 11277 11278 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 11279 if (NewCXXFD->isVirtual()) 11280 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11281 << VirtFuncs; 11282 11283 if (isa<CXXConstructorDecl>(NewCXXFD)) 11284 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11285 << Constructors; 11286 11287 if (isa<CXXDestructorDecl>(NewCXXFD)) 11288 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11289 << Destructors; 11290 } 11291 11292 if (NewFD->isDeleted()) 11293 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11294 << DeletedFuncs; 11295 11296 if (NewFD->isDefaulted()) 11297 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11298 << DefaultedFuncs; 11299 11300 if (!ConstexprSupported && NewFD->isConstexpr()) 11301 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11302 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 11303 11304 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 11305 const auto *NewType = cast<FunctionType>(NewQType); 11306 QualType NewReturnType = NewType->getReturnType(); 11307 11308 if (NewReturnType->isUndeducedType()) 11309 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11310 << DeducedReturn; 11311 11312 // Ensure the return type is identical. 11313 if (OldFD) { 11314 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 11315 const auto *OldType = cast<FunctionType>(OldQType); 11316 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 11317 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 11318 11319 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>(); 11320 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>(); 11321 11322 bool ArmStreamingCCMismatched = false; 11323 if (OldFPT && NewFPT) { 11324 unsigned Diff = 11325 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes(); 11326 // Arm-streaming, arm-streaming-compatible and non-streaming versions 11327 // cannot be mixed. 11328 if (Diff & (FunctionType::SME_PStateSMEnabledMask | 11329 FunctionType::SME_PStateSMCompatibleMask)) 11330 ArmStreamingCCMismatched = true; 11331 } 11332 11333 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched) 11334 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 11335 11336 QualType OldReturnType = OldType->getReturnType(); 11337 11338 if (OldReturnType != NewReturnType) 11339 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 11340 11341 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 11342 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 11343 11344 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 11345 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 11346 11347 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 11348 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 11349 11350 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 11351 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 11352 11353 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT, 11354 NewFD->getLocation())) 11355 return true; 11356 } 11357 return false; 11358 } 11359 11360 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 11361 const FunctionDecl *NewFD, 11362 bool CausesMV, 11363 MultiVersionKind MVKind) { 11364 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 11365 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 11366 if (OldFD) 11367 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11368 return true; 11369 } 11370 11371 bool IsCPUSpecificCPUDispatchMVKind = 11372 MVKind == MultiVersionKind::CPUDispatch || 11373 MVKind == MultiVersionKind::CPUSpecific; 11374 11375 if (CausesMV && OldFD && 11376 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind)) 11377 return true; 11378 11379 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind)) 11380 return true; 11381 11382 // Only allow transition to MultiVersion if it hasn't been used. 11383 if (OldFD && CausesMV && OldFD->isUsed(false)) { 11384 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 11385 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11386 return true; 11387 } 11388 11389 return S.areMultiversionVariantFunctionsCompatible( 11390 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 11391 PartialDiagnosticAt(NewFD->getLocation(), 11392 S.PDiag(diag::note_multiversioning_caused_here)), 11393 PartialDiagnosticAt(NewFD->getLocation(), 11394 S.PDiag(diag::err_multiversion_doesnt_support) 11395 << static_cast<unsigned>(MVKind)), 11396 PartialDiagnosticAt(NewFD->getLocation(), 11397 S.PDiag(diag::err_multiversion_diff)), 11398 /*TemplatesSupported=*/false, 11399 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind, 11400 /*CLinkageMayDiffer=*/false); 11401 } 11402 11403 /// Check the validity of a multiversion function declaration that is the 11404 /// first of its kind. Also sets the multiversion'ness' of the function itself. 11405 /// 11406 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11407 /// 11408 /// Returns true if there was an error, false otherwise. 11409 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) { 11410 MultiVersionKind MVKind = FD->getMultiVersionKind(); 11411 assert(MVKind != MultiVersionKind::None && 11412 "Function lacks multiversion attribute"); 11413 const auto *TA = FD->getAttr<TargetAttr>(); 11414 const auto *TVA = FD->getAttr<TargetVersionAttr>(); 11415 // The target attribute only causes MV if this declaration is the default, 11416 // otherwise it is treated as a normal function. 11417 if (TA && !TA->isDefaultVersion()) 11418 return false; 11419 11420 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) { 11421 FD->setInvalidDecl(); 11422 return true; 11423 } 11424 11425 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) { 11426 FD->setInvalidDecl(); 11427 return true; 11428 } 11429 11430 FD->setIsMultiVersion(); 11431 return false; 11432 } 11433 11434 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 11435 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 11436 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 11437 return true; 11438 } 11439 11440 return false; 11441 } 11442 11443 static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) { 11444 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() && 11445 !From->getASTContext().getTargetInfo().getTriple().isRISCV()) 11446 return; 11447 11448 MultiVersionKind MVKindFrom = From->getMultiVersionKind(); 11449 MultiVersionKind MVKindTo = To->getMultiVersionKind(); 11450 11451 if (MVKindTo == MultiVersionKind::None && 11452 (MVKindFrom == MultiVersionKind::TargetVersion || 11453 MVKindFrom == MultiVersionKind::TargetClones)) 11454 To->addAttr(TargetVersionAttr::CreateImplicit( 11455 To->getASTContext(), "default", To->getSourceRange())); 11456 } 11457 11458 static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, 11459 FunctionDecl *NewFD, 11460 bool &Redeclaration, 11461 NamedDecl *&OldDecl, 11462 LookupResult &Previous) { 11463 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion"); 11464 11465 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11466 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 11467 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11468 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>(); 11469 11470 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute"); 11471 11472 // The definitions should be allowed in any order. If we have discovered 11473 // a new target version and the preceeding was the default, then add the 11474 // corresponding attribute to it. 11475 patchDefaultTargetVersion(NewFD, OldFD); 11476 11477 // If the old decl is NOT MultiVersioned yet, and we don't cause that 11478 // to change, this is a simple redeclaration. 11479 if (NewTA && !NewTA->isDefaultVersion() && 11480 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 11481 return false; 11482 11483 // Otherwise, this decl causes MultiVersioning. 11484 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 11485 NewTVA ? MultiVersionKind::TargetVersion 11486 : MultiVersionKind::Target)) { 11487 NewFD->setInvalidDecl(); 11488 return true; 11489 } 11490 11491 if (CheckMultiVersionValue(S, NewFD)) { 11492 NewFD->setInvalidDecl(); 11493 return true; 11494 } 11495 11496 // If this is 'default', permit the forward declaration. 11497 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) || 11498 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) { 11499 Redeclaration = true; 11500 OldDecl = OldFD; 11501 OldFD->setIsMultiVersion(); 11502 NewFD->setIsMultiVersion(); 11503 return false; 11504 } 11505 11506 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) { 11507 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 11508 NewFD->setInvalidDecl(); 11509 return true; 11510 } 11511 11512 if (NewTA) { 11513 ParsedTargetAttr OldParsed = 11514 S.getASTContext().getTargetInfo().parseTargetAttr( 11515 OldTA->getFeaturesStr()); 11516 llvm::sort(OldParsed.Features); 11517 ParsedTargetAttr NewParsed = 11518 S.getASTContext().getTargetInfo().parseTargetAttr( 11519 NewTA->getFeaturesStr()); 11520 // Sort order doesn't matter, it just needs to be consistent. 11521 llvm::sort(NewParsed.Features); 11522 if (OldParsed == NewParsed) { 11523 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11524 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11525 NewFD->setInvalidDecl(); 11526 return true; 11527 } 11528 } 11529 11530 for (const auto *FD : OldFD->redecls()) { 11531 const auto *CurTA = FD->getAttr<TargetAttr>(); 11532 const auto *CurTVA = FD->getAttr<TargetVersionAttr>(); 11533 // We allow forward declarations before ANY multiversioning attributes, but 11534 // nothing after the fact. 11535 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 11536 ((NewTA && (!CurTA || CurTA->isInherited())) || 11537 (NewTVA && (!CurTVA || CurTVA->isInherited())))) { 11538 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 11539 << (NewTA ? 0 : 2); 11540 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 11541 NewFD->setInvalidDecl(); 11542 return true; 11543 } 11544 } 11545 11546 OldFD->setIsMultiVersion(); 11547 NewFD->setIsMultiVersion(); 11548 Redeclaration = false; 11549 OldDecl = nullptr; 11550 Previous.clear(); 11551 return false; 11552 } 11553 11554 static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) { 11555 MultiVersionKind OldKind = Old->getMultiVersionKind(); 11556 MultiVersionKind NewKind = New->getMultiVersionKind(); 11557 11558 if (OldKind == NewKind || OldKind == MultiVersionKind::None || 11559 NewKind == MultiVersionKind::None) 11560 return true; 11561 11562 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) { 11563 switch (OldKind) { 11564 case MultiVersionKind::TargetVersion: 11565 return NewKind == MultiVersionKind::TargetClones; 11566 case MultiVersionKind::TargetClones: 11567 return NewKind == MultiVersionKind::TargetVersion; 11568 default: 11569 return false; 11570 } 11571 } else { 11572 switch (OldKind) { 11573 case MultiVersionKind::CPUDispatch: 11574 return NewKind == MultiVersionKind::CPUSpecific; 11575 case MultiVersionKind::CPUSpecific: 11576 return NewKind == MultiVersionKind::CPUDispatch; 11577 default: 11578 return false; 11579 } 11580 } 11581 } 11582 11583 /// Check the validity of a new function declaration being added to an existing 11584 /// multiversioned declaration collection. 11585 static bool CheckMultiVersionAdditionalDecl( 11586 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 11587 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 11588 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, 11589 LookupResult &Previous) { 11590 11591 // Disallow mixing of multiversioning types. 11592 if (!MultiVersionTypesCompatible(OldFD, NewFD)) { 11593 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 11594 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11595 NewFD->setInvalidDecl(); 11596 return true; 11597 } 11598 11599 // Add the default target_version attribute if it's missing. 11600 patchDefaultTargetVersion(OldFD, NewFD); 11601 patchDefaultTargetVersion(NewFD, OldFD); 11602 11603 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11604 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11605 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind(); 11606 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind(); 11607 11608 ParsedTargetAttr NewParsed; 11609 if (NewTA) { 11610 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr( 11611 NewTA->getFeaturesStr()); 11612 llvm::sort(NewParsed.Features); 11613 } 11614 llvm::SmallVector<StringRef, 8> NewFeats; 11615 if (NewTVA) { 11616 NewTVA->getFeatures(NewFeats); 11617 llvm::sort(NewFeats); 11618 } 11619 11620 bool UseMemberUsingDeclRules = 11621 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 11622 11623 bool MayNeedOverloadableChecks = 11624 AllowOverloadingOfFunction(Previous, S.Context, NewFD); 11625 11626 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration 11627 // of a previous member of the MultiVersion set. 11628 for (NamedDecl *ND : Previous) { 11629 FunctionDecl *CurFD = ND->getAsFunction(); 11630 if (!CurFD || CurFD->isInvalidDecl()) 11631 continue; 11632 if (MayNeedOverloadableChecks && 11633 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 11634 continue; 11635 11636 switch (NewMVKind) { 11637 case MultiVersionKind::None: 11638 assert(OldMVKind == MultiVersionKind::TargetClones && 11639 "Only target_clones can be omitted in subsequent declarations"); 11640 break; 11641 case MultiVersionKind::Target: { 11642 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 11643 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 11644 NewFD->setIsMultiVersion(); 11645 Redeclaration = true; 11646 OldDecl = ND; 11647 return false; 11648 } 11649 11650 ParsedTargetAttr CurParsed = 11651 S.getASTContext().getTargetInfo().parseTargetAttr( 11652 CurTA->getFeaturesStr()); 11653 llvm::sort(CurParsed.Features); 11654 if (CurParsed == NewParsed) { 11655 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11656 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11657 NewFD->setInvalidDecl(); 11658 return true; 11659 } 11660 break; 11661 } 11662 case MultiVersionKind::TargetVersion: { 11663 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) { 11664 if (CurTVA->getName() == NewTVA->getName()) { 11665 NewFD->setIsMultiVersion(); 11666 Redeclaration = true; 11667 OldDecl = ND; 11668 return false; 11669 } 11670 llvm::SmallVector<StringRef, 8> CurFeats; 11671 CurTVA->getFeatures(CurFeats); 11672 llvm::sort(CurFeats); 11673 11674 if (CurFeats == NewFeats) { 11675 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11676 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11677 NewFD->setInvalidDecl(); 11678 return true; 11679 } 11680 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) { 11681 // Default 11682 if (NewFeats.empty()) 11683 break; 11684 11685 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) { 11686 llvm::SmallVector<StringRef, 8> CurFeats; 11687 CurClones->getFeatures(CurFeats, I); 11688 llvm::sort(CurFeats); 11689 11690 if (CurFeats == NewFeats) { 11691 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11692 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11693 NewFD->setInvalidDecl(); 11694 return true; 11695 } 11696 } 11697 } 11698 break; 11699 } 11700 case MultiVersionKind::TargetClones: { 11701 assert(NewClones && "MultiVersionKind does not match attribute type"); 11702 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) { 11703 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || 11704 !std::equal(CurClones->featuresStrs_begin(), 11705 CurClones->featuresStrs_end(), 11706 NewClones->featuresStrs_begin())) { 11707 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match); 11708 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11709 NewFD->setInvalidDecl(); 11710 return true; 11711 } 11712 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) { 11713 llvm::SmallVector<StringRef, 8> CurFeats; 11714 CurTVA->getFeatures(CurFeats); 11715 llvm::sort(CurFeats); 11716 11717 // Default 11718 if (CurFeats.empty()) 11719 break; 11720 11721 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) { 11722 NewFeats.clear(); 11723 NewClones->getFeatures(NewFeats, I); 11724 llvm::sort(NewFeats); 11725 11726 if (CurFeats == NewFeats) { 11727 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11728 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11729 NewFD->setInvalidDecl(); 11730 return true; 11731 } 11732 } 11733 break; 11734 } 11735 Redeclaration = true; 11736 OldDecl = CurFD; 11737 NewFD->setIsMultiVersion(); 11738 return false; 11739 } 11740 case MultiVersionKind::CPUSpecific: 11741 case MultiVersionKind::CPUDispatch: { 11742 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 11743 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 11744 // Handle CPUDispatch/CPUSpecific versions. 11745 // Only 1 CPUDispatch function is allowed, this will make it go through 11746 // the redeclaration errors. 11747 if (NewMVKind == MultiVersionKind::CPUDispatch && 11748 CurFD->hasAttr<CPUDispatchAttr>()) { 11749 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 11750 std::equal( 11751 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 11752 NewCPUDisp->cpus_begin(), 11753 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 11754 return Cur->getName() == New->getName(); 11755 })) { 11756 NewFD->setIsMultiVersion(); 11757 Redeclaration = true; 11758 OldDecl = ND; 11759 return false; 11760 } 11761 11762 // If the declarations don't match, this is an error condition. 11763 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 11764 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11765 NewFD->setInvalidDecl(); 11766 return true; 11767 } 11768 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) { 11769 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 11770 std::equal( 11771 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 11772 NewCPUSpec->cpus_begin(), 11773 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 11774 return Cur->getName() == New->getName(); 11775 })) { 11776 NewFD->setIsMultiVersion(); 11777 Redeclaration = true; 11778 OldDecl = ND; 11779 return false; 11780 } 11781 11782 // Only 1 version of CPUSpecific is allowed for each CPU. 11783 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 11784 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 11785 if (CurII == NewII) { 11786 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 11787 << NewII; 11788 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11789 NewFD->setInvalidDecl(); 11790 return true; 11791 } 11792 } 11793 } 11794 } 11795 break; 11796 } 11797 } 11798 } 11799 11800 // Else, this is simply a non-redecl case. Checking the 'value' is only 11801 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 11802 // handled in the attribute adding step. 11803 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) { 11804 NewFD->setInvalidDecl(); 11805 return true; 11806 } 11807 11808 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 11809 !OldFD->isMultiVersion(), NewMVKind)) { 11810 NewFD->setInvalidDecl(); 11811 return true; 11812 } 11813 11814 // Permit forward declarations in the case where these two are compatible. 11815 if (!OldFD->isMultiVersion()) { 11816 OldFD->setIsMultiVersion(); 11817 NewFD->setIsMultiVersion(); 11818 Redeclaration = true; 11819 OldDecl = OldFD; 11820 return false; 11821 } 11822 11823 NewFD->setIsMultiVersion(); 11824 Redeclaration = false; 11825 OldDecl = nullptr; 11826 Previous.clear(); 11827 return false; 11828 } 11829 11830 /// Check the validity of a mulitversion function declaration. 11831 /// Also sets the multiversion'ness' of the function itself. 11832 /// 11833 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11834 /// 11835 /// Returns true if there was an error, false otherwise. 11836 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 11837 bool &Redeclaration, NamedDecl *&OldDecl, 11838 LookupResult &Previous) { 11839 const TargetInfo &TI = S.getASTContext().getTargetInfo(); 11840 11841 // Check if FMV is disabled. 11842 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv")) 11843 return false; 11844 11845 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11846 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11847 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 11848 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 11849 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); 11850 MultiVersionKind MVKind = NewFD->getMultiVersionKind(); 11851 11852 // Main isn't allowed to become a multiversion function, however it IS 11853 // permitted to have 'main' be marked with the 'target' optimization hint, 11854 // for 'target_version' only default is allowed. 11855 if (NewFD->isMain()) { 11856 if (MVKind != MultiVersionKind::None && 11857 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) && 11858 !(MVKind == MultiVersionKind::TargetVersion && 11859 NewTVA->isDefaultVersion())) { 11860 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 11861 NewFD->setInvalidDecl(); 11862 return true; 11863 } 11864 return false; 11865 } 11866 11867 // Target attribute on AArch64 is not used for multiversioning 11868 if (NewTA && TI.getTriple().isAArch64()) 11869 return false; 11870 11871 // Target attribute on RISCV is not used for multiversioning 11872 if (NewTA && TI.getTriple().isRISCV()) 11873 return false; 11874 11875 if (!OldDecl || !OldDecl->getAsFunction() || 11876 !OldDecl->getDeclContext()->getRedeclContext()->Equals( 11877 NewFD->getDeclContext()->getRedeclContext())) { 11878 // If there's no previous declaration, AND this isn't attempting to cause 11879 // multiversioning, this isn't an error condition. 11880 if (MVKind == MultiVersionKind::None) 11881 return false; 11882 return CheckMultiVersionFirstFunction(S, NewFD); 11883 } 11884 11885 FunctionDecl *OldFD = OldDecl->getAsFunction(); 11886 11887 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) 11888 return false; 11889 11890 // Multiversioned redeclarations aren't allowed to omit the attribute, except 11891 // for target_clones and target_version. 11892 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None && 11893 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones && 11894 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) { 11895 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 11896 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 11897 NewFD->setInvalidDecl(); 11898 return true; 11899 } 11900 11901 if (!OldFD->isMultiVersion()) { 11902 switch (MVKind) { 11903 case MultiVersionKind::Target: 11904 case MultiVersionKind::TargetVersion: 11905 return CheckDeclarationCausesMultiVersioning( 11906 S, OldFD, NewFD, Redeclaration, OldDecl, Previous); 11907 case MultiVersionKind::TargetClones: 11908 if (OldFD->isUsed(false)) { 11909 NewFD->setInvalidDecl(); 11910 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 11911 } 11912 OldFD->setIsMultiVersion(); 11913 break; 11914 11915 case MultiVersionKind::CPUDispatch: 11916 case MultiVersionKind::CPUSpecific: 11917 case MultiVersionKind::None: 11918 break; 11919 } 11920 } 11921 11922 // At this point, we have a multiversion function decl (in OldFD) AND an 11923 // appropriate attribute in the current function decl. Resolve that these are 11924 // still compatible with previous declarations. 11925 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp, 11926 NewCPUSpec, NewClones, Redeclaration, 11927 OldDecl, Previous); 11928 } 11929 11930 static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) { 11931 bool IsPure = NewFD->hasAttr<PureAttr>(); 11932 bool IsConst = NewFD->hasAttr<ConstAttr>(); 11933 11934 // If there are no pure or const attributes, there's nothing to check. 11935 if (!IsPure && !IsConst) 11936 return; 11937 11938 // If the function is marked both pure and const, we retain the const 11939 // attribute because it makes stronger guarantees than the pure attribute, and 11940 // we drop the pure attribute explicitly to prevent later confusion about 11941 // semantics. 11942 if (IsPure && IsConst) { 11943 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr); 11944 NewFD->dropAttrs<PureAttr>(); 11945 } 11946 11947 // Constructors and destructors are functions which return void, so are 11948 // handled here as well. 11949 if (NewFD->getReturnType()->isVoidType()) { 11950 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void) 11951 << IsConst; 11952 NewFD->dropAttrs<PureAttr, ConstAttr>(); 11953 } 11954 } 11955 11956 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 11957 LookupResult &Previous, 11958 bool IsMemberSpecialization, 11959 bool DeclIsDefn) { 11960 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 11961 "Variably modified return types are not handled here"); 11962 11963 // Determine whether the type of this function should be merged with 11964 // a previous visible declaration. This never happens for functions in C++, 11965 // and always happens in C if the previous declaration was visible. 11966 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 11967 !Previous.isShadowed(); 11968 11969 bool Redeclaration = false; 11970 NamedDecl *OldDecl = nullptr; 11971 bool MayNeedOverloadableChecks = false; 11972 11973 inferLifetimeCaptureByAttribute(NewFD); 11974 // Merge or overload the declaration with an existing declaration of 11975 // the same name, if appropriate. 11976 if (!Previous.empty()) { 11977 // Determine whether NewFD is an overload of PrevDecl or 11978 // a declaration that requires merging. If it's an overload, 11979 // there's no more work to do here; we'll just add the new 11980 // function to the scope. 11981 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 11982 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 11983 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 11984 Redeclaration = true; 11985 OldDecl = Candidate; 11986 } 11987 } else { 11988 MayNeedOverloadableChecks = true; 11989 switch (CheckOverload(S, NewFD, Previous, OldDecl, 11990 /*NewIsUsingDecl*/ false)) { 11991 case Ovl_Match: 11992 Redeclaration = true; 11993 break; 11994 11995 case Ovl_NonFunction: 11996 Redeclaration = true; 11997 break; 11998 11999 case Ovl_Overload: 12000 Redeclaration = false; 12001 break; 12002 } 12003 } 12004 } 12005 12006 // Check for a previous extern "C" declaration with this name. 12007 if (!Redeclaration && 12008 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 12009 if (!Previous.empty()) { 12010 // This is an extern "C" declaration with the same name as a previous 12011 // declaration, and thus redeclares that entity... 12012 Redeclaration = true; 12013 OldDecl = Previous.getFoundDecl(); 12014 MergeTypeWithPrevious = false; 12015 12016 // ... except in the presence of __attribute__((overloadable)). 12017 if (OldDecl->hasAttr<OverloadableAttr>() || 12018 NewFD->hasAttr<OverloadableAttr>()) { 12019 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 12020 MayNeedOverloadableChecks = true; 12021 Redeclaration = false; 12022 OldDecl = nullptr; 12023 } 12024 } 12025 } 12026 } 12027 12028 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous)) 12029 return Redeclaration; 12030 12031 // PPC MMA non-pointer types are not allowed as function return types. 12032 if (Context.getTargetInfo().getTriple().isPPC64() && 12033 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 12034 NewFD->setInvalidDecl(); 12035 } 12036 12037 CheckConstPureAttributesUsage(*this, NewFD); 12038 12039 // C++ [dcl.spec.auto.general]p12: 12040 // Return type deduction for a templated function with a placeholder in its 12041 // declared type occurs when the definition is instantiated even if the 12042 // function body contains a return statement with a non-type-dependent 12043 // operand. 12044 // 12045 // C++ [temp.dep.expr]p3: 12046 // An id-expression is type-dependent if it is a template-id that is not a 12047 // concept-id and is dependent; or if its terminal name is: 12048 // - [...] 12049 // - associated by name lookup with one or more declarations of member 12050 // functions of a class that is the current instantiation declared with a 12051 // return type that contains a placeholder type, 12052 // - [...] 12053 // 12054 // If this is a templated function with a placeholder in its return type, 12055 // make the placeholder type dependent since it won't be deduced until the 12056 // definition is instantiated. We do this here because it needs to happen 12057 // for implicitly instantiated member functions/member function templates. 12058 if (getLangOpts().CPlusPlus14 && 12059 (NewFD->isDependentContext() && 12060 NewFD->getReturnType()->isUndeducedType())) { 12061 const FunctionProtoType *FPT = 12062 NewFD->getType()->castAs<FunctionProtoType>(); 12063 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType()); 12064 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(), 12065 FPT->getExtProtoInfo())); 12066 } 12067 12068 // C++11 [dcl.constexpr]p8: 12069 // A constexpr specifier for a non-static member function that is not 12070 // a constructor declares that member function to be const. 12071 // 12072 // This needs to be delayed until we know whether this is an out-of-line 12073 // definition of a static member function. 12074 // 12075 // This rule is not present in C++1y, so we produce a backwards 12076 // compatibility warning whenever it happens in C++11. 12077 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 12078 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 12079 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 12080 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 12081 CXXMethodDecl *OldMD = nullptr; 12082 if (OldDecl) 12083 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 12084 if (!OldMD || !OldMD->isStatic()) { 12085 const FunctionProtoType *FPT = 12086 MD->getType()->castAs<FunctionProtoType>(); 12087 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12088 EPI.TypeQuals.addConst(); 12089 MD->setType(Context.getFunctionType(FPT->getReturnType(), 12090 FPT->getParamTypes(), EPI)); 12091 12092 // Warn that we did this, if we're not performing template instantiation. 12093 // In that case, we'll have warned already when the template was defined. 12094 if (!inTemplateInstantiation()) { 12095 SourceLocation AddConstLoc; 12096 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 12097 .IgnoreParens().getAs<FunctionTypeLoc>()) 12098 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 12099 12100 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 12101 << FixItHint::CreateInsertion(AddConstLoc, " const"); 12102 } 12103 } 12104 } 12105 12106 if (Redeclaration) { 12107 // NewFD and OldDecl represent declarations that need to be 12108 // merged. 12109 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious, 12110 DeclIsDefn)) { 12111 NewFD->setInvalidDecl(); 12112 return Redeclaration; 12113 } 12114 12115 Previous.clear(); 12116 Previous.addDecl(OldDecl); 12117 12118 if (FunctionTemplateDecl *OldTemplateDecl = 12119 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 12120 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 12121 FunctionTemplateDecl *NewTemplateDecl 12122 = NewFD->getDescribedFunctionTemplate(); 12123 assert(NewTemplateDecl && "Template/non-template mismatch"); 12124 12125 // The call to MergeFunctionDecl above may have created some state in 12126 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 12127 // can add it as a redeclaration. 12128 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 12129 12130 NewFD->setPreviousDeclaration(OldFD); 12131 if (NewFD->isCXXClassMember()) { 12132 NewFD->setAccess(OldTemplateDecl->getAccess()); 12133 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 12134 } 12135 12136 // If this is an explicit specialization of a member that is a function 12137 // template, mark it as a member specialization. 12138 if (IsMemberSpecialization && 12139 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 12140 NewTemplateDecl->setMemberSpecialization(); 12141 assert(OldTemplateDecl->isMemberSpecialization()); 12142 // Explicit specializations of a member template do not inherit deleted 12143 // status from the parent member template that they are specializing. 12144 if (OldFD->isDeleted()) { 12145 // FIXME: This assert will not hold in the presence of modules. 12146 assert(OldFD->getCanonicalDecl() == OldFD); 12147 // FIXME: We need an update record for this AST mutation. 12148 OldFD->setDeletedAsWritten(false); 12149 } 12150 } 12151 12152 } else { 12153 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 12154 auto *OldFD = cast<FunctionDecl>(OldDecl); 12155 // This needs to happen first so that 'inline' propagates. 12156 NewFD->setPreviousDeclaration(OldFD); 12157 if (NewFD->isCXXClassMember()) 12158 NewFD->setAccess(OldFD->getAccess()); 12159 } 12160 } 12161 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 12162 !NewFD->getAttr<OverloadableAttr>()) { 12163 assert((Previous.empty() || 12164 llvm::any_of(Previous, 12165 [](const NamedDecl *ND) { 12166 return ND->hasAttr<OverloadableAttr>(); 12167 })) && 12168 "Non-redecls shouldn't happen without overloadable present"); 12169 12170 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 12171 const auto *FD = dyn_cast<FunctionDecl>(ND); 12172 return FD && !FD->hasAttr<OverloadableAttr>(); 12173 }); 12174 12175 if (OtherUnmarkedIter != Previous.end()) { 12176 Diag(NewFD->getLocation(), 12177 diag::err_attribute_overloadable_multiple_unmarked_overloads); 12178 Diag((*OtherUnmarkedIter)->getLocation(), 12179 diag::note_attribute_overloadable_prev_overload) 12180 << false; 12181 12182 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 12183 } 12184 } 12185 12186 if (LangOpts.OpenMP) 12187 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 12188 12189 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>()) 12190 SYCL().CheckSYCLEntryPointFunctionDecl(NewFD); 12191 12192 // Semantic checking for this function declaration (in isolation). 12193 12194 if (getLangOpts().CPlusPlus) { 12195 // C++-specific checks. 12196 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 12197 CheckConstructor(Constructor); 12198 } else if (CXXDestructorDecl *Destructor = 12199 dyn_cast<CXXDestructorDecl>(NewFD)) { 12200 // We check here for invalid destructor names. 12201 // If we have a friend destructor declaration that is dependent, we can't 12202 // diagnose right away because cases like this are still valid: 12203 // template <class T> struct A { friend T::X::~Y(); }; 12204 // struct B { struct Y { ~Y(); }; using X = Y; }; 12205 // template struct A<B>; 12206 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None || 12207 !Destructor->getFunctionObjectParameterType()->isDependentType()) { 12208 CXXRecordDecl *Record = Destructor->getParent(); 12209 QualType ClassType = Context.getTypeDeclType(Record); 12210 12211 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName( 12212 Context.getCanonicalType(ClassType)); 12213 if (NewFD->getDeclName() != Name) { 12214 Diag(NewFD->getLocation(), diag::err_destructor_name); 12215 NewFD->setInvalidDecl(); 12216 return Redeclaration; 12217 } 12218 } 12219 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 12220 if (auto *TD = Guide->getDescribedFunctionTemplate()) 12221 CheckDeductionGuideTemplate(TD); 12222 12223 // A deduction guide is not on the list of entities that can be 12224 // explicitly specialized. 12225 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 12226 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 12227 << /*explicit specialization*/ 1; 12228 } 12229 12230 // Find any virtual functions that this function overrides. 12231 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 12232 if (!Method->isFunctionTemplateSpecialization() && 12233 !Method->getDescribedFunctionTemplate() && 12234 Method->isCanonicalDecl()) { 12235 AddOverriddenMethods(Method->getParent(), Method); 12236 } 12237 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 12238 // C++2a [class.virtual]p6 12239 // A virtual method shall not have a requires-clause. 12240 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 12241 diag::err_constrained_virtual_method); 12242 12243 if (Method->isStatic()) 12244 checkThisInStaticMemberFunctionType(Method); 12245 } 12246 12247 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 12248 ActOnConversionDeclarator(Conversion); 12249 12250 // Extra checking for C++ overloaded operators (C++ [over.oper]). 12251 if (NewFD->isOverloadedOperator() && 12252 CheckOverloadedOperatorDeclaration(NewFD)) { 12253 NewFD->setInvalidDecl(); 12254 return Redeclaration; 12255 } 12256 12257 // Extra checking for C++0x literal operators (C++0x [over.literal]). 12258 if (NewFD->getLiteralIdentifier() && 12259 CheckLiteralOperatorDeclaration(NewFD)) { 12260 NewFD->setInvalidDecl(); 12261 return Redeclaration; 12262 } 12263 12264 // In C++, check default arguments now that we have merged decls. Unless 12265 // the lexical context is the class, because in this case this is done 12266 // during delayed parsing anyway. 12267 if (!CurContext->isRecord()) 12268 CheckCXXDefaultArguments(NewFD); 12269 12270 // If this function is declared as being extern "C", then check to see if 12271 // the function returns a UDT (class, struct, or union type) that is not C 12272 // compatible, and if it does, warn the user. 12273 // But, issue any diagnostic on the first declaration only. 12274 if (Previous.empty() && NewFD->isExternC()) { 12275 QualType R = NewFD->getReturnType(); 12276 if (R->isIncompleteType() && !R->isVoidType()) 12277 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 12278 << NewFD << R; 12279 else if (!R.isPODType(Context) && !R->isVoidType() && 12280 !R->isObjCObjectPointerType()) 12281 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 12282 } 12283 12284 // C++1z [dcl.fct]p6: 12285 // [...] whether the function has a non-throwing exception-specification 12286 // [is] part of the function type 12287 // 12288 // This results in an ABI break between C++14 and C++17 for functions whose 12289 // declared type includes an exception-specification in a parameter or 12290 // return type. (Exception specifications on the function itself are OK in 12291 // most cases, and exception specifications are not permitted in most other 12292 // contexts where they could make it into a mangling.) 12293 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 12294 auto HasNoexcept = [&](QualType T) -> bool { 12295 // Strip off declarator chunks that could be between us and a function 12296 // type. We don't need to look far, exception specifications are very 12297 // restricted prior to C++17. 12298 if (auto *RT = T->getAs<ReferenceType>()) 12299 T = RT->getPointeeType(); 12300 else if (T->isAnyPointerType()) 12301 T = T->getPointeeType(); 12302 else if (auto *MPT = T->getAs<MemberPointerType>()) 12303 T = MPT->getPointeeType(); 12304 if (auto *FPT = T->getAs<FunctionProtoType>()) 12305 if (FPT->isNothrow()) 12306 return true; 12307 return false; 12308 }; 12309 12310 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 12311 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 12312 for (QualType T : FPT->param_types()) 12313 AnyNoexcept |= HasNoexcept(T); 12314 if (AnyNoexcept) 12315 Diag(NewFD->getLocation(), 12316 diag::warn_cxx17_compat_exception_spec_in_signature) 12317 << NewFD; 12318 } 12319 12320 if (!Redeclaration && LangOpts.CUDA) { 12321 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>(); 12322 for (auto *Parm : NewFD->parameters()) { 12323 if (!Parm->getType()->isDependentType() && 12324 Parm->hasAttr<CUDAGridConstantAttr>() && 12325 !(IsKernel && Parm->getType().isConstQualified())) 12326 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(), 12327 diag::err_cuda_grid_constant_not_allowed); 12328 } 12329 CUDA().checkTargetOverload(NewFD, Previous); 12330 } 12331 } 12332 12333 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64()) 12334 ARM().CheckSMEFunctionDefAttributes(NewFD); 12335 12336 return Redeclaration; 12337 } 12338 12339 void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) { 12340 // [basic.start.main]p3 12341 // The main function shall not be declared with a linkage-specification. 12342 if (FD->isExternCContext() || 12343 (FD->isExternCXXContext() && 12344 FD->getDeclContext()->getRedeclContext()->isTranslationUnit())) 12345 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification) 12346 << FD->getLanguageLinkage(); 12347 12348 // C++11 [basic.start.main]p3: 12349 // A program that [...] declares main to be inline, static or 12350 // constexpr is ill-formed. 12351 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 12352 // appear in a declaration of main. 12353 // static main is not an error under C99, but we should warn about it. 12354 // We accept _Noreturn main as an extension. 12355 if (FD->getStorageClass() == SC_Static) 12356 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 12357 ? diag::err_static_main : diag::warn_static_main) 12358 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 12359 if (FD->isInlineSpecified()) 12360 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 12361 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 12362 if (DS.isNoreturnSpecified()) { 12363 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 12364 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 12365 Diag(NoreturnLoc, diag::ext_noreturn_main); 12366 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 12367 << FixItHint::CreateRemoval(NoreturnRange); 12368 } 12369 if (FD->isConstexpr()) { 12370 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 12371 << FD->isConsteval() 12372 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 12373 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 12374 } 12375 12376 if (getLangOpts().OpenCL) { 12377 Diag(FD->getLocation(), diag::err_opencl_no_main) 12378 << FD->hasAttr<OpenCLKernelAttr>(); 12379 FD->setInvalidDecl(); 12380 return; 12381 } 12382 12383 // Functions named main in hlsl are default entries, but don't have specific 12384 // signatures they are required to conform to. 12385 if (getLangOpts().HLSL) 12386 return; 12387 12388 QualType T = FD->getType(); 12389 assert(T->isFunctionType() && "function decl is not of function type"); 12390 const FunctionType* FT = T->castAs<FunctionType>(); 12391 12392 // Set default calling convention for main() 12393 if (FT->getCallConv() != CC_C) { 12394 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 12395 FD->setType(QualType(FT, 0)); 12396 T = Context.getCanonicalType(FD->getType()); 12397 } 12398 12399 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 12400 // In C with GNU extensions we allow main() to have non-integer return 12401 // type, but we should warn about the extension, and we disable the 12402 // implicit-return-zero rule. 12403 12404 // GCC in C mode accepts qualified 'int'. 12405 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 12406 FD->setHasImplicitReturnZero(true); 12407 else { 12408 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 12409 SourceRange RTRange = FD->getReturnTypeSourceRange(); 12410 if (RTRange.isValid()) 12411 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 12412 << FixItHint::CreateReplacement(RTRange, "int"); 12413 } 12414 } else { 12415 // In C and C++, main magically returns 0 if you fall off the end; 12416 // set the flag which tells us that. 12417 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 12418 12419 // All the standards say that main() should return 'int'. 12420 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 12421 FD->setHasImplicitReturnZero(true); 12422 else { 12423 // Otherwise, this is just a flat-out error. 12424 SourceRange RTRange = FD->getReturnTypeSourceRange(); 12425 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 12426 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 12427 : FixItHint()); 12428 FD->setInvalidDecl(true); 12429 } 12430 } 12431 12432 // Treat protoless main() as nullary. 12433 if (isa<FunctionNoProtoType>(FT)) return; 12434 12435 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 12436 unsigned nparams = FTP->getNumParams(); 12437 assert(FD->getNumParams() == nparams); 12438 12439 bool HasExtraParameters = (nparams > 3); 12440 12441 if (FTP->isVariadic()) { 12442 Diag(FD->getLocation(), diag::ext_variadic_main); 12443 // FIXME: if we had information about the location of the ellipsis, we 12444 // could add a FixIt hint to remove it as a parameter. 12445 } 12446 12447 // Darwin passes an undocumented fourth argument of type char**. If 12448 // other platforms start sprouting these, the logic below will start 12449 // getting shifty. 12450 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 12451 HasExtraParameters = false; 12452 12453 if (HasExtraParameters) { 12454 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 12455 FD->setInvalidDecl(true); 12456 nparams = 3; 12457 } 12458 12459 // FIXME: a lot of the following diagnostics would be improved 12460 // if we had some location information about types. 12461 12462 QualType CharPP = 12463 Context.getPointerType(Context.getPointerType(Context.CharTy)); 12464 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 12465 12466 for (unsigned i = 0; i < nparams; ++i) { 12467 QualType AT = FTP->getParamType(i); 12468 12469 bool mismatch = true; 12470 12471 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 12472 mismatch = false; 12473 else if (Expected[i] == CharPP) { 12474 // As an extension, the following forms are okay: 12475 // char const ** 12476 // char const * const * 12477 // char * const * 12478 12479 QualifierCollector qs; 12480 const PointerType* PT; 12481 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 12482 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 12483 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 12484 Context.CharTy)) { 12485 qs.removeConst(); 12486 mismatch = !qs.empty(); 12487 } 12488 } 12489 12490 if (mismatch) { 12491 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 12492 // TODO: suggest replacing given type with expected type 12493 FD->setInvalidDecl(true); 12494 } 12495 } 12496 12497 if (nparams == 1 && !FD->isInvalidDecl()) { 12498 Diag(FD->getLocation(), diag::warn_main_one_arg); 12499 } 12500 12501 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 12502 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 12503 FD->setInvalidDecl(); 12504 } 12505 } 12506 12507 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 12508 12509 // Default calling convention for main and wmain is __cdecl 12510 if (FD->getName() == "main" || FD->getName() == "wmain") 12511 return false; 12512 12513 // Default calling convention for MinGW is __cdecl 12514 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 12515 if (T.isWindowsGNUEnvironment()) 12516 return false; 12517 12518 // Default calling convention for WinMain, wWinMain and DllMain 12519 // is __stdcall on 32 bit Windows 12520 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 12521 return true; 12522 12523 return false; 12524 } 12525 12526 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 12527 QualType T = FD->getType(); 12528 assert(T->isFunctionType() && "function decl is not of function type"); 12529 const FunctionType *FT = T->castAs<FunctionType>(); 12530 12531 // Set an implicit return of 'zero' if the function can return some integral, 12532 // enumeration, pointer or nullptr type. 12533 if (FT->getReturnType()->isIntegralOrEnumerationType() || 12534 FT->getReturnType()->isAnyPointerType() || 12535 FT->getReturnType()->isNullPtrType()) 12536 // DllMain is exempt because a return value of zero means it failed. 12537 if (FD->getName() != "DllMain") 12538 FD->setHasImplicitReturnZero(true); 12539 12540 // Explicitly specified calling conventions are applied to MSVC entry points 12541 if (!hasExplicitCallingConv(T)) { 12542 if (isDefaultStdCall(FD, *this)) { 12543 if (FT->getCallConv() != CC_X86StdCall) { 12544 FT = Context.adjustFunctionType( 12545 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 12546 FD->setType(QualType(FT, 0)); 12547 } 12548 } else if (FT->getCallConv() != CC_C) { 12549 FT = Context.adjustFunctionType(FT, 12550 FT->getExtInfo().withCallingConv(CC_C)); 12551 FD->setType(QualType(FT, 0)); 12552 } 12553 } 12554 12555 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 12556 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 12557 FD->setInvalidDecl(); 12558 } 12559 } 12560 12561 bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) { 12562 // FIXME: Need strict checking. In C89, we need to check for 12563 // any assignment, increment, decrement, function-calls, or 12564 // commas outside of a sizeof. In C99, it's the same list, 12565 // except that the aforementioned are allowed in unevaluated 12566 // expressions. Everything else falls under the 12567 // "may accept other forms of constant expressions" exception. 12568 // 12569 // Regular C++ code will not end up here (exceptions: language extensions, 12570 // OpenCL C++ etc), so the constant expression rules there don't matter. 12571 if (Init->isValueDependent()) { 12572 assert(Init->containsErrors() && 12573 "Dependent code should only occur in error-recovery path."); 12574 return true; 12575 } 12576 const Expr *Culprit; 12577 if (Init->isConstantInitializer(Context, false, &Culprit)) 12578 return false; 12579 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange(); 12580 return true; 12581 } 12582 12583 namespace { 12584 // Visits an initialization expression to see if OrigDecl is evaluated in 12585 // its own initialization and throws a warning if it does. 12586 class SelfReferenceChecker 12587 : public EvaluatedExprVisitor<SelfReferenceChecker> { 12588 Sema &S; 12589 Decl *OrigDecl; 12590 bool isRecordType; 12591 bool isPODType; 12592 bool isReferenceType; 12593 12594 bool isInitList; 12595 llvm::SmallVector<unsigned, 4> InitFieldIndex; 12596 12597 public: 12598 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 12599 12600 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 12601 S(S), OrigDecl(OrigDecl) { 12602 isPODType = false; 12603 isRecordType = false; 12604 isReferenceType = false; 12605 isInitList = false; 12606 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 12607 isPODType = VD->getType().isPODType(S.Context); 12608 isRecordType = VD->getType()->isRecordType(); 12609 isReferenceType = VD->getType()->isReferenceType(); 12610 } 12611 } 12612 12613 // For most expressions, just call the visitor. For initializer lists, 12614 // track the index of the field being initialized since fields are 12615 // initialized in order allowing use of previously initialized fields. 12616 void CheckExpr(Expr *E) { 12617 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 12618 if (!InitList) { 12619 Visit(E); 12620 return; 12621 } 12622 12623 // Track and increment the index here. 12624 isInitList = true; 12625 InitFieldIndex.push_back(0); 12626 for (auto *Child : InitList->children()) { 12627 CheckExpr(cast<Expr>(Child)); 12628 ++InitFieldIndex.back(); 12629 } 12630 InitFieldIndex.pop_back(); 12631 } 12632 12633 // Returns true if MemberExpr is checked and no further checking is needed. 12634 // Returns false if additional checking is required. 12635 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 12636 llvm::SmallVector<FieldDecl*, 4> Fields; 12637 Expr *Base = E; 12638 bool ReferenceField = false; 12639 12640 // Get the field members used. 12641 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 12642 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 12643 if (!FD) 12644 return false; 12645 Fields.push_back(FD); 12646 if (FD->getType()->isReferenceType()) 12647 ReferenceField = true; 12648 Base = ME->getBase()->IgnoreParenImpCasts(); 12649 } 12650 12651 // Keep checking only if the base Decl is the same. 12652 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 12653 if (!DRE || DRE->getDecl() != OrigDecl) 12654 return false; 12655 12656 // A reference field can be bound to an unininitialized field. 12657 if (CheckReference && !ReferenceField) 12658 return true; 12659 12660 // Convert FieldDecls to their index number. 12661 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 12662 for (const FieldDecl *I : llvm::reverse(Fields)) 12663 UsedFieldIndex.push_back(I->getFieldIndex()); 12664 12665 // See if a warning is needed by checking the first difference in index 12666 // numbers. If field being used has index less than the field being 12667 // initialized, then the use is safe. 12668 for (auto UsedIter = UsedFieldIndex.begin(), 12669 UsedEnd = UsedFieldIndex.end(), 12670 OrigIter = InitFieldIndex.begin(), 12671 OrigEnd = InitFieldIndex.end(); 12672 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 12673 if (*UsedIter < *OrigIter) 12674 return true; 12675 if (*UsedIter > *OrigIter) 12676 break; 12677 } 12678 12679 // TODO: Add a different warning which will print the field names. 12680 HandleDeclRefExpr(DRE); 12681 return true; 12682 } 12683 12684 // For most expressions, the cast is directly above the DeclRefExpr. 12685 // For conditional operators, the cast can be outside the conditional 12686 // operator if both expressions are DeclRefExpr's. 12687 void HandleValue(Expr *E) { 12688 E = E->IgnoreParens(); 12689 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 12690 HandleDeclRefExpr(DRE); 12691 return; 12692 } 12693 12694 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 12695 Visit(CO->getCond()); 12696 HandleValue(CO->getTrueExpr()); 12697 HandleValue(CO->getFalseExpr()); 12698 return; 12699 } 12700 12701 if (BinaryConditionalOperator *BCO = 12702 dyn_cast<BinaryConditionalOperator>(E)) { 12703 Visit(BCO->getCond()); 12704 HandleValue(BCO->getFalseExpr()); 12705 return; 12706 } 12707 12708 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 12709 if (Expr *SE = OVE->getSourceExpr()) 12710 HandleValue(SE); 12711 return; 12712 } 12713 12714 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12715 if (BO->getOpcode() == BO_Comma) { 12716 Visit(BO->getLHS()); 12717 HandleValue(BO->getRHS()); 12718 return; 12719 } 12720 } 12721 12722 if (isa<MemberExpr>(E)) { 12723 if (isInitList) { 12724 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 12725 false /*CheckReference*/)) 12726 return; 12727 } 12728 12729 Expr *Base = E->IgnoreParenImpCasts(); 12730 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 12731 // Check for static member variables and don't warn on them. 12732 if (!isa<FieldDecl>(ME->getMemberDecl())) 12733 return; 12734 Base = ME->getBase()->IgnoreParenImpCasts(); 12735 } 12736 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 12737 HandleDeclRefExpr(DRE); 12738 return; 12739 } 12740 12741 Visit(E); 12742 } 12743 12744 // Reference types not handled in HandleValue are handled here since all 12745 // uses of references are bad, not just r-value uses. 12746 void VisitDeclRefExpr(DeclRefExpr *E) { 12747 if (isReferenceType) 12748 HandleDeclRefExpr(E); 12749 } 12750 12751 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12752 if (E->getCastKind() == CK_LValueToRValue) { 12753 HandleValue(E->getSubExpr()); 12754 return; 12755 } 12756 12757 Inherited::VisitImplicitCastExpr(E); 12758 } 12759 12760 void VisitMemberExpr(MemberExpr *E) { 12761 if (isInitList) { 12762 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 12763 return; 12764 } 12765 12766 // Don't warn on arrays since they can be treated as pointers. 12767 if (E->getType()->canDecayToPointerType()) return; 12768 12769 // Warn when a non-static method call is followed by non-static member 12770 // field accesses, which is followed by a DeclRefExpr. 12771 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 12772 bool Warn = (MD && !MD->isStatic()); 12773 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 12774 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 12775 if (!isa<FieldDecl>(ME->getMemberDecl())) 12776 Warn = false; 12777 Base = ME->getBase()->IgnoreParenImpCasts(); 12778 } 12779 12780 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 12781 if (Warn) 12782 HandleDeclRefExpr(DRE); 12783 return; 12784 } 12785 12786 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 12787 // Visit that expression. 12788 Visit(Base); 12789 } 12790 12791 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 12792 Expr *Callee = E->getCallee(); 12793 12794 if (isa<UnresolvedLookupExpr>(Callee)) 12795 return Inherited::VisitCXXOperatorCallExpr(E); 12796 12797 Visit(Callee); 12798 for (auto Arg: E->arguments()) 12799 HandleValue(Arg->IgnoreParenImpCasts()); 12800 } 12801 12802 void VisitUnaryOperator(UnaryOperator *E) { 12803 // For POD record types, addresses of its own members are well-defined. 12804 if (E->getOpcode() == UO_AddrOf && isRecordType && 12805 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 12806 if (!isPODType) 12807 HandleValue(E->getSubExpr()); 12808 return; 12809 } 12810 12811 if (E->isIncrementDecrementOp()) { 12812 HandleValue(E->getSubExpr()); 12813 return; 12814 } 12815 12816 Inherited::VisitUnaryOperator(E); 12817 } 12818 12819 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 12820 12821 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12822 if (E->getConstructor()->isCopyConstructor()) { 12823 Expr *ArgExpr = E->getArg(0); 12824 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 12825 if (ILE->getNumInits() == 1) 12826 ArgExpr = ILE->getInit(0); 12827 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 12828 if (ICE->getCastKind() == CK_NoOp) 12829 ArgExpr = ICE->getSubExpr(); 12830 HandleValue(ArgExpr); 12831 return; 12832 } 12833 Inherited::VisitCXXConstructExpr(E); 12834 } 12835 12836 void VisitCallExpr(CallExpr *E) { 12837 // Treat std::move as a use. 12838 if (E->isCallToStdMove()) { 12839 HandleValue(E->getArg(0)); 12840 return; 12841 } 12842 12843 Inherited::VisitCallExpr(E); 12844 } 12845 12846 void VisitBinaryOperator(BinaryOperator *E) { 12847 if (E->isCompoundAssignmentOp()) { 12848 HandleValue(E->getLHS()); 12849 Visit(E->getRHS()); 12850 return; 12851 } 12852 12853 Inherited::VisitBinaryOperator(E); 12854 } 12855 12856 // A custom visitor for BinaryConditionalOperator is needed because the 12857 // regular visitor would check the condition and true expression separately 12858 // but both point to the same place giving duplicate diagnostics. 12859 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 12860 Visit(E->getCond()); 12861 Visit(E->getFalseExpr()); 12862 } 12863 12864 void HandleDeclRefExpr(DeclRefExpr *DRE) { 12865 Decl* ReferenceDecl = DRE->getDecl(); 12866 if (OrigDecl != ReferenceDecl) return; 12867 unsigned diag; 12868 if (isReferenceType) { 12869 diag = diag::warn_uninit_self_reference_in_reference_init; 12870 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 12871 diag = diag::warn_static_self_reference_in_init; 12872 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 12873 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 12874 DRE->getDecl()->getType()->isRecordType()) { 12875 diag = diag::warn_uninit_self_reference_in_init; 12876 } else { 12877 // Local variables will be handled by the CFG analysis. 12878 return; 12879 } 12880 12881 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 12882 S.PDiag(diag) 12883 << DRE->getDecl() << OrigDecl->getLocation() 12884 << DRE->getSourceRange()); 12885 } 12886 }; 12887 12888 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 12889 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 12890 bool DirectInit) { 12891 // Parameters arguments are occassionially constructed with itself, 12892 // for instance, in recursive functions. Skip them. 12893 if (isa<ParmVarDecl>(OrigDecl)) 12894 return; 12895 12896 E = E->IgnoreParens(); 12897 12898 // Skip checking T a = a where T is not a record or reference type. 12899 // Doing so is a way to silence uninitialized warnings. 12900 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 12901 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 12902 if (ICE->getCastKind() == CK_LValueToRValue) 12903 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 12904 if (DRE->getDecl() == OrigDecl) 12905 return; 12906 12907 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 12908 } 12909 } // end anonymous namespace 12910 12911 namespace { 12912 // Simple wrapper to add the name of a variable or (if no variable is 12913 // available) a DeclarationName into a diagnostic. 12914 struct VarDeclOrName { 12915 VarDecl *VDecl; 12916 DeclarationName Name; 12917 12918 friend const Sema::SemaDiagnosticBuilder & 12919 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 12920 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 12921 } 12922 }; 12923 } // end anonymous namespace 12924 12925 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 12926 DeclarationName Name, QualType Type, 12927 TypeSourceInfo *TSI, 12928 SourceRange Range, bool DirectInit, 12929 Expr *Init) { 12930 bool IsInitCapture = !VDecl; 12931 assert((!VDecl || !VDecl->isInitCapture()) && 12932 "init captures are expected to be deduced prior to initialization"); 12933 12934 VarDeclOrName VN{VDecl, Name}; 12935 12936 DeducedType *Deduced = Type->getContainedDeducedType(); 12937 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 12938 12939 // Diagnose auto array declarations in C23, unless it's a supported extension. 12940 if (getLangOpts().C23 && Type->isArrayType() && 12941 !isa_and_present<StringLiteral, InitListExpr>(Init)) { 12942 Diag(Range.getBegin(), diag::err_auto_not_allowed) 12943 << (int)Deduced->getContainedAutoType()->getKeyword() 12944 << /*in array decl*/ 23 << Range; 12945 return QualType(); 12946 } 12947 12948 // C++11 [dcl.spec.auto]p3 12949 if (!Init) { 12950 assert(VDecl && "no init for init capture deduction?"); 12951 12952 // Except for class argument deduction, and then for an initializing 12953 // declaration only, i.e. no static at class scope or extern. 12954 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 12955 VDecl->hasExternalStorage() || 12956 VDecl->isStaticDataMember()) { 12957 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 12958 << VDecl->getDeclName() << Type; 12959 return QualType(); 12960 } 12961 } 12962 12963 ArrayRef<Expr*> DeduceInits; 12964 if (Init) 12965 DeduceInits = Init; 12966 12967 auto *PL = dyn_cast_if_present<ParenListExpr>(Init); 12968 if (DirectInit && PL) 12969 DeduceInits = PL->exprs(); 12970 12971 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 12972 assert(VDecl && "non-auto type for init capture deduction?"); 12973 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12974 InitializationKind Kind = InitializationKind::CreateForInit( 12975 VDecl->getLocation(), DirectInit, Init); 12976 // FIXME: Initialization should not be taking a mutable list of inits. 12977 SmallVector<Expr *, 8> InitsCopy(DeduceInits); 12978 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 12979 InitsCopy); 12980 } 12981 12982 if (DirectInit) { 12983 if (auto *IL = dyn_cast<InitListExpr>(Init)) 12984 DeduceInits = IL->inits(); 12985 } 12986 12987 // Deduction only works if we have exactly one source expression. 12988 if (DeduceInits.empty()) { 12989 // It isn't possible to write this directly, but it is possible to 12990 // end up in this situation with "auto x(some_pack...);" 12991 Diag(Init->getBeginLoc(), IsInitCapture 12992 ? diag::err_init_capture_no_expression 12993 : diag::err_auto_var_init_no_expression) 12994 << VN << Type << Range; 12995 return QualType(); 12996 } 12997 12998 if (DeduceInits.size() > 1) { 12999 Diag(DeduceInits[1]->getBeginLoc(), 13000 IsInitCapture ? diag::err_init_capture_multiple_expressions 13001 : diag::err_auto_var_init_multiple_expressions) 13002 << VN << Type << Range; 13003 return QualType(); 13004 } 13005 13006 Expr *DeduceInit = DeduceInits[0]; 13007 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 13008 Diag(Init->getBeginLoc(), IsInitCapture 13009 ? diag::err_init_capture_paren_braces 13010 : diag::err_auto_var_init_paren_braces) 13011 << isa<InitListExpr>(Init) << VN << Type << Range; 13012 return QualType(); 13013 } 13014 13015 // Expressions default to 'id' when we're in a debugger. 13016 bool DefaultedAnyToId = false; 13017 if (getLangOpts().DebuggerCastResultToId && 13018 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 13019 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 13020 if (Result.isInvalid()) { 13021 return QualType(); 13022 } 13023 Init = Result.get(); 13024 DefaultedAnyToId = true; 13025 } 13026 13027 // C++ [dcl.decomp]p1: 13028 // If the assignment-expression [...] has array type A and no ref-qualifier 13029 // is present, e has type cv A 13030 if (VDecl && isa<DecompositionDecl>(VDecl) && 13031 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 13032 DeduceInit->getType()->isConstantArrayType()) 13033 return Context.getQualifiedType(DeduceInit->getType(), 13034 Type.getQualifiers()); 13035 13036 QualType DeducedType; 13037 TemplateDeductionInfo Info(DeduceInit->getExprLoc()); 13038 TemplateDeductionResult Result = 13039 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info); 13040 if (Result != TemplateDeductionResult::Success && 13041 Result != TemplateDeductionResult::AlreadyDiagnosed) { 13042 if (!IsInitCapture) 13043 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 13044 else if (isa<InitListExpr>(Init)) 13045 Diag(Range.getBegin(), 13046 diag::err_init_capture_deduction_failure_from_init_list) 13047 << VN 13048 << (DeduceInit->getType().isNull() ? TSI->getType() 13049 : DeduceInit->getType()) 13050 << DeduceInit->getSourceRange(); 13051 else 13052 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 13053 << VN << TSI->getType() 13054 << (DeduceInit->getType().isNull() ? TSI->getType() 13055 : DeduceInit->getType()) 13056 << DeduceInit->getSourceRange(); 13057 } 13058 13059 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 13060 // 'id' instead of a specific object type prevents most of our usual 13061 // checks. 13062 // We only want to warn outside of template instantiations, though: 13063 // inside a template, the 'id' could have come from a parameter. 13064 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 13065 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 13066 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 13067 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 13068 } 13069 13070 return DeducedType; 13071 } 13072 13073 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 13074 Expr *Init) { 13075 assert(!Init || !Init->containsErrors()); 13076 QualType DeducedType = deduceVarTypeFromInitializer( 13077 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 13078 VDecl->getSourceRange(), DirectInit, Init); 13079 if (DeducedType.isNull()) { 13080 VDecl->setInvalidDecl(); 13081 return true; 13082 } 13083 13084 VDecl->setType(DeducedType); 13085 assert(VDecl->isLinkageValid()); 13086 13087 // In ARC, infer lifetime. 13088 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl)) 13089 VDecl->setInvalidDecl(); 13090 13091 if (getLangOpts().OpenCL) 13092 deduceOpenCLAddressSpace(VDecl); 13093 13094 // If this is a redeclaration, check that the type we just deduced matches 13095 // the previously declared type. 13096 if (VarDecl *Old = VDecl->getPreviousDecl()) { 13097 // We never need to merge the type, because we cannot form an incomplete 13098 // array of auto, nor deduce such a type. 13099 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 13100 } 13101 13102 // Check the deduced type is valid for a variable declaration. 13103 CheckVariableDeclarationType(VDecl); 13104 return VDecl->isInvalidDecl(); 13105 } 13106 13107 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 13108 SourceLocation Loc) { 13109 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 13110 Init = EWC->getSubExpr(); 13111 13112 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 13113 Init = CE->getSubExpr(); 13114 13115 QualType InitType = Init->getType(); 13116 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 13117 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 13118 "shouldn't be called if type doesn't have a non-trivial C struct"); 13119 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 13120 for (auto *I : ILE->inits()) { 13121 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 13122 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13123 continue; 13124 SourceLocation SL = I->getExprLoc(); 13125 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 13126 } 13127 return; 13128 } 13129 13130 if (isa<ImplicitValueInitExpr>(Init)) { 13131 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 13132 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 13133 NTCUK_Init); 13134 } else { 13135 // Assume all other explicit initializers involving copying some existing 13136 // object. 13137 // TODO: ignore any explicit initializers where we can guarantee 13138 // copy-elision. 13139 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 13140 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 13141 } 13142 } 13143 13144 namespace { 13145 13146 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 13147 // Ignore unavailable fields. A field can be marked as unavailable explicitly 13148 // in the source code or implicitly by the compiler if it is in a union 13149 // defined in a system header and has non-trivial ObjC ownership 13150 // qualifications. We don't want those fields to participate in determining 13151 // whether the containing union is non-trivial. 13152 return FD->hasAttr<UnavailableAttr>(); 13153 } 13154 13155 struct DiagNonTrivalCUnionDefaultInitializeVisitor 13156 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 13157 void> { 13158 using Super = 13159 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 13160 void>; 13161 13162 DiagNonTrivalCUnionDefaultInitializeVisitor( 13163 QualType OrigTy, SourceLocation OrigLoc, 13164 Sema::NonTrivialCUnionContext UseContext, Sema &S) 13165 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 13166 13167 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 13168 const FieldDecl *FD, bool InNonTrivialUnion) { 13169 if (const auto *AT = S.Context.getAsArrayType(QT)) 13170 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 13171 InNonTrivialUnion); 13172 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 13173 } 13174 13175 void visitARCStrong(QualType QT, const FieldDecl *FD, 13176 bool InNonTrivialUnion) { 13177 if (InNonTrivialUnion) 13178 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13179 << 1 << 0 << QT << FD->getName(); 13180 } 13181 13182 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13183 if (InNonTrivialUnion) 13184 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13185 << 1 << 0 << QT << FD->getName(); 13186 } 13187 13188 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13189 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 13190 if (RD->isUnion()) { 13191 if (OrigLoc.isValid()) { 13192 bool IsUnion = false; 13193 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 13194 IsUnion = OrigRD->isUnion(); 13195 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 13196 << 0 << OrigTy << IsUnion << UseContext; 13197 // Reset OrigLoc so that this diagnostic is emitted only once. 13198 OrigLoc = SourceLocation(); 13199 } 13200 InNonTrivialUnion = true; 13201 } 13202 13203 if (InNonTrivialUnion) 13204 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 13205 << 0 << 0 << QT.getUnqualifiedType() << ""; 13206 13207 for (const FieldDecl *FD : RD->fields()) 13208 if (!shouldIgnoreForRecordTriviality(FD)) 13209 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 13210 } 13211 13212 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 13213 13214 // The non-trivial C union type or the struct/union type that contains a 13215 // non-trivial C union. 13216 QualType OrigTy; 13217 SourceLocation OrigLoc; 13218 Sema::NonTrivialCUnionContext UseContext; 13219 Sema &S; 13220 }; 13221 13222 struct DiagNonTrivalCUnionDestructedTypeVisitor 13223 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 13224 using Super = 13225 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 13226 13227 DiagNonTrivalCUnionDestructedTypeVisitor( 13228 QualType OrigTy, SourceLocation OrigLoc, 13229 Sema::NonTrivialCUnionContext UseContext, Sema &S) 13230 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 13231 13232 void visitWithKind(QualType::DestructionKind DK, QualType QT, 13233 const FieldDecl *FD, bool InNonTrivialUnion) { 13234 if (const auto *AT = S.Context.getAsArrayType(QT)) 13235 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 13236 InNonTrivialUnion); 13237 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 13238 } 13239 13240 void visitARCStrong(QualType QT, const FieldDecl *FD, 13241 bool InNonTrivialUnion) { 13242 if (InNonTrivialUnion) 13243 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13244 << 1 << 1 << QT << FD->getName(); 13245 } 13246 13247 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13248 if (InNonTrivialUnion) 13249 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13250 << 1 << 1 << QT << FD->getName(); 13251 } 13252 13253 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13254 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 13255 if (RD->isUnion()) { 13256 if (OrigLoc.isValid()) { 13257 bool IsUnion = false; 13258 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 13259 IsUnion = OrigRD->isUnion(); 13260 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 13261 << 1 << OrigTy << IsUnion << UseContext; 13262 // Reset OrigLoc so that this diagnostic is emitted only once. 13263 OrigLoc = SourceLocation(); 13264 } 13265 InNonTrivialUnion = true; 13266 } 13267 13268 if (InNonTrivialUnion) 13269 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 13270 << 0 << 1 << QT.getUnqualifiedType() << ""; 13271 13272 for (const FieldDecl *FD : RD->fields()) 13273 if (!shouldIgnoreForRecordTriviality(FD)) 13274 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 13275 } 13276 13277 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 13278 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 13279 bool InNonTrivialUnion) {} 13280 13281 // The non-trivial C union type or the struct/union type that contains a 13282 // non-trivial C union. 13283 QualType OrigTy; 13284 SourceLocation OrigLoc; 13285 Sema::NonTrivialCUnionContext UseContext; 13286 Sema &S; 13287 }; 13288 13289 struct DiagNonTrivalCUnionCopyVisitor 13290 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 13291 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 13292 13293 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 13294 Sema::NonTrivialCUnionContext UseContext, 13295 Sema &S) 13296 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 13297 13298 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 13299 const FieldDecl *FD, bool InNonTrivialUnion) { 13300 if (const auto *AT = S.Context.getAsArrayType(QT)) 13301 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 13302 InNonTrivialUnion); 13303 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 13304 } 13305 13306 void visitARCStrong(QualType QT, const FieldDecl *FD, 13307 bool InNonTrivialUnion) { 13308 if (InNonTrivialUnion) 13309 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13310 << 1 << 2 << QT << FD->getName(); 13311 } 13312 13313 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13314 if (InNonTrivialUnion) 13315 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13316 << 1 << 2 << QT << FD->getName(); 13317 } 13318 13319 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13320 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 13321 if (RD->isUnion()) { 13322 if (OrigLoc.isValid()) { 13323 bool IsUnion = false; 13324 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 13325 IsUnion = OrigRD->isUnion(); 13326 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 13327 << 2 << OrigTy << IsUnion << UseContext; 13328 // Reset OrigLoc so that this diagnostic is emitted only once. 13329 OrigLoc = SourceLocation(); 13330 } 13331 InNonTrivialUnion = true; 13332 } 13333 13334 if (InNonTrivialUnion) 13335 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 13336 << 0 << 2 << QT.getUnqualifiedType() << ""; 13337 13338 for (const FieldDecl *FD : RD->fields()) 13339 if (!shouldIgnoreForRecordTriviality(FD)) 13340 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 13341 } 13342 13343 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 13344 const FieldDecl *FD, bool InNonTrivialUnion) {} 13345 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 13346 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 13347 bool InNonTrivialUnion) {} 13348 13349 // The non-trivial C union type or the struct/union type that contains a 13350 // non-trivial C union. 13351 QualType OrigTy; 13352 SourceLocation OrigLoc; 13353 Sema::NonTrivialCUnionContext UseContext; 13354 Sema &S; 13355 }; 13356 13357 } // namespace 13358 13359 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 13360 NonTrivialCUnionContext UseContext, 13361 unsigned NonTrivialKind) { 13362 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 13363 QT.hasNonTrivialToPrimitiveDestructCUnion() || 13364 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 13365 "shouldn't be called if type doesn't have a non-trivial C union"); 13366 13367 if ((NonTrivialKind & NTCUK_Init) && 13368 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 13369 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 13370 .visit(QT, nullptr, false); 13371 if ((NonTrivialKind & NTCUK_Destruct) && 13372 QT.hasNonTrivialToPrimitiveDestructCUnion()) 13373 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 13374 .visit(QT, nullptr, false); 13375 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 13376 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 13377 .visit(QT, nullptr, false); 13378 } 13379 13380 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 13381 // If there is no declaration, there was an error parsing it. Just ignore 13382 // the initializer. 13383 if (!RealDecl) { 13384 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 13385 return; 13386 } 13387 13388 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 13389 if (!Method->isInvalidDecl()) { 13390 // Pure-specifiers are handled in ActOnPureSpecifier. 13391 Diag(Method->getLocation(), diag::err_member_function_initialization) 13392 << Method->getDeclName() << Init->getSourceRange(); 13393 Method->setInvalidDecl(); 13394 } 13395 return; 13396 } 13397 13398 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 13399 if (!VDecl) { 13400 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 13401 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 13402 RealDecl->setInvalidDecl(); 13403 return; 13404 } 13405 13406 if (VDecl->isInvalidDecl()) { 13407 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 13408 SmallVector<Expr *> SubExprs; 13409 if (Res.isUsable()) 13410 SubExprs.push_back(Res.get()); 13411 ExprResult Recovery = 13412 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), SubExprs); 13413 if (Expr *E = Recovery.get()) 13414 VDecl->setInit(E); 13415 return; 13416 } 13417 13418 // WebAssembly tables can't be used to initialise a variable. 13419 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) { 13420 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0; 13421 VDecl->setInvalidDecl(); 13422 return; 13423 } 13424 13425 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 13426 if (VDecl->getType()->isUndeducedType()) { 13427 // Attempt typo correction early so that the type of the init expression can 13428 // be deduced based on the chosen correction if the original init contains a 13429 // TypoExpr. 13430 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 13431 if (!Res.isUsable()) { 13432 // There are unresolved typos in Init, just drop them. 13433 // FIXME: improve the recovery strategy to preserve the Init. 13434 RealDecl->setInvalidDecl(); 13435 return; 13436 } 13437 if (Res.get()->containsErrors()) { 13438 // Invalidate the decl as we don't know the type for recovery-expr yet. 13439 RealDecl->setInvalidDecl(); 13440 VDecl->setInit(Res.get()); 13441 return; 13442 } 13443 Init = Res.get(); 13444 13445 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 13446 return; 13447 } 13448 13449 // dllimport cannot be used on variable definitions. 13450 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 13451 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 13452 VDecl->setInvalidDecl(); 13453 return; 13454 } 13455 13456 // C99 6.7.8p5. If the declaration of an identifier has block scope, and 13457 // the identifier has external or internal linkage, the declaration shall 13458 // have no initializer for the identifier. 13459 // C++14 [dcl.init]p5 is the same restriction for C++. 13460 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 13461 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 13462 VDecl->setInvalidDecl(); 13463 return; 13464 } 13465 13466 if (!VDecl->getType()->isDependentType()) { 13467 // A definition must end up with a complete type, which means it must be 13468 // complete with the restriction that an array type might be completed by 13469 // the initializer; note that later code assumes this restriction. 13470 QualType BaseDeclType = VDecl->getType(); 13471 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 13472 BaseDeclType = Array->getElementType(); 13473 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 13474 diag::err_typecheck_decl_incomplete_type)) { 13475 RealDecl->setInvalidDecl(); 13476 return; 13477 } 13478 13479 // The variable can not have an abstract class type. 13480 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 13481 diag::err_abstract_type_in_decl, 13482 AbstractVariableType)) 13483 VDecl->setInvalidDecl(); 13484 } 13485 13486 // C++ [module.import/6] external definitions are not permitted in header 13487 // units. 13488 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() && 13489 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() && 13490 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() && 13491 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) && 13492 !VDecl->getInstantiatedFromStaticDataMember()) { 13493 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit); 13494 VDecl->setInvalidDecl(); 13495 } 13496 13497 // If adding the initializer will turn this declaration into a definition, 13498 // and we already have a definition for this variable, diagnose or otherwise 13499 // handle the situation. 13500 if (VarDecl *Def = VDecl->getDefinition()) 13501 if (Def != VDecl && 13502 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 13503 !VDecl->isThisDeclarationADemotedDefinition() && 13504 checkVarDeclRedefinition(Def, VDecl)) 13505 return; 13506 13507 if (getLangOpts().CPlusPlus) { 13508 // C++ [class.static.data]p4 13509 // If a static data member is of const integral or const 13510 // enumeration type, its declaration in the class definition can 13511 // specify a constant-initializer which shall be an integral 13512 // constant expression (5.19). In that case, the member can appear 13513 // in integral constant expressions. The member shall still be 13514 // defined in a namespace scope if it is used in the program and the 13515 // namespace scope definition shall not contain an initializer. 13516 // 13517 // We already performed a redefinition check above, but for static 13518 // data members we also need to check whether there was an in-class 13519 // declaration with an initializer. 13520 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 13521 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 13522 << VDecl->getDeclName(); 13523 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 13524 diag::note_previous_initializer) 13525 << 0; 13526 return; 13527 } 13528 13529 if (VDecl->hasLocalStorage()) 13530 setFunctionHasBranchProtectedScope(); 13531 13532 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 13533 VDecl->setInvalidDecl(); 13534 return; 13535 } 13536 } 13537 13538 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 13539 // a kernel function cannot be initialized." 13540 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 13541 Diag(VDecl->getLocation(), diag::err_local_cant_init); 13542 VDecl->setInvalidDecl(); 13543 return; 13544 } 13545 13546 // The LoaderUninitialized attribute acts as a definition (of undef). 13547 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 13548 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 13549 VDecl->setInvalidDecl(); 13550 return; 13551 } 13552 13553 // Get the decls type and save a reference for later, since 13554 // CheckInitializerTypes may change it. 13555 QualType DclT = VDecl->getType(), SavT = DclT; 13556 13557 // Expressions default to 'id' when we're in a debugger 13558 // and we are assigning it to a variable of Objective-C pointer type. 13559 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 13560 Init->getType() == Context.UnknownAnyTy) { 13561 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 13562 if (!Result.isUsable()) { 13563 VDecl->setInvalidDecl(); 13564 return; 13565 } 13566 Init = Result.get(); 13567 } 13568 13569 // Perform the initialization. 13570 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 13571 bool IsParenListInit = false; 13572 if (!VDecl->isInvalidDecl()) { 13573 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 13574 InitializationKind Kind = InitializationKind::CreateForInit( 13575 VDecl->getLocation(), DirectInit, Init); 13576 13577 MultiExprArg Args = Init; 13578 if (CXXDirectInit) 13579 Args = MultiExprArg(CXXDirectInit->getExprs(), 13580 CXXDirectInit->getNumExprs()); 13581 13582 // Try to correct any TypoExprs in the initialization arguments. 13583 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 13584 ExprResult Res = CorrectDelayedTyposInExpr( 13585 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 13586 [this, Entity, Kind](Expr *E) { 13587 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 13588 return Init.Failed() ? ExprError() : E; 13589 }); 13590 if (!Res.isUsable()) { 13591 VDecl->setInvalidDecl(); 13592 } else if (Res.get() != Args[Idx]) { 13593 Args[Idx] = Res.get(); 13594 } 13595 } 13596 if (VDecl->isInvalidDecl()) 13597 return; 13598 13599 InitializationSequence InitSeq(*this, Entity, Kind, Args, 13600 /*TopLevelOfInitList=*/false, 13601 /*TreatUnavailableAsInvalid=*/false); 13602 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 13603 if (!Result.isUsable()) { 13604 // If the provided initializer fails to initialize the var decl, 13605 // we attach a recovery expr for better recovery. 13606 auto RecoveryExpr = 13607 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 13608 if (RecoveryExpr.get()) 13609 VDecl->setInit(RecoveryExpr.get()); 13610 // In general, for error recovery purposes, the initializer doesn't play 13611 // part in the valid bit of the declaration. There are a few exceptions: 13612 // 1) if the var decl has a deduced auto type, and the type cannot be 13613 // deduced by an invalid initializer; 13614 // 2) if the var decl is a decomposition decl with a non-deduced type, 13615 // and the initialization fails (e.g. `int [a] = {1, 2};`); 13616 // Case 1) was already handled elsewhere. 13617 if (isa<DecompositionDecl>(VDecl)) // Case 2) 13618 VDecl->setInvalidDecl(); 13619 return; 13620 } 13621 13622 Init = Result.getAs<Expr>(); 13623 IsParenListInit = !InitSeq.steps().empty() && 13624 InitSeq.step_begin()->Kind == 13625 InitializationSequence::SK_ParenthesizedListInit; 13626 QualType VDeclType = VDecl->getType(); 13627 if (!Init->getType().isNull() && !Init->getType()->isDependentType() && 13628 !VDeclType->isDependentType() && 13629 Context.getAsIncompleteArrayType(VDeclType) && 13630 Context.getAsIncompleteArrayType(Init->getType())) { 13631 // Bail out if it is not possible to deduce array size from the 13632 // initializer. 13633 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type) 13634 << VDeclType; 13635 VDecl->setInvalidDecl(); 13636 return; 13637 } 13638 } 13639 13640 // Check for self-references within variable initializers. 13641 // Variables declared within a function/method body (except for references) 13642 // are handled by a dataflow analysis. 13643 // This is undefined behavior in C++, but valid in C. 13644 if (getLangOpts().CPlusPlus) 13645 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 13646 VDecl->getType()->isReferenceType()) 13647 CheckSelfReference(*this, RealDecl, Init, DirectInit); 13648 13649 // If the type changed, it means we had an incomplete type that was 13650 // completed by the initializer. For example: 13651 // int ary[] = { 1, 3, 5 }; 13652 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 13653 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 13654 VDecl->setType(DclT); 13655 13656 if (!VDecl->isInvalidDecl()) { 13657 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 13658 13659 if (VDecl->hasAttr<BlocksAttr>()) 13660 ObjC().checkRetainCycles(VDecl, Init); 13661 13662 // It is safe to assign a weak reference into a strong variable. 13663 // Although this code can still have problems: 13664 // id x = self.weakProp; 13665 // id y = self.weakProp; 13666 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13667 // paths through the function. This should be revisited if 13668 // -Wrepeated-use-of-weak is made flow-sensitive. 13669 if (FunctionScopeInfo *FSI = getCurFunction()) 13670 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 13671 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 13672 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13673 Init->getBeginLoc())) 13674 FSI->markSafeWeakUse(Init); 13675 } 13676 13677 // The initialization is usually a full-expression. 13678 // 13679 // FIXME: If this is a braced initialization of an aggregate, it is not 13680 // an expression, and each individual field initializer is a separate 13681 // full-expression. For instance, in: 13682 // 13683 // struct Temp { ~Temp(); }; 13684 // struct S { S(Temp); }; 13685 // struct T { S a, b; } t = { Temp(), Temp() } 13686 // 13687 // we should destroy the first Temp before constructing the second. 13688 ExprResult Result = 13689 ActOnFinishFullExpr(Init, VDecl->getLocation(), 13690 /*DiscardedValue*/ false, VDecl->isConstexpr()); 13691 if (!Result.isUsable()) { 13692 VDecl->setInvalidDecl(); 13693 return; 13694 } 13695 Init = Result.get(); 13696 13697 // Attach the initializer to the decl. 13698 VDecl->setInit(Init); 13699 13700 if (VDecl->isLocalVarDecl()) { 13701 // Don't check the initializer if the declaration is malformed. 13702 if (VDecl->isInvalidDecl()) { 13703 // do nothing 13704 13705 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 13706 // This is true even in C++ for OpenCL. 13707 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 13708 CheckForConstantInitializer(Init); 13709 13710 // Otherwise, C++ does not restrict the initializer. 13711 } else if (getLangOpts().CPlusPlus) { 13712 // do nothing 13713 13714 // C99 6.7.8p4: All the expressions in an initializer for an object that has 13715 // static storage duration shall be constant expressions or string literals. 13716 } else if (VDecl->getStorageClass() == SC_Static) { 13717 CheckForConstantInitializer(Init); 13718 13719 // C89 is stricter than C99 for aggregate initializers. 13720 // C89 6.5.7p3: All the expressions [...] in an initializer list 13721 // for an object that has aggregate or union type shall be 13722 // constant expressions. 13723 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 13724 isa<InitListExpr>(Init)) { 13725 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant); 13726 } 13727 13728 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 13729 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 13730 if (VDecl->hasLocalStorage()) 13731 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13732 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 13733 VDecl->getLexicalDeclContext()->isRecord()) { 13734 // This is an in-class initialization for a static data member, e.g., 13735 // 13736 // struct S { 13737 // static const int value = 17; 13738 // }; 13739 13740 // C++ [class.mem]p4: 13741 // A member-declarator can contain a constant-initializer only 13742 // if it declares a static member (9.4) of const integral or 13743 // const enumeration type, see 9.4.2. 13744 // 13745 // C++11 [class.static.data]p3: 13746 // If a non-volatile non-inline const static data member is of integral 13747 // or enumeration type, its declaration in the class definition can 13748 // specify a brace-or-equal-initializer in which every initializer-clause 13749 // that is an assignment-expression is a constant expression. A static 13750 // data member of literal type can be declared in the class definition 13751 // with the constexpr specifier; if so, its declaration shall specify a 13752 // brace-or-equal-initializer in which every initializer-clause that is 13753 // an assignment-expression is a constant expression. 13754 13755 // Do nothing on dependent types. 13756 if (DclT->isDependentType()) { 13757 13758 // Allow any 'static constexpr' members, whether or not they are of literal 13759 // type. We separately check that every constexpr variable is of literal 13760 // type. 13761 } else if (VDecl->isConstexpr()) { 13762 13763 // Require constness. 13764 } else if (!DclT.isConstQualified()) { 13765 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 13766 << Init->getSourceRange(); 13767 VDecl->setInvalidDecl(); 13768 13769 // We allow integer constant expressions in all cases. 13770 } else if (DclT->isIntegralOrEnumerationType()) { 13771 // Check whether the expression is a constant expression. 13772 SourceLocation Loc; 13773 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 13774 // In C++11, a non-constexpr const static data member with an 13775 // in-class initializer cannot be volatile. 13776 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 13777 else if (Init->isValueDependent()) 13778 ; // Nothing to check. 13779 else if (Init->isIntegerConstantExpr(Context, &Loc)) 13780 ; // Ok, it's an ICE! 13781 else if (Init->getType()->isScopedEnumeralType() && 13782 Init->isCXX11ConstantExpr(Context)) 13783 ; // Ok, it is a scoped-enum constant expression. 13784 else if (Init->isEvaluatable(Context)) { 13785 // If we can constant fold the initializer through heroics, accept it, 13786 // but report this as a use of an extension for -pedantic. 13787 Diag(Loc, diag::ext_in_class_initializer_non_constant) 13788 << Init->getSourceRange(); 13789 } else { 13790 // Otherwise, this is some crazy unknown case. Report the issue at the 13791 // location provided by the isIntegerConstantExpr failed check. 13792 Diag(Loc, diag::err_in_class_initializer_non_constant) 13793 << Init->getSourceRange(); 13794 VDecl->setInvalidDecl(); 13795 } 13796 13797 // We allow foldable floating-point constants as an extension. 13798 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 13799 // In C++98, this is a GNU extension. In C++11, it is not, but we support 13800 // it anyway and provide a fixit to add the 'constexpr'. 13801 if (getLangOpts().CPlusPlus11) { 13802 Diag(VDecl->getLocation(), 13803 diag::ext_in_class_initializer_float_type_cxx11) 13804 << DclT << Init->getSourceRange(); 13805 Diag(VDecl->getBeginLoc(), 13806 diag::note_in_class_initializer_float_type_cxx11) 13807 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 13808 } else { 13809 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 13810 << DclT << Init->getSourceRange(); 13811 13812 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 13813 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 13814 << Init->getSourceRange(); 13815 VDecl->setInvalidDecl(); 13816 } 13817 } 13818 13819 // Suggest adding 'constexpr' in C++11 for literal types. 13820 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 13821 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 13822 << DclT << Init->getSourceRange() 13823 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 13824 VDecl->setConstexpr(true); 13825 13826 } else { 13827 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 13828 << DclT << Init->getSourceRange(); 13829 VDecl->setInvalidDecl(); 13830 } 13831 } else if (VDecl->isFileVarDecl()) { 13832 // In C, extern is typically used to avoid tentative definitions when 13833 // declaring variables in headers, but adding an initializer makes it a 13834 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 13835 // In C++, extern is often used to give implicitly static const variables 13836 // external linkage, so don't warn in that case. If selectany is present, 13837 // this might be header code intended for C and C++ inclusion, so apply the 13838 // C++ rules. 13839 if (VDecl->getStorageClass() == SC_Extern && 13840 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 13841 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 13842 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 13843 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 13844 Diag(VDecl->getLocation(), diag::warn_extern_init); 13845 13846 // In Microsoft C++ mode, a const variable defined in namespace scope has 13847 // external linkage by default if the variable is declared with 13848 // __declspec(dllexport). 13849 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 13850 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 13851 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 13852 VDecl->setStorageClass(SC_Extern); 13853 13854 // C99 6.7.8p4. All file scoped initializers need to be constant. 13855 // Avoid duplicate diagnostics for constexpr variables. 13856 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() && 13857 !VDecl->isConstexpr()) 13858 CheckForConstantInitializer(Init); 13859 } 13860 13861 QualType InitType = Init->getType(); 13862 if (!InitType.isNull() && 13863 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 13864 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 13865 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 13866 13867 // We will represent direct-initialization similarly to copy-initialization: 13868 // int x(1); -as-> int x = 1; 13869 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 13870 // 13871 // Clients that want to distinguish between the two forms, can check for 13872 // direct initializer using VarDecl::getInitStyle(). 13873 // A major benefit is that clients that don't particularly care about which 13874 // exactly form was it (like the CodeGen) can handle both cases without 13875 // special case code. 13876 13877 // C++ 8.5p11: 13878 // The form of initialization (using parentheses or '=') is generally 13879 // insignificant, but does matter when the entity being initialized has a 13880 // class type. 13881 if (CXXDirectInit) { 13882 assert(DirectInit && "Call-style initializer must be direct init."); 13883 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit 13884 : VarDecl::CallInit); 13885 } else if (DirectInit) { 13886 // This must be list-initialization. No other way is direct-initialization. 13887 VDecl->setInitStyle(VarDecl::ListInit); 13888 } 13889 13890 if (LangOpts.OpenMP && 13891 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) && 13892 VDecl->isFileVarDecl()) 13893 DeclsToCheckForDeferredDiags.insert(VDecl); 13894 CheckCompleteVariableDeclaration(VDecl); 13895 } 13896 13897 void Sema::ActOnInitializerError(Decl *D) { 13898 // Our main concern here is re-establishing invariants like "a 13899 // variable's type is either dependent or complete". 13900 if (!D || D->isInvalidDecl()) return; 13901 13902 VarDecl *VD = dyn_cast<VarDecl>(D); 13903 if (!VD) return; 13904 13905 // Bindings are not usable if we can't make sense of the initializer. 13906 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 13907 for (auto *BD : DD->bindings()) 13908 BD->setInvalidDecl(); 13909 13910 // Auto types are meaningless if we can't make sense of the initializer. 13911 if (VD->getType()->isUndeducedType()) { 13912 D->setInvalidDecl(); 13913 return; 13914 } 13915 13916 QualType Ty = VD->getType(); 13917 if (Ty->isDependentType()) return; 13918 13919 // Require a complete type. 13920 if (RequireCompleteType(VD->getLocation(), 13921 Context.getBaseElementType(Ty), 13922 diag::err_typecheck_decl_incomplete_type)) { 13923 VD->setInvalidDecl(); 13924 return; 13925 } 13926 13927 // Require a non-abstract type. 13928 if (RequireNonAbstractType(VD->getLocation(), Ty, 13929 diag::err_abstract_type_in_decl, 13930 AbstractVariableType)) { 13931 VD->setInvalidDecl(); 13932 return; 13933 } 13934 13935 // Don't bother complaining about constructors or destructors, 13936 // though. 13937 } 13938 13939 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 13940 // If there is no declaration, there was an error parsing it. Just ignore it. 13941 if (!RealDecl) 13942 return; 13943 13944 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 13945 QualType Type = Var->getType(); 13946 13947 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 13948 if (isa<DecompositionDecl>(RealDecl)) { 13949 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 13950 Var->setInvalidDecl(); 13951 return; 13952 } 13953 13954 if (Type->isUndeducedType() && 13955 DeduceVariableDeclarationType(Var, false, nullptr)) 13956 return; 13957 13958 // C++11 [class.static.data]p3: A static data member can be declared with 13959 // the constexpr specifier; if so, its declaration shall specify 13960 // a brace-or-equal-initializer. 13961 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 13962 // the definition of a variable [...] or the declaration of a static data 13963 // member. 13964 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 13965 !Var->isThisDeclarationADemotedDefinition()) { 13966 if (Var->isStaticDataMember()) { 13967 // C++1z removes the relevant rule; the in-class declaration is always 13968 // a definition there. 13969 if (!getLangOpts().CPlusPlus17 && 13970 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13971 Diag(Var->getLocation(), 13972 diag::err_constexpr_static_mem_var_requires_init) 13973 << Var; 13974 Var->setInvalidDecl(); 13975 return; 13976 } 13977 } else { 13978 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 13979 Var->setInvalidDecl(); 13980 return; 13981 } 13982 } 13983 13984 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 13985 // be initialized. 13986 if (!Var->isInvalidDecl() && 13987 Var->getType().getAddressSpace() == LangAS::opencl_constant && 13988 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 13989 bool HasConstExprDefaultConstructor = false; 13990 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 13991 for (auto *Ctor : RD->ctors()) { 13992 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 13993 Ctor->getMethodQualifiers().getAddressSpace() == 13994 LangAS::opencl_constant) { 13995 HasConstExprDefaultConstructor = true; 13996 } 13997 } 13998 } 13999 if (!HasConstExprDefaultConstructor) { 14000 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 14001 Var->setInvalidDecl(); 14002 return; 14003 } 14004 } 14005 14006 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 14007 if (Var->getStorageClass() == SC_Extern) { 14008 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 14009 << Var; 14010 Var->setInvalidDecl(); 14011 return; 14012 } 14013 if (RequireCompleteType(Var->getLocation(), Var->getType(), 14014 diag::err_typecheck_decl_incomplete_type)) { 14015 Var->setInvalidDecl(); 14016 return; 14017 } 14018 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 14019 if (!RD->hasTrivialDefaultConstructor()) { 14020 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 14021 Var->setInvalidDecl(); 14022 return; 14023 } 14024 } 14025 // The declaration is uninitialized, no need for further checks. 14026 return; 14027 } 14028 14029 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 14030 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 14031 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 14032 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 14033 NTCUC_DefaultInitializedObject, NTCUK_Init); 14034 14035 14036 switch (DefKind) { 14037 case VarDecl::Definition: 14038 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 14039 break; 14040 14041 // We have an out-of-line definition of a static data member 14042 // that has an in-class initializer, so we type-check this like 14043 // a declaration. 14044 // 14045 [[fallthrough]]; 14046 14047 case VarDecl::DeclarationOnly: 14048 // It's only a declaration. 14049 14050 // Block scope. C99 6.7p7: If an identifier for an object is 14051 // declared with no linkage (C99 6.2.2p6), the type for the 14052 // object shall be complete. 14053 if (!Type->isDependentType() && Var->isLocalVarDecl() && 14054 !Var->hasLinkage() && !Var->isInvalidDecl() && 14055 RequireCompleteType(Var->getLocation(), Type, 14056 diag::err_typecheck_decl_incomplete_type)) 14057 Var->setInvalidDecl(); 14058 14059 // Make sure that the type is not abstract. 14060 if (!Type->isDependentType() && !Var->isInvalidDecl() && 14061 RequireNonAbstractType(Var->getLocation(), Type, 14062 diag::err_abstract_type_in_decl, 14063 AbstractVariableType)) 14064 Var->setInvalidDecl(); 14065 if (!Type->isDependentType() && !Var->isInvalidDecl() && 14066 Var->getStorageClass() == SC_PrivateExtern) { 14067 Diag(Var->getLocation(), diag::warn_private_extern); 14068 Diag(Var->getLocation(), diag::note_private_extern); 14069 } 14070 14071 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 14072 !Var->isInvalidDecl()) 14073 ExternalDeclarations.push_back(Var); 14074 14075 return; 14076 14077 case VarDecl::TentativeDefinition: 14078 // File scope. C99 6.9.2p2: A declaration of an identifier for an 14079 // object that has file scope without an initializer, and without a 14080 // storage-class specifier or with the storage-class specifier "static", 14081 // constitutes a tentative definition. Note: A tentative definition with 14082 // external linkage is valid (C99 6.2.2p5). 14083 if (!Var->isInvalidDecl()) { 14084 if (const IncompleteArrayType *ArrayT 14085 = Context.getAsIncompleteArrayType(Type)) { 14086 if (RequireCompleteSizedType( 14087 Var->getLocation(), ArrayT->getElementType(), 14088 diag::err_array_incomplete_or_sizeless_type)) 14089 Var->setInvalidDecl(); 14090 } else if (Var->getStorageClass() == SC_Static) { 14091 // C99 6.9.2p3: If the declaration of an identifier for an object is 14092 // a tentative definition and has internal linkage (C99 6.2.2p3), the 14093 // declared type shall not be an incomplete type. 14094 // NOTE: code such as the following 14095 // static struct s; 14096 // struct s { int a; }; 14097 // is accepted by gcc. Hence here we issue a warning instead of 14098 // an error and we do not invalidate the static declaration. 14099 // NOTE: to avoid multiple warnings, only check the first declaration. 14100 if (Var->isFirstDecl()) 14101 RequireCompleteType(Var->getLocation(), Type, 14102 diag::ext_typecheck_decl_incomplete_type); 14103 } 14104 } 14105 14106 // Record the tentative definition; we're done. 14107 if (!Var->isInvalidDecl()) 14108 TentativeDefinitions.push_back(Var); 14109 return; 14110 } 14111 14112 // Provide a specific diagnostic for uninitialized variable 14113 // definitions with incomplete array type. 14114 if (Type->isIncompleteArrayType()) { 14115 if (Var->isConstexpr()) 14116 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init) 14117 << Var; 14118 else 14119 Diag(Var->getLocation(), 14120 diag::err_typecheck_incomplete_array_needs_initializer); 14121 Var->setInvalidDecl(); 14122 return; 14123 } 14124 14125 // Provide a specific diagnostic for uninitialized variable 14126 // definitions with reference type. 14127 if (Type->isReferenceType()) { 14128 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 14129 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 14130 return; 14131 } 14132 14133 // Do not attempt to type-check the default initializer for a 14134 // variable with dependent type. 14135 if (Type->isDependentType()) 14136 return; 14137 14138 if (Var->isInvalidDecl()) 14139 return; 14140 14141 if (!Var->hasAttr<AliasAttr>()) { 14142 if (RequireCompleteType(Var->getLocation(), 14143 Context.getBaseElementType(Type), 14144 diag::err_typecheck_decl_incomplete_type)) { 14145 Var->setInvalidDecl(); 14146 return; 14147 } 14148 } else { 14149 return; 14150 } 14151 14152 // The variable can not have an abstract class type. 14153 if (RequireNonAbstractType(Var->getLocation(), Type, 14154 diag::err_abstract_type_in_decl, 14155 AbstractVariableType)) { 14156 Var->setInvalidDecl(); 14157 return; 14158 } 14159 14160 // Check for jumps past the implicit initializer. C++0x 14161 // clarifies that this applies to a "variable with automatic 14162 // storage duration", not a "local variable". 14163 // C++11 [stmt.dcl]p3 14164 // A program that jumps from a point where a variable with automatic 14165 // storage duration is not in scope to a point where it is in scope is 14166 // ill-formed unless the variable has scalar type, class type with a 14167 // trivial default constructor and a trivial destructor, a cv-qualified 14168 // version of one of these types, or an array of one of the preceding 14169 // types and is declared without an initializer. 14170 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 14171 if (const RecordType *Record 14172 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 14173 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 14174 // Mark the function (if we're in one) for further checking even if the 14175 // looser rules of C++11 do not require such checks, so that we can 14176 // diagnose incompatibilities with C++98. 14177 if (!CXXRecord->isPOD()) 14178 setFunctionHasBranchProtectedScope(); 14179 } 14180 } 14181 // In OpenCL, we can't initialize objects in the __local address space, 14182 // even implicitly, so don't synthesize an implicit initializer. 14183 if (getLangOpts().OpenCL && 14184 Var->getType().getAddressSpace() == LangAS::opencl_local) 14185 return; 14186 // C++03 [dcl.init]p9: 14187 // If no initializer is specified for an object, and the 14188 // object is of (possibly cv-qualified) non-POD class type (or 14189 // array thereof), the object shall be default-initialized; if 14190 // the object is of const-qualified type, the underlying class 14191 // type shall have a user-declared default 14192 // constructor. Otherwise, if no initializer is specified for 14193 // a non- static object, the object and its subobjects, if 14194 // any, have an indeterminate initial value); if the object 14195 // or any of its subobjects are of const-qualified type, the 14196 // program is ill-formed. 14197 // C++0x [dcl.init]p11: 14198 // If no initializer is specified for an object, the object is 14199 // default-initialized; [...]. 14200 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 14201 InitializationKind Kind 14202 = InitializationKind::CreateDefault(Var->getLocation()); 14203 14204 InitializationSequence InitSeq(*this, Entity, Kind, {}); 14205 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {}); 14206 14207 if (Init.get()) { 14208 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 14209 // This is important for template substitution. 14210 Var->setInitStyle(VarDecl::CallInit); 14211 } else if (Init.isInvalid()) { 14212 // If default-init fails, attach a recovery-expr initializer to track 14213 // that initialization was attempted and failed. 14214 auto RecoveryExpr = 14215 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 14216 if (RecoveryExpr.get()) 14217 Var->setInit(RecoveryExpr.get()); 14218 } 14219 14220 CheckCompleteVariableDeclaration(Var); 14221 } 14222 } 14223 14224 void Sema::ActOnCXXForRangeDecl(Decl *D) { 14225 // If there is no declaration, there was an error parsing it. Ignore it. 14226 if (!D) 14227 return; 14228 14229 VarDecl *VD = dyn_cast<VarDecl>(D); 14230 if (!VD) { 14231 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 14232 D->setInvalidDecl(); 14233 return; 14234 } 14235 14236 VD->setCXXForRangeDecl(true); 14237 14238 // for-range-declaration cannot be given a storage class specifier. 14239 int Error = -1; 14240 switch (VD->getStorageClass()) { 14241 case SC_None: 14242 break; 14243 case SC_Extern: 14244 Error = 0; 14245 break; 14246 case SC_Static: 14247 Error = 1; 14248 break; 14249 case SC_PrivateExtern: 14250 Error = 2; 14251 break; 14252 case SC_Auto: 14253 Error = 3; 14254 break; 14255 case SC_Register: 14256 Error = 4; 14257 break; 14258 } 14259 14260 // for-range-declaration cannot be given a storage class specifier con't. 14261 switch (VD->getTSCSpec()) { 14262 case TSCS_thread_local: 14263 Error = 6; 14264 break; 14265 case TSCS___thread: 14266 case TSCS__Thread_local: 14267 case TSCS_unspecified: 14268 break; 14269 } 14270 14271 if (Error != -1) { 14272 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 14273 << VD << Error; 14274 D->setInvalidDecl(); 14275 } 14276 } 14277 14278 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 14279 IdentifierInfo *Ident, 14280 ParsedAttributes &Attrs) { 14281 // C++1y [stmt.iter]p1: 14282 // A range-based for statement of the form 14283 // for ( for-range-identifier : for-range-initializer ) statement 14284 // is equivalent to 14285 // for ( auto&& for-range-identifier : for-range-initializer ) statement 14286 DeclSpec DS(Attrs.getPool().getFactory()); 14287 14288 const char *PrevSpec; 14289 unsigned DiagID; 14290 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 14291 getPrintingPolicy()); 14292 14293 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit); 14294 D.SetIdentifier(Ident, IdentLoc); 14295 D.takeAttributes(Attrs); 14296 14297 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 14298 IdentLoc); 14299 Decl *Var = ActOnDeclarator(S, D); 14300 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 14301 FinalizeDeclaration(Var); 14302 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 14303 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd() 14304 : IdentLoc); 14305 } 14306 14307 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 14308 if (var->isInvalidDecl()) return; 14309 14310 CUDA().MaybeAddConstantAttr(var); 14311 14312 if (getLangOpts().OpenCL) { 14313 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 14314 // initialiser 14315 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 14316 !var->hasInit()) { 14317 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 14318 << 1 /*Init*/; 14319 var->setInvalidDecl(); 14320 return; 14321 } 14322 } 14323 14324 // In Objective-C, don't allow jumps past the implicit initialization of a 14325 // local retaining variable. 14326 if (getLangOpts().ObjC && 14327 var->hasLocalStorage()) { 14328 switch (var->getType().getObjCLifetime()) { 14329 case Qualifiers::OCL_None: 14330 case Qualifiers::OCL_ExplicitNone: 14331 case Qualifiers::OCL_Autoreleasing: 14332 break; 14333 14334 case Qualifiers::OCL_Weak: 14335 case Qualifiers::OCL_Strong: 14336 setFunctionHasBranchProtectedScope(); 14337 break; 14338 } 14339 } 14340 14341 if (var->hasLocalStorage() && 14342 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 14343 setFunctionHasBranchProtectedScope(); 14344 14345 // Warn about externally-visible variables being defined without a 14346 // prior declaration. We only want to do this for global 14347 // declarations, but we also specifically need to avoid doing it for 14348 // class members because the linkage of an anonymous class can 14349 // change if it's later given a typedef name. 14350 if (var->isThisDeclarationADefinition() && 14351 var->getDeclContext()->getRedeclContext()->isFileContext() && 14352 var->isExternallyVisible() && var->hasLinkage() && 14353 !var->isInline() && !var->getDescribedVarTemplate() && 14354 var->getStorageClass() != SC_Register && 14355 !isa<VarTemplatePartialSpecializationDecl>(var) && 14356 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 14357 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 14358 var->getLocation())) { 14359 // Find a previous declaration that's not a definition. 14360 VarDecl *prev = var->getPreviousDecl(); 14361 while (prev && prev->isThisDeclarationADefinition()) 14362 prev = prev->getPreviousDecl(); 14363 14364 if (!prev) { 14365 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 14366 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14367 << /* variable */ 0; 14368 } 14369 } 14370 14371 // Cache the result of checking for constant initialization. 14372 std::optional<bool> CacheHasConstInit; 14373 const Expr *CacheCulprit = nullptr; 14374 auto checkConstInit = [&]() mutable { 14375 if (!CacheHasConstInit) 14376 CacheHasConstInit = var->getInit()->isConstantInitializer( 14377 Context, var->getType()->isReferenceType(), &CacheCulprit); 14378 return *CacheHasConstInit; 14379 }; 14380 14381 if (var->getTLSKind() == VarDecl::TLS_Static) { 14382 if (var->getType().isDestructedType()) { 14383 // GNU C++98 edits for __thread, [basic.start.term]p3: 14384 // The type of an object with thread storage duration shall not 14385 // have a non-trivial destructor. 14386 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 14387 if (getLangOpts().CPlusPlus11) 14388 Diag(var->getLocation(), diag::note_use_thread_local); 14389 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 14390 if (!checkConstInit()) { 14391 // GNU C++98 edits for __thread, [basic.start.init]p4: 14392 // An object of thread storage duration shall not require dynamic 14393 // initialization. 14394 // FIXME: Need strict checking here. 14395 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 14396 << CacheCulprit->getSourceRange(); 14397 if (getLangOpts().CPlusPlus11) 14398 Diag(var->getLocation(), diag::note_use_thread_local); 14399 } 14400 } 14401 } 14402 14403 14404 if (!var->getType()->isStructureType() && var->hasInit() && 14405 isa<InitListExpr>(var->getInit())) { 14406 const auto *ILE = cast<InitListExpr>(var->getInit()); 14407 unsigned NumInits = ILE->getNumInits(); 14408 if (NumInits > 2) 14409 for (unsigned I = 0; I < NumInits; ++I) { 14410 const auto *Init = ILE->getInit(I); 14411 if (!Init) 14412 break; 14413 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 14414 if (!SL) 14415 break; 14416 14417 unsigned NumConcat = SL->getNumConcatenated(); 14418 // Diagnose missing comma in string array initialization. 14419 // Do not warn when all the elements in the initializer are concatenated 14420 // together. Do not warn for macros too. 14421 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 14422 bool OnlyOneMissingComma = true; 14423 for (unsigned J = I + 1; J < NumInits; ++J) { 14424 const auto *Init = ILE->getInit(J); 14425 if (!Init) 14426 break; 14427 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 14428 if (!SLJ || SLJ->getNumConcatenated() > 1) { 14429 OnlyOneMissingComma = false; 14430 break; 14431 } 14432 } 14433 14434 if (OnlyOneMissingComma) { 14435 SmallVector<FixItHint, 1> Hints; 14436 for (unsigned i = 0; i < NumConcat - 1; ++i) 14437 Hints.push_back(FixItHint::CreateInsertion( 14438 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 14439 14440 Diag(SL->getStrTokenLoc(1), 14441 diag::warn_concatenated_literal_array_init) 14442 << Hints; 14443 Diag(SL->getBeginLoc(), 14444 diag::note_concatenated_string_literal_silence); 14445 } 14446 // In any case, stop now. 14447 break; 14448 } 14449 } 14450 } 14451 14452 14453 QualType type = var->getType(); 14454 14455 if (var->hasAttr<BlocksAttr>()) 14456 getCurFunction()->addByrefBlockVar(var); 14457 14458 Expr *Init = var->getInit(); 14459 bool GlobalStorage = var->hasGlobalStorage(); 14460 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 14461 QualType baseType = Context.getBaseElementType(type); 14462 bool HasConstInit = true; 14463 14464 if (getLangOpts().C23 && var->isConstexpr() && !Init) 14465 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init) 14466 << var; 14467 14468 // Check whether the initializer is sufficiently constant. 14469 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) && 14470 !type->isDependentType() && Init && !Init->isValueDependent() && 14471 (GlobalStorage || var->isConstexpr() || 14472 var->mightBeUsableInConstantExpressions(Context))) { 14473 // If this variable might have a constant initializer or might be usable in 14474 // constant expressions, check whether or not it actually is now. We can't 14475 // do this lazily, because the result might depend on things that change 14476 // later, such as which constexpr functions happen to be defined. 14477 SmallVector<PartialDiagnosticAt, 8> Notes; 14478 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) { 14479 // Prior to C++11, in contexts where a constant initializer is required, 14480 // the set of valid constant initializers is described by syntactic rules 14481 // in [expr.const]p2-6. 14482 // FIXME: Stricter checking for these rules would be useful for constinit / 14483 // -Wglobal-constructors. 14484 HasConstInit = checkConstInit(); 14485 14486 // Compute and cache the constant value, and remember that we have a 14487 // constant initializer. 14488 if (HasConstInit) { 14489 (void)var->checkForConstantInitialization(Notes); 14490 Notes.clear(); 14491 } else if (CacheCulprit) { 14492 Notes.emplace_back(CacheCulprit->getExprLoc(), 14493 PDiag(diag::note_invalid_subexpr_in_const_expr)); 14494 Notes.back().second << CacheCulprit->getSourceRange(); 14495 } 14496 } else { 14497 // Evaluate the initializer to see if it's a constant initializer. 14498 HasConstInit = var->checkForConstantInitialization(Notes); 14499 } 14500 14501 if (HasConstInit) { 14502 // FIXME: Consider replacing the initializer with a ConstantExpr. 14503 } else if (var->isConstexpr()) { 14504 SourceLocation DiagLoc = var->getLocation(); 14505 // If the note doesn't add any useful information other than a source 14506 // location, fold it into the primary diagnostic. 14507 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14508 diag::note_invalid_subexpr_in_const_expr) { 14509 DiagLoc = Notes[0].first; 14510 Notes.clear(); 14511 } 14512 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 14513 << var << Init->getSourceRange(); 14514 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 14515 Diag(Notes[I].first, Notes[I].second); 14516 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 14517 auto *Attr = var->getAttr<ConstInitAttr>(); 14518 Diag(var->getLocation(), diag::err_require_constant_init_failed) 14519 << Init->getSourceRange(); 14520 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 14521 << Attr->getRange() << Attr->isConstinit(); 14522 for (auto &it : Notes) 14523 Diag(it.first, it.second); 14524 } else if (IsGlobal && 14525 !getDiagnostics().isIgnored(diag::warn_global_constructor, 14526 var->getLocation())) { 14527 // Warn about globals which don't have a constant initializer. Don't 14528 // warn about globals with a non-trivial destructor because we already 14529 // warned about them. 14530 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 14531 if (!(RD && !RD->hasTrivialDestructor())) { 14532 // checkConstInit() here permits trivial default initialization even in 14533 // C++11 onwards, where such an initializer is not a constant initializer 14534 // but nonetheless doesn't require a global constructor. 14535 if (!checkConstInit()) 14536 Diag(var->getLocation(), diag::warn_global_constructor) 14537 << Init->getSourceRange(); 14538 } 14539 } 14540 } 14541 14542 // Apply section attributes and pragmas to global variables. 14543 if (GlobalStorage && var->isThisDeclarationADefinition() && 14544 !inTemplateInstantiation()) { 14545 PragmaStack<StringLiteral *> *Stack = nullptr; 14546 int SectionFlags = ASTContext::PSF_Read; 14547 bool MSVCEnv = 14548 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment(); 14549 std::optional<QualType::NonConstantStorageReason> Reason; 14550 if (HasConstInit && 14551 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) { 14552 Stack = &ConstSegStack; 14553 } else { 14554 SectionFlags |= ASTContext::PSF_Write; 14555 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack; 14556 } 14557 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 14558 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 14559 SectionFlags |= ASTContext::PSF_Implicit; 14560 UnifySection(SA->getName(), SectionFlags, var); 14561 } else if (Stack->CurrentValue) { 14562 if (Stack != &ConstSegStack && MSVCEnv && 14563 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue && 14564 var->getType().isConstQualified()) { 14565 assert((!Reason || Reason != QualType::NonConstantStorageReason:: 14566 NonConstNonReferenceType) && 14567 "This case should've already been handled elsewhere"); 14568 Diag(var->getLocation(), diag::warn_section_msvc_compat) 14569 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit 14570 ? QualType::NonConstantStorageReason::NonTrivialCtor 14571 : *Reason); 14572 } 14573 SectionFlags |= ASTContext::PSF_Implicit; 14574 auto SectionName = Stack->CurrentValue->getString(); 14575 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName, 14576 Stack->CurrentPragmaLocation, 14577 SectionAttr::Declspec_allocate)); 14578 if (UnifySection(SectionName, SectionFlags, var)) 14579 var->dropAttr<SectionAttr>(); 14580 } 14581 14582 // Apply the init_seg attribute if this has an initializer. If the 14583 // initializer turns out to not be dynamic, we'll end up ignoring this 14584 // attribute. 14585 if (CurInitSeg && var->getInit()) 14586 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 14587 CurInitSegLoc)); 14588 } 14589 14590 // All the following checks are C++ only. 14591 if (!getLangOpts().CPlusPlus) { 14592 // If this variable must be emitted, add it as an initializer for the 14593 // current module. 14594 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 14595 Context.addModuleInitializer(ModuleScopes.back().Module, var); 14596 return; 14597 } 14598 14599 // Require the destructor. 14600 if (!type->isDependentType()) 14601 if (const RecordType *recordType = baseType->getAs<RecordType>()) 14602 FinalizeVarWithDestructor(var, recordType); 14603 14604 // If this variable must be emitted, add it as an initializer for the current 14605 // module. 14606 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 14607 Context.addModuleInitializer(ModuleScopes.back().Module, var); 14608 14609 // Build the bindings if this is a structured binding declaration. 14610 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 14611 CheckCompleteDecompositionDeclaration(DD); 14612 } 14613 14614 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 14615 assert(VD->isStaticLocal()); 14616 14617 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 14618 14619 // Find outermost function when VD is in lambda function. 14620 while (FD && !getDLLAttr(FD) && 14621 !FD->hasAttr<DLLExportStaticLocalAttr>() && 14622 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 14623 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 14624 } 14625 14626 if (!FD) 14627 return; 14628 14629 // Static locals inherit dll attributes from their function. 14630 if (Attr *A = getDLLAttr(FD)) { 14631 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 14632 NewAttr->setInherited(true); 14633 VD->addAttr(NewAttr); 14634 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 14635 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 14636 NewAttr->setInherited(true); 14637 VD->addAttr(NewAttr); 14638 14639 // Export this function to enforce exporting this static variable even 14640 // if it is not used in this compilation unit. 14641 if (!FD->hasAttr<DLLExportAttr>()) 14642 FD->addAttr(NewAttr); 14643 14644 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 14645 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 14646 NewAttr->setInherited(true); 14647 VD->addAttr(NewAttr); 14648 } 14649 } 14650 14651 void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) { 14652 assert(VD->getTLSKind()); 14653 14654 // Perform TLS alignment check here after attributes attached to the variable 14655 // which may affect the alignment have been processed. Only perform the check 14656 // if the target has a maximum TLS alignment (zero means no constraints). 14657 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 14658 // Protect the check so that it's not performed on dependent types and 14659 // dependent alignments (we can't determine the alignment in that case). 14660 if (!VD->hasDependentAlignment()) { 14661 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 14662 if (Context.getDeclAlign(VD) > MaxAlignChars) { 14663 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 14664 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 14665 << (unsigned)MaxAlignChars.getQuantity(); 14666 } 14667 } 14668 } 14669 } 14670 14671 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 14672 // Note that we are no longer parsing the initializer for this declaration. 14673 ParsingInitForAutoVars.erase(ThisDecl); 14674 14675 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 14676 if (!VD) 14677 return; 14678 14679 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 14680 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 14681 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 14682 if (PragmaClangBSSSection.Valid) 14683 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 14684 Context, PragmaClangBSSSection.SectionName, 14685 PragmaClangBSSSection.PragmaLocation)); 14686 if (PragmaClangDataSection.Valid) 14687 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 14688 Context, PragmaClangDataSection.SectionName, 14689 PragmaClangDataSection.PragmaLocation)); 14690 if (PragmaClangRodataSection.Valid) 14691 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 14692 Context, PragmaClangRodataSection.SectionName, 14693 PragmaClangRodataSection.PragmaLocation)); 14694 if (PragmaClangRelroSection.Valid) 14695 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 14696 Context, PragmaClangRelroSection.SectionName, 14697 PragmaClangRelroSection.PragmaLocation)); 14698 } 14699 14700 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 14701 for (auto *BD : DD->bindings()) { 14702 FinalizeDeclaration(BD); 14703 } 14704 } 14705 14706 CheckInvalidBuiltinCountedByRef(VD->getInit(), InitializerKind); 14707 14708 checkAttributesAfterMerging(*this, *VD); 14709 14710 if (VD->isStaticLocal()) 14711 CheckStaticLocalForDllExport(VD); 14712 14713 if (VD->getTLSKind()) 14714 CheckThreadLocalForLargeAlignment(VD); 14715 14716 // Perform check for initializers of device-side global variables. 14717 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 14718 // 7.5). We must also apply the same checks to all __shared__ 14719 // variables whether they are local or not. CUDA also allows 14720 // constant initializers for __constant__ and __device__ variables. 14721 if (getLangOpts().CUDA) 14722 CUDA().checkAllowedInitializer(VD); 14723 14724 // Grab the dllimport or dllexport attribute off of the VarDecl. 14725 const InheritableAttr *DLLAttr = getDLLAttr(VD); 14726 14727 // Imported static data members cannot be defined out-of-line. 14728 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 14729 if (VD->isStaticDataMember() && VD->isOutOfLine() && 14730 VD->isThisDeclarationADefinition()) { 14731 // We allow definitions of dllimport class template static data members 14732 // with a warning. 14733 CXXRecordDecl *Context = 14734 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 14735 bool IsClassTemplateMember = 14736 isa<ClassTemplatePartialSpecializationDecl>(Context) || 14737 Context->getDescribedClassTemplate(); 14738 14739 Diag(VD->getLocation(), 14740 IsClassTemplateMember 14741 ? diag::warn_attribute_dllimport_static_field_definition 14742 : diag::err_attribute_dllimport_static_field_definition); 14743 Diag(IA->getLocation(), diag::note_attribute); 14744 if (!IsClassTemplateMember) 14745 VD->setInvalidDecl(); 14746 } 14747 } 14748 14749 // dllimport/dllexport variables cannot be thread local, their TLS index 14750 // isn't exported with the variable. 14751 if (DLLAttr && VD->getTLSKind()) { 14752 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 14753 if (F && getDLLAttr(F)) { 14754 assert(VD->isStaticLocal()); 14755 // But if this is a static local in a dlimport/dllexport function, the 14756 // function will never be inlined, which means the var would never be 14757 // imported, so having it marked import/export is safe. 14758 } else { 14759 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 14760 << DLLAttr; 14761 VD->setInvalidDecl(); 14762 } 14763 } 14764 14765 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 14766 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 14767 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 14768 << Attr; 14769 VD->dropAttr<UsedAttr>(); 14770 } 14771 } 14772 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 14773 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 14774 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 14775 << Attr; 14776 VD->dropAttr<RetainAttr>(); 14777 } 14778 } 14779 14780 const DeclContext *DC = VD->getDeclContext(); 14781 // If there's a #pragma GCC visibility in scope, and this isn't a class 14782 // member, set the visibility of this variable. 14783 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 14784 AddPushedVisibilityAttribute(VD); 14785 14786 // FIXME: Warn on unused var template partial specializations. 14787 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 14788 MarkUnusedFileScopedDecl(VD); 14789 14790 // Now we have parsed the initializer and can update the table of magic 14791 // tag values. 14792 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 14793 !VD->getType()->isIntegralOrEnumerationType()) 14794 return; 14795 14796 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 14797 const Expr *MagicValueExpr = VD->getInit(); 14798 if (!MagicValueExpr) { 14799 continue; 14800 } 14801 std::optional<llvm::APSInt> MagicValueInt; 14802 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 14803 Diag(I->getRange().getBegin(), 14804 diag::err_type_tag_for_datatype_not_ice) 14805 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 14806 continue; 14807 } 14808 if (MagicValueInt->getActiveBits() > 64) { 14809 Diag(I->getRange().getBegin(), 14810 diag::err_type_tag_for_datatype_too_large) 14811 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 14812 continue; 14813 } 14814 uint64_t MagicValue = MagicValueInt->getZExtValue(); 14815 RegisterTypeTagForDatatype(I->getArgumentKind(), 14816 MagicValue, 14817 I->getMatchingCType(), 14818 I->getLayoutCompatible(), 14819 I->getMustBeNull()); 14820 } 14821 } 14822 14823 static bool hasDeducedAuto(DeclaratorDecl *DD) { 14824 auto *VD = dyn_cast<VarDecl>(DD); 14825 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 14826 } 14827 14828 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 14829 ArrayRef<Decl *> Group) { 14830 SmallVector<Decl*, 8> Decls; 14831 14832 if (DS.isTypeSpecOwned()) 14833 Decls.push_back(DS.getRepAsDecl()); 14834 14835 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 14836 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 14837 bool DiagnosedMultipleDecomps = false; 14838 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 14839 bool DiagnosedNonDeducedAuto = false; 14840 14841 for (Decl *D : Group) { 14842 if (!D) 14843 continue; 14844 // Check if the Decl has been declared in '#pragma omp declare target' 14845 // directive and has static storage duration. 14846 if (auto *VD = dyn_cast<VarDecl>(D); 14847 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() && 14848 VD->hasGlobalStorage()) 14849 OpenMP().ActOnOpenMPDeclareTargetInitializer(D); 14850 // For declarators, there are some additional syntactic-ish checks we need 14851 // to perform. 14852 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 14853 if (!FirstDeclaratorInGroup) 14854 FirstDeclaratorInGroup = DD; 14855 if (!FirstDecompDeclaratorInGroup) 14856 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 14857 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 14858 !hasDeducedAuto(DD)) 14859 FirstNonDeducedAutoInGroup = DD; 14860 14861 if (FirstDeclaratorInGroup != DD) { 14862 // A decomposition declaration cannot be combined with any other 14863 // declaration in the same group. 14864 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 14865 Diag(FirstDecompDeclaratorInGroup->getLocation(), 14866 diag::err_decomp_decl_not_alone) 14867 << FirstDeclaratorInGroup->getSourceRange() 14868 << DD->getSourceRange(); 14869 DiagnosedMultipleDecomps = true; 14870 } 14871 14872 // A declarator that uses 'auto' in any way other than to declare a 14873 // variable with a deduced type cannot be combined with any other 14874 // declarator in the same group. 14875 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 14876 Diag(FirstNonDeducedAutoInGroup->getLocation(), 14877 diag::err_auto_non_deduced_not_alone) 14878 << FirstNonDeducedAutoInGroup->getType() 14879 ->hasAutoForTrailingReturnType() 14880 << FirstDeclaratorInGroup->getSourceRange() 14881 << DD->getSourceRange(); 14882 DiagnosedNonDeducedAuto = true; 14883 } 14884 } 14885 } 14886 14887 Decls.push_back(D); 14888 } 14889 14890 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 14891 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 14892 handleTagNumbering(Tag, S); 14893 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 14894 getLangOpts().CPlusPlus) 14895 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 14896 } 14897 } 14898 14899 return BuildDeclaratorGroup(Decls); 14900 } 14901 14902 Sema::DeclGroupPtrTy 14903 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 14904 // C++14 [dcl.spec.auto]p7: (DR1347) 14905 // If the type that replaces the placeholder type is not the same in each 14906 // deduction, the program is ill-formed. 14907 if (Group.size() > 1) { 14908 QualType Deduced; 14909 VarDecl *DeducedDecl = nullptr; 14910 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 14911 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 14912 if (!D || D->isInvalidDecl()) 14913 break; 14914 DeducedType *DT = D->getType()->getContainedDeducedType(); 14915 if (!DT || DT->getDeducedType().isNull()) 14916 continue; 14917 if (Deduced.isNull()) { 14918 Deduced = DT->getDeducedType(); 14919 DeducedDecl = D; 14920 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 14921 auto *AT = dyn_cast<AutoType>(DT); 14922 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 14923 diag::err_auto_different_deductions) 14924 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 14925 << DeducedDecl->getDeclName() << DT->getDeducedType() 14926 << D->getDeclName(); 14927 if (DeducedDecl->hasInit()) 14928 Dia << DeducedDecl->getInit()->getSourceRange(); 14929 if (D->getInit()) 14930 Dia << D->getInit()->getSourceRange(); 14931 D->setInvalidDecl(); 14932 break; 14933 } 14934 } 14935 } 14936 14937 ActOnDocumentableDecls(Group); 14938 14939 return DeclGroupPtrTy::make( 14940 DeclGroupRef::Create(Context, Group.data(), Group.size())); 14941 } 14942 14943 void Sema::ActOnDocumentableDecl(Decl *D) { 14944 ActOnDocumentableDecls(D); 14945 } 14946 14947 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 14948 // Don't parse the comment if Doxygen diagnostics are ignored. 14949 if (Group.empty() || !Group[0]) 14950 return; 14951 14952 if (Diags.isIgnored(diag::warn_doc_param_not_found, 14953 Group[0]->getLocation()) && 14954 Diags.isIgnored(diag::warn_unknown_comment_command_name, 14955 Group[0]->getLocation())) 14956 return; 14957 14958 if (Group.size() >= 2) { 14959 // This is a decl group. Normally it will contain only declarations 14960 // produced from declarator list. But in case we have any definitions or 14961 // additional declaration references: 14962 // 'typedef struct S {} S;' 14963 // 'typedef struct S *S;' 14964 // 'struct S *pS;' 14965 // FinalizeDeclaratorGroup adds these as separate declarations. 14966 Decl *MaybeTagDecl = Group[0]; 14967 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 14968 Group = Group.slice(1); 14969 } 14970 } 14971 14972 // FIMXE: We assume every Decl in the group is in the same file. 14973 // This is false when preprocessor constructs the group from decls in 14974 // different files (e. g. macros or #include). 14975 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 14976 } 14977 14978 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 14979 // Check that there are no default arguments inside the type of this 14980 // parameter. 14981 if (getLangOpts().CPlusPlus) 14982 CheckExtraCXXDefaultArguments(D); 14983 14984 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 14985 if (D.getCXXScopeSpec().isSet()) { 14986 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 14987 << D.getCXXScopeSpec().getRange(); 14988 } 14989 14990 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 14991 // simple identifier except [...irrelevant cases...]. 14992 switch (D.getName().getKind()) { 14993 case UnqualifiedIdKind::IK_Identifier: 14994 break; 14995 14996 case UnqualifiedIdKind::IK_OperatorFunctionId: 14997 case UnqualifiedIdKind::IK_ConversionFunctionId: 14998 case UnqualifiedIdKind::IK_LiteralOperatorId: 14999 case UnqualifiedIdKind::IK_ConstructorName: 15000 case UnqualifiedIdKind::IK_DestructorName: 15001 case UnqualifiedIdKind::IK_ImplicitSelfParam: 15002 case UnqualifiedIdKind::IK_DeductionGuideName: 15003 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 15004 << GetNameForDeclarator(D).getName(); 15005 break; 15006 15007 case UnqualifiedIdKind::IK_TemplateId: 15008 case UnqualifiedIdKind::IK_ConstructorTemplateId: 15009 // GetNameForDeclarator would not produce a useful name in this case. 15010 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 15011 break; 15012 } 15013 } 15014 15015 static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, 15016 SourceLocation ExplicitThisLoc) { 15017 if (!ExplicitThisLoc.isValid()) 15018 return; 15019 assert(S.getLangOpts().CPlusPlus && 15020 "explicit parameter in non-cplusplus mode"); 15021 if (!S.getLangOpts().CPlusPlus23) 15022 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this) 15023 << P->getSourceRange(); 15024 15025 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function 15026 // parameter pack. 15027 if (P->isParameterPack()) { 15028 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack) 15029 << P->getSourceRange(); 15030 return; 15031 } 15032 P->setExplicitObjectParameterLoc(ExplicitThisLoc); 15033 if (LambdaScopeInfo *LSI = S.getCurLambda()) 15034 LSI->ExplicitObjectParameter = P; 15035 } 15036 15037 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D, 15038 SourceLocation ExplicitThisLoc) { 15039 const DeclSpec &DS = D.getDeclSpec(); 15040 15041 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 15042 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type, 15043 // except for the special case of a single unnamed parameter of type void 15044 // with no storage class specifier, no type qualifier, and no following 15045 // ellipsis terminator. 15046 // Clang applies the C2y rules for 'register void' in all C language modes, 15047 // same as GCC, because it's questionable what that could possibly mean. 15048 15049 // C++03 [dcl.stc]p2 also permits 'auto'. 15050 StorageClass SC = SC_None; 15051 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 15052 SC = SC_Register; 15053 // In C++11, the 'register' storage class specifier is deprecated. 15054 // In C++17, it is not allowed, but we tolerate it as an extension. 15055 if (getLangOpts().CPlusPlus11) { 15056 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus17 15057 ? diag::ext_register_storage_class 15058 : diag::warn_deprecated_register) 15059 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 15060 } else if (!getLangOpts().CPlusPlus && 15061 DS.getTypeSpecType() == DeclSpec::TST_void && 15062 D.getNumTypeObjects() == 0) { 15063 Diag(DS.getStorageClassSpecLoc(), 15064 diag::err_invalid_storage_class_in_func_decl) 15065 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 15066 D.getMutableDeclSpec().ClearStorageClassSpecs(); 15067 } 15068 } else if (getLangOpts().CPlusPlus && 15069 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 15070 SC = SC_Auto; 15071 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 15072 Diag(DS.getStorageClassSpecLoc(), 15073 diag::err_invalid_storage_class_in_func_decl); 15074 D.getMutableDeclSpec().ClearStorageClassSpecs(); 15075 } 15076 15077 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 15078 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 15079 << DeclSpec::getSpecifierName(TSCS); 15080 if (DS.isInlineSpecified()) 15081 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 15082 << getLangOpts().CPlusPlus17; 15083 if (DS.hasConstexprSpecifier()) 15084 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 15085 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 15086 15087 DiagnoseFunctionSpecifiers(DS); 15088 15089 CheckFunctionOrTemplateParamDeclarator(S, D); 15090 15091 TypeSourceInfo *TInfo = GetTypeForDeclarator(D); 15092 QualType parmDeclType = TInfo->getType(); 15093 15094 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 15095 const IdentifierInfo *II = D.getIdentifier(); 15096 if (II) { 15097 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 15098 RedeclarationKind::ForVisibleRedeclaration); 15099 LookupName(R, S); 15100 if (!R.empty()) { 15101 NamedDecl *PrevDecl = *R.begin(); 15102 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) { 15103 // Maybe we will complain about the shadowed template parameter. 15104 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15105 // Just pretend that we didn't see the previous declaration. 15106 PrevDecl = nullptr; 15107 } 15108 if (PrevDecl && S->isDeclScope(PrevDecl)) { 15109 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 15110 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15111 // Recover by removing the name 15112 II = nullptr; 15113 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 15114 D.setInvalidType(true); 15115 } 15116 } 15117 } 15118 15119 // Temporarily put parameter variables in the translation unit, not 15120 // the enclosing context. This prevents them from accidentally 15121 // looking like class members in C++. 15122 ParmVarDecl *New = 15123 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 15124 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 15125 15126 if (D.isInvalidType()) 15127 New->setInvalidDecl(); 15128 15129 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc); 15130 15131 assert(S->isFunctionPrototypeScope()); 15132 assert(S->getFunctionPrototypeDepth() >= 1); 15133 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 15134 S->getNextFunctionPrototypeIndex()); 15135 15136 // Add the parameter declaration into this scope. 15137 S->AddDecl(New); 15138 if (II) 15139 IdResolver.AddDecl(New); 15140 15141 ProcessDeclAttributes(S, New, D); 15142 15143 if (D.getDeclSpec().isModulePrivateSpecified()) 15144 Diag(New->getLocation(), diag::err_module_private_local) 15145 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15146 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 15147 15148 if (New->hasAttr<BlocksAttr>()) { 15149 Diag(New->getLocation(), diag::err_block_on_nonlocal); 15150 } 15151 15152 if (getLangOpts().OpenCL) 15153 deduceOpenCLAddressSpace(New); 15154 15155 return New; 15156 } 15157 15158 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 15159 SourceLocation Loc, 15160 QualType T) { 15161 /* FIXME: setting StartLoc == Loc. 15162 Would it be worth to modify callers so as to provide proper source 15163 location for the unnamed parameters, embedding the parameter's type? */ 15164 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 15165 T, Context.getTrivialTypeSourceInfo(T, Loc), 15166 SC_None, nullptr); 15167 Param->setImplicit(); 15168 return Param; 15169 } 15170 15171 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 15172 // Don't diagnose unused-parameter errors in template instantiations; we 15173 // will already have done so in the template itself. 15174 if (inTemplateInstantiation()) 15175 return; 15176 15177 for (const ParmVarDecl *Parameter : Parameters) { 15178 if (!Parameter->isReferenced() && Parameter->getDeclName() && 15179 !Parameter->hasAttr<UnusedAttr>() && 15180 !Parameter->getIdentifier()->isPlaceholder()) { 15181 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 15182 << Parameter->getDeclName(); 15183 } 15184 } 15185 } 15186 15187 void Sema::DiagnoseSizeOfParametersAndReturnValue( 15188 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 15189 if (LangOpts.NumLargeByValueCopy == 0) // No check. 15190 return; 15191 15192 // Warn if the return value is pass-by-value and larger than the specified 15193 // threshold. 15194 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 15195 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 15196 if (Size > LangOpts.NumLargeByValueCopy) 15197 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 15198 } 15199 15200 // Warn if any parameter is pass-by-value and larger than the specified 15201 // threshold. 15202 for (const ParmVarDecl *Parameter : Parameters) { 15203 QualType T = Parameter->getType(); 15204 if (T->isDependentType() || !T.isPODType(Context)) 15205 continue; 15206 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 15207 if (Size > LangOpts.NumLargeByValueCopy) 15208 Diag(Parameter->getLocation(), diag::warn_parameter_size) 15209 << Parameter << Size; 15210 } 15211 } 15212 15213 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 15214 SourceLocation NameLoc, 15215 const IdentifierInfo *Name, QualType T, 15216 TypeSourceInfo *TSInfo, StorageClass SC) { 15217 // In ARC, infer a lifetime qualifier for appropriate parameter types. 15218 if (getLangOpts().ObjCAutoRefCount && 15219 T.getObjCLifetime() == Qualifiers::OCL_None && 15220 T->isObjCLifetimeType()) { 15221 15222 Qualifiers::ObjCLifetime lifetime; 15223 15224 // Special cases for arrays: 15225 // - if it's const, use __unsafe_unretained 15226 // - otherwise, it's an error 15227 if (T->isArrayType()) { 15228 if (!T.isConstQualified()) { 15229 if (DelayedDiagnostics.shouldDelayDiagnostics()) 15230 DelayedDiagnostics.add( 15231 sema::DelayedDiagnostic::makeForbiddenType( 15232 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 15233 else 15234 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 15235 << TSInfo->getTypeLoc().getSourceRange(); 15236 } 15237 lifetime = Qualifiers::OCL_ExplicitNone; 15238 } else { 15239 lifetime = T->getObjCARCImplicitLifetime(); 15240 } 15241 T = Context.getLifetimeQualifiedType(T, lifetime); 15242 } 15243 15244 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 15245 Context.getAdjustedParameterType(T), 15246 TSInfo, SC, nullptr); 15247 15248 // Make a note if we created a new pack in the scope of a lambda, so that 15249 // we know that references to that pack must also be expanded within the 15250 // lambda scope. 15251 if (New->isParameterPack()) 15252 if (auto *CSI = getEnclosingLambdaOrBlock()) 15253 CSI->LocalPacks.push_back(New); 15254 15255 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 15256 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 15257 checkNonTrivialCUnion(New->getType(), New->getLocation(), 15258 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 15259 15260 // Parameter declarators cannot be interface types. All ObjC objects are 15261 // passed by reference. 15262 if (T->isObjCObjectType()) { 15263 SourceLocation TypeEndLoc = 15264 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 15265 Diag(NameLoc, 15266 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 15267 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 15268 T = Context.getObjCObjectPointerType(T); 15269 New->setType(T); 15270 } 15271 15272 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 15273 // duration shall not be qualified by an address-space qualifier." 15274 // Since all parameters have automatic store duration, they can not have 15275 // an address space. 15276 if (T.getAddressSpace() != LangAS::Default && 15277 // OpenCL allows function arguments declared to be an array of a type 15278 // to be qualified with an address space. 15279 !(getLangOpts().OpenCL && 15280 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) && 15281 // WebAssembly allows reference types as parameters. Funcref in particular 15282 // lives in a different address space. 15283 !(T->isFunctionPointerType() && 15284 T.getAddressSpace() == LangAS::wasm_funcref)) { 15285 Diag(NameLoc, diag::err_arg_with_address_space); 15286 New->setInvalidDecl(); 15287 } 15288 15289 // PPC MMA non-pointer types are not allowed as function argument types. 15290 if (Context.getTargetInfo().getTriple().isPPC64() && 15291 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 15292 New->setInvalidDecl(); 15293 } 15294 15295 return New; 15296 } 15297 15298 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 15299 SourceLocation LocAfterDecls) { 15300 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 15301 15302 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration 15303 // in the declaration list shall have at least one declarator, those 15304 // declarators shall only declare identifiers from the identifier list, and 15305 // every identifier in the identifier list shall be declared. 15306 // 15307 // C89 3.7.1p5 "If a declarator includes an identifier list, only the 15308 // identifiers it names shall be declared in the declaration list." 15309 // 15310 // This is why we only diagnose in C99 and later. Note, the other conditions 15311 // listed are checked elsewhere. 15312 if (!FTI.hasPrototype) { 15313 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 15314 --i; 15315 if (FTI.Params[i].Param == nullptr) { 15316 if (getLangOpts().C99) { 15317 SmallString<256> Code; 15318 llvm::raw_svector_ostream(Code) 15319 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 15320 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 15321 << FTI.Params[i].Ident 15322 << FixItHint::CreateInsertion(LocAfterDecls, Code); 15323 } 15324 15325 // Implicitly declare the argument as type 'int' for lack of a better 15326 // type. 15327 AttributeFactory attrs; 15328 DeclSpec DS(attrs); 15329 const char* PrevSpec; // unused 15330 unsigned DiagID; // unused 15331 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 15332 DiagID, Context.getPrintingPolicy()); 15333 // Use the identifier location for the type source range. 15334 DS.SetRangeStart(FTI.Params[i].IdentLoc); 15335 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 15336 Declarator ParamD(DS, ParsedAttributesView::none(), 15337 DeclaratorContext::KNRTypeList); 15338 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 15339 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 15340 } 15341 } 15342 } 15343 } 15344 15345 Decl * 15346 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 15347 MultiTemplateParamsArg TemplateParameterLists, 15348 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) { 15349 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 15350 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 15351 Scope *ParentScope = FnBodyScope->getParent(); 15352 15353 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 15354 // we define a non-templated function definition, we will create a declaration 15355 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 15356 // The base function declaration will have the equivalent of an `omp declare 15357 // variant` annotation which specifies the mangled definition as a 15358 // specialization function under the OpenMP context defined as part of the 15359 // `omp begin declare variant`. 15360 SmallVector<FunctionDecl *, 4> Bases; 15361 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope()) 15362 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 15363 ParentScope, D, TemplateParameterLists, Bases); 15364 15365 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 15366 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 15367 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind); 15368 15369 if (!Bases.empty()) 15370 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, 15371 Bases); 15372 15373 return Dcl; 15374 } 15375 15376 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 15377 Consumer.HandleInlineFunctionDefinition(D); 15378 } 15379 15380 static bool FindPossiblePrototype(const FunctionDecl *FD, 15381 const FunctionDecl *&PossiblePrototype) { 15382 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev; 15383 Prev = Prev->getPreviousDecl()) { 15384 // Ignore any declarations that occur in function or method 15385 // scope, because they aren't visible from the header. 15386 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 15387 continue; 15388 15389 PossiblePrototype = Prev; 15390 return Prev->getType()->isFunctionProtoType(); 15391 } 15392 return false; 15393 } 15394 15395 static bool 15396 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 15397 const FunctionDecl *&PossiblePrototype) { 15398 // Don't warn about invalid declarations. 15399 if (FD->isInvalidDecl()) 15400 return false; 15401 15402 // Or declarations that aren't global. 15403 if (!FD->isGlobal()) 15404 return false; 15405 15406 // Don't warn about C++ member functions. 15407 if (isa<CXXMethodDecl>(FD)) 15408 return false; 15409 15410 // Don't warn about 'main'. 15411 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 15412 if (IdentifierInfo *II = FD->getIdentifier()) 15413 if (II->isStr("main") || II->isStr("efi_main")) 15414 return false; 15415 15416 if (FD->isMSVCRTEntryPoint()) 15417 return false; 15418 15419 // Don't warn about inline functions. 15420 if (FD->isInlined()) 15421 return false; 15422 15423 // Don't warn about function templates. 15424 if (FD->getDescribedFunctionTemplate()) 15425 return false; 15426 15427 // Don't warn about function template specializations. 15428 if (FD->isFunctionTemplateSpecialization()) 15429 return false; 15430 15431 // Don't warn for OpenCL kernels. 15432 if (FD->hasAttr<OpenCLKernelAttr>()) 15433 return false; 15434 15435 // Don't warn on explicitly deleted functions. 15436 if (FD->isDeleted()) 15437 return false; 15438 15439 // Don't warn on implicitly local functions (such as having local-typed 15440 // parameters). 15441 if (!FD->isExternallyVisible()) 15442 return false; 15443 15444 // If we were able to find a potential prototype, don't warn. 15445 if (FindPossiblePrototype(FD, PossiblePrototype)) 15446 return false; 15447 15448 return true; 15449 } 15450 15451 void 15452 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 15453 const FunctionDecl *EffectiveDefinition, 15454 SkipBodyInfo *SkipBody) { 15455 const FunctionDecl *Definition = EffectiveDefinition; 15456 if (!Definition && 15457 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 15458 return; 15459 15460 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 15461 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 15462 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 15463 // A merged copy of the same function, instantiated as a member of 15464 // the same class, is OK. 15465 if (declaresSameEntity(OrigFD, OrigDef) && 15466 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 15467 cast<Decl>(FD->getLexicalDeclContext()))) 15468 return; 15469 } 15470 } 15471 } 15472 15473 if (canRedefineFunction(Definition, getLangOpts())) 15474 return; 15475 15476 // Don't emit an error when this is redefinition of a typo-corrected 15477 // definition. 15478 if (TypoCorrectedFunctionDefinitions.count(Definition)) 15479 return; 15480 15481 // If we don't have a visible definition of the function, and it's inline or 15482 // a template, skip the new definition. 15483 if (SkipBody && !hasVisibleDefinition(Definition) && 15484 (Definition->getFormalLinkage() == Linkage::Internal || 15485 Definition->isInlined() || Definition->getDescribedFunctionTemplate() || 15486 Definition->getNumTemplateParameterLists())) { 15487 SkipBody->ShouldSkip = true; 15488 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 15489 if (auto *TD = Definition->getDescribedFunctionTemplate()) 15490 makeMergedDefinitionVisible(TD); 15491 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 15492 return; 15493 } 15494 15495 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 15496 Definition->getStorageClass() == SC_Extern) 15497 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 15498 << FD << getLangOpts().CPlusPlus; 15499 else 15500 Diag(FD->getLocation(), diag::err_redefinition) << FD; 15501 15502 Diag(Definition->getLocation(), diag::note_previous_definition); 15503 FD->setInvalidDecl(); 15504 } 15505 15506 LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) { 15507 CXXRecordDecl *LambdaClass = CallOperator->getParent(); 15508 15509 LambdaScopeInfo *LSI = PushLambdaScope(); 15510 LSI->CallOperator = CallOperator; 15511 LSI->Lambda = LambdaClass; 15512 LSI->ReturnType = CallOperator->getReturnType(); 15513 // When this function is called in situation where the context of the call 15514 // operator is not entered, we set AfterParameterList to false, so that 15515 // `tryCaptureVariable` finds explicit captures in the appropriate context. 15516 // There is also at least a situation as in FinishTemplateArgumentDeduction(), 15517 // where we would set the CurContext to the lambda operator before 15518 // substituting into it. In this case the flag needs to be true such that 15519 // tryCaptureVariable can correctly handle potential captures thereof. 15520 LSI->AfterParameterList = CurContext == CallOperator; 15521 15522 // GLTemplateParameterList is necessary for getCurGenericLambda() which is 15523 // used at the point of dealing with potential captures. 15524 // 15525 // We don't use LambdaClass->isGenericLambda() because this value doesn't 15526 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are 15527 // associated. (Technically, we could recover that list from their 15528 // instantiation patterns, but for now, the GLTemplateParameterList seems 15529 // unnecessary in these cases.) 15530 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate()) 15531 LSI->GLTemplateParameterList = FTD->getTemplateParameters(); 15532 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 15533 15534 if (LCD == LCD_None) 15535 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 15536 else if (LCD == LCD_ByCopy) 15537 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 15538 else if (LCD == LCD_ByRef) 15539 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 15540 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 15541 15542 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 15543 LSI->Mutable = !CallOperator->isConst(); 15544 if (CallOperator->isExplicitObjectMemberFunction()) 15545 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0); 15546 15547 // Add the captures to the LSI so they can be noted as already 15548 // captured within tryCaptureVar. 15549 auto I = LambdaClass->field_begin(); 15550 for (const auto &C : LambdaClass->captures()) { 15551 if (C.capturesVariable()) { 15552 ValueDecl *VD = C.getCapturedVar(); 15553 if (VD->isInitCapture()) 15554 CurrentInstantiationScope->InstantiatedLocal(VD, VD); 15555 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 15556 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 15557 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 15558 /*EllipsisLoc*/C.isPackExpansion() 15559 ? C.getEllipsisLoc() : SourceLocation(), 15560 I->getType(), /*Invalid*/false); 15561 15562 } else if (C.capturesThis()) { 15563 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 15564 C.getCaptureKind() == LCK_StarThis); 15565 } else { 15566 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 15567 I->getType()); 15568 } 15569 ++I; 15570 } 15571 return LSI; 15572 } 15573 15574 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 15575 SkipBodyInfo *SkipBody, 15576 FnBodyKind BodyKind) { 15577 if (!D) { 15578 // Parsing the function declaration failed in some way. Push on a fake scope 15579 // anyway so we can try to parse the function body. 15580 PushFunctionScope(); 15581 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15582 return D; 15583 } 15584 15585 FunctionDecl *FD = nullptr; 15586 15587 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 15588 FD = FunTmpl->getTemplatedDecl(); 15589 else 15590 FD = cast<FunctionDecl>(D); 15591 15592 // Do not push if it is a lambda because one is already pushed when building 15593 // the lambda in ActOnStartOfLambdaDefinition(). 15594 if (!isLambdaCallOperator(FD)) 15595 // [expr.const]/p14.1 15596 // An expression or conversion is in an immediate function context if it is 15597 // potentially evaluated and either: its innermost enclosing non-block scope 15598 // is a function parameter scope of an immediate function. 15599 PushExpressionEvaluationContext( 15600 FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext 15601 : ExprEvalContexts.back().Context); 15602 15603 // Each ExpressionEvaluationContextRecord also keeps track of whether the 15604 // context is nested in an immediate function context, so smaller contexts 15605 // that appear inside immediate functions (like variable initializers) are 15606 // considered to be inside an immediate function context even though by 15607 // themselves they are not immediate function contexts. But when a new 15608 // function is entered, we need to reset this tracking, since the entered 15609 // function might be not an immediate function. 15610 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval(); 15611 ExprEvalContexts.back().InImmediateEscalatingFunctionContext = 15612 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating(); 15613 15614 // Check for defining attributes before the check for redefinition. 15615 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 15616 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 15617 FD->dropAttr<AliasAttr>(); 15618 FD->setInvalidDecl(); 15619 } 15620 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 15621 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 15622 FD->dropAttr<IFuncAttr>(); 15623 FD->setInvalidDecl(); 15624 } 15625 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) { 15626 if (Context.getTargetInfo().getTriple().isAArch64() && 15627 !Context.getTargetInfo().hasFeature("fmv") && 15628 !Attr->isDefaultVersion()) { 15629 // If function multi versioning disabled skip parsing function body 15630 // defined with non-default target_version attribute 15631 if (SkipBody) 15632 SkipBody->ShouldSkip = true; 15633 return nullptr; 15634 } 15635 } 15636 15637 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 15638 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 15639 Ctor->isDefaultConstructor() && 15640 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 15641 // If this is an MS ABI dllexport default constructor, instantiate any 15642 // default arguments. 15643 InstantiateDefaultCtorDefaultArgs(Ctor); 15644 } 15645 } 15646 15647 // See if this is a redefinition. If 'will have body' (or similar) is already 15648 // set, then these checks were already performed when it was set. 15649 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 15650 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 15651 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 15652 15653 // If we're skipping the body, we're done. Don't enter the scope. 15654 if (SkipBody && SkipBody->ShouldSkip) 15655 return D; 15656 } 15657 15658 // Mark this function as "will have a body eventually". This lets users to 15659 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 15660 // this function. 15661 FD->setWillHaveBody(); 15662 15663 // If we are instantiating a generic lambda call operator, push 15664 // a LambdaScopeInfo onto the function stack. But use the information 15665 // that's already been calculated (ActOnLambdaExpr) to prime the current 15666 // LambdaScopeInfo. 15667 // When the template operator is being specialized, the LambdaScopeInfo, 15668 // has to be properly restored so that tryCaptureVariable doesn't try 15669 // and capture any new variables. In addition when calculating potential 15670 // captures during transformation of nested lambdas, it is necessary to 15671 // have the LSI properly restored. 15672 if (isGenericLambdaCallOperatorSpecialization(FD)) { 15673 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly 15674 // instantiated, explicitly specialized. 15675 if (FD->getTemplateSpecializationInfo() 15676 ->isExplicitInstantiationOrSpecialization()) { 15677 Diag(FD->getLocation(), diag::err_lambda_explicit_spec); 15678 FD->setInvalidDecl(); 15679 PushFunctionScope(); 15680 } else { 15681 assert(inTemplateInstantiation() && 15682 "There should be an active template instantiation on the stack " 15683 "when instantiating a generic lambda!"); 15684 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D)); 15685 } 15686 } else { 15687 // Enter a new function scope 15688 PushFunctionScope(); 15689 } 15690 15691 // Builtin functions cannot be defined. 15692 if (unsigned BuiltinID = FD->getBuiltinID()) { 15693 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 15694 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 15695 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 15696 FD->setInvalidDecl(); 15697 } 15698 } 15699 15700 // The return type of a function definition must be complete (C99 6.9.1p3). 15701 // C++23 [dcl.fct.def.general]/p2 15702 // The type of [...] the return for a function definition 15703 // shall not be a (possibly cv-qualified) class type that is incomplete 15704 // or abstract within the function body unless the function is deleted. 15705 QualType ResultType = FD->getReturnType(); 15706 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 15707 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete && 15708 (RequireCompleteType(FD->getLocation(), ResultType, 15709 diag::err_func_def_incomplete_result) || 15710 RequireNonAbstractType(FD->getLocation(), FD->getReturnType(), 15711 diag::err_abstract_type_in_decl, 15712 AbstractReturnType))) 15713 FD->setInvalidDecl(); 15714 15715 if (FnBodyScope) 15716 PushDeclContext(FnBodyScope, FD); 15717 15718 // Check the validity of our function parameters 15719 if (BodyKind != FnBodyKind::Delete) 15720 CheckParmsForFunctionDef(FD->parameters(), 15721 /*CheckParameterNames=*/true); 15722 15723 // Add non-parameter declarations already in the function to the current 15724 // scope. 15725 if (FnBodyScope) { 15726 for (Decl *NPD : FD->decls()) { 15727 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 15728 if (!NonParmDecl) 15729 continue; 15730 assert(!isa<ParmVarDecl>(NonParmDecl) && 15731 "parameters should not be in newly created FD yet"); 15732 15733 // If the decl has a name, make it accessible in the current scope. 15734 if (NonParmDecl->getDeclName()) 15735 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 15736 15737 // Similarly, dive into enums and fish their constants out, making them 15738 // accessible in this scope. 15739 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 15740 for (auto *EI : ED->enumerators()) 15741 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 15742 } 15743 } 15744 } 15745 15746 // Introduce our parameters into the function scope 15747 for (auto *Param : FD->parameters()) { 15748 Param->setOwningFunction(FD); 15749 15750 // If this has an identifier, add it to the scope stack. 15751 if (Param->getIdentifier() && FnBodyScope) { 15752 CheckShadow(FnBodyScope, Param); 15753 15754 PushOnScopeChains(Param, FnBodyScope); 15755 } 15756 } 15757 15758 // C++ [module.import/6] external definitions are not permitted in header 15759 // units. Deleted and Defaulted functions are implicitly inline (but the 15760 // inline state is not set at this point, so check the BodyKind explicitly). 15761 // FIXME: Consider an alternate location for the test where the inlined() 15762 // state is complete. 15763 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() && 15764 !FD->isInvalidDecl() && !FD->isInlined() && 15765 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default && 15766 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() && 15767 !FD->isTemplateInstantiation()) { 15768 assert(FD->isThisDeclarationADefinition()); 15769 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit); 15770 FD->setInvalidDecl(); 15771 } 15772 15773 // Ensure that the function's exception specification is instantiated. 15774 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 15775 ResolveExceptionSpec(D->getLocation(), FPT); 15776 15777 // dllimport cannot be applied to non-inline function definitions. 15778 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 15779 !FD->isTemplateInstantiation()) { 15780 assert(!FD->hasAttr<DLLExportAttr>()); 15781 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 15782 FD->setInvalidDecl(); 15783 return D; 15784 } 15785 15786 // Some function attributes (like OptimizeNoneAttr) need actions before 15787 // parsing body started. 15788 applyFunctionAttributesBeforeParsingBody(D); 15789 15790 // We want to attach documentation to original Decl (which might be 15791 // a function template). 15792 ActOnDocumentableDecl(D); 15793 if (getCurLexicalContext()->isObjCContainer() && 15794 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 15795 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 15796 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 15797 15798 maybeAddDeclWithEffects(FD); 15799 15800 return D; 15801 } 15802 15803 void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) { 15804 if (!FD || FD->isInvalidDecl()) 15805 return; 15806 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD)) 15807 FD = TD->getTemplatedDecl(); 15808 if (FD && FD->hasAttr<OptimizeNoneAttr>()) { 15809 FPOptionsOverride FPO; 15810 FPO.setDisallowOptimizations(); 15811 CurFPFeatures.applyChanges(FPO); 15812 FpPragmaStack.CurrentValue = 15813 CurFPFeatures.getChangesFrom(FPOptions(LangOpts)); 15814 } 15815 } 15816 15817 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 15818 ReturnStmt **Returns = Scope->Returns.data(); 15819 15820 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 15821 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 15822 if (!NRVOCandidate->isNRVOVariable()) 15823 Returns[I]->setNRVOCandidate(nullptr); 15824 } 15825 } 15826 } 15827 15828 bool Sema::canDelayFunctionBody(const Declarator &D) { 15829 // We can't delay parsing the body of a constexpr function template (yet). 15830 if (D.getDeclSpec().hasConstexprSpecifier()) 15831 return false; 15832 15833 // We can't delay parsing the body of a function template with a deduced 15834 // return type (yet). 15835 if (D.getDeclSpec().hasAutoTypeSpec()) { 15836 // If the placeholder introduces a non-deduced trailing return type, 15837 // we can still delay parsing it. 15838 if (D.getNumTypeObjects()) { 15839 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 15840 if (Outer.Kind == DeclaratorChunk::Function && 15841 Outer.Fun.hasTrailingReturnType()) { 15842 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 15843 return Ty.isNull() || !Ty->isUndeducedType(); 15844 } 15845 } 15846 return false; 15847 } 15848 15849 return true; 15850 } 15851 15852 bool Sema::canSkipFunctionBody(Decl *D) { 15853 // We cannot skip the body of a function (or function template) which is 15854 // constexpr, since we may need to evaluate its body in order to parse the 15855 // rest of the file. 15856 // We cannot skip the body of a function with an undeduced return type, 15857 // because any callers of that function need to know the type. 15858 if (const FunctionDecl *FD = D->getAsFunction()) { 15859 if (FD->isConstexpr()) 15860 return false; 15861 // We can't simply call Type::isUndeducedType here, because inside template 15862 // auto can be deduced to a dependent type, which is not considered 15863 // "undeduced". 15864 if (FD->getReturnType()->getContainedDeducedType()) 15865 return false; 15866 } 15867 return Consumer.shouldSkipFunctionBody(D); 15868 } 15869 15870 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 15871 if (!Decl) 15872 return nullptr; 15873 if (FunctionDecl *FD = Decl->getAsFunction()) 15874 FD->setHasSkippedBody(); 15875 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 15876 MD->setHasSkippedBody(); 15877 return Decl; 15878 } 15879 15880 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 15881 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false); 15882 } 15883 15884 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 15885 /// body. 15886 class ExitFunctionBodyRAII { 15887 public: 15888 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 15889 ~ExitFunctionBodyRAII() { 15890 if (!IsLambda) 15891 S.PopExpressionEvaluationContext(); 15892 } 15893 15894 private: 15895 Sema &S; 15896 bool IsLambda = false; 15897 }; 15898 15899 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 15900 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 15901 15902 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 15903 if (auto It = EscapeInfo.find(BD); It != EscapeInfo.end()) 15904 return It->second; 15905 15906 bool R = false; 15907 const BlockDecl *CurBD = BD; 15908 15909 do { 15910 R = !CurBD->doesNotEscape(); 15911 if (R) 15912 break; 15913 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 15914 } while (CurBD); 15915 15916 return EscapeInfo[BD] = R; 15917 }; 15918 15919 // If the location where 'self' is implicitly retained is inside a escaping 15920 // block, emit a diagnostic. 15921 for (const std::pair<SourceLocation, const BlockDecl *> &P : 15922 S.ImplicitlyRetainedSelfLocs) 15923 if (IsOrNestedInEscapingBlock(P.second)) 15924 S.Diag(P.first, diag::warn_implicitly_retains_self) 15925 << FixItHint::CreateInsertion(P.first, "self->"); 15926 } 15927 15928 static bool methodHasName(const FunctionDecl *FD, StringRef Name) { 15929 return isa<CXXMethodDecl>(FD) && FD->param_empty() && 15930 FD->getDeclName().isIdentifier() && FD->getName() == Name; 15931 } 15932 15933 bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) { 15934 return methodHasName(FD, "get_return_object"); 15935 } 15936 15937 bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) { 15938 return FD->isStatic() && 15939 methodHasName(FD, "get_return_object_on_allocation_failure"); 15940 } 15941 15942 void Sema::CheckCoroutineWrapper(FunctionDecl *FD) { 15943 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl(); 15944 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>()) 15945 return; 15946 // Allow some_promise_type::get_return_object(). 15947 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD)) 15948 return; 15949 if (!FD->hasAttr<CoroWrapperAttr>()) 15950 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD; 15951 } 15952 15953 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 15954 bool IsInstantiation) { 15955 FunctionScopeInfo *FSI = getCurFunction(); 15956 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 15957 15958 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 15959 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 15960 15961 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15962 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 15963 15964 // If we skip function body, we can't tell if a function is a coroutine. 15965 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) { 15966 if (FSI->isCoroutine()) 15967 CheckCompletedCoroutineBody(FD, Body); 15968 else 15969 CheckCoroutineWrapper(FD); 15970 } 15971 15972 // Diagnose invalid SYCL kernel entry point function declarations 15973 // and build SYCLKernelCallStmts for valid ones. 15974 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) { 15975 SYCLKernelEntryPointAttr *SKEPAttr = 15976 FD->getAttr<SYCLKernelEntryPointAttr>(); 15977 if (FD->isDefaulted()) { 15978 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid) 15979 << /*defaulted function*/ 3; 15980 SKEPAttr->setInvalidAttr(); 15981 } else if (FD->isDeleted()) { 15982 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid) 15983 << /*deleted function*/ 2; 15984 SKEPAttr->setInvalidAttr(); 15985 } else if (FSI->isCoroutine()) { 15986 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid) 15987 << /*coroutine*/ 7; 15988 SKEPAttr->setInvalidAttr(); 15989 } else if (Body && isa<CXXTryStmt>(Body)) { 15990 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid) 15991 << /*function defined with a function try block*/ 8; 15992 SKEPAttr->setInvalidAttr(); 15993 } 15994 15995 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) { 15996 StmtResult SR = 15997 SYCL().BuildSYCLKernelCallStmt(FD, cast<CompoundStmt>(Body)); 15998 if (SR.isInvalid()) 15999 return nullptr; 16000 Body = SR.get(); 16001 } 16002 } 16003 16004 { 16005 // Do not call PopExpressionEvaluationContext() if it is a lambda because 16006 // one is already popped when finishing the lambda in BuildLambdaExpr(). 16007 // This is meant to pop the context added in ActOnStartOfFunctionDef(). 16008 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 16009 if (FD) { 16010 // If this is called by Parser::ParseFunctionDefinition() after marking 16011 // the declaration as deleted, and if the deleted-function-body contains 16012 // a message (C++26), then a DefaultedOrDeletedInfo will have already been 16013 // added to store that message; do not overwrite it in that case. 16014 // 16015 // Since this would always set the body to 'nullptr' in that case anyway, 16016 // which is already done when the function decl is initially created, 16017 // always skipping this irrespective of whether there is a delete message 16018 // should not be a problem. 16019 if (!FD->isDeletedAsWritten()) 16020 FD->setBody(Body); 16021 FD->setWillHaveBody(false); 16022 16023 if (getLangOpts().CPlusPlus14) { 16024 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 16025 FD->getReturnType()->isUndeducedType()) { 16026 // For a function with a deduced result type to return void, 16027 // the result type as written must be 'auto' or 'decltype(auto)', 16028 // possibly cv-qualified or constrained, but not ref-qualified. 16029 if (!FD->getReturnType()->getAs<AutoType>()) { 16030 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 16031 << FD->getReturnType(); 16032 FD->setInvalidDecl(); 16033 } else { 16034 // Falling off the end of the function is the same as 'return;'. 16035 Expr *Dummy = nullptr; 16036 if (DeduceFunctionTypeFromReturnExpr( 16037 FD, dcl->getLocation(), Dummy, 16038 FD->getReturnType()->getAs<AutoType>())) 16039 FD->setInvalidDecl(); 16040 } 16041 } 16042 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) { 16043 // In C++11, we don't use 'auto' deduction rules for lambda call 16044 // operators because we don't support return type deduction. 16045 auto *LSI = getCurLambda(); 16046 if (LSI->HasImplicitReturnType) { 16047 deduceClosureReturnType(*LSI); 16048 16049 // C++11 [expr.prim.lambda]p4: 16050 // [...] if there are no return statements in the compound-statement 16051 // [the deduced type is] the type void 16052 QualType RetType = 16053 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 16054 16055 // Update the return type to the deduced type. 16056 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 16057 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 16058 Proto->getExtProtoInfo())); 16059 } 16060 } 16061 16062 // If the function implicitly returns zero (like 'main') or is naked, 16063 // don't complain about missing return statements. 16064 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 16065 WP.disableCheckFallThrough(); 16066 16067 // MSVC permits the use of pure specifier (=0) on function definition, 16068 // defined at class scope, warn about this non-standard construct. 16069 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() && 16070 !FD->isOutOfLine()) 16071 Diag(FD->getLocation(), diag::ext_pure_function_definition); 16072 16073 if (!FD->isInvalidDecl()) { 16074 // Don't diagnose unused parameters of defaulted, deleted or naked 16075 // functions. 16076 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() && 16077 !FD->hasAttr<NakedAttr>()) 16078 DiagnoseUnusedParameters(FD->parameters()); 16079 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 16080 FD->getReturnType(), FD); 16081 16082 // If this is a structor, we need a vtable. 16083 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 16084 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 16085 else if (CXXDestructorDecl *Destructor = 16086 dyn_cast<CXXDestructorDecl>(FD)) 16087 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 16088 16089 // Try to apply the named return value optimization. We have to check 16090 // if we can do this here because lambdas keep return statements around 16091 // to deduce an implicit return type. 16092 if (FD->getReturnType()->isRecordType() && 16093 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 16094 computeNRVO(Body, FSI); 16095 } 16096 16097 // GNU warning -Wmissing-prototypes: 16098 // Warn if a global function is defined without a previous 16099 // prototype declaration. This warning is issued even if the 16100 // definition itself provides a prototype. The aim is to detect 16101 // global functions that fail to be declared in header files. 16102 const FunctionDecl *PossiblePrototype = nullptr; 16103 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 16104 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 16105 16106 if (PossiblePrototype) { 16107 // We found a declaration that is not a prototype, 16108 // but that could be a zero-parameter prototype 16109 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 16110 TypeLoc TL = TI->getTypeLoc(); 16111 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 16112 Diag(PossiblePrototype->getLocation(), 16113 diag::note_declaration_not_a_prototype) 16114 << (FD->getNumParams() != 0) 16115 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( 16116 FTL.getRParenLoc(), "void") 16117 : FixItHint{}); 16118 } 16119 } else { 16120 // Returns true if the token beginning at this Loc is `const`. 16121 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 16122 const LangOptions &LangOpts) { 16123 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 16124 if (LocInfo.first.isInvalid()) 16125 return false; 16126 16127 bool Invalid = false; 16128 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 16129 if (Invalid) 16130 return false; 16131 16132 if (LocInfo.second > Buffer.size()) 16133 return false; 16134 16135 const char *LexStart = Buffer.data() + LocInfo.second; 16136 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 16137 16138 return StartTok.consume_front("const") && 16139 (StartTok.empty() || isWhitespace(StartTok[0]) || 16140 StartTok.starts_with("/*") || StartTok.starts_with("//")); 16141 }; 16142 16143 auto findBeginLoc = [&]() { 16144 // If the return type has `const` qualifier, we want to insert 16145 // `static` before `const` (and not before the typename). 16146 if ((FD->getReturnType()->isAnyPointerType() && 16147 FD->getReturnType()->getPointeeType().isConstQualified()) || 16148 FD->getReturnType().isConstQualified()) { 16149 // But only do this if we can determine where the `const` is. 16150 16151 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 16152 getLangOpts())) 16153 16154 return FD->getBeginLoc(); 16155 } 16156 return FD->getTypeSpecStartLoc(); 16157 }; 16158 Diag(FD->getTypeSpecStartLoc(), 16159 diag::note_static_for_internal_linkage) 16160 << /* function */ 1 16161 << (FD->getStorageClass() == SC_None 16162 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 16163 : FixItHint{}); 16164 } 16165 } 16166 16167 // We might not have found a prototype because we didn't wish to warn on 16168 // the lack of a missing prototype. Try again without the checks for 16169 // whether we want to warn on the missing prototype. 16170 if (!PossiblePrototype) 16171 (void)FindPossiblePrototype(FD, PossiblePrototype); 16172 16173 // If the function being defined does not have a prototype, then we may 16174 // need to diagnose it as changing behavior in C23 because we now know 16175 // whether the function accepts arguments or not. This only handles the 16176 // case where the definition has no prototype but does have parameters 16177 // and either there is no previous potential prototype, or the previous 16178 // potential prototype also has no actual prototype. This handles cases 16179 // like: 16180 // void f(); void f(a) int a; {} 16181 // void g(a) int a; {} 16182 // See MergeFunctionDecl() for other cases of the behavior change 16183 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 16184 // type without a prototype. 16185 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 && 16186 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() && 16187 !PossiblePrototype->isImplicit()))) { 16188 // The function definition has parameters, so this will change behavior 16189 // in C23. If there is a possible prototype, it comes before the 16190 // function definition. 16191 // FIXME: The declaration may have already been diagnosed as being 16192 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but 16193 // there's no way to test for the "changes behavior" condition in 16194 // SemaType.cpp when forming the declaration's function type. So, we do 16195 // this awkward dance instead. 16196 // 16197 // If we have a possible prototype and it declares a function with a 16198 // prototype, we don't want to diagnose it; if we have a possible 16199 // prototype and it has no prototype, it may have already been 16200 // diagnosed in SemaType.cpp as deprecated depending on whether 16201 // -Wstrict-prototypes is enabled. If we already warned about it being 16202 // deprecated, add a note that it also changes behavior. If we didn't 16203 // warn about it being deprecated (because the diagnostic is not 16204 // enabled), warn now that it is deprecated and changes behavior. 16205 16206 // This K&R C function definition definitely changes behavior in C23, 16207 // so diagnose it. 16208 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior) 16209 << /*definition*/ 1 << /* not supported in C23 */ 0; 16210 16211 // If we have a possible prototype for the function which is a user- 16212 // visible declaration, we already tested that it has no prototype. 16213 // This will change behavior in C23. This gets a warning rather than a 16214 // note because it's the same behavior-changing problem as with the 16215 // definition. 16216 if (PossiblePrototype) 16217 Diag(PossiblePrototype->getLocation(), 16218 diag::warn_non_prototype_changes_behavior) 16219 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1 16220 << /*definition*/ 1; 16221 } 16222 16223 // Warn on CPUDispatch with an actual body. 16224 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 16225 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 16226 if (!CmpndBody->body_empty()) 16227 Diag(CmpndBody->body_front()->getBeginLoc(), 16228 diag::warn_dispatch_body_ignored); 16229 16230 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 16231 const CXXMethodDecl *KeyFunction; 16232 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 16233 MD->isVirtual() && 16234 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 16235 MD == KeyFunction->getCanonicalDecl()) { 16236 // Update the key-function state if necessary for this ABI. 16237 if (FD->isInlined() && 16238 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 16239 Context.setNonKeyFunction(MD); 16240 16241 // If the newly-chosen key function is already defined, then we 16242 // need to mark the vtable as used retroactively. 16243 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 16244 const FunctionDecl *Definition; 16245 if (KeyFunction && KeyFunction->isDefined(Definition)) 16246 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 16247 } else { 16248 // We just defined they key function; mark the vtable as used. 16249 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 16250 } 16251 } 16252 } 16253 16254 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) && 16255 "Function parsing confused"); 16256 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 16257 assert(MD == getCurMethodDecl() && "Method parsing confused"); 16258 MD->setBody(Body); 16259 if (!MD->isInvalidDecl()) { 16260 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 16261 MD->getReturnType(), MD); 16262 16263 if (Body) 16264 computeNRVO(Body, FSI); 16265 } 16266 if (FSI->ObjCShouldCallSuper) { 16267 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 16268 << MD->getSelector().getAsString(); 16269 FSI->ObjCShouldCallSuper = false; 16270 } 16271 if (FSI->ObjCWarnForNoDesignatedInitChain) { 16272 const ObjCMethodDecl *InitMethod = nullptr; 16273 bool isDesignated = 16274 MD->isDesignatedInitializerForTheInterface(&InitMethod); 16275 assert(isDesignated && InitMethod); 16276 (void)isDesignated; 16277 16278 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 16279 auto IFace = MD->getClassInterface(); 16280 if (!IFace) 16281 return false; 16282 auto SuperD = IFace->getSuperClass(); 16283 if (!SuperD) 16284 return false; 16285 return SuperD->getIdentifier() == 16286 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 16287 }; 16288 // Don't issue this warning for unavailable inits or direct subclasses 16289 // of NSObject. 16290 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 16291 Diag(MD->getLocation(), 16292 diag::warn_objc_designated_init_missing_super_call); 16293 Diag(InitMethod->getLocation(), 16294 diag::note_objc_designated_init_marked_here); 16295 } 16296 FSI->ObjCWarnForNoDesignatedInitChain = false; 16297 } 16298 if (FSI->ObjCWarnForNoInitDelegation) { 16299 // Don't issue this warning for unavailable inits. 16300 if (!MD->isUnavailable()) 16301 Diag(MD->getLocation(), 16302 diag::warn_objc_secondary_init_missing_init_call); 16303 FSI->ObjCWarnForNoInitDelegation = false; 16304 } 16305 16306 diagnoseImplicitlyRetainedSelf(*this); 16307 } else { 16308 // Parsing the function declaration failed in some way. Pop the fake scope 16309 // we pushed on. 16310 PopFunctionScopeInfo(ActivePolicy, dcl); 16311 return nullptr; 16312 } 16313 16314 if (Body && FSI->HasPotentialAvailabilityViolations) 16315 DiagnoseUnguardedAvailabilityViolations(dcl); 16316 16317 assert(!FSI->ObjCShouldCallSuper && 16318 "This should only be set for ObjC methods, which should have been " 16319 "handled in the block above."); 16320 16321 // Verify and clean out per-function state. 16322 if (Body && (!FD || !FD->isDefaulted())) { 16323 // C++ constructors that have function-try-blocks can't have return 16324 // statements in the handlers of that block. (C++ [except.handle]p14) 16325 // Verify this. 16326 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 16327 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 16328 16329 // Verify that gotos and switch cases don't jump into scopes illegally. 16330 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) 16331 DiagnoseInvalidJumps(Body); 16332 16333 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 16334 if (!Destructor->getParent()->isDependentType()) 16335 CheckDestructor(Destructor); 16336 16337 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 16338 Destructor->getParent()); 16339 } 16340 16341 // If any errors have occurred, clear out any temporaries that may have 16342 // been leftover. This ensures that these temporaries won't be picked up 16343 // for deletion in some later function. 16344 if (hasUncompilableErrorOccurred() || 16345 hasAnyUnrecoverableErrorsInThisFunction() || 16346 getDiagnostics().getSuppressAllDiagnostics()) { 16347 DiscardCleanupsInEvaluationContext(); 16348 } 16349 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { 16350 // Since the body is valid, issue any analysis-based warnings that are 16351 // enabled. 16352 ActivePolicy = &WP; 16353 } 16354 16355 if (!IsInstantiation && FD && 16356 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) && 16357 !FD->isInvalidDecl() && 16358 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 16359 FD->setInvalidDecl(); 16360 16361 if (FD && FD->hasAttr<NakedAttr>()) { 16362 for (const Stmt *S : Body->children()) { 16363 // Allow local register variables without initializer as they don't 16364 // require prologue. 16365 bool RegisterVariables = false; 16366 if (auto *DS = dyn_cast<DeclStmt>(S)) { 16367 for (const auto *Decl : DS->decls()) { 16368 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 16369 RegisterVariables = 16370 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 16371 if (!RegisterVariables) 16372 break; 16373 } 16374 } 16375 } 16376 if (RegisterVariables) 16377 continue; 16378 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 16379 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 16380 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 16381 FD->setInvalidDecl(); 16382 break; 16383 } 16384 } 16385 } 16386 16387 assert(ExprCleanupObjects.size() == 16388 ExprEvalContexts.back().NumCleanupObjects && 16389 "Leftover temporaries in function"); 16390 assert(!Cleanup.exprNeedsCleanups() && 16391 "Unaccounted cleanups in function"); 16392 assert(MaybeODRUseExprs.empty() && 16393 "Leftover expressions for odr-use checking"); 16394 } 16395 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop 16396 // the declaration context below. Otherwise, we're unable to transform 16397 // 'this' expressions when transforming immediate context functions. 16398 16399 if (FD) 16400 CheckImmediateEscalatingFunctionDefinition(FD, getCurFunction()); 16401 16402 if (!IsInstantiation) 16403 PopDeclContext(); 16404 16405 PopFunctionScopeInfo(ActivePolicy, dcl); 16406 // If any errors have occurred, clear out any temporaries that may have 16407 // been leftover. This ensures that these temporaries won't be picked up for 16408 // deletion in some later function. 16409 if (hasUncompilableErrorOccurred()) { 16410 DiscardCleanupsInEvaluationContext(); 16411 } 16412 16413 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice || 16414 !LangOpts.OMPTargetTriples.empty())) || 16415 LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 16416 auto ES = getEmissionStatus(FD); 16417 if (ES == Sema::FunctionEmissionStatus::Emitted || 16418 ES == Sema::FunctionEmissionStatus::Unknown) 16419 DeclsToCheckForDeferredDiags.insert(FD); 16420 } 16421 16422 if (FD && !FD->isDeleted()) 16423 checkTypeSupport(FD->getType(), FD->getLocation(), FD); 16424 16425 return dcl; 16426 } 16427 16428 /// When we finish delayed parsing of an attribute, we must attach it to the 16429 /// relevant Decl. 16430 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 16431 ParsedAttributes &Attrs) { 16432 // Always attach attributes to the underlying decl. 16433 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 16434 D = TD->getTemplatedDecl(); 16435 ProcessDeclAttributeList(S, D, Attrs); 16436 ProcessAPINotes(D); 16437 16438 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 16439 if (Method->isStatic()) 16440 checkThisInStaticMemberFunctionAttributes(Method); 16441 } 16442 16443 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 16444 IdentifierInfo &II, Scope *S) { 16445 // It is not valid to implicitly define a function in C23. 16446 assert(LangOpts.implicitFunctionsAllowed() && 16447 "Implicit function declarations aren't allowed in this language mode"); 16448 16449 // Find the scope in which the identifier is injected and the corresponding 16450 // DeclContext. 16451 // FIXME: C89 does not say what happens if there is no enclosing block scope. 16452 // In that case, we inject the declaration into the translation unit scope 16453 // instead. 16454 Scope *BlockScope = S; 16455 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 16456 BlockScope = BlockScope->getParent(); 16457 16458 // Loop until we find a DeclContext that is either a function/method or the 16459 // translation unit, which are the only two valid places to implicitly define 16460 // a function. This avoids accidentally defining the function within a tag 16461 // declaration, for example. 16462 Scope *ContextScope = BlockScope; 16463 while (!ContextScope->getEntity() || 16464 (!ContextScope->getEntity()->isFunctionOrMethod() && 16465 !ContextScope->getEntity()->isTranslationUnit())) 16466 ContextScope = ContextScope->getParent(); 16467 ContextRAII SavedContext(*this, ContextScope->getEntity()); 16468 16469 // Before we produce a declaration for an implicitly defined 16470 // function, see whether there was a locally-scoped declaration of 16471 // this name as a function or variable. If so, use that 16472 // (non-visible) declaration, and complain about it. 16473 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 16474 if (ExternCPrev) { 16475 // We still need to inject the function into the enclosing block scope so 16476 // that later (non-call) uses can see it. 16477 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 16478 16479 // C89 footnote 38: 16480 // If in fact it is not defined as having type "function returning int", 16481 // the behavior is undefined. 16482 if (!isa<FunctionDecl>(ExternCPrev) || 16483 !Context.typesAreCompatible( 16484 cast<FunctionDecl>(ExternCPrev)->getType(), 16485 Context.getFunctionNoProtoType(Context.IntTy))) { 16486 Diag(Loc, diag::ext_use_out_of_scope_declaration) 16487 << ExternCPrev << !getLangOpts().C99; 16488 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 16489 return ExternCPrev; 16490 } 16491 } 16492 16493 // Extension in C99 (defaults to error). Legal in C89, but warn about it. 16494 unsigned diag_id; 16495 if (II.getName().starts_with("__builtin_")) 16496 diag_id = diag::warn_builtin_unknown; 16497 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 16498 else if (getLangOpts().C99) 16499 diag_id = diag::ext_implicit_function_decl_c99; 16500 else 16501 diag_id = diag::warn_implicit_function_decl; 16502 16503 TypoCorrection Corrected; 16504 // Because typo correction is expensive, only do it if the implicit 16505 // function declaration is going to be treated as an error. 16506 // 16507 // Perform the correction before issuing the main diagnostic, as some 16508 // consumers use typo-correction callbacks to enhance the main diagnostic. 16509 if (S && !ExternCPrev && 16510 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) { 16511 DeclFilterCCC<FunctionDecl> CCC{}; 16512 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 16513 S, nullptr, CCC, CTK_NonError); 16514 } 16515 16516 Diag(Loc, diag_id) << &II; 16517 if (Corrected) { 16518 // If the correction is going to suggest an implicitly defined function, 16519 // skip the correction as not being a particularly good idea. 16520 bool Diagnose = true; 16521 if (const auto *D = Corrected.getCorrectionDecl()) 16522 Diagnose = !D->isImplicit(); 16523 if (Diagnose) 16524 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 16525 /*ErrorRecovery*/ false); 16526 } 16527 16528 // If we found a prior declaration of this function, don't bother building 16529 // another one. We've already pushed that one into scope, so there's nothing 16530 // more to do. 16531 if (ExternCPrev) 16532 return ExternCPrev; 16533 16534 // Set a Declarator for the implicit definition: int foo(); 16535 const char *Dummy; 16536 AttributeFactory attrFactory; 16537 DeclSpec DS(attrFactory); 16538 unsigned DiagID; 16539 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 16540 Context.getPrintingPolicy()); 16541 (void)Error; // Silence warning. 16542 assert(!Error && "Error setting up implicit decl!"); 16543 SourceLocation NoLoc; 16544 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block); 16545 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 16546 /*IsAmbiguous=*/false, 16547 /*LParenLoc=*/NoLoc, 16548 /*Params=*/nullptr, 16549 /*NumParams=*/0, 16550 /*EllipsisLoc=*/NoLoc, 16551 /*RParenLoc=*/NoLoc, 16552 /*RefQualifierIsLvalueRef=*/true, 16553 /*RefQualifierLoc=*/NoLoc, 16554 /*MutableLoc=*/NoLoc, EST_None, 16555 /*ESpecRange=*/SourceRange(), 16556 /*Exceptions=*/nullptr, 16557 /*ExceptionRanges=*/nullptr, 16558 /*NumExceptions=*/0, 16559 /*NoexceptExpr=*/nullptr, 16560 /*ExceptionSpecTokens=*/nullptr, 16561 /*DeclsInPrototype=*/{}, Loc, Loc, 16562 D), 16563 std::move(DS.getAttributes()), SourceLocation()); 16564 D.SetIdentifier(&II, Loc); 16565 16566 // Insert this function into the enclosing block scope. 16567 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 16568 FD->setImplicit(); 16569 16570 AddKnownFunctionAttributes(FD); 16571 16572 return FD; 16573 } 16574 16575 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 16576 FunctionDecl *FD) { 16577 if (FD->isInvalidDecl()) 16578 return; 16579 16580 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 16581 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 16582 return; 16583 16584 std::optional<unsigned> AlignmentParam; 16585 bool IsNothrow = false; 16586 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 16587 return; 16588 16589 // C++2a [basic.stc.dynamic.allocation]p4: 16590 // An allocation function that has a non-throwing exception specification 16591 // indicates failure by returning a null pointer value. Any other allocation 16592 // function never returns a null pointer value and indicates failure only by 16593 // throwing an exception [...] 16594 // 16595 // However, -fcheck-new invalidates this possible assumption, so don't add 16596 // NonNull when that is enabled. 16597 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() && 16598 !getLangOpts().CheckNew) 16599 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 16600 16601 // C++2a [basic.stc.dynamic.allocation]p2: 16602 // An allocation function attempts to allocate the requested amount of 16603 // storage. [...] If the request succeeds, the value returned by a 16604 // replaceable allocation function is a [...] pointer value p0 different 16605 // from any previously returned value p1 [...] 16606 // 16607 // However, this particular information is being added in codegen, 16608 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 16609 16610 // C++2a [basic.stc.dynamic.allocation]p2: 16611 // An allocation function attempts to allocate the requested amount of 16612 // storage. If it is successful, it returns the address of the start of a 16613 // block of storage whose length in bytes is at least as large as the 16614 // requested size. 16615 if (!FD->hasAttr<AllocSizeAttr>()) { 16616 FD->addAttr(AllocSizeAttr::CreateImplicit( 16617 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 16618 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 16619 } 16620 16621 // C++2a [basic.stc.dynamic.allocation]p3: 16622 // For an allocation function [...], the pointer returned on a successful 16623 // call shall represent the address of storage that is aligned as follows: 16624 // (3.1) If the allocation function takes an argument of type 16625 // std::align_val_t, the storage will have the alignment 16626 // specified by the value of this argument. 16627 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) { 16628 FD->addAttr(AllocAlignAttr::CreateImplicit( 16629 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation())); 16630 } 16631 16632 // FIXME: 16633 // C++2a [basic.stc.dynamic.allocation]p3: 16634 // For an allocation function [...], the pointer returned on a successful 16635 // call shall represent the address of storage that is aligned as follows: 16636 // (3.2) Otherwise, if the allocation function is named operator new[], 16637 // the storage is aligned for any object that does not have 16638 // new-extended alignment ([basic.align]) and is no larger than the 16639 // requested size. 16640 // (3.3) Otherwise, the storage is aligned for any object that does not 16641 // have new-extended alignment and is of the requested size. 16642 } 16643 16644 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 16645 if (FD->isInvalidDecl()) 16646 return; 16647 16648 // If this is a built-in function, map its builtin attributes to 16649 // actual attributes. 16650 if (unsigned BuiltinID = FD->getBuiltinID()) { 16651 // Handle printf-formatting attributes. 16652 unsigned FormatIdx; 16653 bool HasVAListArg; 16654 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 16655 if (!FD->hasAttr<FormatAttr>()) { 16656 const char *fmt = "printf"; 16657 unsigned int NumParams = FD->getNumParams(); 16658 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 16659 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 16660 fmt = "NSString"; 16661 FD->addAttr(FormatAttr::CreateImplicit(Context, 16662 &Context.Idents.get(fmt), 16663 FormatIdx+1, 16664 HasVAListArg ? 0 : FormatIdx+2, 16665 FD->getLocation())); 16666 } 16667 } 16668 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 16669 HasVAListArg)) { 16670 if (!FD->hasAttr<FormatAttr>()) 16671 FD->addAttr(FormatAttr::CreateImplicit(Context, 16672 &Context.Idents.get("scanf"), 16673 FormatIdx+1, 16674 HasVAListArg ? 0 : FormatIdx+2, 16675 FD->getLocation())); 16676 } 16677 16678 // Handle automatically recognized callbacks. 16679 SmallVector<int, 4> Encoding; 16680 if (!FD->hasAttr<CallbackAttr>() && 16681 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 16682 FD->addAttr(CallbackAttr::CreateImplicit( 16683 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 16684 16685 // Mark const if we don't care about errno and/or floating point exceptions 16686 // that are the only thing preventing the function from being const. This 16687 // allows IRgen to use LLVM intrinsics for such functions. 16688 bool NoExceptions = 16689 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore; 16690 bool ConstWithoutErrnoAndExceptions = 16691 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID); 16692 bool ConstWithoutExceptions = 16693 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID); 16694 if (!FD->hasAttr<ConstAttr>() && 16695 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) && 16696 (!ConstWithoutErrnoAndExceptions || 16697 (!getLangOpts().MathErrno && NoExceptions)) && 16698 (!ConstWithoutExceptions || NoExceptions)) 16699 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 16700 16701 // We make "fma" on GNU or Windows const because we know it does not set 16702 // errno in those environments even though it could set errno based on the 16703 // C standard. 16704 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 16705 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) && 16706 !FD->hasAttr<ConstAttr>()) { 16707 switch (BuiltinID) { 16708 case Builtin::BI__builtin_fma: 16709 case Builtin::BI__builtin_fmaf: 16710 case Builtin::BI__builtin_fmal: 16711 case Builtin::BIfma: 16712 case Builtin::BIfmaf: 16713 case Builtin::BIfmal: 16714 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 16715 break; 16716 default: 16717 break; 16718 } 16719 } 16720 16721 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 16722 !FD->hasAttr<ReturnsTwiceAttr>()) 16723 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 16724 FD->getLocation())); 16725 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 16726 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 16727 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 16728 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 16729 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 16730 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 16731 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 16732 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 16733 // Add the appropriate attribute, depending on the CUDA compilation mode 16734 // and which target the builtin belongs to. For example, during host 16735 // compilation, aux builtins are __device__, while the rest are __host__. 16736 if (getLangOpts().CUDAIsDevice != 16737 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 16738 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 16739 else 16740 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 16741 } 16742 16743 // Add known guaranteed alignment for allocation functions. 16744 switch (BuiltinID) { 16745 case Builtin::BImemalign: 16746 case Builtin::BIaligned_alloc: 16747 if (!FD->hasAttr<AllocAlignAttr>()) 16748 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 16749 FD->getLocation())); 16750 break; 16751 default: 16752 break; 16753 } 16754 16755 // Add allocsize attribute for allocation functions. 16756 switch (BuiltinID) { 16757 case Builtin::BIcalloc: 16758 FD->addAttr(AllocSizeAttr::CreateImplicit( 16759 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation())); 16760 break; 16761 case Builtin::BImemalign: 16762 case Builtin::BIaligned_alloc: 16763 case Builtin::BIrealloc: 16764 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD), 16765 ParamIdx(), FD->getLocation())); 16766 break; 16767 case Builtin::BImalloc: 16768 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD), 16769 ParamIdx(), FD->getLocation())); 16770 break; 16771 default: 16772 break; 16773 } 16774 } 16775 16776 LazyProcessLifetimeCaptureByParams(FD); 16777 inferLifetimeBoundAttribute(FD); 16778 inferLifetimeCaptureByAttribute(FD); 16779 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 16780 16781 // If C++ exceptions are enabled but we are told extern "C" functions cannot 16782 // throw, add an implicit nothrow attribute to any extern "C" function we come 16783 // across. 16784 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 16785 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 16786 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 16787 if (!FPT || FPT->getExceptionSpecType() == EST_None) 16788 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 16789 } 16790 16791 IdentifierInfo *Name = FD->getIdentifier(); 16792 if (!Name) 16793 return; 16794 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) || 16795 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 16796 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 16797 LinkageSpecLanguageIDs::C)) { 16798 // Okay: this could be a libc/libm/Objective-C function we know 16799 // about. 16800 } else 16801 return; 16802 16803 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 16804 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 16805 // target-specific builtins, perhaps? 16806 if (!FD->hasAttr<FormatAttr>()) 16807 FD->addAttr(FormatAttr::CreateImplicit(Context, 16808 &Context.Idents.get("printf"), 2, 16809 Name->isStr("vasprintf") ? 0 : 3, 16810 FD->getLocation())); 16811 } 16812 16813 if (Name->isStr("__CFStringMakeConstantString")) { 16814 // We already have a __builtin___CFStringMakeConstantString, 16815 // but builds that use -fno-constant-cfstrings don't go through that. 16816 if (!FD->hasAttr<FormatArgAttr>()) 16817 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 16818 FD->getLocation())); 16819 } 16820 } 16821 16822 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 16823 TypeSourceInfo *TInfo) { 16824 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 16825 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 16826 16827 if (!TInfo) { 16828 assert(D.isInvalidType() && "no declarator info for valid type"); 16829 TInfo = Context.getTrivialTypeSourceInfo(T); 16830 } 16831 16832 // Scope manipulation handled by caller. 16833 TypedefDecl *NewTD = 16834 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 16835 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 16836 16837 // Bail out immediately if we have an invalid declaration. 16838 if (D.isInvalidType()) { 16839 NewTD->setInvalidDecl(); 16840 return NewTD; 16841 } 16842 16843 if (D.getDeclSpec().isModulePrivateSpecified()) { 16844 if (CurContext->isFunctionOrMethod()) 16845 Diag(NewTD->getLocation(), diag::err_module_private_local) 16846 << 2 << NewTD 16847 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 16848 << FixItHint::CreateRemoval( 16849 D.getDeclSpec().getModulePrivateSpecLoc()); 16850 else 16851 NewTD->setModulePrivate(); 16852 } 16853 16854 // C++ [dcl.typedef]p8: 16855 // If the typedef declaration defines an unnamed class (or 16856 // enum), the first typedef-name declared by the declaration 16857 // to be that class type (or enum type) is used to denote the 16858 // class type (or enum type) for linkage purposes only. 16859 // We need to check whether the type was declared in the declaration. 16860 switch (D.getDeclSpec().getTypeSpecType()) { 16861 case TST_enum: 16862 case TST_struct: 16863 case TST_interface: 16864 case TST_union: 16865 case TST_class: { 16866 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 16867 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 16868 break; 16869 } 16870 16871 default: 16872 break; 16873 } 16874 16875 return NewTD; 16876 } 16877 16878 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 16879 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 16880 QualType T = TI->getType(); 16881 16882 if (T->isDependentType()) 16883 return false; 16884 16885 // This doesn't use 'isIntegralType' despite the error message mentioning 16886 // integral type because isIntegralType would also allow enum types in C. 16887 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 16888 if (BT->isInteger()) 16889 return false; 16890 16891 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) 16892 << T << T->isBitIntType(); 16893 } 16894 16895 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 16896 QualType EnumUnderlyingTy, bool IsFixed, 16897 const EnumDecl *Prev) { 16898 if (IsScoped != Prev->isScoped()) { 16899 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 16900 << Prev->isScoped(); 16901 Diag(Prev->getLocation(), diag::note_previous_declaration); 16902 return true; 16903 } 16904 16905 if (IsFixed && Prev->isFixed()) { 16906 if (!EnumUnderlyingTy->isDependentType() && 16907 !Prev->getIntegerType()->isDependentType() && 16908 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 16909 Prev->getIntegerType())) { 16910 // TODO: Highlight the underlying type of the redeclaration. 16911 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 16912 << EnumUnderlyingTy << Prev->getIntegerType(); 16913 Diag(Prev->getLocation(), diag::note_previous_declaration) 16914 << Prev->getIntegerTypeRange(); 16915 return true; 16916 } 16917 } else if (IsFixed != Prev->isFixed()) { 16918 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 16919 << Prev->isFixed(); 16920 Diag(Prev->getLocation(), diag::note_previous_declaration); 16921 return true; 16922 } 16923 16924 return false; 16925 } 16926 16927 /// Get diagnostic %select index for tag kind for 16928 /// redeclaration diagnostic message. 16929 /// WARNING: Indexes apply to particular diagnostics only! 16930 /// 16931 /// \returns diagnostic %select index. 16932 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 16933 switch (Tag) { 16934 case TagTypeKind::Struct: 16935 return 0; 16936 case TagTypeKind::Interface: 16937 return 1; 16938 case TagTypeKind::Class: 16939 return 2; 16940 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 16941 } 16942 } 16943 16944 /// Determine if tag kind is a class-key compatible with 16945 /// class for redeclaration (class, struct, or __interface). 16946 /// 16947 /// \returns true iff the tag kind is compatible. 16948 static bool isClassCompatTagKind(TagTypeKind Tag) 16949 { 16950 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class || 16951 Tag == TagTypeKind::Interface; 16952 } 16953 16954 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 16955 TagTypeKind TTK) { 16956 if (isa<TypedefDecl>(PrevDecl)) 16957 return NTK_Typedef; 16958 else if (isa<TypeAliasDecl>(PrevDecl)) 16959 return NTK_TypeAlias; 16960 else if (isa<ClassTemplateDecl>(PrevDecl)) 16961 return NTK_Template; 16962 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 16963 return NTK_TypeAliasTemplate; 16964 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 16965 return NTK_TemplateTemplateArgument; 16966 switch (TTK) { 16967 case TagTypeKind::Struct: 16968 case TagTypeKind::Interface: 16969 case TagTypeKind::Class: 16970 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 16971 case TagTypeKind::Union: 16972 return NTK_NonUnion; 16973 case TagTypeKind::Enum: 16974 return NTK_NonEnum; 16975 } 16976 llvm_unreachable("invalid TTK"); 16977 } 16978 16979 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 16980 TagTypeKind NewTag, bool isDefinition, 16981 SourceLocation NewTagLoc, 16982 const IdentifierInfo *Name) { 16983 // C++ [dcl.type.elab]p3: 16984 // The class-key or enum keyword present in the 16985 // elaborated-type-specifier shall agree in kind with the 16986 // declaration to which the name in the elaborated-type-specifier 16987 // refers. This rule also applies to the form of 16988 // elaborated-type-specifier that declares a class-name or 16989 // friend class since it can be construed as referring to the 16990 // definition of the class. Thus, in any 16991 // elaborated-type-specifier, the enum keyword shall be used to 16992 // refer to an enumeration (7.2), the union class-key shall be 16993 // used to refer to a union (clause 9), and either the class or 16994 // struct class-key shall be used to refer to a class (clause 9) 16995 // declared using the class or struct class-key. 16996 TagTypeKind OldTag = Previous->getTagKind(); 16997 if (OldTag != NewTag && 16998 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 16999 return false; 17000 17001 // Tags are compatible, but we might still want to warn on mismatched tags. 17002 // Non-class tags can't be mismatched at this point. 17003 if (!isClassCompatTagKind(NewTag)) 17004 return true; 17005 17006 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 17007 // by our warning analysis. We don't want to warn about mismatches with (eg) 17008 // declarations in system headers that are designed to be specialized, but if 17009 // a user asks us to warn, we should warn if their code contains mismatched 17010 // declarations. 17011 auto IsIgnoredLoc = [&](SourceLocation Loc) { 17012 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 17013 Loc); 17014 }; 17015 if (IsIgnoredLoc(NewTagLoc)) 17016 return true; 17017 17018 auto IsIgnored = [&](const TagDecl *Tag) { 17019 return IsIgnoredLoc(Tag->getLocation()); 17020 }; 17021 while (IsIgnored(Previous)) { 17022 Previous = Previous->getPreviousDecl(); 17023 if (!Previous) 17024 return true; 17025 OldTag = Previous->getTagKind(); 17026 } 17027 17028 bool isTemplate = false; 17029 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 17030 isTemplate = Record->getDescribedClassTemplate(); 17031 17032 if (inTemplateInstantiation()) { 17033 if (OldTag != NewTag) { 17034 // In a template instantiation, do not offer fix-its for tag mismatches 17035 // since they usually mess up the template instead of fixing the problem. 17036 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 17037 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 17038 << getRedeclDiagFromTagKind(OldTag); 17039 // FIXME: Note previous location? 17040 } 17041 return true; 17042 } 17043 17044 if (isDefinition) { 17045 // On definitions, check all previous tags and issue a fix-it for each 17046 // one that doesn't match the current tag. 17047 if (Previous->getDefinition()) { 17048 // Don't suggest fix-its for redefinitions. 17049 return true; 17050 } 17051 17052 bool previousMismatch = false; 17053 for (const TagDecl *I : Previous->redecls()) { 17054 if (I->getTagKind() != NewTag) { 17055 // Ignore previous declarations for which the warning was disabled. 17056 if (IsIgnored(I)) 17057 continue; 17058 17059 if (!previousMismatch) { 17060 previousMismatch = true; 17061 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 17062 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 17063 << getRedeclDiagFromTagKind(I->getTagKind()); 17064 } 17065 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 17066 << getRedeclDiagFromTagKind(NewTag) 17067 << FixItHint::CreateReplacement(I->getInnerLocStart(), 17068 TypeWithKeyword::getTagTypeKindName(NewTag)); 17069 } 17070 } 17071 return true; 17072 } 17073 17074 // Identify the prevailing tag kind: this is the kind of the definition (if 17075 // there is a non-ignored definition), or otherwise the kind of the prior 17076 // (non-ignored) declaration. 17077 const TagDecl *PrevDef = Previous->getDefinition(); 17078 if (PrevDef && IsIgnored(PrevDef)) 17079 PrevDef = nullptr; 17080 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 17081 if (Redecl->getTagKind() != NewTag) { 17082 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 17083 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 17084 << getRedeclDiagFromTagKind(OldTag); 17085 Diag(Redecl->getLocation(), diag::note_previous_use); 17086 17087 // If there is a previous definition, suggest a fix-it. 17088 if (PrevDef) { 17089 Diag(NewTagLoc, diag::note_struct_class_suggestion) 17090 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 17091 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 17092 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 17093 } 17094 } 17095 17096 return true; 17097 } 17098 17099 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 17100 /// from an outer enclosing namespace or file scope inside a friend declaration. 17101 /// This should provide the commented out code in the following snippet: 17102 /// namespace N { 17103 /// struct X; 17104 /// namespace M { 17105 /// struct Y { friend struct /*N::*/ X; }; 17106 /// } 17107 /// } 17108 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 17109 SourceLocation NameLoc) { 17110 // While the decl is in a namespace, do repeated lookup of that name and see 17111 // if we get the same namespace back. If we do not, continue until 17112 // translation unit scope, at which point we have a fully qualified NNS. 17113 SmallVector<IdentifierInfo *, 4> Namespaces; 17114 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 17115 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 17116 // This tag should be declared in a namespace, which can only be enclosed by 17117 // other namespaces. Bail if there's an anonymous namespace in the chain. 17118 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 17119 if (!Namespace || Namespace->isAnonymousNamespace()) 17120 return FixItHint(); 17121 IdentifierInfo *II = Namespace->getIdentifier(); 17122 Namespaces.push_back(II); 17123 NamedDecl *Lookup = SemaRef.LookupSingleName( 17124 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 17125 if (Lookup == Namespace) 17126 break; 17127 } 17128 17129 // Once we have all the namespaces, reverse them to go outermost first, and 17130 // build an NNS. 17131 SmallString<64> Insertion; 17132 llvm::raw_svector_ostream OS(Insertion); 17133 if (DC->isTranslationUnit()) 17134 OS << "::"; 17135 std::reverse(Namespaces.begin(), Namespaces.end()); 17136 for (auto *II : Namespaces) 17137 OS << II->getName() << "::"; 17138 return FixItHint::CreateInsertion(NameLoc, Insertion); 17139 } 17140 17141 /// Determine whether a tag originally declared in context \p OldDC can 17142 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 17143 /// found a declaration in \p OldDC as a previous decl, perhaps through a 17144 /// using-declaration). 17145 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 17146 DeclContext *NewDC) { 17147 OldDC = OldDC->getRedeclContext(); 17148 NewDC = NewDC->getRedeclContext(); 17149 17150 if (OldDC->Equals(NewDC)) 17151 return true; 17152 17153 // In MSVC mode, we allow a redeclaration if the contexts are related (either 17154 // encloses the other). 17155 if (S.getLangOpts().MSVCCompat && 17156 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 17157 return true; 17158 17159 return false; 17160 } 17161 17162 DeclResult 17163 Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 17164 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, 17165 const ParsedAttributesView &Attrs, AccessSpecifier AS, 17166 SourceLocation ModulePrivateLoc, 17167 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, 17168 bool &IsDependent, SourceLocation ScopedEnumKWLoc, 17169 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 17170 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 17171 OffsetOfKind OOK, SkipBodyInfo *SkipBody) { 17172 // If this is not a definition, it must have a name. 17173 IdentifierInfo *OrigName = Name; 17174 assert((Name != nullptr || TUK == TagUseKind::Definition) && 17175 "Nameless record must be a definition!"); 17176 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference); 17177 17178 OwnedDecl = false; 17179 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 17180 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 17181 17182 // FIXME: Check member specializations more carefully. 17183 bool isMemberSpecialization = false; 17184 bool Invalid = false; 17185 17186 // We only need to do this matching if we have template parameters 17187 // or a scope specifier, which also conveniently avoids this work 17188 // for non-C++ cases. 17189 if (TemplateParameterLists.size() > 0 || 17190 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) { 17191 TemplateParameterList *TemplateParams = 17192 MatchTemplateParametersToScopeSpecifier( 17193 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 17194 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid); 17195 17196 // C++23 [dcl.type.elab] p2: 17197 // If an elaborated-type-specifier is the sole constituent of a 17198 // declaration, the declaration is ill-formed unless it is an explicit 17199 // specialization, an explicit instantiation or it has one of the 17200 // following forms: [...] 17201 // C++23 [dcl.enum] p1: 17202 // If the enum-head-name of an opaque-enum-declaration contains a 17203 // nested-name-specifier, the declaration shall be an explicit 17204 // specialization. 17205 // 17206 // FIXME: Class template partial specializations can be forward declared 17207 // per CWG2213, but the resolution failed to allow qualified forward 17208 // declarations. This is almost certainly unintentional, so we allow them. 17209 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() && 17210 !isMemberSpecialization) 17211 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 17212 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange(); 17213 17214 if (TemplateParams) { 17215 if (Kind == TagTypeKind::Enum) { 17216 Diag(KWLoc, diag::err_enum_template); 17217 return true; 17218 } 17219 17220 if (TemplateParams->size() > 0) { 17221 // This is a declaration or definition of a class template (which may 17222 // be a member of another template). 17223 17224 if (Invalid) 17225 return true; 17226 17227 OwnedDecl = false; 17228 DeclResult Result = CheckClassTemplate( 17229 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 17230 AS, ModulePrivateLoc, 17231 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 17232 TemplateParameterLists.data(), SkipBody); 17233 return Result.get(); 17234 } else { 17235 // The "template<>" header is extraneous. 17236 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 17237 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 17238 isMemberSpecialization = true; 17239 } 17240 } 17241 17242 if (!TemplateParameterLists.empty() && isMemberSpecialization && 17243 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 17244 return true; 17245 } 17246 17247 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) { 17248 // C++23 [dcl.type.elab]p4: 17249 // If an elaborated-type-specifier appears with the friend specifier as 17250 // an entire member-declaration, the member-declaration shall have one 17251 // of the following forms: 17252 // friend class-key nested-name-specifier(opt) identifier ; 17253 // friend class-key simple-template-id ; 17254 // friend class-key nested-name-specifier template(opt) 17255 // simple-template-id ; 17256 // 17257 // Since enum is not a class-key, so declarations like "friend enum E;" 17258 // are ill-formed. Although CWG2363 reaffirms that such declarations are 17259 // invalid, most implementations accept so we issue a pedantic warning. 17260 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval( 17261 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc); 17262 assert(ScopedEnum || !ScopedEnumUsesClassTag); 17263 Diag(KWLoc, diag::note_enum_friend) 17264 << (ScopedEnum + ScopedEnumUsesClassTag); 17265 } 17266 17267 // Figure out the underlying type if this a enum declaration. We need to do 17268 // this early, because it's needed to detect if this is an incompatible 17269 // redeclaration. 17270 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 17271 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 17272 17273 if (Kind == TagTypeKind::Enum) { 17274 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 17275 // No underlying type explicitly specified, or we failed to parse the 17276 // type, default to int. 17277 EnumUnderlying = Context.IntTy.getTypePtr(); 17278 } else if (UnderlyingType.get()) { 17279 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 17280 // integral type; any cv-qualification is ignored. 17281 TypeSourceInfo *TI = nullptr; 17282 GetTypeFromParser(UnderlyingType.get(), &TI); 17283 EnumUnderlying = TI; 17284 17285 if (CheckEnumUnderlyingType(TI)) 17286 // Recover by falling back to int. 17287 EnumUnderlying = Context.IntTy.getTypePtr(); 17288 17289 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 17290 UPPC_FixedUnderlyingType)) 17291 EnumUnderlying = Context.IntTy.getTypePtr(); 17292 17293 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 17294 // For MSVC ABI compatibility, unfixed enums must use an underlying type 17295 // of 'int'. However, if this is an unfixed forward declaration, don't set 17296 // the underlying type unless the user enables -fms-compatibility. This 17297 // makes unfixed forward declared enums incomplete and is more conforming. 17298 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat) 17299 EnumUnderlying = Context.IntTy.getTypePtr(); 17300 } 17301 } 17302 17303 DeclContext *SearchDC = CurContext; 17304 DeclContext *DC = CurContext; 17305 bool isStdBadAlloc = false; 17306 bool isStdAlignValT = false; 17307 17308 RedeclarationKind Redecl = forRedeclarationInCurContext(); 17309 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) 17310 Redecl = RedeclarationKind::NotForRedeclaration; 17311 17312 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 17313 /// implemented asks for structural equivalence checking, the returned decl 17314 /// here is passed back to the parser, allowing the tag body to be parsed. 17315 auto createTagFromNewDecl = [&]() -> TagDecl * { 17316 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 17317 // If there is an identifier, use the location of the identifier as the 17318 // location of the decl, otherwise use the location of the struct/union 17319 // keyword. 17320 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 17321 TagDecl *New = nullptr; 17322 17323 if (Kind == TagTypeKind::Enum) { 17324 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 17325 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 17326 // If this is an undefined enum, bail. 17327 if (TUK != TagUseKind::Definition && !Invalid) 17328 return nullptr; 17329 if (EnumUnderlying) { 17330 EnumDecl *ED = cast<EnumDecl>(New); 17331 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying)) 17332 ED->setIntegerTypeSourceInfo(TI); 17333 else 17334 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0)); 17335 QualType EnumTy = ED->getIntegerType(); 17336 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy) 17337 ? Context.getPromotedIntegerType(EnumTy) 17338 : EnumTy); 17339 } 17340 } else { // struct/union 17341 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 17342 nullptr); 17343 } 17344 17345 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 17346 // Add alignment attributes if necessary; these attributes are checked 17347 // when the ASTContext lays out the structure. 17348 // 17349 // It is important for implementing the correct semantics that this 17350 // happen here (in ActOnTag). The #pragma pack stack is 17351 // maintained as a result of parser callbacks which can occur at 17352 // many points during the parsing of a struct declaration (because 17353 // the #pragma tokens are effectively skipped over during the 17354 // parsing of the struct). 17355 if (TUK == TagUseKind::Definition && 17356 (!SkipBody || !SkipBody->ShouldSkip)) { 17357 AddAlignmentAttributesForRecord(RD); 17358 AddMsStructLayoutForRecord(RD); 17359 } 17360 } 17361 New->setLexicalDeclContext(CurContext); 17362 return New; 17363 }; 17364 17365 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 17366 if (Name && SS.isNotEmpty()) { 17367 // We have a nested-name tag ('struct foo::bar'). 17368 17369 // Check for invalid 'foo::'. 17370 if (SS.isInvalid()) { 17371 Name = nullptr; 17372 goto CreateNewDecl; 17373 } 17374 17375 // If this is a friend or a reference to a class in a dependent 17376 // context, don't try to make a decl for it. 17377 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) { 17378 DC = computeDeclContext(SS, false); 17379 if (!DC) { 17380 IsDependent = true; 17381 return true; 17382 } 17383 } else { 17384 DC = computeDeclContext(SS, true); 17385 if (!DC) { 17386 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 17387 << SS.getRange(); 17388 return true; 17389 } 17390 } 17391 17392 if (RequireCompleteDeclContext(SS, DC)) 17393 return true; 17394 17395 SearchDC = DC; 17396 // Look-up name inside 'foo::'. 17397 LookupQualifiedName(Previous, DC); 17398 17399 if (Previous.isAmbiguous()) 17400 return true; 17401 17402 if (Previous.empty()) { 17403 // Name lookup did not find anything. However, if the 17404 // nested-name-specifier refers to the current instantiation, 17405 // and that current instantiation has any dependent base 17406 // classes, we might find something at instantiation time: treat 17407 // this as a dependent elaborated-type-specifier. 17408 // But this only makes any sense for reference-like lookups. 17409 if (Previous.wasNotFoundInCurrentInstantiation() && 17410 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) { 17411 IsDependent = true; 17412 return true; 17413 } 17414 17415 // A tag 'foo::bar' must already exist. 17416 Diag(NameLoc, diag::err_not_tag_in_scope) 17417 << llvm::to_underlying(Kind) << Name << DC << SS.getRange(); 17418 Name = nullptr; 17419 Invalid = true; 17420 goto CreateNewDecl; 17421 } 17422 } else if (Name) { 17423 // C++14 [class.mem]p14: 17424 // If T is the name of a class, then each of the following shall have a 17425 // name different from T: 17426 // -- every member of class T that is itself a type 17427 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend && 17428 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 17429 return true; 17430 17431 // If this is a named struct, check to see if there was a previous forward 17432 // declaration or definition. 17433 // FIXME: We're looking into outer scopes here, even when we 17434 // shouldn't be. Doing so can result in ambiguities that we 17435 // shouldn't be diagnosing. 17436 LookupName(Previous, S); 17437 17438 // When declaring or defining a tag, ignore ambiguities introduced 17439 // by types using'ed into this scope. 17440 if (Previous.isAmbiguous() && 17441 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) { 17442 LookupResult::Filter F = Previous.makeFilter(); 17443 while (F.hasNext()) { 17444 NamedDecl *ND = F.next(); 17445 if (!ND->getDeclContext()->getRedeclContext()->Equals( 17446 SearchDC->getRedeclContext())) 17447 F.erase(); 17448 } 17449 F.done(); 17450 } 17451 17452 // C++11 [namespace.memdef]p3: 17453 // If the name in a friend declaration is neither qualified nor 17454 // a template-id and the declaration is a function or an 17455 // elaborated-type-specifier, the lookup to determine whether 17456 // the entity has been previously declared shall not consider 17457 // any scopes outside the innermost enclosing namespace. 17458 // 17459 // MSVC doesn't implement the above rule for types, so a friend tag 17460 // declaration may be a redeclaration of a type declared in an enclosing 17461 // scope. They do implement this rule for friend functions. 17462 // 17463 // Does it matter that this should be by scope instead of by 17464 // semantic context? 17465 if (!Previous.empty() && TUK == TagUseKind::Friend) { 17466 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 17467 LookupResult::Filter F = Previous.makeFilter(); 17468 bool FriendSawTagOutsideEnclosingNamespace = false; 17469 while (F.hasNext()) { 17470 NamedDecl *ND = F.next(); 17471 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 17472 if (DC->isFileContext() && 17473 !EnclosingNS->Encloses(ND->getDeclContext())) { 17474 if (getLangOpts().MSVCCompat) 17475 FriendSawTagOutsideEnclosingNamespace = true; 17476 else 17477 F.erase(); 17478 } 17479 } 17480 F.done(); 17481 17482 // Diagnose this MSVC extension in the easy case where lookup would have 17483 // unambiguously found something outside the enclosing namespace. 17484 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 17485 NamedDecl *ND = Previous.getFoundDecl(); 17486 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 17487 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 17488 } 17489 } 17490 17491 // Note: there used to be some attempt at recovery here. 17492 if (Previous.isAmbiguous()) 17493 return true; 17494 17495 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) { 17496 // FIXME: This makes sure that we ignore the contexts associated 17497 // with C structs, unions, and enums when looking for a matching 17498 // tag declaration or definition. See the similar lookup tweak 17499 // in Sema::LookupName; is there a better way to deal with this? 17500 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC)) 17501 SearchDC = SearchDC->getParent(); 17502 } else if (getLangOpts().CPlusPlus) { 17503 // Inside ObjCContainer want to keep it as a lexical decl context but go 17504 // past it (most often to TranslationUnit) to find the semantic decl 17505 // context. 17506 while (isa<ObjCContainerDecl>(SearchDC)) 17507 SearchDC = SearchDC->getParent(); 17508 } 17509 } else if (getLangOpts().CPlusPlus) { 17510 // Don't use ObjCContainerDecl as the semantic decl context for anonymous 17511 // TagDecl the same way as we skip it for named TagDecl. 17512 while (isa<ObjCContainerDecl>(SearchDC)) 17513 SearchDC = SearchDC->getParent(); 17514 } 17515 17516 if (Previous.isSingleResult() && 17517 Previous.getFoundDecl()->isTemplateParameter()) { 17518 // Maybe we will complain about the shadowed template parameter. 17519 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 17520 // Just pretend that we didn't see the previous declaration. 17521 Previous.clear(); 17522 } 17523 17524 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 17525 DC->Equals(getStdNamespace())) { 17526 if (Name->isStr("bad_alloc")) { 17527 // This is a declaration of or a reference to "std::bad_alloc". 17528 isStdBadAlloc = true; 17529 17530 // If std::bad_alloc has been implicitly declared (but made invisible to 17531 // name lookup), fill in this implicit declaration as the previous 17532 // declaration, so that the declarations get chained appropriately. 17533 if (Previous.empty() && StdBadAlloc) 17534 Previous.addDecl(getStdBadAlloc()); 17535 } else if (Name->isStr("align_val_t")) { 17536 isStdAlignValT = true; 17537 if (Previous.empty() && StdAlignValT) 17538 Previous.addDecl(getStdAlignValT()); 17539 } 17540 } 17541 17542 // If we didn't find a previous declaration, and this is a reference 17543 // (or friend reference), move to the correct scope. In C++, we 17544 // also need to do a redeclaration lookup there, just in case 17545 // there's a shadow friend decl. 17546 if (Name && Previous.empty() && 17547 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend || 17548 IsTemplateParamOrArg)) { 17549 if (Invalid) goto CreateNewDecl; 17550 assert(SS.isEmpty()); 17551 17552 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) { 17553 // C++ [basic.scope.pdecl]p5: 17554 // -- for an elaborated-type-specifier of the form 17555 // 17556 // class-key identifier 17557 // 17558 // if the elaborated-type-specifier is used in the 17559 // decl-specifier-seq or parameter-declaration-clause of a 17560 // function defined in namespace scope, the identifier is 17561 // declared as a class-name in the namespace that contains 17562 // the declaration; otherwise, except as a friend 17563 // declaration, the identifier is declared in the smallest 17564 // non-class, non-function-prototype scope that contains the 17565 // declaration. 17566 // 17567 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 17568 // C structs and unions. 17569 // 17570 // It is an error in C++ to declare (rather than define) an enum 17571 // type, including via an elaborated type specifier. We'll 17572 // diagnose that later; for now, declare the enum in the same 17573 // scope as we would have picked for any other tag type. 17574 // 17575 // GNU C also supports this behavior as part of its incomplete 17576 // enum types extension, while GNU C++ does not. 17577 // 17578 // Find the context where we'll be declaring the tag. 17579 // FIXME: We would like to maintain the current DeclContext as the 17580 // lexical context, 17581 SearchDC = getTagInjectionContext(SearchDC); 17582 17583 // Find the scope where we'll be declaring the tag. 17584 S = getTagInjectionScope(S, getLangOpts()); 17585 } else { 17586 assert(TUK == TagUseKind::Friend); 17587 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC); 17588 17589 // C++ [namespace.memdef]p3: 17590 // If a friend declaration in a non-local class first declares a 17591 // class or function, the friend class or function is a member of 17592 // the innermost enclosing namespace. 17593 SearchDC = RD->isLocalClass() ? RD->isLocalClass() 17594 : SearchDC->getEnclosingNamespaceContext(); 17595 } 17596 17597 // In C++, we need to do a redeclaration lookup to properly 17598 // diagnose some problems. 17599 // FIXME: redeclaration lookup is also used (with and without C++) to find a 17600 // hidden declaration so that we don't get ambiguity errors when using a 17601 // type declared by an elaborated-type-specifier. In C that is not correct 17602 // and we should instead merge compatible types found by lookup. 17603 if (getLangOpts().CPlusPlus) { 17604 // FIXME: This can perform qualified lookups into function contexts, 17605 // which are meaningless. 17606 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 17607 LookupQualifiedName(Previous, SearchDC); 17608 } else { 17609 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 17610 LookupName(Previous, S); 17611 } 17612 } 17613 17614 // If we have a known previous declaration to use, then use it. 17615 if (Previous.empty() && SkipBody && SkipBody->Previous) 17616 Previous.addDecl(SkipBody->Previous); 17617 17618 if (!Previous.empty()) { 17619 NamedDecl *PrevDecl = Previous.getFoundDecl(); 17620 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 17621 17622 // It's okay to have a tag decl in the same scope as a typedef 17623 // which hides a tag decl in the same scope. Finding this 17624 // with a redeclaration lookup can only actually happen in C++. 17625 // 17626 // This is also okay for elaborated-type-specifiers, which is 17627 // technically forbidden by the current standard but which is 17628 // okay according to the likely resolution of an open issue; 17629 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 17630 if (getLangOpts().CPlusPlus) { 17631 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 17632 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 17633 TagDecl *Tag = TT->getDecl(); 17634 if (Tag->getDeclName() == Name && 17635 Tag->getDeclContext()->getRedeclContext() 17636 ->Equals(TD->getDeclContext()->getRedeclContext())) { 17637 PrevDecl = Tag; 17638 Previous.clear(); 17639 Previous.addDecl(Tag); 17640 Previous.resolveKind(); 17641 } 17642 } 17643 } 17644 } 17645 17646 // If this is a redeclaration of a using shadow declaration, it must 17647 // declare a tag in the same context. In MSVC mode, we allow a 17648 // redefinition if either context is within the other. 17649 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 17650 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 17651 if (SS.isEmpty() && TUK != TagUseKind::Reference && 17652 TUK != TagUseKind::Friend && 17653 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 17654 !(OldTag && isAcceptableTagRedeclContext( 17655 *this, OldTag->getDeclContext(), SearchDC))) { 17656 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 17657 Diag(Shadow->getTargetDecl()->getLocation(), 17658 diag::note_using_decl_target); 17659 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 17660 << 0; 17661 // Recover by ignoring the old declaration. 17662 Previous.clear(); 17663 goto CreateNewDecl; 17664 } 17665 } 17666 17667 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 17668 // If this is a use of a previous tag, or if the tag is already declared 17669 // in the same scope (so that the definition/declaration completes or 17670 // rementions the tag), reuse the decl. 17671 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend || 17672 isDeclInScope(DirectPrevDecl, SearchDC, S, 17673 SS.isNotEmpty() || isMemberSpecialization)) { 17674 // Make sure that this wasn't declared as an enum and now used as a 17675 // struct or something similar. 17676 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 17677 TUK == TagUseKind::Definition, KWLoc, 17678 Name)) { 17679 bool SafeToContinue = 17680 (PrevTagDecl->getTagKind() != TagTypeKind::Enum && 17681 Kind != TagTypeKind::Enum); 17682 if (SafeToContinue) 17683 Diag(KWLoc, diag::err_use_with_wrong_tag) 17684 << Name 17685 << FixItHint::CreateReplacement(SourceRange(KWLoc), 17686 PrevTagDecl->getKindName()); 17687 else 17688 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 17689 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 17690 17691 if (SafeToContinue) 17692 Kind = PrevTagDecl->getTagKind(); 17693 else { 17694 // Recover by making this an anonymous redefinition. 17695 Name = nullptr; 17696 Previous.clear(); 17697 Invalid = true; 17698 } 17699 } 17700 17701 if (Kind == TagTypeKind::Enum && 17702 PrevTagDecl->getTagKind() == TagTypeKind::Enum) { 17703 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 17704 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) 17705 return PrevTagDecl; 17706 17707 QualType EnumUnderlyingTy; 17708 if (TypeSourceInfo *TI = 17709 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying)) 17710 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 17711 else if (const Type *T = 17712 dyn_cast_if_present<const Type *>(EnumUnderlying)) 17713 EnumUnderlyingTy = QualType(T, 0); 17714 17715 // All conflicts with previous declarations are recovered by 17716 // returning the previous declaration, unless this is a definition, 17717 // in which case we want the caller to bail out. 17718 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 17719 ScopedEnum, EnumUnderlyingTy, 17720 IsFixed, PrevEnum)) 17721 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr; 17722 } 17723 17724 // C++11 [class.mem]p1: 17725 // A member shall not be declared twice in the member-specification, 17726 // except that a nested class or member class template can be declared 17727 // and then later defined. 17728 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() && 17729 S->isDeclScope(PrevDecl)) { 17730 Diag(NameLoc, diag::ext_member_redeclared); 17731 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 17732 } 17733 17734 if (!Invalid) { 17735 // If this is a use, just return the declaration we found, unless 17736 // we have attributes. 17737 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) { 17738 if (!Attrs.empty()) { 17739 // FIXME: Diagnose these attributes. For now, we create a new 17740 // declaration to hold them. 17741 } else if (TUK == TagUseKind::Reference && 17742 (PrevTagDecl->getFriendObjectKind() == 17743 Decl::FOK_Undeclared || 17744 PrevDecl->getOwningModule() != getCurrentModule()) && 17745 SS.isEmpty()) { 17746 // This declaration is a reference to an existing entity, but 17747 // has different visibility from that entity: it either makes 17748 // a friend visible or it makes a type visible in a new module. 17749 // In either case, create a new declaration. We only do this if 17750 // the declaration would have meant the same thing if no prior 17751 // declaration were found, that is, if it was found in the same 17752 // scope where we would have injected a declaration. 17753 if (!getTagInjectionContext(CurContext)->getRedeclContext() 17754 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 17755 return PrevTagDecl; 17756 // This is in the injected scope, create a new declaration in 17757 // that scope. 17758 S = getTagInjectionScope(S, getLangOpts()); 17759 } else { 17760 return PrevTagDecl; 17761 } 17762 } 17763 17764 // Diagnose attempts to redefine a tag. 17765 if (TUK == TagUseKind::Definition) { 17766 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 17767 // If we're defining a specialization and the previous definition 17768 // is from an implicit instantiation, don't emit an error 17769 // here; we'll catch this in the general case below. 17770 bool IsExplicitSpecializationAfterInstantiation = false; 17771 if (isMemberSpecialization) { 17772 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 17773 IsExplicitSpecializationAfterInstantiation = 17774 RD->getTemplateSpecializationKind() != 17775 TSK_ExplicitSpecialization; 17776 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 17777 IsExplicitSpecializationAfterInstantiation = 17778 ED->getTemplateSpecializationKind() != 17779 TSK_ExplicitSpecialization; 17780 } 17781 17782 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 17783 // not keep more that one definition around (merge them). However, 17784 // ensure the decl passes the structural compatibility check in 17785 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 17786 NamedDecl *Hidden = nullptr; 17787 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 17788 // There is a definition of this tag, but it is not visible. We 17789 // explicitly make use of C++'s one definition rule here, and 17790 // assume that this definition is identical to the hidden one 17791 // we already have. Make the existing definition visible and 17792 // use it in place of this one. 17793 if (!getLangOpts().CPlusPlus) { 17794 // Postpone making the old definition visible until after we 17795 // complete parsing the new one and do the structural 17796 // comparison. 17797 SkipBody->CheckSameAsPrevious = true; 17798 SkipBody->New = createTagFromNewDecl(); 17799 SkipBody->Previous = Def; 17800 return Def; 17801 } else { 17802 SkipBody->ShouldSkip = true; 17803 SkipBody->Previous = Def; 17804 makeMergedDefinitionVisible(Hidden); 17805 // Carry on and handle it like a normal definition. We'll 17806 // skip starting the definition later. 17807 } 17808 } else if (!IsExplicitSpecializationAfterInstantiation) { 17809 // A redeclaration in function prototype scope in C isn't 17810 // visible elsewhere, so merely issue a warning. 17811 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 17812 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 17813 else 17814 Diag(NameLoc, diag::err_redefinition) << Name; 17815 notePreviousDefinition(Def, 17816 NameLoc.isValid() ? NameLoc : KWLoc); 17817 // If this is a redefinition, recover by making this 17818 // struct be anonymous, which will make any later 17819 // references get the previous definition. 17820 Name = nullptr; 17821 Previous.clear(); 17822 Invalid = true; 17823 } 17824 } else { 17825 // If the type is currently being defined, complain 17826 // about a nested redefinition. 17827 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 17828 if (TD->isBeingDefined()) { 17829 Diag(NameLoc, diag::err_nested_redefinition) << Name; 17830 Diag(PrevTagDecl->getLocation(), 17831 diag::note_previous_definition); 17832 Name = nullptr; 17833 Previous.clear(); 17834 Invalid = true; 17835 } 17836 } 17837 17838 // Okay, this is definition of a previously declared or referenced 17839 // tag. We're going to create a new Decl for it. 17840 } 17841 17842 // Okay, we're going to make a redeclaration. If this is some kind 17843 // of reference, make sure we build the redeclaration in the same DC 17844 // as the original, and ignore the current access specifier. 17845 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) { 17846 SearchDC = PrevTagDecl->getDeclContext(); 17847 AS = AS_none; 17848 } 17849 } 17850 // If we get here we have (another) forward declaration or we 17851 // have a definition. Just create a new decl. 17852 17853 } else { 17854 // If we get here, this is a definition of a new tag type in a nested 17855 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 17856 // new decl/type. We set PrevDecl to NULL so that the entities 17857 // have distinct types. 17858 Previous.clear(); 17859 } 17860 // If we get here, we're going to create a new Decl. If PrevDecl 17861 // is non-NULL, it's a definition of the tag declared by 17862 // PrevDecl. If it's NULL, we have a new definition. 17863 17864 // Otherwise, PrevDecl is not a tag, but was found with tag 17865 // lookup. This is only actually possible in C++, where a few 17866 // things like templates still live in the tag namespace. 17867 } else { 17868 // Use a better diagnostic if an elaborated-type-specifier 17869 // found the wrong kind of type on the first 17870 // (non-redeclaration) lookup. 17871 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) && 17872 !Previous.isForRedeclaration()) { 17873 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 17874 Diag(NameLoc, diag::err_tag_reference_non_tag) 17875 << PrevDecl << NTK << llvm::to_underlying(Kind); 17876 Diag(PrevDecl->getLocation(), diag::note_declared_at); 17877 Invalid = true; 17878 17879 // Otherwise, only diagnose if the declaration is in scope. 17880 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 17881 SS.isNotEmpty() || isMemberSpecialization)) { 17882 // do nothing 17883 17884 // Diagnose implicit declarations introduced by elaborated types. 17885 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) { 17886 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 17887 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 17888 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 17889 Invalid = true; 17890 17891 // Otherwise it's a declaration. Call out a particularly common 17892 // case here. 17893 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 17894 unsigned Kind = 0; 17895 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 17896 Diag(NameLoc, diag::err_tag_definition_of_typedef) 17897 << Name << Kind << TND->getUnderlyingType(); 17898 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 17899 Invalid = true; 17900 17901 // Otherwise, diagnose. 17902 } else { 17903 // The tag name clashes with something else in the target scope, 17904 // issue an error and recover by making this tag be anonymous. 17905 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 17906 notePreviousDefinition(PrevDecl, NameLoc); 17907 Name = nullptr; 17908 Invalid = true; 17909 } 17910 17911 // The existing declaration isn't relevant to us; we're in a 17912 // new scope, so clear out the previous declaration. 17913 Previous.clear(); 17914 } 17915 } 17916 17917 CreateNewDecl: 17918 17919 TagDecl *PrevDecl = nullptr; 17920 if (Previous.isSingleResult()) 17921 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 17922 17923 // If there is an identifier, use the location of the identifier as the 17924 // location of the decl, otherwise use the location of the struct/union 17925 // keyword. 17926 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 17927 17928 // Otherwise, create a new declaration. If there is a previous 17929 // declaration of the same entity, the two will be linked via 17930 // PrevDecl. 17931 TagDecl *New; 17932 17933 if (Kind == TagTypeKind::Enum) { 17934 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 17935 // enum X { A, B, C } D; D should chain to X. 17936 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 17937 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 17938 ScopedEnumUsesClassTag, IsFixed); 17939 17940 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 17941 StdAlignValT = cast<EnumDecl>(New); 17942 17943 // If this is an undefined enum, warn. 17944 if (TUK != TagUseKind::Definition && !Invalid) { 17945 TagDecl *Def; 17946 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 17947 // C++0x: 7.2p2: opaque-enum-declaration. 17948 // Conflicts are diagnosed above. Do nothing. 17949 } 17950 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 17951 Diag(Loc, diag::ext_forward_ref_enum_def) 17952 << New; 17953 Diag(Def->getLocation(), diag::note_previous_definition); 17954 } else { 17955 unsigned DiagID = diag::ext_forward_ref_enum; 17956 if (getLangOpts().MSVCCompat) 17957 DiagID = diag::ext_ms_forward_ref_enum; 17958 else if (getLangOpts().CPlusPlus) 17959 DiagID = diag::err_forward_ref_enum; 17960 Diag(Loc, DiagID); 17961 } 17962 } 17963 17964 if (EnumUnderlying) { 17965 EnumDecl *ED = cast<EnumDecl>(New); 17966 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying)) 17967 ED->setIntegerTypeSourceInfo(TI); 17968 else 17969 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0)); 17970 QualType EnumTy = ED->getIntegerType(); 17971 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy) 17972 ? Context.getPromotedIntegerType(EnumTy) 17973 : EnumTy); 17974 assert(ED->isComplete() && "enum with type should be complete"); 17975 } 17976 } else { 17977 // struct/union/class 17978 17979 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 17980 // struct X { int A; } D; D should chain to X. 17981 if (getLangOpts().CPlusPlus) { 17982 // FIXME: Look for a way to use RecordDecl for simple structs. 17983 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 17984 cast_or_null<CXXRecordDecl>(PrevDecl)); 17985 17986 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 17987 StdBadAlloc = cast<CXXRecordDecl>(New); 17988 } else 17989 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 17990 cast_or_null<RecordDecl>(PrevDecl)); 17991 } 17992 17993 // Only C23 and later allow defining new types in 'offsetof()'. 17994 if (OOK != OOK_Outside && TUK == TagUseKind::Definition && 17995 !getLangOpts().CPlusPlus && !getLangOpts().C23) 17996 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof) 17997 << (OOK == OOK_Macro) << New->getSourceRange(); 17998 17999 // C++11 [dcl.type]p3: 18000 // A type-specifier-seq shall not define a class or enumeration [...]. 18001 if (!Invalid && getLangOpts().CPlusPlus && 18002 (IsTypeSpecifier || IsTemplateParamOrArg) && 18003 TUK == TagUseKind::Definition) { 18004 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 18005 << Context.getTagDeclType(New); 18006 Invalid = true; 18007 } 18008 18009 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition && 18010 DC->getDeclKind() == Decl::Enum) { 18011 Diag(New->getLocation(), diag::err_type_defined_in_enum) 18012 << Context.getTagDeclType(New); 18013 Invalid = true; 18014 } 18015 18016 // Maybe add qualifier info. 18017 if (SS.isNotEmpty()) { 18018 if (SS.isSet()) { 18019 // If this is either a declaration or a definition, check the 18020 // nested-name-specifier against the current context. 18021 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) && 18022 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 18023 /*TemplateId=*/nullptr, 18024 isMemberSpecialization)) 18025 Invalid = true; 18026 18027 New->setQualifierInfo(SS.getWithLocInContext(Context)); 18028 if (TemplateParameterLists.size() > 0) { 18029 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 18030 } 18031 } 18032 else 18033 Invalid = true; 18034 } 18035 18036 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 18037 // Add alignment attributes if necessary; these attributes are checked when 18038 // the ASTContext lays out the structure. 18039 // 18040 // It is important for implementing the correct semantics that this 18041 // happen here (in ActOnTag). The #pragma pack stack is 18042 // maintained as a result of parser callbacks which can occur at 18043 // many points during the parsing of a struct declaration (because 18044 // the #pragma tokens are effectively skipped over during the 18045 // parsing of the struct). 18046 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 18047 AddAlignmentAttributesForRecord(RD); 18048 AddMsStructLayoutForRecord(RD); 18049 } 18050 } 18051 18052 if (ModulePrivateLoc.isValid()) { 18053 if (isMemberSpecialization) 18054 Diag(New->getLocation(), diag::err_module_private_specialization) 18055 << 2 18056 << FixItHint::CreateRemoval(ModulePrivateLoc); 18057 // __module_private__ does not apply to local classes. However, we only 18058 // diagnose this as an error when the declaration specifiers are 18059 // freestanding. Here, we just ignore the __module_private__. 18060 else if (!SearchDC->isFunctionOrMethod()) 18061 New->setModulePrivate(); 18062 } 18063 18064 // If this is a specialization of a member class (of a class template), 18065 // check the specialization. 18066 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 18067 Invalid = true; 18068 18069 // If we're declaring or defining a tag in function prototype scope in C, 18070 // note that this type can only be used within the function and add it to 18071 // the list of decls to inject into the function definition scope. 18072 if ((Name || Kind == TagTypeKind::Enum) && 18073 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 18074 if (getLangOpts().CPlusPlus) { 18075 // C++ [dcl.fct]p6: 18076 // Types shall not be defined in return or parameter types. 18077 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) { 18078 Diag(Loc, diag::err_type_defined_in_param_type) 18079 << Name; 18080 Invalid = true; 18081 } 18082 if (TUK == TagUseKind::Declaration) 18083 Invalid = true; 18084 } else if (!PrevDecl) { 18085 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 18086 } 18087 } 18088 18089 if (Invalid) 18090 New->setInvalidDecl(); 18091 18092 // Set the lexical context. If the tag has a C++ scope specifier, the 18093 // lexical context will be different from the semantic context. 18094 New->setLexicalDeclContext(CurContext); 18095 18096 // Mark this as a friend decl if applicable. 18097 // In Microsoft mode, a friend declaration also acts as a forward 18098 // declaration so we always pass true to setObjectOfFriendDecl to make 18099 // the tag name visible. 18100 if (TUK == TagUseKind::Friend) 18101 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 18102 18103 // Set the access specifier. 18104 if (!Invalid && SearchDC->isRecord()) 18105 SetMemberAccessSpecifier(New, PrevDecl, AS); 18106 18107 if (PrevDecl) 18108 CheckRedeclarationInModule(New, PrevDecl); 18109 18110 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) 18111 New->startDefinition(); 18112 18113 ProcessDeclAttributeList(S, New, Attrs); 18114 AddPragmaAttributes(S, New); 18115 18116 // If this has an identifier, add it to the scope stack. 18117 if (TUK == TagUseKind::Friend) { 18118 // We might be replacing an existing declaration in the lookup tables; 18119 // if so, borrow its access specifier. 18120 if (PrevDecl) 18121 New->setAccess(PrevDecl->getAccess()); 18122 18123 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 18124 DC->makeDeclVisibleInContext(New); 18125 if (Name) // can be null along some error paths 18126 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 18127 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 18128 } else if (Name) { 18129 S = getNonFieldDeclScope(S); 18130 PushOnScopeChains(New, S, true); 18131 } else { 18132 CurContext->addDecl(New); 18133 } 18134 18135 // If this is the C FILE type, notify the AST context. 18136 if (IdentifierInfo *II = New->getIdentifier()) 18137 if (!New->isInvalidDecl() && 18138 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 18139 II->isStr("FILE")) 18140 Context.setFILEDecl(New); 18141 18142 if (PrevDecl) 18143 mergeDeclAttributes(New, PrevDecl); 18144 18145 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) { 18146 inferGslOwnerPointerAttribute(CXXRD); 18147 inferNullableClassAttribute(CXXRD); 18148 } 18149 18150 // If there's a #pragma GCC visibility in scope, set the visibility of this 18151 // record. 18152 AddPushedVisibilityAttribute(New); 18153 18154 if (isMemberSpecialization && !New->isInvalidDecl()) 18155 CompleteMemberSpecialization(New, Previous); 18156 18157 OwnedDecl = true; 18158 // In C++, don't return an invalid declaration. We can't recover well from 18159 // the cases where we make the type anonymous. 18160 if (Invalid && getLangOpts().CPlusPlus) { 18161 if (New->isBeingDefined()) 18162 if (auto RD = dyn_cast<RecordDecl>(New)) 18163 RD->completeDefinition(); 18164 return true; 18165 } else if (SkipBody && SkipBody->ShouldSkip) { 18166 return SkipBody->Previous; 18167 } else { 18168 return New; 18169 } 18170 } 18171 18172 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 18173 AdjustDeclIfTemplate(TagD); 18174 TagDecl *Tag = cast<TagDecl>(TagD); 18175 18176 // Enter the tag context. 18177 PushDeclContext(S, Tag); 18178 18179 ActOnDocumentableDecl(TagD); 18180 18181 // If there's a #pragma GCC visibility in scope, set the visibility of this 18182 // record. 18183 AddPushedVisibilityAttribute(Tag); 18184 } 18185 18186 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) { 18187 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 18188 return false; 18189 18190 // Make the previous decl visible. 18191 makeMergedDefinitionVisible(SkipBody.Previous); 18192 return true; 18193 } 18194 18195 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 18196 SourceLocation FinalLoc, 18197 bool IsFinalSpelledSealed, 18198 bool IsAbstract, 18199 SourceLocation LBraceLoc) { 18200 AdjustDeclIfTemplate(TagD); 18201 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 18202 18203 FieldCollector->StartClass(); 18204 18205 if (!Record->getIdentifier()) 18206 return; 18207 18208 if (IsAbstract) 18209 Record->markAbstract(); 18210 18211 if (FinalLoc.isValid()) { 18212 Record->addAttr(FinalAttr::Create(Context, FinalLoc, 18213 IsFinalSpelledSealed 18214 ? FinalAttr::Keyword_sealed 18215 : FinalAttr::Keyword_final)); 18216 } 18217 // C++ [class]p2: 18218 // [...] The class-name is also inserted into the scope of the 18219 // class itself; this is known as the injected-class-name. For 18220 // purposes of access checking, the injected-class-name is treated 18221 // as if it were a public member name. 18222 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 18223 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 18224 Record->getLocation(), Record->getIdentifier(), 18225 /*PrevDecl=*/nullptr, 18226 /*DelayTypeCreation=*/true); 18227 Context.getTypeDeclType(InjectedClassName, Record); 18228 InjectedClassName->setImplicit(); 18229 InjectedClassName->setAccess(AS_public); 18230 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 18231 InjectedClassName->setDescribedClassTemplate(Template); 18232 PushOnScopeChains(InjectedClassName, S); 18233 assert(InjectedClassName->isInjectedClassName() && 18234 "Broken injected-class-name"); 18235 } 18236 18237 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 18238 SourceRange BraceRange) { 18239 AdjustDeclIfTemplate(TagD); 18240 TagDecl *Tag = cast<TagDecl>(TagD); 18241 Tag->setBraceRange(BraceRange); 18242 18243 // Make sure we "complete" the definition even it is invalid. 18244 if (Tag->isBeingDefined()) { 18245 assert(Tag->isInvalidDecl() && "We should already have completed it"); 18246 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 18247 RD->completeDefinition(); 18248 } 18249 18250 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 18251 FieldCollector->FinishClass(); 18252 if (RD->hasAttr<SYCLSpecialClassAttr>()) { 18253 auto *Def = RD->getDefinition(); 18254 assert(Def && "The record is expected to have a completed definition"); 18255 unsigned NumInitMethods = 0; 18256 for (auto *Method : Def->methods()) { 18257 if (!Method->getIdentifier()) 18258 continue; 18259 if (Method->getName() == "__init") 18260 NumInitMethods++; 18261 } 18262 if (NumInitMethods > 1 || !Def->hasInitMethod()) 18263 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method); 18264 } 18265 18266 // If we're defining a dynamic class in a module interface unit, we always 18267 // need to produce the vtable for it, even if the vtable is not used in the 18268 // current TU. 18269 // 18270 // The case where the current class is not dynamic is handled in 18271 // MarkVTableUsed. 18272 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition()) 18273 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true); 18274 } 18275 18276 // Exit this scope of this tag's definition. 18277 PopDeclContext(); 18278 18279 if (getCurLexicalContext()->isObjCContainer() && 18280 Tag->getDeclContext()->isFileContext()) 18281 Tag->setTopLevelDeclInObjCContainer(); 18282 18283 // Notify the consumer that we've defined a tag. 18284 if (!Tag->isInvalidDecl()) 18285 Consumer.HandleTagDeclDefinition(Tag); 18286 18287 // Clangs implementation of #pragma align(packed) differs in bitfield layout 18288 // from XLs and instead matches the XL #pragma pack(1) behavior. 18289 if (Context.getTargetInfo().getTriple().isOSAIX() && 18290 AlignPackStack.hasValue()) { 18291 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 18292 // Only diagnose #pragma align(packed). 18293 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 18294 return; 18295 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 18296 if (!RD) 18297 return; 18298 // Only warn if there is at least 1 bitfield member. 18299 if (llvm::any_of(RD->fields(), 18300 [](const FieldDecl *FD) { return FD->isBitField(); })) 18301 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 18302 } 18303 } 18304 18305 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 18306 AdjustDeclIfTemplate(TagD); 18307 TagDecl *Tag = cast<TagDecl>(TagD); 18308 Tag->setInvalidDecl(); 18309 18310 // Make sure we "complete" the definition even it is invalid. 18311 if (Tag->isBeingDefined()) { 18312 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 18313 RD->completeDefinition(); 18314 } 18315 18316 // We're undoing ActOnTagStartDefinition here, not 18317 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 18318 // the FieldCollector. 18319 18320 PopDeclContext(); 18321 } 18322 18323 // Note that FieldName may be null for anonymous bitfields. 18324 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 18325 const IdentifierInfo *FieldName, 18326 QualType FieldTy, bool IsMsStruct, 18327 Expr *BitWidth) { 18328 assert(BitWidth); 18329 if (BitWidth->containsErrors()) 18330 return ExprError(); 18331 18332 // C99 6.7.2.1p4 - verify the field type. 18333 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 18334 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 18335 // Handle incomplete and sizeless types with a specific error. 18336 if (RequireCompleteSizedType(FieldLoc, FieldTy, 18337 diag::err_field_incomplete_or_sizeless)) 18338 return ExprError(); 18339 if (FieldName) 18340 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 18341 << FieldName << FieldTy << BitWidth->getSourceRange(); 18342 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 18343 << FieldTy << BitWidth->getSourceRange(); 18344 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 18345 UPPC_BitFieldWidth)) 18346 return ExprError(); 18347 18348 // If the bit-width is type- or value-dependent, don't try to check 18349 // it now. 18350 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 18351 return BitWidth; 18352 18353 llvm::APSInt Value; 18354 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 18355 if (ICE.isInvalid()) 18356 return ICE; 18357 BitWidth = ICE.get(); 18358 18359 // Zero-width bitfield is ok for anonymous field. 18360 if (Value == 0 && FieldName) 18361 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) 18362 << FieldName << BitWidth->getSourceRange(); 18363 18364 if (Value.isSigned() && Value.isNegative()) { 18365 if (FieldName) 18366 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 18367 << FieldName << toString(Value, 10); 18368 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 18369 << toString(Value, 10); 18370 } 18371 18372 // The size of the bit-field must not exceed our maximum permitted object 18373 // size. 18374 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 18375 return Diag(FieldLoc, diag::err_bitfield_too_wide) 18376 << !FieldName << FieldName << toString(Value, 10); 18377 } 18378 18379 if (!FieldTy->isDependentType()) { 18380 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 18381 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 18382 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 18383 18384 // Over-wide bitfields are an error in C or when using the MSVC bitfield 18385 // ABI. 18386 bool CStdConstraintViolation = 18387 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 18388 bool MSBitfieldViolation = 18389 Value.ugt(TypeStorageSize) && 18390 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 18391 if (CStdConstraintViolation || MSBitfieldViolation) { 18392 unsigned DiagWidth = 18393 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 18394 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 18395 << (bool)FieldName << FieldName << toString(Value, 10) 18396 << !CStdConstraintViolation << DiagWidth; 18397 } 18398 18399 // Warn on types where the user might conceivably expect to get all 18400 // specified bits as value bits: that's all integral types other than 18401 // 'bool'. 18402 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 18403 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 18404 << FieldName << toString(Value, 10) 18405 << (unsigned)TypeWidth; 18406 } 18407 } 18408 18409 if (isa<ConstantExpr>(BitWidth)) 18410 return BitWidth; 18411 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value}); 18412 } 18413 18414 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 18415 Declarator &D, Expr *BitfieldWidth) { 18416 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart, 18417 D, BitfieldWidth, 18418 /*InitStyle=*/ICIS_NoInit, AS_public); 18419 return Res; 18420 } 18421 18422 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 18423 SourceLocation DeclStart, 18424 Declarator &D, Expr *BitWidth, 18425 InClassInitStyle InitStyle, 18426 AccessSpecifier AS) { 18427 if (D.isDecompositionDeclarator()) { 18428 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 18429 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 18430 << Decomp.getSourceRange(); 18431 return nullptr; 18432 } 18433 18434 const IdentifierInfo *II = D.getIdentifier(); 18435 SourceLocation Loc = DeclStart; 18436 if (II) Loc = D.getIdentifierLoc(); 18437 18438 TypeSourceInfo *TInfo = GetTypeForDeclarator(D); 18439 QualType T = TInfo->getType(); 18440 if (getLangOpts().CPlusPlus) { 18441 CheckExtraCXXDefaultArguments(D); 18442 18443 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 18444 UPPC_DataMemberType)) { 18445 D.setInvalidType(); 18446 T = Context.IntTy; 18447 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 18448 } 18449 } 18450 18451 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 18452 18453 if (D.getDeclSpec().isInlineSpecified()) 18454 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 18455 << getLangOpts().CPlusPlus17; 18456 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 18457 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 18458 diag::err_invalid_thread) 18459 << DeclSpec::getSpecifierName(TSCS); 18460 18461 // Check to see if this name was declared as a member previously 18462 NamedDecl *PrevDecl = nullptr; 18463 LookupResult Previous(*this, II, Loc, LookupMemberName, 18464 RedeclarationKind::ForVisibleRedeclaration); 18465 LookupName(Previous, S); 18466 switch (Previous.getResultKind()) { 18467 case LookupResult::Found: 18468 case LookupResult::FoundUnresolvedValue: 18469 PrevDecl = Previous.getAsSingle<NamedDecl>(); 18470 break; 18471 18472 case LookupResult::FoundOverloaded: 18473 PrevDecl = Previous.getRepresentativeDecl(); 18474 break; 18475 18476 case LookupResult::NotFound: 18477 case LookupResult::NotFoundInCurrentInstantiation: 18478 case LookupResult::Ambiguous: 18479 break; 18480 } 18481 Previous.suppressDiagnostics(); 18482 18483 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18484 // Maybe we will complain about the shadowed template parameter. 18485 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 18486 // Just pretend that we didn't see the previous declaration. 18487 PrevDecl = nullptr; 18488 } 18489 18490 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 18491 PrevDecl = nullptr; 18492 18493 bool Mutable 18494 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 18495 SourceLocation TSSL = D.getBeginLoc(); 18496 FieldDecl *NewFD 18497 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 18498 TSSL, AS, PrevDecl, &D); 18499 18500 if (NewFD->isInvalidDecl()) 18501 Record->setInvalidDecl(); 18502 18503 if (D.getDeclSpec().isModulePrivateSpecified()) 18504 NewFD->setModulePrivate(); 18505 18506 if (NewFD->isInvalidDecl() && PrevDecl) { 18507 // Don't introduce NewFD into scope; there's already something 18508 // with the same name in the same scope. 18509 } else if (II) { 18510 PushOnScopeChains(NewFD, S); 18511 } else 18512 Record->addDecl(NewFD); 18513 18514 return NewFD; 18515 } 18516 18517 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 18518 TypeSourceInfo *TInfo, 18519 RecordDecl *Record, SourceLocation Loc, 18520 bool Mutable, Expr *BitWidth, 18521 InClassInitStyle InitStyle, 18522 SourceLocation TSSL, 18523 AccessSpecifier AS, NamedDecl *PrevDecl, 18524 Declarator *D) { 18525 const IdentifierInfo *II = Name.getAsIdentifierInfo(); 18526 bool InvalidDecl = false; 18527 if (D) InvalidDecl = D->isInvalidType(); 18528 18529 // If we receive a broken type, recover by assuming 'int' and 18530 // marking this declaration as invalid. 18531 if (T.isNull() || T->containsErrors()) { 18532 InvalidDecl = true; 18533 T = Context.IntTy; 18534 } 18535 18536 QualType EltTy = Context.getBaseElementType(T); 18537 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 18538 bool isIncomplete = 18539 LangOpts.HLSL // HLSL allows sizeless builtin types 18540 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type) 18541 : RequireCompleteSizedType(Loc, EltTy, 18542 diag::err_field_incomplete_or_sizeless); 18543 if (isIncomplete) { 18544 // Fields of incomplete type force their record to be invalid. 18545 Record->setInvalidDecl(); 18546 InvalidDecl = true; 18547 } else { 18548 NamedDecl *Def; 18549 EltTy->isIncompleteType(&Def); 18550 if (Def && Def->isInvalidDecl()) { 18551 Record->setInvalidDecl(); 18552 InvalidDecl = true; 18553 } 18554 } 18555 } 18556 18557 // TR 18037 does not allow fields to be declared with address space 18558 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 18559 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 18560 Diag(Loc, diag::err_field_with_address_space); 18561 Record->setInvalidDecl(); 18562 InvalidDecl = true; 18563 } 18564 18565 if (LangOpts.OpenCL) { 18566 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 18567 // used as structure or union field: image, sampler, event or block types. 18568 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 18569 T->isBlockPointerType()) { 18570 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 18571 Record->setInvalidDecl(); 18572 InvalidDecl = true; 18573 } 18574 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 18575 // is enabled. 18576 if (BitWidth && !getOpenCLOptions().isAvailableOption( 18577 "__cl_clang_bitfields", LangOpts)) { 18578 Diag(Loc, diag::err_opencl_bitfields); 18579 InvalidDecl = true; 18580 } 18581 } 18582 18583 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 18584 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 18585 T.hasQualifiers()) { 18586 InvalidDecl = true; 18587 Diag(Loc, diag::err_anon_bitfield_qualifiers); 18588 } 18589 18590 // C99 6.7.2.1p8: A member of a structure or union may have any type other 18591 // than a variably modified type. 18592 if (!InvalidDecl && T->isVariablyModifiedType()) { 18593 if (!tryToFixVariablyModifiedVarType( 18594 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 18595 InvalidDecl = true; 18596 } 18597 18598 // Fields can not have abstract class types 18599 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 18600 diag::err_abstract_type_in_decl, 18601 AbstractFieldType)) 18602 InvalidDecl = true; 18603 18604 if (InvalidDecl) 18605 BitWidth = nullptr; 18606 // If this is declared as a bit-field, check the bit-field. 18607 if (BitWidth) { 18608 BitWidth = 18609 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get(); 18610 if (!BitWidth) { 18611 InvalidDecl = true; 18612 BitWidth = nullptr; 18613 } 18614 } 18615 18616 // Check that 'mutable' is consistent with the type of the declaration. 18617 if (!InvalidDecl && Mutable) { 18618 unsigned DiagID = 0; 18619 if (T->isReferenceType()) 18620 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 18621 : diag::err_mutable_reference; 18622 else if (T.isConstQualified()) 18623 DiagID = diag::err_mutable_const; 18624 18625 if (DiagID) { 18626 SourceLocation ErrLoc = Loc; 18627 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 18628 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 18629 Diag(ErrLoc, DiagID); 18630 if (DiagID != diag::ext_mutable_reference) { 18631 Mutable = false; 18632 InvalidDecl = true; 18633 } 18634 } 18635 } 18636 18637 // C++11 [class.union]p8 (DR1460): 18638 // At most one variant member of a union may have a 18639 // brace-or-equal-initializer. 18640 if (InitStyle != ICIS_NoInit) 18641 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 18642 18643 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 18644 BitWidth, Mutable, InitStyle); 18645 if (InvalidDecl) 18646 NewFD->setInvalidDecl(); 18647 18648 if (PrevDecl && !isa<TagDecl>(PrevDecl) && 18649 !PrevDecl->isPlaceholderVar(getLangOpts())) { 18650 Diag(Loc, diag::err_duplicate_member) << II; 18651 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 18652 NewFD->setInvalidDecl(); 18653 } 18654 18655 if (!InvalidDecl && getLangOpts().CPlusPlus) { 18656 if (Record->isUnion()) { 18657 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 18658 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 18659 if (RDecl->getDefinition()) { 18660 // C++ [class.union]p1: An object of a class with a non-trivial 18661 // constructor, a non-trivial copy constructor, a non-trivial 18662 // destructor, or a non-trivial copy assignment operator 18663 // cannot be a member of a union, nor can an array of such 18664 // objects. 18665 if (CheckNontrivialField(NewFD)) 18666 NewFD->setInvalidDecl(); 18667 } 18668 } 18669 18670 // C++ [class.union]p1: If a union contains a member of reference type, 18671 // the program is ill-formed, except when compiling with MSVC extensions 18672 // enabled. 18673 if (EltTy->isReferenceType()) { 18674 const bool HaveMSExt = 18675 getLangOpts().MicrosoftExt && 18676 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 18677 18678 Diag(NewFD->getLocation(), 18679 HaveMSExt ? diag::ext_union_member_of_reference_type 18680 : diag::err_union_member_of_reference_type) 18681 << NewFD->getDeclName() << EltTy; 18682 if (!HaveMSExt) 18683 NewFD->setInvalidDecl(); 18684 } 18685 } 18686 } 18687 18688 // FIXME: We need to pass in the attributes given an AST 18689 // representation, not a parser representation. 18690 if (D) { 18691 // FIXME: The current scope is almost... but not entirely... correct here. 18692 ProcessDeclAttributes(getCurScope(), NewFD, *D); 18693 18694 if (NewFD->hasAttrs()) 18695 CheckAlignasUnderalignment(NewFD); 18696 } 18697 18698 // In auto-retain/release, infer strong retension for fields of 18699 // retainable type. 18700 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD)) 18701 NewFD->setInvalidDecl(); 18702 18703 if (T.isObjCGCWeak()) 18704 Diag(Loc, diag::warn_attribute_weak_on_field); 18705 18706 // PPC MMA non-pointer types are not allowed as field types. 18707 if (Context.getTargetInfo().getTriple().isPPC64() && 18708 PPC().CheckPPCMMAType(T, NewFD->getLocation())) 18709 NewFD->setInvalidDecl(); 18710 18711 NewFD->setAccess(AS); 18712 return NewFD; 18713 } 18714 18715 bool Sema::CheckNontrivialField(FieldDecl *FD) { 18716 assert(FD); 18717 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 18718 18719 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 18720 return false; 18721 18722 QualType EltTy = Context.getBaseElementType(FD->getType()); 18723 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 18724 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 18725 if (RDecl->getDefinition()) { 18726 // We check for copy constructors before constructors 18727 // because otherwise we'll never get complaints about 18728 // copy constructors. 18729 18730 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid; 18731 // We're required to check for any non-trivial constructors. Since the 18732 // implicit default constructor is suppressed if there are any 18733 // user-declared constructors, we just need to check that there is a 18734 // trivial default constructor and a trivial copy constructor. (We don't 18735 // worry about move constructors here, since this is a C++98 check.) 18736 if (RDecl->hasNonTrivialCopyConstructor()) 18737 member = CXXSpecialMemberKind::CopyConstructor; 18738 else if (!RDecl->hasTrivialDefaultConstructor()) 18739 member = CXXSpecialMemberKind::DefaultConstructor; 18740 else if (RDecl->hasNonTrivialCopyAssignment()) 18741 member = CXXSpecialMemberKind::CopyAssignment; 18742 else if (RDecl->hasNonTrivialDestructor()) 18743 member = CXXSpecialMemberKind::Destructor; 18744 18745 if (member != CXXSpecialMemberKind::Invalid) { 18746 if (!getLangOpts().CPlusPlus11 && 18747 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 18748 // Objective-C++ ARC: it is an error to have a non-trivial field of 18749 // a union. However, system headers in Objective-C programs 18750 // occasionally have Objective-C lifetime objects within unions, 18751 // and rather than cause the program to fail, we make those 18752 // members unavailable. 18753 SourceLocation Loc = FD->getLocation(); 18754 if (getSourceManager().isInSystemHeader(Loc)) { 18755 if (!FD->hasAttr<UnavailableAttr>()) 18756 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 18757 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 18758 return false; 18759 } 18760 } 18761 18762 Diag( 18763 FD->getLocation(), 18764 getLangOpts().CPlusPlus11 18765 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member 18766 : diag::err_illegal_union_or_anon_struct_member) 18767 << FD->getParent()->isUnion() << FD->getDeclName() 18768 << llvm::to_underlying(member); 18769 DiagnoseNontrivial(RDecl, member); 18770 return !getLangOpts().CPlusPlus11; 18771 } 18772 } 18773 } 18774 18775 return false; 18776 } 18777 18778 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 18779 SmallVectorImpl<Decl *> &AllIvarDecls) { 18780 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 18781 return; 18782 18783 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 18784 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 18785 18786 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField()) 18787 return; 18788 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 18789 if (!ID) { 18790 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 18791 if (!CD->IsClassExtension()) 18792 return; 18793 } 18794 // No need to add this to end of @implementation. 18795 else 18796 return; 18797 } 18798 // All conditions are met. Add a new bitfield to the tail end of ivars. 18799 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 18800 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 18801 Expr *BitWidth = 18802 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero))); 18803 18804 Ivar = ObjCIvarDecl::Create( 18805 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr, 18806 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc), 18807 ObjCIvarDecl::Private, BitWidth, true); 18808 AllIvarDecls.push_back(Ivar); 18809 } 18810 18811 /// [class.dtor]p4: 18812 /// At the end of the definition of a class, overload resolution is 18813 /// performed among the prospective destructors declared in that class with 18814 /// an empty argument list to select the destructor for the class, also 18815 /// known as the selected destructor. 18816 /// 18817 /// We do the overload resolution here, then mark the selected constructor in the AST. 18818 /// Later CXXRecordDecl::getDestructor() will return the selected constructor. 18819 static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) { 18820 if (!Record->hasUserDeclaredDestructor()) { 18821 return; 18822 } 18823 18824 SourceLocation Loc = Record->getLocation(); 18825 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal); 18826 18827 for (auto *Decl : Record->decls()) { 18828 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) { 18829 if (DD->isInvalidDecl()) 18830 continue; 18831 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {}, 18832 OCS); 18833 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected."); 18834 } 18835 } 18836 18837 if (OCS.empty()) { 18838 return; 18839 } 18840 OverloadCandidateSet::iterator Best; 18841 unsigned Msg = 0; 18842 OverloadCandidateDisplayKind DisplayKind; 18843 18844 switch (OCS.BestViableFunction(S, Loc, Best)) { 18845 case OR_Success: 18846 case OR_Deleted: 18847 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function)); 18848 break; 18849 18850 case OR_Ambiguous: 18851 Msg = diag::err_ambiguous_destructor; 18852 DisplayKind = OCD_AmbiguousCandidates; 18853 break; 18854 18855 case OR_No_Viable_Function: 18856 Msg = diag::err_no_viable_destructor; 18857 DisplayKind = OCD_AllCandidates; 18858 break; 18859 } 18860 18861 if (Msg) { 18862 // OpenCL have got their own thing going with destructors. It's slightly broken, 18863 // but we allow it. 18864 if (!S.LangOpts.OpenCL) { 18865 PartialDiagnostic Diag = S.PDiag(Msg) << Record; 18866 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {}); 18867 Record->setInvalidDecl(); 18868 } 18869 // It's a bit hacky: At this point we've raised an error but we want the 18870 // rest of the compiler to continue somehow working. However almost 18871 // everything we'll try to do with the class will depend on there being a 18872 // destructor. So let's pretend the first one is selected and hope for the 18873 // best. 18874 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function)); 18875 } 18876 } 18877 18878 /// [class.mem.special]p5 18879 /// Two special member functions are of the same kind if: 18880 /// - they are both default constructors, 18881 /// - they are both copy or move constructors with the same first parameter 18882 /// type, or 18883 /// - they are both copy or move assignment operators with the same first 18884 /// parameter type and the same cv-qualifiers and ref-qualifier, if any. 18885 static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, 18886 CXXMethodDecl *M1, 18887 CXXMethodDecl *M2, 18888 CXXSpecialMemberKind CSM) { 18889 // We don't want to compare templates to non-templates: See 18890 // https://github.com/llvm/llvm-project/issues/59206 18891 if (CSM == CXXSpecialMemberKind::DefaultConstructor) 18892 return bool(M1->getDescribedFunctionTemplate()) == 18893 bool(M2->getDescribedFunctionTemplate()); 18894 // FIXME: better resolve CWG 18895 // https://cplusplus.github.io/CWG/issues/2787.html 18896 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(), 18897 M2->getNonObjectParameter(0)->getType())) 18898 return false; 18899 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(), 18900 M2->getFunctionObjectParameterReferenceType())) 18901 return false; 18902 18903 return true; 18904 } 18905 18906 /// [class.mem.special]p6: 18907 /// An eligible special member function is a special member function for which: 18908 /// - the function is not deleted, 18909 /// - the associated constraints, if any, are satisfied, and 18910 /// - no special member function of the same kind whose associated constraints 18911 /// [CWG2595], if any, are satisfied is more constrained. 18912 static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, 18913 ArrayRef<CXXMethodDecl *> Methods, 18914 CXXSpecialMemberKind CSM) { 18915 SmallVector<bool, 4> SatisfactionStatus; 18916 18917 for (CXXMethodDecl *Method : Methods) { 18918 const Expr *Constraints = Method->getTrailingRequiresClause(); 18919 if (!Constraints) 18920 SatisfactionStatus.push_back(true); 18921 else { 18922 ConstraintSatisfaction Satisfaction; 18923 if (S.CheckFunctionConstraints(Method, Satisfaction)) 18924 SatisfactionStatus.push_back(false); 18925 else 18926 SatisfactionStatus.push_back(Satisfaction.IsSatisfied); 18927 } 18928 } 18929 18930 for (size_t i = 0; i < Methods.size(); i++) { 18931 if (!SatisfactionStatus[i]) 18932 continue; 18933 CXXMethodDecl *Method = Methods[i]; 18934 CXXMethodDecl *OrigMethod = Method; 18935 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction()) 18936 OrigMethod = cast<CXXMethodDecl>(MF); 18937 18938 const Expr *Constraints = OrigMethod->getTrailingRequiresClause(); 18939 bool AnotherMethodIsMoreConstrained = false; 18940 for (size_t j = 0; j < Methods.size(); j++) { 18941 if (i == j || !SatisfactionStatus[j]) 18942 continue; 18943 CXXMethodDecl *OtherMethod = Methods[j]; 18944 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction()) 18945 OtherMethod = cast<CXXMethodDecl>(MF); 18946 18947 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod, 18948 CSM)) 18949 continue; 18950 18951 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause(); 18952 if (!OtherConstraints) 18953 continue; 18954 if (!Constraints) { 18955 AnotherMethodIsMoreConstrained = true; 18956 break; 18957 } 18958 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod, 18959 {Constraints}, 18960 AnotherMethodIsMoreConstrained)) { 18961 // There was an error with the constraints comparison. Exit the loop 18962 // and don't consider this function eligible. 18963 AnotherMethodIsMoreConstrained = true; 18964 } 18965 if (AnotherMethodIsMoreConstrained) 18966 break; 18967 } 18968 // FIXME: Do not consider deleted methods as eligible after implementing 18969 // DR1734 and DR1496. 18970 if (!AnotherMethodIsMoreConstrained) { 18971 Method->setIneligibleOrNotSelected(false); 18972 Record->addedEligibleSpecialMemberFunction(Method, 18973 1 << llvm::to_underlying(CSM)); 18974 } 18975 } 18976 } 18977 18978 static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, 18979 CXXRecordDecl *Record) { 18980 SmallVector<CXXMethodDecl *, 4> DefaultConstructors; 18981 SmallVector<CXXMethodDecl *, 4> CopyConstructors; 18982 SmallVector<CXXMethodDecl *, 4> MoveConstructors; 18983 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators; 18984 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators; 18985 18986 for (auto *Decl : Record->decls()) { 18987 auto *MD = dyn_cast<CXXMethodDecl>(Decl); 18988 if (!MD) { 18989 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl); 18990 if (FTD) 18991 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl()); 18992 } 18993 if (!MD) 18994 continue; 18995 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) { 18996 if (CD->isInvalidDecl()) 18997 continue; 18998 if (CD->isDefaultConstructor()) 18999 DefaultConstructors.push_back(MD); 19000 else if (CD->isCopyConstructor()) 19001 CopyConstructors.push_back(MD); 19002 else if (CD->isMoveConstructor()) 19003 MoveConstructors.push_back(MD); 19004 } else if (MD->isCopyAssignmentOperator()) { 19005 CopyAssignmentOperators.push_back(MD); 19006 } else if (MD->isMoveAssignmentOperator()) { 19007 MoveAssignmentOperators.push_back(MD); 19008 } 19009 } 19010 19011 SetEligibleMethods(S, Record, DefaultConstructors, 19012 CXXSpecialMemberKind::DefaultConstructor); 19013 SetEligibleMethods(S, Record, CopyConstructors, 19014 CXXSpecialMemberKind::CopyConstructor); 19015 SetEligibleMethods(S, Record, MoveConstructors, 19016 CXXSpecialMemberKind::MoveConstructor); 19017 SetEligibleMethods(S, Record, CopyAssignmentOperators, 19018 CXXSpecialMemberKind::CopyAssignment); 19019 SetEligibleMethods(S, Record, MoveAssignmentOperators, 19020 CXXSpecialMemberKind::MoveAssignment); 19021 } 19022 19023 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 19024 ArrayRef<Decl *> Fields, SourceLocation LBrac, 19025 SourceLocation RBrac, 19026 const ParsedAttributesView &Attrs) { 19027 assert(EnclosingDecl && "missing record or interface decl"); 19028 19029 // If this is an Objective-C @implementation or category and we have 19030 // new fields here we should reset the layout of the interface since 19031 // it will now change. 19032 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 19033 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 19034 switch (DC->getKind()) { 19035 default: break; 19036 case Decl::ObjCCategory: 19037 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 19038 break; 19039 case Decl::ObjCImplementation: 19040 Context. 19041 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 19042 break; 19043 } 19044 } 19045 19046 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 19047 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 19048 19049 // Start counting up the number of named members; make sure to include 19050 // members of anonymous structs and unions in the total. 19051 unsigned NumNamedMembers = 0; 19052 if (Record) { 19053 for (const auto *I : Record->decls()) { 19054 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 19055 if (IFD->getDeclName()) 19056 ++NumNamedMembers; 19057 } 19058 } 19059 19060 // Verify that all the fields are okay. 19061 SmallVector<FieldDecl*, 32> RecFields; 19062 19063 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 19064 i != end; ++i) { 19065 FieldDecl *FD = cast<FieldDecl>(*i); 19066 19067 // Get the type for the field. 19068 const Type *FDTy = FD->getType().getTypePtr(); 19069 19070 if (!FD->isAnonymousStructOrUnion()) { 19071 // Remember all fields written by the user. 19072 RecFields.push_back(FD); 19073 } 19074 19075 // If the field is already invalid for some reason, don't emit more 19076 // diagnostics about it. 19077 if (FD->isInvalidDecl()) { 19078 EnclosingDecl->setInvalidDecl(); 19079 continue; 19080 } 19081 19082 // C99 6.7.2.1p2: 19083 // A structure or union shall not contain a member with 19084 // incomplete or function type (hence, a structure shall not 19085 // contain an instance of itself, but may contain a pointer to 19086 // an instance of itself), except that the last member of a 19087 // structure with more than one named member may have incomplete 19088 // array type; such a structure (and any union containing, 19089 // possibly recursively, a member that is such a structure) 19090 // shall not be a member of a structure or an element of an 19091 // array. 19092 bool IsLastField = (i + 1 == Fields.end()); 19093 if (FDTy->isFunctionType()) { 19094 // Field declared as a function. 19095 Diag(FD->getLocation(), diag::err_field_declared_as_function) 19096 << FD->getDeclName(); 19097 FD->setInvalidDecl(); 19098 EnclosingDecl->setInvalidDecl(); 19099 continue; 19100 } else if (FDTy->isIncompleteArrayType() && 19101 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 19102 if (Record) { 19103 // Flexible array member. 19104 // Microsoft and g++ is more permissive regarding flexible array. 19105 // It will accept flexible array in union and also 19106 // as the sole element of a struct/class. 19107 unsigned DiagID = 0; 19108 if (!Record->isUnion() && !IsLastField) { 19109 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 19110 << FD->getDeclName() << FD->getType() 19111 << llvm::to_underlying(Record->getTagKind()); 19112 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 19113 FD->setInvalidDecl(); 19114 EnclosingDecl->setInvalidDecl(); 19115 continue; 19116 } else if (Record->isUnion()) 19117 DiagID = getLangOpts().MicrosoftExt 19118 ? diag::ext_flexible_array_union_ms 19119 : diag::ext_flexible_array_union_gnu; 19120 else if (NumNamedMembers < 1) 19121 DiagID = getLangOpts().MicrosoftExt 19122 ? diag::ext_flexible_array_empty_aggregate_ms 19123 : diag::ext_flexible_array_empty_aggregate_gnu; 19124 19125 if (DiagID) 19126 Diag(FD->getLocation(), DiagID) 19127 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind()); 19128 // While the layout of types that contain virtual bases is not specified 19129 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 19130 // virtual bases after the derived members. This would make a flexible 19131 // array member declared at the end of an object not adjacent to the end 19132 // of the type. 19133 if (CXXRecord && CXXRecord->getNumVBases() != 0) 19134 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 19135 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind()); 19136 if (!getLangOpts().C99) 19137 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 19138 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind()); 19139 19140 // If the element type has a non-trivial destructor, we would not 19141 // implicitly destroy the elements, so disallow it for now. 19142 // 19143 // FIXME: GCC allows this. We should probably either implicitly delete 19144 // the destructor of the containing class, or just allow this. 19145 QualType BaseElem = Context.getBaseElementType(FD->getType()); 19146 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 19147 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 19148 << FD->getDeclName() << FD->getType(); 19149 FD->setInvalidDecl(); 19150 EnclosingDecl->setInvalidDecl(); 19151 continue; 19152 } 19153 // Okay, we have a legal flexible array member at the end of the struct. 19154 Record->setHasFlexibleArrayMember(true); 19155 } else { 19156 // In ObjCContainerDecl ivars with incomplete array type are accepted, 19157 // unless they are followed by another ivar. That check is done 19158 // elsewhere, after synthesized ivars are known. 19159 } 19160 } else if (!FDTy->isDependentType() && 19161 (LangOpts.HLSL // HLSL allows sizeless builtin types 19162 ? RequireCompleteType(FD->getLocation(), FD->getType(), 19163 diag::err_incomplete_type) 19164 : RequireCompleteSizedType( 19165 FD->getLocation(), FD->getType(), 19166 diag::err_field_incomplete_or_sizeless))) { 19167 // Incomplete type 19168 FD->setInvalidDecl(); 19169 EnclosingDecl->setInvalidDecl(); 19170 continue; 19171 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 19172 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 19173 // A type which contains a flexible array member is considered to be a 19174 // flexible array member. 19175 Record->setHasFlexibleArrayMember(true); 19176 if (!Record->isUnion()) { 19177 // If this is a struct/class and this is not the last element, reject 19178 // it. Note that GCC supports variable sized arrays in the middle of 19179 // structures. 19180 if (!IsLastField) 19181 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 19182 << FD->getDeclName() << FD->getType(); 19183 else { 19184 // We support flexible arrays at the end of structs in 19185 // other structs as an extension. 19186 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 19187 << FD->getDeclName(); 19188 } 19189 } 19190 } 19191 if (isa<ObjCContainerDecl>(EnclosingDecl) && 19192 RequireNonAbstractType(FD->getLocation(), FD->getType(), 19193 diag::err_abstract_type_in_decl, 19194 AbstractIvarType)) { 19195 // Ivars can not have abstract class types 19196 FD->setInvalidDecl(); 19197 } 19198 if (Record && FDTTy->getDecl()->hasObjectMember()) 19199 Record->setHasObjectMember(true); 19200 if (Record && FDTTy->getDecl()->hasVolatileMember()) 19201 Record->setHasVolatileMember(true); 19202 } else if (FDTy->isObjCObjectType()) { 19203 /// A field cannot be an Objective-c object 19204 Diag(FD->getLocation(), diag::err_statically_allocated_object) 19205 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 19206 QualType T = Context.getObjCObjectPointerType(FD->getType()); 19207 FD->setType(T); 19208 } else if (Record && Record->isUnion() && 19209 FD->getType().hasNonTrivialObjCLifetime() && 19210 getSourceManager().isInSystemHeader(FD->getLocation()) && 19211 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 19212 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 19213 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 19214 // For backward compatibility, fields of C unions declared in system 19215 // headers that have non-trivial ObjC ownership qualifications are marked 19216 // as unavailable unless the qualifier is explicit and __strong. This can 19217 // break ABI compatibility between programs compiled with ARC and MRR, but 19218 // is a better option than rejecting programs using those unions under 19219 // ARC. 19220 FD->addAttr(UnavailableAttr::CreateImplicit( 19221 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 19222 FD->getLocation())); 19223 } else if (getLangOpts().ObjC && 19224 getLangOpts().getGC() != LangOptions::NonGC && Record && 19225 !Record->hasObjectMember()) { 19226 if (FD->getType()->isObjCObjectPointerType() || 19227 FD->getType().isObjCGCStrong()) 19228 Record->setHasObjectMember(true); 19229 else if (Context.getAsArrayType(FD->getType())) { 19230 QualType BaseType = Context.getBaseElementType(FD->getType()); 19231 if (BaseType->isRecordType() && 19232 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 19233 Record->setHasObjectMember(true); 19234 else if (BaseType->isObjCObjectPointerType() || 19235 BaseType.isObjCGCStrong()) 19236 Record->setHasObjectMember(true); 19237 } 19238 } 19239 19240 if (Record && !getLangOpts().CPlusPlus && 19241 !shouldIgnoreForRecordTriviality(FD)) { 19242 QualType FT = FD->getType(); 19243 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 19244 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 19245 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 19246 Record->isUnion()) 19247 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 19248 } 19249 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 19250 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 19251 Record->setNonTrivialToPrimitiveCopy(true); 19252 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 19253 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 19254 } 19255 if (FD->hasAttr<ExplicitInitAttr>()) 19256 Record->setHasUninitializedExplicitInitFields(true); 19257 if (FT.isDestructedType()) { 19258 Record->setNonTrivialToPrimitiveDestroy(true); 19259 Record->setParamDestroyedInCallee(true); 19260 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 19261 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 19262 } 19263 19264 if (const auto *RT = FT->getAs<RecordType>()) { 19265 if (RT->getDecl()->getArgPassingRestrictions() == 19266 RecordArgPassingKind::CanNeverPassInRegs) 19267 Record->setArgPassingRestrictions( 19268 RecordArgPassingKind::CanNeverPassInRegs); 19269 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 19270 Record->setArgPassingRestrictions( 19271 RecordArgPassingKind::CanNeverPassInRegs); 19272 } 19273 19274 if (Record && FD->getType().isVolatileQualified()) 19275 Record->setHasVolatileMember(true); 19276 // Keep track of the number of named members. 19277 if (FD->getIdentifier()) 19278 ++NumNamedMembers; 19279 } 19280 19281 // Okay, we successfully defined 'Record'. 19282 if (Record) { 19283 bool Completed = false; 19284 if (S) { 19285 Scope *Parent = S->getParent(); 19286 if (Parent && Parent->isTypeAliasScope() && 19287 Parent->isTemplateParamScope()) 19288 Record->setInvalidDecl(); 19289 } 19290 19291 if (CXXRecord) { 19292 if (!CXXRecord->isInvalidDecl()) { 19293 // Set access bits correctly on the directly-declared conversions. 19294 for (CXXRecordDecl::conversion_iterator 19295 I = CXXRecord->conversion_begin(), 19296 E = CXXRecord->conversion_end(); I != E; ++I) 19297 I.setAccess((*I)->getAccess()); 19298 } 19299 19300 // Add any implicitly-declared members to this class. 19301 AddImplicitlyDeclaredMembersToClass(CXXRecord); 19302 19303 if (!CXXRecord->isDependentType()) { 19304 if (!CXXRecord->isInvalidDecl()) { 19305 // If we have virtual base classes, we may end up finding multiple 19306 // final overriders for a given virtual function. Check for this 19307 // problem now. 19308 if (CXXRecord->getNumVBases()) { 19309 CXXFinalOverriderMap FinalOverriders; 19310 CXXRecord->getFinalOverriders(FinalOverriders); 19311 19312 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 19313 MEnd = FinalOverriders.end(); 19314 M != MEnd; ++M) { 19315 for (OverridingMethods::iterator SO = M->second.begin(), 19316 SOEnd = M->second.end(); 19317 SO != SOEnd; ++SO) { 19318 assert(SO->second.size() > 0 && 19319 "Virtual function without overriding functions?"); 19320 if (SO->second.size() == 1) 19321 continue; 19322 19323 // C++ [class.virtual]p2: 19324 // In a derived class, if a virtual member function of a base 19325 // class subobject has more than one final overrider the 19326 // program is ill-formed. 19327 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 19328 << (const NamedDecl *)M->first << Record; 19329 Diag(M->first->getLocation(), 19330 diag::note_overridden_virtual_function); 19331 for (OverridingMethods::overriding_iterator 19332 OM = SO->second.begin(), 19333 OMEnd = SO->second.end(); 19334 OM != OMEnd; ++OM) 19335 Diag(OM->Method->getLocation(), diag::note_final_overrider) 19336 << (const NamedDecl *)M->first << OM->Method->getParent(); 19337 19338 Record->setInvalidDecl(); 19339 } 19340 } 19341 CXXRecord->completeDefinition(&FinalOverriders); 19342 Completed = true; 19343 } 19344 } 19345 ComputeSelectedDestructor(*this, CXXRecord); 19346 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord); 19347 } 19348 } 19349 19350 if (!Completed) 19351 Record->completeDefinition(); 19352 19353 // Handle attributes before checking the layout. 19354 ProcessDeclAttributeList(S, Record, Attrs); 19355 19356 // Check to see if a FieldDecl is a pointer to a function. 19357 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) { 19358 const FieldDecl *FD = dyn_cast<FieldDecl>(D); 19359 if (!FD) { 19360 // Check whether this is a forward declaration that was inserted by 19361 // Clang. This happens when a non-forward declared / defined type is 19362 // used, e.g.: 19363 // 19364 // struct foo { 19365 // struct bar *(*f)(); 19366 // struct bar *(*g)(); 19367 // }; 19368 // 19369 // "struct bar" shows up in the decl AST as a "RecordDecl" with an 19370 // incomplete definition. 19371 if (const auto *TD = dyn_cast<TagDecl>(D)) 19372 return !TD->isCompleteDefinition(); 19373 return false; 19374 } 19375 QualType FieldType = FD->getType().getDesugaredType(Context); 19376 if (isa<PointerType>(FieldType)) { 19377 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType(); 19378 return PointeeType.getDesugaredType(Context)->isFunctionType(); 19379 } 19380 return false; 19381 }; 19382 19383 // Maybe randomize the record's decls. We automatically randomize a record 19384 // of function pointers, unless it has the "no_randomize_layout" attribute. 19385 if (!getLangOpts().CPlusPlus && 19386 (Record->hasAttr<RandomizeLayoutAttr>() || 19387 (!Record->hasAttr<NoRandomizeLayoutAttr>() && 19388 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) && 19389 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() && 19390 !Record->isRandomized()) { 19391 SmallVector<Decl *, 32> NewDeclOrdering; 19392 if (randstruct::randomizeStructureLayout(Context, Record, 19393 NewDeclOrdering)) 19394 Record->reorderDecls(NewDeclOrdering); 19395 } 19396 19397 // We may have deferred checking for a deleted destructor. Check now. 19398 if (CXXRecord) { 19399 auto *Dtor = CXXRecord->getDestructor(); 19400 if (Dtor && Dtor->isImplicit() && 19401 ShouldDeleteSpecialMember(Dtor, CXXSpecialMemberKind::Destructor)) { 19402 CXXRecord->setImplicitDestructorIsDeleted(); 19403 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 19404 } 19405 } 19406 19407 if (Record->hasAttrs()) { 19408 CheckAlignasUnderalignment(Record); 19409 19410 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 19411 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 19412 IA->getRange(), IA->getBestCase(), 19413 IA->getInheritanceModel()); 19414 } 19415 19416 // Check if the structure/union declaration is a type that can have zero 19417 // size in C. For C this is a language extension, for C++ it may cause 19418 // compatibility problems. 19419 bool CheckForZeroSize; 19420 if (!getLangOpts().CPlusPlus) { 19421 CheckForZeroSize = true; 19422 } else { 19423 // For C++ filter out types that cannot be referenced in C code. 19424 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 19425 CheckForZeroSize = 19426 CXXRecord->getLexicalDeclContext()->isExternCContext() && 19427 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 19428 CXXRecord->isCLike(); 19429 } 19430 if (CheckForZeroSize) { 19431 bool ZeroSize = true; 19432 bool IsEmpty = true; 19433 unsigned NonBitFields = 0; 19434 for (RecordDecl::field_iterator I = Record->field_begin(), 19435 E = Record->field_end(); 19436 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 19437 IsEmpty = false; 19438 if (I->isUnnamedBitField()) { 19439 if (!I->isZeroLengthBitField()) 19440 ZeroSize = false; 19441 } else { 19442 ++NonBitFields; 19443 QualType FieldType = I->getType(); 19444 if (FieldType->isIncompleteType() || 19445 !Context.getTypeSizeInChars(FieldType).isZero()) 19446 ZeroSize = false; 19447 } 19448 } 19449 19450 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 19451 // allowed in C++, but warn if its declaration is inside 19452 // extern "C" block. 19453 if (ZeroSize) { 19454 Diag(RecLoc, getLangOpts().CPlusPlus ? 19455 diag::warn_zero_size_struct_union_in_extern_c : 19456 diag::warn_zero_size_struct_union_compat) 19457 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 19458 } 19459 19460 // Structs without named members are extension in C (C99 6.7.2.1p7), 19461 // but are accepted by GCC. In C2y, this became implementation-defined 19462 // (C2y 6.7.3.2p10). 19463 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) { 19464 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union 19465 : diag::ext_no_named_members_in_struct_union) 19466 << Record->isUnion(); 19467 } 19468 } 19469 } else { 19470 ObjCIvarDecl **ClsFields = 19471 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 19472 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 19473 ID->setEndOfDefinitionLoc(RBrac); 19474 // Add ivar's to class's DeclContext. 19475 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 19476 ClsFields[i]->setLexicalDeclContext(ID); 19477 ID->addDecl(ClsFields[i]); 19478 } 19479 // Must enforce the rule that ivars in the base classes may not be 19480 // duplicates. 19481 if (ID->getSuperClass()) 19482 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 19483 } else if (ObjCImplementationDecl *IMPDecl = 19484 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 19485 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 19486 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 19487 // Ivar declared in @implementation never belongs to the implementation. 19488 // Only it is in implementation's lexical context. 19489 ClsFields[I]->setLexicalDeclContext(IMPDecl); 19490 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), 19491 RBrac); 19492 IMPDecl->setIvarLBraceLoc(LBrac); 19493 IMPDecl->setIvarRBraceLoc(RBrac); 19494 } else if (ObjCCategoryDecl *CDecl = 19495 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 19496 // case of ivars in class extension; all other cases have been 19497 // reported as errors elsewhere. 19498 // FIXME. Class extension does not have a LocEnd field. 19499 // CDecl->setLocEnd(RBrac); 19500 // Add ivar's to class extension's DeclContext. 19501 // Diagnose redeclaration of private ivars. 19502 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 19503 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 19504 if (IDecl) { 19505 if (const ObjCIvarDecl *ClsIvar = 19506 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 19507 Diag(ClsFields[i]->getLocation(), 19508 diag::err_duplicate_ivar_declaration); 19509 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 19510 continue; 19511 } 19512 for (const auto *Ext : IDecl->known_extensions()) { 19513 if (const ObjCIvarDecl *ClsExtIvar 19514 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 19515 Diag(ClsFields[i]->getLocation(), 19516 diag::err_duplicate_ivar_declaration); 19517 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 19518 continue; 19519 } 19520 } 19521 } 19522 ClsFields[i]->setLexicalDeclContext(CDecl); 19523 CDecl->addDecl(ClsFields[i]); 19524 } 19525 CDecl->setIvarLBraceLoc(LBrac); 19526 CDecl->setIvarRBraceLoc(RBrac); 19527 } 19528 } 19529 ProcessAPINotes(Record); 19530 } 19531 19532 /// Determine whether the given integral value is representable within 19533 /// the given type T. 19534 static bool isRepresentableIntegerValue(ASTContext &Context, 19535 llvm::APSInt &Value, 19536 QualType T) { 19537 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 19538 "Integral type required!"); 19539 unsigned BitWidth = Context.getIntWidth(T); 19540 19541 if (Value.isUnsigned() || Value.isNonNegative()) { 19542 if (T->isSignedIntegerOrEnumerationType()) 19543 --BitWidth; 19544 return Value.getActiveBits() <= BitWidth; 19545 } 19546 return Value.getSignificantBits() <= BitWidth; 19547 } 19548 19549 // Given an integral type, return the next larger integral type 19550 // (or a NULL type of no such type exists). 19551 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 19552 // FIXME: Int128/UInt128 support, which also needs to be introduced into 19553 // enum checking below. 19554 assert((T->isIntegralType(Context) || 19555 T->isEnumeralType()) && "Integral type required!"); 19556 const unsigned NumTypes = 4; 19557 QualType SignedIntegralTypes[NumTypes] = { 19558 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 19559 }; 19560 QualType UnsignedIntegralTypes[NumTypes] = { 19561 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 19562 Context.UnsignedLongLongTy 19563 }; 19564 19565 unsigned BitWidth = Context.getTypeSize(T); 19566 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 19567 : UnsignedIntegralTypes; 19568 for (unsigned I = 0; I != NumTypes; ++I) 19569 if (Context.getTypeSize(Types[I]) > BitWidth) 19570 return Types[I]; 19571 19572 return QualType(); 19573 } 19574 19575 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 19576 EnumConstantDecl *LastEnumConst, 19577 SourceLocation IdLoc, 19578 IdentifierInfo *Id, 19579 Expr *Val) { 19580 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 19581 llvm::APSInt EnumVal(IntWidth); 19582 QualType EltTy; 19583 19584 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 19585 Val = nullptr; 19586 19587 if (Val) 19588 Val = DefaultLvalueConversion(Val).get(); 19589 19590 if (Val) { 19591 if (Enum->isDependentType() || Val->isTypeDependent() || 19592 Val->containsErrors()) 19593 EltTy = Context.DependentTy; 19594 else { 19595 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 19596 // underlying type, but do allow it in all other contexts. 19597 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 19598 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 19599 // constant-expression in the enumerator-definition shall be a converted 19600 // constant expression of the underlying type. 19601 EltTy = Enum->getIntegerType(); 19602 ExprResult Converted = 19603 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 19604 CCEK_Enumerator); 19605 if (Converted.isInvalid()) 19606 Val = nullptr; 19607 else 19608 Val = Converted.get(); 19609 } else if (!Val->isValueDependent() && 19610 !(Val = 19611 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 19612 .get())) { 19613 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 19614 } else { 19615 if (Enum->isComplete()) { 19616 EltTy = Enum->getIntegerType(); 19617 19618 // In Obj-C and Microsoft mode, require the enumeration value to be 19619 // representable in the underlying type of the enumeration. In C++11, 19620 // we perform a non-narrowing conversion as part of converted constant 19621 // expression checking. 19622 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 19623 if (Context.getTargetInfo() 19624 .getTriple() 19625 .isWindowsMSVCEnvironment()) { 19626 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 19627 } else { 19628 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 19629 } 19630 } 19631 19632 // Cast to the underlying type. 19633 Val = ImpCastExprToType(Val, EltTy, 19634 EltTy->isBooleanType() ? CK_IntegralToBoolean 19635 : CK_IntegralCast) 19636 .get(); 19637 } else if (getLangOpts().CPlusPlus) { 19638 // C++11 [dcl.enum]p5: 19639 // If the underlying type is not fixed, the type of each enumerator 19640 // is the type of its initializing value: 19641 // - If an initializer is specified for an enumerator, the 19642 // initializing value has the same type as the expression. 19643 EltTy = Val->getType(); 19644 } else { 19645 // C99 6.7.2.2p2: 19646 // The expression that defines the value of an enumeration constant 19647 // shall be an integer constant expression that has a value 19648 // representable as an int. 19649 19650 // Complain if the value is not representable in an int. 19651 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) { 19652 Diag(IdLoc, getLangOpts().C23 19653 ? diag::warn_c17_compat_enum_value_not_int 19654 : diag::ext_c23_enum_value_not_int) 19655 << 0 << toString(EnumVal, 10) << Val->getSourceRange() 19656 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 19657 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 19658 // Force the type of the expression to 'int'. 19659 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 19660 } 19661 EltTy = Val->getType(); 19662 } 19663 } 19664 } 19665 } 19666 19667 if (!Val) { 19668 if (Enum->isDependentType()) 19669 EltTy = Context.DependentTy; 19670 else if (!LastEnumConst) { 19671 // C++0x [dcl.enum]p5: 19672 // If the underlying type is not fixed, the type of each enumerator 19673 // is the type of its initializing value: 19674 // - If no initializer is specified for the first enumerator, the 19675 // initializing value has an unspecified integral type. 19676 // 19677 // GCC uses 'int' for its unspecified integral type, as does 19678 // C99 6.7.2.2p3. 19679 if (Enum->isFixed()) { 19680 EltTy = Enum->getIntegerType(); 19681 } 19682 else { 19683 EltTy = Context.IntTy; 19684 } 19685 } else { 19686 // Assign the last value + 1. 19687 EnumVal = LastEnumConst->getInitVal(); 19688 ++EnumVal; 19689 EltTy = LastEnumConst->getType(); 19690 19691 // Check for overflow on increment. 19692 if (EnumVal < LastEnumConst->getInitVal()) { 19693 // C++0x [dcl.enum]p5: 19694 // If the underlying type is not fixed, the type of each enumerator 19695 // is the type of its initializing value: 19696 // 19697 // - Otherwise the type of the initializing value is the same as 19698 // the type of the initializing value of the preceding enumerator 19699 // unless the incremented value is not representable in that type, 19700 // in which case the type is an unspecified integral type 19701 // sufficient to contain the incremented value. If no such type 19702 // exists, the program is ill-formed. 19703 QualType T = getNextLargerIntegralType(Context, EltTy); 19704 if (T.isNull() || Enum->isFixed()) { 19705 // There is no integral type larger enough to represent this 19706 // value. Complain, then allow the value to wrap around. 19707 EnumVal = LastEnumConst->getInitVal(); 19708 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 19709 ++EnumVal; 19710 if (Enum->isFixed()) 19711 // When the underlying type is fixed, this is ill-formed. 19712 Diag(IdLoc, diag::err_enumerator_wrapped) 19713 << toString(EnumVal, 10) 19714 << EltTy; 19715 else 19716 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 19717 << toString(EnumVal, 10); 19718 } else { 19719 EltTy = T; 19720 } 19721 19722 // Retrieve the last enumerator's value, extent that type to the 19723 // type that is supposed to be large enough to represent the incremented 19724 // value, then increment. 19725 EnumVal = LastEnumConst->getInitVal(); 19726 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 19727 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 19728 ++EnumVal; 19729 19730 // If we're not in C++, diagnose the overflow of enumerator values, 19731 // which in C99 means that the enumerator value is not representable in 19732 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that 19733 // are representable in some larger integral type and we allow it in 19734 // older language modes as an extension. 19735 // Exclude fixed enumerators since they are diagnosed with an error for 19736 // this case. 19737 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed()) 19738 Diag(IdLoc, getLangOpts().C23 19739 ? diag::warn_c17_compat_enum_value_not_int 19740 : diag::ext_c23_enum_value_not_int) 19741 << 1 << toString(EnumVal, 10) << 1; 19742 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() && 19743 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 19744 // Enforce C99 6.7.2.2p2 even when we compute the next value. 19745 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int 19746 : diag::ext_c23_enum_value_not_int) 19747 << 1 << toString(EnumVal, 10) << 1; 19748 } 19749 } 19750 } 19751 19752 if (!EltTy->isDependentType()) { 19753 // Make the enumerator value match the signedness and size of the 19754 // enumerator's type. 19755 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 19756 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 19757 } 19758 19759 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 19760 Val, EnumVal); 19761 } 19762 19763 SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 19764 SourceLocation IILoc) { 19765 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 19766 !getLangOpts().CPlusPlus) 19767 return SkipBodyInfo(); 19768 19769 // We have an anonymous enum definition. Look up the first enumerator to 19770 // determine if we should merge the definition with an existing one and 19771 // skip the body. 19772 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 19773 forRedeclarationInCurContext()); 19774 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 19775 if (!PrevECD) 19776 return SkipBodyInfo(); 19777 19778 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 19779 NamedDecl *Hidden; 19780 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 19781 SkipBodyInfo Skip; 19782 Skip.Previous = Hidden; 19783 return Skip; 19784 } 19785 19786 return SkipBodyInfo(); 19787 } 19788 19789 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 19790 SourceLocation IdLoc, IdentifierInfo *Id, 19791 const ParsedAttributesView &Attrs, 19792 SourceLocation EqualLoc, Expr *Val) { 19793 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 19794 EnumConstantDecl *LastEnumConst = 19795 cast_or_null<EnumConstantDecl>(lastEnumConst); 19796 19797 // The scope passed in may not be a decl scope. Zip up the scope tree until 19798 // we find one that is. 19799 S = getNonFieldDeclScope(S); 19800 19801 // Verify that there isn't already something declared with this name in this 19802 // scope. 19803 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, 19804 RedeclarationKind::ForVisibleRedeclaration); 19805 LookupName(R, S); 19806 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 19807 19808 if (PrevDecl && PrevDecl->isTemplateParameter()) { 19809 // Maybe we will complain about the shadowed template parameter. 19810 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 19811 // Just pretend that we didn't see the previous declaration. 19812 PrevDecl = nullptr; 19813 } 19814 19815 // C++ [class.mem]p15: 19816 // If T is the name of a class, then each of the following shall have a name 19817 // different from T: 19818 // - every enumerator of every member of class T that is an unscoped 19819 // enumerated type 19820 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 19821 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 19822 DeclarationNameInfo(Id, IdLoc)); 19823 19824 EnumConstantDecl *New = 19825 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 19826 if (!New) 19827 return nullptr; 19828 19829 if (PrevDecl) { 19830 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 19831 // Check for other kinds of shadowing not already handled. 19832 CheckShadow(New, PrevDecl, R); 19833 } 19834 19835 // When in C++, we may get a TagDecl with the same name; in this case the 19836 // enum constant will 'hide' the tag. 19837 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 19838 "Received TagDecl when not in C++!"); 19839 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 19840 if (isa<EnumConstantDecl>(PrevDecl)) 19841 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 19842 else 19843 Diag(IdLoc, diag::err_redefinition) << Id; 19844 notePreviousDefinition(PrevDecl, IdLoc); 19845 return nullptr; 19846 } 19847 } 19848 19849 // Process attributes. 19850 ProcessDeclAttributeList(S, New, Attrs); 19851 AddPragmaAttributes(S, New); 19852 ProcessAPINotes(New); 19853 19854 // Register this decl in the current scope stack. 19855 New->setAccess(TheEnumDecl->getAccess()); 19856 PushOnScopeChains(New, S); 19857 19858 ActOnDocumentableDecl(New); 19859 19860 return New; 19861 } 19862 19863 // Returns true when the enum initial expression does not trigger the 19864 // duplicate enum warning. A few common cases are exempted as follows: 19865 // Element2 = Element1 19866 // Element2 = Element1 + 1 19867 // Element2 = Element1 - 1 19868 // Where Element2 and Element1 are from the same enum. 19869 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 19870 Expr *InitExpr = ECD->getInitExpr(); 19871 if (!InitExpr) 19872 return true; 19873 InitExpr = InitExpr->IgnoreImpCasts(); 19874 19875 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 19876 if (!BO->isAdditiveOp()) 19877 return true; 19878 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 19879 if (!IL) 19880 return true; 19881 if (IL->getValue() != 1) 19882 return true; 19883 19884 InitExpr = BO->getLHS(); 19885 } 19886 19887 // This checks if the elements are from the same enum. 19888 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 19889 if (!DRE) 19890 return true; 19891 19892 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 19893 if (!EnumConstant) 19894 return true; 19895 19896 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 19897 Enum) 19898 return true; 19899 19900 return false; 19901 } 19902 19903 // Emits a warning when an element is implicitly set a value that 19904 // a previous element has already been set to. 19905 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 19906 EnumDecl *Enum, QualType EnumType) { 19907 // Avoid anonymous enums 19908 if (!Enum->getIdentifier()) 19909 return; 19910 19911 // Only check for small enums. 19912 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 19913 return; 19914 19915 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 19916 return; 19917 19918 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 19919 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 19920 19921 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 19922 19923 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 19924 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 19925 19926 // Use int64_t as a key to avoid needing special handling for map keys. 19927 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 19928 llvm::APSInt Val = D->getInitVal(); 19929 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 19930 }; 19931 19932 DuplicatesVector DupVector; 19933 ValueToVectorMap EnumMap; 19934 19935 // Populate the EnumMap with all values represented by enum constants without 19936 // an initializer. 19937 for (auto *Element : Elements) { 19938 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 19939 19940 // Null EnumConstantDecl means a previous diagnostic has been emitted for 19941 // this constant. Skip this enum since it may be ill-formed. 19942 if (!ECD) { 19943 return; 19944 } 19945 19946 // Constants with initializers are handled in the next loop. 19947 if (ECD->getInitExpr()) 19948 continue; 19949 19950 // Duplicate values are handled in the next loop. 19951 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 19952 } 19953 19954 if (EnumMap.size() == 0) 19955 return; 19956 19957 // Create vectors for any values that has duplicates. 19958 for (auto *Element : Elements) { 19959 // The last loop returned if any constant was null. 19960 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 19961 if (!ValidDuplicateEnum(ECD, Enum)) 19962 continue; 19963 19964 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 19965 if (Iter == EnumMap.end()) 19966 continue; 19967 19968 DeclOrVector& Entry = Iter->second; 19969 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 19970 // Ensure constants are different. 19971 if (D == ECD) 19972 continue; 19973 19974 // Create new vector and push values onto it. 19975 auto Vec = std::make_unique<ECDVector>(); 19976 Vec->push_back(D); 19977 Vec->push_back(ECD); 19978 19979 // Update entry to point to the duplicates vector. 19980 Entry = Vec.get(); 19981 19982 // Store the vector somewhere we can consult later for quick emission of 19983 // diagnostics. 19984 DupVector.emplace_back(std::move(Vec)); 19985 continue; 19986 } 19987 19988 ECDVector *Vec = cast<ECDVector *>(Entry); 19989 // Make sure constants are not added more than once. 19990 if (*Vec->begin() == ECD) 19991 continue; 19992 19993 Vec->push_back(ECD); 19994 } 19995 19996 // Emit diagnostics. 19997 for (const auto &Vec : DupVector) { 19998 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 19999 20000 // Emit warning for one enum constant. 20001 auto *FirstECD = Vec->front(); 20002 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 20003 << FirstECD << toString(FirstECD->getInitVal(), 10) 20004 << FirstECD->getSourceRange(); 20005 20006 // Emit one note for each of the remaining enum constants with 20007 // the same value. 20008 for (auto *ECD : llvm::drop_begin(*Vec)) 20009 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 20010 << ECD << toString(ECD->getInitVal(), 10) 20011 << ECD->getSourceRange(); 20012 } 20013 } 20014 20015 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 20016 bool AllowMask) const { 20017 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 20018 assert(ED->isCompleteDefinition() && "expected enum definition"); 20019 20020 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 20021 llvm::APInt &FlagBits = R.first->second; 20022 20023 if (R.second) { 20024 for (auto *E : ED->enumerators()) { 20025 const auto &EVal = E->getInitVal(); 20026 // Only single-bit enumerators introduce new flag values. 20027 if (EVal.isPowerOf2()) 20028 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal; 20029 } 20030 } 20031 20032 // A value is in a flag enum if either its bits are a subset of the enum's 20033 // flag bits (the first condition) or we are allowing masks and the same is 20034 // true of its complement (the second condition). When masks are allowed, we 20035 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 20036 // 20037 // While it's true that any value could be used as a mask, the assumption is 20038 // that a mask will have all of the insignificant bits set. Anything else is 20039 // likely a logic error. 20040 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 20041 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 20042 } 20043 20044 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 20045 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 20046 const ParsedAttributesView &Attrs) { 20047 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 20048 QualType EnumType = Context.getTypeDeclType(Enum); 20049 20050 ProcessDeclAttributeList(S, Enum, Attrs); 20051 ProcessAPINotes(Enum); 20052 20053 if (Enum->isDependentType()) { 20054 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 20055 EnumConstantDecl *ECD = 20056 cast_or_null<EnumConstantDecl>(Elements[i]); 20057 if (!ECD) continue; 20058 20059 ECD->setType(EnumType); 20060 } 20061 20062 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 20063 return; 20064 } 20065 20066 // Verify that all the values are okay, compute the size of the values, and 20067 // reverse the list. 20068 unsigned NumNegativeBits = 0; 20069 unsigned NumPositiveBits = 0; 20070 bool MembersRepresentableByInt = true; 20071 20072 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 20073 EnumConstantDecl *ECD = 20074 cast_or_null<EnumConstantDecl>(Elements[i]); 20075 if (!ECD) continue; // Already issued a diagnostic. 20076 20077 llvm::APSInt InitVal = ECD->getInitVal(); 20078 20079 // Keep track of the size of positive and negative values. 20080 if (InitVal.isUnsigned() || InitVal.isNonNegative()) { 20081 // If the enumerator is zero that should still be counted as a positive 20082 // bit since we need a bit to store the value zero. 20083 unsigned ActiveBits = InitVal.getActiveBits(); 20084 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u}); 20085 } else { 20086 NumNegativeBits = 20087 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits()); 20088 } 20089 MembersRepresentableByInt &= 20090 isRepresentableIntegerValue(Context, InitVal, Context.IntTy); 20091 } 20092 20093 // If we have an empty set of enumerators we still need one bit. 20094 // From [dcl.enum]p8 20095 // If the enumerator-list is empty, the values of the enumeration are as if 20096 // the enumeration had a single enumerator with value 0 20097 if (!NumPositiveBits && !NumNegativeBits) 20098 NumPositiveBits = 1; 20099 20100 // Figure out the type that should be used for this enum. 20101 QualType BestType; 20102 unsigned BestWidth; 20103 20104 // C++0x N3000 [conv.prom]p3: 20105 // An rvalue of an unscoped enumeration type whose underlying 20106 // type is not fixed can be converted to an rvalue of the first 20107 // of the following types that can represent all the values of 20108 // the enumeration: int, unsigned int, long int, unsigned long 20109 // int, long long int, or unsigned long long int. 20110 // C99 6.4.4.3p2: 20111 // An identifier declared as an enumeration constant has type int. 20112 // The C99 rule is modified by C23. 20113 QualType BestPromotionType; 20114 20115 bool Packed = Enum->hasAttr<PackedAttr>(); 20116 // -fshort-enums is the equivalent to specifying the packed attribute on all 20117 // enum definitions. 20118 if (LangOpts.ShortEnums) 20119 Packed = true; 20120 20121 // If the enum already has a type because it is fixed or dictated by the 20122 // target, promote that type instead of analyzing the enumerators. 20123 if (Enum->isComplete()) { 20124 BestType = Enum->getIntegerType(); 20125 if (Context.isPromotableIntegerType(BestType)) 20126 BestPromotionType = Context.getPromotedIntegerType(BestType); 20127 else 20128 BestPromotionType = BestType; 20129 20130 BestWidth = Context.getIntWidth(BestType); 20131 } else { 20132 bool EnumTooLarge = Context.computeBestEnumTypes( 20133 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType); 20134 BestWidth = Context.getIntWidth(BestType); 20135 if (EnumTooLarge) 20136 Diag(Enum->getLocation(), diag::ext_enum_too_large); 20137 } 20138 20139 // Loop over all of the enumerator constants, changing their types to match 20140 // the type of the enum if needed. 20141 for (auto *D : Elements) { 20142 auto *ECD = cast_or_null<EnumConstantDecl>(D); 20143 if (!ECD) continue; // Already issued a diagnostic. 20144 20145 // C99 says the enumerators have int type, but we allow, as an 20146 // extension, the enumerators to be larger than int size. If each 20147 // enumerator value fits in an int, type it as an int, otherwise type it the 20148 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 20149 // that X has type 'int', not 'unsigned'. 20150 20151 // Determine whether the value fits into an int. 20152 llvm::APSInt InitVal = ECD->getInitVal(); 20153 20154 // If it fits into an integer type, force it. Otherwise force it to match 20155 // the enum decl type. 20156 QualType NewTy; 20157 unsigned NewWidth; 20158 bool NewSign; 20159 if (!getLangOpts().CPlusPlus && !Enum->isFixed() && 20160 MembersRepresentableByInt) { 20161 // C23 6.7.3.3.3p15: 20162 // The enumeration member type for an enumerated type without fixed 20163 // underlying type upon completion is: 20164 // - int if all the values of the enumeration are representable as an 20165 // int; or, 20166 // - the enumerated type 20167 NewTy = Context.IntTy; 20168 NewWidth = Context.getTargetInfo().getIntWidth(); 20169 NewSign = true; 20170 } else if (ECD->getType() == BestType) { 20171 // Already the right type! 20172 if (getLangOpts().CPlusPlus) 20173 // C++ [dcl.enum]p4: Following the closing brace of an 20174 // enum-specifier, each enumerator has the type of its 20175 // enumeration. 20176 ECD->setType(EnumType); 20177 continue; 20178 } else { 20179 NewTy = BestType; 20180 NewWidth = BestWidth; 20181 NewSign = BestType->isSignedIntegerOrEnumerationType(); 20182 } 20183 20184 // Adjust the APSInt value. 20185 InitVal = InitVal.extOrTrunc(NewWidth); 20186 InitVal.setIsSigned(NewSign); 20187 ECD->setInitVal(Context, InitVal); 20188 20189 // Adjust the Expr initializer and type. 20190 if (ECD->getInitExpr() && 20191 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 20192 ECD->setInitExpr(ImplicitCastExpr::Create( 20193 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 20194 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 20195 if (getLangOpts().CPlusPlus) 20196 // C++ [dcl.enum]p4: Following the closing brace of an 20197 // enum-specifier, each enumerator has the type of its 20198 // enumeration. 20199 ECD->setType(EnumType); 20200 else 20201 ECD->setType(NewTy); 20202 } 20203 20204 Enum->completeDefinition(BestType, BestPromotionType, 20205 NumPositiveBits, NumNegativeBits); 20206 20207 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 20208 20209 if (Enum->isClosedFlag()) { 20210 for (Decl *D : Elements) { 20211 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 20212 if (!ECD) continue; // Already issued a diagnostic. 20213 20214 llvm::APSInt InitVal = ECD->getInitVal(); 20215 if (InitVal != 0 && !InitVal.isPowerOf2() && 20216 !IsValueInFlagEnum(Enum, InitVal, true)) 20217 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 20218 << ECD << Enum; 20219 } 20220 } 20221 20222 // Now that the enum type is defined, ensure it's not been underaligned. 20223 if (Enum->hasAttrs()) 20224 CheckAlignasUnderalignment(Enum); 20225 } 20226 20227 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 20228 SourceLocation StartLoc, 20229 SourceLocation EndLoc) { 20230 StringLiteral *AsmString = cast<StringLiteral>(expr); 20231 20232 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 20233 AsmString, StartLoc, 20234 EndLoc); 20235 CurContext->addDecl(New); 20236 return New; 20237 } 20238 20239 TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) { 20240 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr); 20241 CurContext->addDecl(New); 20242 PushDeclContext(S, New); 20243 PushFunctionScope(); 20244 PushCompoundScope(false); 20245 return New; 20246 } 20247 20248 void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) { 20249 D->setStmt(Statement); 20250 PopCompoundScope(); 20251 PopFunctionScopeInfo(); 20252 PopDeclContext(); 20253 } 20254 20255 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 20256 IdentifierInfo* AliasName, 20257 SourceLocation PragmaLoc, 20258 SourceLocation NameLoc, 20259 SourceLocation AliasNameLoc) { 20260 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 20261 LookupOrdinaryName); 20262 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 20263 AttributeCommonInfo::Form::Pragma()); 20264 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 20265 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info); 20266 20267 // If a declaration that: 20268 // 1) declares a function or a variable 20269 // 2) has external linkage 20270 // already exists, add a label attribute to it. 20271 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 20272 if (isDeclExternC(PrevDecl)) 20273 PrevDecl->addAttr(Attr); 20274 else 20275 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 20276 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 20277 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers. 20278 } else 20279 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 20280 } 20281 20282 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 20283 SourceLocation PragmaLoc, 20284 SourceLocation NameLoc) { 20285 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 20286 20287 if (PrevDecl) { 20288 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 20289 } else { 20290 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc)); 20291 } 20292 } 20293 20294 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 20295 IdentifierInfo* AliasName, 20296 SourceLocation PragmaLoc, 20297 SourceLocation NameLoc, 20298 SourceLocation AliasNameLoc) { 20299 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 20300 LookupOrdinaryName); 20301 WeakInfo W = WeakInfo(Name, NameLoc); 20302 20303 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 20304 if (!PrevDecl->hasAttr<AliasAttr>()) 20305 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 20306 DeclApplyPragmaWeak(TUScope, ND, W); 20307 } else { 20308 (void)WeakUndeclaredIdentifiers[AliasName].insert(W); 20309 } 20310 } 20311 20312 Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD, 20313 bool Final) { 20314 assert(FD && "Expected non-null FunctionDecl"); 20315 20316 // SYCL functions can be template, so we check if they have appropriate 20317 // attribute prior to checking if it is a template. 20318 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 20319 return FunctionEmissionStatus::Emitted; 20320 20321 // Templates are emitted when they're instantiated. 20322 if (FD->isDependentContext()) 20323 return FunctionEmissionStatus::TemplateDiscarded; 20324 20325 // Check whether this function is an externally visible definition. 20326 auto IsEmittedForExternalSymbol = [this, FD]() { 20327 // We have to check the GVA linkage of the function's *definition* -- if we 20328 // only have a declaration, we don't know whether or not the function will 20329 // be emitted, because (say) the definition could include "inline". 20330 const FunctionDecl *Def = FD->getDefinition(); 20331 20332 // We can't compute linkage when we skip function bodies. 20333 return Def && !Def->hasSkippedBody() && 20334 !isDiscardableGVALinkage( 20335 getASTContext().GetGVALinkageForFunction(Def)); 20336 }; 20337 20338 if (LangOpts.OpenMPIsTargetDevice) { 20339 // In OpenMP device mode we will not emit host only functions, or functions 20340 // we don't need due to their linkage. 20341 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 20342 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 20343 // DevTy may be changed later by 20344 // #pragma omp declare target to(*) device_type(*). 20345 // Therefore DevTy having no value does not imply host. The emission status 20346 // will be checked again at the end of compilation unit with Final = true. 20347 if (DevTy) 20348 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 20349 return FunctionEmissionStatus::OMPDiscarded; 20350 // If we have an explicit value for the device type, or we are in a target 20351 // declare context, we need to emit all extern and used symbols. 20352 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy) 20353 if (IsEmittedForExternalSymbol()) 20354 return FunctionEmissionStatus::Emitted; 20355 // Device mode only emits what it must, if it wasn't tagged yet and needed, 20356 // we'll omit it. 20357 if (Final) 20358 return FunctionEmissionStatus::OMPDiscarded; 20359 } else if (LangOpts.OpenMP > 45) { 20360 // In OpenMP host compilation prior to 5.0 everything was an emitted host 20361 // function. In 5.0, no_host was introduced which might cause a function to 20362 // be omitted. 20363 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 20364 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 20365 if (DevTy) 20366 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 20367 return FunctionEmissionStatus::OMPDiscarded; 20368 } 20369 20370 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 20371 return FunctionEmissionStatus::Emitted; 20372 20373 if (LangOpts.CUDA) { 20374 // When compiling for device, host functions are never emitted. Similarly, 20375 // when compiling for host, device and global functions are never emitted. 20376 // (Technically, we do emit a host-side stub for global functions, but this 20377 // doesn't count for our purposes here.) 20378 CUDAFunctionTarget T = CUDA().IdentifyTarget(FD); 20379 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host) 20380 return FunctionEmissionStatus::CUDADiscarded; 20381 if (!LangOpts.CUDAIsDevice && 20382 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global)) 20383 return FunctionEmissionStatus::CUDADiscarded; 20384 20385 if (IsEmittedForExternalSymbol()) 20386 return FunctionEmissionStatus::Emitted; 20387 } 20388 20389 // Otherwise, the function is known-emitted if it's in our set of 20390 // known-emitted functions. 20391 return FunctionEmissionStatus::Unknown; 20392 } 20393 20394 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 20395 // Host-side references to a __global__ function refer to the stub, so the 20396 // function itself is never emitted and therefore should not be marked. 20397 // If we have host fn calls kernel fn calls host+device, the HD function 20398 // does not get instantiated on the host. We model this by omitting at the 20399 // call to the kernel from the callgraph. This ensures that, when compiling 20400 // for host, only HD functions actually called from the host get marked as 20401 // known-emitted. 20402 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 20403 CUDA().IdentifyTarget(Callee) == CUDAFunctionTarget::Global; 20404 } 20405