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/CommentDiagnostic.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.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/HLSLRuntime.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/SemaInternal.h" 49 #include "clang/Sema/Template.h" 50 #include "llvm/ADT/SmallString.h" 51 #include "llvm/ADT/StringExtras.h" 52 #include "llvm/TargetParser/Triple.h" 53 #include <algorithm> 54 #include <cstring> 55 #include <functional> 56 #include <optional> 57 #include <unordered_map> 58 59 using namespace clang; 60 using namespace sema; 61 62 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 63 if (OwnedType) { 64 Decl *Group[2] = { OwnedType, Ptr }; 65 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 66 } 67 68 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 69 } 70 71 namespace { 72 73 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 74 public: 75 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 76 bool AllowTemplates = false, 77 bool AllowNonTemplates = true) 78 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 79 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 80 WantExpressionKeywords = false; 81 WantCXXNamedCasts = false; 82 WantRemainingKeywords = false; 83 } 84 85 bool ValidateCandidate(const TypoCorrection &candidate) override { 86 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 87 if (!AllowInvalidDecl && ND->isInvalidDecl()) 88 return false; 89 90 if (getAsTypeTemplateDecl(ND)) 91 return AllowTemplates; 92 93 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 94 if (!IsType) 95 return false; 96 97 if (AllowNonTemplates) 98 return true; 99 100 // An injected-class-name of a class template (specialization) is valid 101 // as a template or as a non-template. 102 if (AllowTemplates) { 103 auto *RD = dyn_cast<CXXRecordDecl>(ND); 104 if (!RD || !RD->isInjectedClassName()) 105 return false; 106 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 107 return RD->getDescribedClassTemplate() || 108 isa<ClassTemplateSpecializationDecl>(RD); 109 } 110 111 return false; 112 } 113 114 return !WantClassName && candidate.isKeyword(); 115 } 116 117 std::unique_ptr<CorrectionCandidateCallback> clone() override { 118 return std::make_unique<TypeNameValidatorCCC>(*this); 119 } 120 121 private: 122 bool AllowInvalidDecl; 123 bool WantClassName; 124 bool AllowTemplates; 125 bool AllowNonTemplates; 126 }; 127 128 } // end anonymous namespace 129 130 /// Determine whether the token kind starts a simple-type-specifier. 131 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 132 switch (Kind) { 133 // FIXME: Take into account the current language when deciding whether a 134 // token kind is a valid type specifier 135 case tok::kw_short: 136 case tok::kw_long: 137 case tok::kw___int64: 138 case tok::kw___int128: 139 case tok::kw_signed: 140 case tok::kw_unsigned: 141 case tok::kw_void: 142 case tok::kw_char: 143 case tok::kw_int: 144 case tok::kw_half: 145 case tok::kw_float: 146 case tok::kw_double: 147 case tok::kw___bf16: 148 case tok::kw__Float16: 149 case tok::kw___float128: 150 case tok::kw___ibm128: 151 case tok::kw_wchar_t: 152 case tok::kw_bool: 153 case tok::kw__Accum: 154 case tok::kw__Fract: 155 case tok::kw__Sat: 156 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait: 157 #include "clang/Basic/TransformTypeTraits.def" 158 case tok::kw___auto_type: 159 return true; 160 161 case tok::annot_typename: 162 case tok::kw_char16_t: 163 case tok::kw_char32_t: 164 case tok::kw_typeof: 165 case tok::annot_decltype: 166 case tok::kw_decltype: 167 return getLangOpts().CPlusPlus; 168 169 case tok::kw_char8_t: 170 return getLangOpts().Char8; 171 172 default: 173 break; 174 } 175 176 return false; 177 } 178 179 namespace { 180 enum class UnqualifiedTypeNameLookupResult { 181 NotFound, 182 FoundNonType, 183 FoundType 184 }; 185 } // end anonymous namespace 186 187 /// Tries to perform unqualified lookup of the type decls in bases for 188 /// dependent class. 189 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 190 /// type decl, \a FoundType if only type decls are found. 191 static UnqualifiedTypeNameLookupResult 192 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 193 SourceLocation NameLoc, 194 const CXXRecordDecl *RD) { 195 if (!RD->hasDefinition()) 196 return UnqualifiedTypeNameLookupResult::NotFound; 197 // Look for type decls in base classes. 198 UnqualifiedTypeNameLookupResult FoundTypeDecl = 199 UnqualifiedTypeNameLookupResult::NotFound; 200 for (const auto &Base : RD->bases()) { 201 const CXXRecordDecl *BaseRD = nullptr; 202 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 203 BaseRD = BaseTT->getAsCXXRecordDecl(); 204 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 205 // Look for type decls in dependent base classes that have known primary 206 // templates. 207 if (!TST || !TST->isDependentType()) 208 continue; 209 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 210 if (!TD) 211 continue; 212 if (auto *BasePrimaryTemplate = 213 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 214 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 215 BaseRD = BasePrimaryTemplate; 216 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 217 if (const ClassTemplatePartialSpecializationDecl *PS = 218 CTD->findPartialSpecialization(Base.getType())) 219 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 220 BaseRD = PS; 221 } 222 } 223 } 224 if (BaseRD) { 225 for (NamedDecl *ND : BaseRD->lookup(&II)) { 226 if (!isa<TypeDecl>(ND)) 227 return UnqualifiedTypeNameLookupResult::FoundNonType; 228 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 229 } 230 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 231 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 232 case UnqualifiedTypeNameLookupResult::FoundNonType: 233 return UnqualifiedTypeNameLookupResult::FoundNonType; 234 case UnqualifiedTypeNameLookupResult::FoundType: 235 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 236 break; 237 case UnqualifiedTypeNameLookupResult::NotFound: 238 break; 239 } 240 } 241 } 242 } 243 244 return FoundTypeDecl; 245 } 246 247 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 248 const IdentifierInfo &II, 249 SourceLocation NameLoc) { 250 // Lookup in the parent class template context, if any. 251 const CXXRecordDecl *RD = nullptr; 252 UnqualifiedTypeNameLookupResult FoundTypeDecl = 253 UnqualifiedTypeNameLookupResult::NotFound; 254 for (DeclContext *DC = S.CurContext; 255 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 256 DC = DC->getParent()) { 257 // Look for type decls in dependent base classes that have known primary 258 // templates. 259 RD = dyn_cast<CXXRecordDecl>(DC); 260 if (RD && RD->getDescribedClassTemplate()) 261 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 262 } 263 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 264 return nullptr; 265 266 // We found some types in dependent base classes. Recover as if the user 267 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 268 // lookup during template instantiation. 269 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 270 271 ASTContext &Context = S.Context; 272 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 273 cast<Type>(Context.getRecordType(RD))); 274 QualType T = 275 Context.getDependentNameType(ElaboratedTypeKeyword::Typename, NNS, &II); 276 277 CXXScopeSpec SS; 278 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 279 280 TypeLocBuilder Builder; 281 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 282 DepTL.setNameLoc(NameLoc); 283 DepTL.setElaboratedKeywordLoc(SourceLocation()); 284 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 285 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 286 } 287 288 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 289 static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T, 290 SourceLocation NameLoc, 291 bool WantNontrivialTypeSourceInfo = true) { 292 switch (T->getTypeClass()) { 293 case Type::DeducedTemplateSpecialization: 294 case Type::Enum: 295 case Type::InjectedClassName: 296 case Type::Record: 297 case Type::Typedef: 298 case Type::UnresolvedUsing: 299 case Type::Using: 300 break; 301 // These can never be qualified so an ElaboratedType node 302 // would carry no additional meaning. 303 case Type::ObjCInterface: 304 case Type::ObjCTypeParam: 305 case Type::TemplateTypeParm: 306 return ParsedType::make(T); 307 default: 308 llvm_unreachable("Unexpected Type Class"); 309 } 310 311 if (!SS || SS->isEmpty()) 312 return ParsedType::make(S.Context.getElaboratedType( 313 ElaboratedTypeKeyword::None, nullptr, T, nullptr)); 314 315 QualType ElTy = S.getElaboratedType(ElaboratedTypeKeyword::None, *SS, T); 316 if (!WantNontrivialTypeSourceInfo) 317 return ParsedType::make(ElTy); 318 319 TypeLocBuilder Builder; 320 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 321 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy); 322 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 323 ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context)); 324 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy)); 325 } 326 327 /// If the identifier refers to a type name within this scope, 328 /// return the declaration of that type. 329 /// 330 /// This routine performs ordinary name lookup of the identifier II 331 /// within the given scope, with optional C++ scope specifier SS, to 332 /// determine whether the name refers to a type. If so, returns an 333 /// opaque pointer (actually a QualType) corresponding to that 334 /// type. Otherwise, returns NULL. 335 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 336 Scope *S, CXXScopeSpec *SS, bool isClassName, 337 bool HasTrailingDot, ParsedType ObjectTypePtr, 338 bool IsCtorOrDtorName, 339 bool WantNontrivialTypeSourceInfo, 340 bool IsClassTemplateDeductionContext, 341 ImplicitTypenameContext AllowImplicitTypename, 342 IdentifierInfo **CorrectedII) { 343 // FIXME: Consider allowing this outside C++1z mode as an extension. 344 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 345 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 346 !isClassName && !HasTrailingDot; 347 348 // Determine where we will perform name lookup. 349 DeclContext *LookupCtx = nullptr; 350 if (ObjectTypePtr) { 351 QualType ObjectType = ObjectTypePtr.get(); 352 if (ObjectType->isRecordType()) 353 LookupCtx = computeDeclContext(ObjectType); 354 } else if (SS && SS->isNotEmpty()) { 355 LookupCtx = computeDeclContext(*SS, false); 356 357 if (!LookupCtx) { 358 if (isDependentScopeSpecifier(*SS)) { 359 // C++ [temp.res]p3: 360 // A qualified-id that refers to a type and in which the 361 // nested-name-specifier depends on a template-parameter (14.6.2) 362 // shall be prefixed by the keyword typename to indicate that the 363 // qualified-id denotes a type, forming an 364 // elaborated-type-specifier (7.1.5.3). 365 // 366 // We therefore do not perform any name lookup if the result would 367 // refer to a member of an unknown specialization. 368 // In C++2a, in several contexts a 'typename' is not required. Also 369 // allow this as an extension. 370 if (AllowImplicitTypename == ImplicitTypenameContext::No && 371 !isClassName && !IsCtorOrDtorName) 372 return nullptr; 373 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName; 374 if (IsImplicitTypename) { 375 SourceLocation QualifiedLoc = SS->getRange().getBegin(); 376 if (getLangOpts().CPlusPlus20) 377 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename); 378 else 379 Diag(QualifiedLoc, diag::ext_implicit_typename) 380 << SS->getScopeRep() << II.getName() 381 << FixItHint::CreateInsertion(QualifiedLoc, "typename "); 382 } 383 384 // We know from the grammar that this name refers to a type, 385 // so build a dependent node to describe the type. 386 if (WantNontrivialTypeSourceInfo) 387 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc, 388 (ImplicitTypenameContext)IsImplicitTypename) 389 .get(); 390 391 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 392 QualType T = CheckTypenameType( 393 IsImplicitTypename ? ElaboratedTypeKeyword::Typename 394 : ElaboratedTypeKeyword::None, 395 SourceLocation(), QualifierLoc, II, NameLoc); 396 return ParsedType::make(T); 397 } 398 399 return nullptr; 400 } 401 402 if (!LookupCtx->isDependentContext() && 403 RequireCompleteDeclContext(*SS, LookupCtx)) 404 return nullptr; 405 } 406 407 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 408 // lookup for class-names. 409 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 410 LookupOrdinaryName; 411 LookupResult Result(*this, &II, NameLoc, Kind); 412 if (LookupCtx) { 413 // Perform "qualified" name lookup into the declaration context we 414 // computed, which is either the type of the base of a member access 415 // expression or the declaration context associated with a prior 416 // nested-name-specifier. 417 LookupQualifiedName(Result, LookupCtx); 418 419 if (ObjectTypePtr && Result.empty()) { 420 // C++ [basic.lookup.classref]p3: 421 // If the unqualified-id is ~type-name, the type-name is looked up 422 // in the context of the entire postfix-expression. If the type T of 423 // the object expression is of a class type C, the type-name is also 424 // looked up in the scope of class C. At least one of the lookups shall 425 // find a name that refers to (possibly cv-qualified) T. 426 LookupName(Result, S); 427 } 428 } else { 429 // Perform unqualified name lookup. 430 LookupName(Result, S); 431 432 // For unqualified lookup in a class template in MSVC mode, look into 433 // dependent base classes where the primary class template is known. 434 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 435 if (ParsedType TypeInBase = 436 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 437 return TypeInBase; 438 } 439 } 440 441 NamedDecl *IIDecl = nullptr; 442 UsingShadowDecl *FoundUsingShadow = nullptr; 443 switch (Result.getResultKind()) { 444 case LookupResult::NotFound: 445 if (CorrectedII) { 446 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 447 AllowDeducedTemplate); 448 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 449 S, SS, CCC, CTK_ErrorRecovery); 450 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 451 TemplateTy Template; 452 bool MemberOfUnknownSpecialization; 453 UnqualifiedId TemplateName; 454 TemplateName.setIdentifier(NewII, NameLoc); 455 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 456 CXXScopeSpec NewSS, *NewSSPtr = SS; 457 if (SS && NNS) { 458 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 459 NewSSPtr = &NewSS; 460 } 461 if (Correction && (NNS || NewII != &II) && 462 // Ignore a correction to a template type as the to-be-corrected 463 // identifier is not a template (typo correction for template names 464 // is handled elsewhere). 465 !(getLangOpts().CPlusPlus && NewSSPtr && 466 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 467 Template, MemberOfUnknownSpecialization))) { 468 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 469 isClassName, HasTrailingDot, ObjectTypePtr, 470 IsCtorOrDtorName, 471 WantNontrivialTypeSourceInfo, 472 IsClassTemplateDeductionContext); 473 if (Ty) { 474 diagnoseTypo(Correction, 475 PDiag(diag::err_unknown_type_or_class_name_suggest) 476 << Result.getLookupName() << isClassName); 477 if (SS && NNS) 478 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 479 *CorrectedII = NewII; 480 return Ty; 481 } 482 } 483 } 484 Result.suppressDiagnostics(); 485 return nullptr; 486 case LookupResult::NotFoundInCurrentInstantiation: 487 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) { 488 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None, 489 SS->getScopeRep(), &II); 490 TypeLocBuilder TLB; 491 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T); 492 TL.setElaboratedKeywordLoc(SourceLocation()); 493 TL.setQualifierLoc(SS->getWithLocInContext(Context)); 494 TL.setNameLoc(NameLoc); 495 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 496 } 497 [[fallthrough]]; 498 case LookupResult::FoundOverloaded: 499 case LookupResult::FoundUnresolvedValue: 500 Result.suppressDiagnostics(); 501 return nullptr; 502 503 case LookupResult::Ambiguous: 504 // Recover from type-hiding ambiguities by hiding the type. We'll 505 // do the lookup again when looking for an object, and we can 506 // diagnose the error then. If we don't do this, then the error 507 // about hiding the type will be immediately followed by an error 508 // that only makes sense if the identifier was treated like a type. 509 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 510 Result.suppressDiagnostics(); 511 return nullptr; 512 } 513 514 // Look to see if we have a type anywhere in the list of results. 515 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 516 Res != ResEnd; ++Res) { 517 NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); 518 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( 519 RealRes) || 520 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { 521 if (!IIDecl || 522 // Make the selection of the recovery decl deterministic. 523 RealRes->getLocation() < IIDecl->getLocation()) { 524 IIDecl = RealRes; 525 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res); 526 } 527 } 528 } 529 530 if (!IIDecl) { 531 // None of the entities we found is a type, so there is no way 532 // to even assume that the result is a type. In this case, don't 533 // complain about the ambiguity. The parser will either try to 534 // perform this lookup again (e.g., as an object name), which 535 // will produce the ambiguity, or will complain that it expected 536 // a type name. 537 Result.suppressDiagnostics(); 538 return nullptr; 539 } 540 541 // We found a type within the ambiguous lookup; diagnose the 542 // ambiguity and then return that type. This might be the right 543 // answer, or it might not be, but it suppresses any attempt to 544 // perform the name lookup again. 545 break; 546 547 case LookupResult::Found: 548 IIDecl = Result.getFoundDecl(); 549 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin()); 550 break; 551 } 552 553 assert(IIDecl && "Didn't find decl"); 554 555 QualType T; 556 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 557 // C++ [class.qual]p2: A lookup that would find the injected-class-name 558 // instead names the constructors of the class, except when naming a class. 559 // This is ill-formed when we're not actually forming a ctor or dtor name. 560 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 561 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 562 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 563 FoundRD->isInjectedClassName() && 564 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 565 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 566 << &II << /*Type*/1; 567 568 DiagnoseUseOfDecl(IIDecl, NameLoc); 569 570 T = Context.getTypeDeclType(TD); 571 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 572 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 573 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 574 if (!HasTrailingDot) 575 T = Context.getObjCInterfaceType(IDecl); 576 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl. 577 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { 578 (void)DiagnoseUseOfDecl(UD, NameLoc); 579 // Recover with 'int' 580 return ParsedType::make(Context.IntTy); 581 } else if (AllowDeducedTemplate) { 582 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) { 583 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD); 584 TemplateName Template = 585 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); 586 T = Context.getDeducedTemplateSpecializationType(Template, QualType(), 587 false); 588 // Don't wrap in a further UsingType. 589 FoundUsingShadow = nullptr; 590 } 591 } 592 593 if (T.isNull()) { 594 // If it's not plausibly a type, suppress diagnostics. 595 Result.suppressDiagnostics(); 596 return nullptr; 597 } 598 599 if (FoundUsingShadow) 600 T = Context.getUsingType(FoundUsingShadow, T); 601 602 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo); 603 } 604 605 // Builds a fake NNS for the given decl context. 606 static NestedNameSpecifier * 607 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 608 for (;; DC = DC->getLookupParent()) { 609 DC = DC->getPrimaryContext(); 610 auto *ND = dyn_cast<NamespaceDecl>(DC); 611 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 612 return NestedNameSpecifier::Create(Context, nullptr, ND); 613 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 614 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 615 RD->getTypeForDecl()); 616 else if (isa<TranslationUnitDecl>(DC)) 617 return NestedNameSpecifier::GlobalSpecifier(Context); 618 } 619 llvm_unreachable("something isn't in TU scope?"); 620 } 621 622 /// Find the parent class with dependent bases of the innermost enclosing method 623 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 624 /// up allowing unqualified dependent type names at class-level, which MSVC 625 /// correctly rejects. 626 static const CXXRecordDecl * 627 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 628 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 629 DC = DC->getPrimaryContext(); 630 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 631 if (MD->getParent()->hasAnyDependentBases()) 632 return MD->getParent(); 633 } 634 return nullptr; 635 } 636 637 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 638 SourceLocation NameLoc, 639 bool IsTemplateTypeArg) { 640 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 641 642 NestedNameSpecifier *NNS = nullptr; 643 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 644 // If we weren't able to parse a default template argument, delay lookup 645 // until instantiation time by making a non-dependent DependentTypeName. We 646 // pretend we saw a NestedNameSpecifier referring to the current scope, and 647 // lookup is retried. 648 // FIXME: This hurts our diagnostic quality, since we get errors like "no 649 // type named 'Foo' in 'current_namespace'" when the user didn't write any 650 // name specifiers. 651 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 652 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 653 } else if (const CXXRecordDecl *RD = 654 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 655 // Build a DependentNameType that will perform lookup into RD at 656 // instantiation time. 657 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 658 RD->getTypeForDecl()); 659 660 // Diagnose that this identifier was undeclared, and retry the lookup during 661 // template instantiation. 662 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 663 << RD; 664 } else { 665 // This is not a situation that we should recover from. 666 return ParsedType(); 667 } 668 669 QualType T = 670 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II); 671 672 // Build type location information. We synthesized the qualifier, so we have 673 // to build a fake NestedNameSpecifierLoc. 674 NestedNameSpecifierLocBuilder NNSLocBuilder; 675 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 676 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 677 678 TypeLocBuilder Builder; 679 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 680 DepTL.setNameLoc(NameLoc); 681 DepTL.setElaboratedKeywordLoc(SourceLocation()); 682 DepTL.setQualifierLoc(QualifierLoc); 683 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 684 } 685 686 /// isTagName() - This method is called *for error recovery purposes only* 687 /// to determine if the specified name is a valid tag name ("struct foo"). If 688 /// so, this returns the TST for the tag corresponding to it (TST_enum, 689 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 690 /// cases in C where the user forgot to specify the tag. 691 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 692 // Do a tag name lookup in this scope. 693 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 694 LookupName(R, S, false); 695 R.suppressDiagnostics(); 696 if (R.getResultKind() == LookupResult::Found) 697 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 698 switch (TD->getTagKind()) { 699 case TagTypeKind::Struct: 700 return DeclSpec::TST_struct; 701 case TagTypeKind::Interface: 702 return DeclSpec::TST_interface; 703 case TagTypeKind::Union: 704 return DeclSpec::TST_union; 705 case TagTypeKind::Class: 706 return DeclSpec::TST_class; 707 case TagTypeKind::Enum: 708 return DeclSpec::TST_enum; 709 } 710 } 711 712 return DeclSpec::TST_unspecified; 713 } 714 715 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 716 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 717 /// then downgrade the missing typename error to a warning. 718 /// This is needed for MSVC compatibility; Example: 719 /// @code 720 /// template<class T> class A { 721 /// public: 722 /// typedef int TYPE; 723 /// }; 724 /// template<class T> class B : public A<T> { 725 /// public: 726 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 727 /// }; 728 /// @endcode 729 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 730 if (CurContext->isRecord()) { 731 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 732 return true; 733 734 const Type *Ty = SS->getScopeRep()->getAsType(); 735 736 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 737 for (const auto &Base : RD->bases()) 738 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 739 return true; 740 return S->isFunctionPrototypeScope(); 741 } 742 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 743 } 744 745 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 746 SourceLocation IILoc, 747 Scope *S, 748 CXXScopeSpec *SS, 749 ParsedType &SuggestedType, 750 bool IsTemplateName) { 751 // Don't report typename errors for editor placeholders. 752 if (II->isEditorPlaceholder()) 753 return; 754 // We don't have anything to suggest (yet). 755 SuggestedType = nullptr; 756 757 // There may have been a typo in the name of the type. Look up typo 758 // results, in case we have something that we can suggest. 759 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 760 /*AllowTemplates=*/IsTemplateName, 761 /*AllowNonTemplates=*/!IsTemplateName); 762 if (TypoCorrection Corrected = 763 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 764 CCC, CTK_ErrorRecovery)) { 765 // FIXME: Support error recovery for the template-name case. 766 bool CanRecover = !IsTemplateName; 767 if (Corrected.isKeyword()) { 768 // We corrected to a keyword. 769 diagnoseTypo(Corrected, 770 PDiag(IsTemplateName ? diag::err_no_template_suggest 771 : diag::err_unknown_typename_suggest) 772 << II); 773 II = Corrected.getCorrectionAsIdentifierInfo(); 774 } else { 775 // We found a similarly-named type or interface; suggest that. 776 if (!SS || !SS->isSet()) { 777 diagnoseTypo(Corrected, 778 PDiag(IsTemplateName ? diag::err_no_template_suggest 779 : diag::err_unknown_typename_suggest) 780 << II, CanRecover); 781 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 782 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 783 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 784 II->getName().equals(CorrectedStr); 785 diagnoseTypo(Corrected, 786 PDiag(IsTemplateName 787 ? diag::err_no_member_template_suggest 788 : diag::err_unknown_nested_typename_suggest) 789 << II << DC << DroppedSpecifier << SS->getRange(), 790 CanRecover); 791 } else { 792 llvm_unreachable("could not have corrected a typo here"); 793 } 794 795 if (!CanRecover) 796 return; 797 798 CXXScopeSpec tmpSS; 799 if (Corrected.getCorrectionSpecifier()) 800 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 801 SourceRange(IILoc)); 802 // FIXME: Support class template argument deduction here. 803 SuggestedType = 804 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 805 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 806 /*IsCtorOrDtorName=*/false, 807 /*WantNontrivialTypeSourceInfo=*/true); 808 } 809 return; 810 } 811 812 if (getLangOpts().CPlusPlus && !IsTemplateName) { 813 // See if II is a class template that the user forgot to pass arguments to. 814 UnqualifiedId Name; 815 Name.setIdentifier(II, IILoc); 816 CXXScopeSpec EmptySS; 817 TemplateTy TemplateResult; 818 bool MemberOfUnknownSpecialization; 819 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 820 Name, nullptr, true, TemplateResult, 821 MemberOfUnknownSpecialization) == TNK_Type_template) { 822 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 823 return; 824 } 825 } 826 827 // FIXME: Should we move the logic that tries to recover from a missing tag 828 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 829 830 if (!SS || (!SS->isSet() && !SS->isInvalid())) 831 Diag(IILoc, IsTemplateName ? diag::err_no_template 832 : diag::err_unknown_typename) 833 << II; 834 else if (DeclContext *DC = computeDeclContext(*SS, false)) 835 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 836 : diag::err_typename_nested_not_found) 837 << II << DC << SS->getRange(); 838 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 839 SuggestedType = 840 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 841 } else if (isDependentScopeSpecifier(*SS)) { 842 unsigned DiagID = diag::err_typename_missing; 843 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 844 DiagID = diag::ext_typename_missing; 845 846 Diag(SS->getRange().getBegin(), DiagID) 847 << SS->getScopeRep() << II->getName() 848 << SourceRange(SS->getRange().getBegin(), IILoc) 849 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 850 SuggestedType = ActOnTypenameType(S, SourceLocation(), 851 *SS, *II, IILoc).get(); 852 } else { 853 assert(SS && SS->isInvalid() && 854 "Invalid scope specifier has already been diagnosed"); 855 } 856 } 857 858 /// Determine whether the given result set contains either a type name 859 /// or 860 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 861 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 862 NextToken.is(tok::less); 863 864 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 865 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 866 return true; 867 868 if (CheckTemplate && isa<TemplateDecl>(*I)) 869 return true; 870 } 871 872 return false; 873 } 874 875 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 876 Scope *S, CXXScopeSpec &SS, 877 IdentifierInfo *&Name, 878 SourceLocation NameLoc) { 879 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 880 SemaRef.LookupParsedName(R, S, &SS); 881 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 882 StringRef FixItTagName; 883 switch (Tag->getTagKind()) { 884 case TagTypeKind::Class: 885 FixItTagName = "class "; 886 break; 887 888 case TagTypeKind::Enum: 889 FixItTagName = "enum "; 890 break; 891 892 case TagTypeKind::Struct: 893 FixItTagName = "struct "; 894 break; 895 896 case TagTypeKind::Interface: 897 FixItTagName = "__interface "; 898 break; 899 900 case TagTypeKind::Union: 901 FixItTagName = "union "; 902 break; 903 } 904 905 StringRef TagName = FixItTagName.drop_back(); 906 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 907 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 908 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 909 910 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 911 I != IEnd; ++I) 912 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 913 << Name << TagName; 914 915 // Replace lookup results with just the tag decl. 916 Result.clear(Sema::LookupTagName); 917 SemaRef.LookupParsedName(Result, S, &SS); 918 return true; 919 } 920 921 return false; 922 } 923 924 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 925 IdentifierInfo *&Name, 926 SourceLocation NameLoc, 927 const Token &NextToken, 928 CorrectionCandidateCallback *CCC) { 929 DeclarationNameInfo NameInfo(Name, NameLoc); 930 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 931 932 assert(NextToken.isNot(tok::coloncolon) && 933 "parse nested name specifiers before calling ClassifyName"); 934 if (getLangOpts().CPlusPlus && SS.isSet() && 935 isCurrentClassName(*Name, S, &SS)) { 936 // Per [class.qual]p2, this names the constructors of SS, not the 937 // injected-class-name. We don't have a classification for that. 938 // There's not much point caching this result, since the parser 939 // will reject it later. 940 return NameClassification::Unknown(); 941 } 942 943 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 944 LookupParsedName(Result, S, &SS, !CurMethod); 945 946 if (SS.isInvalid()) 947 return NameClassification::Error(); 948 949 // For unqualified lookup in a class template in MSVC mode, look into 950 // dependent base classes where the primary class template is known. 951 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 952 if (ParsedType TypeInBase = 953 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 954 return TypeInBase; 955 } 956 957 // Perform lookup for Objective-C instance variables (including automatically 958 // synthesized instance variables), if we're in an Objective-C method. 959 // FIXME: This lookup really, really needs to be folded in to the normal 960 // unqualified lookup mechanism. 961 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 962 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 963 if (Ivar.isInvalid()) 964 return NameClassification::Error(); 965 if (Ivar.isUsable()) 966 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 967 968 // We defer builtin creation until after ivar lookup inside ObjC methods. 969 if (Result.empty()) 970 LookupBuiltin(Result); 971 } 972 973 bool SecondTry = false; 974 bool IsFilteredTemplateName = false; 975 976 Corrected: 977 switch (Result.getResultKind()) { 978 case LookupResult::NotFound: 979 // If an unqualified-id is followed by a '(', then we have a function 980 // call. 981 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 982 // In C++, this is an ADL-only call. 983 // FIXME: Reference? 984 if (getLangOpts().CPlusPlus) 985 return NameClassification::UndeclaredNonType(); 986 987 // C90 6.3.2.2: 988 // If the expression that precedes the parenthesized argument list in a 989 // function call consists solely of an identifier, and if no 990 // declaration is visible for this identifier, the identifier is 991 // implicitly declared exactly as if, in the innermost block containing 992 // the function call, the declaration 993 // 994 // extern int identifier (); 995 // 996 // appeared. 997 // 998 // We also allow this in C99 as an extension. However, this is not 999 // allowed in all language modes as functions without prototypes may not 1000 // be supported. 1001 if (getLangOpts().implicitFunctionsAllowed()) { 1002 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 1003 return NameClassification::NonType(D); 1004 } 1005 } 1006 1007 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 1008 // In C++20 onwards, this could be an ADL-only call to a function 1009 // template, and we're required to assume that this is a template name. 1010 // 1011 // FIXME: Find a way to still do typo correction in this case. 1012 TemplateName Template = 1013 Context.getAssumedTemplateName(NameInfo.getName()); 1014 return NameClassification::UndeclaredTemplate(Template); 1015 } 1016 1017 // In C, we first see whether there is a tag type by the same name, in 1018 // which case it's likely that the user just forgot to write "enum", 1019 // "struct", or "union". 1020 if (!getLangOpts().CPlusPlus && !SecondTry && 1021 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1022 break; 1023 } 1024 1025 // Perform typo correction to determine if there is another name that is 1026 // close to this name. 1027 if (!SecondTry && CCC) { 1028 SecondTry = true; 1029 if (TypoCorrection Corrected = 1030 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 1031 &SS, *CCC, CTK_ErrorRecovery)) { 1032 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 1033 unsigned QualifiedDiag = diag::err_no_member_suggest; 1034 1035 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 1036 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 1037 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1038 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 1039 UnqualifiedDiag = diag::err_no_template_suggest; 1040 QualifiedDiag = diag::err_no_member_template_suggest; 1041 } else if (UnderlyingFirstDecl && 1042 (isa<TypeDecl>(UnderlyingFirstDecl) || 1043 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 1044 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 1045 UnqualifiedDiag = diag::err_unknown_typename_suggest; 1046 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 1047 } 1048 1049 if (SS.isEmpty()) { 1050 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 1051 } else {// FIXME: is this even reachable? Test it. 1052 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1053 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 1054 Name->getName().equals(CorrectedStr); 1055 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 1056 << Name << computeDeclContext(SS, false) 1057 << DroppedSpecifier << SS.getRange()); 1058 } 1059 1060 // Update the name, so that the caller has the new name. 1061 Name = Corrected.getCorrectionAsIdentifierInfo(); 1062 1063 // Typo correction corrected to a keyword. 1064 if (Corrected.isKeyword()) 1065 return Name; 1066 1067 // Also update the LookupResult... 1068 // FIXME: This should probably go away at some point 1069 Result.clear(); 1070 Result.setLookupName(Corrected.getCorrection()); 1071 if (FirstDecl) 1072 Result.addDecl(FirstDecl); 1073 1074 // If we found an Objective-C instance variable, let 1075 // LookupInObjCMethod build the appropriate expression to 1076 // reference the ivar. 1077 // FIXME: This is a gross hack. 1078 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1079 DeclResult R = 1080 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1081 if (R.isInvalid()) 1082 return NameClassification::Error(); 1083 if (R.isUsable()) 1084 return NameClassification::NonType(Ivar); 1085 } 1086 1087 goto Corrected; 1088 } 1089 } 1090 1091 // We failed to correct; just fall through and let the parser deal with it. 1092 Result.suppressDiagnostics(); 1093 return NameClassification::Unknown(); 1094 1095 case LookupResult::NotFoundInCurrentInstantiation: { 1096 // We performed name lookup into the current instantiation, and there were 1097 // dependent bases, so we treat this result the same way as any other 1098 // dependent nested-name-specifier. 1099 1100 // C++ [temp.res]p2: 1101 // A name used in a template declaration or definition and that is 1102 // dependent on a template-parameter is assumed not to name a type 1103 // unless the applicable name lookup finds a type name or the name is 1104 // qualified by the keyword typename. 1105 // 1106 // FIXME: If the next token is '<', we might want to ask the parser to 1107 // perform some heroics to see if we actually have a 1108 // template-argument-list, which would indicate a missing 'template' 1109 // keyword here. 1110 return NameClassification::DependentNonType(); 1111 } 1112 1113 case LookupResult::Found: 1114 case LookupResult::FoundOverloaded: 1115 case LookupResult::FoundUnresolvedValue: 1116 break; 1117 1118 case LookupResult::Ambiguous: 1119 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1120 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1121 /*AllowDependent=*/false)) { 1122 // C++ [temp.local]p3: 1123 // A lookup that finds an injected-class-name (10.2) can result in an 1124 // ambiguity in certain cases (for example, if it is found in more than 1125 // one base class). If all of the injected-class-names that are found 1126 // refer to specializations of the same class template, and if the name 1127 // is followed by a template-argument-list, the reference refers to the 1128 // class template itself and not a specialization thereof, and is not 1129 // ambiguous. 1130 // 1131 // This filtering can make an ambiguous result into an unambiguous one, 1132 // so try again after filtering out template names. 1133 FilterAcceptableTemplateNames(Result); 1134 if (!Result.isAmbiguous()) { 1135 IsFilteredTemplateName = true; 1136 break; 1137 } 1138 } 1139 1140 // Diagnose the ambiguity and return an error. 1141 return NameClassification::Error(); 1142 } 1143 1144 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1145 (IsFilteredTemplateName || 1146 hasAnyAcceptableTemplateNames( 1147 Result, /*AllowFunctionTemplates=*/true, 1148 /*AllowDependent=*/false, 1149 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1150 getLangOpts().CPlusPlus20))) { 1151 // C++ [temp.names]p3: 1152 // After name lookup (3.4) finds that a name is a template-name or that 1153 // an operator-function-id or a literal- operator-id refers to a set of 1154 // overloaded functions any member of which is a function template if 1155 // this is followed by a <, the < is always taken as the delimiter of a 1156 // template-argument-list and never as the less-than operator. 1157 // C++2a [temp.names]p2: 1158 // A name is also considered to refer to a template if it is an 1159 // unqualified-id followed by a < and name lookup finds either one 1160 // or more functions or finds nothing. 1161 if (!IsFilteredTemplateName) 1162 FilterAcceptableTemplateNames(Result); 1163 1164 bool IsFunctionTemplate; 1165 bool IsVarTemplate; 1166 TemplateName Template; 1167 if (Result.end() - Result.begin() > 1) { 1168 IsFunctionTemplate = true; 1169 Template = Context.getOverloadedTemplateName(Result.begin(), 1170 Result.end()); 1171 } else if (!Result.empty()) { 1172 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1173 *Result.begin(), /*AllowFunctionTemplates=*/true, 1174 /*AllowDependent=*/false)); 1175 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1176 IsVarTemplate = isa<VarTemplateDecl>(TD); 1177 1178 UsingShadowDecl *FoundUsingShadow = 1179 dyn_cast<UsingShadowDecl>(*Result.begin()); 1180 assert(!FoundUsingShadow || 1181 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl())); 1182 Template = 1183 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); 1184 if (SS.isNotEmpty()) 1185 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1186 /*TemplateKeyword=*/false, 1187 Template); 1188 } else { 1189 // All results were non-template functions. This is a function template 1190 // name. 1191 IsFunctionTemplate = true; 1192 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1193 } 1194 1195 if (IsFunctionTemplate) { 1196 // Function templates always go through overload resolution, at which 1197 // point we'll perform the various checks (e.g., accessibility) we need 1198 // to based on which function we selected. 1199 Result.suppressDiagnostics(); 1200 1201 return NameClassification::FunctionTemplate(Template); 1202 } 1203 1204 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1205 : NameClassification::TypeTemplate(Template); 1206 } 1207 1208 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) { 1209 QualType T = Context.getTypeDeclType(Type); 1210 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) 1211 T = Context.getUsingType(USD, T); 1212 return buildNamedType(*this, &SS, T, NameLoc); 1213 }; 1214 1215 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1216 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1217 DiagnoseUseOfDecl(Type, NameLoc); 1218 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1219 return BuildTypeFor(Type, *Result.begin()); 1220 } 1221 1222 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1223 if (!Class) { 1224 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1225 if (ObjCCompatibleAliasDecl *Alias = 1226 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1227 Class = Alias->getClassInterface(); 1228 } 1229 1230 if (Class) { 1231 DiagnoseUseOfDecl(Class, NameLoc); 1232 1233 if (NextToken.is(tok::period)) { 1234 // Interface. <something> is parsed as a property reference expression. 1235 // Just return "unknown" as a fall-through for now. 1236 Result.suppressDiagnostics(); 1237 return NameClassification::Unknown(); 1238 } 1239 1240 QualType T = Context.getObjCInterfaceType(Class); 1241 return ParsedType::make(T); 1242 } 1243 1244 if (isa<ConceptDecl>(FirstDecl)) 1245 return NameClassification::Concept( 1246 TemplateName(cast<TemplateDecl>(FirstDecl))); 1247 1248 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { 1249 (void)DiagnoseUseOfDecl(EmptyD, NameLoc); 1250 return NameClassification::Error(); 1251 } 1252 1253 // We can have a type template here if we're classifying a template argument. 1254 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1255 !isa<VarTemplateDecl>(FirstDecl)) 1256 return NameClassification::TypeTemplate( 1257 TemplateName(cast<TemplateDecl>(FirstDecl))); 1258 1259 // Check for a tag type hidden by a non-type decl in a few cases where it 1260 // seems likely a type is wanted instead of the non-type that was found. 1261 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1262 if ((NextToken.is(tok::identifier) || 1263 (NextIsOp && 1264 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1265 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1266 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1267 DiagnoseUseOfDecl(Type, NameLoc); 1268 return BuildTypeFor(Type, *Result.begin()); 1269 } 1270 1271 // If we already know which single declaration is referenced, just annotate 1272 // that declaration directly. Defer resolving even non-overloaded class 1273 // member accesses, as we need to defer certain access checks until we know 1274 // the context. 1275 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1276 if (Result.isSingleResult() && !ADL && 1277 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl))) 1278 return NameClassification::NonType(Result.getRepresentativeDecl()); 1279 1280 // Otherwise, this is an overload set that we will need to resolve later. 1281 Result.suppressDiagnostics(); 1282 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1283 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1284 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1285 Result.begin(), Result.end())); 1286 } 1287 1288 ExprResult 1289 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1290 SourceLocation NameLoc) { 1291 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1292 CXXScopeSpec SS; 1293 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1294 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1295 } 1296 1297 ExprResult 1298 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1299 IdentifierInfo *Name, 1300 SourceLocation NameLoc, 1301 bool IsAddressOfOperand) { 1302 DeclarationNameInfo NameInfo(Name, NameLoc); 1303 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1304 NameInfo, IsAddressOfOperand, 1305 /*TemplateArgs=*/nullptr); 1306 } 1307 1308 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1309 NamedDecl *Found, 1310 SourceLocation NameLoc, 1311 const Token &NextToken) { 1312 if (getCurMethodDecl() && SS.isEmpty()) 1313 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1314 return BuildIvarRefExpr(S, NameLoc, Ivar); 1315 1316 // Reconstruct the lookup result. 1317 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1318 Result.addDecl(Found); 1319 Result.resolveKind(); 1320 1321 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1322 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true); 1323 } 1324 1325 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1326 // For an implicit class member access, transform the result into a member 1327 // access expression if necessary. 1328 auto *ULE = cast<UnresolvedLookupExpr>(E); 1329 if ((*ULE->decls_begin())->isCXXClassMember()) { 1330 CXXScopeSpec SS; 1331 SS.Adopt(ULE->getQualifierLoc()); 1332 1333 // Reconstruct the lookup result. 1334 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1335 LookupOrdinaryName); 1336 Result.setNamingClass(ULE->getNamingClass()); 1337 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1338 Result.addDecl(*I, I.getAccess()); 1339 Result.resolveKind(); 1340 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1341 nullptr, S); 1342 } 1343 1344 // Otherwise, this is already in the form we needed, and no further checks 1345 // are necessary. 1346 return ULE; 1347 } 1348 1349 Sema::TemplateNameKindForDiagnostics 1350 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1351 auto *TD = Name.getAsTemplateDecl(); 1352 if (!TD) 1353 return TemplateNameKindForDiagnostics::DependentTemplate; 1354 if (isa<ClassTemplateDecl>(TD)) 1355 return TemplateNameKindForDiagnostics::ClassTemplate; 1356 if (isa<FunctionTemplateDecl>(TD)) 1357 return TemplateNameKindForDiagnostics::FunctionTemplate; 1358 if (isa<VarTemplateDecl>(TD)) 1359 return TemplateNameKindForDiagnostics::VarTemplate; 1360 if (isa<TypeAliasTemplateDecl>(TD)) 1361 return TemplateNameKindForDiagnostics::AliasTemplate; 1362 if (isa<TemplateTemplateParmDecl>(TD)) 1363 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1364 if (isa<ConceptDecl>(TD)) 1365 return TemplateNameKindForDiagnostics::Concept; 1366 return TemplateNameKindForDiagnostics::DependentTemplate; 1367 } 1368 1369 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1370 assert(DC->getLexicalParent() == CurContext && 1371 "The next DeclContext should be lexically contained in the current one."); 1372 CurContext = DC; 1373 S->setEntity(DC); 1374 } 1375 1376 void Sema::PopDeclContext() { 1377 assert(CurContext && "DeclContext imbalance!"); 1378 1379 CurContext = CurContext->getLexicalParent(); 1380 assert(CurContext && "Popped translation unit!"); 1381 } 1382 1383 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1384 Decl *D) { 1385 // Unlike PushDeclContext, the context to which we return is not necessarily 1386 // the containing DC of TD, because the new context will be some pre-existing 1387 // TagDecl definition instead of a fresh one. 1388 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1389 CurContext = cast<TagDecl>(D)->getDefinition(); 1390 assert(CurContext && "skipping definition of undefined tag"); 1391 // Start lookups from the parent of the current context; we don't want to look 1392 // into the pre-existing complete definition. 1393 S->setEntity(CurContext->getLookupParent()); 1394 return Result; 1395 } 1396 1397 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1398 CurContext = static_cast<decltype(CurContext)>(Context); 1399 } 1400 1401 /// EnterDeclaratorContext - Used when we must lookup names in the context 1402 /// of a declarator's nested name specifier. 1403 /// 1404 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1405 // C++0x [basic.lookup.unqual]p13: 1406 // A name used in the definition of a static data member of class 1407 // X (after the qualified-id of the static member) is looked up as 1408 // if the name was used in a member function of X. 1409 // C++0x [basic.lookup.unqual]p14: 1410 // If a variable member of a namespace is defined outside of the 1411 // scope of its namespace then any name used in the definition of 1412 // the variable member (after the declarator-id) is looked up as 1413 // if the definition of the variable member occurred in its 1414 // namespace. 1415 // Both of these imply that we should push a scope whose context 1416 // is the semantic context of the declaration. We can't use 1417 // PushDeclContext here because that context is not necessarily 1418 // lexically contained in the current context. Fortunately, 1419 // the containing scope should have the appropriate information. 1420 1421 assert(!S->getEntity() && "scope already has entity"); 1422 1423 #ifndef NDEBUG 1424 Scope *Ancestor = S->getParent(); 1425 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1426 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1427 #endif 1428 1429 CurContext = DC; 1430 S->setEntity(DC); 1431 1432 if (S->getParent()->isTemplateParamScope()) { 1433 // Also set the corresponding entities for all immediately-enclosing 1434 // template parameter scopes. 1435 EnterTemplatedContext(S->getParent(), DC); 1436 } 1437 } 1438 1439 void Sema::ExitDeclaratorContext(Scope *S) { 1440 assert(S->getEntity() == CurContext && "Context imbalance!"); 1441 1442 // Switch back to the lexical context. The safety of this is 1443 // enforced by an assert in EnterDeclaratorContext. 1444 Scope *Ancestor = S->getParent(); 1445 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1446 CurContext = Ancestor->getEntity(); 1447 1448 // We don't need to do anything with the scope, which is going to 1449 // disappear. 1450 } 1451 1452 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1453 assert(S->isTemplateParamScope() && 1454 "expected to be initializing a template parameter scope"); 1455 1456 // C++20 [temp.local]p7: 1457 // In the definition of a member of a class template that appears outside 1458 // of the class template definition, the name of a member of the class 1459 // template hides the name of a template-parameter of any enclosing class 1460 // templates (but not a template-parameter of the member if the member is a 1461 // class or function template). 1462 // C++20 [temp.local]p9: 1463 // In the definition of a class template or in the definition of a member 1464 // of such a template that appears outside of the template definition, for 1465 // each non-dependent base class (13.8.2.1), if the name of the base class 1466 // or the name of a member of the base class is the same as the name of a 1467 // template-parameter, the base class name or member name hides the 1468 // template-parameter name (6.4.10). 1469 // 1470 // This means that a template parameter scope should be searched immediately 1471 // after searching the DeclContext for which it is a template parameter 1472 // scope. For example, for 1473 // template<typename T> template<typename U> template<typename V> 1474 // void N::A<T>::B<U>::f(...) 1475 // we search V then B<U> (and base classes) then U then A<T> (and base 1476 // classes) then T then N then ::. 1477 unsigned ScopeDepth = getTemplateDepth(S); 1478 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1479 DeclContext *SearchDCAfterScope = DC; 1480 for (; DC; DC = DC->getLookupParent()) { 1481 if (const TemplateParameterList *TPL = 1482 cast<Decl>(DC)->getDescribedTemplateParams()) { 1483 unsigned DCDepth = TPL->getDepth() + 1; 1484 if (DCDepth > ScopeDepth) 1485 continue; 1486 if (ScopeDepth == DCDepth) 1487 SearchDCAfterScope = DC = DC->getLookupParent(); 1488 break; 1489 } 1490 } 1491 S->setLookupEntity(SearchDCAfterScope); 1492 } 1493 } 1494 1495 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1496 // We assume that the caller has already called 1497 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1498 FunctionDecl *FD = D->getAsFunction(); 1499 if (!FD) 1500 return; 1501 1502 // Same implementation as PushDeclContext, but enters the context 1503 // from the lexical parent, rather than the top-level class. 1504 assert(CurContext == FD->getLexicalParent() && 1505 "The next DeclContext should be lexically contained in the current one."); 1506 CurContext = FD; 1507 S->setEntity(CurContext); 1508 1509 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1510 ParmVarDecl *Param = FD->getParamDecl(P); 1511 // If the parameter has an identifier, then add it to the scope 1512 if (Param->getIdentifier()) { 1513 S->AddDecl(Param); 1514 IdResolver.AddDecl(Param); 1515 } 1516 } 1517 } 1518 1519 void Sema::ActOnExitFunctionContext() { 1520 // Same implementation as PopDeclContext, but returns to the lexical parent, 1521 // rather than the top-level class. 1522 assert(CurContext && "DeclContext imbalance!"); 1523 CurContext = CurContext->getLexicalParent(); 1524 assert(CurContext && "Popped translation unit!"); 1525 } 1526 1527 /// Determine whether overloading is allowed for a new function 1528 /// declaration considering prior declarations of the same name. 1529 /// 1530 /// This routine determines whether overloading is possible, not 1531 /// whether a new declaration actually overloads a previous one. 1532 /// It will return true in C++ (where overloads are alway permitted) 1533 /// or, as a C extension, when either the new declaration or a 1534 /// previous one is declared with the 'overloadable' attribute. 1535 static bool AllowOverloadingOfFunction(const LookupResult &Previous, 1536 ASTContext &Context, 1537 const FunctionDecl *New) { 1538 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>()) 1539 return true; 1540 1541 // Multiversion function declarations are not overloads in the 1542 // usual sense of that term, but lookup will report that an 1543 // overload set was found if more than one multiversion function 1544 // declaration is present for the same name. It is therefore 1545 // inadequate to assume that some prior declaration(s) had 1546 // the overloadable attribute; checking is required. Since one 1547 // declaration is permitted to omit the attribute, it is necessary 1548 // to check at least two; hence the 'any_of' check below. Note that 1549 // the overloadable attribute is implicitly added to declarations 1550 // that were required to have it but did not. 1551 if (Previous.getResultKind() == LookupResult::FoundOverloaded) { 1552 return llvm::any_of(Previous, [](const NamedDecl *ND) { 1553 return ND->hasAttr<OverloadableAttr>(); 1554 }); 1555 } else if (Previous.getResultKind() == LookupResult::Found) 1556 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>(); 1557 1558 return false; 1559 } 1560 1561 /// Add this decl to the scope shadowed decl chains. 1562 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1563 // Move up the scope chain until we find the nearest enclosing 1564 // non-transparent context. The declaration will be introduced into this 1565 // scope. 1566 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1567 S = S->getParent(); 1568 1569 // Add scoped declarations into their context, so that they can be 1570 // found later. Declarations without a context won't be inserted 1571 // into any context. 1572 if (AddToContext) 1573 CurContext->addDecl(D); 1574 1575 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1576 // are function-local declarations. 1577 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1578 return; 1579 1580 // Template instantiations should also not be pushed into scope. 1581 if (isa<FunctionDecl>(D) && 1582 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1583 return; 1584 1585 // If this replaces anything in the current scope, 1586 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1587 IEnd = IdResolver.end(); 1588 for (; I != IEnd; ++I) { 1589 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1590 S->RemoveDecl(*I); 1591 IdResolver.RemoveDecl(*I); 1592 1593 // Should only need to replace one decl. 1594 break; 1595 } 1596 } 1597 1598 S->AddDecl(D); 1599 1600 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1601 // Implicitly-generated labels may end up getting generated in an order that 1602 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1603 // the label at the appropriate place in the identifier chain. 1604 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1605 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1606 if (IDC == CurContext) { 1607 if (!S->isDeclScope(*I)) 1608 continue; 1609 } else if (IDC->Encloses(CurContext)) 1610 break; 1611 } 1612 1613 IdResolver.InsertDeclAfter(I, D); 1614 } else { 1615 IdResolver.AddDecl(D); 1616 } 1617 warnOnReservedIdentifier(D); 1618 } 1619 1620 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1621 bool AllowInlineNamespace) const { 1622 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1623 } 1624 1625 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1626 DeclContext *TargetDC = DC->getPrimaryContext(); 1627 do { 1628 if (DeclContext *ScopeDC = S->getEntity()) 1629 if (ScopeDC->getPrimaryContext() == TargetDC) 1630 return S; 1631 } while ((S = S->getParent())); 1632 1633 return nullptr; 1634 } 1635 1636 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1637 DeclContext*, 1638 ASTContext&); 1639 1640 /// Filters out lookup results that don't fall within the given scope 1641 /// as determined by isDeclInScope. 1642 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1643 bool ConsiderLinkage, 1644 bool AllowInlineNamespace) { 1645 LookupResult::Filter F = R.makeFilter(); 1646 while (F.hasNext()) { 1647 NamedDecl *D = F.next(); 1648 1649 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1650 continue; 1651 1652 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1653 continue; 1654 1655 F.erase(); 1656 } 1657 1658 F.done(); 1659 } 1660 1661 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1662 /// have compatible owning modules. 1663 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1664 // [module.interface]p7: 1665 // A declaration is attached to a module as follows: 1666 // - If the declaration is a non-dependent friend declaration that nominates a 1667 // function with a declarator-id that is a qualified-id or template-id or that 1668 // nominates a class other than with an elaborated-type-specifier with neither 1669 // a nested-name-specifier nor a simple-template-id, it is attached to the 1670 // module to which the friend is attached ([basic.link]). 1671 if (New->getFriendObjectKind() && 1672 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1673 New->setLocalOwningModule(Old->getOwningModule()); 1674 makeMergedDefinitionVisible(New); 1675 return false; 1676 } 1677 1678 Module *NewM = New->getOwningModule(); 1679 Module *OldM = Old->getOwningModule(); 1680 1681 if (NewM && NewM->isPrivateModule()) 1682 NewM = NewM->Parent; 1683 if (OldM && OldM->isPrivateModule()) 1684 OldM = OldM->Parent; 1685 1686 if (NewM == OldM) 1687 return false; 1688 1689 if (NewM && OldM) { 1690 // A module implementation unit has visibility of the decls in its 1691 // implicitly imported interface. 1692 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface) 1693 return false; 1694 1695 // Partitions are part of the module, but a partition could import another 1696 // module, so verify that the PMIs agree. 1697 if ((NewM->isModulePartition() || OldM->isModulePartition()) && 1698 NewM->getPrimaryModuleInterfaceName() == 1699 OldM->getPrimaryModuleInterfaceName()) 1700 return false; 1701 } 1702 1703 bool NewIsModuleInterface = NewM && NewM->isNamedModule(); 1704 bool OldIsModuleInterface = OldM && OldM->isNamedModule(); 1705 if (NewIsModuleInterface || OldIsModuleInterface) { 1706 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1707 // if a declaration of D [...] appears in the purview of a module, all 1708 // other such declarations shall appear in the purview of the same module 1709 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1710 << New 1711 << NewIsModuleInterface 1712 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1713 << OldIsModuleInterface 1714 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1715 Diag(Old->getLocation(), diag::note_previous_declaration); 1716 New->setInvalidDecl(); 1717 return true; 1718 } 1719 1720 return false; 1721 } 1722 1723 // [module.interface]p6: 1724 // A redeclaration of an entity X is implicitly exported if X was introduced by 1725 // an exported declaration; otherwise it shall not be exported. 1726 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) { 1727 // [module.interface]p1: 1728 // An export-declaration shall inhabit a namespace scope. 1729 // 1730 // So it is meaningless to talk about redeclaration which is not at namespace 1731 // scope. 1732 if (!New->getLexicalDeclContext() 1733 ->getNonTransparentContext() 1734 ->isFileContext() || 1735 !Old->getLexicalDeclContext() 1736 ->getNonTransparentContext() 1737 ->isFileContext()) 1738 return false; 1739 1740 bool IsNewExported = New->isInExportDeclContext(); 1741 bool IsOldExported = Old->isInExportDeclContext(); 1742 1743 // It should be irrevelant if both of them are not exported. 1744 if (!IsNewExported && !IsOldExported) 1745 return false; 1746 1747 if (IsOldExported) 1748 return false; 1749 1750 assert(IsNewExported); 1751 1752 auto Lk = Old->getFormalLinkage(); 1753 int S = 0; 1754 if (Lk == Linkage::Internal) 1755 S = 1; 1756 else if (Lk == Linkage::Module) 1757 S = 2; 1758 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S; 1759 Diag(Old->getLocation(), diag::note_previous_declaration); 1760 return true; 1761 } 1762 1763 // A wrapper function for checking the semantic restrictions of 1764 // a redeclaration within a module. 1765 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) { 1766 if (CheckRedeclarationModuleOwnership(New, Old)) 1767 return true; 1768 1769 if (CheckRedeclarationExported(New, Old)) 1770 return true; 1771 1772 return false; 1773 } 1774 1775 // Check the redefinition in C++20 Modules. 1776 // 1777 // [basic.def.odr]p14: 1778 // For any definable item D with definitions in multiple translation units, 1779 // - if D is a non-inline non-templated function or variable, or 1780 // - if the definitions in different translation units do not satisfy the 1781 // following requirements, 1782 // the program is ill-formed; a diagnostic is required only if the definable 1783 // item is attached to a named module and a prior definition is reachable at 1784 // the point where a later definition occurs. 1785 // - Each such definition shall not be attached to a named module 1786 // ([module.unit]). 1787 // - Each such definition shall consist of the same sequence of tokens, ... 1788 // ... 1789 // 1790 // Return true if the redefinition is not allowed. Return false otherwise. 1791 bool Sema::IsRedefinitionInModule(const NamedDecl *New, 1792 const NamedDecl *Old) const { 1793 assert(getASTContext().isSameEntity(New, Old) && 1794 "New and Old are not the same definition, we should diagnostic it " 1795 "immediately instead of checking it."); 1796 assert(const_cast<Sema *>(this)->isReachable(New) && 1797 const_cast<Sema *>(this)->isReachable(Old) && 1798 "We shouldn't see unreachable definitions here."); 1799 1800 Module *NewM = New->getOwningModule(); 1801 Module *OldM = Old->getOwningModule(); 1802 1803 // We only checks for named modules here. The header like modules is skipped. 1804 // FIXME: This is not right if we import the header like modules in the module 1805 // purview. 1806 // 1807 // For example, assuming "header.h" provides definition for `D`. 1808 // ```C++ 1809 // //--- M.cppm 1810 // export module M; 1811 // import "header.h"; // or #include "header.h" but import it by clang modules 1812 // actually. 1813 // 1814 // //--- Use.cpp 1815 // import M; 1816 // import "header.h"; // or uses clang modules. 1817 // ``` 1818 // 1819 // In this case, `D` has multiple definitions in multiple TU (M.cppm and 1820 // Use.cpp) and `D` is attached to a named module `M`. The compiler should 1821 // reject it. But the current implementation couldn't detect the case since we 1822 // don't record the information about the importee modules. 1823 // 1824 // But this might not be painful in practice. Since the design of C++20 Named 1825 // Modules suggests us to use headers in global module fragment instead of 1826 // module purview. 1827 if (NewM && NewM->isHeaderLikeModule()) 1828 NewM = nullptr; 1829 if (OldM && OldM->isHeaderLikeModule()) 1830 OldM = nullptr; 1831 1832 if (!NewM && !OldM) 1833 return true; 1834 1835 // [basic.def.odr]p14.3 1836 // Each such definition shall not be attached to a named module 1837 // ([module.unit]). 1838 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule())) 1839 return true; 1840 1841 // Then New and Old lives in the same TU if their share one same module unit. 1842 if (NewM) 1843 NewM = NewM->getTopLevelModule(); 1844 if (OldM) 1845 OldM = OldM->getTopLevelModule(); 1846 return OldM == NewM; 1847 } 1848 1849 static bool isUsingDeclNotAtClassScope(NamedDecl *D) { 1850 if (D->getDeclContext()->isFileContext()) 1851 return false; 1852 1853 return isa<UsingShadowDecl>(D) || 1854 isa<UnresolvedUsingTypenameDecl>(D) || 1855 isa<UnresolvedUsingValueDecl>(D); 1856 } 1857 1858 /// Removes using shadow declarations not at class scope from the lookup 1859 /// results. 1860 static void RemoveUsingDecls(LookupResult &R) { 1861 LookupResult::Filter F = R.makeFilter(); 1862 while (F.hasNext()) 1863 if (isUsingDeclNotAtClassScope(F.next())) 1864 F.erase(); 1865 1866 F.done(); 1867 } 1868 1869 /// Check for this common pattern: 1870 /// @code 1871 /// class S { 1872 /// S(const S&); // DO NOT IMPLEMENT 1873 /// void operator=(const S&); // DO NOT IMPLEMENT 1874 /// }; 1875 /// @endcode 1876 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1877 // FIXME: Should check for private access too but access is set after we get 1878 // the decl here. 1879 if (D->doesThisDeclarationHaveABody()) 1880 return false; 1881 1882 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1883 return CD->isCopyConstructor(); 1884 return D->isCopyAssignmentOperator(); 1885 } 1886 1887 // We need this to handle 1888 // 1889 // typedef struct { 1890 // void *foo() { return 0; } 1891 // } A; 1892 // 1893 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1894 // for example. If 'A', foo will have external linkage. If we have '*A', 1895 // foo will have no linkage. Since we can't know until we get to the end 1896 // of the typedef, this function finds out if D might have non-external linkage. 1897 // Callers should verify at the end of the TU if it D has external linkage or 1898 // not. 1899 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1900 const DeclContext *DC = D->getDeclContext(); 1901 while (!DC->isTranslationUnit()) { 1902 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1903 if (!RD->hasNameForLinkage()) 1904 return true; 1905 } 1906 DC = DC->getParent(); 1907 } 1908 1909 return !D->isExternallyVisible(); 1910 } 1911 1912 // FIXME: This needs to be refactored; some other isInMainFile users want 1913 // these semantics. 1914 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1915 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile) 1916 return false; 1917 return S.SourceMgr.isInMainFile(Loc); 1918 } 1919 1920 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1921 assert(D); 1922 1923 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1924 return false; 1925 1926 // Ignore all entities declared within templates, and out-of-line definitions 1927 // of members of class templates. 1928 if (D->getDeclContext()->isDependentContext() || 1929 D->getLexicalDeclContext()->isDependentContext()) 1930 return false; 1931 1932 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1933 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1934 return false; 1935 // A non-out-of-line declaration of a member specialization was implicitly 1936 // instantiated; it's the out-of-line declaration that we're interested in. 1937 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1938 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1939 return false; 1940 1941 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1942 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1943 return false; 1944 } else { 1945 // 'static inline' functions are defined in headers; don't warn. 1946 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1947 return false; 1948 } 1949 1950 if (FD->doesThisDeclarationHaveABody() && 1951 Context.DeclMustBeEmitted(FD)) 1952 return false; 1953 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1954 // Constants and utility variables are defined in headers with internal 1955 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1956 // like "inline".) 1957 if (!isMainFileLoc(*this, VD->getLocation())) 1958 return false; 1959 1960 if (Context.DeclMustBeEmitted(VD)) 1961 return false; 1962 1963 if (VD->isStaticDataMember() && 1964 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1965 return false; 1966 if (VD->isStaticDataMember() && 1967 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1968 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1969 return false; 1970 1971 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1972 return false; 1973 } else { 1974 return false; 1975 } 1976 1977 // Only warn for unused decls internal to the translation unit. 1978 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1979 // for inline functions defined in the main source file, for instance. 1980 return mightHaveNonExternalLinkage(D); 1981 } 1982 1983 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1984 if (!D) 1985 return; 1986 1987 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1988 const FunctionDecl *First = FD->getFirstDecl(); 1989 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1990 return; // First should already be in the vector. 1991 } 1992 1993 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1994 const VarDecl *First = VD->getFirstDecl(); 1995 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1996 return; // First should already be in the vector. 1997 } 1998 1999 if (ShouldWarnIfUnusedFileScopedDecl(D)) 2000 UnusedFileScopedDecls.push_back(D); 2001 } 2002 2003 static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, 2004 const NamedDecl *D) { 2005 if (D->isInvalidDecl()) 2006 return false; 2007 2008 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) { 2009 // For a decomposition declaration, warn if none of the bindings are 2010 // referenced, instead of if the variable itself is referenced (which 2011 // it is, by the bindings' expressions). 2012 bool IsAllPlaceholders = true; 2013 for (const auto *BD : DD->bindings()) { 2014 if (BD->isReferenced()) 2015 return false; 2016 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts); 2017 } 2018 if (IsAllPlaceholders) 2019 return false; 2020 } else if (!D->getDeclName()) { 2021 return false; 2022 } else if (D->isReferenced() || D->isUsed()) { 2023 return false; 2024 } 2025 2026 if (D->isPlaceholderVar(LangOpts)) 2027 return false; 2028 2029 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() || 2030 D->hasAttr<CleanupAttr>()) 2031 return false; 2032 2033 if (isa<LabelDecl>(D)) 2034 return true; 2035 2036 // Except for labels, we only care about unused decls that are local to 2037 // functions. 2038 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 2039 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 2040 // For dependent types, the diagnostic is deferred. 2041 WithinFunction = 2042 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 2043 if (!WithinFunction) 2044 return false; 2045 2046 if (isa<TypedefNameDecl>(D)) 2047 return true; 2048 2049 // White-list anything that isn't a local variable. 2050 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 2051 return false; 2052 2053 // Types of valid local variables should be complete, so this should succeed. 2054 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2055 2056 const Expr *Init = VD->getInit(); 2057 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init)) 2058 Init = Cleanups->getSubExpr(); 2059 2060 const auto *Ty = VD->getType().getTypePtr(); 2061 2062 // Only look at the outermost level of typedef. 2063 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 2064 // Allow anything marked with __attribute__((unused)). 2065 if (TT->getDecl()->hasAttr<UnusedAttr>()) 2066 return false; 2067 } 2068 2069 // Warn for reference variables whose initializtion performs lifetime 2070 // extension. 2071 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init); 2072 MTE && MTE->getExtendingDecl()) { 2073 Ty = VD->getType().getNonReferenceType().getTypePtr(); 2074 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten(); 2075 } 2076 2077 // If we failed to complete the type for some reason, or if the type is 2078 // dependent, don't diagnose the variable. 2079 if (Ty->isIncompleteType() || Ty->isDependentType()) 2080 return false; 2081 2082 // Look at the element type to ensure that the warning behaviour is 2083 // consistent for both scalars and arrays. 2084 Ty = Ty->getBaseElementTypeUnsafe(); 2085 2086 if (const TagType *TT = Ty->getAs<TagType>()) { 2087 const TagDecl *Tag = TT->getDecl(); 2088 if (Tag->hasAttr<UnusedAttr>()) 2089 return false; 2090 2091 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 2092 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 2093 return false; 2094 2095 if (Init) { 2096 const auto *Construct = dyn_cast<CXXConstructExpr>(Init); 2097 if (Construct && !Construct->isElidable()) { 2098 const CXXConstructorDecl *CD = Construct->getConstructor(); 2099 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 2100 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 2101 return false; 2102 } 2103 2104 // Suppress the warning if we don't know how this is constructed, and 2105 // it could possibly be non-trivial constructor. 2106 if (Init->isTypeDependent()) { 2107 for (const CXXConstructorDecl *Ctor : RD->ctors()) 2108 if (!Ctor->isTrivial()) 2109 return false; 2110 } 2111 2112 // Suppress the warning if the constructor is unresolved because 2113 // its arguments are dependent. 2114 if (isa<CXXUnresolvedConstructExpr>(Init)) 2115 return false; 2116 } 2117 } 2118 } 2119 2120 // TODO: __attribute__((unused)) templates? 2121 } 2122 2123 return true; 2124 } 2125 2126 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 2127 FixItHint &Hint) { 2128 if (isa<LabelDecl>(D)) { 2129 SourceLocation AfterColon = Lexer::findLocationAfterToken( 2130 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 2131 /*SkipTrailingWhitespaceAndNewline=*/false); 2132 if (AfterColon.isInvalid()) 2133 return; 2134 Hint = FixItHint::CreateRemoval( 2135 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 2136 } 2137 } 2138 2139 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 2140 DiagnoseUnusedNestedTypedefs( 2141 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); }); 2142 } 2143 2144 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D, 2145 DiagReceiverTy DiagReceiver) { 2146 if (D->getTypeForDecl()->isDependentType()) 2147 return; 2148 2149 for (auto *TmpD : D->decls()) { 2150 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 2151 DiagnoseUnusedDecl(T, DiagReceiver); 2152 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 2153 DiagnoseUnusedNestedTypedefs(R, DiagReceiver); 2154 } 2155 } 2156 2157 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 2158 DiagnoseUnusedDecl( 2159 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); }); 2160 } 2161 2162 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 2163 /// unless they are marked attr(unused). 2164 void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) { 2165 if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D)) 2166 return; 2167 2168 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2169 // typedefs can be referenced later on, so the diagnostics are emitted 2170 // at end-of-translation-unit. 2171 UnusedLocalTypedefNameCandidates.insert(TD); 2172 return; 2173 } 2174 2175 FixItHint Hint; 2176 GenerateFixForUnusedDecl(D, Context, Hint); 2177 2178 unsigned DiagID; 2179 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 2180 DiagID = diag::warn_unused_exception_param; 2181 else if (isa<LabelDecl>(D)) 2182 DiagID = diag::warn_unused_label; 2183 else 2184 DiagID = diag::warn_unused_variable; 2185 2186 SourceLocation DiagLoc = D->getLocation(); 2187 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc)); 2188 } 2189 2190 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD, 2191 DiagReceiverTy DiagReceiver) { 2192 // If it's not referenced, it can't be set. If it has the Cleanup attribute, 2193 // it's not really unused. 2194 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>()) 2195 return; 2196 2197 // In C++, `_` variables behave as if they were maybe_unused 2198 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts())) 2199 return; 2200 2201 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 2202 2203 if (Ty->isReferenceType() || Ty->isDependentType()) 2204 return; 2205 2206 if (const TagType *TT = Ty->getAs<TagType>()) { 2207 const TagDecl *Tag = TT->getDecl(); 2208 if (Tag->hasAttr<UnusedAttr>()) 2209 return; 2210 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 2211 // mimic gcc's behavior. 2212 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag); 2213 RD && !RD->hasAttr<WarnUnusedAttr>()) 2214 return; 2215 } 2216 2217 // Don't warn about __block Objective-C pointer variables, as they might 2218 // be assigned in the block but not used elsewhere for the purpose of lifetime 2219 // extension. 2220 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) 2221 return; 2222 2223 // Don't warn about Objective-C pointer variables with precise lifetime 2224 // semantics; they can be used to ensure ARC releases the object at a known 2225 // time, which may mean assignment but no other references. 2226 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType()) 2227 return; 2228 2229 auto iter = RefsMinusAssignments.find(VD); 2230 if (iter == RefsMinusAssignments.end()) 2231 return; 2232 2233 assert(iter->getSecond() >= 0 && 2234 "Found a negative number of references to a VarDecl"); 2235 if (iter->getSecond() != 0) 2236 return; 2237 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 2238 : diag::warn_unused_but_set_variable; 2239 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD); 2240 } 2241 2242 static void CheckPoppedLabel(LabelDecl *L, Sema &S, 2243 Sema::DiagReceiverTy DiagReceiver) { 2244 // Verify that we have no forward references left. If so, there was a goto 2245 // or address of a label taken, but no definition of it. Label fwd 2246 // definitions are indicated with a null substmt which is also not a resolved 2247 // MS inline assembly label name. 2248 bool Diagnose = false; 2249 if (L->isMSAsmLabel()) 2250 Diagnose = !L->isResolvedMSAsmLabel(); 2251 else 2252 Diagnose = L->getStmt() == nullptr; 2253 if (Diagnose) 2254 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use) 2255 << L); 2256 } 2257 2258 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 2259 S->applyNRVO(); 2260 2261 if (S->decl_empty()) return; 2262 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 2263 "Scope shouldn't contain decls!"); 2264 2265 /// We visit the decls in non-deterministic order, but we want diagnostics 2266 /// emitted in deterministic order. Collect any diagnostic that may be emitted 2267 /// and sort the diagnostics before emitting them, after we visited all decls. 2268 struct LocAndDiag { 2269 SourceLocation Loc; 2270 std::optional<SourceLocation> PreviousDeclLoc; 2271 PartialDiagnostic PD; 2272 }; 2273 SmallVector<LocAndDiag, 16> DeclDiags; 2274 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) { 2275 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)}); 2276 }; 2277 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc, 2278 SourceLocation PreviousDeclLoc, 2279 PartialDiagnostic PD) { 2280 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)}); 2281 }; 2282 2283 for (auto *TmpD : S->decls()) { 2284 assert(TmpD && "This decl didn't get pushed??"); 2285 2286 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 2287 NamedDecl *D = cast<NamedDecl>(TmpD); 2288 2289 // Diagnose unused variables in this scope. 2290 if (!S->hasUnrecoverableErrorOccurred()) { 2291 DiagnoseUnusedDecl(D, addDiag); 2292 if (const auto *RD = dyn_cast<RecordDecl>(D)) 2293 DiagnoseUnusedNestedTypedefs(RD, addDiag); 2294 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2295 DiagnoseUnusedButSetDecl(VD, addDiag); 2296 RefsMinusAssignments.erase(VD); 2297 } 2298 } 2299 2300 if (!D->getDeclName()) continue; 2301 2302 // If this was a forward reference to a label, verify it was defined. 2303 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 2304 CheckPoppedLabel(LD, *this, addDiag); 2305 2306 // Remove this name from our lexical scope, and warn on it if we haven't 2307 // already. 2308 IdResolver.RemoveDecl(D); 2309 auto ShadowI = ShadowingDecls.find(D); 2310 if (ShadowI != ShadowingDecls.end()) { 2311 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2312 addDiagWithPrev(D->getLocation(), FD->getLocation(), 2313 PDiag(diag::warn_ctor_parm_shadows_field) 2314 << D << FD << FD->getParent()); 2315 } 2316 ShadowingDecls.erase(ShadowI); 2317 } 2318 } 2319 2320 llvm::sort(DeclDiags, 2321 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool { 2322 // The particular order for diagnostics is not important, as long 2323 // as the order is deterministic. Using the raw location is going 2324 // to generally be in source order unless there are macro 2325 // expansions involved. 2326 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding(); 2327 }); 2328 for (const LocAndDiag &D : DeclDiags) { 2329 Diag(D.Loc, D.PD); 2330 if (D.PreviousDeclLoc) 2331 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration); 2332 } 2333 } 2334 2335 /// Look for an Objective-C class in the translation unit. 2336 /// 2337 /// \param Id The name of the Objective-C class we're looking for. If 2338 /// typo-correction fixes this name, the Id will be updated 2339 /// to the fixed name. 2340 /// 2341 /// \param IdLoc The location of the name in the translation unit. 2342 /// 2343 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2344 /// if there is no class with the given name. 2345 /// 2346 /// \returns The declaration of the named Objective-C class, or NULL if the 2347 /// class could not be found. 2348 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2349 SourceLocation IdLoc, 2350 bool DoTypoCorrection) { 2351 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2352 // creation from this context. 2353 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2354 2355 if (!IDecl && DoTypoCorrection) { 2356 // Perform typo correction at the given location, but only if we 2357 // find an Objective-C class name. 2358 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2359 if (TypoCorrection C = 2360 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2361 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2362 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2363 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2364 Id = IDecl->getIdentifier(); 2365 } 2366 } 2367 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2368 // This routine must always return a class definition, if any. 2369 if (Def && Def->getDefinition()) 2370 Def = Def->getDefinition(); 2371 return Def; 2372 } 2373 2374 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2375 /// from S, where a non-field would be declared. This routine copes 2376 /// with the difference between C and C++ scoping rules in structs and 2377 /// unions. For example, the following code is well-formed in C but 2378 /// ill-formed in C++: 2379 /// @code 2380 /// struct S6 { 2381 /// enum { BAR } e; 2382 /// }; 2383 /// 2384 /// void test_S6() { 2385 /// struct S6 a; 2386 /// a.e = BAR; 2387 /// } 2388 /// @endcode 2389 /// For the declaration of BAR, this routine will return a different 2390 /// scope. The scope S will be the scope of the unnamed enumeration 2391 /// within S6. In C++, this routine will return the scope associated 2392 /// with S6, because the enumeration's scope is a transparent 2393 /// context but structures can contain non-field names. In C, this 2394 /// routine will return the translation unit scope, since the 2395 /// enumeration's scope is a transparent context and structures cannot 2396 /// contain non-field names. 2397 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2398 while (((S->getFlags() & Scope::DeclScope) == 0) || 2399 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2400 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2401 S = S->getParent(); 2402 return S; 2403 } 2404 2405 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2406 ASTContext::GetBuiltinTypeError Error) { 2407 switch (Error) { 2408 case ASTContext::GE_None: 2409 return ""; 2410 case ASTContext::GE_Missing_type: 2411 return BuiltinInfo.getHeaderName(ID); 2412 case ASTContext::GE_Missing_stdio: 2413 return "stdio.h"; 2414 case ASTContext::GE_Missing_setjmp: 2415 return "setjmp.h"; 2416 case ASTContext::GE_Missing_ucontext: 2417 return "ucontext.h"; 2418 } 2419 llvm_unreachable("unhandled error kind"); 2420 } 2421 2422 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2423 unsigned ID, SourceLocation Loc) { 2424 DeclContext *Parent = Context.getTranslationUnitDecl(); 2425 2426 if (getLangOpts().CPlusPlus) { 2427 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2428 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false); 2429 CLinkageDecl->setImplicit(); 2430 Parent->addDecl(CLinkageDecl); 2431 Parent = CLinkageDecl; 2432 } 2433 2434 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2435 /*TInfo=*/nullptr, SC_Extern, 2436 getCurFPFeatures().isFPConstrained(), 2437 false, Type->isFunctionProtoType()); 2438 New->setImplicit(); 2439 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2440 2441 // Create Decl objects for each parameter, adding them to the 2442 // FunctionDecl. 2443 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2444 SmallVector<ParmVarDecl *, 16> Params; 2445 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2446 ParmVarDecl *parm = ParmVarDecl::Create( 2447 Context, New, SourceLocation(), SourceLocation(), nullptr, 2448 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2449 parm->setScopeInfo(0, i); 2450 Params.push_back(parm); 2451 } 2452 New->setParams(Params); 2453 } 2454 2455 AddKnownFunctionAttributes(New); 2456 return New; 2457 } 2458 2459 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2460 /// file scope. lazily create a decl for it. ForRedeclaration is true 2461 /// if we're creating this built-in in anticipation of redeclaring the 2462 /// built-in. 2463 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2464 Scope *S, bool ForRedeclaration, 2465 SourceLocation Loc) { 2466 LookupNecessaryTypesForBuiltin(S, ID); 2467 2468 ASTContext::GetBuiltinTypeError Error; 2469 QualType R = Context.GetBuiltinType(ID, Error); 2470 if (Error) { 2471 if (!ForRedeclaration) 2472 return nullptr; 2473 2474 // If we have a builtin without an associated type we should not emit a 2475 // warning when we were not able to find a type for it. 2476 if (Error == ASTContext::GE_Missing_type || 2477 Context.BuiltinInfo.allowTypeMismatch(ID)) 2478 return nullptr; 2479 2480 // If we could not find a type for setjmp it is because the jmp_buf type was 2481 // not defined prior to the setjmp declaration. 2482 if (Error == ASTContext::GE_Missing_setjmp) { 2483 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2484 << Context.BuiltinInfo.getName(ID); 2485 return nullptr; 2486 } 2487 2488 // Generally, we emit a warning that the declaration requires the 2489 // appropriate header. 2490 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2491 << getHeaderName(Context.BuiltinInfo, ID, Error) 2492 << Context.BuiltinInfo.getName(ID); 2493 return nullptr; 2494 } 2495 2496 if (!ForRedeclaration && 2497 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2498 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2499 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99 2500 : diag::ext_implicit_lib_function_decl) 2501 << Context.BuiltinInfo.getName(ID) << R; 2502 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2503 Diag(Loc, diag::note_include_header_or_declare) 2504 << Header << Context.BuiltinInfo.getName(ID); 2505 } 2506 2507 if (R.isNull()) 2508 return nullptr; 2509 2510 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2511 RegisterLocallyScopedExternCDecl(New, S); 2512 2513 // TUScope is the translation-unit scope to insert this function into. 2514 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2515 // relate Scopes to DeclContexts, and probably eliminate CurContext 2516 // entirely, but we're not there yet. 2517 DeclContext *SavedContext = CurContext; 2518 CurContext = New->getDeclContext(); 2519 PushOnScopeChains(New, TUScope); 2520 CurContext = SavedContext; 2521 return New; 2522 } 2523 2524 /// Typedef declarations don't have linkage, but they still denote the same 2525 /// entity if their types are the same. 2526 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2527 /// isSameEntity. 2528 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2529 TypedefNameDecl *Decl, 2530 LookupResult &Previous) { 2531 // This is only interesting when modules are enabled. 2532 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2533 return; 2534 2535 // Empty sets are uninteresting. 2536 if (Previous.empty()) 2537 return; 2538 2539 LookupResult::Filter Filter = Previous.makeFilter(); 2540 while (Filter.hasNext()) { 2541 NamedDecl *Old = Filter.next(); 2542 2543 // Non-hidden declarations are never ignored. 2544 if (S.isVisible(Old)) 2545 continue; 2546 2547 // Declarations of the same entity are not ignored, even if they have 2548 // different linkages. 2549 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2550 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2551 Decl->getUnderlyingType())) 2552 continue; 2553 2554 // If both declarations give a tag declaration a typedef name for linkage 2555 // purposes, then they declare the same entity. 2556 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2557 Decl->getAnonDeclWithTypedefName()) 2558 continue; 2559 } 2560 2561 Filter.erase(); 2562 } 2563 2564 Filter.done(); 2565 } 2566 2567 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2568 QualType OldType; 2569 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2570 OldType = OldTypedef->getUnderlyingType(); 2571 else 2572 OldType = Context.getTypeDeclType(Old); 2573 QualType NewType = New->getUnderlyingType(); 2574 2575 if (NewType->isVariablyModifiedType()) { 2576 // Must not redefine a typedef with a variably-modified type. 2577 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2578 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2579 << Kind << NewType; 2580 if (Old->getLocation().isValid()) 2581 notePreviousDefinition(Old, New->getLocation()); 2582 New->setInvalidDecl(); 2583 return true; 2584 } 2585 2586 if (OldType != NewType && 2587 !OldType->isDependentType() && 2588 !NewType->isDependentType() && 2589 !Context.hasSameType(OldType, NewType)) { 2590 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2591 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2592 << Kind << NewType << OldType; 2593 if (Old->getLocation().isValid()) 2594 notePreviousDefinition(Old, New->getLocation()); 2595 New->setInvalidDecl(); 2596 return true; 2597 } 2598 return false; 2599 } 2600 2601 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2602 /// same name and scope as a previous declaration 'Old'. Figure out 2603 /// how to resolve this situation, merging decls or emitting 2604 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2605 /// 2606 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2607 LookupResult &OldDecls) { 2608 // If the new decl is known invalid already, don't bother doing any 2609 // merging checks. 2610 if (New->isInvalidDecl()) return; 2611 2612 // Allow multiple definitions for ObjC built-in typedefs. 2613 // FIXME: Verify the underlying types are equivalent! 2614 if (getLangOpts().ObjC) { 2615 const IdentifierInfo *TypeID = New->getIdentifier(); 2616 switch (TypeID->getLength()) { 2617 default: break; 2618 case 2: 2619 { 2620 if (!TypeID->isStr("id")) 2621 break; 2622 QualType T = New->getUnderlyingType(); 2623 if (!T->isPointerType()) 2624 break; 2625 if (!T->isVoidPointerType()) { 2626 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2627 if (!PT->isStructureType()) 2628 break; 2629 } 2630 Context.setObjCIdRedefinitionType(T); 2631 // Install the built-in type for 'id', ignoring the current definition. 2632 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2633 return; 2634 } 2635 case 5: 2636 if (!TypeID->isStr("Class")) 2637 break; 2638 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2639 // Install the built-in type for 'Class', ignoring the current definition. 2640 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2641 return; 2642 case 3: 2643 if (!TypeID->isStr("SEL")) 2644 break; 2645 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2646 // Install the built-in type for 'SEL', ignoring the current definition. 2647 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2648 return; 2649 } 2650 // Fall through - the typedef name was not a builtin type. 2651 } 2652 2653 // Verify the old decl was also a type. 2654 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2655 if (!Old) { 2656 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2657 << New->getDeclName(); 2658 2659 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2660 if (OldD->getLocation().isValid()) 2661 notePreviousDefinition(OldD, New->getLocation()); 2662 2663 return New->setInvalidDecl(); 2664 } 2665 2666 // If the old declaration is invalid, just give up here. 2667 if (Old->isInvalidDecl()) 2668 return New->setInvalidDecl(); 2669 2670 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2671 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2672 auto *NewTag = New->getAnonDeclWithTypedefName(); 2673 NamedDecl *Hidden = nullptr; 2674 if (OldTag && NewTag && 2675 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2676 !hasVisibleDefinition(OldTag, &Hidden)) { 2677 // There is a definition of this tag, but it is not visible. Use it 2678 // instead of our tag. 2679 New->setTypeForDecl(OldTD->getTypeForDecl()); 2680 if (OldTD->isModed()) 2681 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2682 OldTD->getUnderlyingType()); 2683 else 2684 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2685 2686 // Make the old tag definition visible. 2687 makeMergedDefinitionVisible(Hidden); 2688 2689 // If this was an unscoped enumeration, yank all of its enumerators 2690 // out of the scope. 2691 if (isa<EnumDecl>(NewTag)) { 2692 Scope *EnumScope = getNonFieldDeclScope(S); 2693 for (auto *D : NewTag->decls()) { 2694 auto *ED = cast<EnumConstantDecl>(D); 2695 assert(EnumScope->isDeclScope(ED)); 2696 EnumScope->RemoveDecl(ED); 2697 IdResolver.RemoveDecl(ED); 2698 ED->getLexicalDeclContext()->removeDecl(ED); 2699 } 2700 } 2701 } 2702 } 2703 2704 // If the typedef types are not identical, reject them in all languages and 2705 // with any extensions enabled. 2706 if (isIncompatibleTypedef(Old, New)) 2707 return; 2708 2709 // The types match. Link up the redeclaration chain and merge attributes if 2710 // the old declaration was a typedef. 2711 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2712 New->setPreviousDecl(Typedef); 2713 mergeDeclAttributes(New, Old); 2714 } 2715 2716 if (getLangOpts().MicrosoftExt) 2717 return; 2718 2719 if (getLangOpts().CPlusPlus) { 2720 // C++ [dcl.typedef]p2: 2721 // In a given non-class scope, a typedef specifier can be used to 2722 // redefine the name of any type declared in that scope to refer 2723 // to the type to which it already refers. 2724 if (!isa<CXXRecordDecl>(CurContext)) 2725 return; 2726 2727 // C++0x [dcl.typedef]p4: 2728 // In a given class scope, a typedef specifier can be used to redefine 2729 // any class-name declared in that scope that is not also a typedef-name 2730 // to refer to the type to which it already refers. 2731 // 2732 // This wording came in via DR424, which was a correction to the 2733 // wording in DR56, which accidentally banned code like: 2734 // 2735 // struct S { 2736 // typedef struct A { } A; 2737 // }; 2738 // 2739 // in the C++03 standard. We implement the C++0x semantics, which 2740 // allow the above but disallow 2741 // 2742 // struct S { 2743 // typedef int I; 2744 // typedef int I; 2745 // }; 2746 // 2747 // since that was the intent of DR56. 2748 if (!isa<TypedefNameDecl>(Old)) 2749 return; 2750 2751 Diag(New->getLocation(), diag::err_redefinition) 2752 << New->getDeclName(); 2753 notePreviousDefinition(Old, New->getLocation()); 2754 return New->setInvalidDecl(); 2755 } 2756 2757 // Modules always permit redefinition of typedefs, as does C11. 2758 if (getLangOpts().Modules || getLangOpts().C11) 2759 return; 2760 2761 // If we have a redefinition of a typedef in C, emit a warning. This warning 2762 // is normally mapped to an error, but can be controlled with 2763 // -Wtypedef-redefinition. If either the original or the redefinition is 2764 // in a system header, don't emit this for compatibility with GCC. 2765 if (getDiagnostics().getSuppressSystemWarnings() && 2766 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2767 (Old->isImplicit() || 2768 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2769 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2770 return; 2771 2772 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2773 << New->getDeclName(); 2774 notePreviousDefinition(Old, New->getLocation()); 2775 } 2776 2777 /// DeclhasAttr - returns true if decl Declaration already has the target 2778 /// attribute. 2779 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2780 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2781 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2782 for (const auto *i : D->attrs()) 2783 if (i->getKind() == A->getKind()) { 2784 if (Ann) { 2785 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2786 return true; 2787 continue; 2788 } 2789 // FIXME: Don't hardcode this check 2790 if (OA && isa<OwnershipAttr>(i)) 2791 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2792 return true; 2793 } 2794 2795 return false; 2796 } 2797 2798 static bool isAttributeTargetADefinition(Decl *D) { 2799 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2800 return VD->isThisDeclarationADefinition(); 2801 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2802 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2803 return true; 2804 } 2805 2806 /// Merge alignment attributes from \p Old to \p New, taking into account the 2807 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2808 /// 2809 /// \return \c true if any attributes were added to \p New. 2810 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2811 // Look for alignas attributes on Old, and pick out whichever attribute 2812 // specifies the strictest alignment requirement. 2813 AlignedAttr *OldAlignasAttr = nullptr; 2814 AlignedAttr *OldStrictestAlignAttr = nullptr; 2815 unsigned OldAlign = 0; 2816 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2817 // FIXME: We have no way of representing inherited dependent alignments 2818 // in a case like: 2819 // template<int A, int B> struct alignas(A) X; 2820 // template<int A, int B> struct alignas(B) X {}; 2821 // For now, we just ignore any alignas attributes which are not on the 2822 // definition in such a case. 2823 if (I->isAlignmentDependent()) 2824 return false; 2825 2826 if (I->isAlignas()) 2827 OldAlignasAttr = I; 2828 2829 unsigned Align = I->getAlignment(S.Context); 2830 if (Align > OldAlign) { 2831 OldAlign = Align; 2832 OldStrictestAlignAttr = I; 2833 } 2834 } 2835 2836 // Look for alignas attributes on New. 2837 AlignedAttr *NewAlignasAttr = nullptr; 2838 unsigned NewAlign = 0; 2839 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2840 if (I->isAlignmentDependent()) 2841 return false; 2842 2843 if (I->isAlignas()) 2844 NewAlignasAttr = I; 2845 2846 unsigned Align = I->getAlignment(S.Context); 2847 if (Align > NewAlign) 2848 NewAlign = Align; 2849 } 2850 2851 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2852 // Both declarations have 'alignas' attributes. We require them to match. 2853 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2854 // fall short. (If two declarations both have alignas, they must both match 2855 // every definition, and so must match each other if there is a definition.) 2856 2857 // If either declaration only contains 'alignas(0)' specifiers, then it 2858 // specifies the natural alignment for the type. 2859 if (OldAlign == 0 || NewAlign == 0) { 2860 QualType Ty; 2861 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2862 Ty = VD->getType(); 2863 else 2864 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2865 2866 if (OldAlign == 0) 2867 OldAlign = S.Context.getTypeAlign(Ty); 2868 if (NewAlign == 0) 2869 NewAlign = S.Context.getTypeAlign(Ty); 2870 } 2871 2872 if (OldAlign != NewAlign) { 2873 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2874 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2875 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2876 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2877 } 2878 } 2879 2880 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2881 // C++11 [dcl.align]p6: 2882 // if any declaration of an entity has an alignment-specifier, 2883 // every defining declaration of that entity shall specify an 2884 // equivalent alignment. 2885 // C11 6.7.5/7: 2886 // If the definition of an object does not have an alignment 2887 // specifier, any other declaration of that object shall also 2888 // have no alignment specifier. 2889 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2890 << OldAlignasAttr; 2891 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2892 << OldAlignasAttr; 2893 } 2894 2895 bool AnyAdded = false; 2896 2897 // Ensure we have an attribute representing the strictest alignment. 2898 if (OldAlign > NewAlign) { 2899 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2900 Clone->setInherited(true); 2901 New->addAttr(Clone); 2902 AnyAdded = true; 2903 } 2904 2905 // Ensure we have an alignas attribute if the old declaration had one. 2906 if (OldAlignasAttr && !NewAlignasAttr && 2907 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2908 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2909 Clone->setInherited(true); 2910 New->addAttr(Clone); 2911 AnyAdded = true; 2912 } 2913 2914 return AnyAdded; 2915 } 2916 2917 #define WANT_DECL_MERGE_LOGIC 2918 #include "clang/Sema/AttrParsedAttrImpl.inc" 2919 #undef WANT_DECL_MERGE_LOGIC 2920 2921 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2922 const InheritableAttr *Attr, 2923 Sema::AvailabilityMergeKind AMK) { 2924 // Diagnose any mutual exclusions between the attribute that we want to add 2925 // and attributes that already exist on the declaration. 2926 if (!DiagnoseMutualExclusions(S, D, Attr)) 2927 return false; 2928 2929 // This function copies an attribute Attr from a previous declaration to the 2930 // new declaration D if the new declaration doesn't itself have that attribute 2931 // yet or if that attribute allows duplicates. 2932 // If you're adding a new attribute that requires logic different from 2933 // "use explicit attribute on decl if present, else use attribute from 2934 // previous decl", for example if the attribute needs to be consistent 2935 // between redeclarations, you need to call a custom merge function here. 2936 InheritableAttr *NewAttr = nullptr; 2937 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2938 NewAttr = S.mergeAvailabilityAttr( 2939 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2940 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2941 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2942 AA->getPriority()); 2943 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2944 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2945 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2946 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2947 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2948 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2949 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2950 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2951 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2952 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2953 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2954 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2955 FA->getFirstArg()); 2956 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2957 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2958 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2959 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2960 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2961 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2962 IA->getInheritanceModel()); 2963 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2964 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2965 &S.Context.Idents.get(AA->getSpelling())); 2966 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2967 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2968 isa<CUDAGlobalAttr>(Attr))) { 2969 // CUDA target attributes are part of function signature for 2970 // overloading purposes and must not be merged. 2971 return false; 2972 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2973 NewAttr = S.mergeMinSizeAttr(D, *MA); 2974 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2975 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2976 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2977 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2978 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2979 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2980 else if (isa<AlignedAttr>(Attr)) 2981 // AlignedAttrs are handled separately, because we need to handle all 2982 // such attributes on a declaration at the same time. 2983 NewAttr = nullptr; 2984 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2985 (AMK == Sema::AMK_Override || 2986 AMK == Sema::AMK_ProtocolImplementation || 2987 AMK == Sema::AMK_OptionalProtocolImplementation)) 2988 NewAttr = nullptr; 2989 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2990 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2991 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2992 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2993 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2994 NewAttr = S.mergeImportNameAttr(D, *INA); 2995 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2996 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2997 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2998 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2999 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) 3000 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); 3001 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr)) 3002 NewAttr = 3003 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ()); 3004 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr)) 3005 NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType()); 3006 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 3007 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 3008 3009 if (NewAttr) { 3010 NewAttr->setInherited(true); 3011 D->addAttr(NewAttr); 3012 if (isa<MSInheritanceAttr>(NewAttr)) 3013 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 3014 return true; 3015 } 3016 3017 return false; 3018 } 3019 3020 static const NamedDecl *getDefinition(const Decl *D) { 3021 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 3022 return TD->getDefinition(); 3023 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 3024 const VarDecl *Def = VD->getDefinition(); 3025 if (Def) 3026 return Def; 3027 return VD->getActingDefinition(); 3028 } 3029 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 3030 const FunctionDecl *Def = nullptr; 3031 if (FD->isDefined(Def, true)) 3032 return Def; 3033 } 3034 return nullptr; 3035 } 3036 3037 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 3038 for (const auto *Attribute : D->attrs()) 3039 if (Attribute->getKind() == Kind) 3040 return true; 3041 return false; 3042 } 3043 3044 /// checkNewAttributesAfterDef - If we already have a definition, check that 3045 /// there are no new attributes in this declaration. 3046 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 3047 if (!New->hasAttrs()) 3048 return; 3049 3050 const NamedDecl *Def = getDefinition(Old); 3051 if (!Def || Def == New) 3052 return; 3053 3054 AttrVec &NewAttributes = New->getAttrs(); 3055 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 3056 const Attr *NewAttribute = NewAttributes[I]; 3057 3058 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 3059 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 3060 Sema::SkipBodyInfo SkipBody; 3061 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 3062 3063 // If we're skipping this definition, drop the "alias" attribute. 3064 if (SkipBody.ShouldSkip) { 3065 NewAttributes.erase(NewAttributes.begin() + I); 3066 --E; 3067 continue; 3068 } 3069 } else { 3070 VarDecl *VD = cast<VarDecl>(New); 3071 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 3072 VarDecl::TentativeDefinition 3073 ? diag::err_alias_after_tentative 3074 : diag::err_redefinition; 3075 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 3076 if (Diag == diag::err_redefinition) 3077 S.notePreviousDefinition(Def, VD->getLocation()); 3078 else 3079 S.Diag(Def->getLocation(), diag::note_previous_definition); 3080 VD->setInvalidDecl(); 3081 } 3082 ++I; 3083 continue; 3084 } 3085 3086 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 3087 // Tentative definitions are only interesting for the alias check above. 3088 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 3089 ++I; 3090 continue; 3091 } 3092 } 3093 3094 if (hasAttribute(Def, NewAttribute->getKind())) { 3095 ++I; 3096 continue; // regular attr merging will take care of validating this. 3097 } 3098 3099 if (isa<C11NoReturnAttr>(NewAttribute)) { 3100 // C's _Noreturn is allowed to be added to a function after it is defined. 3101 ++I; 3102 continue; 3103 } else if (isa<UuidAttr>(NewAttribute)) { 3104 // msvc will allow a subsequent definition to add an uuid to a class 3105 ++I; 3106 continue; 3107 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 3108 if (AA->isAlignas()) { 3109 // C++11 [dcl.align]p6: 3110 // if any declaration of an entity has an alignment-specifier, 3111 // every defining declaration of that entity shall specify an 3112 // equivalent alignment. 3113 // C11 6.7.5/7: 3114 // If the definition of an object does not have an alignment 3115 // specifier, any other declaration of that object shall also 3116 // have no alignment specifier. 3117 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 3118 << AA; 3119 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 3120 << AA; 3121 NewAttributes.erase(NewAttributes.begin() + I); 3122 --E; 3123 continue; 3124 } 3125 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 3126 // If there is a C definition followed by a redeclaration with this 3127 // attribute then there are two different definitions. In C++, prefer the 3128 // standard diagnostics. 3129 if (!S.getLangOpts().CPlusPlus) { 3130 S.Diag(NewAttribute->getLocation(), 3131 diag::err_loader_uninitialized_redeclaration); 3132 S.Diag(Def->getLocation(), diag::note_previous_definition); 3133 NewAttributes.erase(NewAttributes.begin() + I); 3134 --E; 3135 continue; 3136 } 3137 } else if (isa<SelectAnyAttr>(NewAttribute) && 3138 cast<VarDecl>(New)->isInline() && 3139 !cast<VarDecl>(New)->isInlineSpecified()) { 3140 // Don't warn about applying selectany to implicitly inline variables. 3141 // Older compilers and language modes would require the use of selectany 3142 // to make such variables inline, and it would have no effect if we 3143 // honored it. 3144 ++I; 3145 continue; 3146 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 3147 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 3148 // declarations after definitions. 3149 ++I; 3150 continue; 3151 } 3152 3153 S.Diag(NewAttribute->getLocation(), 3154 diag::warn_attribute_precede_definition); 3155 S.Diag(Def->getLocation(), diag::note_previous_definition); 3156 NewAttributes.erase(NewAttributes.begin() + I); 3157 --E; 3158 } 3159 } 3160 3161 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 3162 const ConstInitAttr *CIAttr, 3163 bool AttrBeforeInit) { 3164 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 3165 3166 // Figure out a good way to write this specifier on the old declaration. 3167 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 3168 // enough of the attribute list spelling information to extract that without 3169 // heroics. 3170 std::string SuitableSpelling; 3171 if (S.getLangOpts().CPlusPlus20) 3172 SuitableSpelling = std::string( 3173 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 3174 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 3175 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 3176 InsertLoc, {tok::l_square, tok::l_square, 3177 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 3178 S.PP.getIdentifierInfo("require_constant_initialization"), 3179 tok::r_square, tok::r_square})); 3180 if (SuitableSpelling.empty()) 3181 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 3182 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 3183 S.PP.getIdentifierInfo("require_constant_initialization"), 3184 tok::r_paren, tok::r_paren})); 3185 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 3186 SuitableSpelling = "constinit"; 3187 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 3188 SuitableSpelling = "[[clang::require_constant_initialization]]"; 3189 if (SuitableSpelling.empty()) 3190 SuitableSpelling = "__attribute__((require_constant_initialization))"; 3191 SuitableSpelling += " "; 3192 3193 if (AttrBeforeInit) { 3194 // extern constinit int a; 3195 // int a = 0; // error (missing 'constinit'), accepted as extension 3196 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 3197 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 3198 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3199 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 3200 } else { 3201 // int a = 0; 3202 // constinit extern int a; // error (missing 'constinit') 3203 S.Diag(CIAttr->getLocation(), 3204 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 3205 : diag::warn_require_const_init_added_too_late) 3206 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 3207 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 3208 << CIAttr->isConstinit() 3209 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3210 } 3211 } 3212 3213 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 3214 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 3215 AvailabilityMergeKind AMK) { 3216 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 3217 UsedAttr *NewAttr = OldAttr->clone(Context); 3218 NewAttr->setInherited(true); 3219 New->addAttr(NewAttr); 3220 } 3221 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 3222 RetainAttr *NewAttr = OldAttr->clone(Context); 3223 NewAttr->setInherited(true); 3224 New->addAttr(NewAttr); 3225 } 3226 3227 if (!Old->hasAttrs() && !New->hasAttrs()) 3228 return; 3229 3230 // [dcl.constinit]p1: 3231 // If the [constinit] specifier is applied to any declaration of a 3232 // variable, it shall be applied to the initializing declaration. 3233 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 3234 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 3235 if (bool(OldConstInit) != bool(NewConstInit)) { 3236 const auto *OldVD = cast<VarDecl>(Old); 3237 auto *NewVD = cast<VarDecl>(New); 3238 3239 // Find the initializing declaration. Note that we might not have linked 3240 // the new declaration into the redeclaration chain yet. 3241 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 3242 if (!InitDecl && 3243 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 3244 InitDecl = NewVD; 3245 3246 if (InitDecl == NewVD) { 3247 // This is the initializing declaration. If it would inherit 'constinit', 3248 // that's ill-formed. (Note that we do not apply this to the attribute 3249 // form). 3250 if (OldConstInit && OldConstInit->isConstinit()) 3251 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 3252 /*AttrBeforeInit=*/true); 3253 } else if (NewConstInit) { 3254 // This is the first time we've been told that this declaration should 3255 // have a constant initializer. If we already saw the initializing 3256 // declaration, this is too late. 3257 if (InitDecl && InitDecl != NewVD) { 3258 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 3259 /*AttrBeforeInit=*/false); 3260 NewVD->dropAttr<ConstInitAttr>(); 3261 } 3262 } 3263 } 3264 3265 // Attributes declared post-definition are currently ignored. 3266 checkNewAttributesAfterDef(*this, New, Old); 3267 3268 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 3269 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 3270 if (!OldA->isEquivalent(NewA)) { 3271 // This redeclaration changes __asm__ label. 3272 Diag(New->getLocation(), diag::err_different_asm_label); 3273 Diag(OldA->getLocation(), diag::note_previous_declaration); 3274 } 3275 } else if (Old->isUsed()) { 3276 // This redeclaration adds an __asm__ label to a declaration that has 3277 // already been ODR-used. 3278 Diag(New->getLocation(), diag::err_late_asm_label_name) 3279 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 3280 } 3281 } 3282 3283 // Re-declaration cannot add abi_tag's. 3284 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 3285 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 3286 for (const auto &NewTag : NewAbiTagAttr->tags()) { 3287 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { 3288 Diag(NewAbiTagAttr->getLocation(), 3289 diag::err_new_abi_tag_on_redeclaration) 3290 << NewTag; 3291 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 3292 } 3293 } 3294 } else { 3295 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 3296 Diag(Old->getLocation(), diag::note_previous_declaration); 3297 } 3298 } 3299 3300 // This redeclaration adds a section attribute. 3301 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 3302 if (auto *VD = dyn_cast<VarDecl>(New)) { 3303 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 3304 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 3305 Diag(Old->getLocation(), diag::note_previous_declaration); 3306 } 3307 } 3308 } 3309 3310 // Redeclaration adds code-seg attribute. 3311 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 3312 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 3313 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 3314 Diag(New->getLocation(), diag::warn_mismatched_section) 3315 << 0 /*codeseg*/; 3316 Diag(Old->getLocation(), diag::note_previous_declaration); 3317 } 3318 3319 if (!Old->hasAttrs()) 3320 return; 3321 3322 bool foundAny = New->hasAttrs(); 3323 3324 // Ensure that any moving of objects within the allocated map is done before 3325 // we process them. 3326 if (!foundAny) New->setAttrs(AttrVec()); 3327 3328 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3329 // Ignore deprecated/unavailable/availability attributes if requested. 3330 AvailabilityMergeKind LocalAMK = AMK_None; 3331 if (isa<DeprecatedAttr>(I) || 3332 isa<UnavailableAttr>(I) || 3333 isa<AvailabilityAttr>(I)) { 3334 switch (AMK) { 3335 case AMK_None: 3336 continue; 3337 3338 case AMK_Redeclaration: 3339 case AMK_Override: 3340 case AMK_ProtocolImplementation: 3341 case AMK_OptionalProtocolImplementation: 3342 LocalAMK = AMK; 3343 break; 3344 } 3345 } 3346 3347 // Already handled. 3348 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3349 continue; 3350 3351 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3352 foundAny = true; 3353 } 3354 3355 if (mergeAlignedAttrs(*this, New, Old)) 3356 foundAny = true; 3357 3358 if (!foundAny) New->dropAttrs(); 3359 } 3360 3361 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3362 /// to the new one. 3363 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3364 const ParmVarDecl *oldDecl, 3365 Sema &S) { 3366 // C++11 [dcl.attr.depend]p2: 3367 // The first declaration of a function shall specify the 3368 // carries_dependency attribute for its declarator-id if any declaration 3369 // of the function specifies the carries_dependency attribute. 3370 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3371 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3372 S.Diag(CDA->getLocation(), 3373 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3374 // Find the first declaration of the parameter. 3375 // FIXME: Should we build redeclaration chains for function parameters? 3376 const FunctionDecl *FirstFD = 3377 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3378 const ParmVarDecl *FirstVD = 3379 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3380 S.Diag(FirstVD->getLocation(), 3381 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3382 } 3383 3384 // HLSL parameter declarations for inout and out must match between 3385 // declarations. In HLSL inout and out are ambiguous at the call site, but 3386 // have different calling behavior, so you cannot overload a method based on a 3387 // difference between inout and out annotations. 3388 if (S.getLangOpts().HLSL) { 3389 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>(); 3390 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>(); 3391 // We don't need to cover the case where one declaration doesn't have an 3392 // attribute. The only possible case there is if one declaration has an `in` 3393 // attribute and the other declaration has no attribute. This case is 3394 // allowed since parameters are `in` by default. 3395 if (NDAttr && ODAttr && 3396 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) { 3397 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch) 3398 << NDAttr << newDecl; 3399 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as) 3400 << ODAttr; 3401 } 3402 } 3403 3404 if (!oldDecl->hasAttrs()) 3405 return; 3406 3407 bool foundAny = newDecl->hasAttrs(); 3408 3409 // Ensure that any moving of objects within the allocated map is 3410 // done before we process them. 3411 if (!foundAny) newDecl->setAttrs(AttrVec()); 3412 3413 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3414 if (!DeclHasAttr(newDecl, I)) { 3415 InheritableAttr *newAttr = 3416 cast<InheritableParamAttr>(I->clone(S.Context)); 3417 newAttr->setInherited(true); 3418 newDecl->addAttr(newAttr); 3419 foundAny = true; 3420 } 3421 } 3422 3423 if (!foundAny) newDecl->dropAttrs(); 3424 } 3425 3426 static bool EquivalentArrayTypes(QualType Old, QualType New, 3427 const ASTContext &Ctx) { 3428 3429 auto NoSizeInfo = [&Ctx](QualType Ty) { 3430 if (Ty->isIncompleteArrayType() || Ty->isPointerType()) 3431 return true; 3432 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty)) 3433 return VAT->getSizeModifier() == ArraySizeModifier::Star; 3434 return false; 3435 }; 3436 3437 // `type[]` is equivalent to `type *` and `type[*]`. 3438 if (NoSizeInfo(Old) && NoSizeInfo(New)) 3439 return true; 3440 3441 // Don't try to compare VLA sizes, unless one of them has the star modifier. 3442 if (Old->isVariableArrayType() && New->isVariableArrayType()) { 3443 const auto *OldVAT = Ctx.getAsVariableArrayType(Old); 3444 const auto *NewVAT = Ctx.getAsVariableArrayType(New); 3445 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^ 3446 (NewVAT->getSizeModifier() == ArraySizeModifier::Star)) 3447 return false; 3448 return true; 3449 } 3450 3451 // Only compare size, ignore Size modifiers and CVR. 3452 if (Old->isConstantArrayType() && New->isConstantArrayType()) { 3453 return Ctx.getAsConstantArrayType(Old)->getSize() == 3454 Ctx.getAsConstantArrayType(New)->getSize(); 3455 } 3456 3457 // Don't try to compare dependent sized array 3458 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) { 3459 return true; 3460 } 3461 3462 return Old == New; 3463 } 3464 3465 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3466 const ParmVarDecl *OldParam, 3467 Sema &S) { 3468 if (auto Oldnullability = OldParam->getType()->getNullability()) { 3469 if (auto Newnullability = NewParam->getType()->getNullability()) { 3470 if (*Oldnullability != *Newnullability) { 3471 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3472 << DiagNullabilityKind( 3473 *Newnullability, 3474 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3475 != 0)) 3476 << DiagNullabilityKind( 3477 *Oldnullability, 3478 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3479 != 0)); 3480 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3481 } 3482 } else { 3483 QualType NewT = NewParam->getType(); 3484 NewT = S.Context.getAttributedType( 3485 AttributedType::getNullabilityAttrKind(*Oldnullability), 3486 NewT, NewT); 3487 NewParam->setType(NewT); 3488 } 3489 } 3490 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType()); 3491 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType()); 3492 if (OldParamDT && NewParamDT && 3493 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) { 3494 QualType OldParamOT = OldParamDT->getOriginalType(); 3495 QualType NewParamOT = NewParamDT->getOriginalType(); 3496 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) { 3497 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form) 3498 << NewParam << NewParamOT; 3499 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as) 3500 << OldParamOT; 3501 } 3502 } 3503 } 3504 3505 namespace { 3506 3507 /// Used in MergeFunctionDecl to keep track of function parameters in 3508 /// C. 3509 struct GNUCompatibleParamWarning { 3510 ParmVarDecl *OldParm; 3511 ParmVarDecl *NewParm; 3512 QualType PromotedType; 3513 }; 3514 3515 } // end anonymous namespace 3516 3517 // Determine whether the previous declaration was a definition, implicit 3518 // declaration, or a declaration. 3519 template <typename T> 3520 static std::pair<diag::kind, SourceLocation> 3521 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3522 diag::kind PrevDiag; 3523 SourceLocation OldLocation = Old->getLocation(); 3524 if (Old->isThisDeclarationADefinition()) 3525 PrevDiag = diag::note_previous_definition; 3526 else if (Old->isImplicit()) { 3527 PrevDiag = diag::note_previous_implicit_declaration; 3528 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) { 3529 if (FD->getBuiltinID()) 3530 PrevDiag = diag::note_previous_builtin_declaration; 3531 } 3532 if (OldLocation.isInvalid()) 3533 OldLocation = New->getLocation(); 3534 } else 3535 PrevDiag = diag::note_previous_declaration; 3536 return std::make_pair(PrevDiag, OldLocation); 3537 } 3538 3539 /// canRedefineFunction - checks if a function can be redefined. Currently, 3540 /// only extern inline functions can be redefined, and even then only in 3541 /// GNU89 mode. 3542 static bool canRedefineFunction(const FunctionDecl *FD, 3543 const LangOptions& LangOpts) { 3544 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3545 !LangOpts.CPlusPlus && 3546 FD->isInlineSpecified() && 3547 FD->getStorageClass() == SC_Extern); 3548 } 3549 3550 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3551 const AttributedType *AT = T->getAs<AttributedType>(); 3552 while (AT && !AT->isCallingConv()) 3553 AT = AT->getModifiedType()->getAs<AttributedType>(); 3554 return AT; 3555 } 3556 3557 template <typename T> 3558 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3559 const DeclContext *DC = Old->getDeclContext(); 3560 if (DC->isRecord()) 3561 return false; 3562 3563 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3564 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3565 return true; 3566 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3567 return true; 3568 return false; 3569 } 3570 3571 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3572 static bool isExternC(VarTemplateDecl *) { return false; } 3573 static bool isExternC(FunctionTemplateDecl *) { return false; } 3574 3575 /// Check whether a redeclaration of an entity introduced by a 3576 /// using-declaration is valid, given that we know it's not an overload 3577 /// (nor a hidden tag declaration). 3578 template<typename ExpectedDecl> 3579 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3580 ExpectedDecl *New) { 3581 // C++11 [basic.scope.declarative]p4: 3582 // Given a set of declarations in a single declarative region, each of 3583 // which specifies the same unqualified name, 3584 // -- they shall all refer to the same entity, or all refer to functions 3585 // and function templates; or 3586 // -- exactly one declaration shall declare a class name or enumeration 3587 // name that is not a typedef name and the other declarations shall all 3588 // refer to the same variable or enumerator, or all refer to functions 3589 // and function templates; in this case the class name or enumeration 3590 // name is hidden (3.3.10). 3591 3592 // C++11 [namespace.udecl]p14: 3593 // If a function declaration in namespace scope or block scope has the 3594 // same name and the same parameter-type-list as a function introduced 3595 // by a using-declaration, and the declarations do not declare the same 3596 // function, the program is ill-formed. 3597 3598 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3599 if (Old && 3600 !Old->getDeclContext()->getRedeclContext()->Equals( 3601 New->getDeclContext()->getRedeclContext()) && 3602 !(isExternC(Old) && isExternC(New))) 3603 Old = nullptr; 3604 3605 if (!Old) { 3606 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3607 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3608 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3609 return true; 3610 } 3611 return false; 3612 } 3613 3614 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3615 const FunctionDecl *B) { 3616 assert(A->getNumParams() == B->getNumParams()); 3617 3618 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3619 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3620 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3621 if (AttrA == AttrB) 3622 return true; 3623 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3624 AttrA->isDynamic() == AttrB->isDynamic(); 3625 }; 3626 3627 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3628 } 3629 3630 /// If necessary, adjust the semantic declaration context for a qualified 3631 /// declaration to name the correct inline namespace within the qualifier. 3632 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3633 DeclaratorDecl *OldD) { 3634 // The only case where we need to update the DeclContext is when 3635 // redeclaration lookup for a qualified name finds a declaration 3636 // in an inline namespace within the context named by the qualifier: 3637 // 3638 // inline namespace N { int f(); } 3639 // int ::f(); // Sema DC needs adjusting from :: to N::. 3640 // 3641 // For unqualified declarations, the semantic context *can* change 3642 // along the redeclaration chain (for local extern declarations, 3643 // extern "C" declarations, and friend declarations in particular). 3644 if (!NewD->getQualifier()) 3645 return; 3646 3647 // NewD is probably already in the right context. 3648 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3649 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3650 if (NamedDC->Equals(SemaDC)) 3651 return; 3652 3653 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3654 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3655 "unexpected context for redeclaration"); 3656 3657 auto *LexDC = NewD->getLexicalDeclContext(); 3658 auto FixSemaDC = [=](NamedDecl *D) { 3659 if (!D) 3660 return; 3661 D->setDeclContext(SemaDC); 3662 D->setLexicalDeclContext(LexDC); 3663 }; 3664 3665 FixSemaDC(NewD); 3666 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3667 FixSemaDC(FD->getDescribedFunctionTemplate()); 3668 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3669 FixSemaDC(VD->getDescribedVarTemplate()); 3670 } 3671 3672 /// MergeFunctionDecl - We just parsed a function 'New' from 3673 /// declarator D which has the same name and scope as a previous 3674 /// declaration 'Old'. Figure out how to resolve this situation, 3675 /// merging decls or emitting diagnostics as appropriate. 3676 /// 3677 /// In C++, New and Old must be declarations that are not 3678 /// overloaded. Use IsOverload to determine whether New and Old are 3679 /// overloaded, and to select the Old declaration that New should be 3680 /// merged with. 3681 /// 3682 /// Returns true if there was an error, false otherwise. 3683 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S, 3684 bool MergeTypeWithOld, bool NewDeclIsDefn) { 3685 // Verify the old decl was also a function. 3686 FunctionDecl *Old = OldD->getAsFunction(); 3687 if (!Old) { 3688 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3689 if (New->getFriendObjectKind()) { 3690 Diag(New->getLocation(), diag::err_using_decl_friend); 3691 Diag(Shadow->getTargetDecl()->getLocation(), 3692 diag::note_using_decl_target); 3693 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3694 << 0; 3695 return true; 3696 } 3697 3698 // Check whether the two declarations might declare the same function or 3699 // function template. 3700 if (FunctionTemplateDecl *NewTemplate = 3701 New->getDescribedFunctionTemplate()) { 3702 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3703 NewTemplate)) 3704 return true; 3705 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3706 ->getAsFunction(); 3707 } else { 3708 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3709 return true; 3710 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3711 } 3712 } else { 3713 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3714 << New->getDeclName(); 3715 notePreviousDefinition(OldD, New->getLocation()); 3716 return true; 3717 } 3718 } 3719 3720 // If the old declaration was found in an inline namespace and the new 3721 // declaration was qualified, update the DeclContext to match. 3722 adjustDeclContextForDeclaratorDecl(New, Old); 3723 3724 // If the old declaration is invalid, just give up here. 3725 if (Old->isInvalidDecl()) 3726 return true; 3727 3728 // Disallow redeclaration of some builtins. 3729 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3730 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3731 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3732 << Old << Old->getType(); 3733 return true; 3734 } 3735 3736 diag::kind PrevDiag; 3737 SourceLocation OldLocation; 3738 std::tie(PrevDiag, OldLocation) = 3739 getNoteDiagForInvalidRedeclaration(Old, New); 3740 3741 // Don't complain about this if we're in GNU89 mode and the old function 3742 // is an extern inline function. 3743 // Don't complain about specializations. They are not supposed to have 3744 // storage classes. 3745 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3746 New->getStorageClass() == SC_Static && 3747 Old->hasExternalFormalLinkage() && 3748 !New->getTemplateSpecializationInfo() && 3749 !canRedefineFunction(Old, getLangOpts())) { 3750 if (getLangOpts().MicrosoftExt) { 3751 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3752 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3753 } else { 3754 Diag(New->getLocation(), diag::err_static_non_static) << New; 3755 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3756 return true; 3757 } 3758 } 3759 3760 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3761 if (!Old->hasAttr<InternalLinkageAttr>()) { 3762 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3763 << ILA; 3764 Diag(Old->getLocation(), diag::note_previous_declaration); 3765 New->dropAttr<InternalLinkageAttr>(); 3766 } 3767 3768 if (auto *EA = New->getAttr<ErrorAttr>()) { 3769 if (!Old->hasAttr<ErrorAttr>()) { 3770 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3771 Diag(Old->getLocation(), diag::note_previous_declaration); 3772 New->dropAttr<ErrorAttr>(); 3773 } 3774 } 3775 3776 if (CheckRedeclarationInModule(New, Old)) 3777 return true; 3778 3779 if (!getLangOpts().CPlusPlus) { 3780 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3781 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3782 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3783 << New << OldOvl; 3784 3785 // Try our best to find a decl that actually has the overloadable 3786 // attribute for the note. In most cases (e.g. programs with only one 3787 // broken declaration/definition), this won't matter. 3788 // 3789 // FIXME: We could do this if we juggled some extra state in 3790 // OverloadableAttr, rather than just removing it. 3791 const Decl *DiagOld = Old; 3792 if (OldOvl) { 3793 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3794 const auto *A = D->getAttr<OverloadableAttr>(); 3795 return A && !A->isImplicit(); 3796 }); 3797 // If we've implicitly added *all* of the overloadable attrs to this 3798 // chain, emitting a "previous redecl" note is pointless. 3799 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3800 } 3801 3802 if (DiagOld) 3803 Diag(DiagOld->getLocation(), 3804 diag::note_attribute_overloadable_prev_overload) 3805 << OldOvl; 3806 3807 if (OldOvl) 3808 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3809 else 3810 New->dropAttr<OverloadableAttr>(); 3811 } 3812 } 3813 3814 // It is not permitted to redeclare an SME function with different SME 3815 // attributes. 3816 if (IsInvalidSMECallConversion(Old->getType(), New->getType(), 3817 AArch64SMECallConversionKind::MatchExactly)) { 3818 Diag(New->getLocation(), diag::err_sme_attr_mismatch) 3819 << New->getType() << Old->getType(); 3820 Diag(OldLocation, diag::note_previous_declaration); 3821 return true; 3822 } 3823 3824 // If a function is first declared with a calling convention, but is later 3825 // declared or defined without one, all following decls assume the calling 3826 // convention of the first. 3827 // 3828 // It's OK if a function is first declared without a calling convention, 3829 // but is later declared or defined with the default calling convention. 3830 // 3831 // To test if either decl has an explicit calling convention, we look for 3832 // AttributedType sugar nodes on the type as written. If they are missing or 3833 // were canonicalized away, we assume the calling convention was implicit. 3834 // 3835 // Note also that we DO NOT return at this point, because we still have 3836 // other tests to run. 3837 QualType OldQType = Context.getCanonicalType(Old->getType()); 3838 QualType NewQType = Context.getCanonicalType(New->getType()); 3839 const FunctionType *OldType = cast<FunctionType>(OldQType); 3840 const FunctionType *NewType = cast<FunctionType>(NewQType); 3841 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3842 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3843 bool RequiresAdjustment = false; 3844 3845 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3846 FunctionDecl *First = Old->getFirstDecl(); 3847 const FunctionType *FT = 3848 First->getType().getCanonicalType()->castAs<FunctionType>(); 3849 FunctionType::ExtInfo FI = FT->getExtInfo(); 3850 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3851 if (!NewCCExplicit) { 3852 // Inherit the CC from the previous declaration if it was specified 3853 // there but not here. 3854 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3855 RequiresAdjustment = true; 3856 } else if (Old->getBuiltinID()) { 3857 // Builtin attribute isn't propagated to the new one yet at this point, 3858 // so we check if the old one is a builtin. 3859 3860 // Calling Conventions on a Builtin aren't really useful and setting a 3861 // default calling convention and cdecl'ing some builtin redeclarations is 3862 // common, so warn and ignore the calling convention on the redeclaration. 3863 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3864 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3865 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3866 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3867 RequiresAdjustment = true; 3868 } else { 3869 // Calling conventions aren't compatible, so complain. 3870 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3871 Diag(New->getLocation(), diag::err_cconv_change) 3872 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3873 << !FirstCCExplicit 3874 << (!FirstCCExplicit ? "" : 3875 FunctionType::getNameForCallConv(FI.getCC())); 3876 3877 // Put the note on the first decl, since it is the one that matters. 3878 Diag(First->getLocation(), diag::note_previous_declaration); 3879 return true; 3880 } 3881 } 3882 3883 // FIXME: diagnose the other way around? 3884 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3885 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3886 RequiresAdjustment = true; 3887 } 3888 3889 // Merge regparm attribute. 3890 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3891 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3892 if (NewTypeInfo.getHasRegParm()) { 3893 Diag(New->getLocation(), diag::err_regparm_mismatch) 3894 << NewType->getRegParmType() 3895 << OldType->getRegParmType(); 3896 Diag(OldLocation, diag::note_previous_declaration); 3897 return true; 3898 } 3899 3900 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3901 RequiresAdjustment = true; 3902 } 3903 3904 // Merge ns_returns_retained attribute. 3905 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3906 if (NewTypeInfo.getProducesResult()) { 3907 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3908 << "'ns_returns_retained'"; 3909 Diag(OldLocation, diag::note_previous_declaration); 3910 return true; 3911 } 3912 3913 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3914 RequiresAdjustment = true; 3915 } 3916 3917 if (OldTypeInfo.getNoCallerSavedRegs() != 3918 NewTypeInfo.getNoCallerSavedRegs()) { 3919 if (NewTypeInfo.getNoCallerSavedRegs()) { 3920 AnyX86NoCallerSavedRegistersAttr *Attr = 3921 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3922 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3923 Diag(OldLocation, diag::note_previous_declaration); 3924 return true; 3925 } 3926 3927 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3928 RequiresAdjustment = true; 3929 } 3930 3931 if (RequiresAdjustment) { 3932 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3933 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3934 New->setType(QualType(AdjustedType, 0)); 3935 NewQType = Context.getCanonicalType(New->getType()); 3936 } 3937 3938 // If this redeclaration makes the function inline, we may need to add it to 3939 // UndefinedButUsed. 3940 if (!Old->isInlined() && New->isInlined() && 3941 !New->hasAttr<GNUInlineAttr>() && 3942 !getLangOpts().GNUInline && 3943 Old->isUsed(false) && 3944 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3945 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3946 SourceLocation())); 3947 3948 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3949 // about it. 3950 if (New->hasAttr<GNUInlineAttr>() && 3951 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3952 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3953 } 3954 3955 // If pass_object_size params don't match up perfectly, this isn't a valid 3956 // redeclaration. 3957 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3958 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3959 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3960 << New->getDeclName(); 3961 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3962 return true; 3963 } 3964 3965 if (getLangOpts().CPlusPlus) { 3966 OldQType = Context.getCanonicalType(Old->getType()); 3967 NewQType = Context.getCanonicalType(New->getType()); 3968 3969 // Go back to the type source info to compare the declared return types, 3970 // per C++1y [dcl.type.auto]p13: 3971 // Redeclarations or specializations of a function or function template 3972 // with a declared return type that uses a placeholder type shall also 3973 // use that placeholder, not a deduced type. 3974 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3975 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3976 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3977 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3978 OldDeclaredReturnType)) { 3979 QualType ResQT; 3980 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3981 OldDeclaredReturnType->isObjCObjectPointerType()) 3982 // FIXME: This does the wrong thing for a deduced return type. 3983 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3984 if (ResQT.isNull()) { 3985 if (New->isCXXClassMember() && New->isOutOfLine()) 3986 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3987 << New << New->getReturnTypeSourceRange(); 3988 else 3989 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3990 << New->getReturnTypeSourceRange(); 3991 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3992 << Old->getReturnTypeSourceRange(); 3993 return true; 3994 } 3995 else 3996 NewQType = ResQT; 3997 } 3998 3999 QualType OldReturnType = OldType->getReturnType(); 4000 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 4001 if (OldReturnType != NewReturnType) { 4002 // If this function has a deduced return type and has already been 4003 // defined, copy the deduced value from the old declaration. 4004 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 4005 if (OldAT && OldAT->isDeduced()) { 4006 QualType DT = OldAT->getDeducedType(); 4007 if (DT.isNull()) { 4008 New->setType(SubstAutoTypeDependent(New->getType())); 4009 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); 4010 } else { 4011 New->setType(SubstAutoType(New->getType(), DT)); 4012 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); 4013 } 4014 } 4015 } 4016 4017 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 4018 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 4019 if (OldMethod && NewMethod) { 4020 // Preserve triviality. 4021 NewMethod->setTrivial(OldMethod->isTrivial()); 4022 4023 // MSVC allows explicit template specialization at class scope: 4024 // 2 CXXMethodDecls referring to the same function will be injected. 4025 // We don't want a redeclaration error. 4026 bool IsClassScopeExplicitSpecialization = 4027 OldMethod->isFunctionTemplateSpecialization() && 4028 NewMethod->isFunctionTemplateSpecialization(); 4029 bool isFriend = NewMethod->getFriendObjectKind(); 4030 4031 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 4032 !IsClassScopeExplicitSpecialization) { 4033 // -- Member function declarations with the same name and the 4034 // same parameter types cannot be overloaded if any of them 4035 // is a static member function declaration. 4036 if (OldMethod->isStatic() != NewMethod->isStatic()) { 4037 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 4038 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4039 return true; 4040 } 4041 4042 // C++ [class.mem]p1: 4043 // [...] A member shall not be declared twice in the 4044 // member-specification, except that a nested class or member 4045 // class template can be declared and then later defined. 4046 if (!inTemplateInstantiation()) { 4047 unsigned NewDiag; 4048 if (isa<CXXConstructorDecl>(OldMethod)) 4049 NewDiag = diag::err_constructor_redeclared; 4050 else if (isa<CXXDestructorDecl>(NewMethod)) 4051 NewDiag = diag::err_destructor_redeclared; 4052 else if (isa<CXXConversionDecl>(NewMethod)) 4053 NewDiag = diag::err_conv_function_redeclared; 4054 else 4055 NewDiag = diag::err_member_redeclared; 4056 4057 Diag(New->getLocation(), NewDiag); 4058 } else { 4059 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 4060 << New << New->getType(); 4061 } 4062 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4063 return true; 4064 4065 // Complain if this is an explicit declaration of a special 4066 // member that was initially declared implicitly. 4067 // 4068 // As an exception, it's okay to befriend such methods in order 4069 // to permit the implicit constructor/destructor/operator calls. 4070 } else if (OldMethod->isImplicit()) { 4071 if (isFriend) { 4072 NewMethod->setImplicit(); 4073 } else { 4074 Diag(NewMethod->getLocation(), 4075 diag::err_definition_of_implicitly_declared_member) 4076 << New << getSpecialMember(OldMethod); 4077 return true; 4078 } 4079 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 4080 Diag(NewMethod->getLocation(), 4081 diag::err_definition_of_explicitly_defaulted_member) 4082 << getSpecialMember(OldMethod); 4083 return true; 4084 } 4085 } 4086 4087 // C++1z [over.load]p2 4088 // Certain function declarations cannot be overloaded: 4089 // -- Function declarations that differ only in the return type, 4090 // the exception specification, or both cannot be overloaded. 4091 4092 // Check the exception specifications match. This may recompute the type of 4093 // both Old and New if it resolved exception specifications, so grab the 4094 // types again after this. Because this updates the type, we do this before 4095 // any of the other checks below, which may update the "de facto" NewQType 4096 // but do not necessarily update the type of New. 4097 if (CheckEquivalentExceptionSpec(Old, New)) 4098 return true; 4099 4100 // C++11 [dcl.attr.noreturn]p1: 4101 // The first declaration of a function shall specify the noreturn 4102 // attribute if any declaration of that function specifies the noreturn 4103 // attribute. 4104 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 4105 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 4106 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 4107 << NRA; 4108 Diag(Old->getLocation(), diag::note_previous_declaration); 4109 } 4110 4111 // C++11 [dcl.attr.depend]p2: 4112 // The first declaration of a function shall specify the 4113 // carries_dependency attribute for its declarator-id if any declaration 4114 // of the function specifies the carries_dependency attribute. 4115 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 4116 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 4117 Diag(CDA->getLocation(), 4118 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 4119 Diag(Old->getFirstDecl()->getLocation(), 4120 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 4121 } 4122 4123 // (C++98 8.3.5p3): 4124 // All declarations for a function shall agree exactly in both the 4125 // return type and the parameter-type-list. 4126 // We also want to respect all the extended bits except noreturn. 4127 4128 // noreturn should now match unless the old type info didn't have it. 4129 QualType OldQTypeForComparison = OldQType; 4130 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 4131 auto *OldType = OldQType->castAs<FunctionProtoType>(); 4132 const FunctionType *OldTypeForComparison 4133 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 4134 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 4135 assert(OldQTypeForComparison.isCanonical()); 4136 } 4137 4138 if (haveIncompatibleLanguageLinkages(Old, New)) { 4139 // As a special case, retain the language linkage from previous 4140 // declarations of a friend function as an extension. 4141 // 4142 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 4143 // and is useful because there's otherwise no way to specify language 4144 // linkage within class scope. 4145 // 4146 // Check cautiously as the friend object kind isn't yet complete. 4147 if (New->getFriendObjectKind() != Decl::FOK_None) { 4148 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 4149 Diag(OldLocation, PrevDiag); 4150 } else { 4151 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4152 Diag(OldLocation, PrevDiag); 4153 return true; 4154 } 4155 } 4156 4157 // If the function types are compatible, merge the declarations. Ignore the 4158 // exception specifier because it was already checked above in 4159 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 4160 // about incompatible types under -fms-compatibility. 4161 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 4162 NewQType)) 4163 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4164 4165 // If the types are imprecise (due to dependent constructs in friends or 4166 // local extern declarations), it's OK if they differ. We'll check again 4167 // during instantiation. 4168 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 4169 return false; 4170 4171 // Fall through for conflicting redeclarations and redefinitions. 4172 } 4173 4174 // C: Function types need to be compatible, not identical. This handles 4175 // duplicate function decls like "void f(int); void f(enum X);" properly. 4176 if (!getLangOpts().CPlusPlus) { 4177 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other 4178 // type is specified by a function definition that contains a (possibly 4179 // empty) identifier list, both shall agree in the number of parameters 4180 // and the type of each parameter shall be compatible with the type that 4181 // results from the application of default argument promotions to the 4182 // type of the corresponding identifier. ... 4183 // This cannot be handled by ASTContext::typesAreCompatible() because that 4184 // doesn't know whether the function type is for a definition or not when 4185 // eventually calling ASTContext::mergeFunctionTypes(). The only situation 4186 // we need to cover here is that the number of arguments agree as the 4187 // default argument promotion rules were already checked by 4188 // ASTContext::typesAreCompatible(). 4189 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn && 4190 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) { 4191 if (Old->hasInheritedPrototype()) 4192 Old = Old->getCanonicalDecl(); 4193 Diag(New->getLocation(), diag::err_conflicting_types) << New; 4194 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 4195 return true; 4196 } 4197 4198 // If we are merging two functions where only one of them has a prototype, 4199 // we may have enough information to decide to issue a diagnostic that the 4200 // function without a protoype will change behavior in C23. This handles 4201 // cases like: 4202 // void i(); void i(int j); 4203 // void i(int j); void i(); 4204 // void i(); void i(int j) {} 4205 // See ActOnFinishFunctionBody() for other cases of the behavior change 4206 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 4207 // type without a prototype. 4208 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() && 4209 !New->isImplicit() && !Old->isImplicit()) { 4210 const FunctionDecl *WithProto, *WithoutProto; 4211 if (New->hasWrittenPrototype()) { 4212 WithProto = New; 4213 WithoutProto = Old; 4214 } else { 4215 WithProto = Old; 4216 WithoutProto = New; 4217 } 4218 4219 if (WithProto->getNumParams() != 0) { 4220 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) { 4221 // The one without the prototype will be changing behavior in C23, so 4222 // warn about that one so long as it's a user-visible declaration. 4223 bool IsWithoutProtoADef = false, IsWithProtoADef = false; 4224 if (WithoutProto == New) 4225 IsWithoutProtoADef = NewDeclIsDefn; 4226 else 4227 IsWithProtoADef = NewDeclIsDefn; 4228 Diag(WithoutProto->getLocation(), 4229 diag::warn_non_prototype_changes_behavior) 4230 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1) 4231 << (WithoutProto == Old) << IsWithProtoADef; 4232 4233 // The reason the one without the prototype will be changing behavior 4234 // is because of the one with the prototype, so note that so long as 4235 // it's a user-visible declaration. There is one exception to this: 4236 // when the new declaration is a definition without a prototype, the 4237 // old declaration with a prototype is not the cause of the issue, 4238 // and that does not need to be noted because the one with a 4239 // prototype will not change behavior in C23. 4240 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() && 4241 !IsWithoutProtoADef) 4242 Diag(WithProto->getLocation(), diag::note_conflicting_prototype); 4243 } 4244 } 4245 } 4246 4247 if (Context.typesAreCompatible(OldQType, NewQType)) { 4248 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 4249 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 4250 const FunctionProtoType *OldProto = nullptr; 4251 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 4252 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 4253 // The old declaration provided a function prototype, but the 4254 // new declaration does not. Merge in the prototype. 4255 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 4256 NewQType = Context.getFunctionType(NewFuncType->getReturnType(), 4257 OldProto->getParamTypes(), 4258 OldProto->getExtProtoInfo()); 4259 New->setType(NewQType); 4260 New->setHasInheritedPrototype(); 4261 4262 // Synthesize parameters with the same types. 4263 SmallVector<ParmVarDecl *, 16> Params; 4264 for (const auto &ParamType : OldProto->param_types()) { 4265 ParmVarDecl *Param = ParmVarDecl::Create( 4266 Context, New, SourceLocation(), SourceLocation(), nullptr, 4267 ParamType, /*TInfo=*/nullptr, SC_None, nullptr); 4268 Param->setScopeInfo(0, Params.size()); 4269 Param->setImplicit(); 4270 Params.push_back(Param); 4271 } 4272 4273 New->setParams(Params); 4274 } 4275 4276 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4277 } 4278 } 4279 4280 // Check if the function types are compatible when pointer size address 4281 // spaces are ignored. 4282 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 4283 return false; 4284 4285 // GNU C permits a K&R definition to follow a prototype declaration 4286 // if the declared types of the parameters in the K&R definition 4287 // match the types in the prototype declaration, even when the 4288 // promoted types of the parameters from the K&R definition differ 4289 // from the types in the prototype. GCC then keeps the types from 4290 // the prototype. 4291 // 4292 // If a variadic prototype is followed by a non-variadic K&R definition, 4293 // the K&R definition becomes variadic. This is sort of an edge case, but 4294 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 4295 // C99 6.9.1p8. 4296 if (!getLangOpts().CPlusPlus && 4297 Old->hasPrototype() && !New->hasPrototype() && 4298 New->getType()->getAs<FunctionProtoType>() && 4299 Old->getNumParams() == New->getNumParams()) { 4300 SmallVector<QualType, 16> ArgTypes; 4301 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 4302 const FunctionProtoType *OldProto 4303 = Old->getType()->getAs<FunctionProtoType>(); 4304 const FunctionProtoType *NewProto 4305 = New->getType()->getAs<FunctionProtoType>(); 4306 4307 // Determine whether this is the GNU C extension. 4308 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 4309 NewProto->getReturnType()); 4310 bool LooseCompatible = !MergedReturn.isNull(); 4311 for (unsigned Idx = 0, End = Old->getNumParams(); 4312 LooseCompatible && Idx != End; ++Idx) { 4313 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 4314 ParmVarDecl *NewParm = New->getParamDecl(Idx); 4315 if (Context.typesAreCompatible(OldParm->getType(), 4316 NewProto->getParamType(Idx))) { 4317 ArgTypes.push_back(NewParm->getType()); 4318 } else if (Context.typesAreCompatible(OldParm->getType(), 4319 NewParm->getType(), 4320 /*CompareUnqualified=*/true)) { 4321 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 4322 NewProto->getParamType(Idx) }; 4323 Warnings.push_back(Warn); 4324 ArgTypes.push_back(NewParm->getType()); 4325 } else 4326 LooseCompatible = false; 4327 } 4328 4329 if (LooseCompatible) { 4330 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 4331 Diag(Warnings[Warn].NewParm->getLocation(), 4332 diag::ext_param_promoted_not_compatible_with_prototype) 4333 << Warnings[Warn].PromotedType 4334 << Warnings[Warn].OldParm->getType(); 4335 if (Warnings[Warn].OldParm->getLocation().isValid()) 4336 Diag(Warnings[Warn].OldParm->getLocation(), 4337 diag::note_previous_declaration); 4338 } 4339 4340 if (MergeTypeWithOld) 4341 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 4342 OldProto->getExtProtoInfo())); 4343 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4344 } 4345 4346 // Fall through to diagnose conflicting types. 4347 } 4348 4349 // A function that has already been declared has been redeclared or 4350 // defined with a different type; show an appropriate diagnostic. 4351 4352 // If the previous declaration was an implicitly-generated builtin 4353 // declaration, then at the very least we should use a specialized note. 4354 unsigned BuiltinID; 4355 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 4356 // If it's actually a library-defined builtin function like 'malloc' 4357 // or 'printf', just warn about the incompatible redeclaration. 4358 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 4359 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 4360 Diag(OldLocation, diag::note_previous_builtin_declaration) 4361 << Old << Old->getType(); 4362 return false; 4363 } 4364 4365 PrevDiag = diag::note_previous_builtin_declaration; 4366 } 4367 4368 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 4369 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4370 return true; 4371 } 4372 4373 /// Completes the merge of two function declarations that are 4374 /// known to be compatible. 4375 /// 4376 /// This routine handles the merging of attributes and other 4377 /// properties of function declarations from the old declaration to 4378 /// the new declaration, once we know that New is in fact a 4379 /// redeclaration of Old. 4380 /// 4381 /// \returns false 4382 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 4383 Scope *S, bool MergeTypeWithOld) { 4384 // Merge the attributes 4385 mergeDeclAttributes(New, Old); 4386 4387 // Merge "pure" flag. 4388 if (Old->isPure()) 4389 New->setPure(); 4390 4391 // Merge "used" flag. 4392 if (Old->getMostRecentDecl()->isUsed(false)) 4393 New->setIsUsed(); 4394 4395 // Merge attributes from the parameters. These can mismatch with K&R 4396 // declarations. 4397 if (New->getNumParams() == Old->getNumParams()) 4398 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 4399 ParmVarDecl *NewParam = New->getParamDecl(i); 4400 ParmVarDecl *OldParam = Old->getParamDecl(i); 4401 mergeParamDeclAttributes(NewParam, OldParam, *this); 4402 mergeParamDeclTypes(NewParam, OldParam, *this); 4403 } 4404 4405 if (getLangOpts().CPlusPlus) 4406 return MergeCXXFunctionDecl(New, Old, S); 4407 4408 // Merge the function types so the we get the composite types for the return 4409 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 4410 // was visible. 4411 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 4412 if (!Merged.isNull() && MergeTypeWithOld) 4413 New->setType(Merged); 4414 4415 return false; 4416 } 4417 4418 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 4419 ObjCMethodDecl *oldMethod) { 4420 // Merge the attributes, including deprecated/unavailable 4421 AvailabilityMergeKind MergeKind = 4422 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 4423 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 4424 : AMK_ProtocolImplementation) 4425 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 4426 : AMK_Override; 4427 4428 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 4429 4430 // Merge attributes from the parameters. 4431 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 4432 oe = oldMethod->param_end(); 4433 for (ObjCMethodDecl::param_iterator 4434 ni = newMethod->param_begin(), ne = newMethod->param_end(); 4435 ni != ne && oi != oe; ++ni, ++oi) 4436 mergeParamDeclAttributes(*ni, *oi, *this); 4437 4438 CheckObjCMethodOverride(newMethod, oldMethod); 4439 } 4440 4441 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 4442 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 4443 4444 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 4445 ? diag::err_redefinition_different_type 4446 : diag::err_redeclaration_different_type) 4447 << New->getDeclName() << New->getType() << Old->getType(); 4448 4449 diag::kind PrevDiag; 4450 SourceLocation OldLocation; 4451 std::tie(PrevDiag, OldLocation) 4452 = getNoteDiagForInvalidRedeclaration(Old, New); 4453 S.Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4454 New->setInvalidDecl(); 4455 } 4456 4457 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 4458 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 4459 /// emitting diagnostics as appropriate. 4460 /// 4461 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 4462 /// to here in AddInitializerToDecl. We can't check them before the initializer 4463 /// is attached. 4464 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 4465 bool MergeTypeWithOld) { 4466 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors()) 4467 return; 4468 4469 QualType MergedT; 4470 if (getLangOpts().CPlusPlus) { 4471 if (New->getType()->isUndeducedType()) { 4472 // We don't know what the new type is until the initializer is attached. 4473 return; 4474 } else if (Context.hasSameType(New->getType(), Old->getType())) { 4475 // These could still be something that needs exception specs checked. 4476 return MergeVarDeclExceptionSpecs(New, Old); 4477 } 4478 // C++ [basic.link]p10: 4479 // [...] the types specified by all declarations referring to a given 4480 // object or function shall be identical, except that declarations for an 4481 // array object can specify array types that differ by the presence or 4482 // absence of a major array bound (8.3.4). 4483 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4484 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4485 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4486 4487 // We are merging a variable declaration New into Old. If it has an array 4488 // bound, and that bound differs from Old's bound, we should diagnose the 4489 // mismatch. 4490 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4491 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4492 PrevVD = PrevVD->getPreviousDecl()) { 4493 QualType PrevVDTy = PrevVD->getType(); 4494 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4495 continue; 4496 4497 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4498 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4499 } 4500 } 4501 4502 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4503 if (Context.hasSameType(OldArray->getElementType(), 4504 NewArray->getElementType())) 4505 MergedT = New->getType(); 4506 } 4507 // FIXME: Check visibility. New is hidden but has a complete type. If New 4508 // has no array bound, it should not inherit one from Old, if Old is not 4509 // visible. 4510 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4511 if (Context.hasSameType(OldArray->getElementType(), 4512 NewArray->getElementType())) 4513 MergedT = Old->getType(); 4514 } 4515 } 4516 else if (New->getType()->isObjCObjectPointerType() && 4517 Old->getType()->isObjCObjectPointerType()) { 4518 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4519 Old->getType()); 4520 } 4521 } else { 4522 // C 6.2.7p2: 4523 // All declarations that refer to the same object or function shall have 4524 // compatible type. 4525 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4526 } 4527 if (MergedT.isNull()) { 4528 // It's OK if we couldn't merge types if either type is dependent, for a 4529 // block-scope variable. In other cases (static data members of class 4530 // templates, variable templates, ...), we require the types to be 4531 // equivalent. 4532 // FIXME: The C++ standard doesn't say anything about this. 4533 if ((New->getType()->isDependentType() || 4534 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4535 // If the old type was dependent, we can't merge with it, so the new type 4536 // becomes dependent for now. We'll reproduce the original type when we 4537 // instantiate the TypeSourceInfo for the variable. 4538 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4539 New->setType(Context.DependentTy); 4540 return; 4541 } 4542 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4543 } 4544 4545 // Don't actually update the type on the new declaration if the old 4546 // declaration was an extern declaration in a different scope. 4547 if (MergeTypeWithOld) 4548 New->setType(MergedT); 4549 } 4550 4551 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4552 LookupResult &Previous) { 4553 // C11 6.2.7p4: 4554 // For an identifier with internal or external linkage declared 4555 // in a scope in which a prior declaration of that identifier is 4556 // visible, if the prior declaration specifies internal or 4557 // external linkage, the type of the identifier at the later 4558 // declaration becomes the composite type. 4559 // 4560 // If the variable isn't visible, we do not merge with its type. 4561 if (Previous.isShadowed()) 4562 return false; 4563 4564 if (S.getLangOpts().CPlusPlus) { 4565 // C++11 [dcl.array]p3: 4566 // If there is a preceding declaration of the entity in the same 4567 // scope in which the bound was specified, an omitted array bound 4568 // is taken to be the same as in that earlier declaration. 4569 return NewVD->isPreviousDeclInSameBlockScope() || 4570 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4571 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4572 } else { 4573 // If the old declaration was function-local, don't merge with its 4574 // type unless we're in the same function. 4575 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4576 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4577 } 4578 } 4579 4580 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4581 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4582 /// situation, merging decls or emitting diagnostics as appropriate. 4583 /// 4584 /// Tentative definition rules (C99 6.9.2p2) are checked by 4585 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4586 /// definitions here, since the initializer hasn't been attached. 4587 /// 4588 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4589 // If the new decl is already invalid, don't do any other checking. 4590 if (New->isInvalidDecl()) 4591 return; 4592 4593 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4594 return; 4595 4596 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4597 4598 // Verify the old decl was also a variable or variable template. 4599 VarDecl *Old = nullptr; 4600 VarTemplateDecl *OldTemplate = nullptr; 4601 if (Previous.isSingleResult()) { 4602 if (NewTemplate) { 4603 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4604 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4605 4606 if (auto *Shadow = 4607 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4608 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4609 return New->setInvalidDecl(); 4610 } else { 4611 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4612 4613 if (auto *Shadow = 4614 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4615 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4616 return New->setInvalidDecl(); 4617 } 4618 } 4619 if (!Old) { 4620 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4621 << New->getDeclName(); 4622 notePreviousDefinition(Previous.getRepresentativeDecl(), 4623 New->getLocation()); 4624 return New->setInvalidDecl(); 4625 } 4626 4627 // If the old declaration was found in an inline namespace and the new 4628 // declaration was qualified, update the DeclContext to match. 4629 adjustDeclContextForDeclaratorDecl(New, Old); 4630 4631 // Ensure the template parameters are compatible. 4632 if (NewTemplate && 4633 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4634 OldTemplate->getTemplateParameters(), 4635 /*Complain=*/true, TPL_TemplateMatch)) 4636 return New->setInvalidDecl(); 4637 4638 // C++ [class.mem]p1: 4639 // A member shall not be declared twice in the member-specification [...] 4640 // 4641 // Here, we need only consider static data members. 4642 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4643 Diag(New->getLocation(), diag::err_duplicate_member) 4644 << New->getIdentifier(); 4645 Diag(Old->getLocation(), diag::note_previous_declaration); 4646 New->setInvalidDecl(); 4647 } 4648 4649 mergeDeclAttributes(New, Old); 4650 // Warn if an already-declared variable is made a weak_import in a subsequent 4651 // declaration 4652 if (New->hasAttr<WeakImportAttr>() && 4653 Old->getStorageClass() == SC_None && 4654 !Old->hasAttr<WeakImportAttr>()) { 4655 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4656 Diag(Old->getLocation(), diag::note_previous_declaration); 4657 // Remove weak_import attribute on new declaration. 4658 New->dropAttr<WeakImportAttr>(); 4659 } 4660 4661 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4662 if (!Old->hasAttr<InternalLinkageAttr>()) { 4663 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4664 << ILA; 4665 Diag(Old->getLocation(), diag::note_previous_declaration); 4666 New->dropAttr<InternalLinkageAttr>(); 4667 } 4668 4669 // Merge the types. 4670 VarDecl *MostRecent = Old->getMostRecentDecl(); 4671 if (MostRecent != Old) { 4672 MergeVarDeclTypes(New, MostRecent, 4673 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4674 if (New->isInvalidDecl()) 4675 return; 4676 } 4677 4678 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4679 if (New->isInvalidDecl()) 4680 return; 4681 4682 diag::kind PrevDiag; 4683 SourceLocation OldLocation; 4684 std::tie(PrevDiag, OldLocation) = 4685 getNoteDiagForInvalidRedeclaration(Old, New); 4686 4687 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4688 if (New->getStorageClass() == SC_Static && 4689 !New->isStaticDataMember() && 4690 Old->hasExternalFormalLinkage()) { 4691 if (getLangOpts().MicrosoftExt) { 4692 Diag(New->getLocation(), diag::ext_static_non_static) 4693 << New->getDeclName(); 4694 Diag(OldLocation, PrevDiag); 4695 } else { 4696 Diag(New->getLocation(), diag::err_static_non_static) 4697 << New->getDeclName(); 4698 Diag(OldLocation, PrevDiag); 4699 return New->setInvalidDecl(); 4700 } 4701 } 4702 // C99 6.2.2p4: 4703 // For an identifier declared with the storage-class specifier 4704 // extern in a scope in which a prior declaration of that 4705 // identifier is visible,23) if the prior declaration specifies 4706 // internal or external linkage, the linkage of the identifier at 4707 // the later declaration is the same as the linkage specified at 4708 // the prior declaration. If no prior declaration is visible, or 4709 // if the prior declaration specifies no linkage, then the 4710 // identifier has external linkage. 4711 if (New->hasExternalStorage() && Old->hasLinkage()) 4712 /* Okay */; 4713 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4714 !New->isStaticDataMember() && 4715 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4716 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4717 Diag(OldLocation, PrevDiag); 4718 return New->setInvalidDecl(); 4719 } 4720 4721 // Check if extern is followed by non-extern and vice-versa. 4722 if (New->hasExternalStorage() && 4723 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4724 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4725 Diag(OldLocation, PrevDiag); 4726 return New->setInvalidDecl(); 4727 } 4728 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4729 !New->hasExternalStorage()) { 4730 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4731 Diag(OldLocation, PrevDiag); 4732 return New->setInvalidDecl(); 4733 } 4734 4735 if (CheckRedeclarationInModule(New, Old)) 4736 return; 4737 4738 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4739 4740 // FIXME: The test for external storage here seems wrong? We still 4741 // need to check for mismatches. 4742 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4743 // Don't complain about out-of-line definitions of static members. 4744 !(Old->getLexicalDeclContext()->isRecord() && 4745 !New->getLexicalDeclContext()->isRecord())) { 4746 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4747 Diag(OldLocation, PrevDiag); 4748 return New->setInvalidDecl(); 4749 } 4750 4751 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4752 if (VarDecl *Def = Old->getDefinition()) { 4753 // C++1z [dcl.fcn.spec]p4: 4754 // If the definition of a variable appears in a translation unit before 4755 // its first declaration as inline, the program is ill-formed. 4756 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4757 Diag(Def->getLocation(), diag::note_previous_definition); 4758 } 4759 } 4760 4761 // If this redeclaration makes the variable inline, we may need to add it to 4762 // UndefinedButUsed. 4763 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4764 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4765 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4766 SourceLocation())); 4767 4768 if (New->getTLSKind() != Old->getTLSKind()) { 4769 if (!Old->getTLSKind()) { 4770 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4771 Diag(OldLocation, PrevDiag); 4772 } else if (!New->getTLSKind()) { 4773 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4774 Diag(OldLocation, PrevDiag); 4775 } else { 4776 // Do not allow redeclaration to change the variable between requiring 4777 // static and dynamic initialization. 4778 // FIXME: GCC allows this, but uses the TLS keyword on the first 4779 // declaration to determine the kind. Do we need to be compatible here? 4780 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4781 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4782 Diag(OldLocation, PrevDiag); 4783 } 4784 } 4785 4786 // C++ doesn't have tentative definitions, so go right ahead and check here. 4787 if (getLangOpts().CPlusPlus) { 4788 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4789 Old->getCanonicalDecl()->isConstexpr()) { 4790 // This definition won't be a definition any more once it's been merged. 4791 Diag(New->getLocation(), 4792 diag::warn_deprecated_redundant_constexpr_static_def); 4793 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) { 4794 VarDecl *Def = Old->getDefinition(); 4795 if (Def && checkVarDeclRedefinition(Def, New)) 4796 return; 4797 } 4798 } 4799 4800 if (haveIncompatibleLanguageLinkages(Old, New)) { 4801 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4802 Diag(OldLocation, PrevDiag); 4803 New->setInvalidDecl(); 4804 return; 4805 } 4806 4807 // Merge "used" flag. 4808 if (Old->getMostRecentDecl()->isUsed(false)) 4809 New->setIsUsed(); 4810 4811 // Keep a chain of previous declarations. 4812 New->setPreviousDecl(Old); 4813 if (NewTemplate) 4814 NewTemplate->setPreviousDecl(OldTemplate); 4815 4816 // Inherit access appropriately. 4817 New->setAccess(Old->getAccess()); 4818 if (NewTemplate) 4819 NewTemplate->setAccess(New->getAccess()); 4820 4821 if (Old->isInline()) 4822 New->setImplicitlyInline(); 4823 } 4824 4825 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4826 SourceManager &SrcMgr = getSourceManager(); 4827 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4828 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4829 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4830 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first); 4831 auto &HSI = PP.getHeaderSearchInfo(); 4832 StringRef HdrFilename = 4833 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4834 4835 auto noteFromModuleOrInclude = [&](Module *Mod, 4836 SourceLocation IncLoc) -> bool { 4837 // Redefinition errors with modules are common with non modular mapped 4838 // headers, example: a non-modular header H in module A that also gets 4839 // included directly in a TU. Pointing twice to the same header/definition 4840 // is confusing, try to get better diagnostics when modules is on. 4841 if (IncLoc.isValid()) { 4842 if (Mod) { 4843 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4844 << HdrFilename.str() << Mod->getFullModuleName(); 4845 if (!Mod->DefinitionLoc.isInvalid()) 4846 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4847 << Mod->getFullModuleName(); 4848 } else { 4849 Diag(IncLoc, diag::note_redefinition_include_same_file) 4850 << HdrFilename.str(); 4851 } 4852 return true; 4853 } 4854 4855 return false; 4856 }; 4857 4858 // Is it the same file and same offset? Provide more information on why 4859 // this leads to a redefinition error. 4860 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4861 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4862 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4863 bool EmittedDiag = 4864 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4865 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4866 4867 // If the header has no guards, emit a note suggesting one. 4868 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld)) 4869 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4870 4871 if (EmittedDiag) 4872 return; 4873 } 4874 4875 // Redefinition coming from different files or couldn't do better above. 4876 if (Old->getLocation().isValid()) 4877 Diag(Old->getLocation(), diag::note_previous_definition); 4878 } 4879 4880 /// We've just determined that \p Old and \p New both appear to be definitions 4881 /// of the same variable. Either diagnose or fix the problem. 4882 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4883 if (!hasVisibleDefinition(Old) && 4884 (New->getFormalLinkage() == Linkage::Internal || New->isInline() || 4885 isa<VarTemplateSpecializationDecl>(New) || 4886 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() || 4887 New->getDeclContext()->isDependentContext())) { 4888 // The previous definition is hidden, and multiple definitions are 4889 // permitted (in separate TUs). Demote this to a declaration. 4890 New->demoteThisDefinitionToDeclaration(); 4891 4892 // Make the canonical definition visible. 4893 if (auto *OldTD = Old->getDescribedVarTemplate()) 4894 makeMergedDefinitionVisible(OldTD); 4895 makeMergedDefinitionVisible(Old); 4896 return false; 4897 } else { 4898 Diag(New->getLocation(), diag::err_redefinition) << New; 4899 notePreviousDefinition(Old, New->getLocation()); 4900 New->setInvalidDecl(); 4901 return true; 4902 } 4903 } 4904 4905 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4906 /// no declarator (e.g. "struct foo;") is parsed. 4907 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 4908 DeclSpec &DS, 4909 const ParsedAttributesView &DeclAttrs, 4910 RecordDecl *&AnonRecord) { 4911 return ParsedFreeStandingDeclSpec( 4912 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord); 4913 } 4914 4915 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4916 // disambiguate entities defined in different scopes. 4917 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4918 // compatibility. 4919 // We will pick our mangling number depending on which version of MSVC is being 4920 // targeted. 4921 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4922 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4923 ? S->getMSCurManglingNumber() 4924 : S->getMSLastManglingNumber(); 4925 } 4926 4927 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4928 if (!Context.getLangOpts().CPlusPlus) 4929 return; 4930 4931 if (isa<CXXRecordDecl>(Tag->getParent())) { 4932 // If this tag is the direct child of a class, number it if 4933 // it is anonymous. 4934 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4935 return; 4936 MangleNumberingContext &MCtx = 4937 Context.getManglingNumberContext(Tag->getParent()); 4938 Context.setManglingNumber( 4939 Tag, MCtx.getManglingNumber( 4940 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4941 return; 4942 } 4943 4944 // If this tag isn't a direct child of a class, number it if it is local. 4945 MangleNumberingContext *MCtx; 4946 Decl *ManglingContextDecl; 4947 std::tie(MCtx, ManglingContextDecl) = 4948 getCurrentMangleNumberContext(Tag->getDeclContext()); 4949 if (MCtx) { 4950 Context.setManglingNumber( 4951 Tag, MCtx->getManglingNumber( 4952 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4953 } 4954 } 4955 4956 namespace { 4957 struct NonCLikeKind { 4958 enum { 4959 None, 4960 BaseClass, 4961 DefaultMemberInit, 4962 Lambda, 4963 Friend, 4964 OtherMember, 4965 Invalid, 4966 } Kind = None; 4967 SourceRange Range; 4968 4969 explicit operator bool() { return Kind != None; } 4970 }; 4971 } 4972 4973 /// Determine whether a class is C-like, according to the rules of C++ 4974 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4975 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4976 if (RD->isInvalidDecl()) 4977 return {NonCLikeKind::Invalid, {}}; 4978 4979 // C++ [dcl.typedef]p9: [P1766R1] 4980 // An unnamed class with a typedef name for linkage purposes shall not 4981 // 4982 // -- have any base classes 4983 if (RD->getNumBases()) 4984 return {NonCLikeKind::BaseClass, 4985 SourceRange(RD->bases_begin()->getBeginLoc(), 4986 RD->bases_end()[-1].getEndLoc())}; 4987 bool Invalid = false; 4988 for (Decl *D : RD->decls()) { 4989 // Don't complain about things we already diagnosed. 4990 if (D->isInvalidDecl()) { 4991 Invalid = true; 4992 continue; 4993 } 4994 4995 // -- have any [...] default member initializers 4996 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4997 if (FD->hasInClassInitializer()) { 4998 auto *Init = FD->getInClassInitializer(); 4999 return {NonCLikeKind::DefaultMemberInit, 5000 Init ? Init->getSourceRange() : D->getSourceRange()}; 5001 } 5002 continue; 5003 } 5004 5005 // FIXME: We don't allow friend declarations. This violates the wording of 5006 // P1766, but not the intent. 5007 if (isa<FriendDecl>(D)) 5008 return {NonCLikeKind::Friend, D->getSourceRange()}; 5009 5010 // -- declare any members other than non-static data members, member 5011 // enumerations, or member classes, 5012 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 5013 isa<EnumDecl>(D)) 5014 continue; 5015 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 5016 if (!MemberRD) { 5017 if (D->isImplicit()) 5018 continue; 5019 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 5020 } 5021 5022 // -- contain a lambda-expression, 5023 if (MemberRD->isLambda()) 5024 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 5025 5026 // and all member classes shall also satisfy these requirements 5027 // (recursively). 5028 if (MemberRD->isThisDeclarationADefinition()) { 5029 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 5030 return Kind; 5031 } 5032 } 5033 5034 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 5035 } 5036 5037 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 5038 TypedefNameDecl *NewTD) { 5039 if (TagFromDeclSpec->isInvalidDecl()) 5040 return; 5041 5042 // Do nothing if the tag already has a name for linkage purposes. 5043 if (TagFromDeclSpec->hasNameForLinkage()) 5044 return; 5045 5046 // A well-formed anonymous tag must always be a TUK_Definition. 5047 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 5048 5049 // The type must match the tag exactly; no qualifiers allowed. 5050 if (!Context.hasSameType(NewTD->getUnderlyingType(), 5051 Context.getTagDeclType(TagFromDeclSpec))) { 5052 if (getLangOpts().CPlusPlus) 5053 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 5054 return; 5055 } 5056 5057 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 5058 // An unnamed class with a typedef name for linkage purposes shall [be 5059 // C-like]. 5060 // 5061 // FIXME: Also diagnose if we've already computed the linkage. That ideally 5062 // shouldn't happen, but there are constructs that the language rule doesn't 5063 // disallow for which we can't reasonably avoid computing linkage early. 5064 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 5065 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 5066 : NonCLikeKind(); 5067 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 5068 if (NonCLike || ChangesLinkage) { 5069 if (NonCLike.Kind == NonCLikeKind::Invalid) 5070 return; 5071 5072 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 5073 if (ChangesLinkage) { 5074 // If the linkage changes, we can't accept this as an extension. 5075 if (NonCLike.Kind == NonCLikeKind::None) 5076 DiagID = diag::err_typedef_changes_linkage; 5077 else 5078 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 5079 } 5080 5081 SourceLocation FixitLoc = 5082 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 5083 llvm::SmallString<40> TextToInsert; 5084 TextToInsert += ' '; 5085 TextToInsert += NewTD->getIdentifier()->getName(); 5086 5087 Diag(FixitLoc, DiagID) 5088 << isa<TypeAliasDecl>(NewTD) 5089 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 5090 if (NonCLike.Kind != NonCLikeKind::None) { 5091 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 5092 << NonCLike.Kind - 1 << NonCLike.Range; 5093 } 5094 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 5095 << NewTD << isa<TypeAliasDecl>(NewTD); 5096 5097 if (ChangesLinkage) 5098 return; 5099 } 5100 5101 // Otherwise, set this as the anon-decl typedef for the tag. 5102 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 5103 } 5104 5105 static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) { 5106 DeclSpec::TST T = DS.getTypeSpecType(); 5107 switch (T) { 5108 case DeclSpec::TST_class: 5109 return 0; 5110 case DeclSpec::TST_struct: 5111 return 1; 5112 case DeclSpec::TST_interface: 5113 return 2; 5114 case DeclSpec::TST_union: 5115 return 3; 5116 case DeclSpec::TST_enum: 5117 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) { 5118 if (ED->isScopedUsingClassTag()) 5119 return 5; 5120 if (ED->isScoped()) 5121 return 6; 5122 } 5123 return 4; 5124 default: 5125 llvm_unreachable("unexpected type specifier"); 5126 } 5127 } 5128 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 5129 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 5130 /// parameters to cope with template friend declarations. 5131 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 5132 DeclSpec &DS, 5133 const ParsedAttributesView &DeclAttrs, 5134 MultiTemplateParamsArg TemplateParams, 5135 bool IsExplicitInstantiation, 5136 RecordDecl *&AnonRecord) { 5137 Decl *TagD = nullptr; 5138 TagDecl *Tag = nullptr; 5139 if (DS.getTypeSpecType() == DeclSpec::TST_class || 5140 DS.getTypeSpecType() == DeclSpec::TST_struct || 5141 DS.getTypeSpecType() == DeclSpec::TST_interface || 5142 DS.getTypeSpecType() == DeclSpec::TST_union || 5143 DS.getTypeSpecType() == DeclSpec::TST_enum) { 5144 TagD = DS.getRepAsDecl(); 5145 5146 if (!TagD) // We probably had an error 5147 return nullptr; 5148 5149 // Note that the above type specs guarantee that the 5150 // type rep is a Decl, whereas in many of the others 5151 // it's a Type. 5152 if (isa<TagDecl>(TagD)) 5153 Tag = cast<TagDecl>(TagD); 5154 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 5155 Tag = CTD->getTemplatedDecl(); 5156 } 5157 5158 if (Tag) { 5159 handleTagNumbering(Tag, S); 5160 Tag->setFreeStanding(); 5161 if (Tag->isInvalidDecl()) 5162 return Tag; 5163 } 5164 5165 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 5166 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 5167 // or incomplete types shall not be restrict-qualified." 5168 if (TypeQuals & DeclSpec::TQ_restrict) 5169 Diag(DS.getRestrictSpecLoc(), 5170 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 5171 << DS.getSourceRange(); 5172 } 5173 5174 if (DS.isInlineSpecified()) 5175 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 5176 << getLangOpts().CPlusPlus17; 5177 5178 if (DS.hasConstexprSpecifier()) { 5179 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 5180 // and definitions of functions and variables. 5181 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 5182 // the declaration of a function or function template 5183 if (Tag) 5184 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 5185 << GetDiagnosticTypeSpecifierID(DS) 5186 << static_cast<int>(DS.getConstexprSpecifier()); 5187 else 5188 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 5189 << static_cast<int>(DS.getConstexprSpecifier()); 5190 // Don't emit warnings after this error. 5191 return TagD; 5192 } 5193 5194 DiagnoseFunctionSpecifiers(DS); 5195 5196 if (DS.isFriendSpecified()) { 5197 // If we're dealing with a decl but not a TagDecl, assume that 5198 // whatever routines created it handled the friendship aspect. 5199 if (TagD && !Tag) 5200 return nullptr; 5201 return ActOnFriendTypeDecl(S, DS, TemplateParams); 5202 } 5203 5204 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 5205 bool IsExplicitSpecialization = 5206 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 5207 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 5208 !IsExplicitInstantiation && !IsExplicitSpecialization && 5209 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 5210 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 5211 // nested-name-specifier unless it is an explicit instantiation 5212 // or an explicit specialization. 5213 // 5214 // FIXME: We allow class template partial specializations here too, per the 5215 // obvious intent of DR1819. 5216 // 5217 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 5218 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 5219 << GetDiagnosticTypeSpecifierID(DS) << SS.getRange(); 5220 return nullptr; 5221 } 5222 5223 // Track whether this decl-specifier declares anything. 5224 bool DeclaresAnything = true; 5225 5226 // Handle anonymous struct definitions. 5227 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 5228 if (!Record->getDeclName() && Record->isCompleteDefinition() && 5229 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 5230 if (getLangOpts().CPlusPlus || 5231 Record->getDeclContext()->isRecord()) { 5232 // If CurContext is a DeclContext that can contain statements, 5233 // RecursiveASTVisitor won't visit the decls that 5234 // BuildAnonymousStructOrUnion() will put into CurContext. 5235 // Also store them here so that they can be part of the 5236 // DeclStmt that gets created in this case. 5237 // FIXME: Also return the IndirectFieldDecls created by 5238 // BuildAnonymousStructOr union, for the same reason? 5239 if (CurContext->isFunctionOrMethod()) 5240 AnonRecord = Record; 5241 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 5242 Context.getPrintingPolicy()); 5243 } 5244 5245 DeclaresAnything = false; 5246 } 5247 } 5248 5249 // C11 6.7.2.1p2: 5250 // A struct-declaration that does not declare an anonymous structure or 5251 // anonymous union shall contain a struct-declarator-list. 5252 // 5253 // This rule also existed in C89 and C99; the grammar for struct-declaration 5254 // did not permit a struct-declaration without a struct-declarator-list. 5255 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 5256 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 5257 // Check for Microsoft C extension: anonymous struct/union member. 5258 // Handle 2 kinds of anonymous struct/union: 5259 // struct STRUCT; 5260 // union UNION; 5261 // and 5262 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 5263 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 5264 if ((Tag && Tag->getDeclName()) || 5265 DS.getTypeSpecType() == DeclSpec::TST_typename) { 5266 RecordDecl *Record = nullptr; 5267 if (Tag) 5268 Record = dyn_cast<RecordDecl>(Tag); 5269 else if (const RecordType *RT = 5270 DS.getRepAsType().get()->getAsStructureType()) 5271 Record = RT->getDecl(); 5272 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 5273 Record = UT->getDecl(); 5274 5275 if (Record && getLangOpts().MicrosoftExt) { 5276 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 5277 << Record->isUnion() << DS.getSourceRange(); 5278 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 5279 } 5280 5281 DeclaresAnything = false; 5282 } 5283 } 5284 5285 // Skip all the checks below if we have a type error. 5286 if (DS.getTypeSpecType() == DeclSpec::TST_error || 5287 (TagD && TagD->isInvalidDecl())) 5288 return TagD; 5289 5290 if (getLangOpts().CPlusPlus && 5291 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 5292 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 5293 if (Enum->enumerator_begin() == Enum->enumerator_end() && 5294 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 5295 DeclaresAnything = false; 5296 5297 if (!DS.isMissingDeclaratorOk()) { 5298 // Customize diagnostic for a typedef missing a name. 5299 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 5300 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 5301 << DS.getSourceRange(); 5302 else 5303 DeclaresAnything = false; 5304 } 5305 5306 if (DS.isModulePrivateSpecified() && 5307 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 5308 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 5309 << llvm::to_underlying(Tag->getTagKind()) 5310 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 5311 5312 ActOnDocumentableDecl(TagD); 5313 5314 // C 6.7/2: 5315 // A declaration [...] shall declare at least a declarator [...], a tag, 5316 // or the members of an enumeration. 5317 // C++ [dcl.dcl]p3: 5318 // [If there are no declarators], and except for the declaration of an 5319 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5320 // names into the program, or shall redeclare a name introduced by a 5321 // previous declaration. 5322 if (!DeclaresAnything) { 5323 // In C, we allow this as a (popular) extension / bug. Don't bother 5324 // producing further diagnostics for redundant qualifiers after this. 5325 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 5326 ? diag::err_no_declarators 5327 : diag::ext_no_declarators) 5328 << DS.getSourceRange(); 5329 return TagD; 5330 } 5331 5332 // C++ [dcl.stc]p1: 5333 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 5334 // init-declarator-list of the declaration shall not be empty. 5335 // C++ [dcl.fct.spec]p1: 5336 // If a cv-qualifier appears in a decl-specifier-seq, the 5337 // init-declarator-list of the declaration shall not be empty. 5338 // 5339 // Spurious qualifiers here appear to be valid in C. 5340 unsigned DiagID = diag::warn_standalone_specifier; 5341 if (getLangOpts().CPlusPlus) 5342 DiagID = diag::ext_standalone_specifier; 5343 5344 // Note that a linkage-specification sets a storage class, but 5345 // 'extern "C" struct foo;' is actually valid and not theoretically 5346 // useless. 5347 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 5348 if (SCS == DeclSpec::SCS_mutable) 5349 // Since mutable is not a viable storage class specifier in C, there is 5350 // no reason to treat it as an extension. Instead, diagnose as an error. 5351 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 5352 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 5353 Diag(DS.getStorageClassSpecLoc(), DiagID) 5354 << DeclSpec::getSpecifierName(SCS); 5355 } 5356 5357 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 5358 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 5359 << DeclSpec::getSpecifierName(TSCS); 5360 if (DS.getTypeQualifiers()) { 5361 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5362 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 5363 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5364 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 5365 // Restrict is covered above. 5366 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5367 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 5368 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5369 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 5370 } 5371 5372 // Warn about ignored type attributes, for example: 5373 // __attribute__((aligned)) struct A; 5374 // Attributes should be placed after tag to apply to type declaration. 5375 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) { 5376 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 5377 if (TypeSpecType == DeclSpec::TST_class || 5378 TypeSpecType == DeclSpec::TST_struct || 5379 TypeSpecType == DeclSpec::TST_interface || 5380 TypeSpecType == DeclSpec::TST_union || 5381 TypeSpecType == DeclSpec::TST_enum) { 5382 5383 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) { 5384 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored; 5385 if (AL.isAlignas() && !getLangOpts().CPlusPlus) 5386 DiagnosticId = diag::warn_attribute_ignored; 5387 else if (AL.isRegularKeywordAttribute()) 5388 DiagnosticId = diag::err_declspec_keyword_has_no_effect; 5389 else 5390 DiagnosticId = diag::warn_declspec_attribute_ignored; 5391 Diag(AL.getLoc(), DiagnosticId) 5392 << AL << GetDiagnosticTypeSpecifierID(DS); 5393 }; 5394 5395 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic); 5396 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic); 5397 } 5398 } 5399 5400 return TagD; 5401 } 5402 5403 /// We are trying to inject an anonymous member into the given scope; 5404 /// check if there's an existing declaration that can't be overloaded. 5405 /// 5406 /// \return true if this is a forbidden redeclaration 5407 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, 5408 DeclContext *Owner, 5409 DeclarationName Name, 5410 SourceLocation NameLoc, bool IsUnion, 5411 StorageClass SC) { 5412 LookupResult R(SemaRef, Name, NameLoc, 5413 Owner->isRecord() ? Sema::LookupMemberName 5414 : Sema::LookupOrdinaryName, 5415 Sema::ForVisibleRedeclaration); 5416 if (!SemaRef.LookupName(R, S)) return false; 5417 5418 // Pick a representative declaration. 5419 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 5420 assert(PrevDecl && "Expected a non-null Decl"); 5421 5422 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 5423 return false; 5424 5425 if (SC == StorageClass::SC_None && 5426 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) && 5427 (Owner->isFunctionOrMethod() || Owner->isRecord())) { 5428 if (!Owner->isRecord()) 5429 SemaRef.DiagPlaceholderVariableDefinition(NameLoc); 5430 return false; 5431 } 5432 5433 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 5434 << IsUnion << Name; 5435 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 5436 5437 return true; 5438 } 5439 5440 void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) { 5441 if (auto *RD = dyn_cast_if_present<RecordDecl>(D)) 5442 DiagPlaceholderFieldDeclDefinitions(RD); 5443 } 5444 5445 /// Emit diagnostic warnings for placeholder members. 5446 /// We can only do that after the class is fully constructed, 5447 /// as anonymous union/structs can insert placeholders 5448 /// in their parent scope (which might be a Record). 5449 void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) { 5450 if (!getLangOpts().CPlusPlus) 5451 return; 5452 5453 // This function can be parsed before we have validated the 5454 // structure as an anonymous struct 5455 if (Record->isAnonymousStructOrUnion()) 5456 return; 5457 5458 const NamedDecl *First = 0; 5459 for (const Decl *D : Record->decls()) { 5460 const NamedDecl *ND = dyn_cast<NamedDecl>(D); 5461 if (!ND || !ND->isPlaceholderVar(getLangOpts())) 5462 continue; 5463 if (!First) 5464 First = ND; 5465 else 5466 DiagPlaceholderVariableDefinition(ND->getLocation()); 5467 } 5468 } 5469 5470 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 5471 /// anonymous struct or union AnonRecord into the owning context Owner 5472 /// and scope S. This routine will be invoked just after we realize 5473 /// that an unnamed union or struct is actually an anonymous union or 5474 /// struct, e.g., 5475 /// 5476 /// @code 5477 /// union { 5478 /// int i; 5479 /// float f; 5480 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 5481 /// // f into the surrounding scope.x 5482 /// @endcode 5483 /// 5484 /// This routine is recursive, injecting the names of nested anonymous 5485 /// structs/unions into the owning context and scope as well. 5486 static bool 5487 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 5488 RecordDecl *AnonRecord, AccessSpecifier AS, 5489 StorageClass SC, 5490 SmallVectorImpl<NamedDecl *> &Chaining) { 5491 bool Invalid = false; 5492 5493 // Look every FieldDecl and IndirectFieldDecl with a name. 5494 for (auto *D : AnonRecord->decls()) { 5495 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 5496 cast<NamedDecl>(D)->getDeclName()) { 5497 ValueDecl *VD = cast<ValueDecl>(D); 5498 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 5499 VD->getLocation(), AnonRecord->isUnion(), 5500 SC)) { 5501 // C++ [class.union]p2: 5502 // The names of the members of an anonymous union shall be 5503 // distinct from the names of any other entity in the 5504 // scope in which the anonymous union is declared. 5505 Invalid = true; 5506 } else { 5507 // C++ [class.union]p2: 5508 // For the purpose of name lookup, after the anonymous union 5509 // definition, the members of the anonymous union are 5510 // considered to have been defined in the scope in which the 5511 // anonymous union is declared. 5512 unsigned OldChainingSize = Chaining.size(); 5513 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 5514 Chaining.append(IF->chain_begin(), IF->chain_end()); 5515 else 5516 Chaining.push_back(VD); 5517 5518 assert(Chaining.size() >= 2); 5519 NamedDecl **NamedChain = 5520 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 5521 for (unsigned i = 0; i < Chaining.size(); i++) 5522 NamedChain[i] = Chaining[i]; 5523 5524 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 5525 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 5526 VD->getType(), {NamedChain, Chaining.size()}); 5527 5528 for (const auto *Attr : VD->attrs()) 5529 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 5530 5531 IndirectField->setAccess(AS); 5532 IndirectField->setImplicit(); 5533 SemaRef.PushOnScopeChains(IndirectField, S); 5534 5535 // That includes picking up the appropriate access specifier. 5536 if (AS != AS_none) IndirectField->setAccess(AS); 5537 5538 Chaining.resize(OldChainingSize); 5539 } 5540 } 5541 } 5542 5543 return Invalid; 5544 } 5545 5546 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5547 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5548 /// illegal input values are mapped to SC_None. 5549 static StorageClass 5550 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5551 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5552 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5553 "Parser allowed 'typedef' as storage class VarDecl."); 5554 switch (StorageClassSpec) { 5555 case DeclSpec::SCS_unspecified: return SC_None; 5556 case DeclSpec::SCS_extern: 5557 if (DS.isExternInLinkageSpec()) 5558 return SC_None; 5559 return SC_Extern; 5560 case DeclSpec::SCS_static: return SC_Static; 5561 case DeclSpec::SCS_auto: return SC_Auto; 5562 case DeclSpec::SCS_register: return SC_Register; 5563 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5564 // Illegal SCSs map to None: error reporting is up to the caller. 5565 case DeclSpec::SCS_mutable: // Fall through. 5566 case DeclSpec::SCS_typedef: return SC_None; 5567 } 5568 llvm_unreachable("unknown storage class specifier"); 5569 } 5570 5571 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5572 assert(Record->hasInClassInitializer()); 5573 5574 for (const auto *I : Record->decls()) { 5575 const auto *FD = dyn_cast<FieldDecl>(I); 5576 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5577 FD = IFD->getAnonField(); 5578 if (FD && FD->hasInClassInitializer()) 5579 return FD->getLocation(); 5580 } 5581 5582 llvm_unreachable("couldn't find in-class initializer"); 5583 } 5584 5585 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5586 SourceLocation DefaultInitLoc) { 5587 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5588 return; 5589 5590 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5591 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5592 } 5593 5594 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5595 CXXRecordDecl *AnonUnion) { 5596 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5597 return; 5598 5599 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5600 } 5601 5602 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5603 /// anonymous structure or union. Anonymous unions are a C++ feature 5604 /// (C++ [class.union]) and a C11 feature; anonymous structures 5605 /// are a C11 feature and GNU C++ extension. 5606 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5607 AccessSpecifier AS, 5608 RecordDecl *Record, 5609 const PrintingPolicy &Policy) { 5610 DeclContext *Owner = Record->getDeclContext(); 5611 5612 // Diagnose whether this anonymous struct/union is an extension. 5613 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5614 Diag(Record->getLocation(), diag::ext_anonymous_union); 5615 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5616 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5617 else if (!Record->isUnion() && !getLangOpts().C11) 5618 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5619 5620 // C and C++ require different kinds of checks for anonymous 5621 // structs/unions. 5622 bool Invalid = false; 5623 if (getLangOpts().CPlusPlus) { 5624 const char *PrevSpec = nullptr; 5625 if (Record->isUnion()) { 5626 // C++ [class.union]p6: 5627 // C++17 [class.union.anon]p2: 5628 // Anonymous unions declared in a named namespace or in the 5629 // global namespace shall be declared static. 5630 unsigned DiagID; 5631 DeclContext *OwnerScope = Owner->getRedeclContext(); 5632 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5633 (OwnerScope->isTranslationUnit() || 5634 (OwnerScope->isNamespace() && 5635 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5636 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5637 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5638 5639 // Recover by adding 'static'. 5640 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5641 PrevSpec, DiagID, Policy); 5642 } 5643 // C++ [class.union]p6: 5644 // A storage class is not allowed in a declaration of an 5645 // anonymous union in a class scope. 5646 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5647 isa<RecordDecl>(Owner)) { 5648 Diag(DS.getStorageClassSpecLoc(), 5649 diag::err_anonymous_union_with_storage_spec) 5650 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5651 5652 // Recover by removing the storage specifier. 5653 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5654 SourceLocation(), 5655 PrevSpec, DiagID, Context.getPrintingPolicy()); 5656 } 5657 } 5658 5659 // Ignore const/volatile/restrict qualifiers. 5660 if (DS.getTypeQualifiers()) { 5661 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5662 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5663 << Record->isUnion() << "const" 5664 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5665 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5666 Diag(DS.getVolatileSpecLoc(), 5667 diag::ext_anonymous_struct_union_qualified) 5668 << Record->isUnion() << "volatile" 5669 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5670 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5671 Diag(DS.getRestrictSpecLoc(), 5672 diag::ext_anonymous_struct_union_qualified) 5673 << Record->isUnion() << "restrict" 5674 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5675 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5676 Diag(DS.getAtomicSpecLoc(), 5677 diag::ext_anonymous_struct_union_qualified) 5678 << Record->isUnion() << "_Atomic" 5679 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5680 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5681 Diag(DS.getUnalignedSpecLoc(), 5682 diag::ext_anonymous_struct_union_qualified) 5683 << Record->isUnion() << "__unaligned" 5684 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5685 5686 DS.ClearTypeQualifiers(); 5687 } 5688 5689 // C++ [class.union]p2: 5690 // The member-specification of an anonymous union shall only 5691 // define non-static data members. [Note: nested types and 5692 // functions cannot be declared within an anonymous union. ] 5693 for (auto *Mem : Record->decls()) { 5694 // Ignore invalid declarations; we already diagnosed them. 5695 if (Mem->isInvalidDecl()) 5696 continue; 5697 5698 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5699 // C++ [class.union]p3: 5700 // An anonymous union shall not have private or protected 5701 // members (clause 11). 5702 assert(FD->getAccess() != AS_none); 5703 if (FD->getAccess() != AS_public) { 5704 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5705 << Record->isUnion() << (FD->getAccess() == AS_protected); 5706 Invalid = true; 5707 } 5708 5709 // C++ [class.union]p1 5710 // An object of a class with a non-trivial constructor, a non-trivial 5711 // copy constructor, a non-trivial destructor, or a non-trivial copy 5712 // assignment operator cannot be a member of a union, nor can an 5713 // array of such objects. 5714 if (CheckNontrivialField(FD)) 5715 Invalid = true; 5716 } else if (Mem->isImplicit()) { 5717 // Any implicit members are fine. 5718 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5719 // This is a type that showed up in an 5720 // elaborated-type-specifier inside the anonymous struct or 5721 // union, but which actually declares a type outside of the 5722 // anonymous struct or union. It's okay. 5723 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5724 if (!MemRecord->isAnonymousStructOrUnion() && 5725 MemRecord->getDeclName()) { 5726 // Visual C++ allows type definition in anonymous struct or union. 5727 if (getLangOpts().MicrosoftExt) 5728 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5729 << Record->isUnion(); 5730 else { 5731 // This is a nested type declaration. 5732 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5733 << Record->isUnion(); 5734 Invalid = true; 5735 } 5736 } else { 5737 // This is an anonymous type definition within another anonymous type. 5738 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5739 // not part of standard C++. 5740 Diag(MemRecord->getLocation(), 5741 diag::ext_anonymous_record_with_anonymous_type) 5742 << Record->isUnion(); 5743 } 5744 } else if (isa<AccessSpecDecl>(Mem)) { 5745 // Any access specifier is fine. 5746 } else if (isa<StaticAssertDecl>(Mem)) { 5747 // In C++1z, static_assert declarations are also fine. 5748 } else { 5749 // We have something that isn't a non-static data 5750 // member. Complain about it. 5751 unsigned DK = diag::err_anonymous_record_bad_member; 5752 if (isa<TypeDecl>(Mem)) 5753 DK = diag::err_anonymous_record_with_type; 5754 else if (isa<FunctionDecl>(Mem)) 5755 DK = diag::err_anonymous_record_with_function; 5756 else if (isa<VarDecl>(Mem)) 5757 DK = diag::err_anonymous_record_with_static; 5758 5759 // Visual C++ allows type definition in anonymous struct or union. 5760 if (getLangOpts().MicrosoftExt && 5761 DK == diag::err_anonymous_record_with_type) 5762 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5763 << Record->isUnion(); 5764 else { 5765 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5766 Invalid = true; 5767 } 5768 } 5769 } 5770 5771 // C++11 [class.union]p8 (DR1460): 5772 // At most one variant member of a union may have a 5773 // brace-or-equal-initializer. 5774 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5775 Owner->isRecord()) 5776 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5777 cast<CXXRecordDecl>(Record)); 5778 } 5779 5780 if (!Record->isUnion() && !Owner->isRecord()) { 5781 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5782 << getLangOpts().CPlusPlus; 5783 Invalid = true; 5784 } 5785 5786 // C++ [dcl.dcl]p3: 5787 // [If there are no declarators], and except for the declaration of an 5788 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5789 // names into the program 5790 // C++ [class.mem]p2: 5791 // each such member-declaration shall either declare at least one member 5792 // name of the class or declare at least one unnamed bit-field 5793 // 5794 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5795 if (getLangOpts().CPlusPlus && Record->field_empty()) 5796 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5797 5798 // Mock up a declarator. 5799 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member); 5800 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5801 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5802 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5803 5804 // Create a declaration for this anonymous struct/union. 5805 NamedDecl *Anon = nullptr; 5806 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5807 Anon = FieldDecl::Create( 5808 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5809 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5810 /*BitWidth=*/nullptr, /*Mutable=*/false, 5811 /*InitStyle=*/ICIS_NoInit); 5812 Anon->setAccess(AS); 5813 ProcessDeclAttributes(S, Anon, Dc); 5814 5815 if (getLangOpts().CPlusPlus) 5816 FieldCollector->Add(cast<FieldDecl>(Anon)); 5817 } else { 5818 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5819 if (SCSpec == DeclSpec::SCS_mutable) { 5820 // mutable can only appear on non-static class members, so it's always 5821 // an error here 5822 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5823 Invalid = true; 5824 SC = SC_None; 5825 } 5826 5827 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5828 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5829 Context.getTypeDeclType(Record), TInfo, SC); 5830 ProcessDeclAttributes(S, Anon, Dc); 5831 5832 // Default-initialize the implicit variable. This initialization will be 5833 // trivial in almost all cases, except if a union member has an in-class 5834 // initializer: 5835 // union { int n = 0; }; 5836 ActOnUninitializedDecl(Anon); 5837 } 5838 Anon->setImplicit(); 5839 5840 // Mark this as an anonymous struct/union type. 5841 Record->setAnonymousStructOrUnion(true); 5842 5843 // Add the anonymous struct/union object to the current 5844 // context. We'll be referencing this object when we refer to one of 5845 // its members. 5846 Owner->addDecl(Anon); 5847 5848 // Inject the members of the anonymous struct/union into the owning 5849 // context and into the identifier resolver chain for name lookup 5850 // purposes. 5851 SmallVector<NamedDecl*, 2> Chain; 5852 Chain.push_back(Anon); 5853 5854 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC, 5855 Chain)) 5856 Invalid = true; 5857 5858 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5859 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5860 MangleNumberingContext *MCtx; 5861 Decl *ManglingContextDecl; 5862 std::tie(MCtx, ManglingContextDecl) = 5863 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5864 if (MCtx) { 5865 Context.setManglingNumber( 5866 NewVD, MCtx->getManglingNumber( 5867 NewVD, getMSManglingNumber(getLangOpts(), S))); 5868 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5869 } 5870 } 5871 } 5872 5873 if (Invalid) 5874 Anon->setInvalidDecl(); 5875 5876 return Anon; 5877 } 5878 5879 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5880 /// Microsoft C anonymous structure. 5881 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5882 /// Example: 5883 /// 5884 /// struct A { int a; }; 5885 /// struct B { struct A; int b; }; 5886 /// 5887 /// void foo() { 5888 /// B var; 5889 /// var.a = 3; 5890 /// } 5891 /// 5892 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5893 RecordDecl *Record) { 5894 assert(Record && "expected a record!"); 5895 5896 // Mock up a declarator. 5897 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName); 5898 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5899 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5900 5901 auto *ParentDecl = cast<RecordDecl>(CurContext); 5902 QualType RecTy = Context.getTypeDeclType(Record); 5903 5904 // Create a declaration for this anonymous struct. 5905 NamedDecl *Anon = 5906 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5907 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5908 /*BitWidth=*/nullptr, /*Mutable=*/false, 5909 /*InitStyle=*/ICIS_NoInit); 5910 Anon->setImplicit(); 5911 5912 // Add the anonymous struct object to the current context. 5913 CurContext->addDecl(Anon); 5914 5915 // Inject the members of the anonymous struct into the current 5916 // context and into the identifier resolver chain for name lookup 5917 // purposes. 5918 SmallVector<NamedDecl*, 2> Chain; 5919 Chain.push_back(Anon); 5920 5921 RecordDecl *RecordDef = Record->getDefinition(); 5922 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5923 diag::err_field_incomplete_or_sizeless) || 5924 InjectAnonymousStructOrUnionMembers( 5925 *this, S, CurContext, RecordDef, AS_none, 5926 StorageClassSpecToVarDeclStorageClass(DS), Chain)) { 5927 Anon->setInvalidDecl(); 5928 ParentDecl->setInvalidDecl(); 5929 } 5930 5931 return Anon; 5932 } 5933 5934 /// GetNameForDeclarator - Determine the full declaration name for the 5935 /// given Declarator. 5936 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5937 return GetNameFromUnqualifiedId(D.getName()); 5938 } 5939 5940 /// Retrieves the declaration name from a parsed unqualified-id. 5941 DeclarationNameInfo 5942 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5943 DeclarationNameInfo NameInfo; 5944 NameInfo.setLoc(Name.StartLocation); 5945 5946 switch (Name.getKind()) { 5947 5948 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5949 case UnqualifiedIdKind::IK_Identifier: 5950 NameInfo.setName(Name.Identifier); 5951 return NameInfo; 5952 5953 case UnqualifiedIdKind::IK_DeductionGuideName: { 5954 // C++ [temp.deduct.guide]p3: 5955 // The simple-template-id shall name a class template specialization. 5956 // The template-name shall be the same identifier as the template-name 5957 // of the simple-template-id. 5958 // These together intend to imply that the template-name shall name a 5959 // class template. 5960 // FIXME: template<typename T> struct X {}; 5961 // template<typename T> using Y = X<T>; 5962 // Y(int) -> Y<int>; 5963 // satisfies these rules but does not name a class template. 5964 TemplateName TN = Name.TemplateName.get().get(); 5965 auto *Template = TN.getAsTemplateDecl(); 5966 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5967 Diag(Name.StartLocation, 5968 diag::err_deduction_guide_name_not_class_template) 5969 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5970 if (Template) 5971 NoteTemplateLocation(*Template); 5972 return DeclarationNameInfo(); 5973 } 5974 5975 NameInfo.setName( 5976 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5977 return NameInfo; 5978 } 5979 5980 case UnqualifiedIdKind::IK_OperatorFunctionId: 5981 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5982 Name.OperatorFunctionId.Operator)); 5983 NameInfo.setCXXOperatorNameRange(SourceRange( 5984 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5985 return NameInfo; 5986 5987 case UnqualifiedIdKind::IK_LiteralOperatorId: 5988 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5989 Name.Identifier)); 5990 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5991 return NameInfo; 5992 5993 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5994 TypeSourceInfo *TInfo; 5995 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5996 if (Ty.isNull()) 5997 return DeclarationNameInfo(); 5998 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5999 Context.getCanonicalType(Ty))); 6000 NameInfo.setNamedTypeInfo(TInfo); 6001 return NameInfo; 6002 } 6003 6004 case UnqualifiedIdKind::IK_ConstructorName: { 6005 TypeSourceInfo *TInfo; 6006 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 6007 if (Ty.isNull()) 6008 return DeclarationNameInfo(); 6009 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 6010 Context.getCanonicalType(Ty))); 6011 NameInfo.setNamedTypeInfo(TInfo); 6012 return NameInfo; 6013 } 6014 6015 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 6016 // In well-formed code, we can only have a constructor 6017 // template-id that refers to the current context, so go there 6018 // to find the actual type being constructed. 6019 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 6020 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 6021 return DeclarationNameInfo(); 6022 6023 // Determine the type of the class being constructed. 6024 QualType CurClassType = Context.getTypeDeclType(CurClass); 6025 6026 // FIXME: Check two things: that the template-id names the same type as 6027 // CurClassType, and that the template-id does not occur when the name 6028 // was qualified. 6029 6030 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 6031 Context.getCanonicalType(CurClassType))); 6032 // FIXME: should we retrieve TypeSourceInfo? 6033 NameInfo.setNamedTypeInfo(nullptr); 6034 return NameInfo; 6035 } 6036 6037 case UnqualifiedIdKind::IK_DestructorName: { 6038 TypeSourceInfo *TInfo; 6039 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 6040 if (Ty.isNull()) 6041 return DeclarationNameInfo(); 6042 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 6043 Context.getCanonicalType(Ty))); 6044 NameInfo.setNamedTypeInfo(TInfo); 6045 return NameInfo; 6046 } 6047 6048 case UnqualifiedIdKind::IK_TemplateId: { 6049 TemplateName TName = Name.TemplateId->Template.get(); 6050 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 6051 return Context.getNameForTemplate(TName, TNameLoc); 6052 } 6053 6054 } // switch (Name.getKind()) 6055 6056 llvm_unreachable("Unknown name kind"); 6057 } 6058 6059 static QualType getCoreType(QualType Ty) { 6060 do { 6061 if (Ty->isPointerType() || Ty->isReferenceType()) 6062 Ty = Ty->getPointeeType(); 6063 else if (Ty->isArrayType()) 6064 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 6065 else 6066 return Ty.withoutLocalFastQualifiers(); 6067 } while (true); 6068 } 6069 6070 /// hasSimilarParameters - Determine whether the C++ functions Declaration 6071 /// and Definition have "nearly" matching parameters. This heuristic is 6072 /// used to improve diagnostics in the case where an out-of-line function 6073 /// definition doesn't match any declaration within the class or namespace. 6074 /// Also sets Params to the list of indices to the parameters that differ 6075 /// between the declaration and the definition. If hasSimilarParameters 6076 /// returns true and Params is empty, then all of the parameters match. 6077 static bool hasSimilarParameters(ASTContext &Context, 6078 FunctionDecl *Declaration, 6079 FunctionDecl *Definition, 6080 SmallVectorImpl<unsigned> &Params) { 6081 Params.clear(); 6082 if (Declaration->param_size() != Definition->param_size()) 6083 return false; 6084 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 6085 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 6086 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 6087 6088 // The parameter types are identical 6089 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 6090 continue; 6091 6092 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 6093 QualType DefParamBaseTy = getCoreType(DefParamTy); 6094 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 6095 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 6096 6097 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 6098 (DeclTyName && DeclTyName == DefTyName)) 6099 Params.push_back(Idx); 6100 else // The two parameters aren't even close 6101 return false; 6102 } 6103 6104 return true; 6105 } 6106 6107 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given 6108 /// declarator needs to be rebuilt in the current instantiation. 6109 /// Any bits of declarator which appear before the name are valid for 6110 /// consideration here. That's specifically the type in the decl spec 6111 /// and the base type in any member-pointer chunks. 6112 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 6113 DeclarationName Name) { 6114 // The types we specifically need to rebuild are: 6115 // - typenames, typeofs, and decltypes 6116 // - types which will become injected class names 6117 // Of course, we also need to rebuild any type referencing such a 6118 // type. It's safest to just say "dependent", but we call out a 6119 // few cases here. 6120 6121 DeclSpec &DS = D.getMutableDeclSpec(); 6122 switch (DS.getTypeSpecType()) { 6123 case DeclSpec::TST_typename: 6124 case DeclSpec::TST_typeofType: 6125 case DeclSpec::TST_typeof_unqualType: 6126 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait: 6127 #include "clang/Basic/TransformTypeTraits.def" 6128 case DeclSpec::TST_atomic: { 6129 // Grab the type from the parser. 6130 TypeSourceInfo *TSI = nullptr; 6131 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 6132 if (T.isNull() || !T->isInstantiationDependentType()) break; 6133 6134 // Make sure there's a type source info. This isn't really much 6135 // of a waste; most dependent types should have type source info 6136 // attached already. 6137 if (!TSI) 6138 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 6139 6140 // Rebuild the type in the current instantiation. 6141 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 6142 if (!TSI) return true; 6143 6144 // Store the new type back in the decl spec. 6145 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 6146 DS.UpdateTypeRep(LocType); 6147 break; 6148 } 6149 6150 case DeclSpec::TST_decltype: 6151 case DeclSpec::TST_typeof_unqualExpr: 6152 case DeclSpec::TST_typeofExpr: { 6153 Expr *E = DS.getRepAsExpr(); 6154 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 6155 if (Result.isInvalid()) return true; 6156 DS.UpdateExprRep(Result.get()); 6157 break; 6158 } 6159 6160 default: 6161 // Nothing to do for these decl specs. 6162 break; 6163 } 6164 6165 // It doesn't matter what order we do this in. 6166 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 6167 DeclaratorChunk &Chunk = D.getTypeObject(I); 6168 6169 // The only type information in the declarator which can come 6170 // before the declaration name is the base type of a member 6171 // pointer. 6172 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 6173 continue; 6174 6175 // Rebuild the scope specifier in-place. 6176 CXXScopeSpec &SS = Chunk.Mem.Scope(); 6177 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 6178 return true; 6179 } 6180 6181 return false; 6182 } 6183 6184 /// Returns true if the declaration is declared in a system header or from a 6185 /// system macro. 6186 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) { 6187 return SM.isInSystemHeader(D->getLocation()) || 6188 SM.isInSystemMacro(D->getLocation()); 6189 } 6190 6191 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 6192 // Avoid warning twice on the same identifier, and don't warn on redeclaration 6193 // of system decl. 6194 if (D->getPreviousDecl() || D->isImplicit()) 6195 return; 6196 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 6197 if (Status != ReservedIdentifierStatus::NotReserved && 6198 !isFromSystemHeader(Context.getSourceManager(), D)) { 6199 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 6200 << D << static_cast<int>(Status); 6201 } 6202 } 6203 6204 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 6205 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 6206 6207 // Check if we are in an `omp begin/end declare variant` scope. Handle this 6208 // declaration only if the `bind_to_declaration` extension is set. 6209 SmallVector<FunctionDecl *, 4> Bases; 6210 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 6211 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty:: 6212 implementation_extension_bind_to_declaration)) 6213 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 6214 S, D, MultiTemplateParamsArg(), Bases); 6215 6216 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 6217 6218 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 6219 Dcl && Dcl->getDeclContext()->isFileContext()) 6220 Dcl->setTopLevelDeclInObjCContainer(); 6221 6222 if (!Bases.empty()) 6223 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 6224 6225 return Dcl; 6226 } 6227 6228 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 6229 /// If T is the name of a class, then each of the following shall have a 6230 /// name different from T: 6231 /// - every static data member of class T; 6232 /// - every member function of class T 6233 /// - every member of class T that is itself a type; 6234 /// \returns true if the declaration name violates these rules. 6235 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 6236 DeclarationNameInfo NameInfo) { 6237 DeclarationName Name = NameInfo.getName(); 6238 6239 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 6240 while (Record && Record->isAnonymousStructOrUnion()) 6241 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 6242 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 6243 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 6244 return true; 6245 } 6246 6247 return false; 6248 } 6249 6250 /// Diagnose a declaration whose declarator-id has the given 6251 /// nested-name-specifier. 6252 /// 6253 /// \param SS The nested-name-specifier of the declarator-id. 6254 /// 6255 /// \param DC The declaration context to which the nested-name-specifier 6256 /// resolves. 6257 /// 6258 /// \param Name The name of the entity being declared. 6259 /// 6260 /// \param Loc The location of the name of the entity being declared. 6261 /// 6262 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 6263 /// we're declaring an explicit / partial specialization / instantiation. 6264 /// 6265 /// \returns true if we cannot safely recover from this error, false otherwise. 6266 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 6267 DeclarationName Name, 6268 SourceLocation Loc, bool IsTemplateId) { 6269 DeclContext *Cur = CurContext; 6270 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 6271 Cur = Cur->getParent(); 6272 6273 // If the user provided a superfluous scope specifier that refers back to the 6274 // class in which the entity is already declared, diagnose and ignore it. 6275 // 6276 // class X { 6277 // void X::f(); 6278 // }; 6279 // 6280 // Note, it was once ill-formed to give redundant qualification in all 6281 // contexts, but that rule was removed by DR482. 6282 if (Cur->Equals(DC)) { 6283 if (Cur->isRecord()) { 6284 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 6285 : diag::err_member_extra_qualification) 6286 << Name << FixItHint::CreateRemoval(SS.getRange()); 6287 SS.clear(); 6288 } else { 6289 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 6290 } 6291 return false; 6292 } 6293 6294 // Check whether the qualifying scope encloses the scope of the original 6295 // declaration. For a template-id, we perform the checks in 6296 // CheckTemplateSpecializationScope. 6297 if (!Cur->Encloses(DC) && !IsTemplateId) { 6298 if (Cur->isRecord()) 6299 Diag(Loc, diag::err_member_qualification) 6300 << Name << SS.getRange(); 6301 else if (isa<TranslationUnitDecl>(DC)) 6302 Diag(Loc, diag::err_invalid_declarator_global_scope) 6303 << Name << SS.getRange(); 6304 else if (isa<FunctionDecl>(Cur)) 6305 Diag(Loc, diag::err_invalid_declarator_in_function) 6306 << Name << SS.getRange(); 6307 else if (isa<BlockDecl>(Cur)) 6308 Diag(Loc, diag::err_invalid_declarator_in_block) 6309 << Name << SS.getRange(); 6310 else if (isa<ExportDecl>(Cur)) { 6311 if (!isa<NamespaceDecl>(DC)) 6312 Diag(Loc, diag::err_export_non_namespace_scope_name) 6313 << Name << SS.getRange(); 6314 else 6315 // The cases that DC is not NamespaceDecl should be handled in 6316 // CheckRedeclarationExported. 6317 return false; 6318 } else 6319 Diag(Loc, diag::err_invalid_declarator_scope) 6320 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 6321 6322 return true; 6323 } 6324 6325 if (Cur->isRecord()) { 6326 // Cannot qualify members within a class. 6327 Diag(Loc, diag::err_member_qualification) 6328 << Name << SS.getRange(); 6329 SS.clear(); 6330 6331 // C++ constructors and destructors with incorrect scopes can break 6332 // our AST invariants by having the wrong underlying types. If 6333 // that's the case, then drop this declaration entirely. 6334 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 6335 Name.getNameKind() == DeclarationName::CXXDestructorName) && 6336 !Context.hasSameType(Name.getCXXNameType(), 6337 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 6338 return true; 6339 6340 return false; 6341 } 6342 6343 // C++11 [dcl.meaning]p1: 6344 // [...] "The nested-name-specifier of the qualified declarator-id shall 6345 // not begin with a decltype-specifer" 6346 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 6347 while (SpecLoc.getPrefix()) 6348 SpecLoc = SpecLoc.getPrefix(); 6349 if (isa_and_nonnull<DecltypeType>( 6350 SpecLoc.getNestedNameSpecifier()->getAsType())) 6351 Diag(Loc, diag::err_decltype_in_declarator) 6352 << SpecLoc.getTypeLoc().getSourceRange(); 6353 6354 return false; 6355 } 6356 6357 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 6358 MultiTemplateParamsArg TemplateParamLists) { 6359 // TODO: consider using NameInfo for diagnostic. 6360 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6361 DeclarationName Name = NameInfo.getName(); 6362 6363 // All of these full declarators require an identifier. If it doesn't have 6364 // one, the ParsedFreeStandingDeclSpec action should be used. 6365 if (D.isDecompositionDeclarator()) { 6366 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 6367 } else if (!Name) { 6368 if (!D.isInvalidType()) // Reject this if we think it is valid. 6369 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 6370 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 6371 return nullptr; 6372 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 6373 return nullptr; 6374 6375 // The scope passed in may not be a decl scope. Zip up the scope tree until 6376 // we find one that is. 6377 while ((S->getFlags() & Scope::DeclScope) == 0 || 6378 (S->getFlags() & Scope::TemplateParamScope) != 0) 6379 S = S->getParent(); 6380 6381 DeclContext *DC = CurContext; 6382 if (D.getCXXScopeSpec().isInvalid()) 6383 D.setInvalidType(); 6384 else if (D.getCXXScopeSpec().isSet()) { 6385 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 6386 UPPC_DeclarationQualifier)) 6387 return nullptr; 6388 6389 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 6390 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 6391 if (!DC || isa<EnumDecl>(DC)) { 6392 // If we could not compute the declaration context, it's because the 6393 // declaration context is dependent but does not refer to a class, 6394 // class template, or class template partial specialization. Complain 6395 // and return early, to avoid the coming semantic disaster. 6396 Diag(D.getIdentifierLoc(), 6397 diag::err_template_qualified_declarator_no_match) 6398 << D.getCXXScopeSpec().getScopeRep() 6399 << D.getCXXScopeSpec().getRange(); 6400 return nullptr; 6401 } 6402 bool IsDependentContext = DC->isDependentContext(); 6403 6404 if (!IsDependentContext && 6405 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 6406 return nullptr; 6407 6408 // If a class is incomplete, do not parse entities inside it. 6409 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 6410 Diag(D.getIdentifierLoc(), 6411 diag::err_member_def_undefined_record) 6412 << Name << DC << D.getCXXScopeSpec().getRange(); 6413 return nullptr; 6414 } 6415 if (!D.getDeclSpec().isFriendSpecified()) { 6416 if (diagnoseQualifiedDeclaration( 6417 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 6418 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 6419 if (DC->isRecord()) 6420 return nullptr; 6421 6422 D.setInvalidType(); 6423 } 6424 } 6425 6426 // Check whether we need to rebuild the type of the given 6427 // declaration in the current instantiation. 6428 if (EnteringContext && IsDependentContext && 6429 TemplateParamLists.size() != 0) { 6430 ContextRAII SavedContext(*this, DC); 6431 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 6432 D.setInvalidType(); 6433 } 6434 } 6435 6436 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6437 QualType R = TInfo->getType(); 6438 6439 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 6440 UPPC_DeclarationType)) 6441 D.setInvalidType(); 6442 6443 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 6444 forRedeclarationInCurContext()); 6445 6446 // See if this is a redefinition of a variable in the same scope. 6447 if (!D.getCXXScopeSpec().isSet()) { 6448 bool IsLinkageLookup = false; 6449 bool CreateBuiltins = false; 6450 6451 // If the declaration we're planning to build will be a function 6452 // or object with linkage, then look for another declaration with 6453 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 6454 // 6455 // If the declaration we're planning to build will be declared with 6456 // external linkage in the translation unit, create any builtin with 6457 // the same name. 6458 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 6459 /* Do nothing*/; 6460 else if (CurContext->isFunctionOrMethod() && 6461 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 6462 R->isFunctionType())) { 6463 IsLinkageLookup = true; 6464 CreateBuiltins = 6465 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 6466 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 6467 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 6468 CreateBuiltins = true; 6469 6470 if (IsLinkageLookup) { 6471 Previous.clear(LookupRedeclarationWithLinkage); 6472 Previous.setRedeclarationKind(ForExternalRedeclaration); 6473 } 6474 6475 LookupName(Previous, S, CreateBuiltins); 6476 } else { // Something like "int foo::x;" 6477 LookupQualifiedName(Previous, DC); 6478 6479 // C++ [dcl.meaning]p1: 6480 // When the declarator-id is qualified, the declaration shall refer to a 6481 // previously declared member of the class or namespace to which the 6482 // qualifier refers (or, in the case of a namespace, of an element of the 6483 // inline namespace set of that namespace (7.3.1)) or to a specialization 6484 // thereof; [...] 6485 // 6486 // Note that we already checked the context above, and that we do not have 6487 // enough information to make sure that Previous contains the declaration 6488 // we want to match. For example, given: 6489 // 6490 // class X { 6491 // void f(); 6492 // void f(float); 6493 // }; 6494 // 6495 // void X::f(int) { } // ill-formed 6496 // 6497 // In this case, Previous will point to the overload set 6498 // containing the two f's declared in X, but neither of them 6499 // matches. 6500 6501 RemoveUsingDecls(Previous); 6502 } 6503 6504 if (Previous.isSingleResult() && 6505 Previous.getFoundDecl()->isTemplateParameter()) { 6506 // Maybe we will complain about the shadowed template parameter. 6507 if (!D.isInvalidType()) 6508 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 6509 Previous.getFoundDecl()); 6510 6511 // Just pretend that we didn't see the previous declaration. 6512 Previous.clear(); 6513 } 6514 6515 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 6516 // Forget that the previous declaration is the injected-class-name. 6517 Previous.clear(); 6518 6519 // In C++, the previous declaration we find might be a tag type 6520 // (class or enum). In this case, the new declaration will hide the 6521 // tag type. Note that this applies to functions, function templates, and 6522 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 6523 if (Previous.isSingleTagDecl() && 6524 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6525 (TemplateParamLists.size() == 0 || R->isFunctionType())) 6526 Previous.clear(); 6527 6528 // Check that there are no default arguments other than in the parameters 6529 // of a function declaration (C++ only). 6530 if (getLangOpts().CPlusPlus) 6531 CheckExtraCXXDefaultArguments(D); 6532 6533 NamedDecl *New; 6534 6535 bool AddToScope = true; 6536 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 6537 if (TemplateParamLists.size()) { 6538 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 6539 return nullptr; 6540 } 6541 6542 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 6543 } else if (R->isFunctionType()) { 6544 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 6545 TemplateParamLists, 6546 AddToScope); 6547 } else { 6548 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 6549 AddToScope); 6550 } 6551 6552 if (!New) 6553 return nullptr; 6554 6555 // If this has an identifier and is not a function template specialization, 6556 // add it to the scope stack. 6557 if (New->getDeclName() && AddToScope) 6558 PushOnScopeChains(New, S); 6559 6560 if (isInOpenMPDeclareTargetContext()) 6561 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 6562 6563 return New; 6564 } 6565 6566 /// Helper method to turn variable array types into constant array 6567 /// types in certain situations which would otherwise be errors (for 6568 /// GCC compatibility). 6569 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6570 ASTContext &Context, 6571 bool &SizeIsNegative, 6572 llvm::APSInt &Oversized) { 6573 // This method tries to turn a variable array into a constant 6574 // array even when the size isn't an ICE. This is necessary 6575 // for compatibility with code that depends on gcc's buggy 6576 // constant expression folding, like struct {char x[(int)(char*)2];} 6577 SizeIsNegative = false; 6578 Oversized = 0; 6579 6580 if (T->isDependentType()) 6581 return QualType(); 6582 6583 QualifierCollector Qs; 6584 const Type *Ty = Qs.strip(T); 6585 6586 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6587 QualType Pointee = PTy->getPointeeType(); 6588 QualType FixedType = 6589 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6590 Oversized); 6591 if (FixedType.isNull()) return FixedType; 6592 FixedType = Context.getPointerType(FixedType); 6593 return Qs.apply(Context, FixedType); 6594 } 6595 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6596 QualType Inner = PTy->getInnerType(); 6597 QualType FixedType = 6598 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6599 Oversized); 6600 if (FixedType.isNull()) return FixedType; 6601 FixedType = Context.getParenType(FixedType); 6602 return Qs.apply(Context, FixedType); 6603 } 6604 6605 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6606 if (!VLATy) 6607 return QualType(); 6608 6609 QualType ElemTy = VLATy->getElementType(); 6610 if (ElemTy->isVariablyModifiedType()) { 6611 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6612 SizeIsNegative, Oversized); 6613 if (ElemTy.isNull()) 6614 return QualType(); 6615 } 6616 6617 Expr::EvalResult Result; 6618 if (!VLATy->getSizeExpr() || 6619 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6620 return QualType(); 6621 6622 llvm::APSInt Res = Result.Val.getInt(); 6623 6624 // Check whether the array size is negative. 6625 if (Res.isSigned() && Res.isNegative()) { 6626 SizeIsNegative = true; 6627 return QualType(); 6628 } 6629 6630 // Check whether the array is too large to be addressed. 6631 unsigned ActiveSizeBits = 6632 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6633 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6634 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6635 : Res.getActiveBits(); 6636 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6637 Oversized = Res; 6638 return QualType(); 6639 } 6640 6641 QualType FoldedArrayType = Context.getConstantArrayType( 6642 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0); 6643 return Qs.apply(Context, FoldedArrayType); 6644 } 6645 6646 static void 6647 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6648 SrcTL = SrcTL.getUnqualifiedLoc(); 6649 DstTL = DstTL.getUnqualifiedLoc(); 6650 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6651 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6652 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6653 DstPTL.getPointeeLoc()); 6654 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6655 return; 6656 } 6657 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6658 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6659 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6660 DstPTL.getInnerLoc()); 6661 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6662 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6663 return; 6664 } 6665 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6666 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6667 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6668 TypeLoc DstElemTL = DstATL.getElementLoc(); 6669 if (VariableArrayTypeLoc SrcElemATL = 6670 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6671 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6672 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6673 } else { 6674 DstElemTL.initializeFullCopy(SrcElemTL); 6675 } 6676 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6677 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6678 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6679 } 6680 6681 /// Helper method to turn variable array types into constant array 6682 /// types in certain situations which would otherwise be errors (for 6683 /// GCC compatibility). 6684 static TypeSourceInfo* 6685 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6686 ASTContext &Context, 6687 bool &SizeIsNegative, 6688 llvm::APSInt &Oversized) { 6689 QualType FixedTy 6690 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6691 SizeIsNegative, Oversized); 6692 if (FixedTy.isNull()) 6693 return nullptr; 6694 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6695 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6696 FixedTInfo->getTypeLoc()); 6697 return FixedTInfo; 6698 } 6699 6700 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6701 /// true if we were successful. 6702 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6703 QualType &T, SourceLocation Loc, 6704 unsigned FailedFoldDiagID) { 6705 bool SizeIsNegative; 6706 llvm::APSInt Oversized; 6707 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6708 TInfo, Context, SizeIsNegative, Oversized); 6709 if (FixedTInfo) { 6710 Diag(Loc, diag::ext_vla_folded_to_constant); 6711 TInfo = FixedTInfo; 6712 T = FixedTInfo->getType(); 6713 return true; 6714 } 6715 6716 if (SizeIsNegative) 6717 Diag(Loc, diag::err_typecheck_negative_array_size); 6718 else if (Oversized.getBoolValue()) 6719 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6720 else if (FailedFoldDiagID) 6721 Diag(Loc, FailedFoldDiagID); 6722 return false; 6723 } 6724 6725 /// Register the given locally-scoped extern "C" declaration so 6726 /// that it can be found later for redeclarations. We include any extern "C" 6727 /// declaration that is not visible in the translation unit here, not just 6728 /// function-scope declarations. 6729 void 6730 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6731 if (!getLangOpts().CPlusPlus && 6732 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6733 // Don't need to track declarations in the TU in C. 6734 return; 6735 6736 // Note that we have a locally-scoped external with this name. 6737 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6738 } 6739 6740 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6741 // FIXME: We can have multiple results via __attribute__((overloadable)). 6742 auto Result = Context.getExternCContextDecl()->lookup(Name); 6743 return Result.empty() ? nullptr : *Result.begin(); 6744 } 6745 6746 /// Diagnose function specifiers on a declaration of an identifier that 6747 /// does not identify a function. 6748 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6749 // FIXME: We should probably indicate the identifier in question to avoid 6750 // confusion for constructs like "virtual int a(), b;" 6751 if (DS.isVirtualSpecified()) 6752 Diag(DS.getVirtualSpecLoc(), 6753 diag::err_virtual_non_function); 6754 6755 if (DS.hasExplicitSpecifier()) 6756 Diag(DS.getExplicitSpecLoc(), 6757 diag::err_explicit_non_function); 6758 6759 if (DS.isNoreturnSpecified()) 6760 Diag(DS.getNoreturnSpecLoc(), 6761 diag::err_noreturn_non_function); 6762 } 6763 6764 NamedDecl* 6765 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6766 TypeSourceInfo *TInfo, LookupResult &Previous) { 6767 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6768 if (D.getCXXScopeSpec().isSet()) { 6769 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6770 << D.getCXXScopeSpec().getRange(); 6771 D.setInvalidType(); 6772 // Pretend we didn't see the scope specifier. 6773 DC = CurContext; 6774 Previous.clear(); 6775 } 6776 6777 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6778 6779 if (D.getDeclSpec().isInlineSpecified()) 6780 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6781 << getLangOpts().CPlusPlus17; 6782 if (D.getDeclSpec().hasConstexprSpecifier()) 6783 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6784 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6785 6786 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) { 6787 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) 6788 Diag(D.getName().StartLocation, 6789 diag::err_deduction_guide_invalid_specifier) 6790 << "typedef"; 6791 else 6792 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6793 << D.getName().getSourceRange(); 6794 return nullptr; 6795 } 6796 6797 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6798 if (!NewTD) return nullptr; 6799 6800 // Handle attributes prior to checking for duplicates in MergeVarDecl 6801 ProcessDeclAttributes(S, NewTD, D); 6802 6803 CheckTypedefForVariablyModifiedType(S, NewTD); 6804 6805 bool Redeclaration = D.isRedeclaration(); 6806 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6807 D.setRedeclaration(Redeclaration); 6808 return ND; 6809 } 6810 6811 void 6812 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6813 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6814 // then it shall have block scope. 6815 // Note that variably modified types must be fixed before merging the decl so 6816 // that redeclarations will match. 6817 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6818 QualType T = TInfo->getType(); 6819 if (T->isVariablyModifiedType()) { 6820 setFunctionHasBranchProtectedScope(); 6821 6822 if (S->getFnParent() == nullptr) { 6823 bool SizeIsNegative; 6824 llvm::APSInt Oversized; 6825 TypeSourceInfo *FixedTInfo = 6826 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6827 SizeIsNegative, 6828 Oversized); 6829 if (FixedTInfo) { 6830 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6831 NewTD->setTypeSourceInfo(FixedTInfo); 6832 } else { 6833 if (SizeIsNegative) 6834 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6835 else if (T->isVariableArrayType()) 6836 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6837 else if (Oversized.getBoolValue()) 6838 Diag(NewTD->getLocation(), diag::err_array_too_large) 6839 << toString(Oversized, 10); 6840 else 6841 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6842 NewTD->setInvalidDecl(); 6843 } 6844 } 6845 } 6846 } 6847 6848 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6849 /// declares a typedef-name, either using the 'typedef' type specifier or via 6850 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6851 NamedDecl* 6852 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6853 LookupResult &Previous, bool &Redeclaration) { 6854 6855 // Find the shadowed declaration before filtering for scope. 6856 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6857 6858 // Merge the decl with the existing one if appropriate. If the decl is 6859 // in an outer scope, it isn't the same thing. 6860 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6861 /*AllowInlineNamespace*/false); 6862 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6863 if (!Previous.empty()) { 6864 Redeclaration = true; 6865 MergeTypedefNameDecl(S, NewTD, Previous); 6866 } else { 6867 inferGslPointerAttribute(NewTD); 6868 } 6869 6870 if (ShadowedDecl && !Redeclaration) 6871 CheckShadow(NewTD, ShadowedDecl, Previous); 6872 6873 // If this is the C FILE type, notify the AST context. 6874 if (IdentifierInfo *II = NewTD->getIdentifier()) 6875 if (!NewTD->isInvalidDecl() && 6876 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6877 switch (II->getInterestingIdentifierID()) { 6878 case tok::InterestingIdentifierKind::FILE: 6879 Context.setFILEDecl(NewTD); 6880 break; 6881 case tok::InterestingIdentifierKind::jmp_buf: 6882 Context.setjmp_bufDecl(NewTD); 6883 break; 6884 case tok::InterestingIdentifierKind::sigjmp_buf: 6885 Context.setsigjmp_bufDecl(NewTD); 6886 break; 6887 case tok::InterestingIdentifierKind::ucontext_t: 6888 Context.setucontext_tDecl(NewTD); 6889 break; 6890 case tok::InterestingIdentifierKind::float_t: 6891 case tok::InterestingIdentifierKind::double_t: 6892 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context)); 6893 break; 6894 default: 6895 break; 6896 } 6897 } 6898 6899 return NewTD; 6900 } 6901 6902 /// Determines whether the given declaration is an out-of-scope 6903 /// previous declaration. 6904 /// 6905 /// This routine should be invoked when name lookup has found a 6906 /// previous declaration (PrevDecl) that is not in the scope where a 6907 /// new declaration by the same name is being introduced. If the new 6908 /// declaration occurs in a local scope, previous declarations with 6909 /// linkage may still be considered previous declarations (C99 6910 /// 6.2.2p4-5, C++ [basic.link]p6). 6911 /// 6912 /// \param PrevDecl the previous declaration found by name 6913 /// lookup 6914 /// 6915 /// \param DC the context in which the new declaration is being 6916 /// declared. 6917 /// 6918 /// \returns true if PrevDecl is an out-of-scope previous declaration 6919 /// for a new delcaration with the same name. 6920 static bool 6921 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6922 ASTContext &Context) { 6923 if (!PrevDecl) 6924 return false; 6925 6926 if (!PrevDecl->hasLinkage()) 6927 return false; 6928 6929 if (Context.getLangOpts().CPlusPlus) { 6930 // C++ [basic.link]p6: 6931 // If there is a visible declaration of an entity with linkage 6932 // having the same name and type, ignoring entities declared 6933 // outside the innermost enclosing namespace scope, the block 6934 // scope declaration declares that same entity and receives the 6935 // linkage of the previous declaration. 6936 DeclContext *OuterContext = DC->getRedeclContext(); 6937 if (!OuterContext->isFunctionOrMethod()) 6938 // This rule only applies to block-scope declarations. 6939 return false; 6940 6941 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6942 if (PrevOuterContext->isRecord()) 6943 // We found a member function: ignore it. 6944 return false; 6945 6946 // Find the innermost enclosing namespace for the new and 6947 // previous declarations. 6948 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6949 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6950 6951 // The previous declaration is in a different namespace, so it 6952 // isn't the same function. 6953 if (!OuterContext->Equals(PrevOuterContext)) 6954 return false; 6955 } 6956 6957 return true; 6958 } 6959 6960 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6961 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6962 if (!SS.isSet()) return; 6963 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6964 } 6965 6966 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6967 QualType type = decl->getType(); 6968 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6969 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6970 // Various kinds of declaration aren't allowed to be __autoreleasing. 6971 unsigned kind = -1U; 6972 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6973 if (var->hasAttr<BlocksAttr>()) 6974 kind = 0; // __block 6975 else if (!var->hasLocalStorage()) 6976 kind = 1; // global 6977 } else if (isa<ObjCIvarDecl>(decl)) { 6978 kind = 3; // ivar 6979 } else if (isa<FieldDecl>(decl)) { 6980 kind = 2; // field 6981 } 6982 6983 if (kind != -1U) { 6984 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6985 << kind; 6986 } 6987 } else if (lifetime == Qualifiers::OCL_None) { 6988 // Try to infer lifetime. 6989 if (!type->isObjCLifetimeType()) 6990 return false; 6991 6992 lifetime = type->getObjCARCImplicitLifetime(); 6993 type = Context.getLifetimeQualifiedType(type, lifetime); 6994 decl->setType(type); 6995 } 6996 6997 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6998 // Thread-local variables cannot have lifetime. 6999 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 7000 var->getTLSKind()) { 7001 Diag(var->getLocation(), diag::err_arc_thread_ownership) 7002 << var->getType(); 7003 return true; 7004 } 7005 } 7006 7007 return false; 7008 } 7009 7010 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 7011 if (Decl->getType().hasAddressSpace()) 7012 return; 7013 if (Decl->getType()->isDependentType()) 7014 return; 7015 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 7016 QualType Type = Var->getType(); 7017 if (Type->isSamplerT() || Type->isVoidType()) 7018 return; 7019 LangAS ImplAS = LangAS::opencl_private; 7020 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 7021 // __opencl_c_program_scope_global_variables feature, the address space 7022 // for a variable at program scope or a static or extern variable inside 7023 // a function are inferred to be __global. 7024 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 7025 Var->hasGlobalStorage()) 7026 ImplAS = LangAS::opencl_global; 7027 // If the original type from a decayed type is an array type and that array 7028 // type has no address space yet, deduce it now. 7029 if (auto DT = dyn_cast<DecayedType>(Type)) { 7030 auto OrigTy = DT->getOriginalType(); 7031 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 7032 // Add the address space to the original array type and then propagate 7033 // that to the element type through `getAsArrayType`. 7034 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 7035 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 7036 // Re-generate the decayed type. 7037 Type = Context.getDecayedType(OrigTy); 7038 } 7039 } 7040 Type = Context.getAddrSpaceQualType(Type, ImplAS); 7041 // Apply any qualifiers (including address space) from the array type to 7042 // the element type. This implements C99 6.7.3p8: "If the specification of 7043 // an array type includes any type qualifiers, the element type is so 7044 // qualified, not the array type." 7045 if (Type->isArrayType()) 7046 Type = QualType(Context.getAsArrayType(Type), 0); 7047 Decl->setType(Type); 7048 } 7049 } 7050 7051 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 7052 // Ensure that an auto decl is deduced otherwise the checks below might cache 7053 // the wrong linkage. 7054 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 7055 7056 // 'weak' only applies to declarations with external linkage. 7057 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 7058 if (!ND.isExternallyVisible()) { 7059 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 7060 ND.dropAttr<WeakAttr>(); 7061 } 7062 } 7063 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 7064 if (ND.isExternallyVisible()) { 7065 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 7066 ND.dropAttr<WeakRefAttr>(); 7067 ND.dropAttr<AliasAttr>(); 7068 } 7069 } 7070 7071 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 7072 if (VD->hasInit()) { 7073 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 7074 assert(VD->isThisDeclarationADefinition() && 7075 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 7076 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 7077 VD->dropAttr<AliasAttr>(); 7078 } 7079 } 7080 } 7081 7082 // 'selectany' only applies to externally visible variable declarations. 7083 // It does not apply to functions. 7084 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 7085 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 7086 S.Diag(Attr->getLocation(), 7087 diag::err_attribute_selectany_non_extern_data); 7088 ND.dropAttr<SelectAnyAttr>(); 7089 } 7090 } 7091 7092 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 7093 auto *VD = dyn_cast<VarDecl>(&ND); 7094 bool IsAnonymousNS = false; 7095 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 7096 if (VD) { 7097 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 7098 while (NS && !IsAnonymousNS) { 7099 IsAnonymousNS = NS->isAnonymousNamespace(); 7100 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 7101 } 7102 } 7103 // dll attributes require external linkage. Static locals may have external 7104 // linkage but still cannot be explicitly imported or exported. 7105 // In Microsoft mode, a variable defined in anonymous namespace must have 7106 // external linkage in order to be exported. 7107 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 7108 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 7109 (!AnonNSInMicrosoftMode && 7110 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 7111 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 7112 << &ND << Attr; 7113 ND.setInvalidDecl(); 7114 } 7115 } 7116 7117 // Check the attributes on the function type, if any. 7118 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 7119 // Don't declare this variable in the second operand of the for-statement; 7120 // GCC miscompiles that by ending its lifetime before evaluating the 7121 // third operand. See gcc.gnu.org/PR86769. 7122 AttributedTypeLoc ATL; 7123 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 7124 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 7125 TL = ATL.getModifiedLoc()) { 7126 // The [[lifetimebound]] attribute can be applied to the implicit object 7127 // parameter of a non-static member function (other than a ctor or dtor) 7128 // by applying it to the function type. 7129 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 7130 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 7131 if (!MD || MD->isStatic()) { 7132 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 7133 << !MD << A->getRange(); 7134 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 7135 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 7136 << isa<CXXDestructorDecl>(MD) << A->getRange(); 7137 } 7138 } 7139 } 7140 } 7141 } 7142 7143 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 7144 NamedDecl *NewDecl, 7145 bool IsSpecialization, 7146 bool IsDefinition) { 7147 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 7148 return; 7149 7150 bool IsTemplate = false; 7151 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 7152 OldDecl = OldTD->getTemplatedDecl(); 7153 IsTemplate = true; 7154 if (!IsSpecialization) 7155 IsDefinition = false; 7156 } 7157 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 7158 NewDecl = NewTD->getTemplatedDecl(); 7159 IsTemplate = true; 7160 } 7161 7162 if (!OldDecl || !NewDecl) 7163 return; 7164 7165 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 7166 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 7167 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 7168 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 7169 7170 // dllimport and dllexport are inheritable attributes so we have to exclude 7171 // inherited attribute instances. 7172 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 7173 (NewExportAttr && !NewExportAttr->isInherited()); 7174 7175 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 7176 // the only exception being explicit specializations. 7177 // Implicitly generated declarations are also excluded for now because there 7178 // is no other way to switch these to use dllimport or dllexport. 7179 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 7180 7181 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 7182 // Allow with a warning for free functions and global variables. 7183 bool JustWarn = false; 7184 if (!OldDecl->isCXXClassMember()) { 7185 auto *VD = dyn_cast<VarDecl>(OldDecl); 7186 if (VD && !VD->getDescribedVarTemplate()) 7187 JustWarn = true; 7188 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 7189 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 7190 JustWarn = true; 7191 } 7192 7193 // We cannot change a declaration that's been used because IR has already 7194 // been emitted. Dllimported functions will still work though (modulo 7195 // address equality) as they can use the thunk. 7196 if (OldDecl->isUsed()) 7197 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 7198 JustWarn = false; 7199 7200 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 7201 : diag::err_attribute_dll_redeclaration; 7202 S.Diag(NewDecl->getLocation(), DiagID) 7203 << NewDecl 7204 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 7205 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 7206 if (!JustWarn) { 7207 NewDecl->setInvalidDecl(); 7208 return; 7209 } 7210 } 7211 7212 // A redeclaration is not allowed to drop a dllimport attribute, the only 7213 // exceptions being inline function definitions (except for function 7214 // templates), local extern declarations, qualified friend declarations or 7215 // special MSVC extension: in the last case, the declaration is treated as if 7216 // it were marked dllexport. 7217 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 7218 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 7219 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 7220 // Ignore static data because out-of-line definitions are diagnosed 7221 // separately. 7222 IsStaticDataMember = VD->isStaticDataMember(); 7223 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 7224 VarDecl::DeclarationOnly; 7225 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 7226 IsInline = FD->isInlined(); 7227 IsQualifiedFriend = FD->getQualifier() && 7228 FD->getFriendObjectKind() == Decl::FOK_Declared; 7229 } 7230 7231 if (OldImportAttr && !HasNewAttr && 7232 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 7233 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 7234 if (IsMicrosoftABI && IsDefinition) { 7235 if (IsSpecialization) { 7236 S.Diag( 7237 NewDecl->getLocation(), 7238 diag::err_attribute_dllimport_function_specialization_definition); 7239 S.Diag(OldImportAttr->getLocation(), diag::note_attribute); 7240 NewDecl->dropAttr<DLLImportAttr>(); 7241 } else { 7242 S.Diag(NewDecl->getLocation(), 7243 diag::warn_redeclaration_without_import_attribute) 7244 << NewDecl; 7245 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 7246 NewDecl->dropAttr<DLLImportAttr>(); 7247 NewDecl->addAttr(DLLExportAttr::CreateImplicit( 7248 S.Context, NewImportAttr->getRange())); 7249 } 7250 } else if (IsMicrosoftABI && IsSpecialization) { 7251 assert(!IsDefinition); 7252 // MSVC allows this. Keep the inherited attribute. 7253 } else { 7254 S.Diag(NewDecl->getLocation(), 7255 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 7256 << NewDecl << OldImportAttr; 7257 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 7258 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 7259 OldDecl->dropAttr<DLLImportAttr>(); 7260 NewDecl->dropAttr<DLLImportAttr>(); 7261 } 7262 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 7263 // In MinGW, seeing a function declared inline drops the dllimport 7264 // attribute. 7265 OldDecl->dropAttr<DLLImportAttr>(); 7266 NewDecl->dropAttr<DLLImportAttr>(); 7267 S.Diag(NewDecl->getLocation(), 7268 diag::warn_dllimport_dropped_from_inline_function) 7269 << NewDecl << OldImportAttr; 7270 } 7271 7272 // A specialization of a class template member function is processed here 7273 // since it's a redeclaration. If the parent class is dllexport, the 7274 // specialization inherits that attribute. This doesn't happen automatically 7275 // since the parent class isn't instantiated until later. 7276 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 7277 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 7278 !NewImportAttr && !NewExportAttr) { 7279 if (const DLLExportAttr *ParentExportAttr = 7280 MD->getParent()->getAttr<DLLExportAttr>()) { 7281 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 7282 NewAttr->setInherited(true); 7283 NewDecl->addAttr(NewAttr); 7284 } 7285 } 7286 } 7287 } 7288 7289 /// Given that we are within the definition of the given function, 7290 /// will that definition behave like C99's 'inline', where the 7291 /// definition is discarded except for optimization purposes? 7292 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 7293 // Try to avoid calling GetGVALinkageForFunction. 7294 7295 // All cases of this require the 'inline' keyword. 7296 if (!FD->isInlined()) return false; 7297 7298 // This is only possible in C++ with the gnu_inline attribute. 7299 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 7300 return false; 7301 7302 // Okay, go ahead and call the relatively-more-expensive function. 7303 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 7304 } 7305 7306 /// Determine whether a variable is extern "C" prior to attaching 7307 /// an initializer. We can't just call isExternC() here, because that 7308 /// will also compute and cache whether the declaration is externally 7309 /// visible, which might change when we attach the initializer. 7310 /// 7311 /// This can only be used if the declaration is known to not be a 7312 /// redeclaration of an internal linkage declaration. 7313 /// 7314 /// For instance: 7315 /// 7316 /// auto x = []{}; 7317 /// 7318 /// Attaching the initializer here makes this declaration not externally 7319 /// visible, because its type has internal linkage. 7320 /// 7321 /// FIXME: This is a hack. 7322 template<typename T> 7323 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 7324 if (S.getLangOpts().CPlusPlus) { 7325 // In C++, the overloadable attribute negates the effects of extern "C". 7326 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 7327 return false; 7328 7329 // So do CUDA's host/device attributes. 7330 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 7331 D->template hasAttr<CUDAHostAttr>())) 7332 return false; 7333 } 7334 return D->isExternC(); 7335 } 7336 7337 static bool shouldConsiderLinkage(const VarDecl *VD) { 7338 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 7339 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 7340 isa<OMPDeclareMapperDecl>(DC)) 7341 return VD->hasExternalStorage(); 7342 if (DC->isFileContext()) 7343 return true; 7344 if (DC->isRecord()) 7345 return false; 7346 if (DC->getDeclKind() == Decl::HLSLBuffer) 7347 return false; 7348 7349 if (isa<RequiresExprBodyDecl>(DC)) 7350 return false; 7351 llvm_unreachable("Unexpected context"); 7352 } 7353 7354 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 7355 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 7356 if (DC->isFileContext() || DC->isFunctionOrMethod() || 7357 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 7358 return true; 7359 if (DC->isRecord()) 7360 return false; 7361 llvm_unreachable("Unexpected context"); 7362 } 7363 7364 static bool hasParsedAttr(Scope *S, const Declarator &PD, 7365 ParsedAttr::Kind Kind) { 7366 // Check decl attributes on the DeclSpec. 7367 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 7368 return true; 7369 7370 // Walk the declarator structure, checking decl attributes that were in a type 7371 // position to the decl itself. 7372 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 7373 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 7374 return true; 7375 } 7376 7377 // Finally, check attributes on the decl itself. 7378 return PD.getAttributes().hasAttribute(Kind) || 7379 PD.getDeclarationAttributes().hasAttribute(Kind); 7380 } 7381 7382 /// Adjust the \c DeclContext for a function or variable that might be a 7383 /// function-local external declaration. 7384 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 7385 if (!DC->isFunctionOrMethod()) 7386 return false; 7387 7388 // If this is a local extern function or variable declared within a function 7389 // template, don't add it into the enclosing namespace scope until it is 7390 // instantiated; it might have a dependent type right now. 7391 if (DC->isDependentContext()) 7392 return true; 7393 7394 // C++11 [basic.link]p7: 7395 // When a block scope declaration of an entity with linkage is not found to 7396 // refer to some other declaration, then that entity is a member of the 7397 // innermost enclosing namespace. 7398 // 7399 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 7400 // semantically-enclosing namespace, not a lexically-enclosing one. 7401 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 7402 DC = DC->getParent(); 7403 return true; 7404 } 7405 7406 /// Returns true if given declaration has external C language linkage. 7407 static bool isDeclExternC(const Decl *D) { 7408 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 7409 return FD->isExternC(); 7410 if (const auto *VD = dyn_cast<VarDecl>(D)) 7411 return VD->isExternC(); 7412 7413 llvm_unreachable("Unknown type of decl!"); 7414 } 7415 7416 /// Returns true if there hasn't been any invalid type diagnosed. 7417 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 7418 DeclContext *DC = NewVD->getDeclContext(); 7419 QualType R = NewVD->getType(); 7420 7421 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 7422 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 7423 // argument. 7424 if (R->isImageType() || R->isPipeType()) { 7425 Se.Diag(NewVD->getLocation(), 7426 diag::err_opencl_type_can_only_be_used_as_function_parameter) 7427 << R; 7428 NewVD->setInvalidDecl(); 7429 return false; 7430 } 7431 7432 // OpenCL v1.2 s6.9.r: 7433 // The event type cannot be used to declare a program scope variable. 7434 // OpenCL v2.0 s6.9.q: 7435 // The clk_event_t and reserve_id_t types cannot be declared in program 7436 // scope. 7437 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 7438 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 7439 Se.Diag(NewVD->getLocation(), 7440 diag::err_invalid_type_for_program_scope_var) 7441 << R; 7442 NewVD->setInvalidDecl(); 7443 return false; 7444 } 7445 } 7446 7447 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 7448 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 7449 Se.getLangOpts())) { 7450 QualType NR = R.getCanonicalType(); 7451 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 7452 NR->isReferenceType()) { 7453 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 7454 NR->isFunctionReferenceType()) { 7455 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 7456 << NR->isReferenceType(); 7457 NewVD->setInvalidDecl(); 7458 return false; 7459 } 7460 NR = NR->getPointeeType(); 7461 } 7462 } 7463 7464 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 7465 Se.getLangOpts())) { 7466 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 7467 // half array type (unless the cl_khr_fp16 extension is enabled). 7468 if (Se.Context.getBaseElementType(R)->isHalfType()) { 7469 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 7470 NewVD->setInvalidDecl(); 7471 return false; 7472 } 7473 } 7474 7475 // OpenCL v1.2 s6.9.r: 7476 // The event type cannot be used with the __local, __constant and __global 7477 // address space qualifiers. 7478 if (R->isEventT()) { 7479 if (R.getAddressSpace() != LangAS::opencl_private) { 7480 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 7481 NewVD->setInvalidDecl(); 7482 return false; 7483 } 7484 } 7485 7486 if (R->isSamplerT()) { 7487 // OpenCL v1.2 s6.9.b p4: 7488 // The sampler type cannot be used with the __local and __global address 7489 // space qualifiers. 7490 if (R.getAddressSpace() == LangAS::opencl_local || 7491 R.getAddressSpace() == LangAS::opencl_global) { 7492 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 7493 NewVD->setInvalidDecl(); 7494 } 7495 7496 // OpenCL v1.2 s6.12.14.1: 7497 // A global sampler must be declared with either the constant address 7498 // space qualifier or with the const qualifier. 7499 if (DC->isTranslationUnit() && 7500 !(R.getAddressSpace() == LangAS::opencl_constant || 7501 R.isConstQualified())) { 7502 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 7503 NewVD->setInvalidDecl(); 7504 } 7505 if (NewVD->isInvalidDecl()) 7506 return false; 7507 } 7508 7509 return true; 7510 } 7511 7512 template <typename AttrTy> 7513 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 7514 const TypedefNameDecl *TND = TT->getDecl(); 7515 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 7516 AttrTy *Clone = Attribute->clone(S.Context); 7517 Clone->setInherited(true); 7518 D->addAttr(Clone); 7519 } 7520 } 7521 7522 // This function emits warning and a corresponding note based on the 7523 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable 7524 // declarations of an annotated type must be const qualified. 7525 void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) { 7526 QualType VarType = VD->getType().getCanonicalType(); 7527 7528 // Ignore local declarations (for now) and those with const qualification. 7529 // TODO: Local variables should not be allowed if their type declaration has 7530 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch. 7531 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified()) 7532 return; 7533 7534 if (VarType->isArrayType()) { 7535 // Retrieve element type for array declarations. 7536 VarType = S.getASTContext().getBaseElementType(VarType); 7537 } 7538 7539 const RecordDecl *RD = VarType->getAsRecordDecl(); 7540 7541 // Check if the record declaration is present and if it has any attributes. 7542 if (RD == nullptr) 7543 return; 7544 7545 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) { 7546 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD; 7547 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement); 7548 return; 7549 } 7550 } 7551 7552 NamedDecl *Sema::ActOnVariableDeclarator( 7553 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 7554 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 7555 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 7556 QualType R = TInfo->getType(); 7557 DeclarationName Name = GetNameForDeclarator(D).getName(); 7558 7559 IdentifierInfo *II = Name.getAsIdentifierInfo(); 7560 bool IsPlaceholderVariable = false; 7561 7562 if (D.isDecompositionDeclarator()) { 7563 // Take the name of the first declarator as our name for diagnostic 7564 // purposes. 7565 auto &Decomp = D.getDecompositionDeclarator(); 7566 if (!Decomp.bindings().empty()) { 7567 II = Decomp.bindings()[0].Name; 7568 Name = II; 7569 } 7570 } else if (!II) { 7571 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 7572 return nullptr; 7573 } 7574 7575 7576 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 7577 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 7578 7579 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) && 7580 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) { 7581 IsPlaceholderVariable = true; 7582 if (!Previous.empty()) { 7583 NamedDecl *PrevDecl = *Previous.begin(); 7584 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals( 7585 DC->getRedeclContext()); 7586 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) 7587 DiagPlaceholderVariableDefinition(D.getIdentifierLoc()); 7588 } 7589 } 7590 7591 // dllimport globals without explicit storage class are treated as extern. We 7592 // have to change the storage class this early to get the right DeclContext. 7593 if (SC == SC_None && !DC->isRecord() && 7594 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 7595 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 7596 SC = SC_Extern; 7597 7598 DeclContext *OriginalDC = DC; 7599 bool IsLocalExternDecl = SC == SC_Extern && 7600 adjustContextForLocalExternDecl(DC); 7601 7602 if (SCSpec == DeclSpec::SCS_mutable) { 7603 // mutable can only appear on non-static class members, so it's always 7604 // an error here 7605 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 7606 D.setInvalidType(); 7607 SC = SC_None; 7608 } 7609 7610 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 7611 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 7612 D.getDeclSpec().getStorageClassSpecLoc())) { 7613 // In C++11, the 'register' storage class specifier is deprecated. 7614 // Suppress the warning in system macros, it's used in macros in some 7615 // popular C system headers, such as in glibc's htonl() macro. 7616 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7617 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 7618 : diag::warn_deprecated_register) 7619 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7620 } 7621 7622 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 7623 7624 if (!DC->isRecord() && S->getFnParent() == nullptr) { 7625 // C99 6.9p2: The storage-class specifiers auto and register shall not 7626 // appear in the declaration specifiers in an external declaration. 7627 // Global Register+Asm is a GNU extension we support. 7628 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 7629 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 7630 D.setInvalidType(); 7631 } 7632 } 7633 7634 // If this variable has a VLA type and an initializer, try to 7635 // fold to a constant-sized type. This is otherwise invalid. 7636 if (D.hasInitializer() && R->isVariableArrayType()) 7637 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7638 /*DiagID=*/0); 7639 7640 bool IsMemberSpecialization = false; 7641 bool IsVariableTemplateSpecialization = false; 7642 bool IsPartialSpecialization = false; 7643 bool IsVariableTemplate = false; 7644 VarDecl *NewVD = nullptr; 7645 VarTemplateDecl *NewTemplate = nullptr; 7646 TemplateParameterList *TemplateParams = nullptr; 7647 if (!getLangOpts().CPlusPlus) { 7648 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7649 II, R, TInfo, SC); 7650 7651 if (R->getContainedDeducedType()) 7652 ParsingInitForAutoVars.insert(NewVD); 7653 7654 if (D.isInvalidType()) 7655 NewVD->setInvalidDecl(); 7656 7657 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7658 NewVD->hasLocalStorage()) 7659 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7660 NTCUC_AutoVar, NTCUK_Destruct); 7661 } else { 7662 bool Invalid = false; 7663 7664 if (DC->isRecord() && !CurContext->isRecord()) { 7665 // This is an out-of-line definition of a static data member. 7666 switch (SC) { 7667 case SC_None: 7668 break; 7669 case SC_Static: 7670 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7671 diag::err_static_out_of_line) 7672 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7673 break; 7674 case SC_Auto: 7675 case SC_Register: 7676 case SC_Extern: 7677 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7678 // to names of variables declared in a block or to function parameters. 7679 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7680 // of class members 7681 7682 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7683 diag::err_storage_class_for_static_member) 7684 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7685 break; 7686 case SC_PrivateExtern: 7687 llvm_unreachable("C storage class in c++!"); 7688 } 7689 } 7690 7691 if (SC == SC_Static && CurContext->isRecord()) { 7692 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7693 // Walk up the enclosing DeclContexts to check for any that are 7694 // incompatible with static data members. 7695 const DeclContext *FunctionOrMethod = nullptr; 7696 const CXXRecordDecl *AnonStruct = nullptr; 7697 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7698 if (Ctxt->isFunctionOrMethod()) { 7699 FunctionOrMethod = Ctxt; 7700 break; 7701 } 7702 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7703 if (ParentDecl && !ParentDecl->getDeclName()) { 7704 AnonStruct = ParentDecl; 7705 break; 7706 } 7707 } 7708 if (FunctionOrMethod) { 7709 // C++ [class.static.data]p5: A local class shall not have static data 7710 // members. 7711 Diag(D.getIdentifierLoc(), 7712 diag::err_static_data_member_not_allowed_in_local_class) 7713 << Name << RD->getDeclName() 7714 << llvm::to_underlying(RD->getTagKind()); 7715 } else if (AnonStruct) { 7716 // C++ [class.static.data]p4: Unnamed classes and classes contained 7717 // directly or indirectly within unnamed classes shall not contain 7718 // static data members. 7719 Diag(D.getIdentifierLoc(), 7720 diag::err_static_data_member_not_allowed_in_anon_struct) 7721 << Name << llvm::to_underlying(AnonStruct->getTagKind()); 7722 Invalid = true; 7723 } else if (RD->isUnion()) { 7724 // C++98 [class.union]p1: If a union contains a static data member, 7725 // the program is ill-formed. C++11 drops this restriction. 7726 Diag(D.getIdentifierLoc(), 7727 getLangOpts().CPlusPlus11 7728 ? diag::warn_cxx98_compat_static_data_member_in_union 7729 : diag::ext_static_data_member_in_union) << Name; 7730 } 7731 } 7732 } 7733 7734 // Match up the template parameter lists with the scope specifier, then 7735 // determine whether we have a template or a template specialization. 7736 bool InvalidScope = false; 7737 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7738 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7739 D.getCXXScopeSpec(), 7740 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7741 ? D.getName().TemplateId 7742 : nullptr, 7743 TemplateParamLists, 7744 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7745 Invalid |= InvalidScope; 7746 7747 if (TemplateParams) { 7748 if (!TemplateParams->size() && 7749 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7750 // There is an extraneous 'template<>' for this variable. Complain 7751 // about it, but allow the declaration of the variable. 7752 Diag(TemplateParams->getTemplateLoc(), 7753 diag::err_template_variable_noparams) 7754 << II 7755 << SourceRange(TemplateParams->getTemplateLoc(), 7756 TemplateParams->getRAngleLoc()); 7757 TemplateParams = nullptr; 7758 } else { 7759 // Check that we can declare a template here. 7760 if (CheckTemplateDeclScope(S, TemplateParams)) 7761 return nullptr; 7762 7763 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7764 // This is an explicit specialization or a partial specialization. 7765 IsVariableTemplateSpecialization = true; 7766 IsPartialSpecialization = TemplateParams->size() > 0; 7767 } else { // if (TemplateParams->size() > 0) 7768 // This is a template declaration. 7769 IsVariableTemplate = true; 7770 7771 // Only C++1y supports variable templates (N3651). 7772 Diag(D.getIdentifierLoc(), 7773 getLangOpts().CPlusPlus14 7774 ? diag::warn_cxx11_compat_variable_template 7775 : diag::ext_variable_template); 7776 } 7777 } 7778 } else { 7779 // Check that we can declare a member specialization here. 7780 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7781 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7782 return nullptr; 7783 assert((Invalid || 7784 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7785 "should have a 'template<>' for this decl"); 7786 } 7787 7788 if (IsVariableTemplateSpecialization) { 7789 SourceLocation TemplateKWLoc = 7790 TemplateParamLists.size() > 0 7791 ? TemplateParamLists[0]->getTemplateLoc() 7792 : SourceLocation(); 7793 DeclResult Res = ActOnVarTemplateSpecialization( 7794 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7795 IsPartialSpecialization); 7796 if (Res.isInvalid()) 7797 return nullptr; 7798 NewVD = cast<VarDecl>(Res.get()); 7799 AddToScope = false; 7800 } else if (D.isDecompositionDeclarator()) { 7801 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7802 D.getIdentifierLoc(), R, TInfo, SC, 7803 Bindings); 7804 } else 7805 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7806 D.getIdentifierLoc(), II, R, TInfo, SC); 7807 7808 // If this is supposed to be a variable template, create it as such. 7809 if (IsVariableTemplate) { 7810 NewTemplate = 7811 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7812 TemplateParams, NewVD); 7813 NewVD->setDescribedVarTemplate(NewTemplate); 7814 } 7815 7816 // If this decl has an auto type in need of deduction, make a note of the 7817 // Decl so we can diagnose uses of it in its own initializer. 7818 if (R->getContainedDeducedType()) 7819 ParsingInitForAutoVars.insert(NewVD); 7820 7821 if (D.isInvalidType() || Invalid) { 7822 NewVD->setInvalidDecl(); 7823 if (NewTemplate) 7824 NewTemplate->setInvalidDecl(); 7825 } 7826 7827 SetNestedNameSpecifier(*this, NewVD, D); 7828 7829 // If we have any template parameter lists that don't directly belong to 7830 // the variable (matching the scope specifier), store them. 7831 // An explicit variable template specialization does not own any template 7832 // parameter lists. 7833 bool IsExplicitSpecialization = 7834 IsVariableTemplateSpecialization && !IsPartialSpecialization; 7835 unsigned VDTemplateParamLists = 7836 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0; 7837 if (TemplateParamLists.size() > VDTemplateParamLists) 7838 NewVD->setTemplateParameterListsInfo( 7839 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7840 } 7841 7842 if (D.getDeclSpec().isInlineSpecified()) { 7843 if (!getLangOpts().CPlusPlus) { 7844 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7845 << 0; 7846 } else if (CurContext->isFunctionOrMethod()) { 7847 // 'inline' is not allowed on block scope variable declaration. 7848 Diag(D.getDeclSpec().getInlineSpecLoc(), 7849 diag::err_inline_declaration_block_scope) << Name 7850 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7851 } else { 7852 Diag(D.getDeclSpec().getInlineSpecLoc(), 7853 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7854 : diag::ext_inline_variable); 7855 NewVD->setInlineSpecified(); 7856 } 7857 } 7858 7859 // Set the lexical context. If the declarator has a C++ scope specifier, the 7860 // lexical context will be different from the semantic context. 7861 NewVD->setLexicalDeclContext(CurContext); 7862 if (NewTemplate) 7863 NewTemplate->setLexicalDeclContext(CurContext); 7864 7865 if (IsLocalExternDecl) { 7866 if (D.isDecompositionDeclarator()) 7867 for (auto *B : Bindings) 7868 B->setLocalExternDecl(); 7869 else 7870 NewVD->setLocalExternDecl(); 7871 } 7872 7873 bool EmitTLSUnsupportedError = false; 7874 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7875 // C++11 [dcl.stc]p4: 7876 // When thread_local is applied to a variable of block scope the 7877 // storage-class-specifier static is implied if it does not appear 7878 // explicitly. 7879 // Core issue: 'static' is not implied if the variable is declared 7880 // 'extern'. 7881 if (NewVD->hasLocalStorage() && 7882 (SCSpec != DeclSpec::SCS_unspecified || 7883 TSCS != DeclSpec::TSCS_thread_local || 7884 !DC->isFunctionOrMethod())) 7885 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7886 diag::err_thread_non_global) 7887 << DeclSpec::getSpecifierName(TSCS); 7888 else if (!Context.getTargetInfo().isTLSSupported()) { 7889 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice || 7890 getLangOpts().SYCLIsDevice) { 7891 // Postpone error emission until we've collected attributes required to 7892 // figure out whether it's a host or device variable and whether the 7893 // error should be ignored. 7894 EmitTLSUnsupportedError = true; 7895 // We still need to mark the variable as TLS so it shows up in AST with 7896 // proper storage class for other tools to use even if we're not going 7897 // to emit any code for it. 7898 NewVD->setTSCSpec(TSCS); 7899 } else 7900 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7901 diag::err_thread_unsupported); 7902 } else 7903 NewVD->setTSCSpec(TSCS); 7904 } 7905 7906 switch (D.getDeclSpec().getConstexprSpecifier()) { 7907 case ConstexprSpecKind::Unspecified: 7908 break; 7909 7910 case ConstexprSpecKind::Consteval: 7911 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7912 diag::err_constexpr_wrong_decl_kind) 7913 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7914 [[fallthrough]]; 7915 7916 case ConstexprSpecKind::Constexpr: 7917 NewVD->setConstexpr(true); 7918 // C++1z [dcl.spec.constexpr]p1: 7919 // A static data member declared with the constexpr specifier is 7920 // implicitly an inline variable. 7921 if (NewVD->isStaticDataMember() && 7922 (getLangOpts().CPlusPlus17 || 7923 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7924 NewVD->setImplicitlyInline(); 7925 break; 7926 7927 case ConstexprSpecKind::Constinit: 7928 if (!NewVD->hasGlobalStorage()) 7929 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7930 diag::err_constinit_local_variable); 7931 else 7932 NewVD->addAttr( 7933 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(), 7934 ConstInitAttr::Keyword_constinit)); 7935 break; 7936 } 7937 7938 // C99 6.7.4p3 7939 // An inline definition of a function with external linkage shall 7940 // not contain a definition of a modifiable object with static or 7941 // thread storage duration... 7942 // We only apply this when the function is required to be defined 7943 // elsewhere, i.e. when the function is not 'extern inline'. Note 7944 // that a local variable with thread storage duration still has to 7945 // be marked 'static'. Also note that it's possible to get these 7946 // semantics in C++ using __attribute__((gnu_inline)). 7947 if (SC == SC_Static && S->getFnParent() != nullptr && 7948 !NewVD->getType().isConstQualified()) { 7949 FunctionDecl *CurFD = getCurFunctionDecl(); 7950 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7951 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7952 diag::warn_static_local_in_extern_inline); 7953 MaybeSuggestAddingStaticToDecl(CurFD); 7954 } 7955 } 7956 7957 if (D.getDeclSpec().isModulePrivateSpecified()) { 7958 if (IsVariableTemplateSpecialization) 7959 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7960 << (IsPartialSpecialization ? 1 : 0) 7961 << FixItHint::CreateRemoval( 7962 D.getDeclSpec().getModulePrivateSpecLoc()); 7963 else if (IsMemberSpecialization) 7964 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7965 << 2 7966 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7967 else if (NewVD->hasLocalStorage()) 7968 Diag(NewVD->getLocation(), diag::err_module_private_local) 7969 << 0 << NewVD 7970 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7971 << FixItHint::CreateRemoval( 7972 D.getDeclSpec().getModulePrivateSpecLoc()); 7973 else { 7974 NewVD->setModulePrivate(); 7975 if (NewTemplate) 7976 NewTemplate->setModulePrivate(); 7977 for (auto *B : Bindings) 7978 B->setModulePrivate(); 7979 } 7980 } 7981 7982 if (getLangOpts().OpenCL) { 7983 deduceOpenCLAddressSpace(NewVD); 7984 7985 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7986 if (TSC != TSCS_unspecified) { 7987 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7988 diag::err_opencl_unknown_type_specifier) 7989 << getLangOpts().getOpenCLVersionString() 7990 << DeclSpec::getSpecifierName(TSC) << 1; 7991 NewVD->setInvalidDecl(); 7992 } 7993 } 7994 7995 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply 7996 // address space if the table has local storage (semantic checks elsewhere 7997 // will produce an error anyway). 7998 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) { 7999 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() && 8000 !NewVD->hasLocalStorage()) { 8001 QualType Type = Context.getAddrSpaceQualType( 8002 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1)); 8003 NewVD->setType(Type); 8004 } 8005 } 8006 8007 // Handle attributes prior to checking for duplicates in MergeVarDecl 8008 ProcessDeclAttributes(S, NewVD, D); 8009 8010 // FIXME: This is probably the wrong location to be doing this and we should 8011 // probably be doing this for more attributes (especially for function 8012 // pointer attributes such as format, warn_unused_result, etc.). Ideally 8013 // the code to copy attributes would be generated by TableGen. 8014 if (R->isFunctionPointerType()) 8015 if (const auto *TT = R->getAs<TypedefType>()) 8016 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 8017 8018 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice || 8019 getLangOpts().SYCLIsDevice) { 8020 if (EmitTLSUnsupportedError && 8021 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 8022 (getLangOpts().OpenMPIsTargetDevice && 8023 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 8024 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8025 diag::err_thread_unsupported); 8026 8027 if (EmitTLSUnsupportedError && 8028 (LangOpts.SYCLIsDevice || 8029 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice))) 8030 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 8031 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 8032 // storage [duration]." 8033 if (SC == SC_None && S->getFnParent() != nullptr && 8034 (NewVD->hasAttr<CUDASharedAttr>() || 8035 NewVD->hasAttr<CUDAConstantAttr>())) { 8036 NewVD->setStorageClass(SC_Static); 8037 } 8038 } 8039 8040 // Ensure that dllimport globals without explicit storage class are treated as 8041 // extern. The storage class is set above using parsed attributes. Now we can 8042 // check the VarDecl itself. 8043 assert(!NewVD->hasAttr<DLLImportAttr>() || 8044 NewVD->getAttr<DLLImportAttr>()->isInherited() || 8045 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 8046 8047 // In auto-retain/release, infer strong retension for variables of 8048 // retainable type. 8049 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 8050 NewVD->setInvalidDecl(); 8051 8052 // Handle GNU asm-label extension (encoded as an attribute). 8053 if (Expr *E = (Expr*)D.getAsmLabel()) { 8054 // The parser guarantees this is a string. 8055 StringLiteral *SE = cast<StringLiteral>(E); 8056 StringRef Label = SE->getString(); 8057 if (S->getFnParent() != nullptr) { 8058 switch (SC) { 8059 case SC_None: 8060 case SC_Auto: 8061 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 8062 break; 8063 case SC_Register: 8064 // Local Named register 8065 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 8066 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 8067 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 8068 break; 8069 case SC_Static: 8070 case SC_Extern: 8071 case SC_PrivateExtern: 8072 break; 8073 } 8074 } else if (SC == SC_Register) { 8075 // Global Named register 8076 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 8077 const auto &TI = Context.getTargetInfo(); 8078 bool HasSizeMismatch; 8079 8080 if (!TI.isValidGCCRegisterName(Label)) 8081 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 8082 else if (!TI.validateGlobalRegisterVariable(Label, 8083 Context.getTypeSize(R), 8084 HasSizeMismatch)) 8085 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 8086 else if (HasSizeMismatch) 8087 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 8088 } 8089 8090 if (!R->isIntegralType(Context) && !R->isPointerType()) { 8091 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 8092 NewVD->setInvalidDecl(true); 8093 } 8094 } 8095 8096 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 8097 /*IsLiteralLabel=*/true, 8098 SE->getStrTokenLoc(0))); 8099 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8100 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8101 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 8102 if (I != ExtnameUndeclaredIdentifiers.end()) { 8103 if (isDeclExternC(NewVD)) { 8104 NewVD->addAttr(I->second); 8105 ExtnameUndeclaredIdentifiers.erase(I); 8106 } else 8107 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 8108 << /*Variable*/1 << NewVD; 8109 } 8110 } 8111 8112 // Find the shadowed declaration before filtering for scope. 8113 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 8114 ? getShadowedDeclaration(NewVD, Previous) 8115 : nullptr; 8116 8117 // Don't consider existing declarations that are in a different 8118 // scope and are out-of-semantic-context declarations (if the new 8119 // declaration has linkage). 8120 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 8121 D.getCXXScopeSpec().isNotEmpty() || 8122 IsMemberSpecialization || 8123 IsVariableTemplateSpecialization); 8124 8125 // Check whether the previous declaration is in the same block scope. This 8126 // affects whether we merge types with it, per C++11 [dcl.array]p3. 8127 if (getLangOpts().CPlusPlus && 8128 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 8129 NewVD->setPreviousDeclInSameBlockScope( 8130 Previous.isSingleResult() && !Previous.isShadowed() && 8131 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 8132 8133 if (!getLangOpts().CPlusPlus) { 8134 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 8135 } else { 8136 // If this is an explicit specialization of a static data member, check it. 8137 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 8138 CheckMemberSpecialization(NewVD, Previous)) 8139 NewVD->setInvalidDecl(); 8140 8141 // Merge the decl with the existing one if appropriate. 8142 if (!Previous.empty()) { 8143 if (Previous.isSingleResult() && 8144 isa<FieldDecl>(Previous.getFoundDecl()) && 8145 D.getCXXScopeSpec().isSet()) { 8146 // The user tried to define a non-static data member 8147 // out-of-line (C++ [dcl.meaning]p1). 8148 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 8149 << D.getCXXScopeSpec().getRange(); 8150 Previous.clear(); 8151 NewVD->setInvalidDecl(); 8152 } 8153 } else if (D.getCXXScopeSpec().isSet()) { 8154 // No previous declaration in the qualifying scope. 8155 Diag(D.getIdentifierLoc(), diag::err_no_member) 8156 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 8157 << D.getCXXScopeSpec().getRange(); 8158 NewVD->setInvalidDecl(); 8159 } 8160 8161 if (!IsVariableTemplateSpecialization && !IsPlaceholderVariable) 8162 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 8163 8164 // CheckVariableDeclaration will set NewVD as invalid if something is in 8165 // error like WebAssembly tables being declared as arrays with a non-zero 8166 // size, but then parsing continues and emits further errors on that line. 8167 // To avoid that we check here if it happened and return nullptr. 8168 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl()) 8169 return nullptr; 8170 8171 if (NewTemplate) { 8172 VarTemplateDecl *PrevVarTemplate = 8173 NewVD->getPreviousDecl() 8174 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 8175 : nullptr; 8176 8177 // Check the template parameter list of this declaration, possibly 8178 // merging in the template parameter list from the previous variable 8179 // template declaration. 8180 if (CheckTemplateParameterList( 8181 TemplateParams, 8182 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 8183 : nullptr, 8184 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 8185 DC->isDependentContext()) 8186 ? TPC_ClassTemplateMember 8187 : TPC_VarTemplate)) 8188 NewVD->setInvalidDecl(); 8189 8190 // If we are providing an explicit specialization of a static variable 8191 // template, make a note of that. 8192 if (PrevVarTemplate && 8193 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 8194 PrevVarTemplate->setMemberSpecialization(); 8195 } 8196 } 8197 8198 // Diagnose shadowed variables iff this isn't a redeclaration. 8199 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration()) 8200 CheckShadow(NewVD, ShadowedDecl, Previous); 8201 8202 ProcessPragmaWeak(S, NewVD); 8203 8204 // If this is the first declaration of an extern C variable, update 8205 // the map of such variables. 8206 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 8207 isIncompleteDeclExternC(*this, NewVD)) 8208 RegisterLocallyScopedExternCDecl(NewVD, S); 8209 8210 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 8211 MangleNumberingContext *MCtx; 8212 Decl *ManglingContextDecl; 8213 std::tie(MCtx, ManglingContextDecl) = 8214 getCurrentMangleNumberContext(NewVD->getDeclContext()); 8215 if (MCtx) { 8216 Context.setManglingNumber( 8217 NewVD, MCtx->getManglingNumber( 8218 NewVD, getMSManglingNumber(getLangOpts(), S))); 8219 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 8220 } 8221 } 8222 8223 // Special handling of variable named 'main'. 8224 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 8225 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 8226 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 8227 8228 // C++ [basic.start.main]p3 8229 // A program that declares a variable main at global scope is ill-formed. 8230 if (getLangOpts().CPlusPlus) 8231 Diag(D.getBeginLoc(), diag::err_main_global_variable); 8232 8233 // In C, and external-linkage variable named main results in undefined 8234 // behavior. 8235 else if (NewVD->hasExternalFormalLinkage()) 8236 Diag(D.getBeginLoc(), diag::warn_main_redefined); 8237 } 8238 8239 if (D.isRedeclaration() && !Previous.empty()) { 8240 NamedDecl *Prev = Previous.getRepresentativeDecl(); 8241 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 8242 D.isFunctionDefinition()); 8243 } 8244 8245 if (NewTemplate) { 8246 if (NewVD->isInvalidDecl()) 8247 NewTemplate->setInvalidDecl(); 8248 ActOnDocumentableDecl(NewTemplate); 8249 return NewTemplate; 8250 } 8251 8252 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 8253 CompleteMemberSpecialization(NewVD, Previous); 8254 8255 emitReadOnlyPlacementAttrWarning(*this, NewVD); 8256 8257 return NewVD; 8258 } 8259 8260 /// Enum describing the %select options in diag::warn_decl_shadow. 8261 enum ShadowedDeclKind { 8262 SDK_Local, 8263 SDK_Global, 8264 SDK_StaticMember, 8265 SDK_Field, 8266 SDK_Typedef, 8267 SDK_Using, 8268 SDK_StructuredBinding 8269 }; 8270 8271 /// Determine what kind of declaration we're shadowing. 8272 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 8273 const DeclContext *OldDC) { 8274 if (isa<TypeAliasDecl>(ShadowedDecl)) 8275 return SDK_Using; 8276 else if (isa<TypedefDecl>(ShadowedDecl)) 8277 return SDK_Typedef; 8278 else if (isa<BindingDecl>(ShadowedDecl)) 8279 return SDK_StructuredBinding; 8280 else if (isa<RecordDecl>(OldDC)) 8281 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 8282 8283 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 8284 } 8285 8286 /// Return the location of the capture if the given lambda captures the given 8287 /// variable \p VD, or an invalid source location otherwise. 8288 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 8289 const VarDecl *VD) { 8290 for (const Capture &Capture : LSI->Captures) { 8291 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 8292 return Capture.getLocation(); 8293 } 8294 return SourceLocation(); 8295 } 8296 8297 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 8298 const LookupResult &R) { 8299 // Only diagnose if we're shadowing an unambiguous field or variable. 8300 if (R.getResultKind() != LookupResult::Found) 8301 return false; 8302 8303 // Return false if warning is ignored. 8304 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 8305 } 8306 8307 /// Return the declaration shadowed by the given variable \p D, or null 8308 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 8309 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 8310 const LookupResult &R) { 8311 if (!shouldWarnIfShadowedDecl(Diags, R)) 8312 return nullptr; 8313 8314 // Don't diagnose declarations at file scope. 8315 if (D->hasGlobalStorage() && !D->isStaticLocal()) 8316 return nullptr; 8317 8318 NamedDecl *ShadowedDecl = R.getFoundDecl(); 8319 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 8320 : nullptr; 8321 } 8322 8323 /// Return the declaration shadowed by the given typedef \p D, or null 8324 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 8325 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 8326 const LookupResult &R) { 8327 // Don't warn if typedef declaration is part of a class 8328 if (D->getDeclContext()->isRecord()) 8329 return nullptr; 8330 8331 if (!shouldWarnIfShadowedDecl(Diags, R)) 8332 return nullptr; 8333 8334 NamedDecl *ShadowedDecl = R.getFoundDecl(); 8335 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 8336 } 8337 8338 /// Return the declaration shadowed by the given variable \p D, or null 8339 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 8340 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 8341 const LookupResult &R) { 8342 if (!shouldWarnIfShadowedDecl(Diags, R)) 8343 return nullptr; 8344 8345 NamedDecl *ShadowedDecl = R.getFoundDecl(); 8346 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 8347 : nullptr; 8348 } 8349 8350 /// Diagnose variable or built-in function shadowing. Implements 8351 /// -Wshadow. 8352 /// 8353 /// This method is called whenever a VarDecl is added to a "useful" 8354 /// scope. 8355 /// 8356 /// \param ShadowedDecl the declaration that is shadowed by the given variable 8357 /// \param R the lookup of the name 8358 /// 8359 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 8360 const LookupResult &R) { 8361 DeclContext *NewDC = D->getDeclContext(); 8362 8363 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 8364 // Fields are not shadowed by variables in C++ static methods. 8365 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 8366 if (MD->isStatic()) 8367 return; 8368 8369 // Fields shadowed by constructor parameters are a special case. Usually 8370 // the constructor initializes the field with the parameter. 8371 if (isa<CXXConstructorDecl>(NewDC)) 8372 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 8373 // Remember that this was shadowed so we can either warn about its 8374 // modification or its existence depending on warning settings. 8375 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 8376 return; 8377 } 8378 } 8379 8380 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 8381 if (shadowedVar->isExternC()) { 8382 // For shadowing external vars, make sure that we point to the global 8383 // declaration, not a locally scoped extern declaration. 8384 for (auto *I : shadowedVar->redecls()) 8385 if (I->isFileVarDecl()) { 8386 ShadowedDecl = I; 8387 break; 8388 } 8389 } 8390 8391 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 8392 8393 unsigned WarningDiag = diag::warn_decl_shadow; 8394 SourceLocation CaptureLoc; 8395 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 8396 isa<CXXMethodDecl>(NewDC)) { 8397 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 8398 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 8399 if (RD->getLambdaCaptureDefault() == LCD_None) { 8400 // Try to avoid warnings for lambdas with an explicit capture list. 8401 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 8402 // Warn only when the lambda captures the shadowed decl explicitly. 8403 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 8404 if (CaptureLoc.isInvalid()) 8405 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 8406 } else { 8407 // Remember that this was shadowed so we can avoid the warning if the 8408 // shadowed decl isn't captured and the warning settings allow it. 8409 cast<LambdaScopeInfo>(getCurFunction()) 8410 ->ShadowingDecls.push_back( 8411 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 8412 return; 8413 } 8414 } 8415 8416 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 8417 // A variable can't shadow a local variable in an enclosing scope, if 8418 // they are separated by a non-capturing declaration context. 8419 for (DeclContext *ParentDC = NewDC; 8420 ParentDC && !ParentDC->Equals(OldDC); 8421 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 8422 // Only block literals, captured statements, and lambda expressions 8423 // can capture; other scopes don't. 8424 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 8425 !isLambdaCallOperator(ParentDC)) { 8426 return; 8427 } 8428 } 8429 } 8430 } 8431 } 8432 8433 // Never warn about shadowing a placeholder variable. 8434 if (ShadowedDecl->isPlaceholderVar(getLangOpts())) 8435 return; 8436 8437 // Only warn about certain kinds of shadowing for class members. 8438 if (NewDC && NewDC->isRecord()) { 8439 // In particular, don't warn about shadowing non-class members. 8440 if (!OldDC->isRecord()) 8441 return; 8442 8443 // TODO: should we warn about static data members shadowing 8444 // static data members from base classes? 8445 8446 // TODO: don't diagnose for inaccessible shadowed members. 8447 // This is hard to do perfectly because we might friend the 8448 // shadowing context, but that's just a false negative. 8449 } 8450 8451 8452 DeclarationName Name = R.getLookupName(); 8453 8454 // Emit warning and note. 8455 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 8456 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 8457 if (!CaptureLoc.isInvalid()) 8458 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8459 << Name << /*explicitly*/ 1; 8460 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8461 } 8462 8463 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 8464 /// when these variables are captured by the lambda. 8465 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 8466 for (const auto &Shadow : LSI->ShadowingDecls) { 8467 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 8468 // Try to avoid the warning when the shadowed decl isn't captured. 8469 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 8470 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8471 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 8472 ? diag::warn_decl_shadow_uncaptured_local 8473 : diag::warn_decl_shadow) 8474 << Shadow.VD->getDeclName() 8475 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 8476 if (!CaptureLoc.isInvalid()) 8477 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8478 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 8479 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8480 } 8481 } 8482 8483 /// Check -Wshadow without the advantage of a previous lookup. 8484 void Sema::CheckShadow(Scope *S, VarDecl *D) { 8485 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 8486 return; 8487 8488 LookupResult R(*this, D->getDeclName(), D->getLocation(), 8489 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 8490 LookupName(R, S); 8491 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 8492 CheckShadow(D, ShadowedDecl, R); 8493 } 8494 8495 /// Check if 'E', which is an expression that is about to be modified, refers 8496 /// to a constructor parameter that shadows a field. 8497 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 8498 // Quickly ignore expressions that can't be shadowing ctor parameters. 8499 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 8500 return; 8501 E = E->IgnoreParenImpCasts(); 8502 auto *DRE = dyn_cast<DeclRefExpr>(E); 8503 if (!DRE) 8504 return; 8505 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 8506 auto I = ShadowingDecls.find(D); 8507 if (I == ShadowingDecls.end()) 8508 return; 8509 const NamedDecl *ShadowedDecl = I->second; 8510 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8511 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 8512 Diag(D->getLocation(), diag::note_var_declared_here) << D; 8513 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8514 8515 // Avoid issuing multiple warnings about the same decl. 8516 ShadowingDecls.erase(I); 8517 } 8518 8519 /// Check for conflict between this global or extern "C" declaration and 8520 /// previous global or extern "C" declarations. This is only used in C++. 8521 template<typename T> 8522 static bool checkGlobalOrExternCConflict( 8523 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 8524 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 8525 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 8526 8527 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 8528 // The common case: this global doesn't conflict with any extern "C" 8529 // declaration. 8530 return false; 8531 } 8532 8533 if (Prev) { 8534 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 8535 // Both the old and new declarations have C language linkage. This is a 8536 // redeclaration. 8537 Previous.clear(); 8538 Previous.addDecl(Prev); 8539 return true; 8540 } 8541 8542 // This is a global, non-extern "C" declaration, and there is a previous 8543 // non-global extern "C" declaration. Diagnose if this is a variable 8544 // declaration. 8545 if (!isa<VarDecl>(ND)) 8546 return false; 8547 } else { 8548 // The declaration is extern "C". Check for any declaration in the 8549 // translation unit which might conflict. 8550 if (IsGlobal) { 8551 // We have already performed the lookup into the translation unit. 8552 IsGlobal = false; 8553 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8554 I != E; ++I) { 8555 if (isa<VarDecl>(*I)) { 8556 Prev = *I; 8557 break; 8558 } 8559 } 8560 } else { 8561 DeclContext::lookup_result R = 8562 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 8563 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 8564 I != E; ++I) { 8565 if (isa<VarDecl>(*I)) { 8566 Prev = *I; 8567 break; 8568 } 8569 // FIXME: If we have any other entity with this name in global scope, 8570 // the declaration is ill-formed, but that is a defect: it breaks the 8571 // 'stat' hack, for instance. Only variables can have mangled name 8572 // clashes with extern "C" declarations, so only they deserve a 8573 // diagnostic. 8574 } 8575 } 8576 8577 if (!Prev) 8578 return false; 8579 } 8580 8581 // Use the first declaration's location to ensure we point at something which 8582 // is lexically inside an extern "C" linkage-spec. 8583 assert(Prev && "should have found a previous declaration to diagnose"); 8584 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 8585 Prev = FD->getFirstDecl(); 8586 else 8587 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 8588 8589 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 8590 << IsGlobal << ND; 8591 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 8592 << IsGlobal; 8593 return false; 8594 } 8595 8596 /// Apply special rules for handling extern "C" declarations. Returns \c true 8597 /// if we have found that this is a redeclaration of some prior entity. 8598 /// 8599 /// Per C++ [dcl.link]p6: 8600 /// Two declarations [for a function or variable] with C language linkage 8601 /// with the same name that appear in different scopes refer to the same 8602 /// [entity]. An entity with C language linkage shall not be declared with 8603 /// the same name as an entity in global scope. 8604 template<typename T> 8605 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 8606 LookupResult &Previous) { 8607 if (!S.getLangOpts().CPlusPlus) { 8608 // In C, when declaring a global variable, look for a corresponding 'extern' 8609 // variable declared in function scope. We don't need this in C++, because 8610 // we find local extern decls in the surrounding file-scope DeclContext. 8611 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8612 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 8613 Previous.clear(); 8614 Previous.addDecl(Prev); 8615 return true; 8616 } 8617 } 8618 return false; 8619 } 8620 8621 // A declaration in the translation unit can conflict with an extern "C" 8622 // declaration. 8623 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 8624 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 8625 8626 // An extern "C" declaration can conflict with a declaration in the 8627 // translation unit or can be a redeclaration of an extern "C" declaration 8628 // in another scope. 8629 if (isIncompleteDeclExternC(S,ND)) 8630 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 8631 8632 // Neither global nor extern "C": nothing to do. 8633 return false; 8634 } 8635 8636 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 8637 // If the decl is already known invalid, don't check it. 8638 if (NewVD->isInvalidDecl()) 8639 return; 8640 8641 QualType T = NewVD->getType(); 8642 8643 // Defer checking an 'auto' type until its initializer is attached. 8644 if (T->isUndeducedType()) 8645 return; 8646 8647 if (NewVD->hasAttrs()) 8648 CheckAlignasUnderalignment(NewVD); 8649 8650 if (T->isObjCObjectType()) { 8651 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 8652 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 8653 T = Context.getObjCObjectPointerType(T); 8654 NewVD->setType(T); 8655 } 8656 8657 // Emit an error if an address space was applied to decl with local storage. 8658 // This includes arrays of objects with address space qualifiers, but not 8659 // automatic variables that point to other address spaces. 8660 // ISO/IEC TR 18037 S5.1.2 8661 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 8662 T.getAddressSpace() != LangAS::Default) { 8663 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 8664 NewVD->setInvalidDecl(); 8665 return; 8666 } 8667 8668 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8669 // scope. 8670 if (getLangOpts().OpenCLVersion == 120 && 8671 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8672 getLangOpts()) && 8673 NewVD->isStaticLocal()) { 8674 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8675 NewVD->setInvalidDecl(); 8676 return; 8677 } 8678 8679 if (getLangOpts().OpenCL) { 8680 if (!diagnoseOpenCLTypes(*this, NewVD)) 8681 return; 8682 8683 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8684 if (NewVD->hasAttr<BlocksAttr>()) { 8685 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8686 return; 8687 } 8688 8689 if (T->isBlockPointerType()) { 8690 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8691 // can't use 'extern' storage class. 8692 if (!T.isConstQualified()) { 8693 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8694 << 0 /*const*/; 8695 NewVD->setInvalidDecl(); 8696 return; 8697 } 8698 if (NewVD->hasExternalStorage()) { 8699 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8700 NewVD->setInvalidDecl(); 8701 return; 8702 } 8703 } 8704 8705 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8706 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8707 NewVD->hasExternalStorage()) { 8708 if (!T->isSamplerT() && !T->isDependentType() && 8709 !(T.getAddressSpace() == LangAS::opencl_constant || 8710 (T.getAddressSpace() == LangAS::opencl_global && 8711 getOpenCLOptions().areProgramScopeVariablesSupported( 8712 getLangOpts())))) { 8713 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8714 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8715 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8716 << Scope << "global or constant"; 8717 else 8718 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8719 << Scope << "constant"; 8720 NewVD->setInvalidDecl(); 8721 return; 8722 } 8723 } else { 8724 if (T.getAddressSpace() == LangAS::opencl_global) { 8725 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8726 << 1 /*is any function*/ << "global"; 8727 NewVD->setInvalidDecl(); 8728 return; 8729 } 8730 if (T.getAddressSpace() == LangAS::opencl_constant || 8731 T.getAddressSpace() == LangAS::opencl_local) { 8732 FunctionDecl *FD = getCurFunctionDecl(); 8733 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8734 // in functions. 8735 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8736 if (T.getAddressSpace() == LangAS::opencl_constant) 8737 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8738 << 0 /*non-kernel only*/ << "constant"; 8739 else 8740 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8741 << 0 /*non-kernel only*/ << "local"; 8742 NewVD->setInvalidDecl(); 8743 return; 8744 } 8745 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8746 // in the outermost scope of a kernel function. 8747 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8748 if (!getCurScope()->isFunctionScope()) { 8749 if (T.getAddressSpace() == LangAS::opencl_constant) 8750 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8751 << "constant"; 8752 else 8753 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8754 << "local"; 8755 NewVD->setInvalidDecl(); 8756 return; 8757 } 8758 } 8759 } else if (T.getAddressSpace() != LangAS::opencl_private && 8760 // If we are parsing a template we didn't deduce an addr 8761 // space yet. 8762 T.getAddressSpace() != LangAS::Default) { 8763 // Do not allow other address spaces on automatic variable. 8764 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8765 NewVD->setInvalidDecl(); 8766 return; 8767 } 8768 } 8769 } 8770 8771 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8772 && !NewVD->hasAttr<BlocksAttr>()) { 8773 if (getLangOpts().getGC() != LangOptions::NonGC) 8774 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8775 else { 8776 assert(!getLangOpts().ObjCAutoRefCount); 8777 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8778 } 8779 } 8780 8781 // WebAssembly tables must be static with a zero length and can't be 8782 // declared within functions. 8783 if (T->isWebAssemblyTableType()) { 8784 if (getCurScope()->getParent()) { // Parent is null at top-level 8785 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function); 8786 NewVD->setInvalidDecl(); 8787 return; 8788 } 8789 if (NewVD->getStorageClass() != SC_Static) { 8790 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static); 8791 NewVD->setInvalidDecl(); 8792 return; 8793 } 8794 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr()); 8795 if (!ATy || ATy->getSize().getSExtValue() != 0) { 8796 Diag(NewVD->getLocation(), 8797 diag::err_typecheck_wasm_table_must_have_zero_length); 8798 NewVD->setInvalidDecl(); 8799 return; 8800 } 8801 } 8802 8803 bool isVM = T->isVariablyModifiedType(); 8804 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8805 NewVD->hasAttr<BlocksAttr>()) 8806 setFunctionHasBranchProtectedScope(); 8807 8808 if ((isVM && NewVD->hasLinkage()) || 8809 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8810 bool SizeIsNegative; 8811 llvm::APSInt Oversized; 8812 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8813 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8814 QualType FixedT; 8815 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8816 FixedT = FixedTInfo->getType(); 8817 else if (FixedTInfo) { 8818 // Type and type-as-written are canonically different. We need to fix up 8819 // both types separately. 8820 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8821 Oversized); 8822 } 8823 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8824 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8825 // FIXME: This won't give the correct result for 8826 // int a[10][n]; 8827 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8828 8829 if (NewVD->isFileVarDecl()) 8830 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8831 << SizeRange; 8832 else if (NewVD->isStaticLocal()) 8833 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8834 << SizeRange; 8835 else 8836 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8837 << SizeRange; 8838 NewVD->setInvalidDecl(); 8839 return; 8840 } 8841 8842 if (!FixedTInfo) { 8843 if (NewVD->isFileVarDecl()) 8844 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8845 else 8846 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8847 NewVD->setInvalidDecl(); 8848 return; 8849 } 8850 8851 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8852 NewVD->setType(FixedT); 8853 NewVD->setTypeSourceInfo(FixedTInfo); 8854 } 8855 8856 if (T->isVoidType()) { 8857 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8858 // of objects and functions. 8859 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8860 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8861 << T; 8862 NewVD->setInvalidDecl(); 8863 return; 8864 } 8865 } 8866 8867 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8868 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8869 NewVD->setInvalidDecl(); 8870 return; 8871 } 8872 8873 if (!NewVD->hasLocalStorage() && T->isSizelessType() && 8874 !T.isWebAssemblyReferenceType()) { 8875 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8876 NewVD->setInvalidDecl(); 8877 return; 8878 } 8879 8880 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8881 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8882 NewVD->setInvalidDecl(); 8883 return; 8884 } 8885 8886 if (NewVD->isConstexpr() && !T->isDependentType() && 8887 RequireLiteralType(NewVD->getLocation(), T, 8888 diag::err_constexpr_var_non_literal)) { 8889 NewVD->setInvalidDecl(); 8890 return; 8891 } 8892 8893 // PPC MMA non-pointer types are not allowed as non-local variable types. 8894 if (Context.getTargetInfo().getTriple().isPPC64() && 8895 !NewVD->isLocalVarDecl() && 8896 CheckPPCMMAType(T, NewVD->getLocation())) { 8897 NewVD->setInvalidDecl(); 8898 return; 8899 } 8900 8901 // Check that SVE types are only used in functions with SVE available. 8902 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) { 8903 const FunctionDecl *FD = cast<FunctionDecl>(CurContext); 8904 llvm::StringMap<bool> CallerFeatureMap; 8905 Context.getFunctionFeatureMap(CallerFeatureMap, FD); 8906 if (!Builtin::evaluateRequiredTargetFeatures( 8907 "sve", CallerFeatureMap)) { 8908 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T; 8909 NewVD->setInvalidDecl(); 8910 return; 8911 } 8912 } 8913 8914 if (T->isRVVSizelessBuiltinType()) 8915 checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext)); 8916 } 8917 8918 /// Perform semantic checking on a newly-created variable 8919 /// declaration. 8920 /// 8921 /// This routine performs all of the type-checking required for a 8922 /// variable declaration once it has been built. It is used both to 8923 /// check variables after they have been parsed and their declarators 8924 /// have been translated into a declaration, and to check variables 8925 /// that have been instantiated from a template. 8926 /// 8927 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8928 /// 8929 /// Returns true if the variable declaration is a redeclaration. 8930 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8931 CheckVariableDeclarationType(NewVD); 8932 8933 // If the decl is already known invalid, don't check it. 8934 if (NewVD->isInvalidDecl()) 8935 return false; 8936 8937 // If we did not find anything by this name, look for a non-visible 8938 // extern "C" declaration with the same name. 8939 if (Previous.empty() && 8940 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8941 Previous.setShadowed(); 8942 8943 if (!Previous.empty()) { 8944 MergeVarDecl(NewVD, Previous); 8945 return true; 8946 } 8947 return false; 8948 } 8949 8950 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8951 /// and if so, check that it's a valid override and remember it. 8952 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8953 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8954 8955 // Look for methods in base classes that this method might override. 8956 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8957 /*DetectVirtual=*/false); 8958 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8959 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8960 DeclarationName Name = MD->getDeclName(); 8961 8962 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8963 // We really want to find the base class destructor here. 8964 QualType T = Context.getTypeDeclType(BaseRecord); 8965 CanQualType CT = Context.getCanonicalType(T); 8966 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8967 } 8968 8969 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8970 CXXMethodDecl *BaseMD = 8971 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8972 if (!BaseMD || !BaseMD->isVirtual() || 8973 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8974 /*ConsiderCudaAttrs=*/true)) 8975 continue; 8976 if (!CheckExplicitObjectOverride(MD, BaseMD)) 8977 continue; 8978 if (Overridden.insert(BaseMD).second) { 8979 MD->addOverriddenMethod(BaseMD); 8980 CheckOverridingFunctionReturnType(MD, BaseMD); 8981 CheckOverridingFunctionAttributes(MD, BaseMD); 8982 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8983 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8984 } 8985 8986 // A method can only override one function from each base class. We 8987 // don't track indirectly overridden methods from bases of bases. 8988 return true; 8989 } 8990 8991 return false; 8992 }; 8993 8994 DC->lookupInBases(VisitBase, Paths); 8995 return !Overridden.empty(); 8996 } 8997 8998 namespace { 8999 // Struct for holding all of the extra arguments needed by 9000 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 9001 struct ActOnFDArgs { 9002 Scope *S; 9003 Declarator &D; 9004 MultiTemplateParamsArg TemplateParamLists; 9005 bool AddToScope; 9006 }; 9007 } // end anonymous namespace 9008 9009 namespace { 9010 9011 // Callback to only accept typo corrections that have a non-zero edit distance. 9012 // Also only accept corrections that have the same parent decl. 9013 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 9014 public: 9015 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 9016 CXXRecordDecl *Parent) 9017 : Context(Context), OriginalFD(TypoFD), 9018 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 9019 9020 bool ValidateCandidate(const TypoCorrection &candidate) override { 9021 if (candidate.getEditDistance() == 0) 9022 return false; 9023 9024 SmallVector<unsigned, 1> MismatchedParams; 9025 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 9026 CDeclEnd = candidate.end(); 9027 CDecl != CDeclEnd; ++CDecl) { 9028 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 9029 9030 if (FD && !FD->hasBody() && 9031 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 9032 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 9033 CXXRecordDecl *Parent = MD->getParent(); 9034 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 9035 return true; 9036 } else if (!ExpectedParent) { 9037 return true; 9038 } 9039 } 9040 } 9041 9042 return false; 9043 } 9044 9045 std::unique_ptr<CorrectionCandidateCallback> clone() override { 9046 return std::make_unique<DifferentNameValidatorCCC>(*this); 9047 } 9048 9049 private: 9050 ASTContext &Context; 9051 FunctionDecl *OriginalFD; 9052 CXXRecordDecl *ExpectedParent; 9053 }; 9054 9055 } // end anonymous namespace 9056 9057 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 9058 TypoCorrectedFunctionDefinitions.insert(F); 9059 } 9060 9061 /// Generate diagnostics for an invalid function redeclaration. 9062 /// 9063 /// This routine handles generating the diagnostic messages for an invalid 9064 /// function redeclaration, including finding possible similar declarations 9065 /// or performing typo correction if there are no previous declarations with 9066 /// the same name. 9067 /// 9068 /// Returns a NamedDecl iff typo correction was performed and substituting in 9069 /// the new declaration name does not cause new errors. 9070 static NamedDecl *DiagnoseInvalidRedeclaration( 9071 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 9072 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 9073 DeclarationName Name = NewFD->getDeclName(); 9074 DeclContext *NewDC = NewFD->getDeclContext(); 9075 SmallVector<unsigned, 1> MismatchedParams; 9076 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 9077 TypoCorrection Correction; 9078 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 9079 unsigned DiagMsg = 9080 IsLocalFriend ? diag::err_no_matching_local_friend : 9081 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 9082 diag::err_member_decl_does_not_match; 9083 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 9084 IsLocalFriend ? Sema::LookupLocalFriendName 9085 : Sema::LookupOrdinaryName, 9086 Sema::ForVisibleRedeclaration); 9087 9088 NewFD->setInvalidDecl(); 9089 if (IsLocalFriend) 9090 SemaRef.LookupName(Prev, S); 9091 else 9092 SemaRef.LookupQualifiedName(Prev, NewDC); 9093 assert(!Prev.isAmbiguous() && 9094 "Cannot have an ambiguity in previous-declaration lookup"); 9095 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9096 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 9097 MD ? MD->getParent() : nullptr); 9098 if (!Prev.empty()) { 9099 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 9100 Func != FuncEnd; ++Func) { 9101 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 9102 if (FD && 9103 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 9104 // Add 1 to the index so that 0 can mean the mismatch didn't 9105 // involve a parameter 9106 unsigned ParamNum = 9107 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 9108 NearMatches.push_back(std::make_pair(FD, ParamNum)); 9109 } 9110 } 9111 // If the qualified name lookup yielded nothing, try typo correction 9112 } else if ((Correction = SemaRef.CorrectTypo( 9113 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 9114 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 9115 IsLocalFriend ? nullptr : NewDC))) { 9116 // Set up everything for the call to ActOnFunctionDeclarator 9117 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 9118 ExtraArgs.D.getIdentifierLoc()); 9119 Previous.clear(); 9120 Previous.setLookupName(Correction.getCorrection()); 9121 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 9122 CDeclEnd = Correction.end(); 9123 CDecl != CDeclEnd; ++CDecl) { 9124 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 9125 if (FD && !FD->hasBody() && 9126 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 9127 Previous.addDecl(FD); 9128 } 9129 } 9130 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 9131 9132 NamedDecl *Result; 9133 // Retry building the function declaration with the new previous 9134 // declarations, and with errors suppressed. 9135 { 9136 // Trap errors. 9137 Sema::SFINAETrap Trap(SemaRef); 9138 9139 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 9140 // pieces need to verify the typo-corrected C++ declaration and hopefully 9141 // eliminate the need for the parameter pack ExtraArgs. 9142 Result = SemaRef.ActOnFunctionDeclarator( 9143 ExtraArgs.S, ExtraArgs.D, 9144 Correction.getCorrectionDecl()->getDeclContext(), 9145 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 9146 ExtraArgs.AddToScope); 9147 9148 if (Trap.hasErrorOccurred()) 9149 Result = nullptr; 9150 } 9151 9152 if (Result) { 9153 // Determine which correction we picked. 9154 Decl *Canonical = Result->getCanonicalDecl(); 9155 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9156 I != E; ++I) 9157 if ((*I)->getCanonicalDecl() == Canonical) 9158 Correction.setCorrectionDecl(*I); 9159 9160 // Let Sema know about the correction. 9161 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 9162 SemaRef.diagnoseTypo( 9163 Correction, 9164 SemaRef.PDiag(IsLocalFriend 9165 ? diag::err_no_matching_local_friend_suggest 9166 : diag::err_member_decl_does_not_match_suggest) 9167 << Name << NewDC << IsDefinition); 9168 return Result; 9169 } 9170 9171 // Pretend the typo correction never occurred 9172 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 9173 ExtraArgs.D.getIdentifierLoc()); 9174 ExtraArgs.D.setRedeclaration(wasRedeclaration); 9175 Previous.clear(); 9176 Previous.setLookupName(Name); 9177 } 9178 9179 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 9180 << Name << NewDC << IsDefinition << NewFD->getLocation(); 9181 9182 bool NewFDisConst = false; 9183 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 9184 NewFDisConst = NewMD->isConst(); 9185 9186 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 9187 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 9188 NearMatch != NearMatchEnd; ++NearMatch) { 9189 FunctionDecl *FD = NearMatch->first; 9190 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 9191 bool FDisConst = MD && MD->isConst(); 9192 bool IsMember = MD || !IsLocalFriend; 9193 9194 // FIXME: These notes are poorly worded for the local friend case. 9195 if (unsigned Idx = NearMatch->second) { 9196 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 9197 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 9198 if (Loc.isInvalid()) Loc = FD->getLocation(); 9199 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 9200 : diag::note_local_decl_close_param_match) 9201 << Idx << FDParam->getType() 9202 << NewFD->getParamDecl(Idx - 1)->getType(); 9203 } else if (FDisConst != NewFDisConst) { 9204 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 9205 << NewFDisConst << FD->getSourceRange().getEnd() 9206 << (NewFDisConst 9207 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo() 9208 .getConstQualifierLoc()) 9209 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo() 9210 .getRParenLoc() 9211 .getLocWithOffset(1), 9212 " const")); 9213 } else 9214 SemaRef.Diag(FD->getLocation(), 9215 IsMember ? diag::note_member_def_close_match 9216 : diag::note_local_decl_close_match); 9217 } 9218 return nullptr; 9219 } 9220 9221 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 9222 switch (D.getDeclSpec().getStorageClassSpec()) { 9223 default: llvm_unreachable("Unknown storage class!"); 9224 case DeclSpec::SCS_auto: 9225 case DeclSpec::SCS_register: 9226 case DeclSpec::SCS_mutable: 9227 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9228 diag::err_typecheck_sclass_func); 9229 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9230 D.setInvalidType(); 9231 break; 9232 case DeclSpec::SCS_unspecified: break; 9233 case DeclSpec::SCS_extern: 9234 if (D.getDeclSpec().isExternInLinkageSpec()) 9235 return SC_None; 9236 return SC_Extern; 9237 case DeclSpec::SCS_static: { 9238 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 9239 // C99 6.7.1p5: 9240 // The declaration of an identifier for a function that has 9241 // block scope shall have no explicit storage-class specifier 9242 // other than extern 9243 // See also (C++ [dcl.stc]p4). 9244 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9245 diag::err_static_block_func); 9246 break; 9247 } else 9248 return SC_Static; 9249 } 9250 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 9251 } 9252 9253 // No explicit storage class has already been returned 9254 return SC_None; 9255 } 9256 9257 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 9258 DeclContext *DC, QualType &R, 9259 TypeSourceInfo *TInfo, 9260 StorageClass SC, 9261 bool &IsVirtualOkay) { 9262 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 9263 DeclarationName Name = NameInfo.getName(); 9264 9265 FunctionDecl *NewFD = nullptr; 9266 bool isInline = D.getDeclSpec().isInlineSpecified(); 9267 9268 if (!SemaRef.getLangOpts().CPlusPlus) { 9269 // Determine whether the function was written with a prototype. This is 9270 // true when: 9271 // - there is a prototype in the declarator, or 9272 // - the type R of the function is some kind of typedef or other non- 9273 // attributed reference to a type name (which eventually refers to a 9274 // function type). Note, we can't always look at the adjusted type to 9275 // check this case because attributes may cause a non-function 9276 // declarator to still have a function type. e.g., 9277 // typedef void func(int a); 9278 // __attribute__((noreturn)) func other_func; // This has a prototype 9279 bool HasPrototype = 9280 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 9281 (D.getDeclSpec().isTypeRep() && 9282 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr) 9283 ->isFunctionProtoType()) || 9284 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 9285 assert( 9286 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) && 9287 "Strict prototypes are required"); 9288 9289 NewFD = FunctionDecl::Create( 9290 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 9291 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 9292 ConstexprSpecKind::Unspecified, 9293 /*TrailingRequiresClause=*/nullptr); 9294 if (D.isInvalidType()) 9295 NewFD->setInvalidDecl(); 9296 9297 return NewFD; 9298 } 9299 9300 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 9301 9302 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9303 if (ConstexprKind == ConstexprSpecKind::Constinit) { 9304 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 9305 diag::err_constexpr_wrong_decl_kind) 9306 << static_cast<int>(ConstexprKind); 9307 ConstexprKind = ConstexprSpecKind::Unspecified; 9308 D.getMutableDeclSpec().ClearConstexprSpec(); 9309 } 9310 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 9311 9312 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R); 9313 9314 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 9315 // This is a C++ constructor declaration. 9316 assert(DC->isRecord() && 9317 "Constructors can only be declared in a member context"); 9318 9319 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 9320 return CXXConstructorDecl::Create( 9321 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 9322 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 9323 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 9324 InheritedConstructor(), TrailingRequiresClause); 9325 9326 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9327 // This is a C++ destructor declaration. 9328 if (DC->isRecord()) { 9329 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 9330 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 9331 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 9332 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 9333 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9334 /*isImplicitlyDeclared=*/false, ConstexprKind, 9335 TrailingRequiresClause); 9336 // User defined destructors start as not selected if the class definition is still 9337 // not done. 9338 if (Record->isBeingDefined()) 9339 NewDD->setIneligibleOrNotSelected(true); 9340 9341 // If the destructor needs an implicit exception specification, set it 9342 // now. FIXME: It'd be nice to be able to create the right type to start 9343 // with, but the type needs to reference the destructor declaration. 9344 if (SemaRef.getLangOpts().CPlusPlus11) 9345 SemaRef.AdjustDestructorExceptionSpec(NewDD); 9346 9347 IsVirtualOkay = true; 9348 return NewDD; 9349 9350 } else { 9351 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 9352 D.setInvalidType(); 9353 9354 // Create a FunctionDecl to satisfy the function definition parsing 9355 // code path. 9356 return FunctionDecl::Create( 9357 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 9358 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9359 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 9360 } 9361 9362 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 9363 if (!DC->isRecord()) { 9364 SemaRef.Diag(D.getIdentifierLoc(), 9365 diag::err_conv_function_not_member); 9366 return nullptr; 9367 } 9368 9369 SemaRef.CheckConversionDeclarator(D, R, SC); 9370 if (D.isInvalidType()) 9371 return nullptr; 9372 9373 IsVirtualOkay = true; 9374 return CXXConversionDecl::Create( 9375 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 9376 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9377 ExplicitSpecifier, ConstexprKind, SourceLocation(), 9378 TrailingRequiresClause); 9379 9380 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 9381 if (TrailingRequiresClause) 9382 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 9383 diag::err_trailing_requires_clause_on_deduction_guide) 9384 << TrailingRequiresClause->getSourceRange(); 9385 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC)) 9386 return nullptr; 9387 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 9388 ExplicitSpecifier, NameInfo, R, TInfo, 9389 D.getEndLoc()); 9390 } else if (DC->isRecord()) { 9391 // If the name of the function is the same as the name of the record, 9392 // then this must be an invalid constructor that has a return type. 9393 // (The parser checks for a return type and makes the declarator a 9394 // constructor if it has no return type). 9395 if (Name.getAsIdentifierInfo() && 9396 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 9397 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 9398 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 9399 << SourceRange(D.getIdentifierLoc()); 9400 return nullptr; 9401 } 9402 9403 // This is a C++ method declaration. 9404 CXXMethodDecl *Ret = CXXMethodDecl::Create( 9405 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 9406 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9407 ConstexprKind, SourceLocation(), TrailingRequiresClause); 9408 IsVirtualOkay = !Ret->isStatic(); 9409 return Ret; 9410 } else { 9411 bool isFriend = 9412 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 9413 if (!isFriend && SemaRef.CurContext->isRecord()) 9414 return nullptr; 9415 9416 // Determine whether the function was written with a 9417 // prototype. This true when: 9418 // - we're in C++ (where every function has a prototype), 9419 return FunctionDecl::Create( 9420 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 9421 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9422 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 9423 } 9424 } 9425 9426 enum OpenCLParamType { 9427 ValidKernelParam, 9428 PtrPtrKernelParam, 9429 PtrKernelParam, 9430 InvalidAddrSpacePtrKernelParam, 9431 InvalidKernelParam, 9432 RecordKernelParam 9433 }; 9434 9435 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 9436 // Size dependent types are just typedefs to normal integer types 9437 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 9438 // integers other than by their names. 9439 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 9440 9441 // Remove typedefs one by one until we reach a typedef 9442 // for a size dependent type. 9443 QualType DesugaredTy = Ty; 9444 do { 9445 ArrayRef<StringRef> Names(SizeTypeNames); 9446 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 9447 if (Names.end() != Match) 9448 return true; 9449 9450 Ty = DesugaredTy; 9451 DesugaredTy = Ty.getSingleStepDesugaredType(C); 9452 } while (DesugaredTy != Ty); 9453 9454 return false; 9455 } 9456 9457 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 9458 if (PT->isDependentType()) 9459 return InvalidKernelParam; 9460 9461 if (PT->isPointerType() || PT->isReferenceType()) { 9462 QualType PointeeType = PT->getPointeeType(); 9463 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 9464 PointeeType.getAddressSpace() == LangAS::opencl_private || 9465 PointeeType.getAddressSpace() == LangAS::Default) 9466 return InvalidAddrSpacePtrKernelParam; 9467 9468 if (PointeeType->isPointerType()) { 9469 // This is a pointer to pointer parameter. 9470 // Recursively check inner type. 9471 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 9472 if (ParamKind == InvalidAddrSpacePtrKernelParam || 9473 ParamKind == InvalidKernelParam) 9474 return ParamKind; 9475 9476 // OpenCL v3.0 s6.11.a: 9477 // A restriction to pass pointers to pointers only applies to OpenCL C 9478 // v1.2 or below. 9479 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120) 9480 return ValidKernelParam; 9481 9482 return PtrPtrKernelParam; 9483 } 9484 9485 // C++ for OpenCL v1.0 s2.4: 9486 // Moreover the types used in parameters of the kernel functions must be: 9487 // Standard layout types for pointer parameters. The same applies to 9488 // reference if an implementation supports them in kernel parameters. 9489 if (S.getLangOpts().OpenCLCPlusPlus && 9490 !S.getOpenCLOptions().isAvailableOption( 9491 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) { 9492 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl(); 9493 bool IsStandardLayoutType = true; 9494 if (CXXRec) { 9495 // If template type is not ODR-used its definition is only available 9496 // in the template definition not its instantiation. 9497 // FIXME: This logic doesn't work for types that depend on template 9498 // parameter (PR58590). 9499 if (!CXXRec->hasDefinition()) 9500 CXXRec = CXXRec->getTemplateInstantiationPattern(); 9501 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout()) 9502 IsStandardLayoutType = false; 9503 } 9504 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() && 9505 !IsStandardLayoutType) 9506 return InvalidKernelParam; 9507 } 9508 9509 // OpenCL v1.2 s6.9.p: 9510 // A restriction to pass pointers only applies to OpenCL C v1.2 or below. 9511 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120) 9512 return ValidKernelParam; 9513 9514 return PtrKernelParam; 9515 } 9516 9517 // OpenCL v1.2 s6.9.k: 9518 // Arguments to kernel functions in a program cannot be declared with the 9519 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9520 // uintptr_t or a struct and/or union that contain fields declared to be one 9521 // of these built-in scalar types. 9522 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 9523 return InvalidKernelParam; 9524 9525 if (PT->isImageType()) 9526 return PtrKernelParam; 9527 9528 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 9529 return InvalidKernelParam; 9530 9531 // OpenCL extension spec v1.2 s9.5: 9532 // This extension adds support for half scalar and vector types as built-in 9533 // types that can be used for arithmetic operations, conversions etc. 9534 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 9535 PT->isHalfType()) 9536 return InvalidKernelParam; 9537 9538 // Look into an array argument to check if it has a forbidden type. 9539 if (PT->isArrayType()) { 9540 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 9541 // Call ourself to check an underlying type of an array. Since the 9542 // getPointeeOrArrayElementType returns an innermost type which is not an 9543 // array, this recursive call only happens once. 9544 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 9545 } 9546 9547 // C++ for OpenCL v1.0 s2.4: 9548 // Moreover the types used in parameters of the kernel functions must be: 9549 // Trivial and standard-layout types C++17 [basic.types] (plain old data 9550 // types) for parameters passed by value; 9551 if (S.getLangOpts().OpenCLCPlusPlus && 9552 !S.getOpenCLOptions().isAvailableOption( 9553 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 9554 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 9555 return InvalidKernelParam; 9556 9557 if (PT->isRecordType()) 9558 return RecordKernelParam; 9559 9560 return ValidKernelParam; 9561 } 9562 9563 static void checkIsValidOpenCLKernelParameter( 9564 Sema &S, 9565 Declarator &D, 9566 ParmVarDecl *Param, 9567 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 9568 QualType PT = Param->getType(); 9569 9570 // Cache the valid types we encounter to avoid rechecking structs that are 9571 // used again 9572 if (ValidTypes.count(PT.getTypePtr())) 9573 return; 9574 9575 switch (getOpenCLKernelParameterType(S, PT)) { 9576 case PtrPtrKernelParam: 9577 // OpenCL v3.0 s6.11.a: 9578 // A kernel function argument cannot be declared as a pointer to a pointer 9579 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 9580 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 9581 D.setInvalidType(); 9582 return; 9583 9584 case InvalidAddrSpacePtrKernelParam: 9585 // OpenCL v1.0 s6.5: 9586 // __kernel function arguments declared to be a pointer of a type can point 9587 // to one of the following address spaces only : __global, __local or 9588 // __constant. 9589 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 9590 D.setInvalidType(); 9591 return; 9592 9593 // OpenCL v1.2 s6.9.k: 9594 // Arguments to kernel functions in a program cannot be declared with the 9595 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9596 // uintptr_t or a struct and/or union that contain fields declared to be 9597 // one of these built-in scalar types. 9598 9599 case InvalidKernelParam: 9600 // OpenCL v1.2 s6.8 n: 9601 // A kernel function argument cannot be declared 9602 // of event_t type. 9603 // Do not diagnose half type since it is diagnosed as invalid argument 9604 // type for any function elsewhere. 9605 if (!PT->isHalfType()) { 9606 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9607 9608 // Explain what typedefs are involved. 9609 const TypedefType *Typedef = nullptr; 9610 while ((Typedef = PT->getAs<TypedefType>())) { 9611 SourceLocation Loc = Typedef->getDecl()->getLocation(); 9612 // SourceLocation may be invalid for a built-in type. 9613 if (Loc.isValid()) 9614 S.Diag(Loc, diag::note_entity_declared_at) << PT; 9615 PT = Typedef->desugar(); 9616 } 9617 } 9618 9619 D.setInvalidType(); 9620 return; 9621 9622 case PtrKernelParam: 9623 case ValidKernelParam: 9624 ValidTypes.insert(PT.getTypePtr()); 9625 return; 9626 9627 case RecordKernelParam: 9628 break; 9629 } 9630 9631 // Track nested structs we will inspect 9632 SmallVector<const Decl *, 4> VisitStack; 9633 9634 // Track where we are in the nested structs. Items will migrate from 9635 // VisitStack to HistoryStack as we do the DFS for bad field. 9636 SmallVector<const FieldDecl *, 4> HistoryStack; 9637 HistoryStack.push_back(nullptr); 9638 9639 // At this point we already handled everything except of a RecordType or 9640 // an ArrayType of a RecordType. 9641 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 9642 const RecordType *RecTy = 9643 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 9644 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 9645 9646 VisitStack.push_back(RecTy->getDecl()); 9647 assert(VisitStack.back() && "First decl null?"); 9648 9649 do { 9650 const Decl *Next = VisitStack.pop_back_val(); 9651 if (!Next) { 9652 assert(!HistoryStack.empty()); 9653 // Found a marker, we have gone up a level 9654 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 9655 ValidTypes.insert(Hist->getType().getTypePtr()); 9656 9657 continue; 9658 } 9659 9660 // Adds everything except the original parameter declaration (which is not a 9661 // field itself) to the history stack. 9662 const RecordDecl *RD; 9663 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 9664 HistoryStack.push_back(Field); 9665 9666 QualType FieldTy = Field->getType(); 9667 // Other field types (known to be valid or invalid) are handled while we 9668 // walk around RecordDecl::fields(). 9669 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 9670 "Unexpected type."); 9671 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 9672 9673 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 9674 } else { 9675 RD = cast<RecordDecl>(Next); 9676 } 9677 9678 // Add a null marker so we know when we've gone back up a level 9679 VisitStack.push_back(nullptr); 9680 9681 for (const auto *FD : RD->fields()) { 9682 QualType QT = FD->getType(); 9683 9684 if (ValidTypes.count(QT.getTypePtr())) 9685 continue; 9686 9687 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 9688 if (ParamType == ValidKernelParam) 9689 continue; 9690 9691 if (ParamType == RecordKernelParam) { 9692 VisitStack.push_back(FD); 9693 continue; 9694 } 9695 9696 // OpenCL v1.2 s6.9.p: 9697 // Arguments to kernel functions that are declared to be a struct or union 9698 // do not allow OpenCL objects to be passed as elements of the struct or 9699 // union. This restriction was lifted in OpenCL v2.0 with the introduction 9700 // of SVM. 9701 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 9702 ParamType == InvalidAddrSpacePtrKernelParam) { 9703 S.Diag(Param->getLocation(), 9704 diag::err_record_with_pointers_kernel_param) 9705 << PT->isUnionType() 9706 << PT; 9707 } else { 9708 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9709 } 9710 9711 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 9712 << OrigRecDecl->getDeclName(); 9713 9714 // We have an error, now let's go back up through history and show where 9715 // the offending field came from 9716 for (ArrayRef<const FieldDecl *>::const_iterator 9717 I = HistoryStack.begin() + 1, 9718 E = HistoryStack.end(); 9719 I != E; ++I) { 9720 const FieldDecl *OuterField = *I; 9721 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 9722 << OuterField->getType(); 9723 } 9724 9725 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 9726 << QT->isPointerType() 9727 << QT; 9728 D.setInvalidType(); 9729 return; 9730 } 9731 } while (!VisitStack.empty()); 9732 } 9733 9734 /// Find the DeclContext in which a tag is implicitly declared if we see an 9735 /// elaborated type specifier in the specified context, and lookup finds 9736 /// nothing. 9737 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9738 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9739 DC = DC->getParent(); 9740 return DC; 9741 } 9742 9743 /// Find the Scope in which a tag is implicitly declared if we see an 9744 /// elaborated type specifier in the specified context, and lookup finds 9745 /// nothing. 9746 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9747 while (S->isClassScope() || 9748 (LangOpts.CPlusPlus && 9749 S->isFunctionPrototypeScope()) || 9750 ((S->getFlags() & Scope::DeclScope) == 0) || 9751 (S->getEntity() && S->getEntity()->isTransparentContext())) 9752 S = S->getParent(); 9753 return S; 9754 } 9755 9756 /// Determine whether a declaration matches a known function in namespace std. 9757 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, 9758 unsigned BuiltinID) { 9759 switch (BuiltinID) { 9760 case Builtin::BI__GetExceptionInfo: 9761 // No type checking whatsoever. 9762 return Ctx.getTargetInfo().getCXXABI().isMicrosoft(); 9763 9764 case Builtin::BIaddressof: 9765 case Builtin::BI__addressof: 9766 case Builtin::BIforward: 9767 case Builtin::BIforward_like: 9768 case Builtin::BImove: 9769 case Builtin::BImove_if_noexcept: 9770 case Builtin::BIas_const: { 9771 // Ensure that we don't treat the algorithm 9772 // OutputIt std::move(InputIt, InputIt, OutputIt) 9773 // as the builtin std::move. 9774 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 9775 return FPT->getNumParams() == 1 && !FPT->isVariadic(); 9776 } 9777 9778 default: 9779 return false; 9780 } 9781 } 9782 9783 NamedDecl* 9784 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9785 TypeSourceInfo *TInfo, LookupResult &Previous, 9786 MultiTemplateParamsArg TemplateParamListsRef, 9787 bool &AddToScope) { 9788 QualType R = TInfo->getType(); 9789 9790 assert(R->isFunctionType()); 9791 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9792 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9793 9794 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9795 llvm::append_range(TemplateParamLists, TemplateParamListsRef); 9796 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9797 if (!TemplateParamLists.empty() && 9798 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9799 TemplateParamLists.back() = Invented; 9800 else 9801 TemplateParamLists.push_back(Invented); 9802 } 9803 9804 // TODO: consider using NameInfo for diagnostic. 9805 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9806 DeclarationName Name = NameInfo.getName(); 9807 StorageClass SC = getFunctionStorageClass(*this, D); 9808 9809 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9810 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9811 diag::err_invalid_thread) 9812 << DeclSpec::getSpecifierName(TSCS); 9813 9814 if (D.isFirstDeclarationOfMember()) 9815 adjustMemberFunctionCC( 9816 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()), 9817 D.isCtorOrDtor(), D.getIdentifierLoc()); 9818 9819 bool isFriend = false; 9820 FunctionTemplateDecl *FunctionTemplate = nullptr; 9821 bool isMemberSpecialization = false; 9822 bool isFunctionTemplateSpecialization = false; 9823 9824 bool HasExplicitTemplateArgs = false; 9825 TemplateArgumentListInfo TemplateArgs; 9826 9827 bool isVirtualOkay = false; 9828 9829 DeclContext *OriginalDC = DC; 9830 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9831 9832 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9833 isVirtualOkay); 9834 if (!NewFD) return nullptr; 9835 9836 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9837 NewFD->setTopLevelDeclInObjCContainer(); 9838 9839 // Set the lexical context. If this is a function-scope declaration, or has a 9840 // C++ scope specifier, or is the object of a friend declaration, the lexical 9841 // context will be different from the semantic context. 9842 NewFD->setLexicalDeclContext(CurContext); 9843 9844 if (IsLocalExternDecl) 9845 NewFD->setLocalExternDecl(); 9846 9847 if (getLangOpts().CPlusPlus) { 9848 // The rules for implicit inlines changed in C++20 for methods and friends 9849 // with an in-class definition (when such a definition is not attached to 9850 // the global module). User-specified 'inline' overrides this (set when 9851 // the function decl is created above). 9852 // FIXME: We need a better way to separate C++ standard and clang modules. 9853 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules || 9854 !NewFD->getOwningModule() || 9855 NewFD->getOwningModule()->isGlobalModule() || 9856 NewFD->getOwningModule()->isHeaderLikeModule(); 9857 bool isInline = D.getDeclSpec().isInlineSpecified(); 9858 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9859 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9860 isFriend = D.getDeclSpec().isFriendSpecified(); 9861 if (isFriend && !isInline && D.isFunctionDefinition()) { 9862 // Pre-C++20 [class.friend]p5 9863 // A function can be defined in a friend declaration of a 9864 // class . . . . Such a function is implicitly inline. 9865 // Post C++20 [class.friend]p7 9866 // Such a function is implicitly an inline function if it is attached 9867 // to the global module. 9868 NewFD->setImplicitlyInline(ImplicitInlineCXX20); 9869 } 9870 9871 // If this is a method defined in an __interface, and is not a constructor 9872 // or an overloaded operator, then set the pure flag (isVirtual will already 9873 // return true). 9874 if (const CXXRecordDecl *Parent = 9875 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9876 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9877 NewFD->setPure(true); 9878 9879 // C++ [class.union]p2 9880 // A union can have member functions, but not virtual functions. 9881 if (isVirtual && Parent->isUnion()) { 9882 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9883 NewFD->setInvalidDecl(); 9884 } 9885 if ((Parent->isClass() || Parent->isStruct()) && 9886 Parent->hasAttr<SYCLSpecialClassAttr>() && 9887 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() && 9888 NewFD->getName() == "__init" && D.isFunctionDefinition()) { 9889 if (auto *Def = Parent->getDefinition()) 9890 Def->setInitMethod(true); 9891 } 9892 } 9893 9894 SetNestedNameSpecifier(*this, NewFD, D); 9895 isMemberSpecialization = false; 9896 isFunctionTemplateSpecialization = false; 9897 if (D.isInvalidType()) 9898 NewFD->setInvalidDecl(); 9899 9900 // Match up the template parameter lists with the scope specifier, then 9901 // determine whether we have a template or a template specialization. 9902 bool Invalid = false; 9903 TemplateIdAnnotation *TemplateId = 9904 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9905 ? D.getName().TemplateId 9906 : nullptr; 9907 TemplateParameterList *TemplateParams = 9908 MatchTemplateParametersToScopeSpecifier( 9909 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9910 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend, 9911 isMemberSpecialization, Invalid); 9912 if (TemplateParams) { 9913 // Check that we can declare a template here. 9914 if (CheckTemplateDeclScope(S, TemplateParams)) 9915 NewFD->setInvalidDecl(); 9916 9917 if (TemplateParams->size() > 0) { 9918 // This is a function template 9919 9920 // A destructor cannot be a template. 9921 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9922 Diag(NewFD->getLocation(), diag::err_destructor_template); 9923 NewFD->setInvalidDecl(); 9924 // Function template with explicit template arguments. 9925 } else if (TemplateId) { 9926 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9927 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9928 NewFD->setInvalidDecl(); 9929 } 9930 9931 // If we're adding a template to a dependent context, we may need to 9932 // rebuilding some of the types used within the template parameter list, 9933 // now that we know what the current instantiation is. 9934 if (DC->isDependentContext()) { 9935 ContextRAII SavedContext(*this, DC); 9936 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9937 Invalid = true; 9938 } 9939 9940 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9941 NewFD->getLocation(), 9942 Name, TemplateParams, 9943 NewFD); 9944 FunctionTemplate->setLexicalDeclContext(CurContext); 9945 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9946 9947 // For source fidelity, store the other template param lists. 9948 if (TemplateParamLists.size() > 1) { 9949 NewFD->setTemplateParameterListsInfo(Context, 9950 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9951 .drop_back(1)); 9952 } 9953 } else { 9954 // This is a function template specialization. 9955 isFunctionTemplateSpecialization = true; 9956 // For source fidelity, store all the template param lists. 9957 if (TemplateParamLists.size() > 0) 9958 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9959 9960 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9961 if (isFriend) { 9962 // We want to remove the "template<>", found here. 9963 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9964 9965 // If we remove the template<> and the name is not a 9966 // template-id, we're actually silently creating a problem: 9967 // the friend declaration will refer to an untemplated decl, 9968 // and clearly the user wants a template specialization. So 9969 // we need to insert '<>' after the name. 9970 SourceLocation InsertLoc; 9971 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9972 InsertLoc = D.getName().getSourceRange().getEnd(); 9973 InsertLoc = getLocForEndOfToken(InsertLoc); 9974 } 9975 9976 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9977 << Name << RemoveRange 9978 << FixItHint::CreateRemoval(RemoveRange) 9979 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9980 Invalid = true; 9981 9982 // Recover by faking up an empty template argument list. 9983 HasExplicitTemplateArgs = true; 9984 TemplateArgs.setLAngleLoc(InsertLoc); 9985 TemplateArgs.setRAngleLoc(InsertLoc); 9986 } 9987 } 9988 } else { 9989 // Check that we can declare a template here. 9990 if (!TemplateParamLists.empty() && isMemberSpecialization && 9991 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9992 NewFD->setInvalidDecl(); 9993 9994 // All template param lists were matched against the scope specifier: 9995 // this is NOT (an explicit specialization of) a template. 9996 if (TemplateParamLists.size() > 0) 9997 // For source fidelity, store all the template param lists. 9998 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9999 10000 // "friend void foo<>(int);" is an implicit specialization decl. 10001 if (isFriend && TemplateId) 10002 isFunctionTemplateSpecialization = true; 10003 } 10004 10005 // If this is a function template specialization and the unqualified-id of 10006 // the declarator-id is a template-id, convert the template argument list 10007 // into our AST format and check for unexpanded packs. 10008 if (isFunctionTemplateSpecialization && TemplateId) { 10009 HasExplicitTemplateArgs = true; 10010 10011 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 10012 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 10013 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 10014 TemplateId->NumArgs); 10015 translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 10016 10017 // FIXME: Should we check for unexpanded packs if this was an (invalid) 10018 // declaration of a function template partial specialization? Should we 10019 // consider the unexpanded pack context to be a partial specialization? 10020 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) { 10021 if (DiagnoseUnexpandedParameterPack( 10022 ArgLoc, isFriend ? UPPC_FriendDeclaration 10023 : UPPC_ExplicitSpecialization)) 10024 NewFD->setInvalidDecl(); 10025 } 10026 } 10027 10028 if (Invalid) { 10029 NewFD->setInvalidDecl(); 10030 if (FunctionTemplate) 10031 FunctionTemplate->setInvalidDecl(); 10032 } 10033 10034 // C++ [dcl.fct.spec]p5: 10035 // The virtual specifier shall only be used in declarations of 10036 // nonstatic class member functions that appear within a 10037 // member-specification of a class declaration; see 10.3. 10038 // 10039 if (isVirtual && !NewFD->isInvalidDecl()) { 10040 if (!isVirtualOkay) { 10041 Diag(D.getDeclSpec().getVirtualSpecLoc(), 10042 diag::err_virtual_non_function); 10043 } else if (!CurContext->isRecord()) { 10044 // 'virtual' was specified outside of the class. 10045 Diag(D.getDeclSpec().getVirtualSpecLoc(), 10046 diag::err_virtual_out_of_class) 10047 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 10048 } else if (NewFD->getDescribedFunctionTemplate()) { 10049 // C++ [temp.mem]p3: 10050 // A member function template shall not be virtual. 10051 Diag(D.getDeclSpec().getVirtualSpecLoc(), 10052 diag::err_virtual_member_function_template) 10053 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 10054 } else { 10055 // Okay: Add virtual to the method. 10056 NewFD->setVirtualAsWritten(true); 10057 } 10058 10059 if (getLangOpts().CPlusPlus14 && 10060 NewFD->getReturnType()->isUndeducedType()) 10061 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 10062 } 10063 10064 if (getLangOpts().CPlusPlus14 && 10065 (NewFD->isDependentContext() || 10066 (isFriend && CurContext->isDependentContext())) && 10067 NewFD->getReturnType()->isUndeducedType()) { 10068 // If the function template is referenced directly (for instance, as a 10069 // member of the current instantiation), pretend it has a dependent type. 10070 // This is not really justified by the standard, but is the only sane 10071 // thing to do. 10072 // FIXME: For a friend function, we have not marked the function as being 10073 // a friend yet, so 'isDependentContext' on the FD doesn't work. 10074 const FunctionProtoType *FPT = 10075 NewFD->getType()->castAs<FunctionProtoType>(); 10076 QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); 10077 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 10078 FPT->getExtProtoInfo())); 10079 } 10080 10081 // C++ [dcl.fct.spec]p3: 10082 // The inline specifier shall not appear on a block scope function 10083 // declaration. 10084 if (isInline && !NewFD->isInvalidDecl()) { 10085 if (CurContext->isFunctionOrMethod()) { 10086 // 'inline' is not allowed on block scope function declaration. 10087 Diag(D.getDeclSpec().getInlineSpecLoc(), 10088 diag::err_inline_declaration_block_scope) << Name 10089 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 10090 } 10091 } 10092 10093 // C++ [dcl.fct.spec]p6: 10094 // The explicit specifier shall be used only in the declaration of a 10095 // constructor or conversion function within its class definition; 10096 // see 12.3.1 and 12.3.2. 10097 if (hasExplicit && !NewFD->isInvalidDecl() && 10098 !isa<CXXDeductionGuideDecl>(NewFD)) { 10099 if (!CurContext->isRecord()) { 10100 // 'explicit' was specified outside of the class. 10101 Diag(D.getDeclSpec().getExplicitSpecLoc(), 10102 diag::err_explicit_out_of_class) 10103 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 10104 } else if (!isa<CXXConstructorDecl>(NewFD) && 10105 !isa<CXXConversionDecl>(NewFD)) { 10106 // 'explicit' was specified on a function that wasn't a constructor 10107 // or conversion function. 10108 Diag(D.getDeclSpec().getExplicitSpecLoc(), 10109 diag::err_explicit_non_ctor_or_conv_function) 10110 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 10111 } 10112 } 10113 10114 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 10115 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 10116 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 10117 // are implicitly inline. 10118 NewFD->setImplicitlyInline(); 10119 10120 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 10121 // be either constructors or to return a literal type. Therefore, 10122 // destructors cannot be declared constexpr. 10123 if (isa<CXXDestructorDecl>(NewFD) && 10124 (!getLangOpts().CPlusPlus20 || 10125 ConstexprKind == ConstexprSpecKind::Consteval)) { 10126 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 10127 << static_cast<int>(ConstexprKind); 10128 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 10129 ? ConstexprSpecKind::Unspecified 10130 : ConstexprSpecKind::Constexpr); 10131 } 10132 // C++20 [dcl.constexpr]p2: An allocation function, or a 10133 // deallocation function shall not be declared with the consteval 10134 // specifier. 10135 if (ConstexprKind == ConstexprSpecKind::Consteval && 10136 (NewFD->getOverloadedOperator() == OO_New || 10137 NewFD->getOverloadedOperator() == OO_Array_New || 10138 NewFD->getOverloadedOperator() == OO_Delete || 10139 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 10140 Diag(D.getDeclSpec().getConstexprSpecLoc(), 10141 diag::err_invalid_consteval_decl_kind) 10142 << NewFD; 10143 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 10144 } 10145 } 10146 10147 // If __module_private__ was specified, mark the function accordingly. 10148 if (D.getDeclSpec().isModulePrivateSpecified()) { 10149 if (isFunctionTemplateSpecialization) { 10150 SourceLocation ModulePrivateLoc 10151 = D.getDeclSpec().getModulePrivateSpecLoc(); 10152 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 10153 << 0 10154 << FixItHint::CreateRemoval(ModulePrivateLoc); 10155 } else { 10156 NewFD->setModulePrivate(); 10157 if (FunctionTemplate) 10158 FunctionTemplate->setModulePrivate(); 10159 } 10160 } 10161 10162 if (isFriend) { 10163 if (FunctionTemplate) { 10164 FunctionTemplate->setObjectOfFriendDecl(); 10165 FunctionTemplate->setAccess(AS_public); 10166 } 10167 NewFD->setObjectOfFriendDecl(); 10168 NewFD->setAccess(AS_public); 10169 } 10170 10171 // If a function is defined as defaulted or deleted, mark it as such now. 10172 // We'll do the relevant checks on defaulted / deleted functions later. 10173 switch (D.getFunctionDefinitionKind()) { 10174 case FunctionDefinitionKind::Declaration: 10175 case FunctionDefinitionKind::Definition: 10176 break; 10177 10178 case FunctionDefinitionKind::Defaulted: 10179 NewFD->setDefaulted(); 10180 break; 10181 10182 case FunctionDefinitionKind::Deleted: 10183 NewFD->setDeletedAsWritten(); 10184 break; 10185 } 10186 10187 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 10188 D.isFunctionDefinition() && !isInline) { 10189 // Pre C++20 [class.mfct]p2: 10190 // A member function may be defined (8.4) in its class definition, in 10191 // which case it is an inline member function (7.1.2) 10192 // Post C++20 [class.mfct]p1: 10193 // If a member function is attached to the global module and is defined 10194 // in its class definition, it is inline. 10195 NewFD->setImplicitlyInline(ImplicitInlineCXX20); 10196 } 10197 10198 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 10199 !CurContext->isRecord()) { 10200 // C++ [class.static]p1: 10201 // A data or function member of a class may be declared static 10202 // in a class definition, in which case it is a static member of 10203 // the class. 10204 10205 // Complain about the 'static' specifier if it's on an out-of-line 10206 // member function definition. 10207 10208 // MSVC permits the use of a 'static' storage specifier on an out-of-line 10209 // member function template declaration and class member template 10210 // declaration (MSVC versions before 2015), warn about this. 10211 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 10212 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 10213 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 10214 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 10215 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 10216 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10217 } 10218 10219 // C++11 [except.spec]p15: 10220 // A deallocation function with no exception-specification is treated 10221 // as if it were specified with noexcept(true). 10222 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 10223 if ((Name.getCXXOverloadedOperator() == OO_Delete || 10224 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 10225 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 10226 NewFD->setType(Context.getFunctionType( 10227 FPT->getReturnType(), FPT->getParamTypes(), 10228 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 10229 10230 // C++20 [dcl.inline]/7 10231 // If an inline function or variable that is attached to a named module 10232 // is declared in a definition domain, it shall be defined in that 10233 // domain. 10234 // So, if the current declaration does not have a definition, we must 10235 // check at the end of the TU (or when the PMF starts) to see that we 10236 // have a definition at that point. 10237 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 && 10238 NewFD->hasOwningModule() && NewFD->getOwningModule()->isNamedModule()) { 10239 PendingInlineFuncDecls.insert(NewFD); 10240 } 10241 } 10242 10243 // Filter out previous declarations that don't match the scope. 10244 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 10245 D.getCXXScopeSpec().isNotEmpty() || 10246 isMemberSpecialization || 10247 isFunctionTemplateSpecialization); 10248 10249 // Handle GNU asm-label extension (encoded as an attribute). 10250 if (Expr *E = (Expr*) D.getAsmLabel()) { 10251 // The parser guarantees this is a string. 10252 StringLiteral *SE = cast<StringLiteral>(E); 10253 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 10254 /*IsLiteralLabel=*/true, 10255 SE->getStrTokenLoc(0))); 10256 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 10257 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 10258 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 10259 if (I != ExtnameUndeclaredIdentifiers.end()) { 10260 if (isDeclExternC(NewFD)) { 10261 NewFD->addAttr(I->second); 10262 ExtnameUndeclaredIdentifiers.erase(I); 10263 } else 10264 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 10265 << /*Variable*/0 << NewFD; 10266 } 10267 } 10268 10269 // Copy the parameter declarations from the declarator D to the function 10270 // declaration NewFD, if they are available. First scavenge them into Params. 10271 SmallVector<ParmVarDecl*, 16> Params; 10272 unsigned FTIIdx; 10273 if (D.isFunctionDeclarator(FTIIdx)) { 10274 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 10275 10276 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 10277 // function that takes no arguments, not a function that takes a 10278 // single void argument. 10279 // We let through "const void" here because Sema::GetTypeForDeclarator 10280 // already checks for that case. 10281 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 10282 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 10283 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 10284 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 10285 Param->setDeclContext(NewFD); 10286 Params.push_back(Param); 10287 10288 if (Param->isInvalidDecl()) 10289 NewFD->setInvalidDecl(); 10290 } 10291 } 10292 10293 if (!getLangOpts().CPlusPlus) { 10294 // In C, find all the tag declarations from the prototype and move them 10295 // into the function DeclContext. Remove them from the surrounding tag 10296 // injection context of the function, which is typically but not always 10297 // the TU. 10298 DeclContext *PrototypeTagContext = 10299 getTagInjectionContext(NewFD->getLexicalDeclContext()); 10300 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 10301 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 10302 10303 // We don't want to reparent enumerators. Look at their parent enum 10304 // instead. 10305 if (!TD) { 10306 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 10307 TD = cast<EnumDecl>(ECD->getDeclContext()); 10308 } 10309 if (!TD) 10310 continue; 10311 DeclContext *TagDC = TD->getLexicalDeclContext(); 10312 if (!TagDC->containsDecl(TD)) 10313 continue; 10314 TagDC->removeDecl(TD); 10315 TD->setDeclContext(NewFD); 10316 NewFD->addDecl(TD); 10317 10318 // Preserve the lexical DeclContext if it is not the surrounding tag 10319 // injection context of the FD. In this example, the semantic context of 10320 // E will be f and the lexical context will be S, while both the 10321 // semantic and lexical contexts of S will be f: 10322 // void f(struct S { enum E { a } f; } s); 10323 if (TagDC != PrototypeTagContext) 10324 TD->setLexicalDeclContext(TagDC); 10325 } 10326 } 10327 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 10328 // When we're declaring a function with a typedef, typeof, etc as in the 10329 // following example, we'll need to synthesize (unnamed) 10330 // parameters for use in the declaration. 10331 // 10332 // @code 10333 // typedef void fn(int); 10334 // fn f; 10335 // @endcode 10336 10337 // Synthesize a parameter for each argument type. 10338 for (const auto &AI : FT->param_types()) { 10339 ParmVarDecl *Param = 10340 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 10341 Param->setScopeInfo(0, Params.size()); 10342 Params.push_back(Param); 10343 } 10344 } else { 10345 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 10346 "Should not need args for typedef of non-prototype fn"); 10347 } 10348 10349 // Finally, we know we have the right number of parameters, install them. 10350 NewFD->setParams(Params); 10351 10352 if (D.getDeclSpec().isNoreturnSpecified()) 10353 NewFD->addAttr( 10354 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc())); 10355 10356 // Functions returning a variably modified type violate C99 6.7.5.2p2 10357 // because all functions have linkage. 10358 if (!NewFD->isInvalidDecl() && 10359 NewFD->getReturnType()->isVariablyModifiedType()) { 10360 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 10361 NewFD->setInvalidDecl(); 10362 } 10363 10364 // Apply an implicit SectionAttr if '#pragma clang section text' is active 10365 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 10366 !NewFD->hasAttr<SectionAttr>()) 10367 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 10368 Context, PragmaClangTextSection.SectionName, 10369 PragmaClangTextSection.PragmaLocation)); 10370 10371 // Apply an implicit SectionAttr if #pragma code_seg is active. 10372 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 10373 !NewFD->hasAttr<SectionAttr>()) { 10374 NewFD->addAttr(SectionAttr::CreateImplicit( 10375 Context, CodeSegStack.CurrentValue->getString(), 10376 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate)); 10377 if (UnifySection(CodeSegStack.CurrentValue->getString(), 10378 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 10379 ASTContext::PSF_Read, 10380 NewFD)) 10381 NewFD->dropAttr<SectionAttr>(); 10382 } 10383 10384 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is 10385 // active. 10386 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() && 10387 !NewFD->hasAttr<StrictGuardStackCheckAttr>()) 10388 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit( 10389 Context, PragmaClangTextSection.PragmaLocation)); 10390 10391 // Apply an implicit CodeSegAttr from class declspec or 10392 // apply an implicit SectionAttr from #pragma code_seg if active. 10393 if (!NewFD->hasAttr<CodeSegAttr>()) { 10394 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 10395 D.isFunctionDefinition())) { 10396 NewFD->addAttr(SAttr); 10397 } 10398 } 10399 10400 // Handle attributes. 10401 ProcessDeclAttributes(S, NewFD, D); 10402 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 10403 if (NewTVA && !NewTVA->isDefaultVersion() && 10404 !Context.getTargetInfo().hasFeature("fmv")) { 10405 // Don't add to scope fmv functions declarations if fmv disabled 10406 AddToScope = false; 10407 return NewFD; 10408 } 10409 10410 if (getLangOpts().OpenCL || getLangOpts().HLSL) { 10411 // Neither OpenCL nor HLSL allow an address space qualifyer on a return 10412 // type. 10413 // 10414 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 10415 // type declaration will generate a compilation error. 10416 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 10417 if (AddressSpace != LangAS::Default) { 10418 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space); 10419 NewFD->setInvalidDecl(); 10420 } 10421 } 10422 10423 if (!getLangOpts().CPlusPlus) { 10424 // Perform semantic checking on the function declaration. 10425 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 10426 CheckMain(NewFD, D.getDeclSpec()); 10427 10428 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 10429 CheckMSVCRTEntryPoint(NewFD); 10430 10431 if (!NewFD->isInvalidDecl()) 10432 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 10433 isMemberSpecialization, 10434 D.isFunctionDefinition())); 10435 else if (!Previous.empty()) 10436 // Recover gracefully from an invalid redeclaration. 10437 D.setRedeclaration(true); 10438 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 10439 Previous.getResultKind() != LookupResult::FoundOverloaded) && 10440 "previous declaration set still overloaded"); 10441 10442 // Diagnose no-prototype function declarations with calling conventions that 10443 // don't support variadic calls. Only do this in C and do it after merging 10444 // possibly prototyped redeclarations. 10445 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 10446 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 10447 CallingConv CC = FT->getExtInfo().getCC(); 10448 if (!supportsVariadicCall(CC)) { 10449 // Windows system headers sometimes accidentally use stdcall without 10450 // (void) parameters, so we relax this to a warning. 10451 int DiagID = 10452 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 10453 Diag(NewFD->getLocation(), DiagID) 10454 << FunctionType::getNameForCallConv(CC); 10455 } 10456 } 10457 10458 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 10459 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 10460 checkNonTrivialCUnion(NewFD->getReturnType(), 10461 NewFD->getReturnTypeSourceRange().getBegin(), 10462 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 10463 } else { 10464 // C++11 [replacement.functions]p3: 10465 // The program's definitions shall not be specified as inline. 10466 // 10467 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 10468 // 10469 // Suppress the diagnostic if the function is __attribute__((used)), since 10470 // that forces an external definition to be emitted. 10471 if (D.getDeclSpec().isInlineSpecified() && 10472 NewFD->isReplaceableGlobalAllocationFunction() && 10473 !NewFD->hasAttr<UsedAttr>()) 10474 Diag(D.getDeclSpec().getInlineSpecLoc(), 10475 diag::ext_operator_new_delete_declared_inline) 10476 << NewFD->getDeclName(); 10477 10478 // We do not add HD attributes to specializations here because 10479 // they may have different constexpr-ness compared to their 10480 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 10481 // may end up with different effective targets. Instead, a 10482 // specialization inherits its target attributes from its template 10483 // in the CheckFunctionTemplateSpecialization() call below. 10484 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 10485 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 10486 10487 // Handle explict specializations of function templates 10488 // and friend function declarations with an explicit 10489 // template argument list. 10490 if (isFunctionTemplateSpecialization) { 10491 bool isDependentSpecialization = false; 10492 if (isFriend) { 10493 // For friend function specializations, this is a dependent 10494 // specialization if its semantic context is dependent, its 10495 // type is dependent, or if its template-id is dependent. 10496 isDependentSpecialization = 10497 DC->isDependentContext() || NewFD->getType()->isDependentType() || 10498 (HasExplicitTemplateArgs && 10499 TemplateSpecializationType:: 10500 anyInstantiationDependentTemplateArguments( 10501 TemplateArgs.arguments())); 10502 assert((!isDependentSpecialization || 10503 (HasExplicitTemplateArgs == isDependentSpecialization)) && 10504 "dependent friend function specialization without template " 10505 "args"); 10506 } else { 10507 // For class-scope explicit specializations of function templates, 10508 // if the lexical context is dependent, then the specialization 10509 // is dependent. 10510 isDependentSpecialization = 10511 CurContext->isRecord() && CurContext->isDependentContext(); 10512 } 10513 10514 TemplateArgumentListInfo *ExplicitTemplateArgs = 10515 HasExplicitTemplateArgs ? &TemplateArgs : nullptr; 10516 if (isDependentSpecialization) { 10517 // If it's a dependent specialization, it may not be possible 10518 // to determine the primary template (for explicit specializations) 10519 // or befriended declaration (for friends) until the enclosing 10520 // template is instantiated. In such cases, we store the declarations 10521 // found by name lookup and defer resolution until instantiation. 10522 if (CheckDependentFunctionTemplateSpecialization( 10523 NewFD, ExplicitTemplateArgs, Previous)) 10524 NewFD->setInvalidDecl(); 10525 } else if (!NewFD->isInvalidDecl()) { 10526 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs, 10527 Previous)) 10528 NewFD->setInvalidDecl(); 10529 } 10530 10531 // C++ [dcl.stc]p1: 10532 // A storage-class-specifier shall not be specified in an explicit 10533 // specialization (14.7.3) 10534 // FIXME: We should be checking this for dependent specializations. 10535 FunctionTemplateSpecializationInfo *Info = 10536 NewFD->getTemplateSpecializationInfo(); 10537 if (Info && SC != SC_None) { 10538 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 10539 Diag(NewFD->getLocation(), 10540 diag::err_explicit_specialization_inconsistent_storage_class) 10541 << SC 10542 << FixItHint::CreateRemoval( 10543 D.getDeclSpec().getStorageClassSpecLoc()); 10544 10545 else 10546 Diag(NewFD->getLocation(), 10547 diag::ext_explicit_specialization_storage_class) 10548 << FixItHint::CreateRemoval( 10549 D.getDeclSpec().getStorageClassSpecLoc()); 10550 } 10551 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 10552 if (CheckMemberSpecialization(NewFD, Previous)) 10553 NewFD->setInvalidDecl(); 10554 } 10555 10556 // Perform semantic checking on the function declaration. 10557 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 10558 CheckMain(NewFD, D.getDeclSpec()); 10559 10560 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 10561 CheckMSVCRTEntryPoint(NewFD); 10562 10563 if (!NewFD->isInvalidDecl()) 10564 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 10565 isMemberSpecialization, 10566 D.isFunctionDefinition())); 10567 else if (!Previous.empty()) 10568 // Recover gracefully from an invalid redeclaration. 10569 D.setRedeclaration(true); 10570 10571 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() || 10572 !D.isRedeclaration() || 10573 Previous.getResultKind() != LookupResult::FoundOverloaded) && 10574 "previous declaration set still overloaded"); 10575 10576 NamedDecl *PrincipalDecl = (FunctionTemplate 10577 ? cast<NamedDecl>(FunctionTemplate) 10578 : NewFD); 10579 10580 if (isFriend && NewFD->getPreviousDecl()) { 10581 AccessSpecifier Access = AS_public; 10582 if (!NewFD->isInvalidDecl()) 10583 Access = NewFD->getPreviousDecl()->getAccess(); 10584 10585 NewFD->setAccess(Access); 10586 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 10587 } 10588 10589 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 10590 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 10591 PrincipalDecl->setNonMemberOperator(); 10592 10593 // If we have a function template, check the template parameter 10594 // list. This will check and merge default template arguments. 10595 if (FunctionTemplate) { 10596 FunctionTemplateDecl *PrevTemplate = 10597 FunctionTemplate->getPreviousDecl(); 10598 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 10599 PrevTemplate ? PrevTemplate->getTemplateParameters() 10600 : nullptr, 10601 D.getDeclSpec().isFriendSpecified() 10602 ? (D.isFunctionDefinition() 10603 ? TPC_FriendFunctionTemplateDefinition 10604 : TPC_FriendFunctionTemplate) 10605 : (D.getCXXScopeSpec().isSet() && 10606 DC && DC->isRecord() && 10607 DC->isDependentContext()) 10608 ? TPC_ClassTemplateMember 10609 : TPC_FunctionTemplate); 10610 } 10611 10612 if (NewFD->isInvalidDecl()) { 10613 // Ignore all the rest of this. 10614 } else if (!D.isRedeclaration()) { 10615 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 10616 AddToScope }; 10617 // Fake up an access specifier if it's supposed to be a class member. 10618 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 10619 NewFD->setAccess(AS_public); 10620 10621 // Qualified decls generally require a previous declaration. 10622 if (D.getCXXScopeSpec().isSet()) { 10623 // ...with the major exception of templated-scope or 10624 // dependent-scope friend declarations. 10625 10626 // TODO: we currently also suppress this check in dependent 10627 // contexts because (1) the parameter depth will be off when 10628 // matching friend templates and (2) we might actually be 10629 // selecting a friend based on a dependent factor. But there 10630 // are situations where these conditions don't apply and we 10631 // can actually do this check immediately. 10632 // 10633 // Unless the scope is dependent, it's always an error if qualified 10634 // redeclaration lookup found nothing at all. Diagnose that now; 10635 // nothing will diagnose that error later. 10636 if (isFriend && 10637 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 10638 (!Previous.empty() && CurContext->isDependentContext()))) { 10639 // ignore these 10640 } else if (NewFD->isCPUDispatchMultiVersion() || 10641 NewFD->isCPUSpecificMultiVersion()) { 10642 // ignore this, we allow the redeclaration behavior here to create new 10643 // versions of the function. 10644 } else { 10645 // The user tried to provide an out-of-line definition for a 10646 // function that is a member of a class or namespace, but there 10647 // was no such member function declared (C++ [class.mfct]p2, 10648 // C++ [namespace.memdef]p2). For example: 10649 // 10650 // class X { 10651 // void f() const; 10652 // }; 10653 // 10654 // void X::f() { } // ill-formed 10655 // 10656 // Complain about this problem, and attempt to suggest close 10657 // matches (e.g., those that differ only in cv-qualifiers and 10658 // whether the parameter types are references). 10659 10660 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10661 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 10662 AddToScope = ExtraArgs.AddToScope; 10663 return Result; 10664 } 10665 } 10666 10667 // Unqualified local friend declarations are required to resolve 10668 // to something. 10669 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 10670 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10671 *this, Previous, NewFD, ExtraArgs, true, S)) { 10672 AddToScope = ExtraArgs.AddToScope; 10673 return Result; 10674 } 10675 } 10676 } else if (!D.isFunctionDefinition() && 10677 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 10678 !isFriend && !isFunctionTemplateSpecialization && 10679 !isMemberSpecialization) { 10680 // An out-of-line member function declaration must also be a 10681 // definition (C++ [class.mfct]p2). 10682 // Note that this is not the case for explicit specializations of 10683 // function templates or member functions of class templates, per 10684 // C++ [temp.expl.spec]p2. We also allow these declarations as an 10685 // extension for compatibility with old SWIG code which likes to 10686 // generate them. 10687 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 10688 << D.getCXXScopeSpec().getRange(); 10689 } 10690 } 10691 10692 if (getLangOpts().HLSL && D.isFunctionDefinition()) { 10693 // Any top level function could potentially be specified as an entry. 10694 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier()) 10695 ActOnHLSLTopLevelFunction(NewFD); 10696 10697 if (NewFD->hasAttr<HLSLShaderAttr>()) 10698 CheckHLSLEntryPoint(NewFD); 10699 } 10700 10701 // If this is the first declaration of a library builtin function, add 10702 // attributes as appropriate. 10703 if (!D.isRedeclaration()) { 10704 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 10705 if (unsigned BuiltinID = II->getBuiltinID()) { 10706 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID); 10707 if (!InStdNamespace && 10708 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 10709 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 10710 // Validate the type matches unless this builtin is specified as 10711 // matching regardless of its declared type. 10712 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 10713 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10714 } else { 10715 ASTContext::GetBuiltinTypeError Error; 10716 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10717 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 10718 10719 if (!Error && !BuiltinType.isNull() && 10720 Context.hasSameFunctionTypeIgnoringExceptionSpec( 10721 NewFD->getType(), BuiltinType)) 10722 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10723 } 10724 } 10725 } else if (InStdNamespace && NewFD->isInStdNamespace() && 10726 isStdBuiltin(Context, NewFD, BuiltinID)) { 10727 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10728 } 10729 } 10730 } 10731 } 10732 10733 ProcessPragmaWeak(S, NewFD); 10734 checkAttributesAfterMerging(*this, *NewFD); 10735 10736 AddKnownFunctionAttributes(NewFD); 10737 10738 if (NewFD->hasAttr<OverloadableAttr>() && 10739 !NewFD->getType()->getAs<FunctionProtoType>()) { 10740 Diag(NewFD->getLocation(), 10741 diag::err_attribute_overloadable_no_prototype) 10742 << NewFD; 10743 NewFD->dropAttr<OverloadableAttr>(); 10744 } 10745 10746 // If there's a #pragma GCC visibility in scope, and this isn't a class 10747 // member, set the visibility of this function. 10748 if (!DC->isRecord() && NewFD->isExternallyVisible()) 10749 AddPushedVisibilityAttribute(NewFD); 10750 10751 // If there's a #pragma clang arc_cf_code_audited in scope, consider 10752 // marking the function. 10753 AddCFAuditedAttribute(NewFD); 10754 10755 // If this is a function definition, check if we have to apply any 10756 // attributes (i.e. optnone and no_builtin) due to a pragma. 10757 if (D.isFunctionDefinition()) { 10758 AddRangeBasedOptnone(NewFD); 10759 AddImplicitMSFunctionNoBuiltinAttr(NewFD); 10760 AddSectionMSAllocText(NewFD); 10761 ModifyFnAttributesMSPragmaOptimize(NewFD); 10762 } 10763 10764 // If this is the first declaration of an extern C variable, update 10765 // the map of such variables. 10766 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 10767 isIncompleteDeclExternC(*this, NewFD)) 10768 RegisterLocallyScopedExternCDecl(NewFD, S); 10769 10770 // Set this FunctionDecl's range up to the right paren. 10771 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 10772 10773 if (D.isRedeclaration() && !Previous.empty()) { 10774 NamedDecl *Prev = Previous.getRepresentativeDecl(); 10775 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 10776 isMemberSpecialization || 10777 isFunctionTemplateSpecialization, 10778 D.isFunctionDefinition()); 10779 } 10780 10781 if (getLangOpts().CUDA) { 10782 IdentifierInfo *II = NewFD->getIdentifier(); 10783 if (II && II->isStr(getCudaConfigureFuncName()) && 10784 !NewFD->isInvalidDecl() && 10785 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 10786 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 10787 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 10788 << getCudaConfigureFuncName(); 10789 Context.setcudaConfigureCallDecl(NewFD); 10790 } 10791 10792 // Variadic functions, other than a *declaration* of printf, are not allowed 10793 // in device-side CUDA code, unless someone passed 10794 // -fcuda-allow-variadic-functions. 10795 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 10796 (NewFD->hasAttr<CUDADeviceAttr>() || 10797 NewFD->hasAttr<CUDAGlobalAttr>()) && 10798 !(II && II->isStr("printf") && NewFD->isExternC() && 10799 !D.isFunctionDefinition())) { 10800 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 10801 } 10802 } 10803 10804 MarkUnusedFileScopedDecl(NewFD); 10805 10806 10807 10808 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 10809 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 10810 if (SC == SC_Static) { 10811 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 10812 D.setInvalidType(); 10813 } 10814 10815 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 10816 if (!NewFD->getReturnType()->isVoidType()) { 10817 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 10818 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 10819 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 10820 : FixItHint()); 10821 D.setInvalidType(); 10822 } 10823 10824 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 10825 for (auto *Param : NewFD->parameters()) 10826 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 10827 10828 if (getLangOpts().OpenCLCPlusPlus) { 10829 if (DC->isRecord()) { 10830 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 10831 D.setInvalidType(); 10832 } 10833 if (FunctionTemplate) { 10834 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10835 D.setInvalidType(); 10836 } 10837 } 10838 } 10839 10840 if (getLangOpts().CPlusPlus) { 10841 // Precalculate whether this is a friend function template with a constraint 10842 // that depends on an enclosing template, per [temp.friend]p9. 10843 if (isFriend && FunctionTemplate && 10844 FriendConstraintsDependOnEnclosingTemplate(NewFD)) 10845 NewFD->setFriendConstraintRefersToEnclosingTemplate(true); 10846 10847 if (FunctionTemplate) { 10848 if (NewFD->isInvalidDecl()) 10849 FunctionTemplate->setInvalidDecl(); 10850 return FunctionTemplate; 10851 } 10852 10853 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10854 CompleteMemberSpecialization(NewFD, Previous); 10855 } 10856 10857 for (const ParmVarDecl *Param : NewFD->parameters()) { 10858 QualType PT = Param->getType(); 10859 10860 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10861 // types. 10862 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10863 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10864 QualType ElemTy = PipeTy->getElementType(); 10865 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10866 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10867 D.setInvalidType(); 10868 } 10869 } 10870 } 10871 // WebAssembly tables can't be used as function parameters. 10872 if (Context.getTargetInfo().getTriple().isWasm()) { 10873 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) { 10874 Diag(Param->getTypeSpecStartLoc(), 10875 diag::err_wasm_table_as_function_parameter); 10876 D.setInvalidType(); 10877 } 10878 } 10879 } 10880 10881 // Diagnose availability attributes. Availability cannot be used on functions 10882 // that are run during load/unload. 10883 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10884 if (NewFD->hasAttr<ConstructorAttr>()) { 10885 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10886 << 1; 10887 NewFD->dropAttr<AvailabilityAttr>(); 10888 } 10889 if (NewFD->hasAttr<DestructorAttr>()) { 10890 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10891 << 2; 10892 NewFD->dropAttr<AvailabilityAttr>(); 10893 } 10894 } 10895 10896 // Diagnose no_builtin attribute on function declaration that are not a 10897 // definition. 10898 // FIXME: We should really be doing this in 10899 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10900 // the FunctionDecl and at this point of the code 10901 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10902 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10903 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10904 switch (D.getFunctionDefinitionKind()) { 10905 case FunctionDefinitionKind::Defaulted: 10906 case FunctionDefinitionKind::Deleted: 10907 Diag(NBA->getLocation(), 10908 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10909 << NBA->getSpelling(); 10910 break; 10911 case FunctionDefinitionKind::Declaration: 10912 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10913 << NBA->getSpelling(); 10914 break; 10915 case FunctionDefinitionKind::Definition: 10916 break; 10917 } 10918 10919 return NewFD; 10920 } 10921 10922 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10923 /// when __declspec(code_seg) "is applied to a class, all member functions of 10924 /// the class and nested classes -- this includes compiler-generated special 10925 /// member functions -- are put in the specified segment." 10926 /// The actual behavior is a little more complicated. The Microsoft compiler 10927 /// won't check outer classes if there is an active value from #pragma code_seg. 10928 /// The CodeSeg is always applied from the direct parent but only from outer 10929 /// classes when the #pragma code_seg stack is empty. See: 10930 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10931 /// available since MS has removed the page. 10932 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10933 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10934 if (!Method) 10935 return nullptr; 10936 const CXXRecordDecl *Parent = Method->getParent(); 10937 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10938 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10939 NewAttr->setImplicit(true); 10940 return NewAttr; 10941 } 10942 10943 // The Microsoft compiler won't check outer classes for the CodeSeg 10944 // when the #pragma code_seg stack is active. 10945 if (S.CodeSegStack.CurrentValue) 10946 return nullptr; 10947 10948 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10949 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10950 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10951 NewAttr->setImplicit(true); 10952 return NewAttr; 10953 } 10954 } 10955 return nullptr; 10956 } 10957 10958 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10959 /// containing class. Otherwise it will return implicit SectionAttr if the 10960 /// function is a definition and there is an active value on CodeSegStack 10961 /// (from the current #pragma code-seg value). 10962 /// 10963 /// \param FD Function being declared. 10964 /// \param IsDefinition Whether it is a definition or just a declaration. 10965 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10966 /// nullptr if no attribute should be added. 10967 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10968 bool IsDefinition) { 10969 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10970 return A; 10971 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10972 CodeSegStack.CurrentValue) 10973 return SectionAttr::CreateImplicit( 10974 getASTContext(), CodeSegStack.CurrentValue->getString(), 10975 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate); 10976 return nullptr; 10977 } 10978 10979 /// Determines if we can perform a correct type check for \p D as a 10980 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10981 /// best-effort check. 10982 /// 10983 /// \param NewD The new declaration. 10984 /// \param OldD The old declaration. 10985 /// \param NewT The portion of the type of the new declaration to check. 10986 /// \param OldT The portion of the type of the old declaration to check. 10987 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10988 QualType NewT, QualType OldT) { 10989 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10990 return true; 10991 10992 // For dependently-typed local extern declarations and friends, we can't 10993 // perform a correct type check in general until instantiation: 10994 // 10995 // int f(); 10996 // template<typename T> void g() { T f(); } 10997 // 10998 // (valid if g() is only instantiated with T = int). 10999 if (NewT->isDependentType() && 11000 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 11001 return false; 11002 11003 // Similarly, if the previous declaration was a dependent local extern 11004 // declaration, we don't really know its type yet. 11005 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 11006 return false; 11007 11008 return true; 11009 } 11010 11011 /// Checks if the new declaration declared in dependent context must be 11012 /// put in the same redeclaration chain as the specified declaration. 11013 /// 11014 /// \param D Declaration that is checked. 11015 /// \param PrevDecl Previous declaration found with proper lookup method for the 11016 /// same declaration name. 11017 /// \returns True if D must be added to the redeclaration chain which PrevDecl 11018 /// belongs to. 11019 /// 11020 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 11021 if (!D->getLexicalDeclContext()->isDependentContext()) 11022 return true; 11023 11024 // Don't chain dependent friend function definitions until instantiation, to 11025 // permit cases like 11026 // 11027 // void func(); 11028 // template<typename T> class C1 { friend void func() {} }; 11029 // template<typename T> class C2 { friend void func() {} }; 11030 // 11031 // ... which is valid if only one of C1 and C2 is ever instantiated. 11032 // 11033 // FIXME: This need only apply to function definitions. For now, we proxy 11034 // this by checking for a file-scope function. We do not want this to apply 11035 // to friend declarations nominating member functions, because that gets in 11036 // the way of access checks. 11037 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 11038 return false; 11039 11040 auto *VD = dyn_cast<ValueDecl>(D); 11041 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 11042 return !VD || !PrevVD || 11043 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 11044 PrevVD->getType()); 11045 } 11046 11047 /// Check the target or target_version attribute of the function for 11048 /// MultiVersion validity. 11049 /// 11050 /// Returns true if there was an error, false otherwise. 11051 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 11052 const auto *TA = FD->getAttr<TargetAttr>(); 11053 const auto *TVA = FD->getAttr<TargetVersionAttr>(); 11054 assert( 11055 (TA || TVA) && 11056 "MultiVersion candidate requires a target or target_version attribute"); 11057 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 11058 enum ErrType { Feature = 0, Architecture = 1 }; 11059 11060 if (TA) { 11061 ParsedTargetAttr ParseInfo = 11062 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr()); 11063 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) { 11064 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11065 << Architecture << ParseInfo.CPU; 11066 return true; 11067 } 11068 for (const auto &Feat : ParseInfo.Features) { 11069 auto BareFeat = StringRef{Feat}.substr(1); 11070 if (Feat[0] == '-') { 11071 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11072 << Feature << ("no-" + BareFeat).str(); 11073 return true; 11074 } 11075 11076 if (!TargetInfo.validateCpuSupports(BareFeat) || 11077 !TargetInfo.isValidFeatureName(BareFeat)) { 11078 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11079 << Feature << BareFeat; 11080 return true; 11081 } 11082 } 11083 } 11084 11085 if (TVA) { 11086 llvm::SmallVector<StringRef, 8> Feats; 11087 TVA->getFeatures(Feats); 11088 for (const auto &Feat : Feats) { 11089 if (!TargetInfo.validateCpuSupports(Feat)) { 11090 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11091 << Feature << Feat; 11092 return true; 11093 } 11094 } 11095 } 11096 return false; 11097 } 11098 11099 // Provide a white-list of attributes that are allowed to be combined with 11100 // multiversion functions. 11101 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 11102 MultiVersionKind MVKind) { 11103 // Note: this list/diagnosis must match the list in 11104 // checkMultiversionAttributesAllSame. 11105 switch (Kind) { 11106 default: 11107 return false; 11108 case attr::Used: 11109 return MVKind == MultiVersionKind::Target; 11110 case attr::NonNull: 11111 case attr::NoThrow: 11112 return true; 11113 } 11114 } 11115 11116 static bool checkNonMultiVersionCompatAttributes(Sema &S, 11117 const FunctionDecl *FD, 11118 const FunctionDecl *CausedFD, 11119 MultiVersionKind MVKind) { 11120 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) { 11121 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 11122 << static_cast<unsigned>(MVKind) << A; 11123 if (CausedFD) 11124 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 11125 return true; 11126 }; 11127 11128 for (const Attr *A : FD->attrs()) { 11129 switch (A->getKind()) { 11130 case attr::CPUDispatch: 11131 case attr::CPUSpecific: 11132 if (MVKind != MultiVersionKind::CPUDispatch && 11133 MVKind != MultiVersionKind::CPUSpecific) 11134 return Diagnose(S, A); 11135 break; 11136 case attr::Target: 11137 if (MVKind != MultiVersionKind::Target) 11138 return Diagnose(S, A); 11139 break; 11140 case attr::TargetVersion: 11141 if (MVKind != MultiVersionKind::TargetVersion) 11142 return Diagnose(S, A); 11143 break; 11144 case attr::TargetClones: 11145 if (MVKind != MultiVersionKind::TargetClones) 11146 return Diagnose(S, A); 11147 break; 11148 default: 11149 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind)) 11150 return Diagnose(S, A); 11151 break; 11152 } 11153 } 11154 return false; 11155 } 11156 11157 bool Sema::areMultiversionVariantFunctionsCompatible( 11158 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 11159 const PartialDiagnostic &NoProtoDiagID, 11160 const PartialDiagnosticAt &NoteCausedDiagIDAt, 11161 const PartialDiagnosticAt &NoSupportDiagIDAt, 11162 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 11163 bool ConstexprSupported, bool CLinkageMayDiffer) { 11164 enum DoesntSupport { 11165 FuncTemplates = 0, 11166 VirtFuncs = 1, 11167 DeducedReturn = 2, 11168 Constructors = 3, 11169 Destructors = 4, 11170 DeletedFuncs = 5, 11171 DefaultedFuncs = 6, 11172 ConstexprFuncs = 7, 11173 ConstevalFuncs = 8, 11174 Lambda = 9, 11175 }; 11176 enum Different { 11177 CallingConv = 0, 11178 ReturnType = 1, 11179 ConstexprSpec = 2, 11180 InlineSpec = 3, 11181 Linkage = 4, 11182 LanguageLinkage = 5, 11183 }; 11184 11185 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 11186 !OldFD->getType()->getAs<FunctionProtoType>()) { 11187 Diag(OldFD->getLocation(), NoProtoDiagID); 11188 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 11189 return true; 11190 } 11191 11192 if (NoProtoDiagID.getDiagID() != 0 && 11193 !NewFD->getType()->getAs<FunctionProtoType>()) 11194 return Diag(NewFD->getLocation(), NoProtoDiagID); 11195 11196 if (!TemplatesSupported && 11197 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11198 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11199 << FuncTemplates; 11200 11201 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 11202 if (NewCXXFD->isVirtual()) 11203 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11204 << VirtFuncs; 11205 11206 if (isa<CXXConstructorDecl>(NewCXXFD)) 11207 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11208 << Constructors; 11209 11210 if (isa<CXXDestructorDecl>(NewCXXFD)) 11211 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11212 << Destructors; 11213 } 11214 11215 if (NewFD->isDeleted()) 11216 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11217 << DeletedFuncs; 11218 11219 if (NewFD->isDefaulted()) 11220 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11221 << DefaultedFuncs; 11222 11223 if (!ConstexprSupported && NewFD->isConstexpr()) 11224 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11225 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 11226 11227 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 11228 const auto *NewType = cast<FunctionType>(NewQType); 11229 QualType NewReturnType = NewType->getReturnType(); 11230 11231 if (NewReturnType->isUndeducedType()) 11232 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11233 << DeducedReturn; 11234 11235 // Ensure the return type is identical. 11236 if (OldFD) { 11237 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 11238 const auto *OldType = cast<FunctionType>(OldQType); 11239 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 11240 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 11241 11242 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 11243 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 11244 11245 QualType OldReturnType = OldType->getReturnType(); 11246 11247 if (OldReturnType != NewReturnType) 11248 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 11249 11250 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 11251 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 11252 11253 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 11254 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 11255 11256 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 11257 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 11258 11259 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 11260 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 11261 11262 if (CheckEquivalentExceptionSpec( 11263 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 11264 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 11265 return true; 11266 } 11267 return false; 11268 } 11269 11270 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 11271 const FunctionDecl *NewFD, 11272 bool CausesMV, 11273 MultiVersionKind MVKind) { 11274 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 11275 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 11276 if (OldFD) 11277 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11278 return true; 11279 } 11280 11281 bool IsCPUSpecificCPUDispatchMVKind = 11282 MVKind == MultiVersionKind::CPUDispatch || 11283 MVKind == MultiVersionKind::CPUSpecific; 11284 11285 if (CausesMV && OldFD && 11286 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind)) 11287 return true; 11288 11289 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind)) 11290 return true; 11291 11292 // Only allow transition to MultiVersion if it hasn't been used. 11293 if (OldFD && CausesMV && OldFD->isUsed(false)) 11294 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 11295 11296 return S.areMultiversionVariantFunctionsCompatible( 11297 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 11298 PartialDiagnosticAt(NewFD->getLocation(), 11299 S.PDiag(diag::note_multiversioning_caused_here)), 11300 PartialDiagnosticAt(NewFD->getLocation(), 11301 S.PDiag(diag::err_multiversion_doesnt_support) 11302 << static_cast<unsigned>(MVKind)), 11303 PartialDiagnosticAt(NewFD->getLocation(), 11304 S.PDiag(diag::err_multiversion_diff)), 11305 /*TemplatesSupported=*/false, 11306 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind, 11307 /*CLinkageMayDiffer=*/false); 11308 } 11309 11310 /// Check the validity of a multiversion function declaration that is the 11311 /// first of its kind. Also sets the multiversion'ness' of the function itself. 11312 /// 11313 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11314 /// 11315 /// Returns true if there was an error, false otherwise. 11316 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) { 11317 MultiVersionKind MVKind = FD->getMultiVersionKind(); 11318 assert(MVKind != MultiVersionKind::None && 11319 "Function lacks multiversion attribute"); 11320 const auto *TA = FD->getAttr<TargetAttr>(); 11321 const auto *TVA = FD->getAttr<TargetVersionAttr>(); 11322 // Target and target_version only causes MV if it is default, otherwise this 11323 // is a normal function. 11324 if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion())) 11325 return false; 11326 11327 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) { 11328 FD->setInvalidDecl(); 11329 return true; 11330 } 11331 11332 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) { 11333 FD->setInvalidDecl(); 11334 return true; 11335 } 11336 11337 FD->setIsMultiVersion(); 11338 return false; 11339 } 11340 11341 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 11342 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 11343 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 11344 return true; 11345 } 11346 11347 return false; 11348 } 11349 11350 static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, 11351 FunctionDecl *NewFD, 11352 bool &Redeclaration, 11353 NamedDecl *&OldDecl, 11354 LookupResult &Previous) { 11355 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11356 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11357 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 11358 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>(); 11359 // If the old decl is NOT MultiVersioned yet, and we don't cause that 11360 // to change, this is a simple redeclaration. 11361 if ((NewTA && !NewTA->isDefaultVersion() && 11362 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) || 11363 (NewTVA && !NewTVA->isDefaultVersion() && 11364 (!OldTVA || OldTVA->getName() == NewTVA->getName()))) 11365 return false; 11366 11367 // Otherwise, this decl causes MultiVersioning. 11368 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 11369 NewTVA ? MultiVersionKind::TargetVersion 11370 : MultiVersionKind::Target)) { 11371 NewFD->setInvalidDecl(); 11372 return true; 11373 } 11374 11375 if (CheckMultiVersionValue(S, NewFD)) { 11376 NewFD->setInvalidDecl(); 11377 return true; 11378 } 11379 11380 // If this is 'default', permit the forward declaration. 11381 if (!OldFD->isMultiVersion() && 11382 ((NewTA && NewTA->isDefaultVersion() && !OldTA) || 11383 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) { 11384 Redeclaration = true; 11385 OldDecl = OldFD; 11386 OldFD->setIsMultiVersion(); 11387 NewFD->setIsMultiVersion(); 11388 return false; 11389 } 11390 11391 if (CheckMultiVersionValue(S, OldFD)) { 11392 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 11393 NewFD->setInvalidDecl(); 11394 return true; 11395 } 11396 11397 if (NewTA) { 11398 ParsedTargetAttr OldParsed = 11399 S.getASTContext().getTargetInfo().parseTargetAttr( 11400 OldTA->getFeaturesStr()); 11401 llvm::sort(OldParsed.Features); 11402 ParsedTargetAttr NewParsed = 11403 S.getASTContext().getTargetInfo().parseTargetAttr( 11404 NewTA->getFeaturesStr()); 11405 // Sort order doesn't matter, it just needs to be consistent. 11406 llvm::sort(NewParsed.Features); 11407 if (OldParsed == NewParsed) { 11408 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11409 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11410 NewFD->setInvalidDecl(); 11411 return true; 11412 } 11413 } 11414 11415 if (NewTVA) { 11416 llvm::SmallVector<StringRef, 8> Feats; 11417 OldTVA->getFeatures(Feats); 11418 llvm::sort(Feats); 11419 llvm::SmallVector<StringRef, 8> NewFeats; 11420 NewTVA->getFeatures(NewFeats); 11421 llvm::sort(NewFeats); 11422 11423 if (Feats == NewFeats) { 11424 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11425 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11426 NewFD->setInvalidDecl(); 11427 return true; 11428 } 11429 } 11430 11431 for (const auto *FD : OldFD->redecls()) { 11432 const auto *CurTA = FD->getAttr<TargetAttr>(); 11433 const auto *CurTVA = FD->getAttr<TargetVersionAttr>(); 11434 // We allow forward declarations before ANY multiversioning attributes, but 11435 // nothing after the fact. 11436 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 11437 ((NewTA && (!CurTA || CurTA->isInherited())) || 11438 (NewTVA && (!CurTVA || CurTVA->isInherited())))) { 11439 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 11440 << (NewTA ? 0 : 2); 11441 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 11442 NewFD->setInvalidDecl(); 11443 return true; 11444 } 11445 } 11446 11447 OldFD->setIsMultiVersion(); 11448 NewFD->setIsMultiVersion(); 11449 Redeclaration = false; 11450 OldDecl = nullptr; 11451 Previous.clear(); 11452 return false; 11453 } 11454 11455 static bool MultiVersionTypesCompatible(MultiVersionKind Old, 11456 MultiVersionKind New) { 11457 if (Old == New || Old == MultiVersionKind::None || 11458 New == MultiVersionKind::None) 11459 return true; 11460 11461 return (Old == MultiVersionKind::CPUDispatch && 11462 New == MultiVersionKind::CPUSpecific) || 11463 (Old == MultiVersionKind::CPUSpecific && 11464 New == MultiVersionKind::CPUDispatch); 11465 } 11466 11467 /// Check the validity of a new function declaration being added to an existing 11468 /// multiversioned declaration collection. 11469 static bool CheckMultiVersionAdditionalDecl( 11470 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 11471 MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp, 11472 const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, 11473 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) { 11474 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11475 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11476 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind(); 11477 // Disallow mixing of multiversioning types. 11478 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) { 11479 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 11480 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11481 NewFD->setInvalidDecl(); 11482 return true; 11483 } 11484 11485 ParsedTargetAttr NewParsed; 11486 if (NewTA) { 11487 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr( 11488 NewTA->getFeaturesStr()); 11489 llvm::sort(NewParsed.Features); 11490 } 11491 llvm::SmallVector<StringRef, 8> NewFeats; 11492 if (NewTVA) { 11493 NewTVA->getFeatures(NewFeats); 11494 llvm::sort(NewFeats); 11495 } 11496 11497 bool UseMemberUsingDeclRules = 11498 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 11499 11500 bool MayNeedOverloadableChecks = 11501 AllowOverloadingOfFunction(Previous, S.Context, NewFD); 11502 11503 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration 11504 // of a previous member of the MultiVersion set. 11505 for (NamedDecl *ND : Previous) { 11506 FunctionDecl *CurFD = ND->getAsFunction(); 11507 if (!CurFD || CurFD->isInvalidDecl()) 11508 continue; 11509 if (MayNeedOverloadableChecks && 11510 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 11511 continue; 11512 11513 if (NewMVKind == MultiVersionKind::None && 11514 OldMVKind == MultiVersionKind::TargetVersion) { 11515 NewFD->addAttr(TargetVersionAttr::CreateImplicit( 11516 S.Context, "default", NewFD->getSourceRange())); 11517 NewFD->setIsMultiVersion(); 11518 NewMVKind = MultiVersionKind::TargetVersion; 11519 if (!NewTVA) { 11520 NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11521 NewTVA->getFeatures(NewFeats); 11522 llvm::sort(NewFeats); 11523 } 11524 } 11525 11526 switch (NewMVKind) { 11527 case MultiVersionKind::None: 11528 assert(OldMVKind == MultiVersionKind::TargetClones && 11529 "Only target_clones can be omitted in subsequent declarations"); 11530 break; 11531 case MultiVersionKind::Target: { 11532 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 11533 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 11534 NewFD->setIsMultiVersion(); 11535 Redeclaration = true; 11536 OldDecl = ND; 11537 return false; 11538 } 11539 11540 ParsedTargetAttr CurParsed = 11541 S.getASTContext().getTargetInfo().parseTargetAttr( 11542 CurTA->getFeaturesStr()); 11543 llvm::sort(CurParsed.Features); 11544 if (CurParsed == NewParsed) { 11545 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11546 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11547 NewFD->setInvalidDecl(); 11548 return true; 11549 } 11550 break; 11551 } 11552 case MultiVersionKind::TargetVersion: { 11553 const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>(); 11554 if (CurTVA->getName() == NewTVA->getName()) { 11555 NewFD->setIsMultiVersion(); 11556 Redeclaration = true; 11557 OldDecl = ND; 11558 return false; 11559 } 11560 llvm::SmallVector<StringRef, 8> CurFeats; 11561 if (CurTVA) { 11562 CurTVA->getFeatures(CurFeats); 11563 llvm::sort(CurFeats); 11564 } 11565 if (CurFeats == NewFeats) { 11566 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11567 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11568 NewFD->setInvalidDecl(); 11569 return true; 11570 } 11571 break; 11572 } 11573 case MultiVersionKind::TargetClones: { 11574 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>(); 11575 Redeclaration = true; 11576 OldDecl = CurFD; 11577 NewFD->setIsMultiVersion(); 11578 11579 if (CurClones && NewClones && 11580 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || 11581 !std::equal(CurClones->featuresStrs_begin(), 11582 CurClones->featuresStrs_end(), 11583 NewClones->featuresStrs_begin()))) { 11584 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match); 11585 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11586 NewFD->setInvalidDecl(); 11587 return true; 11588 } 11589 11590 return false; 11591 } 11592 case MultiVersionKind::CPUSpecific: 11593 case MultiVersionKind::CPUDispatch: { 11594 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 11595 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 11596 // Handle CPUDispatch/CPUSpecific versions. 11597 // Only 1 CPUDispatch function is allowed, this will make it go through 11598 // the redeclaration errors. 11599 if (NewMVKind == MultiVersionKind::CPUDispatch && 11600 CurFD->hasAttr<CPUDispatchAttr>()) { 11601 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 11602 std::equal( 11603 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 11604 NewCPUDisp->cpus_begin(), 11605 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 11606 return Cur->getName() == New->getName(); 11607 })) { 11608 NewFD->setIsMultiVersion(); 11609 Redeclaration = true; 11610 OldDecl = ND; 11611 return false; 11612 } 11613 11614 // If the declarations don't match, this is an error condition. 11615 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 11616 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11617 NewFD->setInvalidDecl(); 11618 return true; 11619 } 11620 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) { 11621 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 11622 std::equal( 11623 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 11624 NewCPUSpec->cpus_begin(), 11625 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 11626 return Cur->getName() == New->getName(); 11627 })) { 11628 NewFD->setIsMultiVersion(); 11629 Redeclaration = true; 11630 OldDecl = ND; 11631 return false; 11632 } 11633 11634 // Only 1 version of CPUSpecific is allowed for each CPU. 11635 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 11636 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 11637 if (CurII == NewII) { 11638 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 11639 << NewII; 11640 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11641 NewFD->setInvalidDecl(); 11642 return true; 11643 } 11644 } 11645 } 11646 } 11647 break; 11648 } 11649 } 11650 } 11651 11652 // Else, this is simply a non-redecl case. Checking the 'value' is only 11653 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 11654 // handled in the attribute adding step. 11655 if ((NewMVKind == MultiVersionKind::TargetVersion || 11656 NewMVKind == MultiVersionKind::Target) && 11657 CheckMultiVersionValue(S, NewFD)) { 11658 NewFD->setInvalidDecl(); 11659 return true; 11660 } 11661 11662 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 11663 !OldFD->isMultiVersion(), NewMVKind)) { 11664 NewFD->setInvalidDecl(); 11665 return true; 11666 } 11667 11668 // Permit forward declarations in the case where these two are compatible. 11669 if (!OldFD->isMultiVersion()) { 11670 OldFD->setIsMultiVersion(); 11671 NewFD->setIsMultiVersion(); 11672 Redeclaration = true; 11673 OldDecl = OldFD; 11674 return false; 11675 } 11676 11677 NewFD->setIsMultiVersion(); 11678 Redeclaration = false; 11679 OldDecl = nullptr; 11680 Previous.clear(); 11681 return false; 11682 } 11683 11684 /// Check the validity of a mulitversion function declaration. 11685 /// Also sets the multiversion'ness' of the function itself. 11686 /// 11687 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11688 /// 11689 /// Returns true if there was an error, false otherwise. 11690 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 11691 bool &Redeclaration, NamedDecl *&OldDecl, 11692 LookupResult &Previous) { 11693 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11694 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11695 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 11696 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 11697 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); 11698 MultiVersionKind MVKind = NewFD->getMultiVersionKind(); 11699 11700 // Main isn't allowed to become a multiversion function, however it IS 11701 // permitted to have 'main' be marked with the 'target' optimization hint, 11702 // for 'target_version' only default is allowed. 11703 if (NewFD->isMain()) { 11704 if (MVKind != MultiVersionKind::None && 11705 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) && 11706 !(MVKind == MultiVersionKind::TargetVersion && 11707 NewTVA->isDefaultVersion())) { 11708 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 11709 NewFD->setInvalidDecl(); 11710 return true; 11711 } 11712 return false; 11713 } 11714 11715 // Target attribute on AArch64 is not used for multiversioning 11716 if (NewTA && S.getASTContext().getTargetInfo().getTriple().isAArch64()) 11717 return false; 11718 11719 if (!OldDecl || !OldDecl->getAsFunction() || 11720 OldDecl->getDeclContext()->getRedeclContext() != 11721 NewFD->getDeclContext()->getRedeclContext()) { 11722 // If there's no previous declaration, AND this isn't attempting to cause 11723 // multiversioning, this isn't an error condition. 11724 if (MVKind == MultiVersionKind::None) 11725 return false; 11726 return CheckMultiVersionFirstFunction(S, NewFD); 11727 } 11728 11729 FunctionDecl *OldFD = OldDecl->getAsFunction(); 11730 11731 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) { 11732 if (NewTVA || !OldFD->getAttr<TargetVersionAttr>()) 11733 return false; 11734 if (!NewFD->getType()->getAs<FunctionProtoType>()) { 11735 // Multiversion declaration doesn't have prototype. 11736 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 11737 NewFD->setInvalidDecl(); 11738 } else { 11739 // No "target_version" attribute is equivalent to "default" attribute. 11740 NewFD->addAttr(TargetVersionAttr::CreateImplicit( 11741 S.Context, "default", NewFD->getSourceRange())); 11742 NewFD->setIsMultiVersion(); 11743 OldFD->setIsMultiVersion(); 11744 OldDecl = OldFD; 11745 Redeclaration = true; 11746 } 11747 return true; 11748 } 11749 11750 // Multiversioned redeclarations aren't allowed to omit the attribute, except 11751 // for target_clones and target_version. 11752 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None && 11753 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones && 11754 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) { 11755 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 11756 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 11757 NewFD->setInvalidDecl(); 11758 return true; 11759 } 11760 11761 if (!OldFD->isMultiVersion()) { 11762 switch (MVKind) { 11763 case MultiVersionKind::Target: 11764 case MultiVersionKind::TargetVersion: 11765 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration, 11766 OldDecl, Previous); 11767 case MultiVersionKind::TargetClones: 11768 if (OldFD->isUsed(false)) { 11769 NewFD->setInvalidDecl(); 11770 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 11771 } 11772 OldFD->setIsMultiVersion(); 11773 break; 11774 11775 case MultiVersionKind::CPUDispatch: 11776 case MultiVersionKind::CPUSpecific: 11777 case MultiVersionKind::None: 11778 break; 11779 } 11780 } 11781 11782 // At this point, we have a multiversion function decl (in OldFD) AND an 11783 // appropriate attribute in the current function decl. Resolve that these are 11784 // still compatible with previous declarations. 11785 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp, 11786 NewCPUSpec, NewClones, Redeclaration, 11787 OldDecl, Previous); 11788 } 11789 11790 /// Perform semantic checking of a new function declaration. 11791 /// 11792 /// Performs semantic analysis of the new function declaration 11793 /// NewFD. This routine performs all semantic checking that does not 11794 /// require the actual declarator involved in the declaration, and is 11795 /// used both for the declaration of functions as they are parsed 11796 /// (called via ActOnDeclarator) and for the declaration of functions 11797 /// that have been instantiated via C++ template instantiation (called 11798 /// via InstantiateDecl). 11799 /// 11800 /// \param IsMemberSpecialization whether this new function declaration is 11801 /// a member specialization (that replaces any definition provided by the 11802 /// previous declaration). 11803 /// 11804 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11805 /// 11806 /// \returns true if the function declaration is a redeclaration. 11807 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 11808 LookupResult &Previous, 11809 bool IsMemberSpecialization, 11810 bool DeclIsDefn) { 11811 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 11812 "Variably modified return types are not handled here"); 11813 11814 // Determine whether the type of this function should be merged with 11815 // a previous visible declaration. This never happens for functions in C++, 11816 // and always happens in C if the previous declaration was visible. 11817 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 11818 !Previous.isShadowed(); 11819 11820 bool Redeclaration = false; 11821 NamedDecl *OldDecl = nullptr; 11822 bool MayNeedOverloadableChecks = false; 11823 11824 // Merge or overload the declaration with an existing declaration of 11825 // the same name, if appropriate. 11826 if (!Previous.empty()) { 11827 // Determine whether NewFD is an overload of PrevDecl or 11828 // a declaration that requires merging. If it's an overload, 11829 // there's no more work to do here; we'll just add the new 11830 // function to the scope. 11831 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 11832 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 11833 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 11834 Redeclaration = true; 11835 OldDecl = Candidate; 11836 } 11837 } else { 11838 MayNeedOverloadableChecks = true; 11839 switch (CheckOverload(S, NewFD, Previous, OldDecl, 11840 /*NewIsUsingDecl*/ false)) { 11841 case Ovl_Match: 11842 Redeclaration = true; 11843 break; 11844 11845 case Ovl_NonFunction: 11846 Redeclaration = true; 11847 break; 11848 11849 case Ovl_Overload: 11850 Redeclaration = false; 11851 break; 11852 } 11853 } 11854 } 11855 11856 // Check for a previous extern "C" declaration with this name. 11857 if (!Redeclaration && 11858 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 11859 if (!Previous.empty()) { 11860 // This is an extern "C" declaration with the same name as a previous 11861 // declaration, and thus redeclares that entity... 11862 Redeclaration = true; 11863 OldDecl = Previous.getFoundDecl(); 11864 MergeTypeWithPrevious = false; 11865 11866 // ... except in the presence of __attribute__((overloadable)). 11867 if (OldDecl->hasAttr<OverloadableAttr>() || 11868 NewFD->hasAttr<OverloadableAttr>()) { 11869 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 11870 MayNeedOverloadableChecks = true; 11871 Redeclaration = false; 11872 OldDecl = nullptr; 11873 } 11874 } 11875 } 11876 } 11877 11878 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous)) 11879 return Redeclaration; 11880 11881 // PPC MMA non-pointer types are not allowed as function return types. 11882 if (Context.getTargetInfo().getTriple().isPPC64() && 11883 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 11884 NewFD->setInvalidDecl(); 11885 } 11886 11887 // C++11 [dcl.constexpr]p8: 11888 // A constexpr specifier for a non-static member function that is not 11889 // a constructor declares that member function to be const. 11890 // 11891 // This needs to be delayed until we know whether this is an out-of-line 11892 // definition of a static member function. 11893 // 11894 // This rule is not present in C++1y, so we produce a backwards 11895 // compatibility warning whenever it happens in C++11. 11896 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 11897 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 11898 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 11899 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 11900 CXXMethodDecl *OldMD = nullptr; 11901 if (OldDecl) 11902 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 11903 if (!OldMD || !OldMD->isStatic()) { 11904 const FunctionProtoType *FPT = 11905 MD->getType()->castAs<FunctionProtoType>(); 11906 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11907 EPI.TypeQuals.addConst(); 11908 MD->setType(Context.getFunctionType(FPT->getReturnType(), 11909 FPT->getParamTypes(), EPI)); 11910 11911 // Warn that we did this, if we're not performing template instantiation. 11912 // In that case, we'll have warned already when the template was defined. 11913 if (!inTemplateInstantiation()) { 11914 SourceLocation AddConstLoc; 11915 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 11916 .IgnoreParens().getAs<FunctionTypeLoc>()) 11917 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 11918 11919 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 11920 << FixItHint::CreateInsertion(AddConstLoc, " const"); 11921 } 11922 } 11923 } 11924 11925 if (Redeclaration) { 11926 // NewFD and OldDecl represent declarations that need to be 11927 // merged. 11928 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious, 11929 DeclIsDefn)) { 11930 NewFD->setInvalidDecl(); 11931 return Redeclaration; 11932 } 11933 11934 Previous.clear(); 11935 Previous.addDecl(OldDecl); 11936 11937 if (FunctionTemplateDecl *OldTemplateDecl = 11938 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 11939 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 11940 FunctionTemplateDecl *NewTemplateDecl 11941 = NewFD->getDescribedFunctionTemplate(); 11942 assert(NewTemplateDecl && "Template/non-template mismatch"); 11943 11944 // The call to MergeFunctionDecl above may have created some state in 11945 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 11946 // can add it as a redeclaration. 11947 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 11948 11949 NewFD->setPreviousDeclaration(OldFD); 11950 if (NewFD->isCXXClassMember()) { 11951 NewFD->setAccess(OldTemplateDecl->getAccess()); 11952 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 11953 } 11954 11955 // If this is an explicit specialization of a member that is a function 11956 // template, mark it as a member specialization. 11957 if (IsMemberSpecialization && 11958 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 11959 NewTemplateDecl->setMemberSpecialization(); 11960 assert(OldTemplateDecl->isMemberSpecialization()); 11961 // Explicit specializations of a member template do not inherit deleted 11962 // status from the parent member template that they are specializing. 11963 if (OldFD->isDeleted()) { 11964 // FIXME: This assert will not hold in the presence of modules. 11965 assert(OldFD->getCanonicalDecl() == OldFD); 11966 // FIXME: We need an update record for this AST mutation. 11967 OldFD->setDeletedAsWritten(false); 11968 } 11969 } 11970 11971 } else { 11972 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 11973 auto *OldFD = cast<FunctionDecl>(OldDecl); 11974 // This needs to happen first so that 'inline' propagates. 11975 NewFD->setPreviousDeclaration(OldFD); 11976 if (NewFD->isCXXClassMember()) 11977 NewFD->setAccess(OldFD->getAccess()); 11978 } 11979 } 11980 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 11981 !NewFD->getAttr<OverloadableAttr>()) { 11982 assert((Previous.empty() || 11983 llvm::any_of(Previous, 11984 [](const NamedDecl *ND) { 11985 return ND->hasAttr<OverloadableAttr>(); 11986 })) && 11987 "Non-redecls shouldn't happen without overloadable present"); 11988 11989 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 11990 const auto *FD = dyn_cast<FunctionDecl>(ND); 11991 return FD && !FD->hasAttr<OverloadableAttr>(); 11992 }); 11993 11994 if (OtherUnmarkedIter != Previous.end()) { 11995 Diag(NewFD->getLocation(), 11996 diag::err_attribute_overloadable_multiple_unmarked_overloads); 11997 Diag((*OtherUnmarkedIter)->getLocation(), 11998 diag::note_attribute_overloadable_prev_overload) 11999 << false; 12000 12001 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 12002 } 12003 } 12004 12005 if (LangOpts.OpenMP) 12006 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 12007 12008 // Semantic checking for this function declaration (in isolation). 12009 12010 if (getLangOpts().CPlusPlus) { 12011 // C++-specific checks. 12012 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 12013 CheckConstructor(Constructor); 12014 } else if (CXXDestructorDecl *Destructor = 12015 dyn_cast<CXXDestructorDecl>(NewFD)) { 12016 // We check here for invalid destructor names. 12017 // If we have a friend destructor declaration that is dependent, we can't 12018 // diagnose right away because cases like this are still valid: 12019 // template <class T> struct A { friend T::X::~Y(); }; 12020 // struct B { struct Y { ~Y(); }; using X = Y; }; 12021 // template struct A<B>; 12022 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None || 12023 !Destructor->getFunctionObjectParameterType()->isDependentType()) { 12024 CXXRecordDecl *Record = Destructor->getParent(); 12025 QualType ClassType = Context.getTypeDeclType(Record); 12026 12027 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName( 12028 Context.getCanonicalType(ClassType)); 12029 if (NewFD->getDeclName() != Name) { 12030 Diag(NewFD->getLocation(), diag::err_destructor_name); 12031 NewFD->setInvalidDecl(); 12032 return Redeclaration; 12033 } 12034 } 12035 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 12036 if (auto *TD = Guide->getDescribedFunctionTemplate()) 12037 CheckDeductionGuideTemplate(TD); 12038 12039 // A deduction guide is not on the list of entities that can be 12040 // explicitly specialized. 12041 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 12042 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 12043 << /*explicit specialization*/ 1; 12044 } 12045 12046 // Find any virtual functions that this function overrides. 12047 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 12048 if (!Method->isFunctionTemplateSpecialization() && 12049 !Method->getDescribedFunctionTemplate() && 12050 Method->isCanonicalDecl()) { 12051 AddOverriddenMethods(Method->getParent(), Method); 12052 } 12053 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 12054 // C++2a [class.virtual]p6 12055 // A virtual method shall not have a requires-clause. 12056 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 12057 diag::err_constrained_virtual_method); 12058 12059 if (Method->isStatic()) 12060 checkThisInStaticMemberFunctionType(Method); 12061 } 12062 12063 // C++20: dcl.decl.general p4: 12064 // The optional requires-clause ([temp.pre]) in an init-declarator or 12065 // member-declarator shall be present only if the declarator declares a 12066 // templated function ([dcl.fct]). 12067 if (Expr *TRC = NewFD->getTrailingRequiresClause()) { 12068 // [temp.pre]/8: 12069 // An entity is templated if it is 12070 // - a template, 12071 // - an entity defined ([basic.def]) or created ([class.temporary]) in a 12072 // templated entity, 12073 // - a member of a templated entity, 12074 // - an enumerator for an enumeration that is a templated entity, or 12075 // - the closure type of a lambda-expression ([expr.prim.lambda.closure]) 12076 // appearing in the declaration of a templated entity. [Note 6: A local 12077 // class, a local or block variable, or a friend function defined in a 12078 // templated entity is a templated entity. — end note] 12079 // 12080 // A templated function is a function template or a function that is 12081 // templated. A templated class is a class template or a class that is 12082 // templated. A templated variable is a variable template or a variable 12083 // that is templated. 12084 12085 if (!NewFD->getDescribedFunctionTemplate() && // -a template 12086 // defined... in a templated entity 12087 !(DeclIsDefn && NewFD->isTemplated()) && 12088 // a member of a templated entity 12089 !(isa<CXXMethodDecl>(NewFD) && NewFD->isTemplated()) && 12090 // Don't complain about instantiations, they've already had these 12091 // rules + others enforced. 12092 !NewFD->isTemplateInstantiation()) { 12093 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function); 12094 } 12095 } 12096 12097 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 12098 ActOnConversionDeclarator(Conversion); 12099 12100 // Extra checking for C++ overloaded operators (C++ [over.oper]). 12101 if (NewFD->isOverloadedOperator() && 12102 CheckOverloadedOperatorDeclaration(NewFD)) { 12103 NewFD->setInvalidDecl(); 12104 return Redeclaration; 12105 } 12106 12107 // Extra checking for C++0x literal operators (C++0x [over.literal]). 12108 if (NewFD->getLiteralIdentifier() && 12109 CheckLiteralOperatorDeclaration(NewFD)) { 12110 NewFD->setInvalidDecl(); 12111 return Redeclaration; 12112 } 12113 12114 // In C++, check default arguments now that we have merged decls. Unless 12115 // the lexical context is the class, because in this case this is done 12116 // during delayed parsing anyway. 12117 if (!CurContext->isRecord()) 12118 CheckCXXDefaultArguments(NewFD); 12119 12120 // If this function is declared as being extern "C", then check to see if 12121 // the function returns a UDT (class, struct, or union type) that is not C 12122 // compatible, and if it does, warn the user. 12123 // But, issue any diagnostic on the first declaration only. 12124 if (Previous.empty() && NewFD->isExternC()) { 12125 QualType R = NewFD->getReturnType(); 12126 if (R->isIncompleteType() && !R->isVoidType()) 12127 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 12128 << NewFD << R; 12129 else if (!R.isPODType(Context) && !R->isVoidType() && 12130 !R->isObjCObjectPointerType()) 12131 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 12132 } 12133 12134 // C++1z [dcl.fct]p6: 12135 // [...] whether the function has a non-throwing exception-specification 12136 // [is] part of the function type 12137 // 12138 // This results in an ABI break between C++14 and C++17 for functions whose 12139 // declared type includes an exception-specification in a parameter or 12140 // return type. (Exception specifications on the function itself are OK in 12141 // most cases, and exception specifications are not permitted in most other 12142 // contexts where they could make it into a mangling.) 12143 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 12144 auto HasNoexcept = [&](QualType T) -> bool { 12145 // Strip off declarator chunks that could be between us and a function 12146 // type. We don't need to look far, exception specifications are very 12147 // restricted prior to C++17. 12148 if (auto *RT = T->getAs<ReferenceType>()) 12149 T = RT->getPointeeType(); 12150 else if (T->isAnyPointerType()) 12151 T = T->getPointeeType(); 12152 else if (auto *MPT = T->getAs<MemberPointerType>()) 12153 T = MPT->getPointeeType(); 12154 if (auto *FPT = T->getAs<FunctionProtoType>()) 12155 if (FPT->isNothrow()) 12156 return true; 12157 return false; 12158 }; 12159 12160 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 12161 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 12162 for (QualType T : FPT->param_types()) 12163 AnyNoexcept |= HasNoexcept(T); 12164 if (AnyNoexcept) 12165 Diag(NewFD->getLocation(), 12166 diag::warn_cxx17_compat_exception_spec_in_signature) 12167 << NewFD; 12168 } 12169 12170 if (!Redeclaration && LangOpts.CUDA) 12171 checkCUDATargetOverload(NewFD, Previous); 12172 } 12173 12174 // Check if the function definition uses any AArch64 SME features without 12175 // having the '+sme' feature enabled. 12176 if (DeclIsDefn) { 12177 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>(); 12178 bool UsesZA = NewFD->hasAttr<ArmNewZAAttr>(); 12179 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) { 12180 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12181 UsesSM |= 12182 EPI.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask; 12183 UsesZA |= EPI.AArch64SMEAttributes & FunctionType::SME_PStateZASharedMask; 12184 } 12185 12186 if (UsesSM || UsesZA) { 12187 llvm::StringMap<bool> FeatureMap; 12188 Context.getFunctionFeatureMap(FeatureMap, NewFD); 12189 if (!FeatureMap.contains("sme")) { 12190 if (UsesSM) 12191 Diag(NewFD->getLocation(), 12192 diag::err_sme_definition_using_sm_in_non_sme_target); 12193 else 12194 Diag(NewFD->getLocation(), 12195 diag::err_sme_definition_using_za_in_non_sme_target); 12196 } 12197 } 12198 } 12199 12200 return Redeclaration; 12201 } 12202 12203 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 12204 // C++11 [basic.start.main]p3: 12205 // A program that [...] declares main to be inline, static or 12206 // constexpr is ill-formed. 12207 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 12208 // appear in a declaration of main. 12209 // static main is not an error under C99, but we should warn about it. 12210 // We accept _Noreturn main as an extension. 12211 if (FD->getStorageClass() == SC_Static) 12212 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 12213 ? diag::err_static_main : diag::warn_static_main) 12214 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 12215 if (FD->isInlineSpecified()) 12216 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 12217 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 12218 if (DS.isNoreturnSpecified()) { 12219 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 12220 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 12221 Diag(NoreturnLoc, diag::ext_noreturn_main); 12222 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 12223 << FixItHint::CreateRemoval(NoreturnRange); 12224 } 12225 if (FD->isConstexpr()) { 12226 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 12227 << FD->isConsteval() 12228 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 12229 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 12230 } 12231 12232 if (getLangOpts().OpenCL) { 12233 Diag(FD->getLocation(), diag::err_opencl_no_main) 12234 << FD->hasAttr<OpenCLKernelAttr>(); 12235 FD->setInvalidDecl(); 12236 return; 12237 } 12238 12239 // Functions named main in hlsl are default entries, but don't have specific 12240 // signatures they are required to conform to. 12241 if (getLangOpts().HLSL) 12242 return; 12243 12244 QualType T = FD->getType(); 12245 assert(T->isFunctionType() && "function decl is not of function type"); 12246 const FunctionType* FT = T->castAs<FunctionType>(); 12247 12248 // Set default calling convention for main() 12249 if (FT->getCallConv() != CC_C) { 12250 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 12251 FD->setType(QualType(FT, 0)); 12252 T = Context.getCanonicalType(FD->getType()); 12253 } 12254 12255 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 12256 // In C with GNU extensions we allow main() to have non-integer return 12257 // type, but we should warn about the extension, and we disable the 12258 // implicit-return-zero rule. 12259 12260 // GCC in C mode accepts qualified 'int'. 12261 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 12262 FD->setHasImplicitReturnZero(true); 12263 else { 12264 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 12265 SourceRange RTRange = FD->getReturnTypeSourceRange(); 12266 if (RTRange.isValid()) 12267 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 12268 << FixItHint::CreateReplacement(RTRange, "int"); 12269 } 12270 } else { 12271 // In C and C++, main magically returns 0 if you fall off the end; 12272 // set the flag which tells us that. 12273 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 12274 12275 // All the standards say that main() should return 'int'. 12276 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 12277 FD->setHasImplicitReturnZero(true); 12278 else { 12279 // Otherwise, this is just a flat-out error. 12280 SourceRange RTRange = FD->getReturnTypeSourceRange(); 12281 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 12282 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 12283 : FixItHint()); 12284 FD->setInvalidDecl(true); 12285 } 12286 } 12287 12288 // Treat protoless main() as nullary. 12289 if (isa<FunctionNoProtoType>(FT)) return; 12290 12291 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 12292 unsigned nparams = FTP->getNumParams(); 12293 assert(FD->getNumParams() == nparams); 12294 12295 bool HasExtraParameters = (nparams > 3); 12296 12297 if (FTP->isVariadic()) { 12298 Diag(FD->getLocation(), diag::ext_variadic_main); 12299 // FIXME: if we had information about the location of the ellipsis, we 12300 // could add a FixIt hint to remove it as a parameter. 12301 } 12302 12303 // Darwin passes an undocumented fourth argument of type char**. If 12304 // other platforms start sprouting these, the logic below will start 12305 // getting shifty. 12306 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 12307 HasExtraParameters = false; 12308 12309 if (HasExtraParameters) { 12310 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 12311 FD->setInvalidDecl(true); 12312 nparams = 3; 12313 } 12314 12315 // FIXME: a lot of the following diagnostics would be improved 12316 // if we had some location information about types. 12317 12318 QualType CharPP = 12319 Context.getPointerType(Context.getPointerType(Context.CharTy)); 12320 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 12321 12322 for (unsigned i = 0; i < nparams; ++i) { 12323 QualType AT = FTP->getParamType(i); 12324 12325 bool mismatch = true; 12326 12327 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 12328 mismatch = false; 12329 else if (Expected[i] == CharPP) { 12330 // As an extension, the following forms are okay: 12331 // char const ** 12332 // char const * const * 12333 // char * const * 12334 12335 QualifierCollector qs; 12336 const PointerType* PT; 12337 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 12338 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 12339 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 12340 Context.CharTy)) { 12341 qs.removeConst(); 12342 mismatch = !qs.empty(); 12343 } 12344 } 12345 12346 if (mismatch) { 12347 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 12348 // TODO: suggest replacing given type with expected type 12349 FD->setInvalidDecl(true); 12350 } 12351 } 12352 12353 if (nparams == 1 && !FD->isInvalidDecl()) { 12354 Diag(FD->getLocation(), diag::warn_main_one_arg); 12355 } 12356 12357 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 12358 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 12359 FD->setInvalidDecl(); 12360 } 12361 } 12362 12363 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 12364 12365 // Default calling convention for main and wmain is __cdecl 12366 if (FD->getName() == "main" || FD->getName() == "wmain") 12367 return false; 12368 12369 // Default calling convention for MinGW is __cdecl 12370 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 12371 if (T.isWindowsGNUEnvironment()) 12372 return false; 12373 12374 // Default calling convention for WinMain, wWinMain and DllMain 12375 // is __stdcall on 32 bit Windows 12376 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 12377 return true; 12378 12379 return false; 12380 } 12381 12382 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 12383 QualType T = FD->getType(); 12384 assert(T->isFunctionType() && "function decl is not of function type"); 12385 const FunctionType *FT = T->castAs<FunctionType>(); 12386 12387 // Set an implicit return of 'zero' if the function can return some integral, 12388 // enumeration, pointer or nullptr type. 12389 if (FT->getReturnType()->isIntegralOrEnumerationType() || 12390 FT->getReturnType()->isAnyPointerType() || 12391 FT->getReturnType()->isNullPtrType()) 12392 // DllMain is exempt because a return value of zero means it failed. 12393 if (FD->getName() != "DllMain") 12394 FD->setHasImplicitReturnZero(true); 12395 12396 // Explicity specified calling conventions are applied to MSVC entry points 12397 if (!hasExplicitCallingConv(T)) { 12398 if (isDefaultStdCall(FD, *this)) { 12399 if (FT->getCallConv() != CC_X86StdCall) { 12400 FT = Context.adjustFunctionType( 12401 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 12402 FD->setType(QualType(FT, 0)); 12403 } 12404 } else if (FT->getCallConv() != CC_C) { 12405 FT = Context.adjustFunctionType(FT, 12406 FT->getExtInfo().withCallingConv(CC_C)); 12407 FD->setType(QualType(FT, 0)); 12408 } 12409 } 12410 12411 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 12412 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 12413 FD->setInvalidDecl(); 12414 } 12415 } 12416 12417 void Sema::ActOnHLSLTopLevelFunction(FunctionDecl *FD) { 12418 auto &TargetInfo = getASTContext().getTargetInfo(); 12419 12420 if (FD->getName() != TargetInfo.getTargetOpts().HLSLEntry) 12421 return; 12422 12423 StringRef Env = TargetInfo.getTriple().getEnvironmentName(); 12424 HLSLShaderAttr::ShaderType ShaderType; 12425 if (HLSLShaderAttr::ConvertStrToShaderType(Env, ShaderType)) { 12426 if (const auto *Shader = FD->getAttr<HLSLShaderAttr>()) { 12427 // The entry point is already annotated - check that it matches the 12428 // triple. 12429 if (Shader->getType() != ShaderType) { 12430 Diag(Shader->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch) 12431 << Shader; 12432 FD->setInvalidDecl(); 12433 } 12434 } else { 12435 // Implicitly add the shader attribute if the entry function isn't 12436 // explicitly annotated. 12437 FD->addAttr(HLSLShaderAttr::CreateImplicit(Context, ShaderType, 12438 FD->getBeginLoc())); 12439 } 12440 } else { 12441 switch (TargetInfo.getTriple().getEnvironment()) { 12442 case llvm::Triple::UnknownEnvironment: 12443 case llvm::Triple::Library: 12444 break; 12445 default: 12446 llvm_unreachable("Unhandled environment in triple"); 12447 } 12448 } 12449 } 12450 12451 void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) { 12452 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>(); 12453 assert(ShaderAttr && "Entry point has no shader attribute"); 12454 HLSLShaderAttr::ShaderType ST = ShaderAttr->getType(); 12455 12456 switch (ST) { 12457 case HLSLShaderAttr::Pixel: 12458 case HLSLShaderAttr::Vertex: 12459 case HLSLShaderAttr::Geometry: 12460 case HLSLShaderAttr::Hull: 12461 case HLSLShaderAttr::Domain: 12462 case HLSLShaderAttr::RayGeneration: 12463 case HLSLShaderAttr::Intersection: 12464 case HLSLShaderAttr::AnyHit: 12465 case HLSLShaderAttr::ClosestHit: 12466 case HLSLShaderAttr::Miss: 12467 case HLSLShaderAttr::Callable: 12468 if (const auto *NT = FD->getAttr<HLSLNumThreadsAttr>()) { 12469 DiagnoseHLSLAttrStageMismatch(NT, ST, 12470 {HLSLShaderAttr::Compute, 12471 HLSLShaderAttr::Amplification, 12472 HLSLShaderAttr::Mesh}); 12473 FD->setInvalidDecl(); 12474 } 12475 break; 12476 12477 case HLSLShaderAttr::Compute: 12478 case HLSLShaderAttr::Amplification: 12479 case HLSLShaderAttr::Mesh: 12480 if (!FD->hasAttr<HLSLNumThreadsAttr>()) { 12481 Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads) 12482 << HLSLShaderAttr::ConvertShaderTypeToStr(ST); 12483 FD->setInvalidDecl(); 12484 } 12485 break; 12486 } 12487 12488 for (ParmVarDecl *Param : FD->parameters()) { 12489 if (const auto *AnnotationAttr = Param->getAttr<HLSLAnnotationAttr>()) { 12490 CheckHLSLSemanticAnnotation(FD, Param, AnnotationAttr); 12491 } else { 12492 // FIXME: Handle struct parameters where annotations are on struct fields. 12493 // See: https://github.com/llvm/llvm-project/issues/57875 12494 Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation); 12495 Diag(Param->getLocation(), diag::note_previous_decl) << Param; 12496 FD->setInvalidDecl(); 12497 } 12498 } 12499 // FIXME: Verify return type semantic annotation. 12500 } 12501 12502 void Sema::CheckHLSLSemanticAnnotation( 12503 FunctionDecl *EntryPoint, const Decl *Param, 12504 const HLSLAnnotationAttr *AnnotationAttr) { 12505 auto *ShaderAttr = EntryPoint->getAttr<HLSLShaderAttr>(); 12506 assert(ShaderAttr && "Entry point has no shader attribute"); 12507 HLSLShaderAttr::ShaderType ST = ShaderAttr->getType(); 12508 12509 switch (AnnotationAttr->getKind()) { 12510 case attr::HLSLSV_DispatchThreadID: 12511 case attr::HLSLSV_GroupIndex: 12512 if (ST == HLSLShaderAttr::Compute) 12513 return; 12514 DiagnoseHLSLAttrStageMismatch(AnnotationAttr, ST, 12515 {HLSLShaderAttr::Compute}); 12516 break; 12517 default: 12518 llvm_unreachable("Unknown HLSLAnnotationAttr"); 12519 } 12520 } 12521 12522 void Sema::DiagnoseHLSLAttrStageMismatch( 12523 const Attr *A, HLSLShaderAttr::ShaderType Stage, 12524 std::initializer_list<HLSLShaderAttr::ShaderType> AllowedStages) { 12525 SmallVector<StringRef, 8> StageStrings; 12526 llvm::transform(AllowedStages, std::back_inserter(StageStrings), 12527 [](HLSLShaderAttr::ShaderType ST) { 12528 return StringRef( 12529 HLSLShaderAttr::ConvertShaderTypeToStr(ST)); 12530 }); 12531 Diag(A->getLoc(), diag::err_hlsl_attr_unsupported_in_stage) 12532 << A << HLSLShaderAttr::ConvertShaderTypeToStr(Stage) 12533 << (AllowedStages.size() != 1) << join(StageStrings, ", "); 12534 } 12535 12536 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 12537 // FIXME: Need strict checking. In C89, we need to check for 12538 // any assignment, increment, decrement, function-calls, or 12539 // commas outside of a sizeof. In C99, it's the same list, 12540 // except that the aforementioned are allowed in unevaluated 12541 // expressions. Everything else falls under the 12542 // "may accept other forms of constant expressions" exception. 12543 // 12544 // Regular C++ code will not end up here (exceptions: language extensions, 12545 // OpenCL C++ etc), so the constant expression rules there don't matter. 12546 if (Init->isValueDependent()) { 12547 assert(Init->containsErrors() && 12548 "Dependent code should only occur in error-recovery path."); 12549 return true; 12550 } 12551 const Expr *Culprit; 12552 if (Init->isConstantInitializer(Context, false, &Culprit)) 12553 return false; 12554 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 12555 << Culprit->getSourceRange(); 12556 return true; 12557 } 12558 12559 namespace { 12560 // Visits an initialization expression to see if OrigDecl is evaluated in 12561 // its own initialization and throws a warning if it does. 12562 class SelfReferenceChecker 12563 : public EvaluatedExprVisitor<SelfReferenceChecker> { 12564 Sema &S; 12565 Decl *OrigDecl; 12566 bool isRecordType; 12567 bool isPODType; 12568 bool isReferenceType; 12569 12570 bool isInitList; 12571 llvm::SmallVector<unsigned, 4> InitFieldIndex; 12572 12573 public: 12574 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 12575 12576 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 12577 S(S), OrigDecl(OrigDecl) { 12578 isPODType = false; 12579 isRecordType = false; 12580 isReferenceType = false; 12581 isInitList = false; 12582 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 12583 isPODType = VD->getType().isPODType(S.Context); 12584 isRecordType = VD->getType()->isRecordType(); 12585 isReferenceType = VD->getType()->isReferenceType(); 12586 } 12587 } 12588 12589 // For most expressions, just call the visitor. For initializer lists, 12590 // track the index of the field being initialized since fields are 12591 // initialized in order allowing use of previously initialized fields. 12592 void CheckExpr(Expr *E) { 12593 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 12594 if (!InitList) { 12595 Visit(E); 12596 return; 12597 } 12598 12599 // Track and increment the index here. 12600 isInitList = true; 12601 InitFieldIndex.push_back(0); 12602 for (auto *Child : InitList->children()) { 12603 CheckExpr(cast<Expr>(Child)); 12604 ++InitFieldIndex.back(); 12605 } 12606 InitFieldIndex.pop_back(); 12607 } 12608 12609 // Returns true if MemberExpr is checked and no further checking is needed. 12610 // Returns false if additional checking is required. 12611 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 12612 llvm::SmallVector<FieldDecl*, 4> Fields; 12613 Expr *Base = E; 12614 bool ReferenceField = false; 12615 12616 // Get the field members used. 12617 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 12618 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 12619 if (!FD) 12620 return false; 12621 Fields.push_back(FD); 12622 if (FD->getType()->isReferenceType()) 12623 ReferenceField = true; 12624 Base = ME->getBase()->IgnoreParenImpCasts(); 12625 } 12626 12627 // Keep checking only if the base Decl is the same. 12628 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 12629 if (!DRE || DRE->getDecl() != OrigDecl) 12630 return false; 12631 12632 // A reference field can be bound to an unininitialized field. 12633 if (CheckReference && !ReferenceField) 12634 return true; 12635 12636 // Convert FieldDecls to their index number. 12637 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 12638 for (const FieldDecl *I : llvm::reverse(Fields)) 12639 UsedFieldIndex.push_back(I->getFieldIndex()); 12640 12641 // See if a warning is needed by checking the first difference in index 12642 // numbers. If field being used has index less than the field being 12643 // initialized, then the use is safe. 12644 for (auto UsedIter = UsedFieldIndex.begin(), 12645 UsedEnd = UsedFieldIndex.end(), 12646 OrigIter = InitFieldIndex.begin(), 12647 OrigEnd = InitFieldIndex.end(); 12648 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 12649 if (*UsedIter < *OrigIter) 12650 return true; 12651 if (*UsedIter > *OrigIter) 12652 break; 12653 } 12654 12655 // TODO: Add a different warning which will print the field names. 12656 HandleDeclRefExpr(DRE); 12657 return true; 12658 } 12659 12660 // For most expressions, the cast is directly above the DeclRefExpr. 12661 // For conditional operators, the cast can be outside the conditional 12662 // operator if both expressions are DeclRefExpr's. 12663 void HandleValue(Expr *E) { 12664 E = E->IgnoreParens(); 12665 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 12666 HandleDeclRefExpr(DRE); 12667 return; 12668 } 12669 12670 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 12671 Visit(CO->getCond()); 12672 HandleValue(CO->getTrueExpr()); 12673 HandleValue(CO->getFalseExpr()); 12674 return; 12675 } 12676 12677 if (BinaryConditionalOperator *BCO = 12678 dyn_cast<BinaryConditionalOperator>(E)) { 12679 Visit(BCO->getCond()); 12680 HandleValue(BCO->getFalseExpr()); 12681 return; 12682 } 12683 12684 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 12685 HandleValue(OVE->getSourceExpr()); 12686 return; 12687 } 12688 12689 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12690 if (BO->getOpcode() == BO_Comma) { 12691 Visit(BO->getLHS()); 12692 HandleValue(BO->getRHS()); 12693 return; 12694 } 12695 } 12696 12697 if (isa<MemberExpr>(E)) { 12698 if (isInitList) { 12699 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 12700 false /*CheckReference*/)) 12701 return; 12702 } 12703 12704 Expr *Base = E->IgnoreParenImpCasts(); 12705 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 12706 // Check for static member variables and don't warn on them. 12707 if (!isa<FieldDecl>(ME->getMemberDecl())) 12708 return; 12709 Base = ME->getBase()->IgnoreParenImpCasts(); 12710 } 12711 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 12712 HandleDeclRefExpr(DRE); 12713 return; 12714 } 12715 12716 Visit(E); 12717 } 12718 12719 // Reference types not handled in HandleValue are handled here since all 12720 // uses of references are bad, not just r-value uses. 12721 void VisitDeclRefExpr(DeclRefExpr *E) { 12722 if (isReferenceType) 12723 HandleDeclRefExpr(E); 12724 } 12725 12726 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12727 if (E->getCastKind() == CK_LValueToRValue) { 12728 HandleValue(E->getSubExpr()); 12729 return; 12730 } 12731 12732 Inherited::VisitImplicitCastExpr(E); 12733 } 12734 12735 void VisitMemberExpr(MemberExpr *E) { 12736 if (isInitList) { 12737 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 12738 return; 12739 } 12740 12741 // Don't warn on arrays since they can be treated as pointers. 12742 if (E->getType()->canDecayToPointerType()) return; 12743 12744 // Warn when a non-static method call is followed by non-static member 12745 // field accesses, which is followed by a DeclRefExpr. 12746 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 12747 bool Warn = (MD && !MD->isStatic()); 12748 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 12749 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 12750 if (!isa<FieldDecl>(ME->getMemberDecl())) 12751 Warn = false; 12752 Base = ME->getBase()->IgnoreParenImpCasts(); 12753 } 12754 12755 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 12756 if (Warn) 12757 HandleDeclRefExpr(DRE); 12758 return; 12759 } 12760 12761 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 12762 // Visit that expression. 12763 Visit(Base); 12764 } 12765 12766 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 12767 Expr *Callee = E->getCallee(); 12768 12769 if (isa<UnresolvedLookupExpr>(Callee)) 12770 return Inherited::VisitCXXOperatorCallExpr(E); 12771 12772 Visit(Callee); 12773 for (auto Arg: E->arguments()) 12774 HandleValue(Arg->IgnoreParenImpCasts()); 12775 } 12776 12777 void VisitUnaryOperator(UnaryOperator *E) { 12778 // For POD record types, addresses of its own members are well-defined. 12779 if (E->getOpcode() == UO_AddrOf && isRecordType && 12780 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 12781 if (!isPODType) 12782 HandleValue(E->getSubExpr()); 12783 return; 12784 } 12785 12786 if (E->isIncrementDecrementOp()) { 12787 HandleValue(E->getSubExpr()); 12788 return; 12789 } 12790 12791 Inherited::VisitUnaryOperator(E); 12792 } 12793 12794 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 12795 12796 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12797 if (E->getConstructor()->isCopyConstructor()) { 12798 Expr *ArgExpr = E->getArg(0); 12799 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 12800 if (ILE->getNumInits() == 1) 12801 ArgExpr = ILE->getInit(0); 12802 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 12803 if (ICE->getCastKind() == CK_NoOp) 12804 ArgExpr = ICE->getSubExpr(); 12805 HandleValue(ArgExpr); 12806 return; 12807 } 12808 Inherited::VisitCXXConstructExpr(E); 12809 } 12810 12811 void VisitCallExpr(CallExpr *E) { 12812 // Treat std::move as a use. 12813 if (E->isCallToStdMove()) { 12814 HandleValue(E->getArg(0)); 12815 return; 12816 } 12817 12818 Inherited::VisitCallExpr(E); 12819 } 12820 12821 void VisitBinaryOperator(BinaryOperator *E) { 12822 if (E->isCompoundAssignmentOp()) { 12823 HandleValue(E->getLHS()); 12824 Visit(E->getRHS()); 12825 return; 12826 } 12827 12828 Inherited::VisitBinaryOperator(E); 12829 } 12830 12831 // A custom visitor for BinaryConditionalOperator is needed because the 12832 // regular visitor would check the condition and true expression separately 12833 // but both point to the same place giving duplicate diagnostics. 12834 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 12835 Visit(E->getCond()); 12836 Visit(E->getFalseExpr()); 12837 } 12838 12839 void HandleDeclRefExpr(DeclRefExpr *DRE) { 12840 Decl* ReferenceDecl = DRE->getDecl(); 12841 if (OrigDecl != ReferenceDecl) return; 12842 unsigned diag; 12843 if (isReferenceType) { 12844 diag = diag::warn_uninit_self_reference_in_reference_init; 12845 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 12846 diag = diag::warn_static_self_reference_in_init; 12847 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 12848 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 12849 DRE->getDecl()->getType()->isRecordType()) { 12850 diag = diag::warn_uninit_self_reference_in_init; 12851 } else { 12852 // Local variables will be handled by the CFG analysis. 12853 return; 12854 } 12855 12856 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 12857 S.PDiag(diag) 12858 << DRE->getDecl() << OrigDecl->getLocation() 12859 << DRE->getSourceRange()); 12860 } 12861 }; 12862 12863 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 12864 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 12865 bool DirectInit) { 12866 // Parameters arguments are occassionially constructed with itself, 12867 // for instance, in recursive functions. Skip them. 12868 if (isa<ParmVarDecl>(OrigDecl)) 12869 return; 12870 12871 E = E->IgnoreParens(); 12872 12873 // Skip checking T a = a where T is not a record or reference type. 12874 // Doing so is a way to silence uninitialized warnings. 12875 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 12876 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 12877 if (ICE->getCastKind() == CK_LValueToRValue) 12878 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 12879 if (DRE->getDecl() == OrigDecl) 12880 return; 12881 12882 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 12883 } 12884 } // end anonymous namespace 12885 12886 namespace { 12887 // Simple wrapper to add the name of a variable or (if no variable is 12888 // available) a DeclarationName into a diagnostic. 12889 struct VarDeclOrName { 12890 VarDecl *VDecl; 12891 DeclarationName Name; 12892 12893 friend const Sema::SemaDiagnosticBuilder & 12894 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 12895 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 12896 } 12897 }; 12898 } // end anonymous namespace 12899 12900 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 12901 DeclarationName Name, QualType Type, 12902 TypeSourceInfo *TSI, 12903 SourceRange Range, bool DirectInit, 12904 Expr *Init) { 12905 bool IsInitCapture = !VDecl; 12906 assert((!VDecl || !VDecl->isInitCapture()) && 12907 "init captures are expected to be deduced prior to initialization"); 12908 12909 VarDeclOrName VN{VDecl, Name}; 12910 12911 DeducedType *Deduced = Type->getContainedDeducedType(); 12912 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 12913 12914 // Diagnose auto array declarations in C23, unless it's a supported extension. 12915 if (getLangOpts().C23 && Type->isArrayType() && 12916 !isa_and_present<StringLiteral, InitListExpr>(Init)) { 12917 Diag(Range.getBegin(), diag::err_auto_not_allowed) 12918 << (int)Deduced->getContainedAutoType()->getKeyword() 12919 << /*in array decl*/ 23 << Range; 12920 return QualType(); 12921 } 12922 12923 // C++11 [dcl.spec.auto]p3 12924 if (!Init) { 12925 assert(VDecl && "no init for init capture deduction?"); 12926 12927 // Except for class argument deduction, and then for an initializing 12928 // declaration only, i.e. no static at class scope or extern. 12929 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 12930 VDecl->hasExternalStorage() || 12931 VDecl->isStaticDataMember()) { 12932 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 12933 << VDecl->getDeclName() << Type; 12934 return QualType(); 12935 } 12936 } 12937 12938 ArrayRef<Expr*> DeduceInits; 12939 if (Init) 12940 DeduceInits = Init; 12941 12942 auto *PL = dyn_cast_if_present<ParenListExpr>(Init); 12943 if (DirectInit && PL) 12944 DeduceInits = PL->exprs(); 12945 12946 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 12947 assert(VDecl && "non-auto type for init capture deduction?"); 12948 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12949 InitializationKind Kind = InitializationKind::CreateForInit( 12950 VDecl->getLocation(), DirectInit, Init); 12951 // FIXME: Initialization should not be taking a mutable list of inits. 12952 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 12953 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 12954 InitsCopy); 12955 } 12956 12957 if (DirectInit) { 12958 if (auto *IL = dyn_cast<InitListExpr>(Init)) 12959 DeduceInits = IL->inits(); 12960 } 12961 12962 // Deduction only works if we have exactly one source expression. 12963 if (DeduceInits.empty()) { 12964 // It isn't possible to write this directly, but it is possible to 12965 // end up in this situation with "auto x(some_pack...);" 12966 Diag(Init->getBeginLoc(), IsInitCapture 12967 ? diag::err_init_capture_no_expression 12968 : diag::err_auto_var_init_no_expression) 12969 << VN << Type << Range; 12970 return QualType(); 12971 } 12972 12973 if (DeduceInits.size() > 1) { 12974 Diag(DeduceInits[1]->getBeginLoc(), 12975 IsInitCapture ? diag::err_init_capture_multiple_expressions 12976 : diag::err_auto_var_init_multiple_expressions) 12977 << VN << Type << Range; 12978 return QualType(); 12979 } 12980 12981 Expr *DeduceInit = DeduceInits[0]; 12982 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 12983 Diag(Init->getBeginLoc(), IsInitCapture 12984 ? diag::err_init_capture_paren_braces 12985 : diag::err_auto_var_init_paren_braces) 12986 << isa<InitListExpr>(Init) << VN << Type << Range; 12987 return QualType(); 12988 } 12989 12990 // Expressions default to 'id' when we're in a debugger. 12991 bool DefaultedAnyToId = false; 12992 if (getLangOpts().DebuggerCastResultToId && 12993 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 12994 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12995 if (Result.isInvalid()) { 12996 return QualType(); 12997 } 12998 Init = Result.get(); 12999 DefaultedAnyToId = true; 13000 } 13001 13002 // C++ [dcl.decomp]p1: 13003 // If the assignment-expression [...] has array type A and no ref-qualifier 13004 // is present, e has type cv A 13005 if (VDecl && isa<DecompositionDecl>(VDecl) && 13006 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 13007 DeduceInit->getType()->isConstantArrayType()) 13008 return Context.getQualifiedType(DeduceInit->getType(), 13009 Type.getQualifiers()); 13010 13011 QualType DeducedType; 13012 TemplateDeductionInfo Info(DeduceInit->getExprLoc()); 13013 TemplateDeductionResult Result = 13014 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info); 13015 if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) { 13016 if (!IsInitCapture) 13017 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 13018 else if (isa<InitListExpr>(Init)) 13019 Diag(Range.getBegin(), 13020 diag::err_init_capture_deduction_failure_from_init_list) 13021 << VN 13022 << (DeduceInit->getType().isNull() ? TSI->getType() 13023 : DeduceInit->getType()) 13024 << DeduceInit->getSourceRange(); 13025 else 13026 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 13027 << VN << TSI->getType() 13028 << (DeduceInit->getType().isNull() ? TSI->getType() 13029 : DeduceInit->getType()) 13030 << DeduceInit->getSourceRange(); 13031 } 13032 13033 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 13034 // 'id' instead of a specific object type prevents most of our usual 13035 // checks. 13036 // We only want to warn outside of template instantiations, though: 13037 // inside a template, the 'id' could have come from a parameter. 13038 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 13039 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 13040 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 13041 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 13042 } 13043 13044 return DeducedType; 13045 } 13046 13047 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 13048 Expr *Init) { 13049 assert(!Init || !Init->containsErrors()); 13050 QualType DeducedType = deduceVarTypeFromInitializer( 13051 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 13052 VDecl->getSourceRange(), DirectInit, Init); 13053 if (DeducedType.isNull()) { 13054 VDecl->setInvalidDecl(); 13055 return true; 13056 } 13057 13058 VDecl->setType(DeducedType); 13059 assert(VDecl->isLinkageValid()); 13060 13061 // In ARC, infer lifetime. 13062 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 13063 VDecl->setInvalidDecl(); 13064 13065 if (getLangOpts().OpenCL) 13066 deduceOpenCLAddressSpace(VDecl); 13067 13068 // If this is a redeclaration, check that the type we just deduced matches 13069 // the previously declared type. 13070 if (VarDecl *Old = VDecl->getPreviousDecl()) { 13071 // We never need to merge the type, because we cannot form an incomplete 13072 // array of auto, nor deduce such a type. 13073 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 13074 } 13075 13076 // Check the deduced type is valid for a variable declaration. 13077 CheckVariableDeclarationType(VDecl); 13078 return VDecl->isInvalidDecl(); 13079 } 13080 13081 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 13082 SourceLocation Loc) { 13083 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 13084 Init = EWC->getSubExpr(); 13085 13086 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 13087 Init = CE->getSubExpr(); 13088 13089 QualType InitType = Init->getType(); 13090 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 13091 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 13092 "shouldn't be called if type doesn't have a non-trivial C struct"); 13093 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 13094 for (auto *I : ILE->inits()) { 13095 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 13096 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13097 continue; 13098 SourceLocation SL = I->getExprLoc(); 13099 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 13100 } 13101 return; 13102 } 13103 13104 if (isa<ImplicitValueInitExpr>(Init)) { 13105 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 13106 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 13107 NTCUK_Init); 13108 } else { 13109 // Assume all other explicit initializers involving copying some existing 13110 // object. 13111 // TODO: ignore any explicit initializers where we can guarantee 13112 // copy-elision. 13113 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 13114 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 13115 } 13116 } 13117 13118 namespace { 13119 13120 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 13121 // Ignore unavailable fields. A field can be marked as unavailable explicitly 13122 // in the source code or implicitly by the compiler if it is in a union 13123 // defined in a system header and has non-trivial ObjC ownership 13124 // qualifications. We don't want those fields to participate in determining 13125 // whether the containing union is non-trivial. 13126 return FD->hasAttr<UnavailableAttr>(); 13127 } 13128 13129 struct DiagNonTrivalCUnionDefaultInitializeVisitor 13130 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 13131 void> { 13132 using Super = 13133 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 13134 void>; 13135 13136 DiagNonTrivalCUnionDefaultInitializeVisitor( 13137 QualType OrigTy, SourceLocation OrigLoc, 13138 Sema::NonTrivialCUnionContext UseContext, Sema &S) 13139 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 13140 13141 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 13142 const FieldDecl *FD, bool InNonTrivialUnion) { 13143 if (const auto *AT = S.Context.getAsArrayType(QT)) 13144 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 13145 InNonTrivialUnion); 13146 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 13147 } 13148 13149 void visitARCStrong(QualType QT, const FieldDecl *FD, 13150 bool InNonTrivialUnion) { 13151 if (InNonTrivialUnion) 13152 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13153 << 1 << 0 << QT << FD->getName(); 13154 } 13155 13156 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13157 if (InNonTrivialUnion) 13158 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13159 << 1 << 0 << QT << FD->getName(); 13160 } 13161 13162 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13163 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 13164 if (RD->isUnion()) { 13165 if (OrigLoc.isValid()) { 13166 bool IsUnion = false; 13167 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 13168 IsUnion = OrigRD->isUnion(); 13169 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 13170 << 0 << OrigTy << IsUnion << UseContext; 13171 // Reset OrigLoc so that this diagnostic is emitted only once. 13172 OrigLoc = SourceLocation(); 13173 } 13174 InNonTrivialUnion = true; 13175 } 13176 13177 if (InNonTrivialUnion) 13178 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 13179 << 0 << 0 << QT.getUnqualifiedType() << ""; 13180 13181 for (const FieldDecl *FD : RD->fields()) 13182 if (!shouldIgnoreForRecordTriviality(FD)) 13183 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 13184 } 13185 13186 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 13187 13188 // The non-trivial C union type or the struct/union type that contains a 13189 // non-trivial C union. 13190 QualType OrigTy; 13191 SourceLocation OrigLoc; 13192 Sema::NonTrivialCUnionContext UseContext; 13193 Sema &S; 13194 }; 13195 13196 struct DiagNonTrivalCUnionDestructedTypeVisitor 13197 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 13198 using Super = 13199 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 13200 13201 DiagNonTrivalCUnionDestructedTypeVisitor( 13202 QualType OrigTy, SourceLocation OrigLoc, 13203 Sema::NonTrivialCUnionContext UseContext, Sema &S) 13204 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 13205 13206 void visitWithKind(QualType::DestructionKind DK, QualType QT, 13207 const FieldDecl *FD, bool InNonTrivialUnion) { 13208 if (const auto *AT = S.Context.getAsArrayType(QT)) 13209 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 13210 InNonTrivialUnion); 13211 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 13212 } 13213 13214 void visitARCStrong(QualType QT, const FieldDecl *FD, 13215 bool InNonTrivialUnion) { 13216 if (InNonTrivialUnion) 13217 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13218 << 1 << 1 << QT << FD->getName(); 13219 } 13220 13221 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13222 if (InNonTrivialUnion) 13223 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13224 << 1 << 1 << QT << FD->getName(); 13225 } 13226 13227 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13228 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 13229 if (RD->isUnion()) { 13230 if (OrigLoc.isValid()) { 13231 bool IsUnion = false; 13232 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 13233 IsUnion = OrigRD->isUnion(); 13234 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 13235 << 1 << OrigTy << IsUnion << UseContext; 13236 // Reset OrigLoc so that this diagnostic is emitted only once. 13237 OrigLoc = SourceLocation(); 13238 } 13239 InNonTrivialUnion = true; 13240 } 13241 13242 if (InNonTrivialUnion) 13243 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 13244 << 0 << 1 << QT.getUnqualifiedType() << ""; 13245 13246 for (const FieldDecl *FD : RD->fields()) 13247 if (!shouldIgnoreForRecordTriviality(FD)) 13248 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 13249 } 13250 13251 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 13252 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 13253 bool InNonTrivialUnion) {} 13254 13255 // The non-trivial C union type or the struct/union type that contains a 13256 // non-trivial C union. 13257 QualType OrigTy; 13258 SourceLocation OrigLoc; 13259 Sema::NonTrivialCUnionContext UseContext; 13260 Sema &S; 13261 }; 13262 13263 struct DiagNonTrivalCUnionCopyVisitor 13264 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 13265 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 13266 13267 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 13268 Sema::NonTrivialCUnionContext UseContext, 13269 Sema &S) 13270 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 13271 13272 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 13273 const FieldDecl *FD, bool InNonTrivialUnion) { 13274 if (const auto *AT = S.Context.getAsArrayType(QT)) 13275 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 13276 InNonTrivialUnion); 13277 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 13278 } 13279 13280 void visitARCStrong(QualType QT, const FieldDecl *FD, 13281 bool InNonTrivialUnion) { 13282 if (InNonTrivialUnion) 13283 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13284 << 1 << 2 << QT << FD->getName(); 13285 } 13286 13287 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13288 if (InNonTrivialUnion) 13289 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13290 << 1 << 2 << QT << FD->getName(); 13291 } 13292 13293 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13294 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 13295 if (RD->isUnion()) { 13296 if (OrigLoc.isValid()) { 13297 bool IsUnion = false; 13298 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 13299 IsUnion = OrigRD->isUnion(); 13300 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 13301 << 2 << OrigTy << IsUnion << UseContext; 13302 // Reset OrigLoc so that this diagnostic is emitted only once. 13303 OrigLoc = SourceLocation(); 13304 } 13305 InNonTrivialUnion = true; 13306 } 13307 13308 if (InNonTrivialUnion) 13309 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 13310 << 0 << 2 << QT.getUnqualifiedType() << ""; 13311 13312 for (const FieldDecl *FD : RD->fields()) 13313 if (!shouldIgnoreForRecordTriviality(FD)) 13314 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 13315 } 13316 13317 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 13318 const FieldDecl *FD, bool InNonTrivialUnion) {} 13319 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 13320 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 13321 bool InNonTrivialUnion) {} 13322 13323 // The non-trivial C union type or the struct/union type that contains a 13324 // non-trivial C union. 13325 QualType OrigTy; 13326 SourceLocation OrigLoc; 13327 Sema::NonTrivialCUnionContext UseContext; 13328 Sema &S; 13329 }; 13330 13331 } // namespace 13332 13333 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 13334 NonTrivialCUnionContext UseContext, 13335 unsigned NonTrivialKind) { 13336 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 13337 QT.hasNonTrivialToPrimitiveDestructCUnion() || 13338 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 13339 "shouldn't be called if type doesn't have a non-trivial C union"); 13340 13341 if ((NonTrivialKind & NTCUK_Init) && 13342 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 13343 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 13344 .visit(QT, nullptr, false); 13345 if ((NonTrivialKind & NTCUK_Destruct) && 13346 QT.hasNonTrivialToPrimitiveDestructCUnion()) 13347 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 13348 .visit(QT, nullptr, false); 13349 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 13350 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 13351 .visit(QT, nullptr, false); 13352 } 13353 13354 /// AddInitializerToDecl - Adds the initializer Init to the 13355 /// declaration dcl. If DirectInit is true, this is C++ direct 13356 /// initialization rather than copy initialization. 13357 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 13358 // If there is no declaration, there was an error parsing it. Just ignore 13359 // the initializer. 13360 if (!RealDecl || RealDecl->isInvalidDecl()) { 13361 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 13362 return; 13363 } 13364 13365 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 13366 // Pure-specifiers are handled in ActOnPureSpecifier. 13367 Diag(Method->getLocation(), diag::err_member_function_initialization) 13368 << Method->getDeclName() << Init->getSourceRange(); 13369 Method->setInvalidDecl(); 13370 return; 13371 } 13372 13373 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 13374 if (!VDecl) { 13375 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 13376 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 13377 RealDecl->setInvalidDecl(); 13378 return; 13379 } 13380 13381 // WebAssembly tables can't be used to initialise a variable. 13382 if (Init && !Init->getType().isNull() && 13383 Init->getType()->isWebAssemblyTableType()) { 13384 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0; 13385 VDecl->setInvalidDecl(); 13386 return; 13387 } 13388 13389 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 13390 if (VDecl->getType()->isUndeducedType()) { 13391 // Attempt typo correction early so that the type of the init expression can 13392 // be deduced based on the chosen correction if the original init contains a 13393 // TypoExpr. 13394 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 13395 if (!Res.isUsable()) { 13396 // There are unresolved typos in Init, just drop them. 13397 // FIXME: improve the recovery strategy to preserve the Init. 13398 RealDecl->setInvalidDecl(); 13399 return; 13400 } 13401 if (Res.get()->containsErrors()) { 13402 // Invalidate the decl as we don't know the type for recovery-expr yet. 13403 RealDecl->setInvalidDecl(); 13404 VDecl->setInit(Res.get()); 13405 return; 13406 } 13407 Init = Res.get(); 13408 13409 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 13410 return; 13411 } 13412 13413 // dllimport cannot be used on variable definitions. 13414 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 13415 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 13416 VDecl->setInvalidDecl(); 13417 return; 13418 } 13419 13420 // C99 6.7.8p5. If the declaration of an identifier has block scope, and 13421 // the identifier has external or internal linkage, the declaration shall 13422 // have no initializer for the identifier. 13423 // C++14 [dcl.init]p5 is the same restriction for C++. 13424 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 13425 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 13426 VDecl->setInvalidDecl(); 13427 return; 13428 } 13429 13430 if (!VDecl->getType()->isDependentType()) { 13431 // A definition must end up with a complete type, which means it must be 13432 // complete with the restriction that an array type might be completed by 13433 // the initializer; note that later code assumes this restriction. 13434 QualType BaseDeclType = VDecl->getType(); 13435 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 13436 BaseDeclType = Array->getElementType(); 13437 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 13438 diag::err_typecheck_decl_incomplete_type)) { 13439 RealDecl->setInvalidDecl(); 13440 return; 13441 } 13442 13443 // The variable can not have an abstract class type. 13444 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 13445 diag::err_abstract_type_in_decl, 13446 AbstractVariableType)) 13447 VDecl->setInvalidDecl(); 13448 } 13449 13450 // C++ [module.import/6] external definitions are not permitted in header 13451 // units. 13452 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() && 13453 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() && 13454 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() && 13455 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl)) { 13456 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit); 13457 VDecl->setInvalidDecl(); 13458 } 13459 13460 // If adding the initializer will turn this declaration into a definition, 13461 // and we already have a definition for this variable, diagnose or otherwise 13462 // handle the situation. 13463 if (VarDecl *Def = VDecl->getDefinition()) 13464 if (Def != VDecl && 13465 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 13466 !VDecl->isThisDeclarationADemotedDefinition() && 13467 checkVarDeclRedefinition(Def, VDecl)) 13468 return; 13469 13470 if (getLangOpts().CPlusPlus) { 13471 // C++ [class.static.data]p4 13472 // If a static data member is of const integral or const 13473 // enumeration type, its declaration in the class definition can 13474 // specify a constant-initializer which shall be an integral 13475 // constant expression (5.19). In that case, the member can appear 13476 // in integral constant expressions. The member shall still be 13477 // defined in a namespace scope if it is used in the program and the 13478 // namespace scope definition shall not contain an initializer. 13479 // 13480 // We already performed a redefinition check above, but for static 13481 // data members we also need to check whether there was an in-class 13482 // declaration with an initializer. 13483 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 13484 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 13485 << VDecl->getDeclName(); 13486 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 13487 diag::note_previous_initializer) 13488 << 0; 13489 return; 13490 } 13491 13492 if (VDecl->hasLocalStorage()) 13493 setFunctionHasBranchProtectedScope(); 13494 13495 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 13496 VDecl->setInvalidDecl(); 13497 return; 13498 } 13499 } 13500 13501 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 13502 // a kernel function cannot be initialized." 13503 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 13504 Diag(VDecl->getLocation(), diag::err_local_cant_init); 13505 VDecl->setInvalidDecl(); 13506 return; 13507 } 13508 13509 // The LoaderUninitialized attribute acts as a definition (of undef). 13510 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 13511 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 13512 VDecl->setInvalidDecl(); 13513 return; 13514 } 13515 13516 // Get the decls type and save a reference for later, since 13517 // CheckInitializerTypes may change it. 13518 QualType DclT = VDecl->getType(), SavT = DclT; 13519 13520 // Expressions default to 'id' when we're in a debugger 13521 // and we are assigning it to a variable of Objective-C pointer type. 13522 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 13523 Init->getType() == Context.UnknownAnyTy) { 13524 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 13525 if (Result.isInvalid()) { 13526 VDecl->setInvalidDecl(); 13527 return; 13528 } 13529 Init = Result.get(); 13530 } 13531 13532 // Perform the initialization. 13533 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 13534 bool IsParenListInit = false; 13535 if (!VDecl->isInvalidDecl()) { 13536 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 13537 InitializationKind Kind = InitializationKind::CreateForInit( 13538 VDecl->getLocation(), DirectInit, Init); 13539 13540 MultiExprArg Args = Init; 13541 if (CXXDirectInit) 13542 Args = MultiExprArg(CXXDirectInit->getExprs(), 13543 CXXDirectInit->getNumExprs()); 13544 13545 // Try to correct any TypoExprs in the initialization arguments. 13546 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 13547 ExprResult Res = CorrectDelayedTyposInExpr( 13548 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 13549 [this, Entity, Kind](Expr *E) { 13550 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 13551 return Init.Failed() ? ExprError() : E; 13552 }); 13553 if (Res.isInvalid()) { 13554 VDecl->setInvalidDecl(); 13555 } else if (Res.get() != Args[Idx]) { 13556 Args[Idx] = Res.get(); 13557 } 13558 } 13559 if (VDecl->isInvalidDecl()) 13560 return; 13561 13562 InitializationSequence InitSeq(*this, Entity, Kind, Args, 13563 /*TopLevelOfInitList=*/false, 13564 /*TreatUnavailableAsInvalid=*/false); 13565 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 13566 if (Result.isInvalid()) { 13567 // If the provided initializer fails to initialize the var decl, 13568 // we attach a recovery expr for better recovery. 13569 auto RecoveryExpr = 13570 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 13571 if (RecoveryExpr.get()) 13572 VDecl->setInit(RecoveryExpr.get()); 13573 return; 13574 } 13575 13576 Init = Result.getAs<Expr>(); 13577 IsParenListInit = !InitSeq.steps().empty() && 13578 InitSeq.step_begin()->Kind == 13579 InitializationSequence::SK_ParenthesizedListInit; 13580 QualType VDeclType = VDecl->getType(); 13581 if (Init && !Init->getType().isNull() && 13582 !Init->getType()->isDependentType() && !VDeclType->isDependentType() && 13583 Context.getAsIncompleteArrayType(VDeclType) && 13584 Context.getAsIncompleteArrayType(Init->getType())) { 13585 // Bail out if it is not possible to deduce array size from the 13586 // initializer. 13587 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type) 13588 << VDeclType; 13589 VDecl->setInvalidDecl(); 13590 return; 13591 } 13592 } 13593 13594 // Check for self-references within variable initializers. 13595 // Variables declared within a function/method body (except for references) 13596 // are handled by a dataflow analysis. 13597 // This is undefined behavior in C++, but valid in C. 13598 if (getLangOpts().CPlusPlus) 13599 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 13600 VDecl->getType()->isReferenceType()) 13601 CheckSelfReference(*this, RealDecl, Init, DirectInit); 13602 13603 // If the type changed, it means we had an incomplete type that was 13604 // completed by the initializer. For example: 13605 // int ary[] = { 1, 3, 5 }; 13606 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 13607 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 13608 VDecl->setType(DclT); 13609 13610 if (!VDecl->isInvalidDecl()) { 13611 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 13612 13613 if (VDecl->hasAttr<BlocksAttr>()) 13614 checkRetainCycles(VDecl, Init); 13615 13616 // It is safe to assign a weak reference into a strong variable. 13617 // Although this code can still have problems: 13618 // id x = self.weakProp; 13619 // id y = self.weakProp; 13620 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13621 // paths through the function. This should be revisited if 13622 // -Wrepeated-use-of-weak is made flow-sensitive. 13623 if (FunctionScopeInfo *FSI = getCurFunction()) 13624 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 13625 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 13626 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13627 Init->getBeginLoc())) 13628 FSI->markSafeWeakUse(Init); 13629 } 13630 13631 // The initialization is usually a full-expression. 13632 // 13633 // FIXME: If this is a braced initialization of an aggregate, it is not 13634 // an expression, and each individual field initializer is a separate 13635 // full-expression. For instance, in: 13636 // 13637 // struct Temp { ~Temp(); }; 13638 // struct S { S(Temp); }; 13639 // struct T { S a, b; } t = { Temp(), Temp() } 13640 // 13641 // we should destroy the first Temp before constructing the second. 13642 ExprResult Result = 13643 ActOnFinishFullExpr(Init, VDecl->getLocation(), 13644 /*DiscardedValue*/ false, VDecl->isConstexpr()); 13645 if (Result.isInvalid()) { 13646 VDecl->setInvalidDecl(); 13647 return; 13648 } 13649 Init = Result.get(); 13650 13651 // Attach the initializer to the decl. 13652 VDecl->setInit(Init); 13653 13654 if (VDecl->isLocalVarDecl()) { 13655 // Don't check the initializer if the declaration is malformed. 13656 if (VDecl->isInvalidDecl()) { 13657 // do nothing 13658 13659 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 13660 // This is true even in C++ for OpenCL. 13661 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 13662 CheckForConstantInitializer(Init, DclT); 13663 13664 // Otherwise, C++ does not restrict the initializer. 13665 } else if (getLangOpts().CPlusPlus) { 13666 // do nothing 13667 13668 // C99 6.7.8p4: All the expressions in an initializer for an object that has 13669 // static storage duration shall be constant expressions or string literals. 13670 } else if (VDecl->getStorageClass() == SC_Static) { 13671 CheckForConstantInitializer(Init, DclT); 13672 13673 // C89 is stricter than C99 for aggregate initializers. 13674 // C89 6.5.7p3: All the expressions [...] in an initializer list 13675 // for an object that has aggregate or union type shall be 13676 // constant expressions. 13677 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 13678 isa<InitListExpr>(Init)) { 13679 const Expr *Culprit; 13680 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 13681 Diag(Culprit->getExprLoc(), 13682 diag::ext_aggregate_init_not_constant) 13683 << Culprit->getSourceRange(); 13684 } 13685 } 13686 13687 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 13688 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 13689 if (VDecl->hasLocalStorage()) 13690 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13691 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 13692 VDecl->getLexicalDeclContext()->isRecord()) { 13693 // This is an in-class initialization for a static data member, e.g., 13694 // 13695 // struct S { 13696 // static const int value = 17; 13697 // }; 13698 13699 // C++ [class.mem]p4: 13700 // A member-declarator can contain a constant-initializer only 13701 // if it declares a static member (9.4) of const integral or 13702 // const enumeration type, see 9.4.2. 13703 // 13704 // C++11 [class.static.data]p3: 13705 // If a non-volatile non-inline const static data member is of integral 13706 // or enumeration type, its declaration in the class definition can 13707 // specify a brace-or-equal-initializer in which every initializer-clause 13708 // that is an assignment-expression is a constant expression. A static 13709 // data member of literal type can be declared in the class definition 13710 // with the constexpr specifier; if so, its declaration shall specify a 13711 // brace-or-equal-initializer in which every initializer-clause that is 13712 // an assignment-expression is a constant expression. 13713 13714 // Do nothing on dependent types. 13715 if (DclT->isDependentType()) { 13716 13717 // Allow any 'static constexpr' members, whether or not they are of literal 13718 // type. We separately check that every constexpr variable is of literal 13719 // type. 13720 } else if (VDecl->isConstexpr()) { 13721 13722 // Require constness. 13723 } else if (!DclT.isConstQualified()) { 13724 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 13725 << Init->getSourceRange(); 13726 VDecl->setInvalidDecl(); 13727 13728 // We allow integer constant expressions in all cases. 13729 } else if (DclT->isIntegralOrEnumerationType()) { 13730 // Check whether the expression is a constant expression. 13731 SourceLocation Loc; 13732 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 13733 // In C++11, a non-constexpr const static data member with an 13734 // in-class initializer cannot be volatile. 13735 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 13736 else if (Init->isValueDependent()) 13737 ; // Nothing to check. 13738 else if (Init->isIntegerConstantExpr(Context, &Loc)) 13739 ; // Ok, it's an ICE! 13740 else if (Init->getType()->isScopedEnumeralType() && 13741 Init->isCXX11ConstantExpr(Context)) 13742 ; // Ok, it is a scoped-enum constant expression. 13743 else if (Init->isEvaluatable(Context)) { 13744 // If we can constant fold the initializer through heroics, accept it, 13745 // but report this as a use of an extension for -pedantic. 13746 Diag(Loc, diag::ext_in_class_initializer_non_constant) 13747 << Init->getSourceRange(); 13748 } else { 13749 // Otherwise, this is some crazy unknown case. Report the issue at the 13750 // location provided by the isIntegerConstantExpr failed check. 13751 Diag(Loc, diag::err_in_class_initializer_non_constant) 13752 << Init->getSourceRange(); 13753 VDecl->setInvalidDecl(); 13754 } 13755 13756 // We allow foldable floating-point constants as an extension. 13757 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 13758 // In C++98, this is a GNU extension. In C++11, it is not, but we support 13759 // it anyway and provide a fixit to add the 'constexpr'. 13760 if (getLangOpts().CPlusPlus11) { 13761 Diag(VDecl->getLocation(), 13762 diag::ext_in_class_initializer_float_type_cxx11) 13763 << DclT << Init->getSourceRange(); 13764 Diag(VDecl->getBeginLoc(), 13765 diag::note_in_class_initializer_float_type_cxx11) 13766 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 13767 } else { 13768 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 13769 << DclT << Init->getSourceRange(); 13770 13771 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 13772 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 13773 << Init->getSourceRange(); 13774 VDecl->setInvalidDecl(); 13775 } 13776 } 13777 13778 // Suggest adding 'constexpr' in C++11 for literal types. 13779 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 13780 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 13781 << DclT << Init->getSourceRange() 13782 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 13783 VDecl->setConstexpr(true); 13784 13785 } else { 13786 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 13787 << DclT << Init->getSourceRange(); 13788 VDecl->setInvalidDecl(); 13789 } 13790 } else if (VDecl->isFileVarDecl()) { 13791 // In C, extern is typically used to avoid tentative definitions when 13792 // declaring variables in headers, but adding an intializer makes it a 13793 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 13794 // In C++, extern is often used to give implictly static const variables 13795 // external linkage, so don't warn in that case. If selectany is present, 13796 // this might be header code intended for C and C++ inclusion, so apply the 13797 // C++ rules. 13798 if (VDecl->getStorageClass() == SC_Extern && 13799 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 13800 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 13801 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 13802 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 13803 Diag(VDecl->getLocation(), diag::warn_extern_init); 13804 13805 // In Microsoft C++ mode, a const variable defined in namespace scope has 13806 // external linkage by default if the variable is declared with 13807 // __declspec(dllexport). 13808 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 13809 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 13810 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 13811 VDecl->setStorageClass(SC_Extern); 13812 13813 // C99 6.7.8p4. All file scoped initializers need to be constant. 13814 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 13815 CheckForConstantInitializer(Init, DclT); 13816 } 13817 13818 QualType InitType = Init->getType(); 13819 if (!InitType.isNull() && 13820 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 13821 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 13822 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 13823 13824 // We will represent direct-initialization similarly to copy-initialization: 13825 // int x(1); -as-> int x = 1; 13826 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 13827 // 13828 // Clients that want to distinguish between the two forms, can check for 13829 // direct initializer using VarDecl::getInitStyle(). 13830 // A major benefit is that clients that don't particularly care about which 13831 // exactly form was it (like the CodeGen) can handle both cases without 13832 // special case code. 13833 13834 // C++ 8.5p11: 13835 // The form of initialization (using parentheses or '=') is generally 13836 // insignificant, but does matter when the entity being initialized has a 13837 // class type. 13838 if (CXXDirectInit) { 13839 assert(DirectInit && "Call-style initializer must be direct init."); 13840 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit 13841 : VarDecl::CallInit); 13842 } else if (DirectInit) { 13843 // This must be list-initialization. No other way is direct-initialization. 13844 VDecl->setInitStyle(VarDecl::ListInit); 13845 } 13846 13847 if (LangOpts.OpenMP && 13848 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) && 13849 VDecl->isFileVarDecl()) 13850 DeclsToCheckForDeferredDiags.insert(VDecl); 13851 CheckCompleteVariableDeclaration(VDecl); 13852 } 13853 13854 /// ActOnInitializerError - Given that there was an error parsing an 13855 /// initializer for the given declaration, try to at least re-establish 13856 /// invariants such as whether a variable's type is either dependent or 13857 /// complete. 13858 void Sema::ActOnInitializerError(Decl *D) { 13859 // Our main concern here is re-establishing invariants like "a 13860 // variable's type is either dependent or complete". 13861 if (!D || D->isInvalidDecl()) return; 13862 13863 VarDecl *VD = dyn_cast<VarDecl>(D); 13864 if (!VD) return; 13865 13866 // Bindings are not usable if we can't make sense of the initializer. 13867 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 13868 for (auto *BD : DD->bindings()) 13869 BD->setInvalidDecl(); 13870 13871 // Auto types are meaningless if we can't make sense of the initializer. 13872 if (VD->getType()->isUndeducedType()) { 13873 D->setInvalidDecl(); 13874 return; 13875 } 13876 13877 QualType Ty = VD->getType(); 13878 if (Ty->isDependentType()) return; 13879 13880 // Require a complete type. 13881 if (RequireCompleteType(VD->getLocation(), 13882 Context.getBaseElementType(Ty), 13883 diag::err_typecheck_decl_incomplete_type)) { 13884 VD->setInvalidDecl(); 13885 return; 13886 } 13887 13888 // Require a non-abstract type. 13889 if (RequireNonAbstractType(VD->getLocation(), Ty, 13890 diag::err_abstract_type_in_decl, 13891 AbstractVariableType)) { 13892 VD->setInvalidDecl(); 13893 return; 13894 } 13895 13896 // Don't bother complaining about constructors or destructors, 13897 // though. 13898 } 13899 13900 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 13901 // If there is no declaration, there was an error parsing it. Just ignore it. 13902 if (!RealDecl) 13903 return; 13904 13905 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 13906 QualType Type = Var->getType(); 13907 13908 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 13909 if (isa<DecompositionDecl>(RealDecl)) { 13910 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 13911 Var->setInvalidDecl(); 13912 return; 13913 } 13914 13915 if (Type->isUndeducedType() && 13916 DeduceVariableDeclarationType(Var, false, nullptr)) 13917 return; 13918 13919 // C++11 [class.static.data]p3: A static data member can be declared with 13920 // the constexpr specifier; if so, its declaration shall specify 13921 // a brace-or-equal-initializer. 13922 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 13923 // the definition of a variable [...] or the declaration of a static data 13924 // member. 13925 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 13926 !Var->isThisDeclarationADemotedDefinition()) { 13927 if (Var->isStaticDataMember()) { 13928 // C++1z removes the relevant rule; the in-class declaration is always 13929 // a definition there. 13930 if (!getLangOpts().CPlusPlus17 && 13931 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13932 Diag(Var->getLocation(), 13933 diag::err_constexpr_static_mem_var_requires_init) 13934 << Var; 13935 Var->setInvalidDecl(); 13936 return; 13937 } 13938 } else { 13939 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 13940 Var->setInvalidDecl(); 13941 return; 13942 } 13943 } 13944 13945 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 13946 // be initialized. 13947 if (!Var->isInvalidDecl() && 13948 Var->getType().getAddressSpace() == LangAS::opencl_constant && 13949 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 13950 bool HasConstExprDefaultConstructor = false; 13951 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 13952 for (auto *Ctor : RD->ctors()) { 13953 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 13954 Ctor->getMethodQualifiers().getAddressSpace() == 13955 LangAS::opencl_constant) { 13956 HasConstExprDefaultConstructor = true; 13957 } 13958 } 13959 } 13960 if (!HasConstExprDefaultConstructor) { 13961 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 13962 Var->setInvalidDecl(); 13963 return; 13964 } 13965 } 13966 13967 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 13968 if (Var->getStorageClass() == SC_Extern) { 13969 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 13970 << Var; 13971 Var->setInvalidDecl(); 13972 return; 13973 } 13974 if (RequireCompleteType(Var->getLocation(), Var->getType(), 13975 diag::err_typecheck_decl_incomplete_type)) { 13976 Var->setInvalidDecl(); 13977 return; 13978 } 13979 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 13980 if (!RD->hasTrivialDefaultConstructor()) { 13981 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 13982 Var->setInvalidDecl(); 13983 return; 13984 } 13985 } 13986 // The declaration is unitialized, no need for further checks. 13987 return; 13988 } 13989 13990 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 13991 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 13992 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 13993 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 13994 NTCUC_DefaultInitializedObject, NTCUK_Init); 13995 13996 13997 switch (DefKind) { 13998 case VarDecl::Definition: 13999 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 14000 break; 14001 14002 // We have an out-of-line definition of a static data member 14003 // that has an in-class initializer, so we type-check this like 14004 // a declaration. 14005 // 14006 [[fallthrough]]; 14007 14008 case VarDecl::DeclarationOnly: 14009 // It's only a declaration. 14010 14011 // Block scope. C99 6.7p7: If an identifier for an object is 14012 // declared with no linkage (C99 6.2.2p6), the type for the 14013 // object shall be complete. 14014 if (!Type->isDependentType() && Var->isLocalVarDecl() && 14015 !Var->hasLinkage() && !Var->isInvalidDecl() && 14016 RequireCompleteType(Var->getLocation(), Type, 14017 diag::err_typecheck_decl_incomplete_type)) 14018 Var->setInvalidDecl(); 14019 14020 // Make sure that the type is not abstract. 14021 if (!Type->isDependentType() && !Var->isInvalidDecl() && 14022 RequireNonAbstractType(Var->getLocation(), Type, 14023 diag::err_abstract_type_in_decl, 14024 AbstractVariableType)) 14025 Var->setInvalidDecl(); 14026 if (!Type->isDependentType() && !Var->isInvalidDecl() && 14027 Var->getStorageClass() == SC_PrivateExtern) { 14028 Diag(Var->getLocation(), diag::warn_private_extern); 14029 Diag(Var->getLocation(), diag::note_private_extern); 14030 } 14031 14032 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 14033 !Var->isInvalidDecl()) 14034 ExternalDeclarations.push_back(Var); 14035 14036 return; 14037 14038 case VarDecl::TentativeDefinition: 14039 // File scope. C99 6.9.2p2: A declaration of an identifier for an 14040 // object that has file scope without an initializer, and without a 14041 // storage-class specifier or with the storage-class specifier "static", 14042 // constitutes a tentative definition. Note: A tentative definition with 14043 // external linkage is valid (C99 6.2.2p5). 14044 if (!Var->isInvalidDecl()) { 14045 if (const IncompleteArrayType *ArrayT 14046 = Context.getAsIncompleteArrayType(Type)) { 14047 if (RequireCompleteSizedType( 14048 Var->getLocation(), ArrayT->getElementType(), 14049 diag::err_array_incomplete_or_sizeless_type)) 14050 Var->setInvalidDecl(); 14051 } else if (Var->getStorageClass() == SC_Static) { 14052 // C99 6.9.2p3: If the declaration of an identifier for an object is 14053 // a tentative definition and has internal linkage (C99 6.2.2p3), the 14054 // declared type shall not be an incomplete type. 14055 // NOTE: code such as the following 14056 // static struct s; 14057 // struct s { int a; }; 14058 // is accepted by gcc. Hence here we issue a warning instead of 14059 // an error and we do not invalidate the static declaration. 14060 // NOTE: to avoid multiple warnings, only check the first declaration. 14061 if (Var->isFirstDecl()) 14062 RequireCompleteType(Var->getLocation(), Type, 14063 diag::ext_typecheck_decl_incomplete_type); 14064 } 14065 } 14066 14067 // Record the tentative definition; we're done. 14068 if (!Var->isInvalidDecl()) 14069 TentativeDefinitions.push_back(Var); 14070 return; 14071 } 14072 14073 // Provide a specific diagnostic for uninitialized variable 14074 // definitions with incomplete array type. 14075 if (Type->isIncompleteArrayType()) { 14076 if (Var->isConstexpr()) 14077 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init) 14078 << Var; 14079 else 14080 Diag(Var->getLocation(), 14081 diag::err_typecheck_incomplete_array_needs_initializer); 14082 Var->setInvalidDecl(); 14083 return; 14084 } 14085 14086 // Provide a specific diagnostic for uninitialized variable 14087 // definitions with reference type. 14088 if (Type->isReferenceType()) { 14089 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 14090 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 14091 return; 14092 } 14093 14094 // Do not attempt to type-check the default initializer for a 14095 // variable with dependent type. 14096 if (Type->isDependentType()) 14097 return; 14098 14099 if (Var->isInvalidDecl()) 14100 return; 14101 14102 if (!Var->hasAttr<AliasAttr>()) { 14103 if (RequireCompleteType(Var->getLocation(), 14104 Context.getBaseElementType(Type), 14105 diag::err_typecheck_decl_incomplete_type)) { 14106 Var->setInvalidDecl(); 14107 return; 14108 } 14109 } else { 14110 return; 14111 } 14112 14113 // The variable can not have an abstract class type. 14114 if (RequireNonAbstractType(Var->getLocation(), Type, 14115 diag::err_abstract_type_in_decl, 14116 AbstractVariableType)) { 14117 Var->setInvalidDecl(); 14118 return; 14119 } 14120 14121 // Check for jumps past the implicit initializer. C++0x 14122 // clarifies that this applies to a "variable with automatic 14123 // storage duration", not a "local variable". 14124 // C++11 [stmt.dcl]p3 14125 // A program that jumps from a point where a variable with automatic 14126 // storage duration is not in scope to a point where it is in scope is 14127 // ill-formed unless the variable has scalar type, class type with a 14128 // trivial default constructor and a trivial destructor, a cv-qualified 14129 // version of one of these types, or an array of one of the preceding 14130 // types and is declared without an initializer. 14131 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 14132 if (const RecordType *Record 14133 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 14134 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 14135 // Mark the function (if we're in one) for further checking even if the 14136 // looser rules of C++11 do not require such checks, so that we can 14137 // diagnose incompatibilities with C++98. 14138 if (!CXXRecord->isPOD()) 14139 setFunctionHasBranchProtectedScope(); 14140 } 14141 } 14142 // In OpenCL, we can't initialize objects in the __local address space, 14143 // even implicitly, so don't synthesize an implicit initializer. 14144 if (getLangOpts().OpenCL && 14145 Var->getType().getAddressSpace() == LangAS::opencl_local) 14146 return; 14147 // C++03 [dcl.init]p9: 14148 // If no initializer is specified for an object, and the 14149 // object is of (possibly cv-qualified) non-POD class type (or 14150 // array thereof), the object shall be default-initialized; if 14151 // the object is of const-qualified type, the underlying class 14152 // type shall have a user-declared default 14153 // constructor. Otherwise, if no initializer is specified for 14154 // a non- static object, the object and its subobjects, if 14155 // any, have an indeterminate initial value); if the object 14156 // or any of its subobjects are of const-qualified type, the 14157 // program is ill-formed. 14158 // C++0x [dcl.init]p11: 14159 // If no initializer is specified for an object, the object is 14160 // default-initialized; [...]. 14161 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 14162 InitializationKind Kind 14163 = InitializationKind::CreateDefault(Var->getLocation()); 14164 14165 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt); 14166 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt); 14167 14168 if (Init.get()) { 14169 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 14170 // This is important for template substitution. 14171 Var->setInitStyle(VarDecl::CallInit); 14172 } else if (Init.isInvalid()) { 14173 // If default-init fails, attach a recovery-expr initializer to track 14174 // that initialization was attempted and failed. 14175 auto RecoveryExpr = 14176 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 14177 if (RecoveryExpr.get()) 14178 Var->setInit(RecoveryExpr.get()); 14179 } 14180 14181 CheckCompleteVariableDeclaration(Var); 14182 } 14183 } 14184 14185 void Sema::ActOnCXXForRangeDecl(Decl *D) { 14186 // If there is no declaration, there was an error parsing it. Ignore it. 14187 if (!D) 14188 return; 14189 14190 VarDecl *VD = dyn_cast<VarDecl>(D); 14191 if (!VD) { 14192 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 14193 D->setInvalidDecl(); 14194 return; 14195 } 14196 14197 VD->setCXXForRangeDecl(true); 14198 14199 // for-range-declaration cannot be given a storage class specifier. 14200 int Error = -1; 14201 switch (VD->getStorageClass()) { 14202 case SC_None: 14203 break; 14204 case SC_Extern: 14205 Error = 0; 14206 break; 14207 case SC_Static: 14208 Error = 1; 14209 break; 14210 case SC_PrivateExtern: 14211 Error = 2; 14212 break; 14213 case SC_Auto: 14214 Error = 3; 14215 break; 14216 case SC_Register: 14217 Error = 4; 14218 break; 14219 } 14220 14221 // for-range-declaration cannot be given a storage class specifier con't. 14222 switch (VD->getTSCSpec()) { 14223 case TSCS_thread_local: 14224 Error = 6; 14225 break; 14226 case TSCS___thread: 14227 case TSCS__Thread_local: 14228 case TSCS_unspecified: 14229 break; 14230 } 14231 14232 if (Error != -1) { 14233 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 14234 << VD << Error; 14235 D->setInvalidDecl(); 14236 } 14237 } 14238 14239 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 14240 IdentifierInfo *Ident, 14241 ParsedAttributes &Attrs) { 14242 // C++1y [stmt.iter]p1: 14243 // A range-based for statement of the form 14244 // for ( for-range-identifier : for-range-initializer ) statement 14245 // is equivalent to 14246 // for ( auto&& for-range-identifier : for-range-initializer ) statement 14247 DeclSpec DS(Attrs.getPool().getFactory()); 14248 14249 const char *PrevSpec; 14250 unsigned DiagID; 14251 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 14252 getPrintingPolicy()); 14253 14254 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit); 14255 D.SetIdentifier(Ident, IdentLoc); 14256 D.takeAttributes(Attrs); 14257 14258 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 14259 IdentLoc); 14260 Decl *Var = ActOnDeclarator(S, D); 14261 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 14262 FinalizeDeclaration(Var); 14263 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 14264 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd() 14265 : IdentLoc); 14266 } 14267 14268 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 14269 if (var->isInvalidDecl()) return; 14270 14271 MaybeAddCUDAConstantAttr(var); 14272 14273 if (getLangOpts().OpenCL) { 14274 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 14275 // initialiser 14276 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 14277 !var->hasInit()) { 14278 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 14279 << 1 /*Init*/; 14280 var->setInvalidDecl(); 14281 return; 14282 } 14283 } 14284 14285 // In Objective-C, don't allow jumps past the implicit initialization of a 14286 // local retaining variable. 14287 if (getLangOpts().ObjC && 14288 var->hasLocalStorage()) { 14289 switch (var->getType().getObjCLifetime()) { 14290 case Qualifiers::OCL_None: 14291 case Qualifiers::OCL_ExplicitNone: 14292 case Qualifiers::OCL_Autoreleasing: 14293 break; 14294 14295 case Qualifiers::OCL_Weak: 14296 case Qualifiers::OCL_Strong: 14297 setFunctionHasBranchProtectedScope(); 14298 break; 14299 } 14300 } 14301 14302 if (var->hasLocalStorage() && 14303 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 14304 setFunctionHasBranchProtectedScope(); 14305 14306 // Warn about externally-visible variables being defined without a 14307 // prior declaration. We only want to do this for global 14308 // declarations, but we also specifically need to avoid doing it for 14309 // class members because the linkage of an anonymous class can 14310 // change if it's later given a typedef name. 14311 if (var->isThisDeclarationADefinition() && 14312 var->getDeclContext()->getRedeclContext()->isFileContext() && 14313 var->isExternallyVisible() && var->hasLinkage() && 14314 !var->isInline() && !var->getDescribedVarTemplate() && 14315 var->getStorageClass() != SC_Register && 14316 !isa<VarTemplatePartialSpecializationDecl>(var) && 14317 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 14318 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 14319 var->getLocation())) { 14320 // Find a previous declaration that's not a definition. 14321 VarDecl *prev = var->getPreviousDecl(); 14322 while (prev && prev->isThisDeclarationADefinition()) 14323 prev = prev->getPreviousDecl(); 14324 14325 if (!prev) { 14326 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 14327 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14328 << /* variable */ 0; 14329 } 14330 } 14331 14332 // Cache the result of checking for constant initialization. 14333 std::optional<bool> CacheHasConstInit; 14334 const Expr *CacheCulprit = nullptr; 14335 auto checkConstInit = [&]() mutable { 14336 if (!CacheHasConstInit) 14337 CacheHasConstInit = var->getInit()->isConstantInitializer( 14338 Context, var->getType()->isReferenceType(), &CacheCulprit); 14339 return *CacheHasConstInit; 14340 }; 14341 14342 if (var->getTLSKind() == VarDecl::TLS_Static) { 14343 if (var->getType().isDestructedType()) { 14344 // GNU C++98 edits for __thread, [basic.start.term]p3: 14345 // The type of an object with thread storage duration shall not 14346 // have a non-trivial destructor. 14347 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 14348 if (getLangOpts().CPlusPlus11) 14349 Diag(var->getLocation(), diag::note_use_thread_local); 14350 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 14351 if (!checkConstInit()) { 14352 // GNU C++98 edits for __thread, [basic.start.init]p4: 14353 // An object of thread storage duration shall not require dynamic 14354 // initialization. 14355 // FIXME: Need strict checking here. 14356 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 14357 << CacheCulprit->getSourceRange(); 14358 if (getLangOpts().CPlusPlus11) 14359 Diag(var->getLocation(), diag::note_use_thread_local); 14360 } 14361 } 14362 } 14363 14364 14365 if (!var->getType()->isStructureType() && var->hasInit() && 14366 isa<InitListExpr>(var->getInit())) { 14367 const auto *ILE = cast<InitListExpr>(var->getInit()); 14368 unsigned NumInits = ILE->getNumInits(); 14369 if (NumInits > 2) 14370 for (unsigned I = 0; I < NumInits; ++I) { 14371 const auto *Init = ILE->getInit(I); 14372 if (!Init) 14373 break; 14374 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 14375 if (!SL) 14376 break; 14377 14378 unsigned NumConcat = SL->getNumConcatenated(); 14379 // Diagnose missing comma in string array initialization. 14380 // Do not warn when all the elements in the initializer are concatenated 14381 // together. Do not warn for macros too. 14382 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 14383 bool OnlyOneMissingComma = true; 14384 for (unsigned J = I + 1; J < NumInits; ++J) { 14385 const auto *Init = ILE->getInit(J); 14386 if (!Init) 14387 break; 14388 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 14389 if (!SLJ || SLJ->getNumConcatenated() > 1) { 14390 OnlyOneMissingComma = false; 14391 break; 14392 } 14393 } 14394 14395 if (OnlyOneMissingComma) { 14396 SmallVector<FixItHint, 1> Hints; 14397 for (unsigned i = 0; i < NumConcat - 1; ++i) 14398 Hints.push_back(FixItHint::CreateInsertion( 14399 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 14400 14401 Diag(SL->getStrTokenLoc(1), 14402 diag::warn_concatenated_literal_array_init) 14403 << Hints; 14404 Diag(SL->getBeginLoc(), 14405 diag::note_concatenated_string_literal_silence); 14406 } 14407 // In any case, stop now. 14408 break; 14409 } 14410 } 14411 } 14412 14413 14414 QualType type = var->getType(); 14415 14416 if (var->hasAttr<BlocksAttr>()) 14417 getCurFunction()->addByrefBlockVar(var); 14418 14419 Expr *Init = var->getInit(); 14420 bool GlobalStorage = var->hasGlobalStorage(); 14421 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 14422 QualType baseType = Context.getBaseElementType(type); 14423 bool HasConstInit = true; 14424 14425 // Check whether the initializer is sufficiently constant. 14426 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 14427 !Init->isValueDependent() && 14428 (GlobalStorage || var->isConstexpr() || 14429 var->mightBeUsableInConstantExpressions(Context))) { 14430 // If this variable might have a constant initializer or might be usable in 14431 // constant expressions, check whether or not it actually is now. We can't 14432 // do this lazily, because the result might depend on things that change 14433 // later, such as which constexpr functions happen to be defined. 14434 SmallVector<PartialDiagnosticAt, 8> Notes; 14435 if (!getLangOpts().CPlusPlus11) { 14436 // Prior to C++11, in contexts where a constant initializer is required, 14437 // the set of valid constant initializers is described by syntactic rules 14438 // in [expr.const]p2-6. 14439 // FIXME: Stricter checking for these rules would be useful for constinit / 14440 // -Wglobal-constructors. 14441 HasConstInit = checkConstInit(); 14442 14443 // Compute and cache the constant value, and remember that we have a 14444 // constant initializer. 14445 if (HasConstInit) { 14446 (void)var->checkForConstantInitialization(Notes); 14447 Notes.clear(); 14448 } else if (CacheCulprit) { 14449 Notes.emplace_back(CacheCulprit->getExprLoc(), 14450 PDiag(diag::note_invalid_subexpr_in_const_expr)); 14451 Notes.back().second << CacheCulprit->getSourceRange(); 14452 } 14453 } else { 14454 // Evaluate the initializer to see if it's a constant initializer. 14455 HasConstInit = var->checkForConstantInitialization(Notes); 14456 } 14457 14458 if (HasConstInit) { 14459 // FIXME: Consider replacing the initializer with a ConstantExpr. 14460 } else if (var->isConstexpr()) { 14461 SourceLocation DiagLoc = var->getLocation(); 14462 // If the note doesn't add any useful information other than a source 14463 // location, fold it into the primary diagnostic. 14464 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14465 diag::note_invalid_subexpr_in_const_expr) { 14466 DiagLoc = Notes[0].first; 14467 Notes.clear(); 14468 } 14469 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 14470 << var << Init->getSourceRange(); 14471 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 14472 Diag(Notes[I].first, Notes[I].second); 14473 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 14474 auto *Attr = var->getAttr<ConstInitAttr>(); 14475 Diag(var->getLocation(), diag::err_require_constant_init_failed) 14476 << Init->getSourceRange(); 14477 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 14478 << Attr->getRange() << Attr->isConstinit(); 14479 for (auto &it : Notes) 14480 Diag(it.first, it.second); 14481 } else if (IsGlobal && 14482 !getDiagnostics().isIgnored(diag::warn_global_constructor, 14483 var->getLocation())) { 14484 // Warn about globals which don't have a constant initializer. Don't 14485 // warn about globals with a non-trivial destructor because we already 14486 // warned about them. 14487 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 14488 if (!(RD && !RD->hasTrivialDestructor())) { 14489 // checkConstInit() here permits trivial default initialization even in 14490 // C++11 onwards, where such an initializer is not a constant initializer 14491 // but nonetheless doesn't require a global constructor. 14492 if (!checkConstInit()) 14493 Diag(var->getLocation(), diag::warn_global_constructor) 14494 << Init->getSourceRange(); 14495 } 14496 } 14497 } 14498 14499 // Apply section attributes and pragmas to global variables. 14500 if (GlobalStorage && var->isThisDeclarationADefinition() && 14501 !inTemplateInstantiation()) { 14502 PragmaStack<StringLiteral *> *Stack = nullptr; 14503 int SectionFlags = ASTContext::PSF_Read; 14504 bool MSVCEnv = 14505 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment(); 14506 std::optional<QualType::NonConstantStorageReason> Reason; 14507 if (HasConstInit && 14508 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) { 14509 Stack = &ConstSegStack; 14510 } else { 14511 SectionFlags |= ASTContext::PSF_Write; 14512 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack; 14513 } 14514 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 14515 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 14516 SectionFlags |= ASTContext::PSF_Implicit; 14517 UnifySection(SA->getName(), SectionFlags, var); 14518 } else if (Stack->CurrentValue) { 14519 if (Stack != &ConstSegStack && MSVCEnv && 14520 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue && 14521 var->getType().isConstQualified()) { 14522 assert((!Reason || Reason != QualType::NonConstantStorageReason:: 14523 NonConstNonReferenceType) && 14524 "This case should've already been handled elsewhere"); 14525 Diag(var->getLocation(), diag::warn_section_msvc_compat) 14526 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit 14527 ? QualType::NonConstantStorageReason::NonTrivialCtor 14528 : *Reason); 14529 } 14530 SectionFlags |= ASTContext::PSF_Implicit; 14531 auto SectionName = Stack->CurrentValue->getString(); 14532 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName, 14533 Stack->CurrentPragmaLocation, 14534 SectionAttr::Declspec_allocate)); 14535 if (UnifySection(SectionName, SectionFlags, var)) 14536 var->dropAttr<SectionAttr>(); 14537 } 14538 14539 // Apply the init_seg attribute if this has an initializer. If the 14540 // initializer turns out to not be dynamic, we'll end up ignoring this 14541 // attribute. 14542 if (CurInitSeg && var->getInit()) 14543 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 14544 CurInitSegLoc)); 14545 } 14546 14547 // All the following checks are C++ only. 14548 if (!getLangOpts().CPlusPlus) { 14549 // If this variable must be emitted, add it as an initializer for the 14550 // current module. 14551 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 14552 Context.addModuleInitializer(ModuleScopes.back().Module, var); 14553 return; 14554 } 14555 14556 // Require the destructor. 14557 if (!type->isDependentType()) 14558 if (const RecordType *recordType = baseType->getAs<RecordType>()) 14559 FinalizeVarWithDestructor(var, recordType); 14560 14561 // If this variable must be emitted, add it as an initializer for the current 14562 // module. 14563 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 14564 Context.addModuleInitializer(ModuleScopes.back().Module, var); 14565 14566 // Build the bindings if this is a structured binding declaration. 14567 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 14568 CheckCompleteDecompositionDeclaration(DD); 14569 } 14570 14571 /// Check if VD needs to be dllexport/dllimport due to being in a 14572 /// dllexport/import function. 14573 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 14574 assert(VD->isStaticLocal()); 14575 14576 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 14577 14578 // Find outermost function when VD is in lambda function. 14579 while (FD && !getDLLAttr(FD) && 14580 !FD->hasAttr<DLLExportStaticLocalAttr>() && 14581 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 14582 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 14583 } 14584 14585 if (!FD) 14586 return; 14587 14588 // Static locals inherit dll attributes from their function. 14589 if (Attr *A = getDLLAttr(FD)) { 14590 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 14591 NewAttr->setInherited(true); 14592 VD->addAttr(NewAttr); 14593 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 14594 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 14595 NewAttr->setInherited(true); 14596 VD->addAttr(NewAttr); 14597 14598 // Export this function to enforce exporting this static variable even 14599 // if it is not used in this compilation unit. 14600 if (!FD->hasAttr<DLLExportAttr>()) 14601 FD->addAttr(NewAttr); 14602 14603 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 14604 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 14605 NewAttr->setInherited(true); 14606 VD->addAttr(NewAttr); 14607 } 14608 } 14609 14610 void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) { 14611 assert(VD->getTLSKind()); 14612 14613 // Perform TLS alignment check here after attributes attached to the variable 14614 // which may affect the alignment have been processed. Only perform the check 14615 // if the target has a maximum TLS alignment (zero means no constraints). 14616 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 14617 // Protect the check so that it's not performed on dependent types and 14618 // dependent alignments (we can't determine the alignment in that case). 14619 if (!VD->hasDependentAlignment()) { 14620 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 14621 if (Context.getDeclAlign(VD) > MaxAlignChars) { 14622 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 14623 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 14624 << (unsigned)MaxAlignChars.getQuantity(); 14625 } 14626 } 14627 } 14628 } 14629 14630 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 14631 /// any semantic actions necessary after any initializer has been attached. 14632 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 14633 // Note that we are no longer parsing the initializer for this declaration. 14634 ParsingInitForAutoVars.erase(ThisDecl); 14635 14636 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 14637 if (!VD) 14638 return; 14639 14640 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 14641 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 14642 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 14643 if (PragmaClangBSSSection.Valid) 14644 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 14645 Context, PragmaClangBSSSection.SectionName, 14646 PragmaClangBSSSection.PragmaLocation)); 14647 if (PragmaClangDataSection.Valid) 14648 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 14649 Context, PragmaClangDataSection.SectionName, 14650 PragmaClangDataSection.PragmaLocation)); 14651 if (PragmaClangRodataSection.Valid) 14652 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 14653 Context, PragmaClangRodataSection.SectionName, 14654 PragmaClangRodataSection.PragmaLocation)); 14655 if (PragmaClangRelroSection.Valid) 14656 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 14657 Context, PragmaClangRelroSection.SectionName, 14658 PragmaClangRelroSection.PragmaLocation)); 14659 } 14660 14661 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 14662 for (auto *BD : DD->bindings()) { 14663 FinalizeDeclaration(BD); 14664 } 14665 } 14666 14667 checkAttributesAfterMerging(*this, *VD); 14668 14669 if (VD->isStaticLocal()) 14670 CheckStaticLocalForDllExport(VD); 14671 14672 if (VD->getTLSKind()) 14673 CheckThreadLocalForLargeAlignment(VD); 14674 14675 // Perform check for initializers of device-side global variables. 14676 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 14677 // 7.5). We must also apply the same checks to all __shared__ 14678 // variables whether they are local or not. CUDA also allows 14679 // constant initializers for __constant__ and __device__ variables. 14680 if (getLangOpts().CUDA) 14681 checkAllowedCUDAInitializer(VD); 14682 14683 // Grab the dllimport or dllexport attribute off of the VarDecl. 14684 const InheritableAttr *DLLAttr = getDLLAttr(VD); 14685 14686 // Imported static data members cannot be defined out-of-line. 14687 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 14688 if (VD->isStaticDataMember() && VD->isOutOfLine() && 14689 VD->isThisDeclarationADefinition()) { 14690 // We allow definitions of dllimport class template static data members 14691 // with a warning. 14692 CXXRecordDecl *Context = 14693 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 14694 bool IsClassTemplateMember = 14695 isa<ClassTemplatePartialSpecializationDecl>(Context) || 14696 Context->getDescribedClassTemplate(); 14697 14698 Diag(VD->getLocation(), 14699 IsClassTemplateMember 14700 ? diag::warn_attribute_dllimport_static_field_definition 14701 : diag::err_attribute_dllimport_static_field_definition); 14702 Diag(IA->getLocation(), diag::note_attribute); 14703 if (!IsClassTemplateMember) 14704 VD->setInvalidDecl(); 14705 } 14706 } 14707 14708 // dllimport/dllexport variables cannot be thread local, their TLS index 14709 // isn't exported with the variable. 14710 if (DLLAttr && VD->getTLSKind()) { 14711 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 14712 if (F && getDLLAttr(F)) { 14713 assert(VD->isStaticLocal()); 14714 // But if this is a static local in a dlimport/dllexport function, the 14715 // function will never be inlined, which means the var would never be 14716 // imported, so having it marked import/export is safe. 14717 } else { 14718 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 14719 << DLLAttr; 14720 VD->setInvalidDecl(); 14721 } 14722 } 14723 14724 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 14725 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 14726 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 14727 << Attr; 14728 VD->dropAttr<UsedAttr>(); 14729 } 14730 } 14731 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 14732 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 14733 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 14734 << Attr; 14735 VD->dropAttr<RetainAttr>(); 14736 } 14737 } 14738 14739 const DeclContext *DC = VD->getDeclContext(); 14740 // If there's a #pragma GCC visibility in scope, and this isn't a class 14741 // member, set the visibility of this variable. 14742 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 14743 AddPushedVisibilityAttribute(VD); 14744 14745 // FIXME: Warn on unused var template partial specializations. 14746 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 14747 MarkUnusedFileScopedDecl(VD); 14748 14749 // Now we have parsed the initializer and can update the table of magic 14750 // tag values. 14751 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 14752 !VD->getType()->isIntegralOrEnumerationType()) 14753 return; 14754 14755 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 14756 const Expr *MagicValueExpr = VD->getInit(); 14757 if (!MagicValueExpr) { 14758 continue; 14759 } 14760 std::optional<llvm::APSInt> MagicValueInt; 14761 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 14762 Diag(I->getRange().getBegin(), 14763 diag::err_type_tag_for_datatype_not_ice) 14764 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 14765 continue; 14766 } 14767 if (MagicValueInt->getActiveBits() > 64) { 14768 Diag(I->getRange().getBegin(), 14769 diag::err_type_tag_for_datatype_too_large) 14770 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 14771 continue; 14772 } 14773 uint64_t MagicValue = MagicValueInt->getZExtValue(); 14774 RegisterTypeTagForDatatype(I->getArgumentKind(), 14775 MagicValue, 14776 I->getMatchingCType(), 14777 I->getLayoutCompatible(), 14778 I->getMustBeNull()); 14779 } 14780 } 14781 14782 static bool hasDeducedAuto(DeclaratorDecl *DD) { 14783 auto *VD = dyn_cast<VarDecl>(DD); 14784 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 14785 } 14786 14787 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 14788 ArrayRef<Decl *> Group) { 14789 SmallVector<Decl*, 8> Decls; 14790 14791 if (DS.isTypeSpecOwned()) 14792 Decls.push_back(DS.getRepAsDecl()); 14793 14794 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 14795 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 14796 bool DiagnosedMultipleDecomps = false; 14797 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 14798 bool DiagnosedNonDeducedAuto = false; 14799 14800 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 14801 if (Decl *D = Group[i]) { 14802 // Check if the Decl has been declared in '#pragma omp declare target' 14803 // directive and has static storage duration. 14804 if (auto *VD = dyn_cast<VarDecl>(D); 14805 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() && 14806 VD->hasGlobalStorage()) 14807 ActOnOpenMPDeclareTargetInitializer(D); 14808 // For declarators, there are some additional syntactic-ish checks we need 14809 // to perform. 14810 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 14811 if (!FirstDeclaratorInGroup) 14812 FirstDeclaratorInGroup = DD; 14813 if (!FirstDecompDeclaratorInGroup) 14814 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 14815 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 14816 !hasDeducedAuto(DD)) 14817 FirstNonDeducedAutoInGroup = DD; 14818 14819 if (FirstDeclaratorInGroup != DD) { 14820 // A decomposition declaration cannot be combined with any other 14821 // declaration in the same group. 14822 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 14823 Diag(FirstDecompDeclaratorInGroup->getLocation(), 14824 diag::err_decomp_decl_not_alone) 14825 << FirstDeclaratorInGroup->getSourceRange() 14826 << DD->getSourceRange(); 14827 DiagnosedMultipleDecomps = true; 14828 } 14829 14830 // A declarator that uses 'auto' in any way other than to declare a 14831 // variable with a deduced type cannot be combined with any other 14832 // declarator in the same group. 14833 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 14834 Diag(FirstNonDeducedAutoInGroup->getLocation(), 14835 diag::err_auto_non_deduced_not_alone) 14836 << FirstNonDeducedAutoInGroup->getType() 14837 ->hasAutoForTrailingReturnType() 14838 << FirstDeclaratorInGroup->getSourceRange() 14839 << DD->getSourceRange(); 14840 DiagnosedNonDeducedAuto = true; 14841 } 14842 } 14843 } 14844 14845 Decls.push_back(D); 14846 } 14847 } 14848 14849 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 14850 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 14851 handleTagNumbering(Tag, S); 14852 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 14853 getLangOpts().CPlusPlus) 14854 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 14855 } 14856 } 14857 14858 return BuildDeclaratorGroup(Decls); 14859 } 14860 14861 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 14862 /// group, performing any necessary semantic checking. 14863 Sema::DeclGroupPtrTy 14864 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 14865 // C++14 [dcl.spec.auto]p7: (DR1347) 14866 // If the type that replaces the placeholder type is not the same in each 14867 // deduction, the program is ill-formed. 14868 if (Group.size() > 1) { 14869 QualType Deduced; 14870 VarDecl *DeducedDecl = nullptr; 14871 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 14872 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 14873 if (!D || D->isInvalidDecl()) 14874 break; 14875 DeducedType *DT = D->getType()->getContainedDeducedType(); 14876 if (!DT || DT->getDeducedType().isNull()) 14877 continue; 14878 if (Deduced.isNull()) { 14879 Deduced = DT->getDeducedType(); 14880 DeducedDecl = D; 14881 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 14882 auto *AT = dyn_cast<AutoType>(DT); 14883 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 14884 diag::err_auto_different_deductions) 14885 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 14886 << DeducedDecl->getDeclName() << DT->getDeducedType() 14887 << D->getDeclName(); 14888 if (DeducedDecl->hasInit()) 14889 Dia << DeducedDecl->getInit()->getSourceRange(); 14890 if (D->getInit()) 14891 Dia << D->getInit()->getSourceRange(); 14892 D->setInvalidDecl(); 14893 break; 14894 } 14895 } 14896 } 14897 14898 ActOnDocumentableDecls(Group); 14899 14900 return DeclGroupPtrTy::make( 14901 DeclGroupRef::Create(Context, Group.data(), Group.size())); 14902 } 14903 14904 void Sema::ActOnDocumentableDecl(Decl *D) { 14905 ActOnDocumentableDecls(D); 14906 } 14907 14908 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 14909 // Don't parse the comment if Doxygen diagnostics are ignored. 14910 if (Group.empty() || !Group[0]) 14911 return; 14912 14913 if (Diags.isIgnored(diag::warn_doc_param_not_found, 14914 Group[0]->getLocation()) && 14915 Diags.isIgnored(diag::warn_unknown_comment_command_name, 14916 Group[0]->getLocation())) 14917 return; 14918 14919 if (Group.size() >= 2) { 14920 // This is a decl group. Normally it will contain only declarations 14921 // produced from declarator list. But in case we have any definitions or 14922 // additional declaration references: 14923 // 'typedef struct S {} S;' 14924 // 'typedef struct S *S;' 14925 // 'struct S *pS;' 14926 // FinalizeDeclaratorGroup adds these as separate declarations. 14927 Decl *MaybeTagDecl = Group[0]; 14928 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 14929 Group = Group.slice(1); 14930 } 14931 } 14932 14933 // FIMXE: We assume every Decl in the group is in the same file. 14934 // This is false when preprocessor constructs the group from decls in 14935 // different files (e. g. macros or #include). 14936 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 14937 } 14938 14939 /// Common checks for a parameter-declaration that should apply to both function 14940 /// parameters and non-type template parameters. 14941 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 14942 // Check that there are no default arguments inside the type of this 14943 // parameter. 14944 if (getLangOpts().CPlusPlus) 14945 CheckExtraCXXDefaultArguments(D); 14946 14947 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 14948 if (D.getCXXScopeSpec().isSet()) { 14949 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 14950 << D.getCXXScopeSpec().getRange(); 14951 } 14952 14953 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 14954 // simple identifier except [...irrelevant cases...]. 14955 switch (D.getName().getKind()) { 14956 case UnqualifiedIdKind::IK_Identifier: 14957 break; 14958 14959 case UnqualifiedIdKind::IK_OperatorFunctionId: 14960 case UnqualifiedIdKind::IK_ConversionFunctionId: 14961 case UnqualifiedIdKind::IK_LiteralOperatorId: 14962 case UnqualifiedIdKind::IK_ConstructorName: 14963 case UnqualifiedIdKind::IK_DestructorName: 14964 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14965 case UnqualifiedIdKind::IK_DeductionGuideName: 14966 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 14967 << GetNameForDeclarator(D).getName(); 14968 break; 14969 14970 case UnqualifiedIdKind::IK_TemplateId: 14971 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14972 // GetNameForDeclarator would not produce a useful name in this case. 14973 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 14974 break; 14975 } 14976 } 14977 14978 static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, 14979 SourceLocation ExplicitThisLoc) { 14980 if (!ExplicitThisLoc.isValid()) 14981 return; 14982 assert(S.getLangOpts().CPlusPlus && 14983 "explicit parameter in non-cplusplus mode"); 14984 if (!S.getLangOpts().CPlusPlus23) 14985 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this) 14986 << P->getSourceRange(); 14987 14988 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function 14989 // parameter pack. 14990 if (P->isParameterPack()) { 14991 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack) 14992 << P->getSourceRange(); 14993 return; 14994 } 14995 P->setExplicitObjectParameterLoc(ExplicitThisLoc); 14996 if (LambdaScopeInfo *LSI = S.getCurLambda()) 14997 LSI->ExplicitObjectParameter = P; 14998 } 14999 15000 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 15001 /// to introduce parameters into function prototype scope. 15002 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D, 15003 SourceLocation ExplicitThisLoc) { 15004 const DeclSpec &DS = D.getDeclSpec(); 15005 15006 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 15007 15008 // C++03 [dcl.stc]p2 also permits 'auto'. 15009 StorageClass SC = SC_None; 15010 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 15011 SC = SC_Register; 15012 // In C++11, the 'register' storage class specifier is deprecated. 15013 // In C++17, it is not allowed, but we tolerate it as an extension. 15014 if (getLangOpts().CPlusPlus11) { 15015 Diag(DS.getStorageClassSpecLoc(), 15016 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 15017 : diag::warn_deprecated_register) 15018 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 15019 } 15020 } else if (getLangOpts().CPlusPlus && 15021 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 15022 SC = SC_Auto; 15023 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 15024 Diag(DS.getStorageClassSpecLoc(), 15025 diag::err_invalid_storage_class_in_func_decl); 15026 D.getMutableDeclSpec().ClearStorageClassSpecs(); 15027 } 15028 15029 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 15030 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 15031 << DeclSpec::getSpecifierName(TSCS); 15032 if (DS.isInlineSpecified()) 15033 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 15034 << getLangOpts().CPlusPlus17; 15035 if (DS.hasConstexprSpecifier()) 15036 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 15037 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 15038 15039 DiagnoseFunctionSpecifiers(DS); 15040 15041 CheckFunctionOrTemplateParamDeclarator(S, D); 15042 15043 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15044 QualType parmDeclType = TInfo->getType(); 15045 15046 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 15047 IdentifierInfo *II = D.getIdentifier(); 15048 if (II) { 15049 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 15050 ForVisibleRedeclaration); 15051 LookupName(R, S); 15052 if (!R.empty()) { 15053 NamedDecl *PrevDecl = *R.begin(); 15054 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) { 15055 // Maybe we will complain about the shadowed template parameter. 15056 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15057 // Just pretend that we didn't see the previous declaration. 15058 PrevDecl = nullptr; 15059 } 15060 if (PrevDecl && S->isDeclScope(PrevDecl)) { 15061 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 15062 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15063 // Recover by removing the name 15064 II = nullptr; 15065 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 15066 D.setInvalidType(true); 15067 } 15068 } 15069 } 15070 15071 // Temporarily put parameter variables in the translation unit, not 15072 // the enclosing context. This prevents them from accidentally 15073 // looking like class members in C++. 15074 ParmVarDecl *New = 15075 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 15076 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 15077 15078 if (D.isInvalidType()) 15079 New->setInvalidDecl(); 15080 15081 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc); 15082 15083 assert(S->isFunctionPrototypeScope()); 15084 assert(S->getFunctionPrototypeDepth() >= 1); 15085 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 15086 S->getNextFunctionPrototypeIndex()); 15087 15088 // Add the parameter declaration into this scope. 15089 S->AddDecl(New); 15090 if (II) 15091 IdResolver.AddDecl(New); 15092 15093 ProcessDeclAttributes(S, New, D); 15094 15095 if (D.getDeclSpec().isModulePrivateSpecified()) 15096 Diag(New->getLocation(), diag::err_module_private_local) 15097 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15098 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 15099 15100 if (New->hasAttr<BlocksAttr>()) { 15101 Diag(New->getLocation(), diag::err_block_on_nonlocal); 15102 } 15103 15104 if (getLangOpts().OpenCL) 15105 deduceOpenCLAddressSpace(New); 15106 15107 return New; 15108 } 15109 15110 /// Synthesizes a variable for a parameter arising from a 15111 /// typedef. 15112 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 15113 SourceLocation Loc, 15114 QualType T) { 15115 /* FIXME: setting StartLoc == Loc. 15116 Would it be worth to modify callers so as to provide proper source 15117 location for the unnamed parameters, embedding the parameter's type? */ 15118 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 15119 T, Context.getTrivialTypeSourceInfo(T, Loc), 15120 SC_None, nullptr); 15121 Param->setImplicit(); 15122 return Param; 15123 } 15124 15125 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 15126 // Don't diagnose unused-parameter errors in template instantiations; we 15127 // will already have done so in the template itself. 15128 if (inTemplateInstantiation()) 15129 return; 15130 15131 for (const ParmVarDecl *Parameter : Parameters) { 15132 if (!Parameter->isReferenced() && Parameter->getDeclName() && 15133 !Parameter->hasAttr<UnusedAttr>() && 15134 !Parameter->getIdentifier()->isPlaceholder()) { 15135 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 15136 << Parameter->getDeclName(); 15137 } 15138 } 15139 } 15140 15141 void Sema::DiagnoseSizeOfParametersAndReturnValue( 15142 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 15143 if (LangOpts.NumLargeByValueCopy == 0) // No check. 15144 return; 15145 15146 // Warn if the return value is pass-by-value and larger than the specified 15147 // threshold. 15148 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 15149 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 15150 if (Size > LangOpts.NumLargeByValueCopy) 15151 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 15152 } 15153 15154 // Warn if any parameter is pass-by-value and larger than the specified 15155 // threshold. 15156 for (const ParmVarDecl *Parameter : Parameters) { 15157 QualType T = Parameter->getType(); 15158 if (T->isDependentType() || !T.isPODType(Context)) 15159 continue; 15160 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 15161 if (Size > LangOpts.NumLargeByValueCopy) 15162 Diag(Parameter->getLocation(), diag::warn_parameter_size) 15163 << Parameter << Size; 15164 } 15165 } 15166 15167 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 15168 SourceLocation NameLoc, IdentifierInfo *Name, 15169 QualType T, TypeSourceInfo *TSInfo, 15170 StorageClass SC) { 15171 // In ARC, infer a lifetime qualifier for appropriate parameter types. 15172 if (getLangOpts().ObjCAutoRefCount && 15173 T.getObjCLifetime() == Qualifiers::OCL_None && 15174 T->isObjCLifetimeType()) { 15175 15176 Qualifiers::ObjCLifetime lifetime; 15177 15178 // Special cases for arrays: 15179 // - if it's const, use __unsafe_unretained 15180 // - otherwise, it's an error 15181 if (T->isArrayType()) { 15182 if (!T.isConstQualified()) { 15183 if (DelayedDiagnostics.shouldDelayDiagnostics()) 15184 DelayedDiagnostics.add( 15185 sema::DelayedDiagnostic::makeForbiddenType( 15186 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 15187 else 15188 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 15189 << TSInfo->getTypeLoc().getSourceRange(); 15190 } 15191 lifetime = Qualifiers::OCL_ExplicitNone; 15192 } else { 15193 lifetime = T->getObjCARCImplicitLifetime(); 15194 } 15195 T = Context.getLifetimeQualifiedType(T, lifetime); 15196 } 15197 15198 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 15199 Context.getAdjustedParameterType(T), 15200 TSInfo, SC, nullptr); 15201 15202 // Make a note if we created a new pack in the scope of a lambda, so that 15203 // we know that references to that pack must also be expanded within the 15204 // lambda scope. 15205 if (New->isParameterPack()) 15206 if (auto *LSI = getEnclosingLambda()) 15207 LSI->LocalPacks.push_back(New); 15208 15209 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 15210 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 15211 checkNonTrivialCUnion(New->getType(), New->getLocation(), 15212 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 15213 15214 // Parameter declarators cannot be interface types. All ObjC objects are 15215 // passed by reference. 15216 if (T->isObjCObjectType()) { 15217 SourceLocation TypeEndLoc = 15218 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 15219 Diag(NameLoc, 15220 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 15221 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 15222 T = Context.getObjCObjectPointerType(T); 15223 New->setType(T); 15224 } 15225 15226 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 15227 // duration shall not be qualified by an address-space qualifier." 15228 // Since all parameters have automatic store duration, they can not have 15229 // an address space. 15230 if (T.getAddressSpace() != LangAS::Default && 15231 // OpenCL allows function arguments declared to be an array of a type 15232 // to be qualified with an address space. 15233 !(getLangOpts().OpenCL && 15234 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) && 15235 // WebAssembly allows reference types as parameters. Funcref in particular 15236 // lives in a different address space. 15237 !(T->isFunctionPointerType() && 15238 T.getAddressSpace() == LangAS::wasm_funcref)) { 15239 Diag(NameLoc, diag::err_arg_with_address_space); 15240 New->setInvalidDecl(); 15241 } 15242 15243 // PPC MMA non-pointer types are not allowed as function argument types. 15244 if (Context.getTargetInfo().getTriple().isPPC64() && 15245 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 15246 New->setInvalidDecl(); 15247 } 15248 15249 return New; 15250 } 15251 15252 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 15253 SourceLocation LocAfterDecls) { 15254 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 15255 15256 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration 15257 // in the declaration list shall have at least one declarator, those 15258 // declarators shall only declare identifiers from the identifier list, and 15259 // every identifier in the identifier list shall be declared. 15260 // 15261 // C89 3.7.1p5 "If a declarator includes an identifier list, only the 15262 // identifiers it names shall be declared in the declaration list." 15263 // 15264 // This is why we only diagnose in C99 and later. Note, the other conditions 15265 // listed are checked elsewhere. 15266 if (!FTI.hasPrototype) { 15267 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 15268 --i; 15269 if (FTI.Params[i].Param == nullptr) { 15270 if (getLangOpts().C99) { 15271 SmallString<256> Code; 15272 llvm::raw_svector_ostream(Code) 15273 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 15274 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 15275 << FTI.Params[i].Ident 15276 << FixItHint::CreateInsertion(LocAfterDecls, Code); 15277 } 15278 15279 // Implicitly declare the argument as type 'int' for lack of a better 15280 // type. 15281 AttributeFactory attrs; 15282 DeclSpec DS(attrs); 15283 const char* PrevSpec; // unused 15284 unsigned DiagID; // unused 15285 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 15286 DiagID, Context.getPrintingPolicy()); 15287 // Use the identifier location for the type source range. 15288 DS.SetRangeStart(FTI.Params[i].IdentLoc); 15289 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 15290 Declarator ParamD(DS, ParsedAttributesView::none(), 15291 DeclaratorContext::KNRTypeList); 15292 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 15293 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 15294 } 15295 } 15296 } 15297 } 15298 15299 Decl * 15300 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 15301 MultiTemplateParamsArg TemplateParameterLists, 15302 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) { 15303 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 15304 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 15305 Scope *ParentScope = FnBodyScope->getParent(); 15306 15307 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 15308 // we define a non-templated function definition, we will create a declaration 15309 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 15310 // The base function declaration will have the equivalent of an `omp declare 15311 // variant` annotation which specifies the mangled definition as a 15312 // specialization function under the OpenMP context defined as part of the 15313 // `omp begin declare variant`. 15314 SmallVector<FunctionDecl *, 4> Bases; 15315 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 15316 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 15317 ParentScope, D, TemplateParameterLists, Bases); 15318 15319 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 15320 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 15321 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind); 15322 15323 if (!Bases.empty()) 15324 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 15325 15326 return Dcl; 15327 } 15328 15329 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 15330 Consumer.HandleInlineFunctionDefinition(D); 15331 } 15332 15333 static bool FindPossiblePrototype(const FunctionDecl *FD, 15334 const FunctionDecl *&PossiblePrototype) { 15335 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev; 15336 Prev = Prev->getPreviousDecl()) { 15337 // Ignore any declarations that occur in function or method 15338 // scope, because they aren't visible from the header. 15339 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 15340 continue; 15341 15342 PossiblePrototype = Prev; 15343 return Prev->getType()->isFunctionProtoType(); 15344 } 15345 return false; 15346 } 15347 15348 static bool 15349 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 15350 const FunctionDecl *&PossiblePrototype) { 15351 // Don't warn about invalid declarations. 15352 if (FD->isInvalidDecl()) 15353 return false; 15354 15355 // Or declarations that aren't global. 15356 if (!FD->isGlobal()) 15357 return false; 15358 15359 // Don't warn about C++ member functions. 15360 if (isa<CXXMethodDecl>(FD)) 15361 return false; 15362 15363 // Don't warn about 'main'. 15364 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 15365 if (IdentifierInfo *II = FD->getIdentifier()) 15366 if (II->isStr("main") || II->isStr("efi_main")) 15367 return false; 15368 15369 // Don't warn about inline functions. 15370 if (FD->isInlined()) 15371 return false; 15372 15373 // Don't warn about function templates. 15374 if (FD->getDescribedFunctionTemplate()) 15375 return false; 15376 15377 // Don't warn about function template specializations. 15378 if (FD->isFunctionTemplateSpecialization()) 15379 return false; 15380 15381 // Don't warn for OpenCL kernels. 15382 if (FD->hasAttr<OpenCLKernelAttr>()) 15383 return false; 15384 15385 // Don't warn on explicitly deleted functions. 15386 if (FD->isDeleted()) 15387 return false; 15388 15389 // Don't warn on implicitly local functions (such as having local-typed 15390 // parameters). 15391 if (!FD->isExternallyVisible()) 15392 return false; 15393 15394 // If we were able to find a potential prototype, don't warn. 15395 if (FindPossiblePrototype(FD, PossiblePrototype)) 15396 return false; 15397 15398 return true; 15399 } 15400 15401 void 15402 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 15403 const FunctionDecl *EffectiveDefinition, 15404 SkipBodyInfo *SkipBody) { 15405 const FunctionDecl *Definition = EffectiveDefinition; 15406 if (!Definition && 15407 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 15408 return; 15409 15410 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 15411 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 15412 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 15413 // A merged copy of the same function, instantiated as a member of 15414 // the same class, is OK. 15415 if (declaresSameEntity(OrigFD, OrigDef) && 15416 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 15417 cast<Decl>(FD->getLexicalDeclContext()))) 15418 return; 15419 } 15420 } 15421 } 15422 15423 if (canRedefineFunction(Definition, getLangOpts())) 15424 return; 15425 15426 // Don't emit an error when this is redefinition of a typo-corrected 15427 // definition. 15428 if (TypoCorrectedFunctionDefinitions.count(Definition)) 15429 return; 15430 15431 // If we don't have a visible definition of the function, and it's inline or 15432 // a template, skip the new definition. 15433 if (SkipBody && !hasVisibleDefinition(Definition) && 15434 (Definition->getFormalLinkage() == Linkage::Internal || 15435 Definition->isInlined() || Definition->getDescribedFunctionTemplate() || 15436 Definition->getNumTemplateParameterLists())) { 15437 SkipBody->ShouldSkip = true; 15438 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 15439 if (auto *TD = Definition->getDescribedFunctionTemplate()) 15440 makeMergedDefinitionVisible(TD); 15441 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 15442 return; 15443 } 15444 15445 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 15446 Definition->getStorageClass() == SC_Extern) 15447 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 15448 << FD << getLangOpts().CPlusPlus; 15449 else 15450 Diag(FD->getLocation(), diag::err_redefinition) << FD; 15451 15452 Diag(Definition->getLocation(), diag::note_previous_definition); 15453 FD->setInvalidDecl(); 15454 } 15455 15456 LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) { 15457 CXXRecordDecl *LambdaClass = CallOperator->getParent(); 15458 15459 LambdaScopeInfo *LSI = PushLambdaScope(); 15460 LSI->CallOperator = CallOperator; 15461 LSI->Lambda = LambdaClass; 15462 LSI->ReturnType = CallOperator->getReturnType(); 15463 // This function in calls in situation where the context of the call operator 15464 // is not entered, so we set AfterParameterList to false, so that 15465 // `tryCaptureVariable` finds explicit captures in the appropriate context. 15466 LSI->AfterParameterList = false; 15467 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 15468 15469 if (LCD == LCD_None) 15470 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 15471 else if (LCD == LCD_ByCopy) 15472 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 15473 else if (LCD == LCD_ByRef) 15474 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 15475 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 15476 15477 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 15478 LSI->Mutable = !CallOperator->isConst(); 15479 if (CallOperator->isExplicitObjectMemberFunction()) 15480 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0); 15481 15482 // Add the captures to the LSI so they can be noted as already 15483 // captured within tryCaptureVar. 15484 auto I = LambdaClass->field_begin(); 15485 for (const auto &C : LambdaClass->captures()) { 15486 if (C.capturesVariable()) { 15487 ValueDecl *VD = C.getCapturedVar(); 15488 if (VD->isInitCapture()) 15489 CurrentInstantiationScope->InstantiatedLocal(VD, VD); 15490 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 15491 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 15492 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 15493 /*EllipsisLoc*/C.isPackExpansion() 15494 ? C.getEllipsisLoc() : SourceLocation(), 15495 I->getType(), /*Invalid*/false); 15496 15497 } else if (C.capturesThis()) { 15498 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 15499 C.getCaptureKind() == LCK_StarThis); 15500 } else { 15501 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 15502 I->getType()); 15503 } 15504 ++I; 15505 } 15506 return LSI; 15507 } 15508 15509 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 15510 SkipBodyInfo *SkipBody, 15511 FnBodyKind BodyKind) { 15512 if (!D) { 15513 // Parsing the function declaration failed in some way. Push on a fake scope 15514 // anyway so we can try to parse the function body. 15515 PushFunctionScope(); 15516 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15517 return D; 15518 } 15519 15520 FunctionDecl *FD = nullptr; 15521 15522 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 15523 FD = FunTmpl->getTemplatedDecl(); 15524 else 15525 FD = cast<FunctionDecl>(D); 15526 15527 // Do not push if it is a lambda because one is already pushed when building 15528 // the lambda in ActOnStartOfLambdaDefinition(). 15529 if (!isLambdaCallOperator(FD)) 15530 // [expr.const]/p14.1 15531 // An expression or conversion is in an immediate function context if it is 15532 // potentially evaluated and either: its innermost enclosing non-block scope 15533 // is a function parameter scope of an immediate function. 15534 PushExpressionEvaluationContext( 15535 FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext 15536 : ExprEvalContexts.back().Context); 15537 15538 // Each ExpressionEvaluationContextRecord also keeps track of whether the 15539 // context is nested in an immediate function context, so smaller contexts 15540 // that appear inside immediate functions (like variable initializers) are 15541 // considered to be inside an immediate function context even though by 15542 // themselves they are not immediate function contexts. But when a new 15543 // function is entered, we need to reset this tracking, since the entered 15544 // function might be not an immediate function. 15545 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval(); 15546 ExprEvalContexts.back().InImmediateEscalatingFunctionContext = 15547 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating(); 15548 15549 // Check for defining attributes before the check for redefinition. 15550 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 15551 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 15552 FD->dropAttr<AliasAttr>(); 15553 FD->setInvalidDecl(); 15554 } 15555 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 15556 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 15557 FD->dropAttr<IFuncAttr>(); 15558 FD->setInvalidDecl(); 15559 } 15560 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) { 15561 if (!Context.getTargetInfo().hasFeature("fmv") && 15562 !Attr->isDefaultVersion()) { 15563 // If function multi versioning disabled skip parsing function body 15564 // defined with non-default target_version attribute 15565 if (SkipBody) 15566 SkipBody->ShouldSkip = true; 15567 return nullptr; 15568 } 15569 } 15570 15571 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 15572 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 15573 Ctor->isDefaultConstructor() && 15574 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 15575 // If this is an MS ABI dllexport default constructor, instantiate any 15576 // default arguments. 15577 InstantiateDefaultCtorDefaultArgs(Ctor); 15578 } 15579 } 15580 15581 // See if this is a redefinition. If 'will have body' (or similar) is already 15582 // set, then these checks were already performed when it was set. 15583 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 15584 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 15585 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 15586 15587 // If we're skipping the body, we're done. Don't enter the scope. 15588 if (SkipBody && SkipBody->ShouldSkip) 15589 return D; 15590 } 15591 15592 // Mark this function as "will have a body eventually". This lets users to 15593 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 15594 // this function. 15595 FD->setWillHaveBody(); 15596 15597 // If we are instantiating a generic lambda call operator, push 15598 // a LambdaScopeInfo onto the function stack. But use the information 15599 // that's already been calculated (ActOnLambdaExpr) to prime the current 15600 // LambdaScopeInfo. 15601 // When the template operator is being specialized, the LambdaScopeInfo, 15602 // has to be properly restored so that tryCaptureVariable doesn't try 15603 // and capture any new variables. In addition when calculating potential 15604 // captures during transformation of nested lambdas, it is necessary to 15605 // have the LSI properly restored. 15606 if (isGenericLambdaCallOperatorSpecialization(FD)) { 15607 assert(inTemplateInstantiation() && 15608 "There should be an active template instantiation on the stack " 15609 "when instantiating a generic lambda!"); 15610 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D)); 15611 } else { 15612 // Enter a new function scope 15613 PushFunctionScope(); 15614 } 15615 15616 // Builtin functions cannot be defined. 15617 if (unsigned BuiltinID = FD->getBuiltinID()) { 15618 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 15619 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 15620 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 15621 FD->setInvalidDecl(); 15622 } 15623 } 15624 15625 // The return type of a function definition must be complete (C99 6.9.1p3). 15626 // C++23 [dcl.fct.def.general]/p2 15627 // The type of [...] the return for a function definition 15628 // shall not be a (possibly cv-qualified) class type that is incomplete 15629 // or abstract within the function body unless the function is deleted. 15630 QualType ResultType = FD->getReturnType(); 15631 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 15632 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete && 15633 (RequireCompleteType(FD->getLocation(), ResultType, 15634 diag::err_func_def_incomplete_result) || 15635 RequireNonAbstractType(FD->getLocation(), FD->getReturnType(), 15636 diag::err_abstract_type_in_decl, 15637 AbstractReturnType))) 15638 FD->setInvalidDecl(); 15639 15640 if (FnBodyScope) 15641 PushDeclContext(FnBodyScope, FD); 15642 15643 // Check the validity of our function parameters 15644 if (BodyKind != FnBodyKind::Delete) 15645 CheckParmsForFunctionDef(FD->parameters(), 15646 /*CheckParameterNames=*/true); 15647 15648 // Add non-parameter declarations already in the function to the current 15649 // scope. 15650 if (FnBodyScope) { 15651 for (Decl *NPD : FD->decls()) { 15652 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 15653 if (!NonParmDecl) 15654 continue; 15655 assert(!isa<ParmVarDecl>(NonParmDecl) && 15656 "parameters should not be in newly created FD yet"); 15657 15658 // If the decl has a name, make it accessible in the current scope. 15659 if (NonParmDecl->getDeclName()) 15660 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 15661 15662 // Similarly, dive into enums and fish their constants out, making them 15663 // accessible in this scope. 15664 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 15665 for (auto *EI : ED->enumerators()) 15666 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 15667 } 15668 } 15669 } 15670 15671 // Introduce our parameters into the function scope 15672 for (auto *Param : FD->parameters()) { 15673 Param->setOwningFunction(FD); 15674 15675 // If this has an identifier, add it to the scope stack. 15676 if (Param->getIdentifier() && FnBodyScope) { 15677 CheckShadow(FnBodyScope, Param); 15678 15679 PushOnScopeChains(Param, FnBodyScope); 15680 } 15681 } 15682 15683 // C++ [module.import/6] external definitions are not permitted in header 15684 // units. Deleted and Defaulted functions are implicitly inline (but the 15685 // inline state is not set at this point, so check the BodyKind explicitly). 15686 // FIXME: Consider an alternate location for the test where the inlined() 15687 // state is complete. 15688 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() && 15689 !FD->isInvalidDecl() && !FD->isInlined() && 15690 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default && 15691 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() && 15692 !FD->isTemplateInstantiation()) { 15693 assert(FD->isThisDeclarationADefinition()); 15694 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit); 15695 FD->setInvalidDecl(); 15696 } 15697 15698 // Ensure that the function's exception specification is instantiated. 15699 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 15700 ResolveExceptionSpec(D->getLocation(), FPT); 15701 15702 // dllimport cannot be applied to non-inline function definitions. 15703 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 15704 !FD->isTemplateInstantiation()) { 15705 assert(!FD->hasAttr<DLLExportAttr>()); 15706 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 15707 FD->setInvalidDecl(); 15708 return D; 15709 } 15710 // We want to attach documentation to original Decl (which might be 15711 // a function template). 15712 ActOnDocumentableDecl(D); 15713 if (getCurLexicalContext()->isObjCContainer() && 15714 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 15715 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 15716 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 15717 15718 return D; 15719 } 15720 15721 /// Given the set of return statements within a function body, 15722 /// compute the variables that are subject to the named return value 15723 /// optimization. 15724 /// 15725 /// Each of the variables that is subject to the named return value 15726 /// optimization will be marked as NRVO variables in the AST, and any 15727 /// return statement that has a marked NRVO variable as its NRVO candidate can 15728 /// use the named return value optimization. 15729 /// 15730 /// This function applies a very simplistic algorithm for NRVO: if every return 15731 /// statement in the scope of a variable has the same NRVO candidate, that 15732 /// candidate is an NRVO variable. 15733 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 15734 ReturnStmt **Returns = Scope->Returns.data(); 15735 15736 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 15737 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 15738 if (!NRVOCandidate->isNRVOVariable()) 15739 Returns[I]->setNRVOCandidate(nullptr); 15740 } 15741 } 15742 } 15743 15744 bool Sema::canDelayFunctionBody(const Declarator &D) { 15745 // We can't delay parsing the body of a constexpr function template (yet). 15746 if (D.getDeclSpec().hasConstexprSpecifier()) 15747 return false; 15748 15749 // We can't delay parsing the body of a function template with a deduced 15750 // return type (yet). 15751 if (D.getDeclSpec().hasAutoTypeSpec()) { 15752 // If the placeholder introduces a non-deduced trailing return type, 15753 // we can still delay parsing it. 15754 if (D.getNumTypeObjects()) { 15755 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 15756 if (Outer.Kind == DeclaratorChunk::Function && 15757 Outer.Fun.hasTrailingReturnType()) { 15758 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 15759 return Ty.isNull() || !Ty->isUndeducedType(); 15760 } 15761 } 15762 return false; 15763 } 15764 15765 return true; 15766 } 15767 15768 bool Sema::canSkipFunctionBody(Decl *D) { 15769 // We cannot skip the body of a function (or function template) which is 15770 // constexpr, since we may need to evaluate its body in order to parse the 15771 // rest of the file. 15772 // We cannot skip the body of a function with an undeduced return type, 15773 // because any callers of that function need to know the type. 15774 if (const FunctionDecl *FD = D->getAsFunction()) { 15775 if (FD->isConstexpr()) 15776 return false; 15777 // We can't simply call Type::isUndeducedType here, because inside template 15778 // auto can be deduced to a dependent type, which is not considered 15779 // "undeduced". 15780 if (FD->getReturnType()->getContainedDeducedType()) 15781 return false; 15782 } 15783 return Consumer.shouldSkipFunctionBody(D); 15784 } 15785 15786 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 15787 if (!Decl) 15788 return nullptr; 15789 if (FunctionDecl *FD = Decl->getAsFunction()) 15790 FD->setHasSkippedBody(); 15791 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 15792 MD->setHasSkippedBody(); 15793 return Decl; 15794 } 15795 15796 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 15797 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false); 15798 } 15799 15800 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 15801 /// body. 15802 class ExitFunctionBodyRAII { 15803 public: 15804 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 15805 ~ExitFunctionBodyRAII() { 15806 if (!IsLambda) 15807 S.PopExpressionEvaluationContext(); 15808 } 15809 15810 private: 15811 Sema &S; 15812 bool IsLambda = false; 15813 }; 15814 15815 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 15816 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 15817 15818 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 15819 if (EscapeInfo.count(BD)) 15820 return EscapeInfo[BD]; 15821 15822 bool R = false; 15823 const BlockDecl *CurBD = BD; 15824 15825 do { 15826 R = !CurBD->doesNotEscape(); 15827 if (R) 15828 break; 15829 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 15830 } while (CurBD); 15831 15832 return EscapeInfo[BD] = R; 15833 }; 15834 15835 // If the location where 'self' is implicitly retained is inside a escaping 15836 // block, emit a diagnostic. 15837 for (const std::pair<SourceLocation, const BlockDecl *> &P : 15838 S.ImplicitlyRetainedSelfLocs) 15839 if (IsOrNestedInEscapingBlock(P.second)) 15840 S.Diag(P.first, diag::warn_implicitly_retains_self) 15841 << FixItHint::CreateInsertion(P.first, "self->"); 15842 } 15843 15844 void Sema::CheckCoroutineWrapper(FunctionDecl *FD) { 15845 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl(); 15846 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>()) 15847 return; 15848 // Allow `get_return_object()`. 15849 if (FD->getDeclName().isIdentifier() && 15850 FD->getName().equals("get_return_object") && FD->param_empty()) 15851 return; 15852 if (!FD->hasAttr<CoroWrapperAttr>()) 15853 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD; 15854 } 15855 15856 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 15857 bool IsInstantiation) { 15858 FunctionScopeInfo *FSI = getCurFunction(); 15859 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 15860 15861 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 15862 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 15863 15864 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15865 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 15866 15867 // If we skip function body, we can't tell if a function is a coroutine. 15868 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) { 15869 if (FSI->isCoroutine()) 15870 CheckCompletedCoroutineBody(FD, Body); 15871 else 15872 CheckCoroutineWrapper(FD); 15873 } 15874 15875 { 15876 // Do not call PopExpressionEvaluationContext() if it is a lambda because 15877 // one is already popped when finishing the lambda in BuildLambdaExpr(). 15878 // This is meant to pop the context added in ActOnStartOfFunctionDef(). 15879 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 15880 if (FD) { 15881 FD->setBody(Body); 15882 FD->setWillHaveBody(false); 15883 CheckImmediateEscalatingFunctionDefinition(FD, FSI); 15884 15885 if (getLangOpts().CPlusPlus14) { 15886 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 15887 FD->getReturnType()->isUndeducedType()) { 15888 // For a function with a deduced result type to return void, 15889 // the result type as written must be 'auto' or 'decltype(auto)', 15890 // possibly cv-qualified or constrained, but not ref-qualified. 15891 if (!FD->getReturnType()->getAs<AutoType>()) { 15892 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 15893 << FD->getReturnType(); 15894 FD->setInvalidDecl(); 15895 } else { 15896 // Falling off the end of the function is the same as 'return;'. 15897 Expr *Dummy = nullptr; 15898 if (DeduceFunctionTypeFromReturnExpr( 15899 FD, dcl->getLocation(), Dummy, 15900 FD->getReturnType()->getAs<AutoType>())) 15901 FD->setInvalidDecl(); 15902 } 15903 } 15904 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 15905 // In C++11, we don't use 'auto' deduction rules for lambda call 15906 // operators because we don't support return type deduction. 15907 auto *LSI = getCurLambda(); 15908 if (LSI->HasImplicitReturnType) { 15909 deduceClosureReturnType(*LSI); 15910 15911 // C++11 [expr.prim.lambda]p4: 15912 // [...] if there are no return statements in the compound-statement 15913 // [the deduced type is] the type void 15914 QualType RetType = 15915 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 15916 15917 // Update the return type to the deduced type. 15918 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 15919 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 15920 Proto->getExtProtoInfo())); 15921 } 15922 } 15923 15924 // If the function implicitly returns zero (like 'main') or is naked, 15925 // don't complain about missing return statements. 15926 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 15927 WP.disableCheckFallThrough(); 15928 15929 // MSVC permits the use of pure specifier (=0) on function definition, 15930 // defined at class scope, warn about this non-standard construct. 15931 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 15932 Diag(FD->getLocation(), diag::ext_pure_function_definition); 15933 15934 if (!FD->isInvalidDecl()) { 15935 // Don't diagnose unused parameters of defaulted, deleted or naked 15936 // functions. 15937 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() && 15938 !FD->hasAttr<NakedAttr>()) 15939 DiagnoseUnusedParameters(FD->parameters()); 15940 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 15941 FD->getReturnType(), FD); 15942 15943 // If this is a structor, we need a vtable. 15944 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 15945 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 15946 else if (CXXDestructorDecl *Destructor = 15947 dyn_cast<CXXDestructorDecl>(FD)) 15948 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 15949 15950 // Try to apply the named return value optimization. We have to check 15951 // if we can do this here because lambdas keep return statements around 15952 // to deduce an implicit return type. 15953 if (FD->getReturnType()->isRecordType() && 15954 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 15955 computeNRVO(Body, FSI); 15956 } 15957 15958 // GNU warning -Wmissing-prototypes: 15959 // Warn if a global function is defined without a previous 15960 // prototype declaration. This warning is issued even if the 15961 // definition itself provides a prototype. The aim is to detect 15962 // global functions that fail to be declared in header files. 15963 const FunctionDecl *PossiblePrototype = nullptr; 15964 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 15965 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 15966 15967 if (PossiblePrototype) { 15968 // We found a declaration that is not a prototype, 15969 // but that could be a zero-parameter prototype 15970 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 15971 TypeLoc TL = TI->getTypeLoc(); 15972 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 15973 Diag(PossiblePrototype->getLocation(), 15974 diag::note_declaration_not_a_prototype) 15975 << (FD->getNumParams() != 0) 15976 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( 15977 FTL.getRParenLoc(), "void") 15978 : FixItHint{}); 15979 } 15980 } else { 15981 // Returns true if the token beginning at this Loc is `const`. 15982 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 15983 const LangOptions &LangOpts) { 15984 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 15985 if (LocInfo.first.isInvalid()) 15986 return false; 15987 15988 bool Invalid = false; 15989 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 15990 if (Invalid) 15991 return false; 15992 15993 if (LocInfo.second > Buffer.size()) 15994 return false; 15995 15996 const char *LexStart = Buffer.data() + LocInfo.second; 15997 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 15998 15999 return StartTok.consume_front("const") && 16000 (StartTok.empty() || isWhitespace(StartTok[0]) || 16001 StartTok.starts_with("/*") || StartTok.starts_with("//")); 16002 }; 16003 16004 auto findBeginLoc = [&]() { 16005 // If the return type has `const` qualifier, we want to insert 16006 // `static` before `const` (and not before the typename). 16007 if ((FD->getReturnType()->isAnyPointerType() && 16008 FD->getReturnType()->getPointeeType().isConstQualified()) || 16009 FD->getReturnType().isConstQualified()) { 16010 // But only do this if we can determine where the `const` is. 16011 16012 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 16013 getLangOpts())) 16014 16015 return FD->getBeginLoc(); 16016 } 16017 return FD->getTypeSpecStartLoc(); 16018 }; 16019 Diag(FD->getTypeSpecStartLoc(), 16020 diag::note_static_for_internal_linkage) 16021 << /* function */ 1 16022 << (FD->getStorageClass() == SC_None 16023 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 16024 : FixItHint{}); 16025 } 16026 } 16027 16028 // We might not have found a prototype because we didn't wish to warn on 16029 // the lack of a missing prototype. Try again without the checks for 16030 // whether we want to warn on the missing prototype. 16031 if (!PossiblePrototype) 16032 (void)FindPossiblePrototype(FD, PossiblePrototype); 16033 16034 // If the function being defined does not have a prototype, then we may 16035 // need to diagnose it as changing behavior in C23 because we now know 16036 // whether the function accepts arguments or not. This only handles the 16037 // case where the definition has no prototype but does have parameters 16038 // and either there is no previous potential prototype, or the previous 16039 // potential prototype also has no actual prototype. This handles cases 16040 // like: 16041 // void f(); void f(a) int a; {} 16042 // void g(a) int a; {} 16043 // See MergeFunctionDecl() for other cases of the behavior change 16044 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 16045 // type without a prototype. 16046 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 && 16047 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() && 16048 !PossiblePrototype->isImplicit()))) { 16049 // The function definition has parameters, so this will change behavior 16050 // in C23. If there is a possible prototype, it comes before the 16051 // function definition. 16052 // FIXME: The declaration may have already been diagnosed as being 16053 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but 16054 // there's no way to test for the "changes behavior" condition in 16055 // SemaType.cpp when forming the declaration's function type. So, we do 16056 // this awkward dance instead. 16057 // 16058 // If we have a possible prototype and it declares a function with a 16059 // prototype, we don't want to diagnose it; if we have a possible 16060 // prototype and it has no prototype, it may have already been 16061 // diagnosed in SemaType.cpp as deprecated depending on whether 16062 // -Wstrict-prototypes is enabled. If we already warned about it being 16063 // deprecated, add a note that it also changes behavior. If we didn't 16064 // warn about it being deprecated (because the diagnostic is not 16065 // enabled), warn now that it is deprecated and changes behavior. 16066 16067 // This K&R C function definition definitely changes behavior in C23, 16068 // so diagnose it. 16069 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior) 16070 << /*definition*/ 1 << /* not supported in C23 */ 0; 16071 16072 // If we have a possible prototype for the function which is a user- 16073 // visible declaration, we already tested that it has no prototype. 16074 // This will change behavior in C23. This gets a warning rather than a 16075 // note because it's the same behavior-changing problem as with the 16076 // definition. 16077 if (PossiblePrototype) 16078 Diag(PossiblePrototype->getLocation(), 16079 diag::warn_non_prototype_changes_behavior) 16080 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1 16081 << /*definition*/ 1; 16082 } 16083 16084 // Warn on CPUDispatch with an actual body. 16085 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 16086 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 16087 if (!CmpndBody->body_empty()) 16088 Diag(CmpndBody->body_front()->getBeginLoc(), 16089 diag::warn_dispatch_body_ignored); 16090 16091 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 16092 const CXXMethodDecl *KeyFunction; 16093 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 16094 MD->isVirtual() && 16095 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 16096 MD == KeyFunction->getCanonicalDecl()) { 16097 // Update the key-function state if necessary for this ABI. 16098 if (FD->isInlined() && 16099 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 16100 Context.setNonKeyFunction(MD); 16101 16102 // If the newly-chosen key function is already defined, then we 16103 // need to mark the vtable as used retroactively. 16104 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 16105 const FunctionDecl *Definition; 16106 if (KeyFunction && KeyFunction->isDefined(Definition)) 16107 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 16108 } else { 16109 // We just defined they key function; mark the vtable as used. 16110 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 16111 } 16112 } 16113 } 16114 16115 assert( 16116 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 16117 "Function parsing confused"); 16118 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 16119 assert(MD == getCurMethodDecl() && "Method parsing confused"); 16120 MD->setBody(Body); 16121 if (!MD->isInvalidDecl()) { 16122 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 16123 MD->getReturnType(), MD); 16124 16125 if (Body) 16126 computeNRVO(Body, FSI); 16127 } 16128 if (FSI->ObjCShouldCallSuper) { 16129 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 16130 << MD->getSelector().getAsString(); 16131 FSI->ObjCShouldCallSuper = false; 16132 } 16133 if (FSI->ObjCWarnForNoDesignatedInitChain) { 16134 const ObjCMethodDecl *InitMethod = nullptr; 16135 bool isDesignated = 16136 MD->isDesignatedInitializerForTheInterface(&InitMethod); 16137 assert(isDesignated && InitMethod); 16138 (void)isDesignated; 16139 16140 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 16141 auto IFace = MD->getClassInterface(); 16142 if (!IFace) 16143 return false; 16144 auto SuperD = IFace->getSuperClass(); 16145 if (!SuperD) 16146 return false; 16147 return SuperD->getIdentifier() == 16148 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 16149 }; 16150 // Don't issue this warning for unavailable inits or direct subclasses 16151 // of NSObject. 16152 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 16153 Diag(MD->getLocation(), 16154 diag::warn_objc_designated_init_missing_super_call); 16155 Diag(InitMethod->getLocation(), 16156 diag::note_objc_designated_init_marked_here); 16157 } 16158 FSI->ObjCWarnForNoDesignatedInitChain = false; 16159 } 16160 if (FSI->ObjCWarnForNoInitDelegation) { 16161 // Don't issue this warning for unavaialable inits. 16162 if (!MD->isUnavailable()) 16163 Diag(MD->getLocation(), 16164 diag::warn_objc_secondary_init_missing_init_call); 16165 FSI->ObjCWarnForNoInitDelegation = false; 16166 } 16167 16168 diagnoseImplicitlyRetainedSelf(*this); 16169 } else { 16170 // Parsing the function declaration failed in some way. Pop the fake scope 16171 // we pushed on. 16172 PopFunctionScopeInfo(ActivePolicy, dcl); 16173 return nullptr; 16174 } 16175 16176 if (Body && FSI->HasPotentialAvailabilityViolations) 16177 DiagnoseUnguardedAvailabilityViolations(dcl); 16178 16179 assert(!FSI->ObjCShouldCallSuper && 16180 "This should only be set for ObjC methods, which should have been " 16181 "handled in the block above."); 16182 16183 // Verify and clean out per-function state. 16184 if (Body && (!FD || !FD->isDefaulted())) { 16185 // C++ constructors that have function-try-blocks can't have return 16186 // statements in the handlers of that block. (C++ [except.handle]p14) 16187 // Verify this. 16188 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 16189 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 16190 16191 // Verify that gotos and switch cases don't jump into scopes illegally. 16192 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) 16193 DiagnoseInvalidJumps(Body); 16194 16195 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 16196 if (!Destructor->getParent()->isDependentType()) 16197 CheckDestructor(Destructor); 16198 16199 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 16200 Destructor->getParent()); 16201 } 16202 16203 // If any errors have occurred, clear out any temporaries that may have 16204 // been leftover. This ensures that these temporaries won't be picked up 16205 // for deletion in some later function. 16206 if (hasUncompilableErrorOccurred() || 16207 hasAnyUnrecoverableErrorsInThisFunction() || 16208 getDiagnostics().getSuppressAllDiagnostics()) { 16209 DiscardCleanupsInEvaluationContext(); 16210 } 16211 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { 16212 // Since the body is valid, issue any analysis-based warnings that are 16213 // enabled. 16214 ActivePolicy = &WP; 16215 } 16216 16217 if (!IsInstantiation && FD && 16218 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) && 16219 !FD->isInvalidDecl() && 16220 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 16221 FD->setInvalidDecl(); 16222 16223 if (FD && FD->hasAttr<NakedAttr>()) { 16224 for (const Stmt *S : Body->children()) { 16225 // Allow local register variables without initializer as they don't 16226 // require prologue. 16227 bool RegisterVariables = false; 16228 if (auto *DS = dyn_cast<DeclStmt>(S)) { 16229 for (const auto *Decl : DS->decls()) { 16230 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 16231 RegisterVariables = 16232 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 16233 if (!RegisterVariables) 16234 break; 16235 } 16236 } 16237 } 16238 if (RegisterVariables) 16239 continue; 16240 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 16241 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 16242 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 16243 FD->setInvalidDecl(); 16244 break; 16245 } 16246 } 16247 } 16248 16249 assert(ExprCleanupObjects.size() == 16250 ExprEvalContexts.back().NumCleanupObjects && 16251 "Leftover temporaries in function"); 16252 assert(!Cleanup.exprNeedsCleanups() && 16253 "Unaccounted cleanups in function"); 16254 assert(MaybeODRUseExprs.empty() && 16255 "Leftover expressions for odr-use checking"); 16256 } 16257 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop 16258 // the declaration context below. Otherwise, we're unable to transform 16259 // 'this' expressions when transforming immediate context functions. 16260 16261 if (!IsInstantiation) 16262 PopDeclContext(); 16263 16264 PopFunctionScopeInfo(ActivePolicy, dcl); 16265 // If any errors have occurred, clear out any temporaries that may have 16266 // been leftover. This ensures that these temporaries won't be picked up for 16267 // deletion in some later function. 16268 if (hasUncompilableErrorOccurred()) { 16269 DiscardCleanupsInEvaluationContext(); 16270 } 16271 16272 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice || 16273 !LangOpts.OMPTargetTriples.empty())) || 16274 LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 16275 auto ES = getEmissionStatus(FD); 16276 if (ES == Sema::FunctionEmissionStatus::Emitted || 16277 ES == Sema::FunctionEmissionStatus::Unknown) 16278 DeclsToCheckForDeferredDiags.insert(FD); 16279 } 16280 16281 if (FD && !FD->isDeleted()) 16282 checkTypeSupport(FD->getType(), FD->getLocation(), FD); 16283 16284 return dcl; 16285 } 16286 16287 /// When we finish delayed parsing of an attribute, we must attach it to the 16288 /// relevant Decl. 16289 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 16290 ParsedAttributes &Attrs) { 16291 // Always attach attributes to the underlying decl. 16292 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 16293 D = TD->getTemplatedDecl(); 16294 ProcessDeclAttributeList(S, D, Attrs); 16295 16296 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 16297 if (Method->isStatic()) 16298 checkThisInStaticMemberFunctionAttributes(Method); 16299 } 16300 16301 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 16302 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 16303 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 16304 IdentifierInfo &II, Scope *S) { 16305 // It is not valid to implicitly define a function in C23. 16306 assert(LangOpts.implicitFunctionsAllowed() && 16307 "Implicit function declarations aren't allowed in this language mode"); 16308 16309 // Find the scope in which the identifier is injected and the corresponding 16310 // DeclContext. 16311 // FIXME: C89 does not say what happens if there is no enclosing block scope. 16312 // In that case, we inject the declaration into the translation unit scope 16313 // instead. 16314 Scope *BlockScope = S; 16315 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 16316 BlockScope = BlockScope->getParent(); 16317 16318 // Loop until we find a DeclContext that is either a function/method or the 16319 // translation unit, which are the only two valid places to implicitly define 16320 // a function. This avoids accidentally defining the function within a tag 16321 // declaration, for example. 16322 Scope *ContextScope = BlockScope; 16323 while (!ContextScope->getEntity() || 16324 (!ContextScope->getEntity()->isFunctionOrMethod() && 16325 !ContextScope->getEntity()->isTranslationUnit())) 16326 ContextScope = ContextScope->getParent(); 16327 ContextRAII SavedContext(*this, ContextScope->getEntity()); 16328 16329 // Before we produce a declaration for an implicitly defined 16330 // function, see whether there was a locally-scoped declaration of 16331 // this name as a function or variable. If so, use that 16332 // (non-visible) declaration, and complain about it. 16333 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 16334 if (ExternCPrev) { 16335 // We still need to inject the function into the enclosing block scope so 16336 // that later (non-call) uses can see it. 16337 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 16338 16339 // C89 footnote 38: 16340 // If in fact it is not defined as having type "function returning int", 16341 // the behavior is undefined. 16342 if (!isa<FunctionDecl>(ExternCPrev) || 16343 !Context.typesAreCompatible( 16344 cast<FunctionDecl>(ExternCPrev)->getType(), 16345 Context.getFunctionNoProtoType(Context.IntTy))) { 16346 Diag(Loc, diag::ext_use_out_of_scope_declaration) 16347 << ExternCPrev << !getLangOpts().C99; 16348 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 16349 return ExternCPrev; 16350 } 16351 } 16352 16353 // Extension in C99 (defaults to error). Legal in C89, but warn about it. 16354 unsigned diag_id; 16355 if (II.getName().starts_with("__builtin_")) 16356 diag_id = diag::warn_builtin_unknown; 16357 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 16358 else if (getLangOpts().C99) 16359 diag_id = diag::ext_implicit_function_decl_c99; 16360 else 16361 diag_id = diag::warn_implicit_function_decl; 16362 16363 TypoCorrection Corrected; 16364 // Because typo correction is expensive, only do it if the implicit 16365 // function declaration is going to be treated as an error. 16366 // 16367 // Perform the correction before issuing the main diagnostic, as some 16368 // consumers use typo-correction callbacks to enhance the main diagnostic. 16369 if (S && !ExternCPrev && 16370 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) { 16371 DeclFilterCCC<FunctionDecl> CCC{}; 16372 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 16373 S, nullptr, CCC, CTK_NonError); 16374 } 16375 16376 Diag(Loc, diag_id) << &II; 16377 if (Corrected) { 16378 // If the correction is going to suggest an implicitly defined function, 16379 // skip the correction as not being a particularly good idea. 16380 bool Diagnose = true; 16381 if (const auto *D = Corrected.getCorrectionDecl()) 16382 Diagnose = !D->isImplicit(); 16383 if (Diagnose) 16384 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 16385 /*ErrorRecovery*/ false); 16386 } 16387 16388 // If we found a prior declaration of this function, don't bother building 16389 // another one. We've already pushed that one into scope, so there's nothing 16390 // more to do. 16391 if (ExternCPrev) 16392 return ExternCPrev; 16393 16394 // Set a Declarator for the implicit definition: int foo(); 16395 const char *Dummy; 16396 AttributeFactory attrFactory; 16397 DeclSpec DS(attrFactory); 16398 unsigned DiagID; 16399 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 16400 Context.getPrintingPolicy()); 16401 (void)Error; // Silence warning. 16402 assert(!Error && "Error setting up implicit decl!"); 16403 SourceLocation NoLoc; 16404 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block); 16405 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 16406 /*IsAmbiguous=*/false, 16407 /*LParenLoc=*/NoLoc, 16408 /*Params=*/nullptr, 16409 /*NumParams=*/0, 16410 /*EllipsisLoc=*/NoLoc, 16411 /*RParenLoc=*/NoLoc, 16412 /*RefQualifierIsLvalueRef=*/true, 16413 /*RefQualifierLoc=*/NoLoc, 16414 /*MutableLoc=*/NoLoc, EST_None, 16415 /*ESpecRange=*/SourceRange(), 16416 /*Exceptions=*/nullptr, 16417 /*ExceptionRanges=*/nullptr, 16418 /*NumExceptions=*/0, 16419 /*NoexceptExpr=*/nullptr, 16420 /*ExceptionSpecTokens=*/nullptr, 16421 /*DeclsInPrototype=*/std::nullopt, 16422 Loc, Loc, D), 16423 std::move(DS.getAttributes()), SourceLocation()); 16424 D.SetIdentifier(&II, Loc); 16425 16426 // Insert this function into the enclosing block scope. 16427 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 16428 FD->setImplicit(); 16429 16430 AddKnownFunctionAttributes(FD); 16431 16432 return FD; 16433 } 16434 16435 /// If this function is a C++ replaceable global allocation function 16436 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 16437 /// adds any function attributes that we know a priori based on the standard. 16438 /// 16439 /// We need to check for duplicate attributes both here and where user-written 16440 /// attributes are applied to declarations. 16441 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 16442 FunctionDecl *FD) { 16443 if (FD->isInvalidDecl()) 16444 return; 16445 16446 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 16447 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 16448 return; 16449 16450 std::optional<unsigned> AlignmentParam; 16451 bool IsNothrow = false; 16452 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 16453 return; 16454 16455 // C++2a [basic.stc.dynamic.allocation]p4: 16456 // An allocation function that has a non-throwing exception specification 16457 // indicates failure by returning a null pointer value. Any other allocation 16458 // function never returns a null pointer value and indicates failure only by 16459 // throwing an exception [...] 16460 // 16461 // However, -fcheck-new invalidates this possible assumption, so don't add 16462 // NonNull when that is enabled. 16463 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() && 16464 !getLangOpts().CheckNew) 16465 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 16466 16467 // C++2a [basic.stc.dynamic.allocation]p2: 16468 // An allocation function attempts to allocate the requested amount of 16469 // storage. [...] If the request succeeds, the value returned by a 16470 // replaceable allocation function is a [...] pointer value p0 different 16471 // from any previously returned value p1 [...] 16472 // 16473 // However, this particular information is being added in codegen, 16474 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 16475 16476 // C++2a [basic.stc.dynamic.allocation]p2: 16477 // An allocation function attempts to allocate the requested amount of 16478 // storage. If it is successful, it returns the address of the start of a 16479 // block of storage whose length in bytes is at least as large as the 16480 // requested size. 16481 if (!FD->hasAttr<AllocSizeAttr>()) { 16482 FD->addAttr(AllocSizeAttr::CreateImplicit( 16483 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 16484 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 16485 } 16486 16487 // C++2a [basic.stc.dynamic.allocation]p3: 16488 // For an allocation function [...], the pointer returned on a successful 16489 // call shall represent the address of storage that is aligned as follows: 16490 // (3.1) If the allocation function takes an argument of type 16491 // std::align_val_t, the storage will have the alignment 16492 // specified by the value of this argument. 16493 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) { 16494 FD->addAttr(AllocAlignAttr::CreateImplicit( 16495 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation())); 16496 } 16497 16498 // FIXME: 16499 // C++2a [basic.stc.dynamic.allocation]p3: 16500 // For an allocation function [...], the pointer returned on a successful 16501 // call shall represent the address of storage that is aligned as follows: 16502 // (3.2) Otherwise, if the allocation function is named operator new[], 16503 // the storage is aligned for any object that does not have 16504 // new-extended alignment ([basic.align]) and is no larger than the 16505 // requested size. 16506 // (3.3) Otherwise, the storage is aligned for any object that does not 16507 // have new-extended alignment and is of the requested size. 16508 } 16509 16510 /// Adds any function attributes that we know a priori based on 16511 /// the declaration of this function. 16512 /// 16513 /// These attributes can apply both to implicitly-declared builtins 16514 /// (like __builtin___printf_chk) or to library-declared functions 16515 /// like NSLog or printf. 16516 /// 16517 /// We need to check for duplicate attributes both here and where user-written 16518 /// attributes are applied to declarations. 16519 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 16520 if (FD->isInvalidDecl()) 16521 return; 16522 16523 // If this is a built-in function, map its builtin attributes to 16524 // actual attributes. 16525 if (unsigned BuiltinID = FD->getBuiltinID()) { 16526 // Handle printf-formatting attributes. 16527 unsigned FormatIdx; 16528 bool HasVAListArg; 16529 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 16530 if (!FD->hasAttr<FormatAttr>()) { 16531 const char *fmt = "printf"; 16532 unsigned int NumParams = FD->getNumParams(); 16533 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 16534 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 16535 fmt = "NSString"; 16536 FD->addAttr(FormatAttr::CreateImplicit(Context, 16537 &Context.Idents.get(fmt), 16538 FormatIdx+1, 16539 HasVAListArg ? 0 : FormatIdx+2, 16540 FD->getLocation())); 16541 } 16542 } 16543 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 16544 HasVAListArg)) { 16545 if (!FD->hasAttr<FormatAttr>()) 16546 FD->addAttr(FormatAttr::CreateImplicit(Context, 16547 &Context.Idents.get("scanf"), 16548 FormatIdx+1, 16549 HasVAListArg ? 0 : FormatIdx+2, 16550 FD->getLocation())); 16551 } 16552 16553 // Handle automatically recognized callbacks. 16554 SmallVector<int, 4> Encoding; 16555 if (!FD->hasAttr<CallbackAttr>() && 16556 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 16557 FD->addAttr(CallbackAttr::CreateImplicit( 16558 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 16559 16560 // Mark const if we don't care about errno and/or floating point exceptions 16561 // that are the only thing preventing the function from being const. This 16562 // allows IRgen to use LLVM intrinsics for such functions. 16563 bool NoExceptions = 16564 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore; 16565 bool ConstWithoutErrnoAndExceptions = 16566 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID); 16567 bool ConstWithoutExceptions = 16568 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID); 16569 if (!FD->hasAttr<ConstAttr>() && 16570 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) && 16571 (!ConstWithoutErrnoAndExceptions || 16572 (!getLangOpts().MathErrno && NoExceptions)) && 16573 (!ConstWithoutExceptions || NoExceptions)) 16574 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 16575 16576 // We make "fma" on GNU or Windows const because we know it does not set 16577 // errno in those environments even though it could set errno based on the 16578 // C standard. 16579 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 16580 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) && 16581 !FD->hasAttr<ConstAttr>()) { 16582 switch (BuiltinID) { 16583 case Builtin::BI__builtin_fma: 16584 case Builtin::BI__builtin_fmaf: 16585 case Builtin::BI__builtin_fmal: 16586 case Builtin::BIfma: 16587 case Builtin::BIfmaf: 16588 case Builtin::BIfmal: 16589 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 16590 break; 16591 default: 16592 break; 16593 } 16594 } 16595 16596 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 16597 !FD->hasAttr<ReturnsTwiceAttr>()) 16598 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 16599 FD->getLocation())); 16600 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 16601 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 16602 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 16603 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 16604 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 16605 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 16606 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 16607 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 16608 // Add the appropriate attribute, depending on the CUDA compilation mode 16609 // and which target the builtin belongs to. For example, during host 16610 // compilation, aux builtins are __device__, while the rest are __host__. 16611 if (getLangOpts().CUDAIsDevice != 16612 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 16613 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 16614 else 16615 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 16616 } 16617 16618 // Add known guaranteed alignment for allocation functions. 16619 switch (BuiltinID) { 16620 case Builtin::BImemalign: 16621 case Builtin::BIaligned_alloc: 16622 if (!FD->hasAttr<AllocAlignAttr>()) 16623 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 16624 FD->getLocation())); 16625 break; 16626 default: 16627 break; 16628 } 16629 16630 // Add allocsize attribute for allocation functions. 16631 switch (BuiltinID) { 16632 case Builtin::BIcalloc: 16633 FD->addAttr(AllocSizeAttr::CreateImplicit( 16634 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation())); 16635 break; 16636 case Builtin::BImemalign: 16637 case Builtin::BIaligned_alloc: 16638 case Builtin::BIrealloc: 16639 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD), 16640 ParamIdx(), FD->getLocation())); 16641 break; 16642 case Builtin::BImalloc: 16643 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD), 16644 ParamIdx(), FD->getLocation())); 16645 break; 16646 default: 16647 break; 16648 } 16649 16650 // Add lifetime attribute to std::move, std::fowrard et al. 16651 switch (BuiltinID) { 16652 case Builtin::BIaddressof: 16653 case Builtin::BI__addressof: 16654 case Builtin::BI__builtin_addressof: 16655 case Builtin::BIas_const: 16656 case Builtin::BIforward: 16657 case Builtin::BIforward_like: 16658 case Builtin::BImove: 16659 case Builtin::BImove_if_noexcept: 16660 if (ParmVarDecl *P = FD->getParamDecl(0u); 16661 !P->hasAttr<LifetimeBoundAttr>()) 16662 P->addAttr( 16663 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation())); 16664 break; 16665 default: 16666 break; 16667 } 16668 } 16669 16670 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 16671 16672 // If C++ exceptions are enabled but we are told extern "C" functions cannot 16673 // throw, add an implicit nothrow attribute to any extern "C" function we come 16674 // across. 16675 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 16676 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 16677 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 16678 if (!FPT || FPT->getExceptionSpecType() == EST_None) 16679 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 16680 } 16681 16682 IdentifierInfo *Name = FD->getIdentifier(); 16683 if (!Name) 16684 return; 16685 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) || 16686 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 16687 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 16688 LinkageSpecLanguageIDs::C)) { 16689 // Okay: this could be a libc/libm/Objective-C function we know 16690 // about. 16691 } else 16692 return; 16693 16694 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 16695 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 16696 // target-specific builtins, perhaps? 16697 if (!FD->hasAttr<FormatAttr>()) 16698 FD->addAttr(FormatAttr::CreateImplicit(Context, 16699 &Context.Idents.get("printf"), 2, 16700 Name->isStr("vasprintf") ? 0 : 3, 16701 FD->getLocation())); 16702 } 16703 16704 if (Name->isStr("__CFStringMakeConstantString")) { 16705 // We already have a __builtin___CFStringMakeConstantString, 16706 // but builds that use -fno-constant-cfstrings don't go through that. 16707 if (!FD->hasAttr<FormatArgAttr>()) 16708 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 16709 FD->getLocation())); 16710 } 16711 } 16712 16713 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 16714 TypeSourceInfo *TInfo) { 16715 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 16716 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 16717 16718 if (!TInfo) { 16719 assert(D.isInvalidType() && "no declarator info for valid type"); 16720 TInfo = Context.getTrivialTypeSourceInfo(T); 16721 } 16722 16723 // Scope manipulation handled by caller. 16724 TypedefDecl *NewTD = 16725 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 16726 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 16727 16728 // Bail out immediately if we have an invalid declaration. 16729 if (D.isInvalidType()) { 16730 NewTD->setInvalidDecl(); 16731 return NewTD; 16732 } 16733 16734 if (D.getDeclSpec().isModulePrivateSpecified()) { 16735 if (CurContext->isFunctionOrMethod()) 16736 Diag(NewTD->getLocation(), diag::err_module_private_local) 16737 << 2 << NewTD 16738 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 16739 << FixItHint::CreateRemoval( 16740 D.getDeclSpec().getModulePrivateSpecLoc()); 16741 else 16742 NewTD->setModulePrivate(); 16743 } 16744 16745 // C++ [dcl.typedef]p8: 16746 // If the typedef declaration defines an unnamed class (or 16747 // enum), the first typedef-name declared by the declaration 16748 // to be that class type (or enum type) is used to denote the 16749 // class type (or enum type) for linkage purposes only. 16750 // We need to check whether the type was declared in the declaration. 16751 switch (D.getDeclSpec().getTypeSpecType()) { 16752 case TST_enum: 16753 case TST_struct: 16754 case TST_interface: 16755 case TST_union: 16756 case TST_class: { 16757 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 16758 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 16759 break; 16760 } 16761 16762 default: 16763 break; 16764 } 16765 16766 return NewTD; 16767 } 16768 16769 /// Check that this is a valid underlying type for an enum declaration. 16770 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 16771 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 16772 QualType T = TI->getType(); 16773 16774 if (T->isDependentType()) 16775 return false; 16776 16777 // This doesn't use 'isIntegralType' despite the error message mentioning 16778 // integral type because isIntegralType would also allow enum types in C. 16779 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 16780 if (BT->isInteger()) 16781 return false; 16782 16783 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) 16784 << T << T->isBitIntType(); 16785 } 16786 16787 /// Check whether this is a valid redeclaration of a previous enumeration. 16788 /// \return true if the redeclaration was invalid. 16789 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 16790 QualType EnumUnderlyingTy, bool IsFixed, 16791 const EnumDecl *Prev) { 16792 if (IsScoped != Prev->isScoped()) { 16793 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 16794 << Prev->isScoped(); 16795 Diag(Prev->getLocation(), diag::note_previous_declaration); 16796 return true; 16797 } 16798 16799 if (IsFixed && Prev->isFixed()) { 16800 if (!EnumUnderlyingTy->isDependentType() && 16801 !Prev->getIntegerType()->isDependentType() && 16802 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 16803 Prev->getIntegerType())) { 16804 // TODO: Highlight the underlying type of the redeclaration. 16805 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 16806 << EnumUnderlyingTy << Prev->getIntegerType(); 16807 Diag(Prev->getLocation(), diag::note_previous_declaration) 16808 << Prev->getIntegerTypeRange(); 16809 return true; 16810 } 16811 } else if (IsFixed != Prev->isFixed()) { 16812 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 16813 << Prev->isFixed(); 16814 Diag(Prev->getLocation(), diag::note_previous_declaration); 16815 return true; 16816 } 16817 16818 return false; 16819 } 16820 16821 /// Get diagnostic %select index for tag kind for 16822 /// redeclaration diagnostic message. 16823 /// WARNING: Indexes apply to particular diagnostics only! 16824 /// 16825 /// \returns diagnostic %select index. 16826 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 16827 switch (Tag) { 16828 case TagTypeKind::Struct: 16829 return 0; 16830 case TagTypeKind::Interface: 16831 return 1; 16832 case TagTypeKind::Class: 16833 return 2; 16834 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 16835 } 16836 } 16837 16838 /// Determine if tag kind is a class-key compatible with 16839 /// class for redeclaration (class, struct, or __interface). 16840 /// 16841 /// \returns true iff the tag kind is compatible. 16842 static bool isClassCompatTagKind(TagTypeKind Tag) 16843 { 16844 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class || 16845 Tag == TagTypeKind::Interface; 16846 } 16847 16848 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 16849 TagTypeKind TTK) { 16850 if (isa<TypedefDecl>(PrevDecl)) 16851 return NTK_Typedef; 16852 else if (isa<TypeAliasDecl>(PrevDecl)) 16853 return NTK_TypeAlias; 16854 else if (isa<ClassTemplateDecl>(PrevDecl)) 16855 return NTK_Template; 16856 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 16857 return NTK_TypeAliasTemplate; 16858 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 16859 return NTK_TemplateTemplateArgument; 16860 switch (TTK) { 16861 case TagTypeKind::Struct: 16862 case TagTypeKind::Interface: 16863 case TagTypeKind::Class: 16864 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 16865 case TagTypeKind::Union: 16866 return NTK_NonUnion; 16867 case TagTypeKind::Enum: 16868 return NTK_NonEnum; 16869 } 16870 llvm_unreachable("invalid TTK"); 16871 } 16872 16873 /// Determine whether a tag with a given kind is acceptable 16874 /// as a redeclaration of the given tag declaration. 16875 /// 16876 /// \returns true if the new tag kind is acceptable, false otherwise. 16877 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 16878 TagTypeKind NewTag, bool isDefinition, 16879 SourceLocation NewTagLoc, 16880 const IdentifierInfo *Name) { 16881 // C++ [dcl.type.elab]p3: 16882 // The class-key or enum keyword present in the 16883 // elaborated-type-specifier shall agree in kind with the 16884 // declaration to which the name in the elaborated-type-specifier 16885 // refers. This rule also applies to the form of 16886 // elaborated-type-specifier that declares a class-name or 16887 // friend class since it can be construed as referring to the 16888 // definition of the class. Thus, in any 16889 // elaborated-type-specifier, the enum keyword shall be used to 16890 // refer to an enumeration (7.2), the union class-key shall be 16891 // used to refer to a union (clause 9), and either the class or 16892 // struct class-key shall be used to refer to a class (clause 9) 16893 // declared using the class or struct class-key. 16894 TagTypeKind OldTag = Previous->getTagKind(); 16895 if (OldTag != NewTag && 16896 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 16897 return false; 16898 16899 // Tags are compatible, but we might still want to warn on mismatched tags. 16900 // Non-class tags can't be mismatched at this point. 16901 if (!isClassCompatTagKind(NewTag)) 16902 return true; 16903 16904 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 16905 // by our warning analysis. We don't want to warn about mismatches with (eg) 16906 // declarations in system headers that are designed to be specialized, but if 16907 // a user asks us to warn, we should warn if their code contains mismatched 16908 // declarations. 16909 auto IsIgnoredLoc = [&](SourceLocation Loc) { 16910 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 16911 Loc); 16912 }; 16913 if (IsIgnoredLoc(NewTagLoc)) 16914 return true; 16915 16916 auto IsIgnored = [&](const TagDecl *Tag) { 16917 return IsIgnoredLoc(Tag->getLocation()); 16918 }; 16919 while (IsIgnored(Previous)) { 16920 Previous = Previous->getPreviousDecl(); 16921 if (!Previous) 16922 return true; 16923 OldTag = Previous->getTagKind(); 16924 } 16925 16926 bool isTemplate = false; 16927 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 16928 isTemplate = Record->getDescribedClassTemplate(); 16929 16930 if (inTemplateInstantiation()) { 16931 if (OldTag != NewTag) { 16932 // In a template instantiation, do not offer fix-its for tag mismatches 16933 // since they usually mess up the template instead of fixing the problem. 16934 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 16935 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 16936 << getRedeclDiagFromTagKind(OldTag); 16937 // FIXME: Note previous location? 16938 } 16939 return true; 16940 } 16941 16942 if (isDefinition) { 16943 // On definitions, check all previous tags and issue a fix-it for each 16944 // one that doesn't match the current tag. 16945 if (Previous->getDefinition()) { 16946 // Don't suggest fix-its for redefinitions. 16947 return true; 16948 } 16949 16950 bool previousMismatch = false; 16951 for (const TagDecl *I : Previous->redecls()) { 16952 if (I->getTagKind() != NewTag) { 16953 // Ignore previous declarations for which the warning was disabled. 16954 if (IsIgnored(I)) 16955 continue; 16956 16957 if (!previousMismatch) { 16958 previousMismatch = true; 16959 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 16960 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 16961 << getRedeclDiagFromTagKind(I->getTagKind()); 16962 } 16963 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 16964 << getRedeclDiagFromTagKind(NewTag) 16965 << FixItHint::CreateReplacement(I->getInnerLocStart(), 16966 TypeWithKeyword::getTagTypeKindName(NewTag)); 16967 } 16968 } 16969 return true; 16970 } 16971 16972 // Identify the prevailing tag kind: this is the kind of the definition (if 16973 // there is a non-ignored definition), or otherwise the kind of the prior 16974 // (non-ignored) declaration. 16975 const TagDecl *PrevDef = Previous->getDefinition(); 16976 if (PrevDef && IsIgnored(PrevDef)) 16977 PrevDef = nullptr; 16978 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 16979 if (Redecl->getTagKind() != NewTag) { 16980 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 16981 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 16982 << getRedeclDiagFromTagKind(OldTag); 16983 Diag(Redecl->getLocation(), diag::note_previous_use); 16984 16985 // If there is a previous definition, suggest a fix-it. 16986 if (PrevDef) { 16987 Diag(NewTagLoc, diag::note_struct_class_suggestion) 16988 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 16989 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 16990 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 16991 } 16992 } 16993 16994 return true; 16995 } 16996 16997 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 16998 /// from an outer enclosing namespace or file scope inside a friend declaration. 16999 /// This should provide the commented out code in the following snippet: 17000 /// namespace N { 17001 /// struct X; 17002 /// namespace M { 17003 /// struct Y { friend struct /*N::*/ X; }; 17004 /// } 17005 /// } 17006 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 17007 SourceLocation NameLoc) { 17008 // While the decl is in a namespace, do repeated lookup of that name and see 17009 // if we get the same namespace back. If we do not, continue until 17010 // translation unit scope, at which point we have a fully qualified NNS. 17011 SmallVector<IdentifierInfo *, 4> Namespaces; 17012 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 17013 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 17014 // This tag should be declared in a namespace, which can only be enclosed by 17015 // other namespaces. Bail if there's an anonymous namespace in the chain. 17016 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 17017 if (!Namespace || Namespace->isAnonymousNamespace()) 17018 return FixItHint(); 17019 IdentifierInfo *II = Namespace->getIdentifier(); 17020 Namespaces.push_back(II); 17021 NamedDecl *Lookup = SemaRef.LookupSingleName( 17022 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 17023 if (Lookup == Namespace) 17024 break; 17025 } 17026 17027 // Once we have all the namespaces, reverse them to go outermost first, and 17028 // build an NNS. 17029 SmallString<64> Insertion; 17030 llvm::raw_svector_ostream OS(Insertion); 17031 if (DC->isTranslationUnit()) 17032 OS << "::"; 17033 std::reverse(Namespaces.begin(), Namespaces.end()); 17034 for (auto *II : Namespaces) 17035 OS << II->getName() << "::"; 17036 return FixItHint::CreateInsertion(NameLoc, Insertion); 17037 } 17038 17039 /// Determine whether a tag originally declared in context \p OldDC can 17040 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 17041 /// found a declaration in \p OldDC as a previous decl, perhaps through a 17042 /// using-declaration). 17043 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 17044 DeclContext *NewDC) { 17045 OldDC = OldDC->getRedeclContext(); 17046 NewDC = NewDC->getRedeclContext(); 17047 17048 if (OldDC->Equals(NewDC)) 17049 return true; 17050 17051 // In MSVC mode, we allow a redeclaration if the contexts are related (either 17052 // encloses the other). 17053 if (S.getLangOpts().MSVCCompat && 17054 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 17055 return true; 17056 17057 return false; 17058 } 17059 17060 /// This is invoked when we see 'struct foo' or 'struct {'. In the 17061 /// former case, Name will be non-null. In the later case, Name will be null. 17062 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 17063 /// reference/declaration/definition of a tag. 17064 /// 17065 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 17066 /// trailing-type-specifier) other than one in an alias-declaration. 17067 /// 17068 /// \param SkipBody If non-null, will be set to indicate if the caller should 17069 /// skip the definition of this tag and treat it as if it were a declaration. 17070 DeclResult 17071 Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 17072 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, 17073 const ParsedAttributesView &Attrs, AccessSpecifier AS, 17074 SourceLocation ModulePrivateLoc, 17075 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, 17076 bool &IsDependent, SourceLocation ScopedEnumKWLoc, 17077 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 17078 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 17079 OffsetOfKind OOK, SkipBodyInfo *SkipBody) { 17080 // If this is not a definition, it must have a name. 17081 IdentifierInfo *OrigName = Name; 17082 assert((Name != nullptr || TUK == TUK_Definition) && 17083 "Nameless record must be a definition!"); 17084 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 17085 17086 OwnedDecl = false; 17087 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 17088 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 17089 17090 // FIXME: Check member specializations more carefully. 17091 bool isMemberSpecialization = false; 17092 bool Invalid = false; 17093 17094 // We only need to do this matching if we have template parameters 17095 // or a scope specifier, which also conveniently avoids this work 17096 // for non-C++ cases. 17097 if (TemplateParameterLists.size() > 0 || 17098 (SS.isNotEmpty() && TUK != TUK_Reference)) { 17099 if (TemplateParameterList *TemplateParams = 17100 MatchTemplateParametersToScopeSpecifier( 17101 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 17102 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 17103 if (Kind == TagTypeKind::Enum) { 17104 Diag(KWLoc, diag::err_enum_template); 17105 return true; 17106 } 17107 17108 if (TemplateParams->size() > 0) { 17109 // This is a declaration or definition of a class template (which may 17110 // be a member of another template). 17111 17112 if (Invalid) 17113 return true; 17114 17115 OwnedDecl = false; 17116 DeclResult Result = CheckClassTemplate( 17117 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 17118 AS, ModulePrivateLoc, 17119 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 17120 TemplateParameterLists.data(), SkipBody); 17121 return Result.get(); 17122 } else { 17123 // The "template<>" header is extraneous. 17124 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 17125 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 17126 isMemberSpecialization = true; 17127 } 17128 } 17129 17130 if (!TemplateParameterLists.empty() && isMemberSpecialization && 17131 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 17132 return true; 17133 } 17134 17135 // Figure out the underlying type if this a enum declaration. We need to do 17136 // this early, because it's needed to detect if this is an incompatible 17137 // redeclaration. 17138 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 17139 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 17140 17141 if (Kind == TagTypeKind::Enum) { 17142 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 17143 // No underlying type explicitly specified, or we failed to parse the 17144 // type, default to int. 17145 EnumUnderlying = Context.IntTy.getTypePtr(); 17146 } else if (UnderlyingType.get()) { 17147 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 17148 // integral type; any cv-qualification is ignored. 17149 TypeSourceInfo *TI = nullptr; 17150 GetTypeFromParser(UnderlyingType.get(), &TI); 17151 EnumUnderlying = TI; 17152 17153 if (CheckEnumUnderlyingType(TI)) 17154 // Recover by falling back to int. 17155 EnumUnderlying = Context.IntTy.getTypePtr(); 17156 17157 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 17158 UPPC_FixedUnderlyingType)) 17159 EnumUnderlying = Context.IntTy.getTypePtr(); 17160 17161 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 17162 // For MSVC ABI compatibility, unfixed enums must use an underlying type 17163 // of 'int'. However, if this is an unfixed forward declaration, don't set 17164 // the underlying type unless the user enables -fms-compatibility. This 17165 // makes unfixed forward declared enums incomplete and is more conforming. 17166 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 17167 EnumUnderlying = Context.IntTy.getTypePtr(); 17168 } 17169 } 17170 17171 DeclContext *SearchDC = CurContext; 17172 DeclContext *DC = CurContext; 17173 bool isStdBadAlloc = false; 17174 bool isStdAlignValT = false; 17175 17176 RedeclarationKind Redecl = forRedeclarationInCurContext(); 17177 if (TUK == TUK_Friend || TUK == TUK_Reference) 17178 Redecl = NotForRedeclaration; 17179 17180 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 17181 /// implemented asks for structural equivalence checking, the returned decl 17182 /// here is passed back to the parser, allowing the tag body to be parsed. 17183 auto createTagFromNewDecl = [&]() -> TagDecl * { 17184 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 17185 // If there is an identifier, use the location of the identifier as the 17186 // location of the decl, otherwise use the location of the struct/union 17187 // keyword. 17188 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 17189 TagDecl *New = nullptr; 17190 17191 if (Kind == TagTypeKind::Enum) { 17192 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 17193 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 17194 // If this is an undefined enum, bail. 17195 if (TUK != TUK_Definition && !Invalid) 17196 return nullptr; 17197 if (EnumUnderlying) { 17198 EnumDecl *ED = cast<EnumDecl>(New); 17199 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 17200 ED->setIntegerTypeSourceInfo(TI); 17201 else 17202 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 17203 QualType EnumTy = ED->getIntegerType(); 17204 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy) 17205 ? Context.getPromotedIntegerType(EnumTy) 17206 : EnumTy); 17207 } 17208 } else { // struct/union 17209 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 17210 nullptr); 17211 } 17212 17213 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 17214 // Add alignment attributes if necessary; these attributes are checked 17215 // when the ASTContext lays out the structure. 17216 // 17217 // It is important for implementing the correct semantics that this 17218 // happen here (in ActOnTag). The #pragma pack stack is 17219 // maintained as a result of parser callbacks which can occur at 17220 // many points during the parsing of a struct declaration (because 17221 // the #pragma tokens are effectively skipped over during the 17222 // parsing of the struct). 17223 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 17224 AddAlignmentAttributesForRecord(RD); 17225 AddMsStructLayoutForRecord(RD); 17226 } 17227 } 17228 New->setLexicalDeclContext(CurContext); 17229 return New; 17230 }; 17231 17232 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 17233 if (Name && SS.isNotEmpty()) { 17234 // We have a nested-name tag ('struct foo::bar'). 17235 17236 // Check for invalid 'foo::'. 17237 if (SS.isInvalid()) { 17238 Name = nullptr; 17239 goto CreateNewDecl; 17240 } 17241 17242 // If this is a friend or a reference to a class in a dependent 17243 // context, don't try to make a decl for it. 17244 if (TUK == TUK_Friend || TUK == TUK_Reference) { 17245 DC = computeDeclContext(SS, false); 17246 if (!DC) { 17247 IsDependent = true; 17248 return true; 17249 } 17250 } else { 17251 DC = computeDeclContext(SS, true); 17252 if (!DC) { 17253 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 17254 << SS.getRange(); 17255 return true; 17256 } 17257 } 17258 17259 if (RequireCompleteDeclContext(SS, DC)) 17260 return true; 17261 17262 SearchDC = DC; 17263 // Look-up name inside 'foo::'. 17264 LookupQualifiedName(Previous, DC); 17265 17266 if (Previous.isAmbiguous()) 17267 return true; 17268 17269 if (Previous.empty()) { 17270 // Name lookup did not find anything. However, if the 17271 // nested-name-specifier refers to the current instantiation, 17272 // and that current instantiation has any dependent base 17273 // classes, we might find something at instantiation time: treat 17274 // this as a dependent elaborated-type-specifier. 17275 // But this only makes any sense for reference-like lookups. 17276 if (Previous.wasNotFoundInCurrentInstantiation() && 17277 (TUK == TUK_Reference || TUK == TUK_Friend)) { 17278 IsDependent = true; 17279 return true; 17280 } 17281 17282 // A tag 'foo::bar' must already exist. 17283 Diag(NameLoc, diag::err_not_tag_in_scope) 17284 << llvm::to_underlying(Kind) << Name << DC << SS.getRange(); 17285 Name = nullptr; 17286 Invalid = true; 17287 goto CreateNewDecl; 17288 } 17289 } else if (Name) { 17290 // C++14 [class.mem]p14: 17291 // If T is the name of a class, then each of the following shall have a 17292 // name different from T: 17293 // -- every member of class T that is itself a type 17294 if (TUK != TUK_Reference && TUK != TUK_Friend && 17295 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 17296 return true; 17297 17298 // If this is a named struct, check to see if there was a previous forward 17299 // declaration or definition. 17300 // FIXME: We're looking into outer scopes here, even when we 17301 // shouldn't be. Doing so can result in ambiguities that we 17302 // shouldn't be diagnosing. 17303 LookupName(Previous, S); 17304 17305 // When declaring or defining a tag, ignore ambiguities introduced 17306 // by types using'ed into this scope. 17307 if (Previous.isAmbiguous() && 17308 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 17309 LookupResult::Filter F = Previous.makeFilter(); 17310 while (F.hasNext()) { 17311 NamedDecl *ND = F.next(); 17312 if (!ND->getDeclContext()->getRedeclContext()->Equals( 17313 SearchDC->getRedeclContext())) 17314 F.erase(); 17315 } 17316 F.done(); 17317 } 17318 17319 // C++11 [namespace.memdef]p3: 17320 // If the name in a friend declaration is neither qualified nor 17321 // a template-id and the declaration is a function or an 17322 // elaborated-type-specifier, the lookup to determine whether 17323 // the entity has been previously declared shall not consider 17324 // any scopes outside the innermost enclosing namespace. 17325 // 17326 // MSVC doesn't implement the above rule for types, so a friend tag 17327 // declaration may be a redeclaration of a type declared in an enclosing 17328 // scope. They do implement this rule for friend functions. 17329 // 17330 // Does it matter that this should be by scope instead of by 17331 // semantic context? 17332 if (!Previous.empty() && TUK == TUK_Friend) { 17333 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 17334 LookupResult::Filter F = Previous.makeFilter(); 17335 bool FriendSawTagOutsideEnclosingNamespace = false; 17336 while (F.hasNext()) { 17337 NamedDecl *ND = F.next(); 17338 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 17339 if (DC->isFileContext() && 17340 !EnclosingNS->Encloses(ND->getDeclContext())) { 17341 if (getLangOpts().MSVCCompat) 17342 FriendSawTagOutsideEnclosingNamespace = true; 17343 else 17344 F.erase(); 17345 } 17346 } 17347 F.done(); 17348 17349 // Diagnose this MSVC extension in the easy case where lookup would have 17350 // unambiguously found something outside the enclosing namespace. 17351 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 17352 NamedDecl *ND = Previous.getFoundDecl(); 17353 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 17354 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 17355 } 17356 } 17357 17358 // Note: there used to be some attempt at recovery here. 17359 if (Previous.isAmbiguous()) 17360 return true; 17361 17362 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 17363 // FIXME: This makes sure that we ignore the contexts associated 17364 // with C structs, unions, and enums when looking for a matching 17365 // tag declaration or definition. See the similar lookup tweak 17366 // in Sema::LookupName; is there a better way to deal with this? 17367 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC)) 17368 SearchDC = SearchDC->getParent(); 17369 } else if (getLangOpts().CPlusPlus) { 17370 // Inside ObjCContainer want to keep it as a lexical decl context but go 17371 // past it (most often to TranslationUnit) to find the semantic decl 17372 // context. 17373 while (isa<ObjCContainerDecl>(SearchDC)) 17374 SearchDC = SearchDC->getParent(); 17375 } 17376 } else if (getLangOpts().CPlusPlus) { 17377 // Don't use ObjCContainerDecl as the semantic decl context for anonymous 17378 // TagDecl the same way as we skip it for named TagDecl. 17379 while (isa<ObjCContainerDecl>(SearchDC)) 17380 SearchDC = SearchDC->getParent(); 17381 } 17382 17383 if (Previous.isSingleResult() && 17384 Previous.getFoundDecl()->isTemplateParameter()) { 17385 // Maybe we will complain about the shadowed template parameter. 17386 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 17387 // Just pretend that we didn't see the previous declaration. 17388 Previous.clear(); 17389 } 17390 17391 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 17392 DC->Equals(getStdNamespace())) { 17393 if (Name->isStr("bad_alloc")) { 17394 // This is a declaration of or a reference to "std::bad_alloc". 17395 isStdBadAlloc = true; 17396 17397 // If std::bad_alloc has been implicitly declared (but made invisible to 17398 // name lookup), fill in this implicit declaration as the previous 17399 // declaration, so that the declarations get chained appropriately. 17400 if (Previous.empty() && StdBadAlloc) 17401 Previous.addDecl(getStdBadAlloc()); 17402 } else if (Name->isStr("align_val_t")) { 17403 isStdAlignValT = true; 17404 if (Previous.empty() && StdAlignValT) 17405 Previous.addDecl(getStdAlignValT()); 17406 } 17407 } 17408 17409 // If we didn't find a previous declaration, and this is a reference 17410 // (or friend reference), move to the correct scope. In C++, we 17411 // also need to do a redeclaration lookup there, just in case 17412 // there's a shadow friend decl. 17413 if (Name && Previous.empty() && 17414 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 17415 if (Invalid) goto CreateNewDecl; 17416 assert(SS.isEmpty()); 17417 17418 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 17419 // C++ [basic.scope.pdecl]p5: 17420 // -- for an elaborated-type-specifier of the form 17421 // 17422 // class-key identifier 17423 // 17424 // if the elaborated-type-specifier is used in the 17425 // decl-specifier-seq or parameter-declaration-clause of a 17426 // function defined in namespace scope, the identifier is 17427 // declared as a class-name in the namespace that contains 17428 // the declaration; otherwise, except as a friend 17429 // declaration, the identifier is declared in the smallest 17430 // non-class, non-function-prototype scope that contains the 17431 // declaration. 17432 // 17433 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 17434 // C structs and unions. 17435 // 17436 // It is an error in C++ to declare (rather than define) an enum 17437 // type, including via an elaborated type specifier. We'll 17438 // diagnose that later; for now, declare the enum in the same 17439 // scope as we would have picked for any other tag type. 17440 // 17441 // GNU C also supports this behavior as part of its incomplete 17442 // enum types extension, while GNU C++ does not. 17443 // 17444 // Find the context where we'll be declaring the tag. 17445 // FIXME: We would like to maintain the current DeclContext as the 17446 // lexical context, 17447 SearchDC = getTagInjectionContext(SearchDC); 17448 17449 // Find the scope where we'll be declaring the tag. 17450 S = getTagInjectionScope(S, getLangOpts()); 17451 } else { 17452 assert(TUK == TUK_Friend); 17453 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC); 17454 17455 // C++ [namespace.memdef]p3: 17456 // If a friend declaration in a non-local class first declares a 17457 // class or function, the friend class or function is a member of 17458 // the innermost enclosing namespace. 17459 SearchDC = RD->isLocalClass() ? RD->isLocalClass() 17460 : SearchDC->getEnclosingNamespaceContext(); 17461 } 17462 17463 // In C++, we need to do a redeclaration lookup to properly 17464 // diagnose some problems. 17465 // FIXME: redeclaration lookup is also used (with and without C++) to find a 17466 // hidden declaration so that we don't get ambiguity errors when using a 17467 // type declared by an elaborated-type-specifier. In C that is not correct 17468 // and we should instead merge compatible types found by lookup. 17469 if (getLangOpts().CPlusPlus) { 17470 // FIXME: This can perform qualified lookups into function contexts, 17471 // which are meaningless. 17472 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 17473 LookupQualifiedName(Previous, SearchDC); 17474 } else { 17475 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 17476 LookupName(Previous, S); 17477 } 17478 } 17479 17480 // If we have a known previous declaration to use, then use it. 17481 if (Previous.empty() && SkipBody && SkipBody->Previous) 17482 Previous.addDecl(SkipBody->Previous); 17483 17484 if (!Previous.empty()) { 17485 NamedDecl *PrevDecl = Previous.getFoundDecl(); 17486 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 17487 17488 // It's okay to have a tag decl in the same scope as a typedef 17489 // which hides a tag decl in the same scope. Finding this 17490 // with a redeclaration lookup can only actually happen in C++. 17491 // 17492 // This is also okay for elaborated-type-specifiers, which is 17493 // technically forbidden by the current standard but which is 17494 // okay according to the likely resolution of an open issue; 17495 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 17496 if (getLangOpts().CPlusPlus) { 17497 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 17498 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 17499 TagDecl *Tag = TT->getDecl(); 17500 if (Tag->getDeclName() == Name && 17501 Tag->getDeclContext()->getRedeclContext() 17502 ->Equals(TD->getDeclContext()->getRedeclContext())) { 17503 PrevDecl = Tag; 17504 Previous.clear(); 17505 Previous.addDecl(Tag); 17506 Previous.resolveKind(); 17507 } 17508 } 17509 } 17510 } 17511 17512 // If this is a redeclaration of a using shadow declaration, it must 17513 // declare a tag in the same context. In MSVC mode, we allow a 17514 // redefinition if either context is within the other. 17515 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 17516 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 17517 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 17518 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 17519 !(OldTag && isAcceptableTagRedeclContext( 17520 *this, OldTag->getDeclContext(), SearchDC))) { 17521 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 17522 Diag(Shadow->getTargetDecl()->getLocation(), 17523 diag::note_using_decl_target); 17524 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 17525 << 0; 17526 // Recover by ignoring the old declaration. 17527 Previous.clear(); 17528 goto CreateNewDecl; 17529 } 17530 } 17531 17532 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 17533 // If this is a use of a previous tag, or if the tag is already declared 17534 // in the same scope (so that the definition/declaration completes or 17535 // rementions the tag), reuse the decl. 17536 if (TUK == TUK_Reference || TUK == TUK_Friend || 17537 isDeclInScope(DirectPrevDecl, SearchDC, S, 17538 SS.isNotEmpty() || isMemberSpecialization)) { 17539 // Make sure that this wasn't declared as an enum and now used as a 17540 // struct or something similar. 17541 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 17542 TUK == TUK_Definition, KWLoc, 17543 Name)) { 17544 bool SafeToContinue = 17545 (PrevTagDecl->getTagKind() != TagTypeKind::Enum && 17546 Kind != TagTypeKind::Enum); 17547 if (SafeToContinue) 17548 Diag(KWLoc, diag::err_use_with_wrong_tag) 17549 << Name 17550 << FixItHint::CreateReplacement(SourceRange(KWLoc), 17551 PrevTagDecl->getKindName()); 17552 else 17553 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 17554 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 17555 17556 if (SafeToContinue) 17557 Kind = PrevTagDecl->getTagKind(); 17558 else { 17559 // Recover by making this an anonymous redefinition. 17560 Name = nullptr; 17561 Previous.clear(); 17562 Invalid = true; 17563 } 17564 } 17565 17566 if (Kind == TagTypeKind::Enum && 17567 PrevTagDecl->getTagKind() == TagTypeKind::Enum) { 17568 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 17569 if (TUK == TUK_Reference || TUK == TUK_Friend) 17570 return PrevTagDecl; 17571 17572 QualType EnumUnderlyingTy; 17573 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 17574 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 17575 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 17576 EnumUnderlyingTy = QualType(T, 0); 17577 17578 // All conflicts with previous declarations are recovered by 17579 // returning the previous declaration, unless this is a definition, 17580 // in which case we want the caller to bail out. 17581 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 17582 ScopedEnum, EnumUnderlyingTy, 17583 IsFixed, PrevEnum)) 17584 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 17585 } 17586 17587 // C++11 [class.mem]p1: 17588 // A member shall not be declared twice in the member-specification, 17589 // except that a nested class or member class template can be declared 17590 // and then later defined. 17591 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 17592 S->isDeclScope(PrevDecl)) { 17593 Diag(NameLoc, diag::ext_member_redeclared); 17594 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 17595 } 17596 17597 if (!Invalid) { 17598 // If this is a use, just return the declaration we found, unless 17599 // we have attributes. 17600 if (TUK == TUK_Reference || TUK == TUK_Friend) { 17601 if (!Attrs.empty()) { 17602 // FIXME: Diagnose these attributes. For now, we create a new 17603 // declaration to hold them. 17604 } else if (TUK == TUK_Reference && 17605 (PrevTagDecl->getFriendObjectKind() == 17606 Decl::FOK_Undeclared || 17607 PrevDecl->getOwningModule() != getCurrentModule()) && 17608 SS.isEmpty()) { 17609 // This declaration is a reference to an existing entity, but 17610 // has different visibility from that entity: it either makes 17611 // a friend visible or it makes a type visible in a new module. 17612 // In either case, create a new declaration. We only do this if 17613 // the declaration would have meant the same thing if no prior 17614 // declaration were found, that is, if it was found in the same 17615 // scope where we would have injected a declaration. 17616 if (!getTagInjectionContext(CurContext)->getRedeclContext() 17617 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 17618 return PrevTagDecl; 17619 // This is in the injected scope, create a new declaration in 17620 // that scope. 17621 S = getTagInjectionScope(S, getLangOpts()); 17622 } else { 17623 return PrevTagDecl; 17624 } 17625 } 17626 17627 // Diagnose attempts to redefine a tag. 17628 if (TUK == TUK_Definition) { 17629 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 17630 // If we're defining a specialization and the previous definition 17631 // is from an implicit instantiation, don't emit an error 17632 // here; we'll catch this in the general case below. 17633 bool IsExplicitSpecializationAfterInstantiation = false; 17634 if (isMemberSpecialization) { 17635 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 17636 IsExplicitSpecializationAfterInstantiation = 17637 RD->getTemplateSpecializationKind() != 17638 TSK_ExplicitSpecialization; 17639 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 17640 IsExplicitSpecializationAfterInstantiation = 17641 ED->getTemplateSpecializationKind() != 17642 TSK_ExplicitSpecialization; 17643 } 17644 17645 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 17646 // not keep more that one definition around (merge them). However, 17647 // ensure the decl passes the structural compatibility check in 17648 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 17649 NamedDecl *Hidden = nullptr; 17650 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 17651 // There is a definition of this tag, but it is not visible. We 17652 // explicitly make use of C++'s one definition rule here, and 17653 // assume that this definition is identical to the hidden one 17654 // we already have. Make the existing definition visible and 17655 // use it in place of this one. 17656 if (!getLangOpts().CPlusPlus) { 17657 // Postpone making the old definition visible until after we 17658 // complete parsing the new one and do the structural 17659 // comparison. 17660 SkipBody->CheckSameAsPrevious = true; 17661 SkipBody->New = createTagFromNewDecl(); 17662 SkipBody->Previous = Def; 17663 return Def; 17664 } else { 17665 SkipBody->ShouldSkip = true; 17666 SkipBody->Previous = Def; 17667 makeMergedDefinitionVisible(Hidden); 17668 // Carry on and handle it like a normal definition. We'll 17669 // skip starting the definitiion later. 17670 } 17671 } else if (!IsExplicitSpecializationAfterInstantiation) { 17672 // A redeclaration in function prototype scope in C isn't 17673 // visible elsewhere, so merely issue a warning. 17674 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 17675 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 17676 else 17677 Diag(NameLoc, diag::err_redefinition) << Name; 17678 notePreviousDefinition(Def, 17679 NameLoc.isValid() ? NameLoc : KWLoc); 17680 // If this is a redefinition, recover by making this 17681 // struct be anonymous, which will make any later 17682 // references get the previous definition. 17683 Name = nullptr; 17684 Previous.clear(); 17685 Invalid = true; 17686 } 17687 } else { 17688 // If the type is currently being defined, complain 17689 // about a nested redefinition. 17690 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 17691 if (TD->isBeingDefined()) { 17692 Diag(NameLoc, diag::err_nested_redefinition) << Name; 17693 Diag(PrevTagDecl->getLocation(), 17694 diag::note_previous_definition); 17695 Name = nullptr; 17696 Previous.clear(); 17697 Invalid = true; 17698 } 17699 } 17700 17701 // Okay, this is definition of a previously declared or referenced 17702 // tag. We're going to create a new Decl for it. 17703 } 17704 17705 // Okay, we're going to make a redeclaration. If this is some kind 17706 // of reference, make sure we build the redeclaration in the same DC 17707 // as the original, and ignore the current access specifier. 17708 if (TUK == TUK_Friend || TUK == TUK_Reference) { 17709 SearchDC = PrevTagDecl->getDeclContext(); 17710 AS = AS_none; 17711 } 17712 } 17713 // If we get here we have (another) forward declaration or we 17714 // have a definition. Just create a new decl. 17715 17716 } else { 17717 // If we get here, this is a definition of a new tag type in a nested 17718 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 17719 // new decl/type. We set PrevDecl to NULL so that the entities 17720 // have distinct types. 17721 Previous.clear(); 17722 } 17723 // If we get here, we're going to create a new Decl. If PrevDecl 17724 // is non-NULL, it's a definition of the tag declared by 17725 // PrevDecl. If it's NULL, we have a new definition. 17726 17727 // Otherwise, PrevDecl is not a tag, but was found with tag 17728 // lookup. This is only actually possible in C++, where a few 17729 // things like templates still live in the tag namespace. 17730 } else { 17731 // Use a better diagnostic if an elaborated-type-specifier 17732 // found the wrong kind of type on the first 17733 // (non-redeclaration) lookup. 17734 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 17735 !Previous.isForRedeclaration()) { 17736 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 17737 Diag(NameLoc, diag::err_tag_reference_non_tag) 17738 << PrevDecl << NTK << llvm::to_underlying(Kind); 17739 Diag(PrevDecl->getLocation(), diag::note_declared_at); 17740 Invalid = true; 17741 17742 // Otherwise, only diagnose if the declaration is in scope. 17743 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 17744 SS.isNotEmpty() || isMemberSpecialization)) { 17745 // do nothing 17746 17747 // Diagnose implicit declarations introduced by elaborated types. 17748 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 17749 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 17750 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 17751 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 17752 Invalid = true; 17753 17754 // Otherwise it's a declaration. Call out a particularly common 17755 // case here. 17756 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 17757 unsigned Kind = 0; 17758 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 17759 Diag(NameLoc, diag::err_tag_definition_of_typedef) 17760 << Name << Kind << TND->getUnderlyingType(); 17761 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 17762 Invalid = true; 17763 17764 // Otherwise, diagnose. 17765 } else { 17766 // The tag name clashes with something else in the target scope, 17767 // issue an error and recover by making this tag be anonymous. 17768 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 17769 notePreviousDefinition(PrevDecl, NameLoc); 17770 Name = nullptr; 17771 Invalid = true; 17772 } 17773 17774 // The existing declaration isn't relevant to us; we're in a 17775 // new scope, so clear out the previous declaration. 17776 Previous.clear(); 17777 } 17778 } 17779 17780 CreateNewDecl: 17781 17782 TagDecl *PrevDecl = nullptr; 17783 if (Previous.isSingleResult()) 17784 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 17785 17786 // If there is an identifier, use the location of the identifier as the 17787 // location of the decl, otherwise use the location of the struct/union 17788 // keyword. 17789 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 17790 17791 // Otherwise, create a new declaration. If there is a previous 17792 // declaration of the same entity, the two will be linked via 17793 // PrevDecl. 17794 TagDecl *New; 17795 17796 if (Kind == TagTypeKind::Enum) { 17797 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 17798 // enum X { A, B, C } D; D should chain to X. 17799 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 17800 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 17801 ScopedEnumUsesClassTag, IsFixed); 17802 17803 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 17804 StdAlignValT = cast<EnumDecl>(New); 17805 17806 // If this is an undefined enum, warn. 17807 if (TUK != TUK_Definition && !Invalid) { 17808 TagDecl *Def; 17809 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 17810 // C++0x: 7.2p2: opaque-enum-declaration. 17811 // Conflicts are diagnosed above. Do nothing. 17812 } 17813 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 17814 Diag(Loc, diag::ext_forward_ref_enum_def) 17815 << New; 17816 Diag(Def->getLocation(), diag::note_previous_definition); 17817 } else { 17818 unsigned DiagID = diag::ext_forward_ref_enum; 17819 if (getLangOpts().MSVCCompat) 17820 DiagID = diag::ext_ms_forward_ref_enum; 17821 else if (getLangOpts().CPlusPlus) 17822 DiagID = diag::err_forward_ref_enum; 17823 Diag(Loc, DiagID); 17824 } 17825 } 17826 17827 if (EnumUnderlying) { 17828 EnumDecl *ED = cast<EnumDecl>(New); 17829 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 17830 ED->setIntegerTypeSourceInfo(TI); 17831 else 17832 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 17833 QualType EnumTy = ED->getIntegerType(); 17834 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy) 17835 ? Context.getPromotedIntegerType(EnumTy) 17836 : EnumTy); 17837 assert(ED->isComplete() && "enum with type should be complete"); 17838 } 17839 } else { 17840 // struct/union/class 17841 17842 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 17843 // struct X { int A; } D; D should chain to X. 17844 if (getLangOpts().CPlusPlus) { 17845 // FIXME: Look for a way to use RecordDecl for simple structs. 17846 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 17847 cast_or_null<CXXRecordDecl>(PrevDecl)); 17848 17849 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 17850 StdBadAlloc = cast<CXXRecordDecl>(New); 17851 } else 17852 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 17853 cast_or_null<RecordDecl>(PrevDecl)); 17854 } 17855 17856 if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus) 17857 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof) 17858 << (OOK == OOK_Macro) << New->getSourceRange(); 17859 17860 // C++11 [dcl.type]p3: 17861 // A type-specifier-seq shall not define a class or enumeration [...]. 17862 if (!Invalid && getLangOpts().CPlusPlus && 17863 (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) { 17864 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 17865 << Context.getTagDeclType(New); 17866 Invalid = true; 17867 } 17868 17869 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 17870 DC->getDeclKind() == Decl::Enum) { 17871 Diag(New->getLocation(), diag::err_type_defined_in_enum) 17872 << Context.getTagDeclType(New); 17873 Invalid = true; 17874 } 17875 17876 // Maybe add qualifier info. 17877 if (SS.isNotEmpty()) { 17878 if (SS.isSet()) { 17879 // If this is either a declaration or a definition, check the 17880 // nested-name-specifier against the current context. 17881 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 17882 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 17883 isMemberSpecialization)) 17884 Invalid = true; 17885 17886 New->setQualifierInfo(SS.getWithLocInContext(Context)); 17887 if (TemplateParameterLists.size() > 0) { 17888 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 17889 } 17890 } 17891 else 17892 Invalid = true; 17893 } 17894 17895 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 17896 // Add alignment attributes if necessary; these attributes are checked when 17897 // the ASTContext lays out the structure. 17898 // 17899 // It is important for implementing the correct semantics that this 17900 // happen here (in ActOnTag). The #pragma pack stack is 17901 // maintained as a result of parser callbacks which can occur at 17902 // many points during the parsing of a struct declaration (because 17903 // the #pragma tokens are effectively skipped over during the 17904 // parsing of the struct). 17905 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 17906 AddAlignmentAttributesForRecord(RD); 17907 AddMsStructLayoutForRecord(RD); 17908 } 17909 } 17910 17911 if (ModulePrivateLoc.isValid()) { 17912 if (isMemberSpecialization) 17913 Diag(New->getLocation(), diag::err_module_private_specialization) 17914 << 2 17915 << FixItHint::CreateRemoval(ModulePrivateLoc); 17916 // __module_private__ does not apply to local classes. However, we only 17917 // diagnose this as an error when the declaration specifiers are 17918 // freestanding. Here, we just ignore the __module_private__. 17919 else if (!SearchDC->isFunctionOrMethod()) 17920 New->setModulePrivate(); 17921 } 17922 17923 // If this is a specialization of a member class (of a class template), 17924 // check the specialization. 17925 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 17926 Invalid = true; 17927 17928 // If we're declaring or defining a tag in function prototype scope in C, 17929 // note that this type can only be used within the function and add it to 17930 // the list of decls to inject into the function definition scope. 17931 if ((Name || Kind == TagTypeKind::Enum) && 17932 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 17933 if (getLangOpts().CPlusPlus) { 17934 // C++ [dcl.fct]p6: 17935 // Types shall not be defined in return or parameter types. 17936 if (TUK == TUK_Definition && !IsTypeSpecifier) { 17937 Diag(Loc, diag::err_type_defined_in_param_type) 17938 << Name; 17939 Invalid = true; 17940 } 17941 } else if (!PrevDecl) { 17942 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 17943 } 17944 } 17945 17946 if (Invalid) 17947 New->setInvalidDecl(); 17948 17949 // Set the lexical context. If the tag has a C++ scope specifier, the 17950 // lexical context will be different from the semantic context. 17951 New->setLexicalDeclContext(CurContext); 17952 17953 // Mark this as a friend decl if applicable. 17954 // In Microsoft mode, a friend declaration also acts as a forward 17955 // declaration so we always pass true to setObjectOfFriendDecl to make 17956 // the tag name visible. 17957 if (TUK == TUK_Friend) 17958 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 17959 17960 // Set the access specifier. 17961 if (!Invalid && SearchDC->isRecord()) 17962 SetMemberAccessSpecifier(New, PrevDecl, AS); 17963 17964 if (PrevDecl) 17965 CheckRedeclarationInModule(New, PrevDecl); 17966 17967 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 17968 New->startDefinition(); 17969 17970 ProcessDeclAttributeList(S, New, Attrs); 17971 AddPragmaAttributes(S, New); 17972 17973 // If this has an identifier, add it to the scope stack. 17974 if (TUK == TUK_Friend) { 17975 // We might be replacing an existing declaration in the lookup tables; 17976 // if so, borrow its access specifier. 17977 if (PrevDecl) 17978 New->setAccess(PrevDecl->getAccess()); 17979 17980 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 17981 DC->makeDeclVisibleInContext(New); 17982 if (Name) // can be null along some error paths 17983 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 17984 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 17985 } else if (Name) { 17986 S = getNonFieldDeclScope(S); 17987 PushOnScopeChains(New, S, true); 17988 } else { 17989 CurContext->addDecl(New); 17990 } 17991 17992 // If this is the C FILE type, notify the AST context. 17993 if (IdentifierInfo *II = New->getIdentifier()) 17994 if (!New->isInvalidDecl() && 17995 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 17996 II->isStr("FILE")) 17997 Context.setFILEDecl(New); 17998 17999 if (PrevDecl) 18000 mergeDeclAttributes(New, PrevDecl); 18001 18002 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 18003 inferGslOwnerPointerAttribute(CXXRD); 18004 18005 // If there's a #pragma GCC visibility in scope, set the visibility of this 18006 // record. 18007 AddPushedVisibilityAttribute(New); 18008 18009 if (isMemberSpecialization && !New->isInvalidDecl()) 18010 CompleteMemberSpecialization(New, Previous); 18011 18012 OwnedDecl = true; 18013 // In C++, don't return an invalid declaration. We can't recover well from 18014 // the cases where we make the type anonymous. 18015 if (Invalid && getLangOpts().CPlusPlus) { 18016 if (New->isBeingDefined()) 18017 if (auto RD = dyn_cast<RecordDecl>(New)) 18018 RD->completeDefinition(); 18019 return true; 18020 } else if (SkipBody && SkipBody->ShouldSkip) { 18021 return SkipBody->Previous; 18022 } else { 18023 return New; 18024 } 18025 } 18026 18027 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 18028 AdjustDeclIfTemplate(TagD); 18029 TagDecl *Tag = cast<TagDecl>(TagD); 18030 18031 // Enter the tag context. 18032 PushDeclContext(S, Tag); 18033 18034 ActOnDocumentableDecl(TagD); 18035 18036 // If there's a #pragma GCC visibility in scope, set the visibility of this 18037 // record. 18038 AddPushedVisibilityAttribute(Tag); 18039 } 18040 18041 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) { 18042 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 18043 return false; 18044 18045 // Make the previous decl visible. 18046 makeMergedDefinitionVisible(SkipBody.Previous); 18047 return true; 18048 } 18049 18050 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) { 18051 assert(IDecl->getLexicalParent() == CurContext && 18052 "The next DeclContext should be lexically contained in the current one."); 18053 CurContext = IDecl; 18054 } 18055 18056 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 18057 SourceLocation FinalLoc, 18058 bool IsFinalSpelledSealed, 18059 bool IsAbstract, 18060 SourceLocation LBraceLoc) { 18061 AdjustDeclIfTemplate(TagD); 18062 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 18063 18064 FieldCollector->StartClass(); 18065 18066 if (!Record->getIdentifier()) 18067 return; 18068 18069 if (IsAbstract) 18070 Record->markAbstract(); 18071 18072 if (FinalLoc.isValid()) { 18073 Record->addAttr(FinalAttr::Create(Context, FinalLoc, 18074 IsFinalSpelledSealed 18075 ? FinalAttr::Keyword_sealed 18076 : FinalAttr::Keyword_final)); 18077 } 18078 // C++ [class]p2: 18079 // [...] The class-name is also inserted into the scope of the 18080 // class itself; this is known as the injected-class-name. For 18081 // purposes of access checking, the injected-class-name is treated 18082 // as if it were a public member name. 18083 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 18084 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 18085 Record->getLocation(), Record->getIdentifier(), 18086 /*PrevDecl=*/nullptr, 18087 /*DelayTypeCreation=*/true); 18088 Context.getTypeDeclType(InjectedClassName, Record); 18089 InjectedClassName->setImplicit(); 18090 InjectedClassName->setAccess(AS_public); 18091 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 18092 InjectedClassName->setDescribedClassTemplate(Template); 18093 PushOnScopeChains(InjectedClassName, S); 18094 assert(InjectedClassName->isInjectedClassName() && 18095 "Broken injected-class-name"); 18096 } 18097 18098 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 18099 SourceRange BraceRange) { 18100 AdjustDeclIfTemplate(TagD); 18101 TagDecl *Tag = cast<TagDecl>(TagD); 18102 Tag->setBraceRange(BraceRange); 18103 18104 // Make sure we "complete" the definition even it is invalid. 18105 if (Tag->isBeingDefined()) { 18106 assert(Tag->isInvalidDecl() && "We should already have completed it"); 18107 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 18108 RD->completeDefinition(); 18109 } 18110 18111 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 18112 FieldCollector->FinishClass(); 18113 if (RD->hasAttr<SYCLSpecialClassAttr>()) { 18114 auto *Def = RD->getDefinition(); 18115 assert(Def && "The record is expected to have a completed definition"); 18116 unsigned NumInitMethods = 0; 18117 for (auto *Method : Def->methods()) { 18118 if (!Method->getIdentifier()) 18119 continue; 18120 if (Method->getName() == "__init") 18121 NumInitMethods++; 18122 } 18123 if (NumInitMethods > 1 || !Def->hasInitMethod()) 18124 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method); 18125 } 18126 } 18127 18128 // Exit this scope of this tag's definition. 18129 PopDeclContext(); 18130 18131 if (getCurLexicalContext()->isObjCContainer() && 18132 Tag->getDeclContext()->isFileContext()) 18133 Tag->setTopLevelDeclInObjCContainer(); 18134 18135 // Notify the consumer that we've defined a tag. 18136 if (!Tag->isInvalidDecl()) 18137 Consumer.HandleTagDeclDefinition(Tag); 18138 18139 // Clangs implementation of #pragma align(packed) differs in bitfield layout 18140 // from XLs and instead matches the XL #pragma pack(1) behavior. 18141 if (Context.getTargetInfo().getTriple().isOSAIX() && 18142 AlignPackStack.hasValue()) { 18143 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 18144 // Only diagnose #pragma align(packed). 18145 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 18146 return; 18147 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 18148 if (!RD) 18149 return; 18150 // Only warn if there is at least 1 bitfield member. 18151 if (llvm::any_of(RD->fields(), 18152 [](const FieldDecl *FD) { return FD->isBitField(); })) 18153 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 18154 } 18155 } 18156 18157 void Sema::ActOnObjCContainerFinishDefinition() { 18158 // Exit this scope of this interface definition. 18159 PopDeclContext(); 18160 } 18161 18162 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) { 18163 assert(ObjCCtx == CurContext && "Mismatch of container contexts"); 18164 OriginalLexicalContext = ObjCCtx; 18165 ActOnObjCContainerFinishDefinition(); 18166 } 18167 18168 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) { 18169 ActOnObjCContainerStartDefinition(ObjCCtx); 18170 OriginalLexicalContext = nullptr; 18171 } 18172 18173 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 18174 AdjustDeclIfTemplate(TagD); 18175 TagDecl *Tag = cast<TagDecl>(TagD); 18176 Tag->setInvalidDecl(); 18177 18178 // Make sure we "complete" the definition even it is invalid. 18179 if (Tag->isBeingDefined()) { 18180 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 18181 RD->completeDefinition(); 18182 } 18183 18184 // We're undoing ActOnTagStartDefinition here, not 18185 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 18186 // the FieldCollector. 18187 18188 PopDeclContext(); 18189 } 18190 18191 // Note that FieldName may be null for anonymous bitfields. 18192 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 18193 IdentifierInfo *FieldName, QualType FieldTy, 18194 bool IsMsStruct, Expr *BitWidth) { 18195 assert(BitWidth); 18196 if (BitWidth->containsErrors()) 18197 return ExprError(); 18198 18199 // C99 6.7.2.1p4 - verify the field type. 18200 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 18201 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 18202 // Handle incomplete and sizeless types with a specific error. 18203 if (RequireCompleteSizedType(FieldLoc, FieldTy, 18204 diag::err_field_incomplete_or_sizeless)) 18205 return ExprError(); 18206 if (FieldName) 18207 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 18208 << FieldName << FieldTy << BitWidth->getSourceRange(); 18209 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 18210 << FieldTy << BitWidth->getSourceRange(); 18211 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 18212 UPPC_BitFieldWidth)) 18213 return ExprError(); 18214 18215 // If the bit-width is type- or value-dependent, don't try to check 18216 // it now. 18217 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 18218 return BitWidth; 18219 18220 llvm::APSInt Value; 18221 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 18222 if (ICE.isInvalid()) 18223 return ICE; 18224 BitWidth = ICE.get(); 18225 18226 // Zero-width bitfield is ok for anonymous field. 18227 if (Value == 0 && FieldName) 18228 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) 18229 << FieldName << BitWidth->getSourceRange(); 18230 18231 if (Value.isSigned() && Value.isNegative()) { 18232 if (FieldName) 18233 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 18234 << FieldName << toString(Value, 10); 18235 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 18236 << toString(Value, 10); 18237 } 18238 18239 // The size of the bit-field must not exceed our maximum permitted object 18240 // size. 18241 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 18242 return Diag(FieldLoc, diag::err_bitfield_too_wide) 18243 << !FieldName << FieldName << toString(Value, 10); 18244 } 18245 18246 if (!FieldTy->isDependentType()) { 18247 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 18248 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 18249 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 18250 18251 // Over-wide bitfields are an error in C or when using the MSVC bitfield 18252 // ABI. 18253 bool CStdConstraintViolation = 18254 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 18255 bool MSBitfieldViolation = 18256 Value.ugt(TypeStorageSize) && 18257 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 18258 if (CStdConstraintViolation || MSBitfieldViolation) { 18259 unsigned DiagWidth = 18260 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 18261 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 18262 << (bool)FieldName << FieldName << toString(Value, 10) 18263 << !CStdConstraintViolation << DiagWidth; 18264 } 18265 18266 // Warn on types where the user might conceivably expect to get all 18267 // specified bits as value bits: that's all integral types other than 18268 // 'bool'. 18269 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 18270 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 18271 << FieldName << toString(Value, 10) 18272 << (unsigned)TypeWidth; 18273 } 18274 } 18275 18276 return BitWidth; 18277 } 18278 18279 /// ActOnField - Each field of a C struct/union is passed into this in order 18280 /// to create a FieldDecl object for it. 18281 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 18282 Declarator &D, Expr *BitfieldWidth) { 18283 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart, 18284 D, BitfieldWidth, 18285 /*InitStyle=*/ICIS_NoInit, AS_public); 18286 return Res; 18287 } 18288 18289 /// HandleField - Analyze a field of a C struct or a C++ data member. 18290 /// 18291 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 18292 SourceLocation DeclStart, 18293 Declarator &D, Expr *BitWidth, 18294 InClassInitStyle InitStyle, 18295 AccessSpecifier AS) { 18296 if (D.isDecompositionDeclarator()) { 18297 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 18298 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 18299 << Decomp.getSourceRange(); 18300 return nullptr; 18301 } 18302 18303 IdentifierInfo *II = D.getIdentifier(); 18304 SourceLocation Loc = DeclStart; 18305 if (II) Loc = D.getIdentifierLoc(); 18306 18307 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 18308 QualType T = TInfo->getType(); 18309 if (getLangOpts().CPlusPlus) { 18310 CheckExtraCXXDefaultArguments(D); 18311 18312 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 18313 UPPC_DataMemberType)) { 18314 D.setInvalidType(); 18315 T = Context.IntTy; 18316 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 18317 } 18318 } 18319 18320 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 18321 18322 if (D.getDeclSpec().isInlineSpecified()) 18323 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 18324 << getLangOpts().CPlusPlus17; 18325 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 18326 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 18327 diag::err_invalid_thread) 18328 << DeclSpec::getSpecifierName(TSCS); 18329 18330 // Check to see if this name was declared as a member previously 18331 NamedDecl *PrevDecl = nullptr; 18332 LookupResult Previous(*this, II, Loc, LookupMemberName, 18333 ForVisibleRedeclaration); 18334 LookupName(Previous, S); 18335 switch (Previous.getResultKind()) { 18336 case LookupResult::Found: 18337 case LookupResult::FoundUnresolvedValue: 18338 PrevDecl = Previous.getAsSingle<NamedDecl>(); 18339 break; 18340 18341 case LookupResult::FoundOverloaded: 18342 PrevDecl = Previous.getRepresentativeDecl(); 18343 break; 18344 18345 case LookupResult::NotFound: 18346 case LookupResult::NotFoundInCurrentInstantiation: 18347 case LookupResult::Ambiguous: 18348 break; 18349 } 18350 Previous.suppressDiagnostics(); 18351 18352 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18353 // Maybe we will complain about the shadowed template parameter. 18354 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 18355 // Just pretend that we didn't see the previous declaration. 18356 PrevDecl = nullptr; 18357 } 18358 18359 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 18360 PrevDecl = nullptr; 18361 18362 bool Mutable 18363 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 18364 SourceLocation TSSL = D.getBeginLoc(); 18365 FieldDecl *NewFD 18366 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 18367 TSSL, AS, PrevDecl, &D); 18368 18369 if (NewFD->isInvalidDecl()) 18370 Record->setInvalidDecl(); 18371 18372 if (D.getDeclSpec().isModulePrivateSpecified()) 18373 NewFD->setModulePrivate(); 18374 18375 if (NewFD->isInvalidDecl() && PrevDecl) { 18376 // Don't introduce NewFD into scope; there's already something 18377 // with the same name in the same scope. 18378 } else if (II) { 18379 PushOnScopeChains(NewFD, S); 18380 } else 18381 Record->addDecl(NewFD); 18382 18383 return NewFD; 18384 } 18385 18386 /// Build a new FieldDecl and check its well-formedness. 18387 /// 18388 /// This routine builds a new FieldDecl given the fields name, type, 18389 /// record, etc. \p PrevDecl should refer to any previous declaration 18390 /// with the same name and in the same scope as the field to be 18391 /// created. 18392 /// 18393 /// \returns a new FieldDecl. 18394 /// 18395 /// \todo The Declarator argument is a hack. It will be removed once 18396 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 18397 TypeSourceInfo *TInfo, 18398 RecordDecl *Record, SourceLocation Loc, 18399 bool Mutable, Expr *BitWidth, 18400 InClassInitStyle InitStyle, 18401 SourceLocation TSSL, 18402 AccessSpecifier AS, NamedDecl *PrevDecl, 18403 Declarator *D) { 18404 IdentifierInfo *II = Name.getAsIdentifierInfo(); 18405 bool InvalidDecl = false; 18406 if (D) InvalidDecl = D->isInvalidType(); 18407 18408 // If we receive a broken type, recover by assuming 'int' and 18409 // marking this declaration as invalid. 18410 if (T.isNull() || T->containsErrors()) { 18411 InvalidDecl = true; 18412 T = Context.IntTy; 18413 } 18414 18415 QualType EltTy = Context.getBaseElementType(T); 18416 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 18417 if (RequireCompleteSizedType(Loc, EltTy, 18418 diag::err_field_incomplete_or_sizeless)) { 18419 // Fields of incomplete type force their record to be invalid. 18420 Record->setInvalidDecl(); 18421 InvalidDecl = true; 18422 } else { 18423 NamedDecl *Def; 18424 EltTy->isIncompleteType(&Def); 18425 if (Def && Def->isInvalidDecl()) { 18426 Record->setInvalidDecl(); 18427 InvalidDecl = true; 18428 } 18429 } 18430 } 18431 18432 // TR 18037 does not allow fields to be declared with address space 18433 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 18434 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 18435 Diag(Loc, diag::err_field_with_address_space); 18436 Record->setInvalidDecl(); 18437 InvalidDecl = true; 18438 } 18439 18440 if (LangOpts.OpenCL) { 18441 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 18442 // used as structure or union field: image, sampler, event or block types. 18443 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 18444 T->isBlockPointerType()) { 18445 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 18446 Record->setInvalidDecl(); 18447 InvalidDecl = true; 18448 } 18449 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 18450 // is enabled. 18451 if (BitWidth && !getOpenCLOptions().isAvailableOption( 18452 "__cl_clang_bitfields", LangOpts)) { 18453 Diag(Loc, diag::err_opencl_bitfields); 18454 InvalidDecl = true; 18455 } 18456 } 18457 18458 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 18459 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 18460 T.hasQualifiers()) { 18461 InvalidDecl = true; 18462 Diag(Loc, diag::err_anon_bitfield_qualifiers); 18463 } 18464 18465 // C99 6.7.2.1p8: A member of a structure or union may have any type other 18466 // than a variably modified type. 18467 if (!InvalidDecl && T->isVariablyModifiedType()) { 18468 if (!tryToFixVariablyModifiedVarType( 18469 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 18470 InvalidDecl = true; 18471 } 18472 18473 // Fields can not have abstract class types 18474 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 18475 diag::err_abstract_type_in_decl, 18476 AbstractFieldType)) 18477 InvalidDecl = true; 18478 18479 if (InvalidDecl) 18480 BitWidth = nullptr; 18481 // If this is declared as a bit-field, check the bit-field. 18482 if (BitWidth) { 18483 BitWidth = 18484 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get(); 18485 if (!BitWidth) { 18486 InvalidDecl = true; 18487 BitWidth = nullptr; 18488 } 18489 } 18490 18491 // Check that 'mutable' is consistent with the type of the declaration. 18492 if (!InvalidDecl && Mutable) { 18493 unsigned DiagID = 0; 18494 if (T->isReferenceType()) 18495 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 18496 : diag::err_mutable_reference; 18497 else if (T.isConstQualified()) 18498 DiagID = diag::err_mutable_const; 18499 18500 if (DiagID) { 18501 SourceLocation ErrLoc = Loc; 18502 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 18503 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 18504 Diag(ErrLoc, DiagID); 18505 if (DiagID != diag::ext_mutable_reference) { 18506 Mutable = false; 18507 InvalidDecl = true; 18508 } 18509 } 18510 } 18511 18512 // C++11 [class.union]p8 (DR1460): 18513 // At most one variant member of a union may have a 18514 // brace-or-equal-initializer. 18515 if (InitStyle != ICIS_NoInit) 18516 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 18517 18518 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 18519 BitWidth, Mutable, InitStyle); 18520 if (InvalidDecl) 18521 NewFD->setInvalidDecl(); 18522 18523 if (PrevDecl && !isa<TagDecl>(PrevDecl) && 18524 !PrevDecl->isPlaceholderVar(getLangOpts())) { 18525 Diag(Loc, diag::err_duplicate_member) << II; 18526 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 18527 NewFD->setInvalidDecl(); 18528 } 18529 18530 if (!InvalidDecl && getLangOpts().CPlusPlus) { 18531 if (Record->isUnion()) { 18532 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 18533 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 18534 if (RDecl->getDefinition()) { 18535 // C++ [class.union]p1: An object of a class with a non-trivial 18536 // constructor, a non-trivial copy constructor, a non-trivial 18537 // destructor, or a non-trivial copy assignment operator 18538 // cannot be a member of a union, nor can an array of such 18539 // objects. 18540 if (CheckNontrivialField(NewFD)) 18541 NewFD->setInvalidDecl(); 18542 } 18543 } 18544 18545 // C++ [class.union]p1: If a union contains a member of reference type, 18546 // the program is ill-formed, except when compiling with MSVC extensions 18547 // enabled. 18548 if (EltTy->isReferenceType()) { 18549 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 18550 diag::ext_union_member_of_reference_type : 18551 diag::err_union_member_of_reference_type) 18552 << NewFD->getDeclName() << EltTy; 18553 if (!getLangOpts().MicrosoftExt) 18554 NewFD->setInvalidDecl(); 18555 } 18556 } 18557 } 18558 18559 // FIXME: We need to pass in the attributes given an AST 18560 // representation, not a parser representation. 18561 if (D) { 18562 // FIXME: The current scope is almost... but not entirely... correct here. 18563 ProcessDeclAttributes(getCurScope(), NewFD, *D); 18564 18565 if (NewFD->hasAttrs()) 18566 CheckAlignasUnderalignment(NewFD); 18567 } 18568 18569 // In auto-retain/release, infer strong retension for fields of 18570 // retainable type. 18571 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 18572 NewFD->setInvalidDecl(); 18573 18574 if (T.isObjCGCWeak()) 18575 Diag(Loc, diag::warn_attribute_weak_on_field); 18576 18577 // PPC MMA non-pointer types are not allowed as field types. 18578 if (Context.getTargetInfo().getTriple().isPPC64() && 18579 CheckPPCMMAType(T, NewFD->getLocation())) 18580 NewFD->setInvalidDecl(); 18581 18582 NewFD->setAccess(AS); 18583 return NewFD; 18584 } 18585 18586 bool Sema::CheckNontrivialField(FieldDecl *FD) { 18587 assert(FD); 18588 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 18589 18590 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 18591 return false; 18592 18593 QualType EltTy = Context.getBaseElementType(FD->getType()); 18594 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 18595 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 18596 if (RDecl->getDefinition()) { 18597 // We check for copy constructors before constructors 18598 // because otherwise we'll never get complaints about 18599 // copy constructors. 18600 18601 CXXSpecialMember member = CXXInvalid; 18602 // We're required to check for any non-trivial constructors. Since the 18603 // implicit default constructor is suppressed if there are any 18604 // user-declared constructors, we just need to check that there is a 18605 // trivial default constructor and a trivial copy constructor. (We don't 18606 // worry about move constructors here, since this is a C++98 check.) 18607 if (RDecl->hasNonTrivialCopyConstructor()) 18608 member = CXXCopyConstructor; 18609 else if (!RDecl->hasTrivialDefaultConstructor()) 18610 member = CXXDefaultConstructor; 18611 else if (RDecl->hasNonTrivialCopyAssignment()) 18612 member = CXXCopyAssignment; 18613 else if (RDecl->hasNonTrivialDestructor()) 18614 member = CXXDestructor; 18615 18616 if (member != CXXInvalid) { 18617 if (!getLangOpts().CPlusPlus11 && 18618 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 18619 // Objective-C++ ARC: it is an error to have a non-trivial field of 18620 // a union. However, system headers in Objective-C programs 18621 // occasionally have Objective-C lifetime objects within unions, 18622 // and rather than cause the program to fail, we make those 18623 // members unavailable. 18624 SourceLocation Loc = FD->getLocation(); 18625 if (getSourceManager().isInSystemHeader(Loc)) { 18626 if (!FD->hasAttr<UnavailableAttr>()) 18627 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 18628 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 18629 return false; 18630 } 18631 } 18632 18633 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 18634 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 18635 diag::err_illegal_union_or_anon_struct_member) 18636 << FD->getParent()->isUnion() << FD->getDeclName() << member; 18637 DiagnoseNontrivial(RDecl, member); 18638 return !getLangOpts().CPlusPlus11; 18639 } 18640 } 18641 } 18642 18643 return false; 18644 } 18645 18646 /// TranslateIvarVisibility - Translate visibility from a token ID to an 18647 /// AST enum value. 18648 static ObjCIvarDecl::AccessControl 18649 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 18650 switch (ivarVisibility) { 18651 default: llvm_unreachable("Unknown visitibility kind"); 18652 case tok::objc_private: return ObjCIvarDecl::Private; 18653 case tok::objc_public: return ObjCIvarDecl::Public; 18654 case tok::objc_protected: return ObjCIvarDecl::Protected; 18655 case tok::objc_package: return ObjCIvarDecl::Package; 18656 } 18657 } 18658 18659 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 18660 /// in order to create an IvarDecl object for it. 18661 Decl *Sema::ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, 18662 Expr *BitWidth, tok::ObjCKeywordKind Visibility) { 18663 18664 IdentifierInfo *II = D.getIdentifier(); 18665 SourceLocation Loc = DeclStart; 18666 if (II) Loc = D.getIdentifierLoc(); 18667 18668 // FIXME: Unnamed fields can be handled in various different ways, for 18669 // example, unnamed unions inject all members into the struct namespace! 18670 18671 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 18672 QualType T = TInfo->getType(); 18673 18674 if (BitWidth) { 18675 // 6.7.2.1p3, 6.7.2.1p4 18676 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 18677 if (!BitWidth) 18678 D.setInvalidType(); 18679 } else { 18680 // Not a bitfield. 18681 18682 // validate II. 18683 18684 } 18685 if (T->isReferenceType()) { 18686 Diag(Loc, diag::err_ivar_reference_type); 18687 D.setInvalidType(); 18688 } 18689 // C99 6.7.2.1p8: A member of a structure or union may have any type other 18690 // than a variably modified type. 18691 else if (T->isVariablyModifiedType()) { 18692 if (!tryToFixVariablyModifiedVarType( 18693 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 18694 D.setInvalidType(); 18695 } 18696 18697 // Get the visibility (access control) for this ivar. 18698 ObjCIvarDecl::AccessControl ac = 18699 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 18700 : ObjCIvarDecl::None; 18701 // Must set ivar's DeclContext to its enclosing interface. 18702 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 18703 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 18704 return nullptr; 18705 ObjCContainerDecl *EnclosingContext; 18706 if (ObjCImplementationDecl *IMPDecl = 18707 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 18708 if (LangOpts.ObjCRuntime.isFragile()) { 18709 // Case of ivar declared in an implementation. Context is that of its class. 18710 EnclosingContext = IMPDecl->getClassInterface(); 18711 assert(EnclosingContext && "Implementation has no class interface!"); 18712 } 18713 else 18714 EnclosingContext = EnclosingDecl; 18715 } else { 18716 if (ObjCCategoryDecl *CDecl = 18717 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 18718 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 18719 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 18720 return nullptr; 18721 } 18722 } 18723 EnclosingContext = EnclosingDecl; 18724 } 18725 18726 // Construct the decl. 18727 ObjCIvarDecl *NewID = ObjCIvarDecl::Create( 18728 Context, EnclosingContext, DeclStart, Loc, II, T, TInfo, ac, BitWidth); 18729 18730 if (T->containsErrors()) 18731 NewID->setInvalidDecl(); 18732 18733 if (II) { 18734 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 18735 ForVisibleRedeclaration); 18736 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 18737 && !isa<TagDecl>(PrevDecl)) { 18738 Diag(Loc, diag::err_duplicate_member) << II; 18739 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 18740 NewID->setInvalidDecl(); 18741 } 18742 } 18743 18744 // Process attributes attached to the ivar. 18745 ProcessDeclAttributes(S, NewID, D); 18746 18747 if (D.isInvalidType()) 18748 NewID->setInvalidDecl(); 18749 18750 // In ARC, infer 'retaining' for ivars of retainable type. 18751 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 18752 NewID->setInvalidDecl(); 18753 18754 if (D.getDeclSpec().isModulePrivateSpecified()) 18755 NewID->setModulePrivate(); 18756 18757 if (II) { 18758 // FIXME: When interfaces are DeclContexts, we'll need to add 18759 // these to the interface. 18760 S->AddDecl(NewID); 18761 IdResolver.AddDecl(NewID); 18762 } 18763 18764 if (LangOpts.ObjCRuntime.isNonFragile() && 18765 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 18766 Diag(Loc, diag::warn_ivars_in_interface); 18767 18768 return NewID; 18769 } 18770 18771 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 18772 /// class and class extensions. For every class \@interface and class 18773 /// extension \@interface, if the last ivar is a bitfield of any type, 18774 /// then add an implicit `char :0` ivar to the end of that interface. 18775 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 18776 SmallVectorImpl<Decl *> &AllIvarDecls) { 18777 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 18778 return; 18779 18780 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 18781 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 18782 18783 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 18784 return; 18785 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 18786 if (!ID) { 18787 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 18788 if (!CD->IsClassExtension()) 18789 return; 18790 } 18791 // No need to add this to end of @implementation. 18792 else 18793 return; 18794 } 18795 // All conditions are met. Add a new bitfield to the tail end of ivars. 18796 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 18797 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 18798 18799 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 18800 DeclLoc, DeclLoc, nullptr, 18801 Context.CharTy, 18802 Context.getTrivialTypeSourceInfo(Context.CharTy, 18803 DeclLoc), 18804 ObjCIvarDecl::Private, BW, 18805 true); 18806 AllIvarDecls.push_back(Ivar); 18807 } 18808 18809 /// [class.dtor]p4: 18810 /// At the end of the definition of a class, overload resolution is 18811 /// performed among the prospective destructors declared in that class with 18812 /// an empty argument list to select the destructor for the class, also 18813 /// known as the selected destructor. 18814 /// 18815 /// We do the overload resolution here, then mark the selected constructor in the AST. 18816 /// Later CXXRecordDecl::getDestructor() will return the selected constructor. 18817 static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) { 18818 if (!Record->hasUserDeclaredDestructor()) { 18819 return; 18820 } 18821 18822 SourceLocation Loc = Record->getLocation(); 18823 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal); 18824 18825 for (auto *Decl : Record->decls()) { 18826 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) { 18827 if (DD->isInvalidDecl()) 18828 continue; 18829 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {}, 18830 OCS); 18831 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected."); 18832 } 18833 } 18834 18835 if (OCS.empty()) { 18836 return; 18837 } 18838 OverloadCandidateSet::iterator Best; 18839 unsigned Msg = 0; 18840 OverloadCandidateDisplayKind DisplayKind; 18841 18842 switch (OCS.BestViableFunction(S, Loc, Best)) { 18843 case OR_Success: 18844 case OR_Deleted: 18845 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function)); 18846 break; 18847 18848 case OR_Ambiguous: 18849 Msg = diag::err_ambiguous_destructor; 18850 DisplayKind = OCD_AmbiguousCandidates; 18851 break; 18852 18853 case OR_No_Viable_Function: 18854 Msg = diag::err_no_viable_destructor; 18855 DisplayKind = OCD_AllCandidates; 18856 break; 18857 } 18858 18859 if (Msg) { 18860 // OpenCL have got their own thing going with destructors. It's slightly broken, 18861 // but we allow it. 18862 if (!S.LangOpts.OpenCL) { 18863 PartialDiagnostic Diag = S.PDiag(Msg) << Record; 18864 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {}); 18865 Record->setInvalidDecl(); 18866 } 18867 // It's a bit hacky: At this point we've raised an error but we want the 18868 // rest of the compiler to continue somehow working. However almost 18869 // everything we'll try to do with the class will depend on there being a 18870 // destructor. So let's pretend the first one is selected and hope for the 18871 // best. 18872 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function)); 18873 } 18874 } 18875 18876 /// [class.mem.special]p5 18877 /// Two special member functions are of the same kind if: 18878 /// - they are both default constructors, 18879 /// - they are both copy or move constructors with the same first parameter 18880 /// type, or 18881 /// - they are both copy or move assignment operators with the same first 18882 /// parameter type and the same cv-qualifiers and ref-qualifier, if any. 18883 static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, 18884 CXXMethodDecl *M1, 18885 CXXMethodDecl *M2, 18886 Sema::CXXSpecialMember CSM) { 18887 // We don't want to compare templates to non-templates: See 18888 // https://github.com/llvm/llvm-project/issues/59206 18889 if (CSM == Sema::CXXDefaultConstructor) 18890 return bool(M1->getDescribedFunctionTemplate()) == 18891 bool(M2->getDescribedFunctionTemplate()); 18892 // FIXME: better resolve CWG 18893 // https://cplusplus.github.io/CWG/issues/2787.html 18894 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(), 18895 M2->getNonObjectParameter(0)->getType())) 18896 return false; 18897 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(), 18898 M2->getFunctionObjectParameterReferenceType())) 18899 return false; 18900 18901 return true; 18902 } 18903 18904 /// [class.mem.special]p6: 18905 /// An eligible special member function is a special member function for which: 18906 /// - the function is not deleted, 18907 /// - the associated constraints, if any, are satisfied, and 18908 /// - no special member function of the same kind whose associated constraints 18909 /// [CWG2595], if any, are satisfied is more constrained. 18910 static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, 18911 ArrayRef<CXXMethodDecl *> Methods, 18912 Sema::CXXSpecialMember CSM) { 18913 SmallVector<bool, 4> SatisfactionStatus; 18914 18915 for (CXXMethodDecl *Method : Methods) { 18916 const Expr *Constraints = Method->getTrailingRequiresClause(); 18917 if (!Constraints) 18918 SatisfactionStatus.push_back(true); 18919 else { 18920 ConstraintSatisfaction Satisfaction; 18921 if (S.CheckFunctionConstraints(Method, Satisfaction)) 18922 SatisfactionStatus.push_back(false); 18923 else 18924 SatisfactionStatus.push_back(Satisfaction.IsSatisfied); 18925 } 18926 } 18927 18928 for (size_t i = 0; i < Methods.size(); i++) { 18929 if (!SatisfactionStatus[i]) 18930 continue; 18931 CXXMethodDecl *Method = Methods[i]; 18932 CXXMethodDecl *OrigMethod = Method; 18933 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction()) 18934 OrigMethod = cast<CXXMethodDecl>(MF); 18935 18936 const Expr *Constraints = OrigMethod->getTrailingRequiresClause(); 18937 bool AnotherMethodIsMoreConstrained = false; 18938 for (size_t j = 0; j < Methods.size(); j++) { 18939 if (i == j || !SatisfactionStatus[j]) 18940 continue; 18941 CXXMethodDecl *OtherMethod = Methods[j]; 18942 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction()) 18943 OtherMethod = cast<CXXMethodDecl>(MF); 18944 18945 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod, 18946 CSM)) 18947 continue; 18948 18949 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause(); 18950 if (!OtherConstraints) 18951 continue; 18952 if (!Constraints) { 18953 AnotherMethodIsMoreConstrained = true; 18954 break; 18955 } 18956 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod, 18957 {Constraints}, 18958 AnotherMethodIsMoreConstrained)) { 18959 // There was an error with the constraints comparison. Exit the loop 18960 // and don't consider this function eligible. 18961 AnotherMethodIsMoreConstrained = true; 18962 } 18963 if (AnotherMethodIsMoreConstrained) 18964 break; 18965 } 18966 // FIXME: Do not consider deleted methods as eligible after implementing 18967 // DR1734 and DR1496. 18968 if (!AnotherMethodIsMoreConstrained) { 18969 Method->setIneligibleOrNotSelected(false); 18970 Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM); 18971 } 18972 } 18973 } 18974 18975 static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, 18976 CXXRecordDecl *Record) { 18977 SmallVector<CXXMethodDecl *, 4> DefaultConstructors; 18978 SmallVector<CXXMethodDecl *, 4> CopyConstructors; 18979 SmallVector<CXXMethodDecl *, 4> MoveConstructors; 18980 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators; 18981 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators; 18982 18983 for (auto *Decl : Record->decls()) { 18984 auto *MD = dyn_cast<CXXMethodDecl>(Decl); 18985 if (!MD) { 18986 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl); 18987 if (FTD) 18988 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl()); 18989 } 18990 if (!MD) 18991 continue; 18992 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) { 18993 if (CD->isInvalidDecl()) 18994 continue; 18995 if (CD->isDefaultConstructor()) 18996 DefaultConstructors.push_back(MD); 18997 else if (CD->isCopyConstructor()) 18998 CopyConstructors.push_back(MD); 18999 else if (CD->isMoveConstructor()) 19000 MoveConstructors.push_back(MD); 19001 } else if (MD->isCopyAssignmentOperator()) { 19002 CopyAssignmentOperators.push_back(MD); 19003 } else if (MD->isMoveAssignmentOperator()) { 19004 MoveAssignmentOperators.push_back(MD); 19005 } 19006 } 19007 19008 SetEligibleMethods(S, Record, DefaultConstructors, 19009 Sema::CXXDefaultConstructor); 19010 SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor); 19011 SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor); 19012 SetEligibleMethods(S, Record, CopyAssignmentOperators, 19013 Sema::CXXCopyAssignment); 19014 SetEligibleMethods(S, Record, MoveAssignmentOperators, 19015 Sema::CXXMoveAssignment); 19016 } 19017 19018 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 19019 ArrayRef<Decl *> Fields, SourceLocation LBrac, 19020 SourceLocation RBrac, 19021 const ParsedAttributesView &Attrs) { 19022 assert(EnclosingDecl && "missing record or interface decl"); 19023 19024 // If this is an Objective-C @implementation or category and we have 19025 // new fields here we should reset the layout of the interface since 19026 // it will now change. 19027 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 19028 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 19029 switch (DC->getKind()) { 19030 default: break; 19031 case Decl::ObjCCategory: 19032 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 19033 break; 19034 case Decl::ObjCImplementation: 19035 Context. 19036 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 19037 break; 19038 } 19039 } 19040 19041 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 19042 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 19043 19044 // Start counting up the number of named members; make sure to include 19045 // members of anonymous structs and unions in the total. 19046 unsigned NumNamedMembers = 0; 19047 if (Record) { 19048 for (const auto *I : Record->decls()) { 19049 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 19050 if (IFD->getDeclName()) 19051 ++NumNamedMembers; 19052 } 19053 } 19054 19055 // Verify that all the fields are okay. 19056 SmallVector<FieldDecl*, 32> RecFields; 19057 19058 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 19059 i != end; ++i) { 19060 FieldDecl *FD = cast<FieldDecl>(*i); 19061 19062 // Get the type for the field. 19063 const Type *FDTy = FD->getType().getTypePtr(); 19064 19065 if (!FD->isAnonymousStructOrUnion()) { 19066 // Remember all fields written by the user. 19067 RecFields.push_back(FD); 19068 } 19069 19070 // If the field is already invalid for some reason, don't emit more 19071 // diagnostics about it. 19072 if (FD->isInvalidDecl()) { 19073 EnclosingDecl->setInvalidDecl(); 19074 continue; 19075 } 19076 19077 // C99 6.7.2.1p2: 19078 // A structure or union shall not contain a member with 19079 // incomplete or function type (hence, a structure shall not 19080 // contain an instance of itself, but may contain a pointer to 19081 // an instance of itself), except that the last member of a 19082 // structure with more than one named member may have incomplete 19083 // array type; such a structure (and any union containing, 19084 // possibly recursively, a member that is such a structure) 19085 // shall not be a member of a structure or an element of an 19086 // array. 19087 bool IsLastField = (i + 1 == Fields.end()); 19088 if (FDTy->isFunctionType()) { 19089 // Field declared as a function. 19090 Diag(FD->getLocation(), diag::err_field_declared_as_function) 19091 << FD->getDeclName(); 19092 FD->setInvalidDecl(); 19093 EnclosingDecl->setInvalidDecl(); 19094 continue; 19095 } else if (FDTy->isIncompleteArrayType() && 19096 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 19097 if (Record) { 19098 // Flexible array member. 19099 // Microsoft and g++ is more permissive regarding flexible array. 19100 // It will accept flexible array in union and also 19101 // as the sole element of a struct/class. 19102 unsigned DiagID = 0; 19103 if (!Record->isUnion() && !IsLastField) { 19104 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 19105 << FD->getDeclName() << FD->getType() 19106 << llvm::to_underlying(Record->getTagKind()); 19107 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 19108 FD->setInvalidDecl(); 19109 EnclosingDecl->setInvalidDecl(); 19110 continue; 19111 } else if (Record->isUnion()) 19112 DiagID = getLangOpts().MicrosoftExt 19113 ? diag::ext_flexible_array_union_ms 19114 : getLangOpts().CPlusPlus 19115 ? diag::ext_flexible_array_union_gnu 19116 : diag::err_flexible_array_union; 19117 else if (NumNamedMembers < 1) 19118 DiagID = getLangOpts().MicrosoftExt 19119 ? diag::ext_flexible_array_empty_aggregate_ms 19120 : getLangOpts().CPlusPlus 19121 ? diag::ext_flexible_array_empty_aggregate_gnu 19122 : diag::err_flexible_array_empty_aggregate; 19123 19124 if (DiagID) 19125 Diag(FD->getLocation(), DiagID) 19126 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind()); 19127 // While the layout of types that contain virtual bases is not specified 19128 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 19129 // virtual bases after the derived members. This would make a flexible 19130 // array member declared at the end of an object not adjacent to the end 19131 // of the type. 19132 if (CXXRecord && CXXRecord->getNumVBases() != 0) 19133 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 19134 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind()); 19135 if (!getLangOpts().C99) 19136 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 19137 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind()); 19138 19139 // If the element type has a non-trivial destructor, we would not 19140 // implicitly destroy the elements, so disallow it for now. 19141 // 19142 // FIXME: GCC allows this. We should probably either implicitly delete 19143 // the destructor of the containing class, or just allow this. 19144 QualType BaseElem = Context.getBaseElementType(FD->getType()); 19145 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 19146 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 19147 << FD->getDeclName() << FD->getType(); 19148 FD->setInvalidDecl(); 19149 EnclosingDecl->setInvalidDecl(); 19150 continue; 19151 } 19152 // Okay, we have a legal flexible array member at the end of the struct. 19153 Record->setHasFlexibleArrayMember(true); 19154 } else { 19155 // In ObjCContainerDecl ivars with incomplete array type are accepted, 19156 // unless they are followed by another ivar. That check is done 19157 // elsewhere, after synthesized ivars are known. 19158 } 19159 } else if (!FDTy->isDependentType() && 19160 RequireCompleteSizedType( 19161 FD->getLocation(), FD->getType(), 19162 diag::err_field_incomplete_or_sizeless)) { 19163 // Incomplete type 19164 FD->setInvalidDecl(); 19165 EnclosingDecl->setInvalidDecl(); 19166 continue; 19167 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 19168 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 19169 // A type which contains a flexible array member is considered to be a 19170 // flexible array member. 19171 Record->setHasFlexibleArrayMember(true); 19172 if (!Record->isUnion()) { 19173 // If this is a struct/class and this is not the last element, reject 19174 // it. Note that GCC supports variable sized arrays in the middle of 19175 // structures. 19176 if (!IsLastField) 19177 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 19178 << FD->getDeclName() << FD->getType(); 19179 else { 19180 // We support flexible arrays at the end of structs in 19181 // other structs as an extension. 19182 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 19183 << FD->getDeclName(); 19184 } 19185 } 19186 } 19187 if (isa<ObjCContainerDecl>(EnclosingDecl) && 19188 RequireNonAbstractType(FD->getLocation(), FD->getType(), 19189 diag::err_abstract_type_in_decl, 19190 AbstractIvarType)) { 19191 // Ivars can not have abstract class types 19192 FD->setInvalidDecl(); 19193 } 19194 if (Record && FDTTy->getDecl()->hasObjectMember()) 19195 Record->setHasObjectMember(true); 19196 if (Record && FDTTy->getDecl()->hasVolatileMember()) 19197 Record->setHasVolatileMember(true); 19198 } else if (FDTy->isObjCObjectType()) { 19199 /// A field cannot be an Objective-c object 19200 Diag(FD->getLocation(), diag::err_statically_allocated_object) 19201 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 19202 QualType T = Context.getObjCObjectPointerType(FD->getType()); 19203 FD->setType(T); 19204 } else if (Record && Record->isUnion() && 19205 FD->getType().hasNonTrivialObjCLifetime() && 19206 getSourceManager().isInSystemHeader(FD->getLocation()) && 19207 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 19208 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 19209 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 19210 // For backward compatibility, fields of C unions declared in system 19211 // headers that have non-trivial ObjC ownership qualifications are marked 19212 // as unavailable unless the qualifier is explicit and __strong. This can 19213 // break ABI compatibility between programs compiled with ARC and MRR, but 19214 // is a better option than rejecting programs using those unions under 19215 // ARC. 19216 FD->addAttr(UnavailableAttr::CreateImplicit( 19217 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 19218 FD->getLocation())); 19219 } else if (getLangOpts().ObjC && 19220 getLangOpts().getGC() != LangOptions::NonGC && Record && 19221 !Record->hasObjectMember()) { 19222 if (FD->getType()->isObjCObjectPointerType() || 19223 FD->getType().isObjCGCStrong()) 19224 Record->setHasObjectMember(true); 19225 else if (Context.getAsArrayType(FD->getType())) { 19226 QualType BaseType = Context.getBaseElementType(FD->getType()); 19227 if (BaseType->isRecordType() && 19228 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 19229 Record->setHasObjectMember(true); 19230 else if (BaseType->isObjCObjectPointerType() || 19231 BaseType.isObjCGCStrong()) 19232 Record->setHasObjectMember(true); 19233 } 19234 } 19235 19236 if (Record && !getLangOpts().CPlusPlus && 19237 !shouldIgnoreForRecordTriviality(FD)) { 19238 QualType FT = FD->getType(); 19239 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 19240 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 19241 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 19242 Record->isUnion()) 19243 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 19244 } 19245 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 19246 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 19247 Record->setNonTrivialToPrimitiveCopy(true); 19248 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 19249 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 19250 } 19251 if (FT.isDestructedType()) { 19252 Record->setNonTrivialToPrimitiveDestroy(true); 19253 Record->setParamDestroyedInCallee(true); 19254 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 19255 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 19256 } 19257 19258 if (const auto *RT = FT->getAs<RecordType>()) { 19259 if (RT->getDecl()->getArgPassingRestrictions() == 19260 RecordArgPassingKind::CanNeverPassInRegs) 19261 Record->setArgPassingRestrictions( 19262 RecordArgPassingKind::CanNeverPassInRegs); 19263 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 19264 Record->setArgPassingRestrictions( 19265 RecordArgPassingKind::CanNeverPassInRegs); 19266 } 19267 19268 if (Record && FD->getType().isVolatileQualified()) 19269 Record->setHasVolatileMember(true); 19270 // Keep track of the number of named members. 19271 if (FD->getIdentifier()) 19272 ++NumNamedMembers; 19273 } 19274 19275 // Okay, we successfully defined 'Record'. 19276 if (Record) { 19277 bool Completed = false; 19278 if (CXXRecord) { 19279 if (!CXXRecord->isInvalidDecl()) { 19280 // Set access bits correctly on the directly-declared conversions. 19281 for (CXXRecordDecl::conversion_iterator 19282 I = CXXRecord->conversion_begin(), 19283 E = CXXRecord->conversion_end(); I != E; ++I) 19284 I.setAccess((*I)->getAccess()); 19285 } 19286 19287 // Add any implicitly-declared members to this class. 19288 AddImplicitlyDeclaredMembersToClass(CXXRecord); 19289 19290 if (!CXXRecord->isDependentType()) { 19291 if (!CXXRecord->isInvalidDecl()) { 19292 // If we have virtual base classes, we may end up finding multiple 19293 // final overriders for a given virtual function. Check for this 19294 // problem now. 19295 if (CXXRecord->getNumVBases()) { 19296 CXXFinalOverriderMap FinalOverriders; 19297 CXXRecord->getFinalOverriders(FinalOverriders); 19298 19299 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 19300 MEnd = FinalOverriders.end(); 19301 M != MEnd; ++M) { 19302 for (OverridingMethods::iterator SO = M->second.begin(), 19303 SOEnd = M->second.end(); 19304 SO != SOEnd; ++SO) { 19305 assert(SO->second.size() > 0 && 19306 "Virtual function without overriding functions?"); 19307 if (SO->second.size() == 1) 19308 continue; 19309 19310 // C++ [class.virtual]p2: 19311 // In a derived class, if a virtual member function of a base 19312 // class subobject has more than one final overrider the 19313 // program is ill-formed. 19314 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 19315 << (const NamedDecl *)M->first << Record; 19316 Diag(M->first->getLocation(), 19317 diag::note_overridden_virtual_function); 19318 for (OverridingMethods::overriding_iterator 19319 OM = SO->second.begin(), 19320 OMEnd = SO->second.end(); 19321 OM != OMEnd; ++OM) 19322 Diag(OM->Method->getLocation(), diag::note_final_overrider) 19323 << (const NamedDecl *)M->first << OM->Method->getParent(); 19324 19325 Record->setInvalidDecl(); 19326 } 19327 } 19328 CXXRecord->completeDefinition(&FinalOverriders); 19329 Completed = true; 19330 } 19331 } 19332 ComputeSelectedDestructor(*this, CXXRecord); 19333 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord); 19334 } 19335 } 19336 19337 if (!Completed) 19338 Record->completeDefinition(); 19339 19340 // Handle attributes before checking the layout. 19341 ProcessDeclAttributeList(S, Record, Attrs); 19342 19343 // Check to see if a FieldDecl is a pointer to a function. 19344 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) { 19345 const FieldDecl *FD = dyn_cast<FieldDecl>(D); 19346 if (!FD) { 19347 // Check whether this is a forward declaration that was inserted by 19348 // Clang. This happens when a non-forward declared / defined type is 19349 // used, e.g.: 19350 // 19351 // struct foo { 19352 // struct bar *(*f)(); 19353 // struct bar *(*g)(); 19354 // }; 19355 // 19356 // "struct bar" shows up in the decl AST as a "RecordDecl" with an 19357 // incomplete definition. 19358 if (const auto *TD = dyn_cast<TagDecl>(D)) 19359 return !TD->isCompleteDefinition(); 19360 return false; 19361 } 19362 QualType FieldType = FD->getType().getDesugaredType(Context); 19363 if (isa<PointerType>(FieldType)) { 19364 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType(); 19365 return PointeeType.getDesugaredType(Context)->isFunctionType(); 19366 } 19367 return false; 19368 }; 19369 19370 // Maybe randomize the record's decls. We automatically randomize a record 19371 // of function pointers, unless it has the "no_randomize_layout" attribute. 19372 if (!getLangOpts().CPlusPlus && 19373 (Record->hasAttr<RandomizeLayoutAttr>() || 19374 (!Record->hasAttr<NoRandomizeLayoutAttr>() && 19375 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) && 19376 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() && 19377 !Record->isRandomized()) { 19378 SmallVector<Decl *, 32> NewDeclOrdering; 19379 if (randstruct::randomizeStructureLayout(Context, Record, 19380 NewDeclOrdering)) 19381 Record->reorderDecls(NewDeclOrdering); 19382 } 19383 19384 // We may have deferred checking for a deleted destructor. Check now. 19385 if (CXXRecord) { 19386 auto *Dtor = CXXRecord->getDestructor(); 19387 if (Dtor && Dtor->isImplicit() && 19388 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 19389 CXXRecord->setImplicitDestructorIsDeleted(); 19390 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 19391 } 19392 } 19393 19394 if (Record->hasAttrs()) { 19395 CheckAlignasUnderalignment(Record); 19396 19397 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 19398 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 19399 IA->getRange(), IA->getBestCase(), 19400 IA->getInheritanceModel()); 19401 } 19402 19403 // Check if the structure/union declaration is a type that can have zero 19404 // size in C. For C this is a language extension, for C++ it may cause 19405 // compatibility problems. 19406 bool CheckForZeroSize; 19407 if (!getLangOpts().CPlusPlus) { 19408 CheckForZeroSize = true; 19409 } else { 19410 // For C++ filter out types that cannot be referenced in C code. 19411 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 19412 CheckForZeroSize = 19413 CXXRecord->getLexicalDeclContext()->isExternCContext() && 19414 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 19415 CXXRecord->isCLike(); 19416 } 19417 if (CheckForZeroSize) { 19418 bool ZeroSize = true; 19419 bool IsEmpty = true; 19420 unsigned NonBitFields = 0; 19421 for (RecordDecl::field_iterator I = Record->field_begin(), 19422 E = Record->field_end(); 19423 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 19424 IsEmpty = false; 19425 if (I->isUnnamedBitfield()) { 19426 if (!I->isZeroLengthBitField(Context)) 19427 ZeroSize = false; 19428 } else { 19429 ++NonBitFields; 19430 QualType FieldType = I->getType(); 19431 if (FieldType->isIncompleteType() || 19432 !Context.getTypeSizeInChars(FieldType).isZero()) 19433 ZeroSize = false; 19434 } 19435 } 19436 19437 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 19438 // allowed in C++, but warn if its declaration is inside 19439 // extern "C" block. 19440 if (ZeroSize) { 19441 Diag(RecLoc, getLangOpts().CPlusPlus ? 19442 diag::warn_zero_size_struct_union_in_extern_c : 19443 diag::warn_zero_size_struct_union_compat) 19444 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 19445 } 19446 19447 // Structs without named members are extension in C (C99 6.7.2.1p7), 19448 // but are accepted by GCC. 19449 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 19450 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 19451 diag::ext_no_named_members_in_struct_union) 19452 << Record->isUnion(); 19453 } 19454 } 19455 } else { 19456 ObjCIvarDecl **ClsFields = 19457 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 19458 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 19459 ID->setEndOfDefinitionLoc(RBrac); 19460 // Add ivar's to class's DeclContext. 19461 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 19462 ClsFields[i]->setLexicalDeclContext(ID); 19463 ID->addDecl(ClsFields[i]); 19464 } 19465 // Must enforce the rule that ivars in the base classes may not be 19466 // duplicates. 19467 if (ID->getSuperClass()) 19468 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 19469 } else if (ObjCImplementationDecl *IMPDecl = 19470 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 19471 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 19472 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 19473 // Ivar declared in @implementation never belongs to the implementation. 19474 // Only it is in implementation's lexical context. 19475 ClsFields[I]->setLexicalDeclContext(IMPDecl); 19476 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 19477 IMPDecl->setIvarLBraceLoc(LBrac); 19478 IMPDecl->setIvarRBraceLoc(RBrac); 19479 } else if (ObjCCategoryDecl *CDecl = 19480 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 19481 // case of ivars in class extension; all other cases have been 19482 // reported as errors elsewhere. 19483 // FIXME. Class extension does not have a LocEnd field. 19484 // CDecl->setLocEnd(RBrac); 19485 // Add ivar's to class extension's DeclContext. 19486 // Diagnose redeclaration of private ivars. 19487 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 19488 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 19489 if (IDecl) { 19490 if (const ObjCIvarDecl *ClsIvar = 19491 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 19492 Diag(ClsFields[i]->getLocation(), 19493 diag::err_duplicate_ivar_declaration); 19494 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 19495 continue; 19496 } 19497 for (const auto *Ext : IDecl->known_extensions()) { 19498 if (const ObjCIvarDecl *ClsExtIvar 19499 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 19500 Diag(ClsFields[i]->getLocation(), 19501 diag::err_duplicate_ivar_declaration); 19502 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 19503 continue; 19504 } 19505 } 19506 } 19507 ClsFields[i]->setLexicalDeclContext(CDecl); 19508 CDecl->addDecl(ClsFields[i]); 19509 } 19510 CDecl->setIvarLBraceLoc(LBrac); 19511 CDecl->setIvarRBraceLoc(RBrac); 19512 } 19513 } 19514 } 19515 19516 /// Determine whether the given integral value is representable within 19517 /// the given type T. 19518 static bool isRepresentableIntegerValue(ASTContext &Context, 19519 llvm::APSInt &Value, 19520 QualType T) { 19521 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 19522 "Integral type required!"); 19523 unsigned BitWidth = Context.getIntWidth(T); 19524 19525 if (Value.isUnsigned() || Value.isNonNegative()) { 19526 if (T->isSignedIntegerOrEnumerationType()) 19527 --BitWidth; 19528 return Value.getActiveBits() <= BitWidth; 19529 } 19530 return Value.getSignificantBits() <= BitWidth; 19531 } 19532 19533 // Given an integral type, return the next larger integral type 19534 // (or a NULL type of no such type exists). 19535 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 19536 // FIXME: Int128/UInt128 support, which also needs to be introduced into 19537 // enum checking below. 19538 assert((T->isIntegralType(Context) || 19539 T->isEnumeralType()) && "Integral type required!"); 19540 const unsigned NumTypes = 4; 19541 QualType SignedIntegralTypes[NumTypes] = { 19542 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 19543 }; 19544 QualType UnsignedIntegralTypes[NumTypes] = { 19545 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 19546 Context.UnsignedLongLongTy 19547 }; 19548 19549 unsigned BitWidth = Context.getTypeSize(T); 19550 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 19551 : UnsignedIntegralTypes; 19552 for (unsigned I = 0; I != NumTypes; ++I) 19553 if (Context.getTypeSize(Types[I]) > BitWidth) 19554 return Types[I]; 19555 19556 return QualType(); 19557 } 19558 19559 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 19560 EnumConstantDecl *LastEnumConst, 19561 SourceLocation IdLoc, 19562 IdentifierInfo *Id, 19563 Expr *Val) { 19564 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 19565 llvm::APSInt EnumVal(IntWidth); 19566 QualType EltTy; 19567 19568 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 19569 Val = nullptr; 19570 19571 if (Val) 19572 Val = DefaultLvalueConversion(Val).get(); 19573 19574 if (Val) { 19575 if (Enum->isDependentType() || Val->isTypeDependent() || 19576 Val->containsErrors()) 19577 EltTy = Context.DependentTy; 19578 else { 19579 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 19580 // underlying type, but do allow it in all other contexts. 19581 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 19582 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 19583 // constant-expression in the enumerator-definition shall be a converted 19584 // constant expression of the underlying type. 19585 EltTy = Enum->getIntegerType(); 19586 ExprResult Converted = 19587 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 19588 CCEK_Enumerator); 19589 if (Converted.isInvalid()) 19590 Val = nullptr; 19591 else 19592 Val = Converted.get(); 19593 } else if (!Val->isValueDependent() && 19594 !(Val = 19595 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 19596 .get())) { 19597 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 19598 } else { 19599 if (Enum->isComplete()) { 19600 EltTy = Enum->getIntegerType(); 19601 19602 // In Obj-C and Microsoft mode, require the enumeration value to be 19603 // representable in the underlying type of the enumeration. In C++11, 19604 // we perform a non-narrowing conversion as part of converted constant 19605 // expression checking. 19606 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 19607 if (Context.getTargetInfo() 19608 .getTriple() 19609 .isWindowsMSVCEnvironment()) { 19610 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 19611 } else { 19612 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 19613 } 19614 } 19615 19616 // Cast to the underlying type. 19617 Val = ImpCastExprToType(Val, EltTy, 19618 EltTy->isBooleanType() ? CK_IntegralToBoolean 19619 : CK_IntegralCast) 19620 .get(); 19621 } else if (getLangOpts().CPlusPlus) { 19622 // C++11 [dcl.enum]p5: 19623 // If the underlying type is not fixed, the type of each enumerator 19624 // is the type of its initializing value: 19625 // - If an initializer is specified for an enumerator, the 19626 // initializing value has the same type as the expression. 19627 EltTy = Val->getType(); 19628 } else { 19629 // C99 6.7.2.2p2: 19630 // The expression that defines the value of an enumeration constant 19631 // shall be an integer constant expression that has a value 19632 // representable as an int. 19633 19634 // Complain if the value is not representable in an int. 19635 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 19636 Diag(IdLoc, diag::ext_enum_value_not_int) 19637 << toString(EnumVal, 10) << Val->getSourceRange() 19638 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 19639 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 19640 // Force the type of the expression to 'int'. 19641 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 19642 } 19643 EltTy = Val->getType(); 19644 } 19645 } 19646 } 19647 } 19648 19649 if (!Val) { 19650 if (Enum->isDependentType()) 19651 EltTy = Context.DependentTy; 19652 else if (!LastEnumConst) { 19653 // C++0x [dcl.enum]p5: 19654 // If the underlying type is not fixed, the type of each enumerator 19655 // is the type of its initializing value: 19656 // - If no initializer is specified for the first enumerator, the 19657 // initializing value has an unspecified integral type. 19658 // 19659 // GCC uses 'int' for its unspecified integral type, as does 19660 // C99 6.7.2.2p3. 19661 if (Enum->isFixed()) { 19662 EltTy = Enum->getIntegerType(); 19663 } 19664 else { 19665 EltTy = Context.IntTy; 19666 } 19667 } else { 19668 // Assign the last value + 1. 19669 EnumVal = LastEnumConst->getInitVal(); 19670 ++EnumVal; 19671 EltTy = LastEnumConst->getType(); 19672 19673 // Check for overflow on increment. 19674 if (EnumVal < LastEnumConst->getInitVal()) { 19675 // C++0x [dcl.enum]p5: 19676 // If the underlying type is not fixed, the type of each enumerator 19677 // is the type of its initializing value: 19678 // 19679 // - Otherwise the type of the initializing value is the same as 19680 // the type of the initializing value of the preceding enumerator 19681 // unless the incremented value is not representable in that type, 19682 // in which case the type is an unspecified integral type 19683 // sufficient to contain the incremented value. If no such type 19684 // exists, the program is ill-formed. 19685 QualType T = getNextLargerIntegralType(Context, EltTy); 19686 if (T.isNull() || Enum->isFixed()) { 19687 // There is no integral type larger enough to represent this 19688 // value. Complain, then allow the value to wrap around. 19689 EnumVal = LastEnumConst->getInitVal(); 19690 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 19691 ++EnumVal; 19692 if (Enum->isFixed()) 19693 // When the underlying type is fixed, this is ill-formed. 19694 Diag(IdLoc, diag::err_enumerator_wrapped) 19695 << toString(EnumVal, 10) 19696 << EltTy; 19697 else 19698 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 19699 << toString(EnumVal, 10); 19700 } else { 19701 EltTy = T; 19702 } 19703 19704 // Retrieve the last enumerator's value, extent that type to the 19705 // type that is supposed to be large enough to represent the incremented 19706 // value, then increment. 19707 EnumVal = LastEnumConst->getInitVal(); 19708 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 19709 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 19710 ++EnumVal; 19711 19712 // If we're not in C++, diagnose the overflow of enumerator values, 19713 // which in C99 means that the enumerator value is not representable in 19714 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 19715 // permits enumerator values that are representable in some larger 19716 // integral type. 19717 if (!getLangOpts().CPlusPlus && !T.isNull()) 19718 Diag(IdLoc, diag::warn_enum_value_overflow); 19719 } else if (!getLangOpts().CPlusPlus && 19720 !EltTy->isDependentType() && 19721 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 19722 // Enforce C99 6.7.2.2p2 even when we compute the next value. 19723 Diag(IdLoc, diag::ext_enum_value_not_int) 19724 << toString(EnumVal, 10) << 1; 19725 } 19726 } 19727 } 19728 19729 if (!EltTy->isDependentType()) { 19730 // Make the enumerator value match the signedness and size of the 19731 // enumerator's type. 19732 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 19733 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 19734 } 19735 19736 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 19737 Val, EnumVal); 19738 } 19739 19740 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 19741 SourceLocation IILoc) { 19742 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 19743 !getLangOpts().CPlusPlus) 19744 return SkipBodyInfo(); 19745 19746 // We have an anonymous enum definition. Look up the first enumerator to 19747 // determine if we should merge the definition with an existing one and 19748 // skip the body. 19749 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 19750 forRedeclarationInCurContext()); 19751 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 19752 if (!PrevECD) 19753 return SkipBodyInfo(); 19754 19755 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 19756 NamedDecl *Hidden; 19757 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 19758 SkipBodyInfo Skip; 19759 Skip.Previous = Hidden; 19760 return Skip; 19761 } 19762 19763 return SkipBodyInfo(); 19764 } 19765 19766 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 19767 SourceLocation IdLoc, IdentifierInfo *Id, 19768 const ParsedAttributesView &Attrs, 19769 SourceLocation EqualLoc, Expr *Val) { 19770 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 19771 EnumConstantDecl *LastEnumConst = 19772 cast_or_null<EnumConstantDecl>(lastEnumConst); 19773 19774 // The scope passed in may not be a decl scope. Zip up the scope tree until 19775 // we find one that is. 19776 S = getNonFieldDeclScope(S); 19777 19778 // Verify that there isn't already something declared with this name in this 19779 // scope. 19780 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 19781 LookupName(R, S); 19782 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 19783 19784 if (PrevDecl && PrevDecl->isTemplateParameter()) { 19785 // Maybe we will complain about the shadowed template parameter. 19786 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 19787 // Just pretend that we didn't see the previous declaration. 19788 PrevDecl = nullptr; 19789 } 19790 19791 // C++ [class.mem]p15: 19792 // If T is the name of a class, then each of the following shall have a name 19793 // different from T: 19794 // - every enumerator of every member of class T that is an unscoped 19795 // enumerated type 19796 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 19797 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 19798 DeclarationNameInfo(Id, IdLoc)); 19799 19800 EnumConstantDecl *New = 19801 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 19802 if (!New) 19803 return nullptr; 19804 19805 if (PrevDecl) { 19806 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 19807 // Check for other kinds of shadowing not already handled. 19808 CheckShadow(New, PrevDecl, R); 19809 } 19810 19811 // When in C++, we may get a TagDecl with the same name; in this case the 19812 // enum constant will 'hide' the tag. 19813 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 19814 "Received TagDecl when not in C++!"); 19815 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 19816 if (isa<EnumConstantDecl>(PrevDecl)) 19817 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 19818 else 19819 Diag(IdLoc, diag::err_redefinition) << Id; 19820 notePreviousDefinition(PrevDecl, IdLoc); 19821 return nullptr; 19822 } 19823 } 19824 19825 // Process attributes. 19826 ProcessDeclAttributeList(S, New, Attrs); 19827 AddPragmaAttributes(S, New); 19828 19829 // Register this decl in the current scope stack. 19830 New->setAccess(TheEnumDecl->getAccess()); 19831 PushOnScopeChains(New, S); 19832 19833 ActOnDocumentableDecl(New); 19834 19835 return New; 19836 } 19837 19838 // Returns true when the enum initial expression does not trigger the 19839 // duplicate enum warning. A few common cases are exempted as follows: 19840 // Element2 = Element1 19841 // Element2 = Element1 + 1 19842 // Element2 = Element1 - 1 19843 // Where Element2 and Element1 are from the same enum. 19844 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 19845 Expr *InitExpr = ECD->getInitExpr(); 19846 if (!InitExpr) 19847 return true; 19848 InitExpr = InitExpr->IgnoreImpCasts(); 19849 19850 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 19851 if (!BO->isAdditiveOp()) 19852 return true; 19853 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 19854 if (!IL) 19855 return true; 19856 if (IL->getValue() != 1) 19857 return true; 19858 19859 InitExpr = BO->getLHS(); 19860 } 19861 19862 // This checks if the elements are from the same enum. 19863 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 19864 if (!DRE) 19865 return true; 19866 19867 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 19868 if (!EnumConstant) 19869 return true; 19870 19871 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 19872 Enum) 19873 return true; 19874 19875 return false; 19876 } 19877 19878 // Emits a warning when an element is implicitly set a value that 19879 // a previous element has already been set to. 19880 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 19881 EnumDecl *Enum, QualType EnumType) { 19882 // Avoid anonymous enums 19883 if (!Enum->getIdentifier()) 19884 return; 19885 19886 // Only check for small enums. 19887 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 19888 return; 19889 19890 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 19891 return; 19892 19893 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 19894 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 19895 19896 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 19897 19898 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 19899 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 19900 19901 // Use int64_t as a key to avoid needing special handling for map keys. 19902 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 19903 llvm::APSInt Val = D->getInitVal(); 19904 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 19905 }; 19906 19907 DuplicatesVector DupVector; 19908 ValueToVectorMap EnumMap; 19909 19910 // Populate the EnumMap with all values represented by enum constants without 19911 // an initializer. 19912 for (auto *Element : Elements) { 19913 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 19914 19915 // Null EnumConstantDecl means a previous diagnostic has been emitted for 19916 // this constant. Skip this enum since it may be ill-formed. 19917 if (!ECD) { 19918 return; 19919 } 19920 19921 // Constants with initializers are handled in the next loop. 19922 if (ECD->getInitExpr()) 19923 continue; 19924 19925 // Duplicate values are handled in the next loop. 19926 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 19927 } 19928 19929 if (EnumMap.size() == 0) 19930 return; 19931 19932 // Create vectors for any values that has duplicates. 19933 for (auto *Element : Elements) { 19934 // The last loop returned if any constant was null. 19935 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 19936 if (!ValidDuplicateEnum(ECD, Enum)) 19937 continue; 19938 19939 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 19940 if (Iter == EnumMap.end()) 19941 continue; 19942 19943 DeclOrVector& Entry = Iter->second; 19944 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 19945 // Ensure constants are different. 19946 if (D == ECD) 19947 continue; 19948 19949 // Create new vector and push values onto it. 19950 auto Vec = std::make_unique<ECDVector>(); 19951 Vec->push_back(D); 19952 Vec->push_back(ECD); 19953 19954 // Update entry to point to the duplicates vector. 19955 Entry = Vec.get(); 19956 19957 // Store the vector somewhere we can consult later for quick emission of 19958 // diagnostics. 19959 DupVector.emplace_back(std::move(Vec)); 19960 continue; 19961 } 19962 19963 ECDVector *Vec = Entry.get<ECDVector*>(); 19964 // Make sure constants are not added more than once. 19965 if (*Vec->begin() == ECD) 19966 continue; 19967 19968 Vec->push_back(ECD); 19969 } 19970 19971 // Emit diagnostics. 19972 for (const auto &Vec : DupVector) { 19973 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 19974 19975 // Emit warning for one enum constant. 19976 auto *FirstECD = Vec->front(); 19977 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 19978 << FirstECD << toString(FirstECD->getInitVal(), 10) 19979 << FirstECD->getSourceRange(); 19980 19981 // Emit one note for each of the remaining enum constants with 19982 // the same value. 19983 for (auto *ECD : llvm::drop_begin(*Vec)) 19984 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 19985 << ECD << toString(ECD->getInitVal(), 10) 19986 << ECD->getSourceRange(); 19987 } 19988 } 19989 19990 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 19991 bool AllowMask) const { 19992 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 19993 assert(ED->isCompleteDefinition() && "expected enum definition"); 19994 19995 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 19996 llvm::APInt &FlagBits = R.first->second; 19997 19998 if (R.second) { 19999 for (auto *E : ED->enumerators()) { 20000 const auto &EVal = E->getInitVal(); 20001 // Only single-bit enumerators introduce new flag values. 20002 if (EVal.isPowerOf2()) 20003 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal; 20004 } 20005 } 20006 20007 // A value is in a flag enum if either its bits are a subset of the enum's 20008 // flag bits (the first condition) or we are allowing masks and the same is 20009 // true of its complement (the second condition). When masks are allowed, we 20010 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 20011 // 20012 // While it's true that any value could be used as a mask, the assumption is 20013 // that a mask will have all of the insignificant bits set. Anything else is 20014 // likely a logic error. 20015 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 20016 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 20017 } 20018 20019 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 20020 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 20021 const ParsedAttributesView &Attrs) { 20022 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 20023 QualType EnumType = Context.getTypeDeclType(Enum); 20024 20025 ProcessDeclAttributeList(S, Enum, Attrs); 20026 20027 if (Enum->isDependentType()) { 20028 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 20029 EnumConstantDecl *ECD = 20030 cast_or_null<EnumConstantDecl>(Elements[i]); 20031 if (!ECD) continue; 20032 20033 ECD->setType(EnumType); 20034 } 20035 20036 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 20037 return; 20038 } 20039 20040 // TODO: If the result value doesn't fit in an int, it must be a long or long 20041 // long value. ISO C does not support this, but GCC does as an extension, 20042 // emit a warning. 20043 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 20044 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 20045 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 20046 20047 // Verify that all the values are okay, compute the size of the values, and 20048 // reverse the list. 20049 unsigned NumNegativeBits = 0; 20050 unsigned NumPositiveBits = 0; 20051 20052 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 20053 EnumConstantDecl *ECD = 20054 cast_or_null<EnumConstantDecl>(Elements[i]); 20055 if (!ECD) continue; // Already issued a diagnostic. 20056 20057 const llvm::APSInt &InitVal = ECD->getInitVal(); 20058 20059 // Keep track of the size of positive and negative values. 20060 if (InitVal.isUnsigned() || InitVal.isNonNegative()) { 20061 // If the enumerator is zero that should still be counted as a positive 20062 // bit since we need a bit to store the value zero. 20063 unsigned ActiveBits = InitVal.getActiveBits(); 20064 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u}); 20065 } else { 20066 NumNegativeBits = 20067 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits()); 20068 } 20069 } 20070 20071 // If we have an empty set of enumerators we still need one bit. 20072 // From [dcl.enum]p8 20073 // If the enumerator-list is empty, the values of the enumeration are as if 20074 // the enumeration had a single enumerator with value 0 20075 if (!NumPositiveBits && !NumNegativeBits) 20076 NumPositiveBits = 1; 20077 20078 // Figure out the type that should be used for this enum. 20079 QualType BestType; 20080 unsigned BestWidth; 20081 20082 // C++0x N3000 [conv.prom]p3: 20083 // An rvalue of an unscoped enumeration type whose underlying 20084 // type is not fixed can be converted to an rvalue of the first 20085 // of the following types that can represent all the values of 20086 // the enumeration: int, unsigned int, long int, unsigned long 20087 // int, long long int, or unsigned long long int. 20088 // C99 6.4.4.3p2: 20089 // An identifier declared as an enumeration constant has type int. 20090 // The C99 rule is modified by a gcc extension 20091 QualType BestPromotionType; 20092 20093 bool Packed = Enum->hasAttr<PackedAttr>(); 20094 // -fshort-enums is the equivalent to specifying the packed attribute on all 20095 // enum definitions. 20096 if (LangOpts.ShortEnums) 20097 Packed = true; 20098 20099 // If the enum already has a type because it is fixed or dictated by the 20100 // target, promote that type instead of analyzing the enumerators. 20101 if (Enum->isComplete()) { 20102 BestType = Enum->getIntegerType(); 20103 if (Context.isPromotableIntegerType(BestType)) 20104 BestPromotionType = Context.getPromotedIntegerType(BestType); 20105 else 20106 BestPromotionType = BestType; 20107 20108 BestWidth = Context.getIntWidth(BestType); 20109 } 20110 else if (NumNegativeBits) { 20111 // If there is a negative value, figure out the smallest integer type (of 20112 // int/long/longlong) that fits. 20113 // If it's packed, check also if it fits a char or a short. 20114 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 20115 BestType = Context.SignedCharTy; 20116 BestWidth = CharWidth; 20117 } else if (Packed && NumNegativeBits <= ShortWidth && 20118 NumPositiveBits < ShortWidth) { 20119 BestType = Context.ShortTy; 20120 BestWidth = ShortWidth; 20121 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 20122 BestType = Context.IntTy; 20123 BestWidth = IntWidth; 20124 } else { 20125 BestWidth = Context.getTargetInfo().getLongWidth(); 20126 20127 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 20128 BestType = Context.LongTy; 20129 } else { 20130 BestWidth = Context.getTargetInfo().getLongLongWidth(); 20131 20132 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 20133 Diag(Enum->getLocation(), diag::ext_enum_too_large); 20134 BestType = Context.LongLongTy; 20135 } 20136 } 20137 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 20138 } else { 20139 // If there is no negative value, figure out the smallest type that fits 20140 // all of the enumerator values. 20141 // If it's packed, check also if it fits a char or a short. 20142 if (Packed && NumPositiveBits <= CharWidth) { 20143 BestType = Context.UnsignedCharTy; 20144 BestPromotionType = Context.IntTy; 20145 BestWidth = CharWidth; 20146 } else if (Packed && NumPositiveBits <= ShortWidth) { 20147 BestType = Context.UnsignedShortTy; 20148 BestPromotionType = Context.IntTy; 20149 BestWidth = ShortWidth; 20150 } else if (NumPositiveBits <= IntWidth) { 20151 BestType = Context.UnsignedIntTy; 20152 BestWidth = IntWidth; 20153 BestPromotionType 20154 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 20155 ? Context.UnsignedIntTy : Context.IntTy; 20156 } else if (NumPositiveBits <= 20157 (BestWidth = Context.getTargetInfo().getLongWidth())) { 20158 BestType = Context.UnsignedLongTy; 20159 BestPromotionType 20160 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 20161 ? Context.UnsignedLongTy : Context.LongTy; 20162 } else { 20163 BestWidth = Context.getTargetInfo().getLongLongWidth(); 20164 assert(NumPositiveBits <= BestWidth && 20165 "How could an initializer get larger than ULL?"); 20166 BestType = Context.UnsignedLongLongTy; 20167 BestPromotionType 20168 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 20169 ? Context.UnsignedLongLongTy : Context.LongLongTy; 20170 } 20171 } 20172 20173 // Loop over all of the enumerator constants, changing their types to match 20174 // the type of the enum if needed. 20175 for (auto *D : Elements) { 20176 auto *ECD = cast_or_null<EnumConstantDecl>(D); 20177 if (!ECD) continue; // Already issued a diagnostic. 20178 20179 // Standard C says the enumerators have int type, but we allow, as an 20180 // extension, the enumerators to be larger than int size. If each 20181 // enumerator value fits in an int, type it as an int, otherwise type it the 20182 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 20183 // that X has type 'int', not 'unsigned'. 20184 20185 // Determine whether the value fits into an int. 20186 llvm::APSInt InitVal = ECD->getInitVal(); 20187 20188 // If it fits into an integer type, force it. Otherwise force it to match 20189 // the enum decl type. 20190 QualType NewTy; 20191 unsigned NewWidth; 20192 bool NewSign; 20193 if (!getLangOpts().CPlusPlus && 20194 !Enum->isFixed() && 20195 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 20196 NewTy = Context.IntTy; 20197 NewWidth = IntWidth; 20198 NewSign = true; 20199 } else if (ECD->getType() == BestType) { 20200 // Already the right type! 20201 if (getLangOpts().CPlusPlus) 20202 // C++ [dcl.enum]p4: Following the closing brace of an 20203 // enum-specifier, each enumerator has the type of its 20204 // enumeration. 20205 ECD->setType(EnumType); 20206 continue; 20207 } else { 20208 NewTy = BestType; 20209 NewWidth = BestWidth; 20210 NewSign = BestType->isSignedIntegerOrEnumerationType(); 20211 } 20212 20213 // Adjust the APSInt value. 20214 InitVal = InitVal.extOrTrunc(NewWidth); 20215 InitVal.setIsSigned(NewSign); 20216 ECD->setInitVal(InitVal); 20217 20218 // Adjust the Expr initializer and type. 20219 if (ECD->getInitExpr() && 20220 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 20221 ECD->setInitExpr(ImplicitCastExpr::Create( 20222 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 20223 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 20224 if (getLangOpts().CPlusPlus) 20225 // C++ [dcl.enum]p4: Following the closing brace of an 20226 // enum-specifier, each enumerator has the type of its 20227 // enumeration. 20228 ECD->setType(EnumType); 20229 else 20230 ECD->setType(NewTy); 20231 } 20232 20233 Enum->completeDefinition(BestType, BestPromotionType, 20234 NumPositiveBits, NumNegativeBits); 20235 20236 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 20237 20238 if (Enum->isClosedFlag()) { 20239 for (Decl *D : Elements) { 20240 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 20241 if (!ECD) continue; // Already issued a diagnostic. 20242 20243 llvm::APSInt InitVal = ECD->getInitVal(); 20244 if (InitVal != 0 && !InitVal.isPowerOf2() && 20245 !IsValueInFlagEnum(Enum, InitVal, true)) 20246 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 20247 << ECD << Enum; 20248 } 20249 } 20250 20251 // Now that the enum type is defined, ensure it's not been underaligned. 20252 if (Enum->hasAttrs()) 20253 CheckAlignasUnderalignment(Enum); 20254 } 20255 20256 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 20257 SourceLocation StartLoc, 20258 SourceLocation EndLoc) { 20259 StringLiteral *AsmString = cast<StringLiteral>(expr); 20260 20261 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 20262 AsmString, StartLoc, 20263 EndLoc); 20264 CurContext->addDecl(New); 20265 return New; 20266 } 20267 20268 Decl *Sema::ActOnTopLevelStmtDecl(Stmt *Statement) { 20269 auto *New = TopLevelStmtDecl::Create(Context, Statement); 20270 Context.getTranslationUnitDecl()->addDecl(New); 20271 return New; 20272 } 20273 20274 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 20275 IdentifierInfo* AliasName, 20276 SourceLocation PragmaLoc, 20277 SourceLocation NameLoc, 20278 SourceLocation AliasNameLoc) { 20279 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 20280 LookupOrdinaryName); 20281 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 20282 AttributeCommonInfo::Form::Pragma()); 20283 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 20284 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info); 20285 20286 // If a declaration that: 20287 // 1) declares a function or a variable 20288 // 2) has external linkage 20289 // already exists, add a label attribute to it. 20290 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 20291 if (isDeclExternC(PrevDecl)) 20292 PrevDecl->addAttr(Attr); 20293 else 20294 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 20295 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 20296 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers. 20297 } else 20298 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 20299 } 20300 20301 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 20302 SourceLocation PragmaLoc, 20303 SourceLocation NameLoc) { 20304 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 20305 20306 if (PrevDecl) { 20307 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 20308 } else { 20309 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc)); 20310 } 20311 } 20312 20313 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 20314 IdentifierInfo* AliasName, 20315 SourceLocation PragmaLoc, 20316 SourceLocation NameLoc, 20317 SourceLocation AliasNameLoc) { 20318 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 20319 LookupOrdinaryName); 20320 WeakInfo W = WeakInfo(Name, NameLoc); 20321 20322 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 20323 if (!PrevDecl->hasAttr<AliasAttr>()) 20324 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 20325 DeclApplyPragmaWeak(TUScope, ND, W); 20326 } else { 20327 (void)WeakUndeclaredIdentifiers[AliasName].insert(W); 20328 } 20329 } 20330 20331 ObjCContainerDecl *Sema::getObjCDeclContext() const { 20332 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 20333 } 20334 20335 Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD, 20336 bool Final) { 20337 assert(FD && "Expected non-null FunctionDecl"); 20338 20339 // SYCL functions can be template, so we check if they have appropriate 20340 // attribute prior to checking if it is a template. 20341 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 20342 return FunctionEmissionStatus::Emitted; 20343 20344 // Templates are emitted when they're instantiated. 20345 if (FD->isDependentContext()) 20346 return FunctionEmissionStatus::TemplateDiscarded; 20347 20348 // Check whether this function is an externally visible definition. 20349 auto IsEmittedForExternalSymbol = [this, FD]() { 20350 // We have to check the GVA linkage of the function's *definition* -- if we 20351 // only have a declaration, we don't know whether or not the function will 20352 // be emitted, because (say) the definition could include "inline". 20353 const FunctionDecl *Def = FD->getDefinition(); 20354 20355 return Def && !isDiscardableGVALinkage( 20356 getASTContext().GetGVALinkageForFunction(Def)); 20357 }; 20358 20359 if (LangOpts.OpenMPIsTargetDevice) { 20360 // In OpenMP device mode we will not emit host only functions, or functions 20361 // we don't need due to their linkage. 20362 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 20363 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 20364 // DevTy may be changed later by 20365 // #pragma omp declare target to(*) device_type(*). 20366 // Therefore DevTy having no value does not imply host. The emission status 20367 // will be checked again at the end of compilation unit with Final = true. 20368 if (DevTy) 20369 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 20370 return FunctionEmissionStatus::OMPDiscarded; 20371 // If we have an explicit value for the device type, or we are in a target 20372 // declare context, we need to emit all extern and used symbols. 20373 if (isInOpenMPDeclareTargetContext() || DevTy) 20374 if (IsEmittedForExternalSymbol()) 20375 return FunctionEmissionStatus::Emitted; 20376 // Device mode only emits what it must, if it wasn't tagged yet and needed, 20377 // we'll omit it. 20378 if (Final) 20379 return FunctionEmissionStatus::OMPDiscarded; 20380 } else if (LangOpts.OpenMP > 45) { 20381 // In OpenMP host compilation prior to 5.0 everything was an emitted host 20382 // function. In 5.0, no_host was introduced which might cause a function to 20383 // be ommitted. 20384 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 20385 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 20386 if (DevTy) 20387 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 20388 return FunctionEmissionStatus::OMPDiscarded; 20389 } 20390 20391 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 20392 return FunctionEmissionStatus::Emitted; 20393 20394 if (LangOpts.CUDA) { 20395 // When compiling for device, host functions are never emitted. Similarly, 20396 // when compiling for host, device and global functions are never emitted. 20397 // (Technically, we do emit a host-side stub for global functions, but this 20398 // doesn't count for our purposes here.) 20399 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 20400 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 20401 return FunctionEmissionStatus::CUDADiscarded; 20402 if (!LangOpts.CUDAIsDevice && 20403 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 20404 return FunctionEmissionStatus::CUDADiscarded; 20405 20406 if (IsEmittedForExternalSymbol()) 20407 return FunctionEmissionStatus::Emitted; 20408 } 20409 20410 // Otherwise, the function is known-emitted if it's in our set of 20411 // known-emitted functions. 20412 return FunctionEmissionStatus::Unknown; 20413 } 20414 20415 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 20416 // Host-side references to a __global__ function refer to the stub, so the 20417 // function itself is never emitted and therefore should not be marked. 20418 // If we have host fn calls kernel fn calls host+device, the HD function 20419 // does not get instantiated on the host. We model this by omitting at the 20420 // call to the kernel from the callgraph. This ensures that, when compiling 20421 // for host, only HD functions actually called from the host get marked as 20422 // known-emitted. 20423 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 20424 IdentifyCUDATarget(Callee) == CFT_Global; 20425 } 20426