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 if (!getLangOpts().CPlusPlus && S->isClassScope()) { 2320 if (auto *FD = dyn_cast<FieldDecl>(TmpD); 2321 FD && FD->hasAttr<CountedByAttr>()) 2322 CheckCountedByAttr(S, FD); 2323 } 2324 } 2325 2326 llvm::sort(DeclDiags, 2327 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool { 2328 // The particular order for diagnostics is not important, as long 2329 // as the order is deterministic. Using the raw location is going 2330 // to generally be in source order unless there are macro 2331 // expansions involved. 2332 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding(); 2333 }); 2334 for (const LocAndDiag &D : DeclDiags) { 2335 Diag(D.Loc, D.PD); 2336 if (D.PreviousDeclLoc) 2337 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration); 2338 } 2339 } 2340 2341 /// Look for an Objective-C class in the translation unit. 2342 /// 2343 /// \param Id The name of the Objective-C class we're looking for. If 2344 /// typo-correction fixes this name, the Id will be updated 2345 /// to the fixed name. 2346 /// 2347 /// \param IdLoc The location of the name in the translation unit. 2348 /// 2349 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2350 /// if there is no class with the given name. 2351 /// 2352 /// \returns The declaration of the named Objective-C class, or NULL if the 2353 /// class could not be found. 2354 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2355 SourceLocation IdLoc, 2356 bool DoTypoCorrection) { 2357 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2358 // creation from this context. 2359 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2360 2361 if (!IDecl && DoTypoCorrection) { 2362 // Perform typo correction at the given location, but only if we 2363 // find an Objective-C class name. 2364 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2365 if (TypoCorrection C = 2366 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2367 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2368 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2369 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2370 Id = IDecl->getIdentifier(); 2371 } 2372 } 2373 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2374 // This routine must always return a class definition, if any. 2375 if (Def && Def->getDefinition()) 2376 Def = Def->getDefinition(); 2377 return Def; 2378 } 2379 2380 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2381 /// from S, where a non-field would be declared. This routine copes 2382 /// with the difference between C and C++ scoping rules in structs and 2383 /// unions. For example, the following code is well-formed in C but 2384 /// ill-formed in C++: 2385 /// @code 2386 /// struct S6 { 2387 /// enum { BAR } e; 2388 /// }; 2389 /// 2390 /// void test_S6() { 2391 /// struct S6 a; 2392 /// a.e = BAR; 2393 /// } 2394 /// @endcode 2395 /// For the declaration of BAR, this routine will return a different 2396 /// scope. The scope S will be the scope of the unnamed enumeration 2397 /// within S6. In C++, this routine will return the scope associated 2398 /// with S6, because the enumeration's scope is a transparent 2399 /// context but structures can contain non-field names. In C, this 2400 /// routine will return the translation unit scope, since the 2401 /// enumeration's scope is a transparent context and structures cannot 2402 /// contain non-field names. 2403 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2404 while (((S->getFlags() & Scope::DeclScope) == 0) || 2405 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2406 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2407 S = S->getParent(); 2408 return S; 2409 } 2410 2411 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2412 ASTContext::GetBuiltinTypeError Error) { 2413 switch (Error) { 2414 case ASTContext::GE_None: 2415 return ""; 2416 case ASTContext::GE_Missing_type: 2417 return BuiltinInfo.getHeaderName(ID); 2418 case ASTContext::GE_Missing_stdio: 2419 return "stdio.h"; 2420 case ASTContext::GE_Missing_setjmp: 2421 return "setjmp.h"; 2422 case ASTContext::GE_Missing_ucontext: 2423 return "ucontext.h"; 2424 } 2425 llvm_unreachable("unhandled error kind"); 2426 } 2427 2428 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2429 unsigned ID, SourceLocation Loc) { 2430 DeclContext *Parent = Context.getTranslationUnitDecl(); 2431 2432 if (getLangOpts().CPlusPlus) { 2433 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2434 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false); 2435 CLinkageDecl->setImplicit(); 2436 Parent->addDecl(CLinkageDecl); 2437 Parent = CLinkageDecl; 2438 } 2439 2440 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2441 /*TInfo=*/nullptr, SC_Extern, 2442 getCurFPFeatures().isFPConstrained(), 2443 false, Type->isFunctionProtoType()); 2444 New->setImplicit(); 2445 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2446 2447 // Create Decl objects for each parameter, adding them to the 2448 // FunctionDecl. 2449 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2450 SmallVector<ParmVarDecl *, 16> Params; 2451 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2452 ParmVarDecl *parm = ParmVarDecl::Create( 2453 Context, New, SourceLocation(), SourceLocation(), nullptr, 2454 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2455 parm->setScopeInfo(0, i); 2456 Params.push_back(parm); 2457 } 2458 New->setParams(Params); 2459 } 2460 2461 AddKnownFunctionAttributes(New); 2462 return New; 2463 } 2464 2465 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2466 /// file scope. lazily create a decl for it. ForRedeclaration is true 2467 /// if we're creating this built-in in anticipation of redeclaring the 2468 /// built-in. 2469 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2470 Scope *S, bool ForRedeclaration, 2471 SourceLocation Loc) { 2472 LookupNecessaryTypesForBuiltin(S, ID); 2473 2474 ASTContext::GetBuiltinTypeError Error; 2475 QualType R = Context.GetBuiltinType(ID, Error); 2476 if (Error) { 2477 if (!ForRedeclaration) 2478 return nullptr; 2479 2480 // If we have a builtin without an associated type we should not emit a 2481 // warning when we were not able to find a type for it. 2482 if (Error == ASTContext::GE_Missing_type || 2483 Context.BuiltinInfo.allowTypeMismatch(ID)) 2484 return nullptr; 2485 2486 // If we could not find a type for setjmp it is because the jmp_buf type was 2487 // not defined prior to the setjmp declaration. 2488 if (Error == ASTContext::GE_Missing_setjmp) { 2489 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2490 << Context.BuiltinInfo.getName(ID); 2491 return nullptr; 2492 } 2493 2494 // Generally, we emit a warning that the declaration requires the 2495 // appropriate header. 2496 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2497 << getHeaderName(Context.BuiltinInfo, ID, Error) 2498 << Context.BuiltinInfo.getName(ID); 2499 return nullptr; 2500 } 2501 2502 if (!ForRedeclaration && 2503 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2504 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2505 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99 2506 : diag::ext_implicit_lib_function_decl) 2507 << Context.BuiltinInfo.getName(ID) << R; 2508 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2509 Diag(Loc, diag::note_include_header_or_declare) 2510 << Header << Context.BuiltinInfo.getName(ID); 2511 } 2512 2513 if (R.isNull()) 2514 return nullptr; 2515 2516 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2517 RegisterLocallyScopedExternCDecl(New, S); 2518 2519 // TUScope is the translation-unit scope to insert this function into. 2520 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2521 // relate Scopes to DeclContexts, and probably eliminate CurContext 2522 // entirely, but we're not there yet. 2523 DeclContext *SavedContext = CurContext; 2524 CurContext = New->getDeclContext(); 2525 PushOnScopeChains(New, TUScope); 2526 CurContext = SavedContext; 2527 return New; 2528 } 2529 2530 /// Typedef declarations don't have linkage, but they still denote the same 2531 /// entity if their types are the same. 2532 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2533 /// isSameEntity. 2534 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2535 TypedefNameDecl *Decl, 2536 LookupResult &Previous) { 2537 // This is only interesting when modules are enabled. 2538 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2539 return; 2540 2541 // Empty sets are uninteresting. 2542 if (Previous.empty()) 2543 return; 2544 2545 LookupResult::Filter Filter = Previous.makeFilter(); 2546 while (Filter.hasNext()) { 2547 NamedDecl *Old = Filter.next(); 2548 2549 // Non-hidden declarations are never ignored. 2550 if (S.isVisible(Old)) 2551 continue; 2552 2553 // Declarations of the same entity are not ignored, even if they have 2554 // different linkages. 2555 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2556 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2557 Decl->getUnderlyingType())) 2558 continue; 2559 2560 // If both declarations give a tag declaration a typedef name for linkage 2561 // purposes, then they declare the same entity. 2562 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2563 Decl->getAnonDeclWithTypedefName()) 2564 continue; 2565 } 2566 2567 Filter.erase(); 2568 } 2569 2570 Filter.done(); 2571 } 2572 2573 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2574 QualType OldType; 2575 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2576 OldType = OldTypedef->getUnderlyingType(); 2577 else 2578 OldType = Context.getTypeDeclType(Old); 2579 QualType NewType = New->getUnderlyingType(); 2580 2581 if (NewType->isVariablyModifiedType()) { 2582 // Must not redefine a typedef with a variably-modified type. 2583 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2584 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2585 << Kind << NewType; 2586 if (Old->getLocation().isValid()) 2587 notePreviousDefinition(Old, New->getLocation()); 2588 New->setInvalidDecl(); 2589 return true; 2590 } 2591 2592 if (OldType != NewType && 2593 !OldType->isDependentType() && 2594 !NewType->isDependentType() && 2595 !Context.hasSameType(OldType, NewType)) { 2596 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2597 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2598 << Kind << NewType << OldType; 2599 if (Old->getLocation().isValid()) 2600 notePreviousDefinition(Old, New->getLocation()); 2601 New->setInvalidDecl(); 2602 return true; 2603 } 2604 return false; 2605 } 2606 2607 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2608 /// same name and scope as a previous declaration 'Old'. Figure out 2609 /// how to resolve this situation, merging decls or emitting 2610 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2611 /// 2612 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2613 LookupResult &OldDecls) { 2614 // If the new decl is known invalid already, don't bother doing any 2615 // merging checks. 2616 if (New->isInvalidDecl()) return; 2617 2618 // Allow multiple definitions for ObjC built-in typedefs. 2619 // FIXME: Verify the underlying types are equivalent! 2620 if (getLangOpts().ObjC) { 2621 const IdentifierInfo *TypeID = New->getIdentifier(); 2622 switch (TypeID->getLength()) { 2623 default: break; 2624 case 2: 2625 { 2626 if (!TypeID->isStr("id")) 2627 break; 2628 QualType T = New->getUnderlyingType(); 2629 if (!T->isPointerType()) 2630 break; 2631 if (!T->isVoidPointerType()) { 2632 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2633 if (!PT->isStructureType()) 2634 break; 2635 } 2636 Context.setObjCIdRedefinitionType(T); 2637 // Install the built-in type for 'id', ignoring the current definition. 2638 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2639 return; 2640 } 2641 case 5: 2642 if (!TypeID->isStr("Class")) 2643 break; 2644 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2645 // Install the built-in type for 'Class', ignoring the current definition. 2646 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2647 return; 2648 case 3: 2649 if (!TypeID->isStr("SEL")) 2650 break; 2651 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2652 // Install the built-in type for 'SEL', ignoring the current definition. 2653 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2654 return; 2655 } 2656 // Fall through - the typedef name was not a builtin type. 2657 } 2658 2659 // Verify the old decl was also a type. 2660 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2661 if (!Old) { 2662 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2663 << New->getDeclName(); 2664 2665 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2666 if (OldD->getLocation().isValid()) 2667 notePreviousDefinition(OldD, New->getLocation()); 2668 2669 return New->setInvalidDecl(); 2670 } 2671 2672 // If the old declaration is invalid, just give up here. 2673 if (Old->isInvalidDecl()) 2674 return New->setInvalidDecl(); 2675 2676 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2677 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2678 auto *NewTag = New->getAnonDeclWithTypedefName(); 2679 NamedDecl *Hidden = nullptr; 2680 if (OldTag && NewTag && 2681 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2682 !hasVisibleDefinition(OldTag, &Hidden)) { 2683 // There is a definition of this tag, but it is not visible. Use it 2684 // instead of our tag. 2685 New->setTypeForDecl(OldTD->getTypeForDecl()); 2686 if (OldTD->isModed()) 2687 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2688 OldTD->getUnderlyingType()); 2689 else 2690 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2691 2692 // Make the old tag definition visible. 2693 makeMergedDefinitionVisible(Hidden); 2694 2695 // If this was an unscoped enumeration, yank all of its enumerators 2696 // out of the scope. 2697 if (isa<EnumDecl>(NewTag)) { 2698 Scope *EnumScope = getNonFieldDeclScope(S); 2699 for (auto *D : NewTag->decls()) { 2700 auto *ED = cast<EnumConstantDecl>(D); 2701 assert(EnumScope->isDeclScope(ED)); 2702 EnumScope->RemoveDecl(ED); 2703 IdResolver.RemoveDecl(ED); 2704 ED->getLexicalDeclContext()->removeDecl(ED); 2705 } 2706 } 2707 } 2708 } 2709 2710 // If the typedef types are not identical, reject them in all languages and 2711 // with any extensions enabled. 2712 if (isIncompatibleTypedef(Old, New)) 2713 return; 2714 2715 // The types match. Link up the redeclaration chain and merge attributes if 2716 // the old declaration was a typedef. 2717 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2718 New->setPreviousDecl(Typedef); 2719 mergeDeclAttributes(New, Old); 2720 } 2721 2722 if (getLangOpts().MicrosoftExt) 2723 return; 2724 2725 if (getLangOpts().CPlusPlus) { 2726 // C++ [dcl.typedef]p2: 2727 // In a given non-class scope, a typedef specifier can be used to 2728 // redefine the name of any type declared in that scope to refer 2729 // to the type to which it already refers. 2730 if (!isa<CXXRecordDecl>(CurContext)) 2731 return; 2732 2733 // C++0x [dcl.typedef]p4: 2734 // In a given class scope, a typedef specifier can be used to redefine 2735 // any class-name declared in that scope that is not also a typedef-name 2736 // to refer to the type to which it already refers. 2737 // 2738 // This wording came in via DR424, which was a correction to the 2739 // wording in DR56, which accidentally banned code like: 2740 // 2741 // struct S { 2742 // typedef struct A { } A; 2743 // }; 2744 // 2745 // in the C++03 standard. We implement the C++0x semantics, which 2746 // allow the above but disallow 2747 // 2748 // struct S { 2749 // typedef int I; 2750 // typedef int I; 2751 // }; 2752 // 2753 // since that was the intent of DR56. 2754 if (!isa<TypedefNameDecl>(Old)) 2755 return; 2756 2757 Diag(New->getLocation(), diag::err_redefinition) 2758 << New->getDeclName(); 2759 notePreviousDefinition(Old, New->getLocation()); 2760 return New->setInvalidDecl(); 2761 } 2762 2763 // Modules always permit redefinition of typedefs, as does C11. 2764 if (getLangOpts().Modules || getLangOpts().C11) 2765 return; 2766 2767 // If we have a redefinition of a typedef in C, emit a warning. This warning 2768 // is normally mapped to an error, but can be controlled with 2769 // -Wtypedef-redefinition. If either the original or the redefinition is 2770 // in a system header, don't emit this for compatibility with GCC. 2771 if (getDiagnostics().getSuppressSystemWarnings() && 2772 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2773 (Old->isImplicit() || 2774 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2775 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2776 return; 2777 2778 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2779 << New->getDeclName(); 2780 notePreviousDefinition(Old, New->getLocation()); 2781 } 2782 2783 /// DeclhasAttr - returns true if decl Declaration already has the target 2784 /// attribute. 2785 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2786 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2787 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2788 for (const auto *i : D->attrs()) 2789 if (i->getKind() == A->getKind()) { 2790 if (Ann) { 2791 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2792 return true; 2793 continue; 2794 } 2795 // FIXME: Don't hardcode this check 2796 if (OA && isa<OwnershipAttr>(i)) 2797 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2798 return true; 2799 } 2800 2801 return false; 2802 } 2803 2804 static bool isAttributeTargetADefinition(Decl *D) { 2805 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2806 return VD->isThisDeclarationADefinition(); 2807 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2808 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2809 return true; 2810 } 2811 2812 /// Merge alignment attributes from \p Old to \p New, taking into account the 2813 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2814 /// 2815 /// \return \c true if any attributes were added to \p New. 2816 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2817 // Look for alignas attributes on Old, and pick out whichever attribute 2818 // specifies the strictest alignment requirement. 2819 AlignedAttr *OldAlignasAttr = nullptr; 2820 AlignedAttr *OldStrictestAlignAttr = nullptr; 2821 unsigned OldAlign = 0; 2822 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2823 // FIXME: We have no way of representing inherited dependent alignments 2824 // in a case like: 2825 // template<int A, int B> struct alignas(A) X; 2826 // template<int A, int B> struct alignas(B) X {}; 2827 // For now, we just ignore any alignas attributes which are not on the 2828 // definition in such a case. 2829 if (I->isAlignmentDependent()) 2830 return false; 2831 2832 if (I->isAlignas()) 2833 OldAlignasAttr = I; 2834 2835 unsigned Align = I->getAlignment(S.Context); 2836 if (Align > OldAlign) { 2837 OldAlign = Align; 2838 OldStrictestAlignAttr = I; 2839 } 2840 } 2841 2842 // Look for alignas attributes on New. 2843 AlignedAttr *NewAlignasAttr = nullptr; 2844 unsigned NewAlign = 0; 2845 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2846 if (I->isAlignmentDependent()) 2847 return false; 2848 2849 if (I->isAlignas()) 2850 NewAlignasAttr = I; 2851 2852 unsigned Align = I->getAlignment(S.Context); 2853 if (Align > NewAlign) 2854 NewAlign = Align; 2855 } 2856 2857 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2858 // Both declarations have 'alignas' attributes. We require them to match. 2859 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2860 // fall short. (If two declarations both have alignas, they must both match 2861 // every definition, and so must match each other if there is a definition.) 2862 2863 // If either declaration only contains 'alignas(0)' specifiers, then it 2864 // specifies the natural alignment for the type. 2865 if (OldAlign == 0 || NewAlign == 0) { 2866 QualType Ty; 2867 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2868 Ty = VD->getType(); 2869 else 2870 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2871 2872 if (OldAlign == 0) 2873 OldAlign = S.Context.getTypeAlign(Ty); 2874 if (NewAlign == 0) 2875 NewAlign = S.Context.getTypeAlign(Ty); 2876 } 2877 2878 if (OldAlign != NewAlign) { 2879 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2880 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2881 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2882 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2883 } 2884 } 2885 2886 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2887 // C++11 [dcl.align]p6: 2888 // if any declaration of an entity has an alignment-specifier, 2889 // every defining declaration of that entity shall specify an 2890 // equivalent alignment. 2891 // C11 6.7.5/7: 2892 // If the definition of an object does not have an alignment 2893 // specifier, any other declaration of that object shall also 2894 // have no alignment specifier. 2895 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2896 << OldAlignasAttr; 2897 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2898 << OldAlignasAttr; 2899 } 2900 2901 bool AnyAdded = false; 2902 2903 // Ensure we have an attribute representing the strictest alignment. 2904 if (OldAlign > NewAlign) { 2905 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2906 Clone->setInherited(true); 2907 New->addAttr(Clone); 2908 AnyAdded = true; 2909 } 2910 2911 // Ensure we have an alignas attribute if the old declaration had one. 2912 if (OldAlignasAttr && !NewAlignasAttr && 2913 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2914 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2915 Clone->setInherited(true); 2916 New->addAttr(Clone); 2917 AnyAdded = true; 2918 } 2919 2920 return AnyAdded; 2921 } 2922 2923 #define WANT_DECL_MERGE_LOGIC 2924 #include "clang/Sema/AttrParsedAttrImpl.inc" 2925 #undef WANT_DECL_MERGE_LOGIC 2926 2927 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2928 const InheritableAttr *Attr, 2929 Sema::AvailabilityMergeKind AMK) { 2930 // Diagnose any mutual exclusions between the attribute that we want to add 2931 // and attributes that already exist on the declaration. 2932 if (!DiagnoseMutualExclusions(S, D, Attr)) 2933 return false; 2934 2935 // This function copies an attribute Attr from a previous declaration to the 2936 // new declaration D if the new declaration doesn't itself have that attribute 2937 // yet or if that attribute allows duplicates. 2938 // If you're adding a new attribute that requires logic different from 2939 // "use explicit attribute on decl if present, else use attribute from 2940 // previous decl", for example if the attribute needs to be consistent 2941 // between redeclarations, you need to call a custom merge function here. 2942 InheritableAttr *NewAttr = nullptr; 2943 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2944 NewAttr = S.mergeAvailabilityAttr( 2945 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2946 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2947 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2948 AA->getPriority()); 2949 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2950 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2951 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2952 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2953 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2954 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2955 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2956 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2957 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2958 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2959 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2960 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2961 FA->getFirstArg()); 2962 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2963 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2964 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2965 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2966 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2967 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2968 IA->getInheritanceModel()); 2969 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2970 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2971 &S.Context.Idents.get(AA->getSpelling())); 2972 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2973 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2974 isa<CUDAGlobalAttr>(Attr))) { 2975 // CUDA target attributes are part of function signature for 2976 // overloading purposes and must not be merged. 2977 return false; 2978 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2979 NewAttr = S.mergeMinSizeAttr(D, *MA); 2980 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2981 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2982 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2983 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2984 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2985 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2986 else if (isa<AlignedAttr>(Attr)) 2987 // AlignedAttrs are handled separately, because we need to handle all 2988 // such attributes on a declaration at the same time. 2989 NewAttr = nullptr; 2990 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2991 (AMK == Sema::AMK_Override || 2992 AMK == Sema::AMK_ProtocolImplementation || 2993 AMK == Sema::AMK_OptionalProtocolImplementation)) 2994 NewAttr = nullptr; 2995 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2996 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2997 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2998 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2999 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 3000 NewAttr = S.mergeImportNameAttr(D, *INA); 3001 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 3002 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 3003 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 3004 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 3005 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) 3006 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); 3007 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr)) 3008 NewAttr = 3009 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ()); 3010 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr)) 3011 NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType()); 3012 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 3013 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 3014 3015 if (NewAttr) { 3016 NewAttr->setInherited(true); 3017 D->addAttr(NewAttr); 3018 if (isa<MSInheritanceAttr>(NewAttr)) 3019 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 3020 return true; 3021 } 3022 3023 return false; 3024 } 3025 3026 static const NamedDecl *getDefinition(const Decl *D) { 3027 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 3028 return TD->getDefinition(); 3029 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 3030 const VarDecl *Def = VD->getDefinition(); 3031 if (Def) 3032 return Def; 3033 return VD->getActingDefinition(); 3034 } 3035 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 3036 const FunctionDecl *Def = nullptr; 3037 if (FD->isDefined(Def, true)) 3038 return Def; 3039 } 3040 return nullptr; 3041 } 3042 3043 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 3044 for (const auto *Attribute : D->attrs()) 3045 if (Attribute->getKind() == Kind) 3046 return true; 3047 return false; 3048 } 3049 3050 /// checkNewAttributesAfterDef - If we already have a definition, check that 3051 /// there are no new attributes in this declaration. 3052 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 3053 if (!New->hasAttrs()) 3054 return; 3055 3056 const NamedDecl *Def = getDefinition(Old); 3057 if (!Def || Def == New) 3058 return; 3059 3060 AttrVec &NewAttributes = New->getAttrs(); 3061 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 3062 const Attr *NewAttribute = NewAttributes[I]; 3063 3064 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 3065 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 3066 Sema::SkipBodyInfo SkipBody; 3067 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 3068 3069 // If we're skipping this definition, drop the "alias" attribute. 3070 if (SkipBody.ShouldSkip) { 3071 NewAttributes.erase(NewAttributes.begin() + I); 3072 --E; 3073 continue; 3074 } 3075 } else { 3076 VarDecl *VD = cast<VarDecl>(New); 3077 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 3078 VarDecl::TentativeDefinition 3079 ? diag::err_alias_after_tentative 3080 : diag::err_redefinition; 3081 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 3082 if (Diag == diag::err_redefinition) 3083 S.notePreviousDefinition(Def, VD->getLocation()); 3084 else 3085 S.Diag(Def->getLocation(), diag::note_previous_definition); 3086 VD->setInvalidDecl(); 3087 } 3088 ++I; 3089 continue; 3090 } 3091 3092 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 3093 // Tentative definitions are only interesting for the alias check above. 3094 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 3095 ++I; 3096 continue; 3097 } 3098 } 3099 3100 if (hasAttribute(Def, NewAttribute->getKind())) { 3101 ++I; 3102 continue; // regular attr merging will take care of validating this. 3103 } 3104 3105 if (isa<C11NoReturnAttr>(NewAttribute)) { 3106 // C's _Noreturn is allowed to be added to a function after it is defined. 3107 ++I; 3108 continue; 3109 } else if (isa<UuidAttr>(NewAttribute)) { 3110 // msvc will allow a subsequent definition to add an uuid to a class 3111 ++I; 3112 continue; 3113 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 3114 if (AA->isAlignas()) { 3115 // C++11 [dcl.align]p6: 3116 // if any declaration of an entity has an alignment-specifier, 3117 // every defining declaration of that entity shall specify an 3118 // equivalent alignment. 3119 // C11 6.7.5/7: 3120 // If the definition of an object does not have an alignment 3121 // specifier, any other declaration of that object shall also 3122 // have no alignment specifier. 3123 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 3124 << AA; 3125 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 3126 << AA; 3127 NewAttributes.erase(NewAttributes.begin() + I); 3128 --E; 3129 continue; 3130 } 3131 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 3132 // If there is a C definition followed by a redeclaration with this 3133 // attribute then there are two different definitions. In C++, prefer the 3134 // standard diagnostics. 3135 if (!S.getLangOpts().CPlusPlus) { 3136 S.Diag(NewAttribute->getLocation(), 3137 diag::err_loader_uninitialized_redeclaration); 3138 S.Diag(Def->getLocation(), diag::note_previous_definition); 3139 NewAttributes.erase(NewAttributes.begin() + I); 3140 --E; 3141 continue; 3142 } 3143 } else if (isa<SelectAnyAttr>(NewAttribute) && 3144 cast<VarDecl>(New)->isInline() && 3145 !cast<VarDecl>(New)->isInlineSpecified()) { 3146 // Don't warn about applying selectany to implicitly inline variables. 3147 // Older compilers and language modes would require the use of selectany 3148 // to make such variables inline, and it would have no effect if we 3149 // honored it. 3150 ++I; 3151 continue; 3152 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 3153 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 3154 // declarations after definitions. 3155 ++I; 3156 continue; 3157 } 3158 3159 S.Diag(NewAttribute->getLocation(), 3160 diag::warn_attribute_precede_definition); 3161 S.Diag(Def->getLocation(), diag::note_previous_definition); 3162 NewAttributes.erase(NewAttributes.begin() + I); 3163 --E; 3164 } 3165 } 3166 3167 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 3168 const ConstInitAttr *CIAttr, 3169 bool AttrBeforeInit) { 3170 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 3171 3172 // Figure out a good way to write this specifier on the old declaration. 3173 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 3174 // enough of the attribute list spelling information to extract that without 3175 // heroics. 3176 std::string SuitableSpelling; 3177 if (S.getLangOpts().CPlusPlus20) 3178 SuitableSpelling = std::string( 3179 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 3180 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 3181 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 3182 InsertLoc, {tok::l_square, tok::l_square, 3183 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 3184 S.PP.getIdentifierInfo("require_constant_initialization"), 3185 tok::r_square, tok::r_square})); 3186 if (SuitableSpelling.empty()) 3187 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 3188 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 3189 S.PP.getIdentifierInfo("require_constant_initialization"), 3190 tok::r_paren, tok::r_paren})); 3191 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 3192 SuitableSpelling = "constinit"; 3193 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 3194 SuitableSpelling = "[[clang::require_constant_initialization]]"; 3195 if (SuitableSpelling.empty()) 3196 SuitableSpelling = "__attribute__((require_constant_initialization))"; 3197 SuitableSpelling += " "; 3198 3199 if (AttrBeforeInit) { 3200 // extern constinit int a; 3201 // int a = 0; // error (missing 'constinit'), accepted as extension 3202 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 3203 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 3204 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3205 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 3206 } else { 3207 // int a = 0; 3208 // constinit extern int a; // error (missing 'constinit') 3209 S.Diag(CIAttr->getLocation(), 3210 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 3211 : diag::warn_require_const_init_added_too_late) 3212 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 3213 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 3214 << CIAttr->isConstinit() 3215 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3216 } 3217 } 3218 3219 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 3220 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 3221 AvailabilityMergeKind AMK) { 3222 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 3223 UsedAttr *NewAttr = OldAttr->clone(Context); 3224 NewAttr->setInherited(true); 3225 New->addAttr(NewAttr); 3226 } 3227 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 3228 RetainAttr *NewAttr = OldAttr->clone(Context); 3229 NewAttr->setInherited(true); 3230 New->addAttr(NewAttr); 3231 } 3232 3233 if (!Old->hasAttrs() && !New->hasAttrs()) 3234 return; 3235 3236 // [dcl.constinit]p1: 3237 // If the [constinit] specifier is applied to any declaration of a 3238 // variable, it shall be applied to the initializing declaration. 3239 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 3240 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 3241 if (bool(OldConstInit) != bool(NewConstInit)) { 3242 const auto *OldVD = cast<VarDecl>(Old); 3243 auto *NewVD = cast<VarDecl>(New); 3244 3245 // Find the initializing declaration. Note that we might not have linked 3246 // the new declaration into the redeclaration chain yet. 3247 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 3248 if (!InitDecl && 3249 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 3250 InitDecl = NewVD; 3251 3252 if (InitDecl == NewVD) { 3253 // This is the initializing declaration. If it would inherit 'constinit', 3254 // that's ill-formed. (Note that we do not apply this to the attribute 3255 // form). 3256 if (OldConstInit && OldConstInit->isConstinit()) 3257 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 3258 /*AttrBeforeInit=*/true); 3259 } else if (NewConstInit) { 3260 // This is the first time we've been told that this declaration should 3261 // have a constant initializer. If we already saw the initializing 3262 // declaration, this is too late. 3263 if (InitDecl && InitDecl != NewVD) { 3264 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 3265 /*AttrBeforeInit=*/false); 3266 NewVD->dropAttr<ConstInitAttr>(); 3267 } 3268 } 3269 } 3270 3271 // Attributes declared post-definition are currently ignored. 3272 checkNewAttributesAfterDef(*this, New, Old); 3273 3274 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 3275 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 3276 if (!OldA->isEquivalent(NewA)) { 3277 // This redeclaration changes __asm__ label. 3278 Diag(New->getLocation(), diag::err_different_asm_label); 3279 Diag(OldA->getLocation(), diag::note_previous_declaration); 3280 } 3281 } else if (Old->isUsed()) { 3282 // This redeclaration adds an __asm__ label to a declaration that has 3283 // already been ODR-used. 3284 Diag(New->getLocation(), diag::err_late_asm_label_name) 3285 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 3286 } 3287 } 3288 3289 // Re-declaration cannot add abi_tag's. 3290 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 3291 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 3292 for (const auto &NewTag : NewAbiTagAttr->tags()) { 3293 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { 3294 Diag(NewAbiTagAttr->getLocation(), 3295 diag::err_new_abi_tag_on_redeclaration) 3296 << NewTag; 3297 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 3298 } 3299 } 3300 } else { 3301 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 3302 Diag(Old->getLocation(), diag::note_previous_declaration); 3303 } 3304 } 3305 3306 // This redeclaration adds a section attribute. 3307 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 3308 if (auto *VD = dyn_cast<VarDecl>(New)) { 3309 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 3310 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 3311 Diag(Old->getLocation(), diag::note_previous_declaration); 3312 } 3313 } 3314 } 3315 3316 // Redeclaration adds code-seg attribute. 3317 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 3318 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 3319 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 3320 Diag(New->getLocation(), diag::warn_mismatched_section) 3321 << 0 /*codeseg*/; 3322 Diag(Old->getLocation(), diag::note_previous_declaration); 3323 } 3324 3325 if (!Old->hasAttrs()) 3326 return; 3327 3328 bool foundAny = New->hasAttrs(); 3329 3330 // Ensure that any moving of objects within the allocated map is done before 3331 // we process them. 3332 if (!foundAny) New->setAttrs(AttrVec()); 3333 3334 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3335 // Ignore deprecated/unavailable/availability attributes if requested. 3336 AvailabilityMergeKind LocalAMK = AMK_None; 3337 if (isa<DeprecatedAttr>(I) || 3338 isa<UnavailableAttr>(I) || 3339 isa<AvailabilityAttr>(I)) { 3340 switch (AMK) { 3341 case AMK_None: 3342 continue; 3343 3344 case AMK_Redeclaration: 3345 case AMK_Override: 3346 case AMK_ProtocolImplementation: 3347 case AMK_OptionalProtocolImplementation: 3348 LocalAMK = AMK; 3349 break; 3350 } 3351 } 3352 3353 // Already handled. 3354 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3355 continue; 3356 3357 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3358 foundAny = true; 3359 } 3360 3361 if (mergeAlignedAttrs(*this, New, Old)) 3362 foundAny = true; 3363 3364 if (!foundAny) New->dropAttrs(); 3365 } 3366 3367 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3368 /// to the new one. 3369 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3370 const ParmVarDecl *oldDecl, 3371 Sema &S) { 3372 // C++11 [dcl.attr.depend]p2: 3373 // The first declaration of a function shall specify the 3374 // carries_dependency attribute for its declarator-id if any declaration 3375 // of the function specifies the carries_dependency attribute. 3376 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3377 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3378 S.Diag(CDA->getLocation(), 3379 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3380 // Find the first declaration of the parameter. 3381 // FIXME: Should we build redeclaration chains for function parameters? 3382 const FunctionDecl *FirstFD = 3383 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3384 const ParmVarDecl *FirstVD = 3385 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3386 S.Diag(FirstVD->getLocation(), 3387 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3388 } 3389 3390 // HLSL parameter declarations for inout and out must match between 3391 // declarations. In HLSL inout and out are ambiguous at the call site, but 3392 // have different calling behavior, so you cannot overload a method based on a 3393 // difference between inout and out annotations. 3394 if (S.getLangOpts().HLSL) { 3395 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>(); 3396 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>(); 3397 // We don't need to cover the case where one declaration doesn't have an 3398 // attribute. The only possible case there is if one declaration has an `in` 3399 // attribute and the other declaration has no attribute. This case is 3400 // allowed since parameters are `in` by default. 3401 if (NDAttr && ODAttr && 3402 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) { 3403 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch) 3404 << NDAttr << newDecl; 3405 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as) 3406 << ODAttr; 3407 } 3408 } 3409 3410 if (!oldDecl->hasAttrs()) 3411 return; 3412 3413 bool foundAny = newDecl->hasAttrs(); 3414 3415 // Ensure that any moving of objects within the allocated map is 3416 // done before we process them. 3417 if (!foundAny) newDecl->setAttrs(AttrVec()); 3418 3419 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3420 if (!DeclHasAttr(newDecl, I)) { 3421 InheritableAttr *newAttr = 3422 cast<InheritableParamAttr>(I->clone(S.Context)); 3423 newAttr->setInherited(true); 3424 newDecl->addAttr(newAttr); 3425 foundAny = true; 3426 } 3427 } 3428 3429 if (!foundAny) newDecl->dropAttrs(); 3430 } 3431 3432 static bool EquivalentArrayTypes(QualType Old, QualType New, 3433 const ASTContext &Ctx) { 3434 3435 auto NoSizeInfo = [&Ctx](QualType Ty) { 3436 if (Ty->isIncompleteArrayType() || Ty->isPointerType()) 3437 return true; 3438 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty)) 3439 return VAT->getSizeModifier() == ArraySizeModifier::Star; 3440 return false; 3441 }; 3442 3443 // `type[]` is equivalent to `type *` and `type[*]`. 3444 if (NoSizeInfo(Old) && NoSizeInfo(New)) 3445 return true; 3446 3447 // Don't try to compare VLA sizes, unless one of them has the star modifier. 3448 if (Old->isVariableArrayType() && New->isVariableArrayType()) { 3449 const auto *OldVAT = Ctx.getAsVariableArrayType(Old); 3450 const auto *NewVAT = Ctx.getAsVariableArrayType(New); 3451 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^ 3452 (NewVAT->getSizeModifier() == ArraySizeModifier::Star)) 3453 return false; 3454 return true; 3455 } 3456 3457 // Only compare size, ignore Size modifiers and CVR. 3458 if (Old->isConstantArrayType() && New->isConstantArrayType()) { 3459 return Ctx.getAsConstantArrayType(Old)->getSize() == 3460 Ctx.getAsConstantArrayType(New)->getSize(); 3461 } 3462 3463 // Don't try to compare dependent sized array 3464 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) { 3465 return true; 3466 } 3467 3468 return Old == New; 3469 } 3470 3471 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3472 const ParmVarDecl *OldParam, 3473 Sema &S) { 3474 if (auto Oldnullability = OldParam->getType()->getNullability()) { 3475 if (auto Newnullability = NewParam->getType()->getNullability()) { 3476 if (*Oldnullability != *Newnullability) { 3477 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3478 << DiagNullabilityKind( 3479 *Newnullability, 3480 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3481 != 0)) 3482 << DiagNullabilityKind( 3483 *Oldnullability, 3484 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3485 != 0)); 3486 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3487 } 3488 } else { 3489 QualType NewT = NewParam->getType(); 3490 NewT = S.Context.getAttributedType( 3491 AttributedType::getNullabilityAttrKind(*Oldnullability), 3492 NewT, NewT); 3493 NewParam->setType(NewT); 3494 } 3495 } 3496 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType()); 3497 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType()); 3498 if (OldParamDT && NewParamDT && 3499 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) { 3500 QualType OldParamOT = OldParamDT->getOriginalType(); 3501 QualType NewParamOT = NewParamDT->getOriginalType(); 3502 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) { 3503 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form) 3504 << NewParam << NewParamOT; 3505 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as) 3506 << OldParamOT; 3507 } 3508 } 3509 } 3510 3511 namespace { 3512 3513 /// Used in MergeFunctionDecl to keep track of function parameters in 3514 /// C. 3515 struct GNUCompatibleParamWarning { 3516 ParmVarDecl *OldParm; 3517 ParmVarDecl *NewParm; 3518 QualType PromotedType; 3519 }; 3520 3521 } // end anonymous namespace 3522 3523 // Determine whether the previous declaration was a definition, implicit 3524 // declaration, or a declaration. 3525 template <typename T> 3526 static std::pair<diag::kind, SourceLocation> 3527 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3528 diag::kind PrevDiag; 3529 SourceLocation OldLocation = Old->getLocation(); 3530 if (Old->isThisDeclarationADefinition()) 3531 PrevDiag = diag::note_previous_definition; 3532 else if (Old->isImplicit()) { 3533 PrevDiag = diag::note_previous_implicit_declaration; 3534 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) { 3535 if (FD->getBuiltinID()) 3536 PrevDiag = diag::note_previous_builtin_declaration; 3537 } 3538 if (OldLocation.isInvalid()) 3539 OldLocation = New->getLocation(); 3540 } else 3541 PrevDiag = diag::note_previous_declaration; 3542 return std::make_pair(PrevDiag, OldLocation); 3543 } 3544 3545 /// canRedefineFunction - checks if a function can be redefined. Currently, 3546 /// only extern inline functions can be redefined, and even then only in 3547 /// GNU89 mode. 3548 static bool canRedefineFunction(const FunctionDecl *FD, 3549 const LangOptions& LangOpts) { 3550 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3551 !LangOpts.CPlusPlus && 3552 FD->isInlineSpecified() && 3553 FD->getStorageClass() == SC_Extern); 3554 } 3555 3556 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3557 const AttributedType *AT = T->getAs<AttributedType>(); 3558 while (AT && !AT->isCallingConv()) 3559 AT = AT->getModifiedType()->getAs<AttributedType>(); 3560 return AT; 3561 } 3562 3563 template <typename T> 3564 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3565 const DeclContext *DC = Old->getDeclContext(); 3566 if (DC->isRecord()) 3567 return false; 3568 3569 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3570 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3571 return true; 3572 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3573 return true; 3574 return false; 3575 } 3576 3577 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3578 static bool isExternC(VarTemplateDecl *) { return false; } 3579 static bool isExternC(FunctionTemplateDecl *) { return false; } 3580 3581 /// Check whether a redeclaration of an entity introduced by a 3582 /// using-declaration is valid, given that we know it's not an overload 3583 /// (nor a hidden tag declaration). 3584 template<typename ExpectedDecl> 3585 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3586 ExpectedDecl *New) { 3587 // C++11 [basic.scope.declarative]p4: 3588 // Given a set of declarations in a single declarative region, each of 3589 // which specifies the same unqualified name, 3590 // -- they shall all refer to the same entity, or all refer to functions 3591 // and function templates; or 3592 // -- exactly one declaration shall declare a class name or enumeration 3593 // name that is not a typedef name and the other declarations shall all 3594 // refer to the same variable or enumerator, or all refer to functions 3595 // and function templates; in this case the class name or enumeration 3596 // name is hidden (3.3.10). 3597 3598 // C++11 [namespace.udecl]p14: 3599 // If a function declaration in namespace scope or block scope has the 3600 // same name and the same parameter-type-list as a function introduced 3601 // by a using-declaration, and the declarations do not declare the same 3602 // function, the program is ill-formed. 3603 3604 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3605 if (Old && 3606 !Old->getDeclContext()->getRedeclContext()->Equals( 3607 New->getDeclContext()->getRedeclContext()) && 3608 !(isExternC(Old) && isExternC(New))) 3609 Old = nullptr; 3610 3611 if (!Old) { 3612 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3613 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3614 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3615 return true; 3616 } 3617 return false; 3618 } 3619 3620 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3621 const FunctionDecl *B) { 3622 assert(A->getNumParams() == B->getNumParams()); 3623 3624 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3625 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3626 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3627 if (AttrA == AttrB) 3628 return true; 3629 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3630 AttrA->isDynamic() == AttrB->isDynamic(); 3631 }; 3632 3633 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3634 } 3635 3636 /// If necessary, adjust the semantic declaration context for a qualified 3637 /// declaration to name the correct inline namespace within the qualifier. 3638 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3639 DeclaratorDecl *OldD) { 3640 // The only case where we need to update the DeclContext is when 3641 // redeclaration lookup for a qualified name finds a declaration 3642 // in an inline namespace within the context named by the qualifier: 3643 // 3644 // inline namespace N { int f(); } 3645 // int ::f(); // Sema DC needs adjusting from :: to N::. 3646 // 3647 // For unqualified declarations, the semantic context *can* change 3648 // along the redeclaration chain (for local extern declarations, 3649 // extern "C" declarations, and friend declarations in particular). 3650 if (!NewD->getQualifier()) 3651 return; 3652 3653 // NewD is probably already in the right context. 3654 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3655 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3656 if (NamedDC->Equals(SemaDC)) 3657 return; 3658 3659 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3660 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3661 "unexpected context for redeclaration"); 3662 3663 auto *LexDC = NewD->getLexicalDeclContext(); 3664 auto FixSemaDC = [=](NamedDecl *D) { 3665 if (!D) 3666 return; 3667 D->setDeclContext(SemaDC); 3668 D->setLexicalDeclContext(LexDC); 3669 }; 3670 3671 FixSemaDC(NewD); 3672 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3673 FixSemaDC(FD->getDescribedFunctionTemplate()); 3674 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3675 FixSemaDC(VD->getDescribedVarTemplate()); 3676 } 3677 3678 /// MergeFunctionDecl - We just parsed a function 'New' from 3679 /// declarator D which has the same name and scope as a previous 3680 /// declaration 'Old'. Figure out how to resolve this situation, 3681 /// merging decls or emitting diagnostics as appropriate. 3682 /// 3683 /// In C++, New and Old must be declarations that are not 3684 /// overloaded. Use IsOverload to determine whether New and Old are 3685 /// overloaded, and to select the Old declaration that New should be 3686 /// merged with. 3687 /// 3688 /// Returns true if there was an error, false otherwise. 3689 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S, 3690 bool MergeTypeWithOld, bool NewDeclIsDefn) { 3691 // Verify the old decl was also a function. 3692 FunctionDecl *Old = OldD->getAsFunction(); 3693 if (!Old) { 3694 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3695 if (New->getFriendObjectKind()) { 3696 Diag(New->getLocation(), diag::err_using_decl_friend); 3697 Diag(Shadow->getTargetDecl()->getLocation(), 3698 diag::note_using_decl_target); 3699 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3700 << 0; 3701 return true; 3702 } 3703 3704 // Check whether the two declarations might declare the same function or 3705 // function template. 3706 if (FunctionTemplateDecl *NewTemplate = 3707 New->getDescribedFunctionTemplate()) { 3708 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3709 NewTemplate)) 3710 return true; 3711 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3712 ->getAsFunction(); 3713 } else { 3714 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3715 return true; 3716 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3717 } 3718 } else { 3719 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3720 << New->getDeclName(); 3721 notePreviousDefinition(OldD, New->getLocation()); 3722 return true; 3723 } 3724 } 3725 3726 // If the old declaration was found in an inline namespace and the new 3727 // declaration was qualified, update the DeclContext to match. 3728 adjustDeclContextForDeclaratorDecl(New, Old); 3729 3730 // If the old declaration is invalid, just give up here. 3731 if (Old->isInvalidDecl()) 3732 return true; 3733 3734 // Disallow redeclaration of some builtins. 3735 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3736 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3737 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3738 << Old << Old->getType(); 3739 return true; 3740 } 3741 3742 diag::kind PrevDiag; 3743 SourceLocation OldLocation; 3744 std::tie(PrevDiag, OldLocation) = 3745 getNoteDiagForInvalidRedeclaration(Old, New); 3746 3747 // Don't complain about this if we're in GNU89 mode and the old function 3748 // is an extern inline function. 3749 // Don't complain about specializations. They are not supposed to have 3750 // storage classes. 3751 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3752 New->getStorageClass() == SC_Static && 3753 Old->hasExternalFormalLinkage() && 3754 !New->getTemplateSpecializationInfo() && 3755 !canRedefineFunction(Old, getLangOpts())) { 3756 if (getLangOpts().MicrosoftExt) { 3757 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3758 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3759 } else { 3760 Diag(New->getLocation(), diag::err_static_non_static) << New; 3761 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3762 return true; 3763 } 3764 } 3765 3766 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3767 if (!Old->hasAttr<InternalLinkageAttr>()) { 3768 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3769 << ILA; 3770 Diag(Old->getLocation(), diag::note_previous_declaration); 3771 New->dropAttr<InternalLinkageAttr>(); 3772 } 3773 3774 if (auto *EA = New->getAttr<ErrorAttr>()) { 3775 if (!Old->hasAttr<ErrorAttr>()) { 3776 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3777 Diag(Old->getLocation(), diag::note_previous_declaration); 3778 New->dropAttr<ErrorAttr>(); 3779 } 3780 } 3781 3782 if (CheckRedeclarationInModule(New, Old)) 3783 return true; 3784 3785 if (!getLangOpts().CPlusPlus) { 3786 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3787 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3788 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3789 << New << OldOvl; 3790 3791 // Try our best to find a decl that actually has the overloadable 3792 // attribute for the note. In most cases (e.g. programs with only one 3793 // broken declaration/definition), this won't matter. 3794 // 3795 // FIXME: We could do this if we juggled some extra state in 3796 // OverloadableAttr, rather than just removing it. 3797 const Decl *DiagOld = Old; 3798 if (OldOvl) { 3799 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3800 const auto *A = D->getAttr<OverloadableAttr>(); 3801 return A && !A->isImplicit(); 3802 }); 3803 // If we've implicitly added *all* of the overloadable attrs to this 3804 // chain, emitting a "previous redecl" note is pointless. 3805 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3806 } 3807 3808 if (DiagOld) 3809 Diag(DiagOld->getLocation(), 3810 diag::note_attribute_overloadable_prev_overload) 3811 << OldOvl; 3812 3813 if (OldOvl) 3814 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3815 else 3816 New->dropAttr<OverloadableAttr>(); 3817 } 3818 } 3819 3820 // It is not permitted to redeclare an SME function with different SME 3821 // attributes. 3822 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) { 3823 Diag(New->getLocation(), diag::err_sme_attr_mismatch) 3824 << New->getType() << Old->getType(); 3825 Diag(OldLocation, diag::note_previous_declaration); 3826 return true; 3827 } 3828 3829 // If a function is first declared with a calling convention, but is later 3830 // declared or defined without one, all following decls assume the calling 3831 // convention of the first. 3832 // 3833 // It's OK if a function is first declared without a calling convention, 3834 // but is later declared or defined with the default calling convention. 3835 // 3836 // To test if either decl has an explicit calling convention, we look for 3837 // AttributedType sugar nodes on the type as written. If they are missing or 3838 // were canonicalized away, we assume the calling convention was implicit. 3839 // 3840 // Note also that we DO NOT return at this point, because we still have 3841 // other tests to run. 3842 QualType OldQType = Context.getCanonicalType(Old->getType()); 3843 QualType NewQType = Context.getCanonicalType(New->getType()); 3844 const FunctionType *OldType = cast<FunctionType>(OldQType); 3845 const FunctionType *NewType = cast<FunctionType>(NewQType); 3846 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3847 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3848 bool RequiresAdjustment = false; 3849 3850 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3851 FunctionDecl *First = Old->getFirstDecl(); 3852 const FunctionType *FT = 3853 First->getType().getCanonicalType()->castAs<FunctionType>(); 3854 FunctionType::ExtInfo FI = FT->getExtInfo(); 3855 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3856 if (!NewCCExplicit) { 3857 // Inherit the CC from the previous declaration if it was specified 3858 // there but not here. 3859 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3860 RequiresAdjustment = true; 3861 } else if (Old->getBuiltinID()) { 3862 // Builtin attribute isn't propagated to the new one yet at this point, 3863 // so we check if the old one is a builtin. 3864 3865 // Calling Conventions on a Builtin aren't really useful and setting a 3866 // default calling convention and cdecl'ing some builtin redeclarations is 3867 // common, so warn and ignore the calling convention on the redeclaration. 3868 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3869 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3870 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3871 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3872 RequiresAdjustment = true; 3873 } else { 3874 // Calling conventions aren't compatible, so complain. 3875 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3876 Diag(New->getLocation(), diag::err_cconv_change) 3877 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3878 << !FirstCCExplicit 3879 << (!FirstCCExplicit ? "" : 3880 FunctionType::getNameForCallConv(FI.getCC())); 3881 3882 // Put the note on the first decl, since it is the one that matters. 3883 Diag(First->getLocation(), diag::note_previous_declaration); 3884 return true; 3885 } 3886 } 3887 3888 // FIXME: diagnose the other way around? 3889 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3890 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3891 RequiresAdjustment = true; 3892 } 3893 3894 // Merge regparm attribute. 3895 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3896 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3897 if (NewTypeInfo.getHasRegParm()) { 3898 Diag(New->getLocation(), diag::err_regparm_mismatch) 3899 << NewType->getRegParmType() 3900 << OldType->getRegParmType(); 3901 Diag(OldLocation, diag::note_previous_declaration); 3902 return true; 3903 } 3904 3905 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3906 RequiresAdjustment = true; 3907 } 3908 3909 // Merge ns_returns_retained attribute. 3910 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3911 if (NewTypeInfo.getProducesResult()) { 3912 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3913 << "'ns_returns_retained'"; 3914 Diag(OldLocation, diag::note_previous_declaration); 3915 return true; 3916 } 3917 3918 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3919 RequiresAdjustment = true; 3920 } 3921 3922 if (OldTypeInfo.getNoCallerSavedRegs() != 3923 NewTypeInfo.getNoCallerSavedRegs()) { 3924 if (NewTypeInfo.getNoCallerSavedRegs()) { 3925 AnyX86NoCallerSavedRegistersAttr *Attr = 3926 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3927 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3928 Diag(OldLocation, diag::note_previous_declaration); 3929 return true; 3930 } 3931 3932 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3933 RequiresAdjustment = true; 3934 } 3935 3936 if (RequiresAdjustment) { 3937 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3938 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3939 New->setType(QualType(AdjustedType, 0)); 3940 NewQType = Context.getCanonicalType(New->getType()); 3941 } 3942 3943 // If this redeclaration makes the function inline, we may need to add it to 3944 // UndefinedButUsed. 3945 if (!Old->isInlined() && New->isInlined() && 3946 !New->hasAttr<GNUInlineAttr>() && 3947 !getLangOpts().GNUInline && 3948 Old->isUsed(false) && 3949 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3950 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3951 SourceLocation())); 3952 3953 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3954 // about it. 3955 if (New->hasAttr<GNUInlineAttr>() && 3956 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3957 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3958 } 3959 3960 // If pass_object_size params don't match up perfectly, this isn't a valid 3961 // redeclaration. 3962 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3963 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3964 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3965 << New->getDeclName(); 3966 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3967 return true; 3968 } 3969 3970 if (getLangOpts().CPlusPlus) { 3971 OldQType = Context.getCanonicalType(Old->getType()); 3972 NewQType = Context.getCanonicalType(New->getType()); 3973 3974 // Go back to the type source info to compare the declared return types, 3975 // per C++1y [dcl.type.auto]p13: 3976 // Redeclarations or specializations of a function or function template 3977 // with a declared return type that uses a placeholder type shall also 3978 // use that placeholder, not a deduced type. 3979 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3980 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3981 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3982 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3983 OldDeclaredReturnType)) { 3984 QualType ResQT; 3985 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3986 OldDeclaredReturnType->isObjCObjectPointerType()) 3987 // FIXME: This does the wrong thing for a deduced return type. 3988 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3989 if (ResQT.isNull()) { 3990 if (New->isCXXClassMember() && New->isOutOfLine()) 3991 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3992 << New << New->getReturnTypeSourceRange(); 3993 else 3994 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3995 << New->getReturnTypeSourceRange(); 3996 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3997 << Old->getReturnTypeSourceRange(); 3998 return true; 3999 } 4000 else 4001 NewQType = ResQT; 4002 } 4003 4004 QualType OldReturnType = OldType->getReturnType(); 4005 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 4006 if (OldReturnType != NewReturnType) { 4007 // If this function has a deduced return type and has already been 4008 // defined, copy the deduced value from the old declaration. 4009 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 4010 if (OldAT && OldAT->isDeduced()) { 4011 QualType DT = OldAT->getDeducedType(); 4012 if (DT.isNull()) { 4013 New->setType(SubstAutoTypeDependent(New->getType())); 4014 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); 4015 } else { 4016 New->setType(SubstAutoType(New->getType(), DT)); 4017 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); 4018 } 4019 } 4020 } 4021 4022 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 4023 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 4024 if (OldMethod && NewMethod) { 4025 // Preserve triviality. 4026 NewMethod->setTrivial(OldMethod->isTrivial()); 4027 4028 // MSVC allows explicit template specialization at class scope: 4029 // 2 CXXMethodDecls referring to the same function will be injected. 4030 // We don't want a redeclaration error. 4031 bool IsClassScopeExplicitSpecialization = 4032 OldMethod->isFunctionTemplateSpecialization() && 4033 NewMethod->isFunctionTemplateSpecialization(); 4034 bool isFriend = NewMethod->getFriendObjectKind(); 4035 4036 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 4037 !IsClassScopeExplicitSpecialization) { 4038 // -- Member function declarations with the same name and the 4039 // same parameter types cannot be overloaded if any of them 4040 // is a static member function declaration. 4041 if (OldMethod->isStatic() != NewMethod->isStatic()) { 4042 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 4043 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4044 return true; 4045 } 4046 4047 // C++ [class.mem]p1: 4048 // [...] A member shall not be declared twice in the 4049 // member-specification, except that a nested class or member 4050 // class template can be declared and then later defined. 4051 if (!inTemplateInstantiation()) { 4052 unsigned NewDiag; 4053 if (isa<CXXConstructorDecl>(OldMethod)) 4054 NewDiag = diag::err_constructor_redeclared; 4055 else if (isa<CXXDestructorDecl>(NewMethod)) 4056 NewDiag = diag::err_destructor_redeclared; 4057 else if (isa<CXXConversionDecl>(NewMethod)) 4058 NewDiag = diag::err_conv_function_redeclared; 4059 else 4060 NewDiag = diag::err_member_redeclared; 4061 4062 Diag(New->getLocation(), NewDiag); 4063 } else { 4064 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 4065 << New << New->getType(); 4066 } 4067 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4068 return true; 4069 4070 // Complain if this is an explicit declaration of a special 4071 // member that was initially declared implicitly. 4072 // 4073 // As an exception, it's okay to befriend such methods in order 4074 // to permit the implicit constructor/destructor/operator calls. 4075 } else if (OldMethod->isImplicit()) { 4076 if (isFriend) { 4077 NewMethod->setImplicit(); 4078 } else { 4079 Diag(NewMethod->getLocation(), 4080 diag::err_definition_of_implicitly_declared_member) 4081 << New << getSpecialMember(OldMethod); 4082 return true; 4083 } 4084 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 4085 Diag(NewMethod->getLocation(), 4086 diag::err_definition_of_explicitly_defaulted_member) 4087 << getSpecialMember(OldMethod); 4088 return true; 4089 } 4090 } 4091 4092 // C++1z [over.load]p2 4093 // Certain function declarations cannot be overloaded: 4094 // -- Function declarations that differ only in the return type, 4095 // the exception specification, or both cannot be overloaded. 4096 4097 // Check the exception specifications match. This may recompute the type of 4098 // both Old and New if it resolved exception specifications, so grab the 4099 // types again after this. Because this updates the type, we do this before 4100 // any of the other checks below, which may update the "de facto" NewQType 4101 // but do not necessarily update the type of New. 4102 if (CheckEquivalentExceptionSpec(Old, New)) 4103 return true; 4104 4105 // C++11 [dcl.attr.noreturn]p1: 4106 // The first declaration of a function shall specify the noreturn 4107 // attribute if any declaration of that function specifies the noreturn 4108 // attribute. 4109 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 4110 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 4111 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 4112 << NRA; 4113 Diag(Old->getLocation(), diag::note_previous_declaration); 4114 } 4115 4116 // C++11 [dcl.attr.depend]p2: 4117 // The first declaration of a function shall specify the 4118 // carries_dependency attribute for its declarator-id if any declaration 4119 // of the function specifies the carries_dependency attribute. 4120 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 4121 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 4122 Diag(CDA->getLocation(), 4123 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 4124 Diag(Old->getFirstDecl()->getLocation(), 4125 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 4126 } 4127 4128 // (C++98 8.3.5p3): 4129 // All declarations for a function shall agree exactly in both the 4130 // return type and the parameter-type-list. 4131 // We also want to respect all the extended bits except noreturn. 4132 4133 // noreturn should now match unless the old type info didn't have it. 4134 QualType OldQTypeForComparison = OldQType; 4135 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 4136 auto *OldType = OldQType->castAs<FunctionProtoType>(); 4137 const FunctionType *OldTypeForComparison 4138 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 4139 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 4140 assert(OldQTypeForComparison.isCanonical()); 4141 } 4142 4143 if (haveIncompatibleLanguageLinkages(Old, New)) { 4144 // As a special case, retain the language linkage from previous 4145 // declarations of a friend function as an extension. 4146 // 4147 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 4148 // and is useful because there's otherwise no way to specify language 4149 // linkage within class scope. 4150 // 4151 // Check cautiously as the friend object kind isn't yet complete. 4152 if (New->getFriendObjectKind() != Decl::FOK_None) { 4153 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 4154 Diag(OldLocation, PrevDiag); 4155 } else { 4156 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4157 Diag(OldLocation, PrevDiag); 4158 return true; 4159 } 4160 } 4161 4162 // If the function types are compatible, merge the declarations. Ignore the 4163 // exception specifier because it was already checked above in 4164 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 4165 // about incompatible types under -fms-compatibility. 4166 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 4167 NewQType)) 4168 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4169 4170 // If the types are imprecise (due to dependent constructs in friends or 4171 // local extern declarations), it's OK if they differ. We'll check again 4172 // during instantiation. 4173 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 4174 return false; 4175 4176 // Fall through for conflicting redeclarations and redefinitions. 4177 } 4178 4179 // C: Function types need to be compatible, not identical. This handles 4180 // duplicate function decls like "void f(int); void f(enum X);" properly. 4181 if (!getLangOpts().CPlusPlus) { 4182 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other 4183 // type is specified by a function definition that contains a (possibly 4184 // empty) identifier list, both shall agree in the number of parameters 4185 // and the type of each parameter shall be compatible with the type that 4186 // results from the application of default argument promotions to the 4187 // type of the corresponding identifier. ... 4188 // This cannot be handled by ASTContext::typesAreCompatible() because that 4189 // doesn't know whether the function type is for a definition or not when 4190 // eventually calling ASTContext::mergeFunctionTypes(). The only situation 4191 // we need to cover here is that the number of arguments agree as the 4192 // default argument promotion rules were already checked by 4193 // ASTContext::typesAreCompatible(). 4194 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn && 4195 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) { 4196 if (Old->hasInheritedPrototype()) 4197 Old = Old->getCanonicalDecl(); 4198 Diag(New->getLocation(), diag::err_conflicting_types) << New; 4199 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 4200 return true; 4201 } 4202 4203 // If we are merging two functions where only one of them has a prototype, 4204 // we may have enough information to decide to issue a diagnostic that the 4205 // function without a protoype will change behavior in C23. This handles 4206 // cases like: 4207 // void i(); void i(int j); 4208 // void i(int j); void i(); 4209 // void i(); void i(int j) {} 4210 // See ActOnFinishFunctionBody() for other cases of the behavior change 4211 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 4212 // type without a prototype. 4213 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() && 4214 !New->isImplicit() && !Old->isImplicit()) { 4215 const FunctionDecl *WithProto, *WithoutProto; 4216 if (New->hasWrittenPrototype()) { 4217 WithProto = New; 4218 WithoutProto = Old; 4219 } else { 4220 WithProto = Old; 4221 WithoutProto = New; 4222 } 4223 4224 if (WithProto->getNumParams() != 0) { 4225 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) { 4226 // The one without the prototype will be changing behavior in C23, so 4227 // warn about that one so long as it's a user-visible declaration. 4228 bool IsWithoutProtoADef = false, IsWithProtoADef = false; 4229 if (WithoutProto == New) 4230 IsWithoutProtoADef = NewDeclIsDefn; 4231 else 4232 IsWithProtoADef = NewDeclIsDefn; 4233 Diag(WithoutProto->getLocation(), 4234 diag::warn_non_prototype_changes_behavior) 4235 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1) 4236 << (WithoutProto == Old) << IsWithProtoADef; 4237 4238 // The reason the one without the prototype will be changing behavior 4239 // is because of the one with the prototype, so note that so long as 4240 // it's a user-visible declaration. There is one exception to this: 4241 // when the new declaration is a definition without a prototype, the 4242 // old declaration with a prototype is not the cause of the issue, 4243 // and that does not need to be noted because the one with a 4244 // prototype will not change behavior in C23. 4245 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() && 4246 !IsWithoutProtoADef) 4247 Diag(WithProto->getLocation(), diag::note_conflicting_prototype); 4248 } 4249 } 4250 } 4251 4252 if (Context.typesAreCompatible(OldQType, NewQType)) { 4253 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 4254 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 4255 const FunctionProtoType *OldProto = nullptr; 4256 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 4257 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 4258 // The old declaration provided a function prototype, but the 4259 // new declaration does not. Merge in the prototype. 4260 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 4261 NewQType = Context.getFunctionType(NewFuncType->getReturnType(), 4262 OldProto->getParamTypes(), 4263 OldProto->getExtProtoInfo()); 4264 New->setType(NewQType); 4265 New->setHasInheritedPrototype(); 4266 4267 // Synthesize parameters with the same types. 4268 SmallVector<ParmVarDecl *, 16> Params; 4269 for (const auto &ParamType : OldProto->param_types()) { 4270 ParmVarDecl *Param = ParmVarDecl::Create( 4271 Context, New, SourceLocation(), SourceLocation(), nullptr, 4272 ParamType, /*TInfo=*/nullptr, SC_None, nullptr); 4273 Param->setScopeInfo(0, Params.size()); 4274 Param->setImplicit(); 4275 Params.push_back(Param); 4276 } 4277 4278 New->setParams(Params); 4279 } 4280 4281 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4282 } 4283 } 4284 4285 // Check if the function types are compatible when pointer size address 4286 // spaces are ignored. 4287 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 4288 return false; 4289 4290 // GNU C permits a K&R definition to follow a prototype declaration 4291 // if the declared types of the parameters in the K&R definition 4292 // match the types in the prototype declaration, even when the 4293 // promoted types of the parameters from the K&R definition differ 4294 // from the types in the prototype. GCC then keeps the types from 4295 // the prototype. 4296 // 4297 // If a variadic prototype is followed by a non-variadic K&R definition, 4298 // the K&R definition becomes variadic. This is sort of an edge case, but 4299 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 4300 // C99 6.9.1p8. 4301 if (!getLangOpts().CPlusPlus && 4302 Old->hasPrototype() && !New->hasPrototype() && 4303 New->getType()->getAs<FunctionProtoType>() && 4304 Old->getNumParams() == New->getNumParams()) { 4305 SmallVector<QualType, 16> ArgTypes; 4306 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 4307 const FunctionProtoType *OldProto 4308 = Old->getType()->getAs<FunctionProtoType>(); 4309 const FunctionProtoType *NewProto 4310 = New->getType()->getAs<FunctionProtoType>(); 4311 4312 // Determine whether this is the GNU C extension. 4313 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 4314 NewProto->getReturnType()); 4315 bool LooseCompatible = !MergedReturn.isNull(); 4316 for (unsigned Idx = 0, End = Old->getNumParams(); 4317 LooseCompatible && Idx != End; ++Idx) { 4318 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 4319 ParmVarDecl *NewParm = New->getParamDecl(Idx); 4320 if (Context.typesAreCompatible(OldParm->getType(), 4321 NewProto->getParamType(Idx))) { 4322 ArgTypes.push_back(NewParm->getType()); 4323 } else if (Context.typesAreCompatible(OldParm->getType(), 4324 NewParm->getType(), 4325 /*CompareUnqualified=*/true)) { 4326 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 4327 NewProto->getParamType(Idx) }; 4328 Warnings.push_back(Warn); 4329 ArgTypes.push_back(NewParm->getType()); 4330 } else 4331 LooseCompatible = false; 4332 } 4333 4334 if (LooseCompatible) { 4335 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 4336 Diag(Warnings[Warn].NewParm->getLocation(), 4337 diag::ext_param_promoted_not_compatible_with_prototype) 4338 << Warnings[Warn].PromotedType 4339 << Warnings[Warn].OldParm->getType(); 4340 if (Warnings[Warn].OldParm->getLocation().isValid()) 4341 Diag(Warnings[Warn].OldParm->getLocation(), 4342 diag::note_previous_declaration); 4343 } 4344 4345 if (MergeTypeWithOld) 4346 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 4347 OldProto->getExtProtoInfo())); 4348 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4349 } 4350 4351 // Fall through to diagnose conflicting types. 4352 } 4353 4354 // A function that has already been declared has been redeclared or 4355 // defined with a different type; show an appropriate diagnostic. 4356 4357 // If the previous declaration was an implicitly-generated builtin 4358 // declaration, then at the very least we should use a specialized note. 4359 unsigned BuiltinID; 4360 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 4361 // If it's actually a library-defined builtin function like 'malloc' 4362 // or 'printf', just warn about the incompatible redeclaration. 4363 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 4364 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 4365 Diag(OldLocation, diag::note_previous_builtin_declaration) 4366 << Old << Old->getType(); 4367 return false; 4368 } 4369 4370 PrevDiag = diag::note_previous_builtin_declaration; 4371 } 4372 4373 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 4374 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4375 return true; 4376 } 4377 4378 /// Completes the merge of two function declarations that are 4379 /// known to be compatible. 4380 /// 4381 /// This routine handles the merging of attributes and other 4382 /// properties of function declarations from the old declaration to 4383 /// the new declaration, once we know that New is in fact a 4384 /// redeclaration of Old. 4385 /// 4386 /// \returns false 4387 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 4388 Scope *S, bool MergeTypeWithOld) { 4389 // Merge the attributes 4390 mergeDeclAttributes(New, Old); 4391 4392 // Merge "pure" flag. 4393 if (Old->isPureVirtual()) 4394 New->setIsPureVirtual(); 4395 4396 // Merge "used" flag. 4397 if (Old->getMostRecentDecl()->isUsed(false)) 4398 New->setIsUsed(); 4399 4400 // Merge attributes from the parameters. These can mismatch with K&R 4401 // declarations. 4402 if (New->getNumParams() == Old->getNumParams()) 4403 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 4404 ParmVarDecl *NewParam = New->getParamDecl(i); 4405 ParmVarDecl *OldParam = Old->getParamDecl(i); 4406 mergeParamDeclAttributes(NewParam, OldParam, *this); 4407 mergeParamDeclTypes(NewParam, OldParam, *this); 4408 } 4409 4410 if (getLangOpts().CPlusPlus) 4411 return MergeCXXFunctionDecl(New, Old, S); 4412 4413 // Merge the function types so the we get the composite types for the return 4414 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 4415 // was visible. 4416 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 4417 if (!Merged.isNull() && MergeTypeWithOld) 4418 New->setType(Merged); 4419 4420 return false; 4421 } 4422 4423 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 4424 ObjCMethodDecl *oldMethod) { 4425 // Merge the attributes, including deprecated/unavailable 4426 AvailabilityMergeKind MergeKind = 4427 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 4428 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 4429 : AMK_ProtocolImplementation) 4430 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 4431 : AMK_Override; 4432 4433 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 4434 4435 // Merge attributes from the parameters. 4436 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 4437 oe = oldMethod->param_end(); 4438 for (ObjCMethodDecl::param_iterator 4439 ni = newMethod->param_begin(), ne = newMethod->param_end(); 4440 ni != ne && oi != oe; ++ni, ++oi) 4441 mergeParamDeclAttributes(*ni, *oi, *this); 4442 4443 CheckObjCMethodOverride(newMethod, oldMethod); 4444 } 4445 4446 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 4447 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 4448 4449 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 4450 ? diag::err_redefinition_different_type 4451 : diag::err_redeclaration_different_type) 4452 << New->getDeclName() << New->getType() << Old->getType(); 4453 4454 diag::kind PrevDiag; 4455 SourceLocation OldLocation; 4456 std::tie(PrevDiag, OldLocation) 4457 = getNoteDiagForInvalidRedeclaration(Old, New); 4458 S.Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4459 New->setInvalidDecl(); 4460 } 4461 4462 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 4463 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 4464 /// emitting diagnostics as appropriate. 4465 /// 4466 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 4467 /// to here in AddInitializerToDecl. We can't check them before the initializer 4468 /// is attached. 4469 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 4470 bool MergeTypeWithOld) { 4471 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors()) 4472 return; 4473 4474 QualType MergedT; 4475 if (getLangOpts().CPlusPlus) { 4476 if (New->getType()->isUndeducedType()) { 4477 // We don't know what the new type is until the initializer is attached. 4478 return; 4479 } else if (Context.hasSameType(New->getType(), Old->getType())) { 4480 // These could still be something that needs exception specs checked. 4481 return MergeVarDeclExceptionSpecs(New, Old); 4482 } 4483 // C++ [basic.link]p10: 4484 // [...] the types specified by all declarations referring to a given 4485 // object or function shall be identical, except that declarations for an 4486 // array object can specify array types that differ by the presence or 4487 // absence of a major array bound (8.3.4). 4488 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4489 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4490 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4491 4492 // We are merging a variable declaration New into Old. If it has an array 4493 // bound, and that bound differs from Old's bound, we should diagnose the 4494 // mismatch. 4495 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4496 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4497 PrevVD = PrevVD->getPreviousDecl()) { 4498 QualType PrevVDTy = PrevVD->getType(); 4499 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4500 continue; 4501 4502 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4503 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4504 } 4505 } 4506 4507 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4508 if (Context.hasSameType(OldArray->getElementType(), 4509 NewArray->getElementType())) 4510 MergedT = New->getType(); 4511 } 4512 // FIXME: Check visibility. New is hidden but has a complete type. If New 4513 // has no array bound, it should not inherit one from Old, if Old is not 4514 // visible. 4515 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4516 if (Context.hasSameType(OldArray->getElementType(), 4517 NewArray->getElementType())) 4518 MergedT = Old->getType(); 4519 } 4520 } 4521 else if (New->getType()->isObjCObjectPointerType() && 4522 Old->getType()->isObjCObjectPointerType()) { 4523 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4524 Old->getType()); 4525 } 4526 } else { 4527 // C 6.2.7p2: 4528 // All declarations that refer to the same object or function shall have 4529 // compatible type. 4530 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4531 } 4532 if (MergedT.isNull()) { 4533 // It's OK if we couldn't merge types if either type is dependent, for a 4534 // block-scope variable. In other cases (static data members of class 4535 // templates, variable templates, ...), we require the types to be 4536 // equivalent. 4537 // FIXME: The C++ standard doesn't say anything about this. 4538 if ((New->getType()->isDependentType() || 4539 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4540 // If the old type was dependent, we can't merge with it, so the new type 4541 // becomes dependent for now. We'll reproduce the original type when we 4542 // instantiate the TypeSourceInfo for the variable. 4543 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4544 New->setType(Context.DependentTy); 4545 return; 4546 } 4547 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4548 } 4549 4550 // Don't actually update the type on the new declaration if the old 4551 // declaration was an extern declaration in a different scope. 4552 if (MergeTypeWithOld) 4553 New->setType(MergedT); 4554 } 4555 4556 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4557 LookupResult &Previous) { 4558 // C11 6.2.7p4: 4559 // For an identifier with internal or external linkage declared 4560 // in a scope in which a prior declaration of that identifier is 4561 // visible, if the prior declaration specifies internal or 4562 // external linkage, the type of the identifier at the later 4563 // declaration becomes the composite type. 4564 // 4565 // If the variable isn't visible, we do not merge with its type. 4566 if (Previous.isShadowed()) 4567 return false; 4568 4569 if (S.getLangOpts().CPlusPlus) { 4570 // C++11 [dcl.array]p3: 4571 // If there is a preceding declaration of the entity in the same 4572 // scope in which the bound was specified, an omitted array bound 4573 // is taken to be the same as in that earlier declaration. 4574 return NewVD->isPreviousDeclInSameBlockScope() || 4575 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4576 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4577 } else { 4578 // If the old declaration was function-local, don't merge with its 4579 // type unless we're in the same function. 4580 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4581 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4582 } 4583 } 4584 4585 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4586 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4587 /// situation, merging decls or emitting diagnostics as appropriate. 4588 /// 4589 /// Tentative definition rules (C99 6.9.2p2) are checked by 4590 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4591 /// definitions here, since the initializer hasn't been attached. 4592 /// 4593 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4594 // If the new decl is already invalid, don't do any other checking. 4595 if (New->isInvalidDecl()) 4596 return; 4597 4598 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4599 return; 4600 4601 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4602 4603 // Verify the old decl was also a variable or variable template. 4604 VarDecl *Old = nullptr; 4605 VarTemplateDecl *OldTemplate = nullptr; 4606 if (Previous.isSingleResult()) { 4607 if (NewTemplate) { 4608 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4609 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4610 4611 if (auto *Shadow = 4612 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4613 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4614 return New->setInvalidDecl(); 4615 } else { 4616 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4617 4618 if (auto *Shadow = 4619 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4620 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4621 return New->setInvalidDecl(); 4622 } 4623 } 4624 if (!Old) { 4625 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4626 << New->getDeclName(); 4627 notePreviousDefinition(Previous.getRepresentativeDecl(), 4628 New->getLocation()); 4629 return New->setInvalidDecl(); 4630 } 4631 4632 // If the old declaration was found in an inline namespace and the new 4633 // declaration was qualified, update the DeclContext to match. 4634 adjustDeclContextForDeclaratorDecl(New, Old); 4635 4636 // Ensure the template parameters are compatible. 4637 if (NewTemplate && 4638 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4639 OldTemplate->getTemplateParameters(), 4640 /*Complain=*/true, TPL_TemplateMatch)) 4641 return New->setInvalidDecl(); 4642 4643 // C++ [class.mem]p1: 4644 // A member shall not be declared twice in the member-specification [...] 4645 // 4646 // Here, we need only consider static data members. 4647 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4648 Diag(New->getLocation(), diag::err_duplicate_member) 4649 << New->getIdentifier(); 4650 Diag(Old->getLocation(), diag::note_previous_declaration); 4651 New->setInvalidDecl(); 4652 } 4653 4654 mergeDeclAttributes(New, Old); 4655 // Warn if an already-declared variable is made a weak_import in a subsequent 4656 // declaration 4657 if (New->hasAttr<WeakImportAttr>() && 4658 Old->getStorageClass() == SC_None && 4659 !Old->hasAttr<WeakImportAttr>()) { 4660 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4661 Diag(Old->getLocation(), diag::note_previous_declaration); 4662 // Remove weak_import attribute on new declaration. 4663 New->dropAttr<WeakImportAttr>(); 4664 } 4665 4666 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4667 if (!Old->hasAttr<InternalLinkageAttr>()) { 4668 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4669 << ILA; 4670 Diag(Old->getLocation(), diag::note_previous_declaration); 4671 New->dropAttr<InternalLinkageAttr>(); 4672 } 4673 4674 // Merge the types. 4675 VarDecl *MostRecent = Old->getMostRecentDecl(); 4676 if (MostRecent != Old) { 4677 MergeVarDeclTypes(New, MostRecent, 4678 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4679 if (New->isInvalidDecl()) 4680 return; 4681 } 4682 4683 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4684 if (New->isInvalidDecl()) 4685 return; 4686 4687 diag::kind PrevDiag; 4688 SourceLocation OldLocation; 4689 std::tie(PrevDiag, OldLocation) = 4690 getNoteDiagForInvalidRedeclaration(Old, New); 4691 4692 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4693 if (New->getStorageClass() == SC_Static && 4694 !New->isStaticDataMember() && 4695 Old->hasExternalFormalLinkage()) { 4696 if (getLangOpts().MicrosoftExt) { 4697 Diag(New->getLocation(), diag::ext_static_non_static) 4698 << New->getDeclName(); 4699 Diag(OldLocation, PrevDiag); 4700 } else { 4701 Diag(New->getLocation(), diag::err_static_non_static) 4702 << New->getDeclName(); 4703 Diag(OldLocation, PrevDiag); 4704 return New->setInvalidDecl(); 4705 } 4706 } 4707 // C99 6.2.2p4: 4708 // For an identifier declared with the storage-class specifier 4709 // extern in a scope in which a prior declaration of that 4710 // identifier is visible,23) if the prior declaration specifies 4711 // internal or external linkage, the linkage of the identifier at 4712 // the later declaration is the same as the linkage specified at 4713 // the prior declaration. If no prior declaration is visible, or 4714 // if the prior declaration specifies no linkage, then the 4715 // identifier has external linkage. 4716 if (New->hasExternalStorage() && Old->hasLinkage()) 4717 /* Okay */; 4718 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4719 !New->isStaticDataMember() && 4720 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4721 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4722 Diag(OldLocation, PrevDiag); 4723 return New->setInvalidDecl(); 4724 } 4725 4726 // Check if extern is followed by non-extern and vice-versa. 4727 if (New->hasExternalStorage() && 4728 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4729 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4730 Diag(OldLocation, PrevDiag); 4731 return New->setInvalidDecl(); 4732 } 4733 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4734 !New->hasExternalStorage()) { 4735 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4736 Diag(OldLocation, PrevDiag); 4737 return New->setInvalidDecl(); 4738 } 4739 4740 if (CheckRedeclarationInModule(New, Old)) 4741 return; 4742 4743 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4744 4745 // FIXME: The test for external storage here seems wrong? We still 4746 // need to check for mismatches. 4747 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4748 // Don't complain about out-of-line definitions of static members. 4749 !(Old->getLexicalDeclContext()->isRecord() && 4750 !New->getLexicalDeclContext()->isRecord())) { 4751 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4752 Diag(OldLocation, PrevDiag); 4753 return New->setInvalidDecl(); 4754 } 4755 4756 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4757 if (VarDecl *Def = Old->getDefinition()) { 4758 // C++1z [dcl.fcn.spec]p4: 4759 // If the definition of a variable appears in a translation unit before 4760 // its first declaration as inline, the program is ill-formed. 4761 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4762 Diag(Def->getLocation(), diag::note_previous_definition); 4763 } 4764 } 4765 4766 // If this redeclaration makes the variable inline, we may need to add it to 4767 // UndefinedButUsed. 4768 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4769 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4770 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4771 SourceLocation())); 4772 4773 if (New->getTLSKind() != Old->getTLSKind()) { 4774 if (!Old->getTLSKind()) { 4775 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4776 Diag(OldLocation, PrevDiag); 4777 } else if (!New->getTLSKind()) { 4778 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4779 Diag(OldLocation, PrevDiag); 4780 } else { 4781 // Do not allow redeclaration to change the variable between requiring 4782 // static and dynamic initialization. 4783 // FIXME: GCC allows this, but uses the TLS keyword on the first 4784 // declaration to determine the kind. Do we need to be compatible here? 4785 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4786 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4787 Diag(OldLocation, PrevDiag); 4788 } 4789 } 4790 4791 // C++ doesn't have tentative definitions, so go right ahead and check here. 4792 if (getLangOpts().CPlusPlus) { 4793 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4794 Old->getCanonicalDecl()->isConstexpr()) { 4795 // This definition won't be a definition any more once it's been merged. 4796 Diag(New->getLocation(), 4797 diag::warn_deprecated_redundant_constexpr_static_def); 4798 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) { 4799 VarDecl *Def = Old->getDefinition(); 4800 if (Def && checkVarDeclRedefinition(Def, New)) 4801 return; 4802 } 4803 } 4804 4805 if (haveIncompatibleLanguageLinkages(Old, New)) { 4806 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4807 Diag(OldLocation, PrevDiag); 4808 New->setInvalidDecl(); 4809 return; 4810 } 4811 4812 // Merge "used" flag. 4813 if (Old->getMostRecentDecl()->isUsed(false)) 4814 New->setIsUsed(); 4815 4816 // Keep a chain of previous declarations. 4817 New->setPreviousDecl(Old); 4818 if (NewTemplate) 4819 NewTemplate->setPreviousDecl(OldTemplate); 4820 4821 // Inherit access appropriately. 4822 New->setAccess(Old->getAccess()); 4823 if (NewTemplate) 4824 NewTemplate->setAccess(New->getAccess()); 4825 4826 if (Old->isInline()) 4827 New->setImplicitlyInline(); 4828 } 4829 4830 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4831 SourceManager &SrcMgr = getSourceManager(); 4832 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4833 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4834 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4835 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first); 4836 auto &HSI = PP.getHeaderSearchInfo(); 4837 StringRef HdrFilename = 4838 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4839 4840 auto noteFromModuleOrInclude = [&](Module *Mod, 4841 SourceLocation IncLoc) -> bool { 4842 // Redefinition errors with modules are common with non modular mapped 4843 // headers, example: a non-modular header H in module A that also gets 4844 // included directly in a TU. Pointing twice to the same header/definition 4845 // is confusing, try to get better diagnostics when modules is on. 4846 if (IncLoc.isValid()) { 4847 if (Mod) { 4848 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4849 << HdrFilename.str() << Mod->getFullModuleName(); 4850 if (!Mod->DefinitionLoc.isInvalid()) 4851 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4852 << Mod->getFullModuleName(); 4853 } else { 4854 Diag(IncLoc, diag::note_redefinition_include_same_file) 4855 << HdrFilename.str(); 4856 } 4857 return true; 4858 } 4859 4860 return false; 4861 }; 4862 4863 // Is it the same file and same offset? Provide more information on why 4864 // this leads to a redefinition error. 4865 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4866 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4867 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4868 bool EmittedDiag = 4869 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4870 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4871 4872 // If the header has no guards, emit a note suggesting one. 4873 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld)) 4874 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4875 4876 if (EmittedDiag) 4877 return; 4878 } 4879 4880 // Redefinition coming from different files or couldn't do better above. 4881 if (Old->getLocation().isValid()) 4882 Diag(Old->getLocation(), diag::note_previous_definition); 4883 } 4884 4885 /// We've just determined that \p Old and \p New both appear to be definitions 4886 /// of the same variable. Either diagnose or fix the problem. 4887 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4888 if (!hasVisibleDefinition(Old) && 4889 (New->getFormalLinkage() == Linkage::Internal || New->isInline() || 4890 isa<VarTemplateSpecializationDecl>(New) || 4891 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() || 4892 New->getDeclContext()->isDependentContext())) { 4893 // The previous definition is hidden, and multiple definitions are 4894 // permitted (in separate TUs). Demote this to a declaration. 4895 New->demoteThisDefinitionToDeclaration(); 4896 4897 // Make the canonical definition visible. 4898 if (auto *OldTD = Old->getDescribedVarTemplate()) 4899 makeMergedDefinitionVisible(OldTD); 4900 makeMergedDefinitionVisible(Old); 4901 return false; 4902 } else { 4903 Diag(New->getLocation(), diag::err_redefinition) << New; 4904 notePreviousDefinition(Old, New->getLocation()); 4905 New->setInvalidDecl(); 4906 return true; 4907 } 4908 } 4909 4910 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4911 /// no declarator (e.g. "struct foo;") is parsed. 4912 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 4913 DeclSpec &DS, 4914 const ParsedAttributesView &DeclAttrs, 4915 RecordDecl *&AnonRecord) { 4916 return ParsedFreeStandingDeclSpec( 4917 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord); 4918 } 4919 4920 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4921 // disambiguate entities defined in different scopes. 4922 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4923 // compatibility. 4924 // We will pick our mangling number depending on which version of MSVC is being 4925 // targeted. 4926 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4927 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4928 ? S->getMSCurManglingNumber() 4929 : S->getMSLastManglingNumber(); 4930 } 4931 4932 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4933 if (!Context.getLangOpts().CPlusPlus) 4934 return; 4935 4936 if (isa<CXXRecordDecl>(Tag->getParent())) { 4937 // If this tag is the direct child of a class, number it if 4938 // it is anonymous. 4939 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4940 return; 4941 MangleNumberingContext &MCtx = 4942 Context.getManglingNumberContext(Tag->getParent()); 4943 Context.setManglingNumber( 4944 Tag, MCtx.getManglingNumber( 4945 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4946 return; 4947 } 4948 4949 // If this tag isn't a direct child of a class, number it if it is local. 4950 MangleNumberingContext *MCtx; 4951 Decl *ManglingContextDecl; 4952 std::tie(MCtx, ManglingContextDecl) = 4953 getCurrentMangleNumberContext(Tag->getDeclContext()); 4954 if (MCtx) { 4955 Context.setManglingNumber( 4956 Tag, MCtx->getManglingNumber( 4957 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4958 } 4959 } 4960 4961 namespace { 4962 struct NonCLikeKind { 4963 enum { 4964 None, 4965 BaseClass, 4966 DefaultMemberInit, 4967 Lambda, 4968 Friend, 4969 OtherMember, 4970 Invalid, 4971 } Kind = None; 4972 SourceRange Range; 4973 4974 explicit operator bool() { return Kind != None; } 4975 }; 4976 } 4977 4978 /// Determine whether a class is C-like, according to the rules of C++ 4979 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4980 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4981 if (RD->isInvalidDecl()) 4982 return {NonCLikeKind::Invalid, {}}; 4983 4984 // C++ [dcl.typedef]p9: [P1766R1] 4985 // An unnamed class with a typedef name for linkage purposes shall not 4986 // 4987 // -- have any base classes 4988 if (RD->getNumBases()) 4989 return {NonCLikeKind::BaseClass, 4990 SourceRange(RD->bases_begin()->getBeginLoc(), 4991 RD->bases_end()[-1].getEndLoc())}; 4992 bool Invalid = false; 4993 for (Decl *D : RD->decls()) { 4994 // Don't complain about things we already diagnosed. 4995 if (D->isInvalidDecl()) { 4996 Invalid = true; 4997 continue; 4998 } 4999 5000 // -- have any [...] default member initializers 5001 if (auto *FD = dyn_cast<FieldDecl>(D)) { 5002 if (FD->hasInClassInitializer()) { 5003 auto *Init = FD->getInClassInitializer(); 5004 return {NonCLikeKind::DefaultMemberInit, 5005 Init ? Init->getSourceRange() : D->getSourceRange()}; 5006 } 5007 continue; 5008 } 5009 5010 // FIXME: We don't allow friend declarations. This violates the wording of 5011 // P1766, but not the intent. 5012 if (isa<FriendDecl>(D)) 5013 return {NonCLikeKind::Friend, D->getSourceRange()}; 5014 5015 // -- declare any members other than non-static data members, member 5016 // enumerations, or member classes, 5017 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 5018 isa<EnumDecl>(D)) 5019 continue; 5020 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 5021 if (!MemberRD) { 5022 if (D->isImplicit()) 5023 continue; 5024 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 5025 } 5026 5027 // -- contain a lambda-expression, 5028 if (MemberRD->isLambda()) 5029 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 5030 5031 // and all member classes shall also satisfy these requirements 5032 // (recursively). 5033 if (MemberRD->isThisDeclarationADefinition()) { 5034 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 5035 return Kind; 5036 } 5037 } 5038 5039 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 5040 } 5041 5042 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 5043 TypedefNameDecl *NewTD) { 5044 if (TagFromDeclSpec->isInvalidDecl()) 5045 return; 5046 5047 // Do nothing if the tag already has a name for linkage purposes. 5048 if (TagFromDeclSpec->hasNameForLinkage()) 5049 return; 5050 5051 // A well-formed anonymous tag must always be a TUK_Definition. 5052 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 5053 5054 // The type must match the tag exactly; no qualifiers allowed. 5055 if (!Context.hasSameType(NewTD->getUnderlyingType(), 5056 Context.getTagDeclType(TagFromDeclSpec))) { 5057 if (getLangOpts().CPlusPlus) 5058 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 5059 return; 5060 } 5061 5062 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 5063 // An unnamed class with a typedef name for linkage purposes shall [be 5064 // C-like]. 5065 // 5066 // FIXME: Also diagnose if we've already computed the linkage. That ideally 5067 // shouldn't happen, but there are constructs that the language rule doesn't 5068 // disallow for which we can't reasonably avoid computing linkage early. 5069 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 5070 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 5071 : NonCLikeKind(); 5072 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 5073 if (NonCLike || ChangesLinkage) { 5074 if (NonCLike.Kind == NonCLikeKind::Invalid) 5075 return; 5076 5077 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 5078 if (ChangesLinkage) { 5079 // If the linkage changes, we can't accept this as an extension. 5080 if (NonCLike.Kind == NonCLikeKind::None) 5081 DiagID = diag::err_typedef_changes_linkage; 5082 else 5083 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 5084 } 5085 5086 SourceLocation FixitLoc = 5087 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 5088 llvm::SmallString<40> TextToInsert; 5089 TextToInsert += ' '; 5090 TextToInsert += NewTD->getIdentifier()->getName(); 5091 5092 Diag(FixitLoc, DiagID) 5093 << isa<TypeAliasDecl>(NewTD) 5094 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 5095 if (NonCLike.Kind != NonCLikeKind::None) { 5096 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 5097 << NonCLike.Kind - 1 << NonCLike.Range; 5098 } 5099 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 5100 << NewTD << isa<TypeAliasDecl>(NewTD); 5101 5102 if (ChangesLinkage) 5103 return; 5104 } 5105 5106 // Otherwise, set this as the anon-decl typedef for the tag. 5107 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 5108 } 5109 5110 static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) { 5111 DeclSpec::TST T = DS.getTypeSpecType(); 5112 switch (T) { 5113 case DeclSpec::TST_class: 5114 return 0; 5115 case DeclSpec::TST_struct: 5116 return 1; 5117 case DeclSpec::TST_interface: 5118 return 2; 5119 case DeclSpec::TST_union: 5120 return 3; 5121 case DeclSpec::TST_enum: 5122 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) { 5123 if (ED->isScopedUsingClassTag()) 5124 return 5; 5125 if (ED->isScoped()) 5126 return 6; 5127 } 5128 return 4; 5129 default: 5130 llvm_unreachable("unexpected type specifier"); 5131 } 5132 } 5133 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 5134 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 5135 /// parameters to cope with template friend declarations. 5136 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 5137 DeclSpec &DS, 5138 const ParsedAttributesView &DeclAttrs, 5139 MultiTemplateParamsArg TemplateParams, 5140 bool IsExplicitInstantiation, 5141 RecordDecl *&AnonRecord) { 5142 Decl *TagD = nullptr; 5143 TagDecl *Tag = nullptr; 5144 if (DS.getTypeSpecType() == DeclSpec::TST_class || 5145 DS.getTypeSpecType() == DeclSpec::TST_struct || 5146 DS.getTypeSpecType() == DeclSpec::TST_interface || 5147 DS.getTypeSpecType() == DeclSpec::TST_union || 5148 DS.getTypeSpecType() == DeclSpec::TST_enum) { 5149 TagD = DS.getRepAsDecl(); 5150 5151 if (!TagD) // We probably had an error 5152 return nullptr; 5153 5154 // Note that the above type specs guarantee that the 5155 // type rep is a Decl, whereas in many of the others 5156 // it's a Type. 5157 if (isa<TagDecl>(TagD)) 5158 Tag = cast<TagDecl>(TagD); 5159 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 5160 Tag = CTD->getTemplatedDecl(); 5161 } 5162 5163 if (Tag) { 5164 handleTagNumbering(Tag, S); 5165 Tag->setFreeStanding(); 5166 if (Tag->isInvalidDecl()) 5167 return Tag; 5168 } 5169 5170 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 5171 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 5172 // or incomplete types shall not be restrict-qualified." 5173 if (TypeQuals & DeclSpec::TQ_restrict) 5174 Diag(DS.getRestrictSpecLoc(), 5175 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 5176 << DS.getSourceRange(); 5177 } 5178 5179 if (DS.isInlineSpecified()) 5180 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 5181 << getLangOpts().CPlusPlus17; 5182 5183 if (DS.hasConstexprSpecifier()) { 5184 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 5185 // and definitions of functions and variables. 5186 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 5187 // the declaration of a function or function template 5188 if (Tag) 5189 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 5190 << GetDiagnosticTypeSpecifierID(DS) 5191 << static_cast<int>(DS.getConstexprSpecifier()); 5192 else 5193 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 5194 << static_cast<int>(DS.getConstexprSpecifier()); 5195 // Don't emit warnings after this error. 5196 return TagD; 5197 } 5198 5199 DiagnoseFunctionSpecifiers(DS); 5200 5201 if (DS.isFriendSpecified()) { 5202 // If we're dealing with a decl but not a TagDecl, assume that 5203 // whatever routines created it handled the friendship aspect. 5204 if (TagD && !Tag) 5205 return nullptr; 5206 return ActOnFriendTypeDecl(S, DS, TemplateParams); 5207 } 5208 5209 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 5210 bool IsExplicitSpecialization = 5211 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 5212 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 5213 !IsExplicitInstantiation && !IsExplicitSpecialization && 5214 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 5215 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 5216 // nested-name-specifier unless it is an explicit instantiation 5217 // or an explicit specialization. 5218 // 5219 // FIXME: We allow class template partial specializations here too, per the 5220 // obvious intent of DR1819. 5221 // 5222 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 5223 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 5224 << GetDiagnosticTypeSpecifierID(DS) << SS.getRange(); 5225 return nullptr; 5226 } 5227 5228 // Track whether this decl-specifier declares anything. 5229 bool DeclaresAnything = true; 5230 5231 // Handle anonymous struct definitions. 5232 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 5233 if (!Record->getDeclName() && Record->isCompleteDefinition() && 5234 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 5235 if (getLangOpts().CPlusPlus || 5236 Record->getDeclContext()->isRecord()) { 5237 // If CurContext is a DeclContext that can contain statements, 5238 // RecursiveASTVisitor won't visit the decls that 5239 // BuildAnonymousStructOrUnion() will put into CurContext. 5240 // Also store them here so that they can be part of the 5241 // DeclStmt that gets created in this case. 5242 // FIXME: Also return the IndirectFieldDecls created by 5243 // BuildAnonymousStructOr union, for the same reason? 5244 if (CurContext->isFunctionOrMethod()) 5245 AnonRecord = Record; 5246 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 5247 Context.getPrintingPolicy()); 5248 } 5249 5250 DeclaresAnything = false; 5251 } 5252 } 5253 5254 // C11 6.7.2.1p2: 5255 // A struct-declaration that does not declare an anonymous structure or 5256 // anonymous union shall contain a struct-declarator-list. 5257 // 5258 // This rule also existed in C89 and C99; the grammar for struct-declaration 5259 // did not permit a struct-declaration without a struct-declarator-list. 5260 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 5261 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 5262 // Check for Microsoft C extension: anonymous struct/union member. 5263 // Handle 2 kinds of anonymous struct/union: 5264 // struct STRUCT; 5265 // union UNION; 5266 // and 5267 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 5268 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 5269 if ((Tag && Tag->getDeclName()) || 5270 DS.getTypeSpecType() == DeclSpec::TST_typename) { 5271 RecordDecl *Record = nullptr; 5272 if (Tag) 5273 Record = dyn_cast<RecordDecl>(Tag); 5274 else if (const RecordType *RT = 5275 DS.getRepAsType().get()->getAsStructureType()) 5276 Record = RT->getDecl(); 5277 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 5278 Record = UT->getDecl(); 5279 5280 if (Record && getLangOpts().MicrosoftExt) { 5281 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 5282 << Record->isUnion() << DS.getSourceRange(); 5283 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 5284 } 5285 5286 DeclaresAnything = false; 5287 } 5288 } 5289 5290 // Skip all the checks below if we have a type error. 5291 if (DS.getTypeSpecType() == DeclSpec::TST_error || 5292 (TagD && TagD->isInvalidDecl())) 5293 return TagD; 5294 5295 if (getLangOpts().CPlusPlus && 5296 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 5297 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 5298 if (Enum->enumerator_begin() == Enum->enumerator_end() && 5299 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 5300 DeclaresAnything = false; 5301 5302 if (!DS.isMissingDeclaratorOk()) { 5303 // Customize diagnostic for a typedef missing a name. 5304 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 5305 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 5306 << DS.getSourceRange(); 5307 else 5308 DeclaresAnything = false; 5309 } 5310 5311 if (DS.isModulePrivateSpecified() && 5312 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 5313 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 5314 << llvm::to_underlying(Tag->getTagKind()) 5315 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 5316 5317 ActOnDocumentableDecl(TagD); 5318 5319 // C 6.7/2: 5320 // A declaration [...] shall declare at least a declarator [...], a tag, 5321 // or the members of an enumeration. 5322 // C++ [dcl.dcl]p3: 5323 // [If there are no declarators], and except for the declaration of an 5324 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5325 // names into the program, or shall redeclare a name introduced by a 5326 // previous declaration. 5327 if (!DeclaresAnything) { 5328 // In C, we allow this as a (popular) extension / bug. Don't bother 5329 // producing further diagnostics for redundant qualifiers after this. 5330 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 5331 ? diag::err_no_declarators 5332 : diag::ext_no_declarators) 5333 << DS.getSourceRange(); 5334 return TagD; 5335 } 5336 5337 // C++ [dcl.stc]p1: 5338 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 5339 // init-declarator-list of the declaration shall not be empty. 5340 // C++ [dcl.fct.spec]p1: 5341 // If a cv-qualifier appears in a decl-specifier-seq, the 5342 // init-declarator-list of the declaration shall not be empty. 5343 // 5344 // Spurious qualifiers here appear to be valid in C. 5345 unsigned DiagID = diag::warn_standalone_specifier; 5346 if (getLangOpts().CPlusPlus) 5347 DiagID = diag::ext_standalone_specifier; 5348 5349 // Note that a linkage-specification sets a storage class, but 5350 // 'extern "C" struct foo;' is actually valid and not theoretically 5351 // useless. 5352 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 5353 if (SCS == DeclSpec::SCS_mutable) 5354 // Since mutable is not a viable storage class specifier in C, there is 5355 // no reason to treat it as an extension. Instead, diagnose as an error. 5356 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 5357 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 5358 Diag(DS.getStorageClassSpecLoc(), DiagID) 5359 << DeclSpec::getSpecifierName(SCS); 5360 } 5361 5362 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 5363 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 5364 << DeclSpec::getSpecifierName(TSCS); 5365 if (DS.getTypeQualifiers()) { 5366 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5367 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 5368 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5369 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 5370 // Restrict is covered above. 5371 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5372 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 5373 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5374 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 5375 } 5376 5377 // Warn about ignored type attributes, for example: 5378 // __attribute__((aligned)) struct A; 5379 // Attributes should be placed after tag to apply to type declaration. 5380 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) { 5381 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 5382 if (TypeSpecType == DeclSpec::TST_class || 5383 TypeSpecType == DeclSpec::TST_struct || 5384 TypeSpecType == DeclSpec::TST_interface || 5385 TypeSpecType == DeclSpec::TST_union || 5386 TypeSpecType == DeclSpec::TST_enum) { 5387 5388 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) { 5389 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored; 5390 if (AL.isAlignas() && !getLangOpts().CPlusPlus) 5391 DiagnosticId = diag::warn_attribute_ignored; 5392 else if (AL.isRegularKeywordAttribute()) 5393 DiagnosticId = diag::err_declspec_keyword_has_no_effect; 5394 else 5395 DiagnosticId = diag::warn_declspec_attribute_ignored; 5396 Diag(AL.getLoc(), DiagnosticId) 5397 << AL << GetDiagnosticTypeSpecifierID(DS); 5398 }; 5399 5400 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic); 5401 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic); 5402 } 5403 } 5404 5405 return TagD; 5406 } 5407 5408 /// We are trying to inject an anonymous member into the given scope; 5409 /// check if there's an existing declaration that can't be overloaded. 5410 /// 5411 /// \return true if this is a forbidden redeclaration 5412 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, 5413 DeclContext *Owner, 5414 DeclarationName Name, 5415 SourceLocation NameLoc, bool IsUnion, 5416 StorageClass SC) { 5417 LookupResult R(SemaRef, Name, NameLoc, 5418 Owner->isRecord() ? Sema::LookupMemberName 5419 : Sema::LookupOrdinaryName, 5420 Sema::ForVisibleRedeclaration); 5421 if (!SemaRef.LookupName(R, S)) return false; 5422 5423 // Pick a representative declaration. 5424 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 5425 assert(PrevDecl && "Expected a non-null Decl"); 5426 5427 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 5428 return false; 5429 5430 if (SC == StorageClass::SC_None && 5431 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) && 5432 (Owner->isFunctionOrMethod() || Owner->isRecord())) { 5433 if (!Owner->isRecord()) 5434 SemaRef.DiagPlaceholderVariableDefinition(NameLoc); 5435 return false; 5436 } 5437 5438 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 5439 << IsUnion << Name; 5440 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 5441 5442 return true; 5443 } 5444 5445 void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) { 5446 if (auto *RD = dyn_cast_if_present<RecordDecl>(D)) 5447 DiagPlaceholderFieldDeclDefinitions(RD); 5448 } 5449 5450 /// Emit diagnostic warnings for placeholder members. 5451 /// We can only do that after the class is fully constructed, 5452 /// as anonymous union/structs can insert placeholders 5453 /// in their parent scope (which might be a Record). 5454 void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) { 5455 if (!getLangOpts().CPlusPlus) 5456 return; 5457 5458 // This function can be parsed before we have validated the 5459 // structure as an anonymous struct 5460 if (Record->isAnonymousStructOrUnion()) 5461 return; 5462 5463 const NamedDecl *First = 0; 5464 for (const Decl *D : Record->decls()) { 5465 const NamedDecl *ND = dyn_cast<NamedDecl>(D); 5466 if (!ND || !ND->isPlaceholderVar(getLangOpts())) 5467 continue; 5468 if (!First) 5469 First = ND; 5470 else 5471 DiagPlaceholderVariableDefinition(ND->getLocation()); 5472 } 5473 } 5474 5475 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 5476 /// anonymous struct or union AnonRecord into the owning context Owner 5477 /// and scope S. This routine will be invoked just after we realize 5478 /// that an unnamed union or struct is actually an anonymous union or 5479 /// struct, e.g., 5480 /// 5481 /// @code 5482 /// union { 5483 /// int i; 5484 /// float f; 5485 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 5486 /// // f into the surrounding scope.x 5487 /// @endcode 5488 /// 5489 /// This routine is recursive, injecting the names of nested anonymous 5490 /// structs/unions into the owning context and scope as well. 5491 static bool 5492 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 5493 RecordDecl *AnonRecord, AccessSpecifier AS, 5494 StorageClass SC, 5495 SmallVectorImpl<NamedDecl *> &Chaining) { 5496 bool Invalid = false; 5497 5498 // Look every FieldDecl and IndirectFieldDecl with a name. 5499 for (auto *D : AnonRecord->decls()) { 5500 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 5501 cast<NamedDecl>(D)->getDeclName()) { 5502 ValueDecl *VD = cast<ValueDecl>(D); 5503 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 5504 VD->getLocation(), AnonRecord->isUnion(), 5505 SC)) { 5506 // C++ [class.union]p2: 5507 // The names of the members of an anonymous union shall be 5508 // distinct from the names of any other entity in the 5509 // scope in which the anonymous union is declared. 5510 Invalid = true; 5511 } else { 5512 // C++ [class.union]p2: 5513 // For the purpose of name lookup, after the anonymous union 5514 // definition, the members of the anonymous union are 5515 // considered to have been defined in the scope in which the 5516 // anonymous union is declared. 5517 unsigned OldChainingSize = Chaining.size(); 5518 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 5519 Chaining.append(IF->chain_begin(), IF->chain_end()); 5520 else 5521 Chaining.push_back(VD); 5522 5523 assert(Chaining.size() >= 2); 5524 NamedDecl **NamedChain = 5525 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 5526 for (unsigned i = 0; i < Chaining.size(); i++) 5527 NamedChain[i] = Chaining[i]; 5528 5529 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 5530 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 5531 VD->getType(), {NamedChain, Chaining.size()}); 5532 5533 for (const auto *Attr : VD->attrs()) 5534 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 5535 5536 IndirectField->setAccess(AS); 5537 IndirectField->setImplicit(); 5538 SemaRef.PushOnScopeChains(IndirectField, S); 5539 5540 // That includes picking up the appropriate access specifier. 5541 if (AS != AS_none) IndirectField->setAccess(AS); 5542 5543 Chaining.resize(OldChainingSize); 5544 } 5545 } 5546 } 5547 5548 return Invalid; 5549 } 5550 5551 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5552 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5553 /// illegal input values are mapped to SC_None. 5554 static StorageClass 5555 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5556 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5557 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5558 "Parser allowed 'typedef' as storage class VarDecl."); 5559 switch (StorageClassSpec) { 5560 case DeclSpec::SCS_unspecified: return SC_None; 5561 case DeclSpec::SCS_extern: 5562 if (DS.isExternInLinkageSpec()) 5563 return SC_None; 5564 return SC_Extern; 5565 case DeclSpec::SCS_static: return SC_Static; 5566 case DeclSpec::SCS_auto: return SC_Auto; 5567 case DeclSpec::SCS_register: return SC_Register; 5568 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5569 // Illegal SCSs map to None: error reporting is up to the caller. 5570 case DeclSpec::SCS_mutable: // Fall through. 5571 case DeclSpec::SCS_typedef: return SC_None; 5572 } 5573 llvm_unreachable("unknown storage class specifier"); 5574 } 5575 5576 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5577 assert(Record->hasInClassInitializer()); 5578 5579 for (const auto *I : Record->decls()) { 5580 const auto *FD = dyn_cast<FieldDecl>(I); 5581 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5582 FD = IFD->getAnonField(); 5583 if (FD && FD->hasInClassInitializer()) 5584 return FD->getLocation(); 5585 } 5586 5587 llvm_unreachable("couldn't find in-class initializer"); 5588 } 5589 5590 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5591 SourceLocation DefaultInitLoc) { 5592 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5593 return; 5594 5595 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5596 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5597 } 5598 5599 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5600 CXXRecordDecl *AnonUnion) { 5601 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5602 return; 5603 5604 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5605 } 5606 5607 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5608 /// anonymous structure or union. Anonymous unions are a C++ feature 5609 /// (C++ [class.union]) and a C11 feature; anonymous structures 5610 /// are a C11 feature and GNU C++ extension. 5611 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5612 AccessSpecifier AS, 5613 RecordDecl *Record, 5614 const PrintingPolicy &Policy) { 5615 DeclContext *Owner = Record->getDeclContext(); 5616 5617 // Diagnose whether this anonymous struct/union is an extension. 5618 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5619 Diag(Record->getLocation(), diag::ext_anonymous_union); 5620 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5621 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5622 else if (!Record->isUnion() && !getLangOpts().C11) 5623 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5624 5625 // C and C++ require different kinds of checks for anonymous 5626 // structs/unions. 5627 bool Invalid = false; 5628 if (getLangOpts().CPlusPlus) { 5629 const char *PrevSpec = nullptr; 5630 if (Record->isUnion()) { 5631 // C++ [class.union]p6: 5632 // C++17 [class.union.anon]p2: 5633 // Anonymous unions declared in a named namespace or in the 5634 // global namespace shall be declared static. 5635 unsigned DiagID; 5636 DeclContext *OwnerScope = Owner->getRedeclContext(); 5637 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5638 (OwnerScope->isTranslationUnit() || 5639 (OwnerScope->isNamespace() && 5640 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5641 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5642 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5643 5644 // Recover by adding 'static'. 5645 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5646 PrevSpec, DiagID, Policy); 5647 } 5648 // C++ [class.union]p6: 5649 // A storage class is not allowed in a declaration of an 5650 // anonymous union in a class scope. 5651 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5652 isa<RecordDecl>(Owner)) { 5653 Diag(DS.getStorageClassSpecLoc(), 5654 diag::err_anonymous_union_with_storage_spec) 5655 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5656 5657 // Recover by removing the storage specifier. 5658 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5659 SourceLocation(), 5660 PrevSpec, DiagID, Context.getPrintingPolicy()); 5661 } 5662 } 5663 5664 // Ignore const/volatile/restrict qualifiers. 5665 if (DS.getTypeQualifiers()) { 5666 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5667 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5668 << Record->isUnion() << "const" 5669 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5670 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5671 Diag(DS.getVolatileSpecLoc(), 5672 diag::ext_anonymous_struct_union_qualified) 5673 << Record->isUnion() << "volatile" 5674 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5675 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5676 Diag(DS.getRestrictSpecLoc(), 5677 diag::ext_anonymous_struct_union_qualified) 5678 << Record->isUnion() << "restrict" 5679 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5680 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5681 Diag(DS.getAtomicSpecLoc(), 5682 diag::ext_anonymous_struct_union_qualified) 5683 << Record->isUnion() << "_Atomic" 5684 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5685 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5686 Diag(DS.getUnalignedSpecLoc(), 5687 diag::ext_anonymous_struct_union_qualified) 5688 << Record->isUnion() << "__unaligned" 5689 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5690 5691 DS.ClearTypeQualifiers(); 5692 } 5693 5694 // C++ [class.union]p2: 5695 // The member-specification of an anonymous union shall only 5696 // define non-static data members. [Note: nested types and 5697 // functions cannot be declared within an anonymous union. ] 5698 for (auto *Mem : Record->decls()) { 5699 // Ignore invalid declarations; we already diagnosed them. 5700 if (Mem->isInvalidDecl()) 5701 continue; 5702 5703 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5704 // C++ [class.union]p3: 5705 // An anonymous union shall not have private or protected 5706 // members (clause 11). 5707 assert(FD->getAccess() != AS_none); 5708 if (FD->getAccess() != AS_public) { 5709 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5710 << Record->isUnion() << (FD->getAccess() == AS_protected); 5711 Invalid = true; 5712 } 5713 5714 // C++ [class.union]p1 5715 // An object of a class with a non-trivial constructor, a non-trivial 5716 // copy constructor, a non-trivial destructor, or a non-trivial copy 5717 // assignment operator cannot be a member of a union, nor can an 5718 // array of such objects. 5719 if (CheckNontrivialField(FD)) 5720 Invalid = true; 5721 } else if (Mem->isImplicit()) { 5722 // Any implicit members are fine. 5723 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5724 // This is a type that showed up in an 5725 // elaborated-type-specifier inside the anonymous struct or 5726 // union, but which actually declares a type outside of the 5727 // anonymous struct or union. It's okay. 5728 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5729 if (!MemRecord->isAnonymousStructOrUnion() && 5730 MemRecord->getDeclName()) { 5731 // Visual C++ allows type definition in anonymous struct or union. 5732 if (getLangOpts().MicrosoftExt) 5733 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5734 << Record->isUnion(); 5735 else { 5736 // This is a nested type declaration. 5737 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5738 << Record->isUnion(); 5739 Invalid = true; 5740 } 5741 } else { 5742 // This is an anonymous type definition within another anonymous type. 5743 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5744 // not part of standard C++. 5745 Diag(MemRecord->getLocation(), 5746 diag::ext_anonymous_record_with_anonymous_type) 5747 << Record->isUnion(); 5748 } 5749 } else if (isa<AccessSpecDecl>(Mem)) { 5750 // Any access specifier is fine. 5751 } else if (isa<StaticAssertDecl>(Mem)) { 5752 // In C++1z, static_assert declarations are also fine. 5753 } else { 5754 // We have something that isn't a non-static data 5755 // member. Complain about it. 5756 unsigned DK = diag::err_anonymous_record_bad_member; 5757 if (isa<TypeDecl>(Mem)) 5758 DK = diag::err_anonymous_record_with_type; 5759 else if (isa<FunctionDecl>(Mem)) 5760 DK = diag::err_anonymous_record_with_function; 5761 else if (isa<VarDecl>(Mem)) 5762 DK = diag::err_anonymous_record_with_static; 5763 5764 // Visual C++ allows type definition in anonymous struct or union. 5765 if (getLangOpts().MicrosoftExt && 5766 DK == diag::err_anonymous_record_with_type) 5767 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5768 << Record->isUnion(); 5769 else { 5770 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5771 Invalid = true; 5772 } 5773 } 5774 } 5775 5776 // C++11 [class.union]p8 (DR1460): 5777 // At most one variant member of a union may have a 5778 // brace-or-equal-initializer. 5779 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5780 Owner->isRecord()) 5781 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5782 cast<CXXRecordDecl>(Record)); 5783 } 5784 5785 if (!Record->isUnion() && !Owner->isRecord()) { 5786 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5787 << getLangOpts().CPlusPlus; 5788 Invalid = true; 5789 } 5790 5791 // C++ [dcl.dcl]p3: 5792 // [If there are no declarators], and except for the declaration of an 5793 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5794 // names into the program 5795 // C++ [class.mem]p2: 5796 // each such member-declaration shall either declare at least one member 5797 // name of the class or declare at least one unnamed bit-field 5798 // 5799 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5800 if (getLangOpts().CPlusPlus && Record->field_empty()) 5801 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5802 5803 // Mock up a declarator. 5804 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member); 5805 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5806 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc); 5807 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5808 5809 // Create a declaration for this anonymous struct/union. 5810 NamedDecl *Anon = nullptr; 5811 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5812 Anon = FieldDecl::Create( 5813 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5814 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5815 /*BitWidth=*/nullptr, /*Mutable=*/false, 5816 /*InitStyle=*/ICIS_NoInit); 5817 Anon->setAccess(AS); 5818 ProcessDeclAttributes(S, Anon, Dc); 5819 5820 if (getLangOpts().CPlusPlus) 5821 FieldCollector->Add(cast<FieldDecl>(Anon)); 5822 } else { 5823 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5824 if (SCSpec == DeclSpec::SCS_mutable) { 5825 // mutable can only appear on non-static class members, so it's always 5826 // an error here 5827 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5828 Invalid = true; 5829 SC = SC_None; 5830 } 5831 5832 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5833 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5834 Context.getTypeDeclType(Record), TInfo, SC); 5835 ProcessDeclAttributes(S, Anon, Dc); 5836 5837 // Default-initialize the implicit variable. This initialization will be 5838 // trivial in almost all cases, except if a union member has an in-class 5839 // initializer: 5840 // union { int n = 0; }; 5841 ActOnUninitializedDecl(Anon); 5842 } 5843 Anon->setImplicit(); 5844 5845 // Mark this as an anonymous struct/union type. 5846 Record->setAnonymousStructOrUnion(true); 5847 5848 // Add the anonymous struct/union object to the current 5849 // context. We'll be referencing this object when we refer to one of 5850 // its members. 5851 Owner->addDecl(Anon); 5852 5853 // Inject the members of the anonymous struct/union into the owning 5854 // context and into the identifier resolver chain for name lookup 5855 // purposes. 5856 SmallVector<NamedDecl*, 2> Chain; 5857 Chain.push_back(Anon); 5858 5859 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC, 5860 Chain)) 5861 Invalid = true; 5862 5863 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5864 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5865 MangleNumberingContext *MCtx; 5866 Decl *ManglingContextDecl; 5867 std::tie(MCtx, ManglingContextDecl) = 5868 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5869 if (MCtx) { 5870 Context.setManglingNumber( 5871 NewVD, MCtx->getManglingNumber( 5872 NewVD, getMSManglingNumber(getLangOpts(), S))); 5873 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5874 } 5875 } 5876 } 5877 5878 if (Invalid) 5879 Anon->setInvalidDecl(); 5880 5881 return Anon; 5882 } 5883 5884 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5885 /// Microsoft C anonymous structure. 5886 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5887 /// Example: 5888 /// 5889 /// struct A { int a; }; 5890 /// struct B { struct A; int b; }; 5891 /// 5892 /// void foo() { 5893 /// B var; 5894 /// var.a = 3; 5895 /// } 5896 /// 5897 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5898 RecordDecl *Record) { 5899 assert(Record && "expected a record!"); 5900 5901 // Mock up a declarator. 5902 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName); 5903 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc); 5904 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5905 5906 auto *ParentDecl = cast<RecordDecl>(CurContext); 5907 QualType RecTy = Context.getTypeDeclType(Record); 5908 5909 // Create a declaration for this anonymous struct. 5910 NamedDecl *Anon = 5911 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5912 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5913 /*BitWidth=*/nullptr, /*Mutable=*/false, 5914 /*InitStyle=*/ICIS_NoInit); 5915 Anon->setImplicit(); 5916 5917 // Add the anonymous struct object to the current context. 5918 CurContext->addDecl(Anon); 5919 5920 // Inject the members of the anonymous struct into the current 5921 // context and into the identifier resolver chain for name lookup 5922 // purposes. 5923 SmallVector<NamedDecl*, 2> Chain; 5924 Chain.push_back(Anon); 5925 5926 RecordDecl *RecordDef = Record->getDefinition(); 5927 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5928 diag::err_field_incomplete_or_sizeless) || 5929 InjectAnonymousStructOrUnionMembers( 5930 *this, S, CurContext, RecordDef, AS_none, 5931 StorageClassSpecToVarDeclStorageClass(DS), Chain)) { 5932 Anon->setInvalidDecl(); 5933 ParentDecl->setInvalidDecl(); 5934 } 5935 5936 return Anon; 5937 } 5938 5939 /// GetNameForDeclarator - Determine the full declaration name for the 5940 /// given Declarator. 5941 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5942 return GetNameFromUnqualifiedId(D.getName()); 5943 } 5944 5945 /// Retrieves the declaration name from a parsed unqualified-id. 5946 DeclarationNameInfo 5947 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5948 DeclarationNameInfo NameInfo; 5949 NameInfo.setLoc(Name.StartLocation); 5950 5951 switch (Name.getKind()) { 5952 5953 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5954 case UnqualifiedIdKind::IK_Identifier: 5955 NameInfo.setName(Name.Identifier); 5956 return NameInfo; 5957 5958 case UnqualifiedIdKind::IK_DeductionGuideName: { 5959 // C++ [temp.deduct.guide]p3: 5960 // The simple-template-id shall name a class template specialization. 5961 // The template-name shall be the same identifier as the template-name 5962 // of the simple-template-id. 5963 // These together intend to imply that the template-name shall name a 5964 // class template. 5965 // FIXME: template<typename T> struct X {}; 5966 // template<typename T> using Y = X<T>; 5967 // Y(int) -> Y<int>; 5968 // satisfies these rules but does not name a class template. 5969 TemplateName TN = Name.TemplateName.get().get(); 5970 auto *Template = TN.getAsTemplateDecl(); 5971 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5972 Diag(Name.StartLocation, 5973 diag::err_deduction_guide_name_not_class_template) 5974 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5975 if (Template) 5976 NoteTemplateLocation(*Template); 5977 return DeclarationNameInfo(); 5978 } 5979 5980 NameInfo.setName( 5981 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5982 return NameInfo; 5983 } 5984 5985 case UnqualifiedIdKind::IK_OperatorFunctionId: 5986 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5987 Name.OperatorFunctionId.Operator)); 5988 NameInfo.setCXXOperatorNameRange(SourceRange( 5989 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5990 return NameInfo; 5991 5992 case UnqualifiedIdKind::IK_LiteralOperatorId: 5993 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5994 Name.Identifier)); 5995 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5996 return NameInfo; 5997 5998 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5999 TypeSourceInfo *TInfo; 6000 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 6001 if (Ty.isNull()) 6002 return DeclarationNameInfo(); 6003 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 6004 Context.getCanonicalType(Ty))); 6005 NameInfo.setNamedTypeInfo(TInfo); 6006 return NameInfo; 6007 } 6008 6009 case UnqualifiedIdKind::IK_ConstructorName: { 6010 TypeSourceInfo *TInfo; 6011 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 6012 if (Ty.isNull()) 6013 return DeclarationNameInfo(); 6014 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 6015 Context.getCanonicalType(Ty))); 6016 NameInfo.setNamedTypeInfo(TInfo); 6017 return NameInfo; 6018 } 6019 6020 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 6021 // In well-formed code, we can only have a constructor 6022 // template-id that refers to the current context, so go there 6023 // to find the actual type being constructed. 6024 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 6025 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 6026 return DeclarationNameInfo(); 6027 6028 // Determine the type of the class being constructed. 6029 QualType CurClassType = Context.getTypeDeclType(CurClass); 6030 6031 // FIXME: Check two things: that the template-id names the same type as 6032 // CurClassType, and that the template-id does not occur when the name 6033 // was qualified. 6034 6035 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 6036 Context.getCanonicalType(CurClassType))); 6037 // FIXME: should we retrieve TypeSourceInfo? 6038 NameInfo.setNamedTypeInfo(nullptr); 6039 return NameInfo; 6040 } 6041 6042 case UnqualifiedIdKind::IK_DestructorName: { 6043 TypeSourceInfo *TInfo; 6044 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 6045 if (Ty.isNull()) 6046 return DeclarationNameInfo(); 6047 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 6048 Context.getCanonicalType(Ty))); 6049 NameInfo.setNamedTypeInfo(TInfo); 6050 return NameInfo; 6051 } 6052 6053 case UnqualifiedIdKind::IK_TemplateId: { 6054 TemplateName TName = Name.TemplateId->Template.get(); 6055 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 6056 return Context.getNameForTemplate(TName, TNameLoc); 6057 } 6058 6059 } // switch (Name.getKind()) 6060 6061 llvm_unreachable("Unknown name kind"); 6062 } 6063 6064 static QualType getCoreType(QualType Ty) { 6065 do { 6066 if (Ty->isPointerType() || Ty->isReferenceType()) 6067 Ty = Ty->getPointeeType(); 6068 else if (Ty->isArrayType()) 6069 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 6070 else 6071 return Ty.withoutLocalFastQualifiers(); 6072 } while (true); 6073 } 6074 6075 /// hasSimilarParameters - Determine whether the C++ functions Declaration 6076 /// and Definition have "nearly" matching parameters. This heuristic is 6077 /// used to improve diagnostics in the case where an out-of-line function 6078 /// definition doesn't match any declaration within the class or namespace. 6079 /// Also sets Params to the list of indices to the parameters that differ 6080 /// between the declaration and the definition. If hasSimilarParameters 6081 /// returns true and Params is empty, then all of the parameters match. 6082 static bool hasSimilarParameters(ASTContext &Context, 6083 FunctionDecl *Declaration, 6084 FunctionDecl *Definition, 6085 SmallVectorImpl<unsigned> &Params) { 6086 Params.clear(); 6087 if (Declaration->param_size() != Definition->param_size()) 6088 return false; 6089 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 6090 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 6091 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 6092 6093 // The parameter types are identical 6094 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 6095 continue; 6096 6097 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 6098 QualType DefParamBaseTy = getCoreType(DefParamTy); 6099 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 6100 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 6101 6102 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 6103 (DeclTyName && DeclTyName == DefTyName)) 6104 Params.push_back(Idx); 6105 else // The two parameters aren't even close 6106 return false; 6107 } 6108 6109 return true; 6110 } 6111 6112 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given 6113 /// declarator needs to be rebuilt in the current instantiation. 6114 /// Any bits of declarator which appear before the name are valid for 6115 /// consideration here. That's specifically the type in the decl spec 6116 /// and the base type in any member-pointer chunks. 6117 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 6118 DeclarationName Name) { 6119 // The types we specifically need to rebuild are: 6120 // - typenames, typeofs, and decltypes 6121 // - types which will become injected class names 6122 // Of course, we also need to rebuild any type referencing such a 6123 // type. It's safest to just say "dependent", but we call out a 6124 // few cases here. 6125 6126 DeclSpec &DS = D.getMutableDeclSpec(); 6127 switch (DS.getTypeSpecType()) { 6128 case DeclSpec::TST_typename: 6129 case DeclSpec::TST_typeofType: 6130 case DeclSpec::TST_typeof_unqualType: 6131 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait: 6132 #include "clang/Basic/TransformTypeTraits.def" 6133 case DeclSpec::TST_atomic: { 6134 // Grab the type from the parser. 6135 TypeSourceInfo *TSI = nullptr; 6136 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 6137 if (T.isNull() || !T->isInstantiationDependentType()) break; 6138 6139 // Make sure there's a type source info. This isn't really much 6140 // of a waste; most dependent types should have type source info 6141 // attached already. 6142 if (!TSI) 6143 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 6144 6145 // Rebuild the type in the current instantiation. 6146 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 6147 if (!TSI) return true; 6148 6149 // Store the new type back in the decl spec. 6150 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 6151 DS.UpdateTypeRep(LocType); 6152 break; 6153 } 6154 6155 case DeclSpec::TST_decltype: 6156 case DeclSpec::TST_typeof_unqualExpr: 6157 case DeclSpec::TST_typeofExpr: { 6158 Expr *E = DS.getRepAsExpr(); 6159 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 6160 if (Result.isInvalid()) return true; 6161 DS.UpdateExprRep(Result.get()); 6162 break; 6163 } 6164 6165 default: 6166 // Nothing to do for these decl specs. 6167 break; 6168 } 6169 6170 // It doesn't matter what order we do this in. 6171 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 6172 DeclaratorChunk &Chunk = D.getTypeObject(I); 6173 6174 // The only type information in the declarator which can come 6175 // before the declaration name is the base type of a member 6176 // pointer. 6177 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 6178 continue; 6179 6180 // Rebuild the scope specifier in-place. 6181 CXXScopeSpec &SS = Chunk.Mem.Scope(); 6182 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 6183 return true; 6184 } 6185 6186 return false; 6187 } 6188 6189 /// Returns true if the declaration is declared in a system header or from a 6190 /// system macro. 6191 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) { 6192 return SM.isInSystemHeader(D->getLocation()) || 6193 SM.isInSystemMacro(D->getLocation()); 6194 } 6195 6196 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 6197 // Avoid warning twice on the same identifier, and don't warn on redeclaration 6198 // of system decl. 6199 if (D->getPreviousDecl() || D->isImplicit()) 6200 return; 6201 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 6202 if (Status != ReservedIdentifierStatus::NotReserved && 6203 !isFromSystemHeader(Context.getSourceManager(), D)) { 6204 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 6205 << D << static_cast<int>(Status); 6206 } 6207 } 6208 6209 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 6210 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 6211 6212 // Check if we are in an `omp begin/end declare variant` scope. Handle this 6213 // declaration only if the `bind_to_declaration` extension is set. 6214 SmallVector<FunctionDecl *, 4> Bases; 6215 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 6216 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty:: 6217 implementation_extension_bind_to_declaration)) 6218 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 6219 S, D, MultiTemplateParamsArg(), Bases); 6220 6221 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 6222 6223 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 6224 Dcl && Dcl->getDeclContext()->isFileContext()) 6225 Dcl->setTopLevelDeclInObjCContainer(); 6226 6227 if (!Bases.empty()) 6228 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 6229 6230 return Dcl; 6231 } 6232 6233 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 6234 /// If T is the name of a class, then each of the following shall have a 6235 /// name different from T: 6236 /// - every static data member of class T; 6237 /// - every member function of class T 6238 /// - every member of class T that is itself a type; 6239 /// \returns true if the declaration name violates these rules. 6240 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 6241 DeclarationNameInfo NameInfo) { 6242 DeclarationName Name = NameInfo.getName(); 6243 6244 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 6245 while (Record && Record->isAnonymousStructOrUnion()) 6246 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 6247 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 6248 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 6249 return true; 6250 } 6251 6252 return false; 6253 } 6254 6255 /// Diagnose a declaration whose declarator-id has the given 6256 /// nested-name-specifier. 6257 /// 6258 /// \param SS The nested-name-specifier of the declarator-id. 6259 /// 6260 /// \param DC The declaration context to which the nested-name-specifier 6261 /// resolves. 6262 /// 6263 /// \param Name The name of the entity being declared. 6264 /// 6265 /// \param Loc The location of the name of the entity being declared. 6266 /// 6267 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 6268 /// we're declaring an explicit / partial specialization / instantiation. 6269 /// 6270 /// \returns true if we cannot safely recover from this error, false otherwise. 6271 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 6272 DeclarationName Name, 6273 SourceLocation Loc, bool IsTemplateId) { 6274 DeclContext *Cur = CurContext; 6275 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 6276 Cur = Cur->getParent(); 6277 6278 // If the user provided a superfluous scope specifier that refers back to the 6279 // class in which the entity is already declared, diagnose and ignore it. 6280 // 6281 // class X { 6282 // void X::f(); 6283 // }; 6284 // 6285 // Note, it was once ill-formed to give redundant qualification in all 6286 // contexts, but that rule was removed by DR482. 6287 if (Cur->Equals(DC)) { 6288 if (Cur->isRecord()) { 6289 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 6290 : diag::err_member_extra_qualification) 6291 << Name << FixItHint::CreateRemoval(SS.getRange()); 6292 SS.clear(); 6293 } else { 6294 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 6295 } 6296 return false; 6297 } 6298 6299 // Check whether the qualifying scope encloses the scope of the original 6300 // declaration. For a template-id, we perform the checks in 6301 // CheckTemplateSpecializationScope. 6302 if (!Cur->Encloses(DC) && !IsTemplateId) { 6303 if (Cur->isRecord()) 6304 Diag(Loc, diag::err_member_qualification) 6305 << Name << SS.getRange(); 6306 else if (isa<TranslationUnitDecl>(DC)) 6307 Diag(Loc, diag::err_invalid_declarator_global_scope) 6308 << Name << SS.getRange(); 6309 else if (isa<FunctionDecl>(Cur)) 6310 Diag(Loc, diag::err_invalid_declarator_in_function) 6311 << Name << SS.getRange(); 6312 else if (isa<BlockDecl>(Cur)) 6313 Diag(Loc, diag::err_invalid_declarator_in_block) 6314 << Name << SS.getRange(); 6315 else if (isa<ExportDecl>(Cur)) { 6316 if (!isa<NamespaceDecl>(DC)) 6317 Diag(Loc, diag::err_export_non_namespace_scope_name) 6318 << Name << SS.getRange(); 6319 else 6320 // The cases that DC is not NamespaceDecl should be handled in 6321 // CheckRedeclarationExported. 6322 return false; 6323 } else 6324 Diag(Loc, diag::err_invalid_declarator_scope) 6325 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 6326 6327 return true; 6328 } 6329 6330 if (Cur->isRecord()) { 6331 // Cannot qualify members within a class. 6332 Diag(Loc, diag::err_member_qualification) 6333 << Name << SS.getRange(); 6334 SS.clear(); 6335 6336 // C++ constructors and destructors with incorrect scopes can break 6337 // our AST invariants by having the wrong underlying types. If 6338 // that's the case, then drop this declaration entirely. 6339 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 6340 Name.getNameKind() == DeclarationName::CXXDestructorName) && 6341 !Context.hasSameType(Name.getCXXNameType(), 6342 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 6343 return true; 6344 6345 return false; 6346 } 6347 6348 // C++11 [dcl.meaning]p1: 6349 // [...] "The nested-name-specifier of the qualified declarator-id shall 6350 // not begin with a decltype-specifer" 6351 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 6352 while (SpecLoc.getPrefix()) 6353 SpecLoc = SpecLoc.getPrefix(); 6354 if (isa_and_nonnull<DecltypeType>( 6355 SpecLoc.getNestedNameSpecifier()->getAsType())) 6356 Diag(Loc, diag::err_decltype_in_declarator) 6357 << SpecLoc.getTypeLoc().getSourceRange(); 6358 6359 return false; 6360 } 6361 6362 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 6363 MultiTemplateParamsArg TemplateParamLists) { 6364 // TODO: consider using NameInfo for diagnostic. 6365 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6366 DeclarationName Name = NameInfo.getName(); 6367 6368 // All of these full declarators require an identifier. If it doesn't have 6369 // one, the ParsedFreeStandingDeclSpec action should be used. 6370 if (D.isDecompositionDeclarator()) { 6371 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 6372 } else if (!Name) { 6373 if (!D.isInvalidType()) // Reject this if we think it is valid. 6374 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 6375 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 6376 return nullptr; 6377 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 6378 return nullptr; 6379 6380 // The scope passed in may not be a decl scope. Zip up the scope tree until 6381 // we find one that is. 6382 while ((S->getFlags() & Scope::DeclScope) == 0 || 6383 (S->getFlags() & Scope::TemplateParamScope) != 0) 6384 S = S->getParent(); 6385 6386 DeclContext *DC = CurContext; 6387 if (D.getCXXScopeSpec().isInvalid()) 6388 D.setInvalidType(); 6389 else if (D.getCXXScopeSpec().isSet()) { 6390 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 6391 UPPC_DeclarationQualifier)) 6392 return nullptr; 6393 6394 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 6395 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 6396 if (!DC || isa<EnumDecl>(DC)) { 6397 // If we could not compute the declaration context, it's because the 6398 // declaration context is dependent but does not refer to a class, 6399 // class template, or class template partial specialization. Complain 6400 // and return early, to avoid the coming semantic disaster. 6401 Diag(D.getIdentifierLoc(), 6402 diag::err_template_qualified_declarator_no_match) 6403 << D.getCXXScopeSpec().getScopeRep() 6404 << D.getCXXScopeSpec().getRange(); 6405 return nullptr; 6406 } 6407 bool IsDependentContext = DC->isDependentContext(); 6408 6409 if (!IsDependentContext && 6410 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 6411 return nullptr; 6412 6413 // If a class is incomplete, do not parse entities inside it. 6414 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 6415 Diag(D.getIdentifierLoc(), 6416 diag::err_member_def_undefined_record) 6417 << Name << DC << D.getCXXScopeSpec().getRange(); 6418 return nullptr; 6419 } 6420 if (!D.getDeclSpec().isFriendSpecified()) { 6421 if (diagnoseQualifiedDeclaration( 6422 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 6423 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 6424 if (DC->isRecord()) 6425 return nullptr; 6426 6427 D.setInvalidType(); 6428 } 6429 } 6430 6431 // Check whether we need to rebuild the type of the given 6432 // declaration in the current instantiation. 6433 if (EnteringContext && IsDependentContext && 6434 TemplateParamLists.size() != 0) { 6435 ContextRAII SavedContext(*this, DC); 6436 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 6437 D.setInvalidType(); 6438 } 6439 } 6440 6441 TypeSourceInfo *TInfo = GetTypeForDeclarator(D); 6442 QualType R = TInfo->getType(); 6443 6444 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 6445 UPPC_DeclarationType)) 6446 D.setInvalidType(); 6447 6448 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 6449 forRedeclarationInCurContext()); 6450 6451 // See if this is a redefinition of a variable in the same scope. 6452 if (!D.getCXXScopeSpec().isSet()) { 6453 bool IsLinkageLookup = false; 6454 bool CreateBuiltins = false; 6455 6456 // If the declaration we're planning to build will be a function 6457 // or object with linkage, then look for another declaration with 6458 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 6459 // 6460 // If the declaration we're planning to build will be declared with 6461 // external linkage in the translation unit, create any builtin with 6462 // the same name. 6463 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 6464 /* Do nothing*/; 6465 else if (CurContext->isFunctionOrMethod() && 6466 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 6467 R->isFunctionType())) { 6468 IsLinkageLookup = true; 6469 CreateBuiltins = 6470 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 6471 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 6472 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 6473 CreateBuiltins = true; 6474 6475 if (IsLinkageLookup) { 6476 Previous.clear(LookupRedeclarationWithLinkage); 6477 Previous.setRedeclarationKind(ForExternalRedeclaration); 6478 } 6479 6480 LookupName(Previous, S, CreateBuiltins); 6481 } else { // Something like "int foo::x;" 6482 LookupQualifiedName(Previous, DC); 6483 6484 // C++ [dcl.meaning]p1: 6485 // When the declarator-id is qualified, the declaration shall refer to a 6486 // previously declared member of the class or namespace to which the 6487 // qualifier refers (or, in the case of a namespace, of an element of the 6488 // inline namespace set of that namespace (7.3.1)) or to a specialization 6489 // thereof; [...] 6490 // 6491 // Note that we already checked the context above, and that we do not have 6492 // enough information to make sure that Previous contains the declaration 6493 // we want to match. For example, given: 6494 // 6495 // class X { 6496 // void f(); 6497 // void f(float); 6498 // }; 6499 // 6500 // void X::f(int) { } // ill-formed 6501 // 6502 // In this case, Previous will point to the overload set 6503 // containing the two f's declared in X, but neither of them 6504 // matches. 6505 6506 RemoveUsingDecls(Previous); 6507 } 6508 6509 if (Previous.isSingleResult() && 6510 Previous.getFoundDecl()->isTemplateParameter()) { 6511 // Maybe we will complain about the shadowed template parameter. 6512 if (!D.isInvalidType()) 6513 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 6514 Previous.getFoundDecl()); 6515 6516 // Just pretend that we didn't see the previous declaration. 6517 Previous.clear(); 6518 } 6519 6520 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 6521 // Forget that the previous declaration is the injected-class-name. 6522 Previous.clear(); 6523 6524 // In C++, the previous declaration we find might be a tag type 6525 // (class or enum). In this case, the new declaration will hide the 6526 // tag type. Note that this applies to functions, function templates, and 6527 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 6528 if (Previous.isSingleTagDecl() && 6529 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6530 (TemplateParamLists.size() == 0 || R->isFunctionType())) 6531 Previous.clear(); 6532 6533 // Check that there are no default arguments other than in the parameters 6534 // of a function declaration (C++ only). 6535 if (getLangOpts().CPlusPlus) 6536 CheckExtraCXXDefaultArguments(D); 6537 6538 NamedDecl *New; 6539 6540 bool AddToScope = true; 6541 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 6542 if (TemplateParamLists.size()) { 6543 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 6544 return nullptr; 6545 } 6546 6547 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 6548 } else if (R->isFunctionType()) { 6549 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 6550 TemplateParamLists, 6551 AddToScope); 6552 } else { 6553 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 6554 AddToScope); 6555 } 6556 6557 if (!New) 6558 return nullptr; 6559 6560 // If this has an identifier and is not a function template specialization, 6561 // add it to the scope stack. 6562 if (New->getDeclName() && AddToScope) 6563 PushOnScopeChains(New, S); 6564 6565 if (isInOpenMPDeclareTargetContext()) 6566 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 6567 6568 return New; 6569 } 6570 6571 /// Helper method to turn variable array types into constant array 6572 /// types in certain situations which would otherwise be errors (for 6573 /// GCC compatibility). 6574 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6575 ASTContext &Context, 6576 bool &SizeIsNegative, 6577 llvm::APSInt &Oversized) { 6578 // This method tries to turn a variable array into a constant 6579 // array even when the size isn't an ICE. This is necessary 6580 // for compatibility with code that depends on gcc's buggy 6581 // constant expression folding, like struct {char x[(int)(char*)2];} 6582 SizeIsNegative = false; 6583 Oversized = 0; 6584 6585 if (T->isDependentType()) 6586 return QualType(); 6587 6588 QualifierCollector Qs; 6589 const Type *Ty = Qs.strip(T); 6590 6591 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6592 QualType Pointee = PTy->getPointeeType(); 6593 QualType FixedType = 6594 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6595 Oversized); 6596 if (FixedType.isNull()) return FixedType; 6597 FixedType = Context.getPointerType(FixedType); 6598 return Qs.apply(Context, FixedType); 6599 } 6600 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6601 QualType Inner = PTy->getInnerType(); 6602 QualType FixedType = 6603 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6604 Oversized); 6605 if (FixedType.isNull()) return FixedType; 6606 FixedType = Context.getParenType(FixedType); 6607 return Qs.apply(Context, FixedType); 6608 } 6609 6610 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6611 if (!VLATy) 6612 return QualType(); 6613 6614 QualType ElemTy = VLATy->getElementType(); 6615 if (ElemTy->isVariablyModifiedType()) { 6616 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6617 SizeIsNegative, Oversized); 6618 if (ElemTy.isNull()) 6619 return QualType(); 6620 } 6621 6622 Expr::EvalResult Result; 6623 if (!VLATy->getSizeExpr() || 6624 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6625 return QualType(); 6626 6627 llvm::APSInt Res = Result.Val.getInt(); 6628 6629 // Check whether the array size is negative. 6630 if (Res.isSigned() && Res.isNegative()) { 6631 SizeIsNegative = true; 6632 return QualType(); 6633 } 6634 6635 // Check whether the array is too large to be addressed. 6636 unsigned ActiveSizeBits = 6637 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6638 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6639 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6640 : Res.getActiveBits(); 6641 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6642 Oversized = Res; 6643 return QualType(); 6644 } 6645 6646 QualType FoldedArrayType = Context.getConstantArrayType( 6647 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0); 6648 return Qs.apply(Context, FoldedArrayType); 6649 } 6650 6651 static void 6652 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6653 SrcTL = SrcTL.getUnqualifiedLoc(); 6654 DstTL = DstTL.getUnqualifiedLoc(); 6655 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6656 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6657 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6658 DstPTL.getPointeeLoc()); 6659 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6660 return; 6661 } 6662 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6663 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6664 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6665 DstPTL.getInnerLoc()); 6666 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6667 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6668 return; 6669 } 6670 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6671 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6672 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6673 TypeLoc DstElemTL = DstATL.getElementLoc(); 6674 if (VariableArrayTypeLoc SrcElemATL = 6675 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6676 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6677 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6678 } else { 6679 DstElemTL.initializeFullCopy(SrcElemTL); 6680 } 6681 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6682 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6683 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6684 } 6685 6686 /// Helper method to turn variable array types into constant array 6687 /// types in certain situations which would otherwise be errors (for 6688 /// GCC compatibility). 6689 static TypeSourceInfo* 6690 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6691 ASTContext &Context, 6692 bool &SizeIsNegative, 6693 llvm::APSInt &Oversized) { 6694 QualType FixedTy 6695 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6696 SizeIsNegative, Oversized); 6697 if (FixedTy.isNull()) 6698 return nullptr; 6699 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6700 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6701 FixedTInfo->getTypeLoc()); 6702 return FixedTInfo; 6703 } 6704 6705 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6706 /// true if we were successful. 6707 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6708 QualType &T, SourceLocation Loc, 6709 unsigned FailedFoldDiagID) { 6710 bool SizeIsNegative; 6711 llvm::APSInt Oversized; 6712 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6713 TInfo, Context, SizeIsNegative, Oversized); 6714 if (FixedTInfo) { 6715 Diag(Loc, diag::ext_vla_folded_to_constant); 6716 TInfo = FixedTInfo; 6717 T = FixedTInfo->getType(); 6718 return true; 6719 } 6720 6721 if (SizeIsNegative) 6722 Diag(Loc, diag::err_typecheck_negative_array_size); 6723 else if (Oversized.getBoolValue()) 6724 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6725 else if (FailedFoldDiagID) 6726 Diag(Loc, FailedFoldDiagID); 6727 return false; 6728 } 6729 6730 /// Register the given locally-scoped extern "C" declaration so 6731 /// that it can be found later for redeclarations. We include any extern "C" 6732 /// declaration that is not visible in the translation unit here, not just 6733 /// function-scope declarations. 6734 void 6735 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6736 if (!getLangOpts().CPlusPlus && 6737 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6738 // Don't need to track declarations in the TU in C. 6739 return; 6740 6741 // Note that we have a locally-scoped external with this name. 6742 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6743 } 6744 6745 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6746 // FIXME: We can have multiple results via __attribute__((overloadable)). 6747 auto Result = Context.getExternCContextDecl()->lookup(Name); 6748 return Result.empty() ? nullptr : *Result.begin(); 6749 } 6750 6751 /// Diagnose function specifiers on a declaration of an identifier that 6752 /// does not identify a function. 6753 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6754 // FIXME: We should probably indicate the identifier in question to avoid 6755 // confusion for constructs like "virtual int a(), b;" 6756 if (DS.isVirtualSpecified()) 6757 Diag(DS.getVirtualSpecLoc(), 6758 diag::err_virtual_non_function); 6759 6760 if (DS.hasExplicitSpecifier()) 6761 Diag(DS.getExplicitSpecLoc(), 6762 diag::err_explicit_non_function); 6763 6764 if (DS.isNoreturnSpecified()) 6765 Diag(DS.getNoreturnSpecLoc(), 6766 diag::err_noreturn_non_function); 6767 } 6768 6769 NamedDecl* 6770 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6771 TypeSourceInfo *TInfo, LookupResult &Previous) { 6772 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6773 if (D.getCXXScopeSpec().isSet()) { 6774 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6775 << D.getCXXScopeSpec().getRange(); 6776 D.setInvalidType(); 6777 // Pretend we didn't see the scope specifier. 6778 DC = CurContext; 6779 Previous.clear(); 6780 } 6781 6782 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6783 6784 if (D.getDeclSpec().isInlineSpecified()) 6785 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6786 << getLangOpts().CPlusPlus17; 6787 if (D.getDeclSpec().hasConstexprSpecifier()) 6788 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6789 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6790 6791 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) { 6792 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) 6793 Diag(D.getName().StartLocation, 6794 diag::err_deduction_guide_invalid_specifier) 6795 << "typedef"; 6796 else 6797 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6798 << D.getName().getSourceRange(); 6799 return nullptr; 6800 } 6801 6802 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6803 if (!NewTD) return nullptr; 6804 6805 // Handle attributes prior to checking for duplicates in MergeVarDecl 6806 ProcessDeclAttributes(S, NewTD, D); 6807 6808 CheckTypedefForVariablyModifiedType(S, NewTD); 6809 6810 bool Redeclaration = D.isRedeclaration(); 6811 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6812 D.setRedeclaration(Redeclaration); 6813 return ND; 6814 } 6815 6816 void 6817 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6818 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6819 // then it shall have block scope. 6820 // Note that variably modified types must be fixed before merging the decl so 6821 // that redeclarations will match. 6822 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6823 QualType T = TInfo->getType(); 6824 if (T->isVariablyModifiedType()) { 6825 setFunctionHasBranchProtectedScope(); 6826 6827 if (S->getFnParent() == nullptr) { 6828 bool SizeIsNegative; 6829 llvm::APSInt Oversized; 6830 TypeSourceInfo *FixedTInfo = 6831 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6832 SizeIsNegative, 6833 Oversized); 6834 if (FixedTInfo) { 6835 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6836 NewTD->setTypeSourceInfo(FixedTInfo); 6837 } else { 6838 if (SizeIsNegative) 6839 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6840 else if (T->isVariableArrayType()) 6841 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6842 else if (Oversized.getBoolValue()) 6843 Diag(NewTD->getLocation(), diag::err_array_too_large) 6844 << toString(Oversized, 10); 6845 else 6846 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6847 NewTD->setInvalidDecl(); 6848 } 6849 } 6850 } 6851 } 6852 6853 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6854 /// declares a typedef-name, either using the 'typedef' type specifier or via 6855 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6856 NamedDecl* 6857 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6858 LookupResult &Previous, bool &Redeclaration) { 6859 6860 // Find the shadowed declaration before filtering for scope. 6861 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6862 6863 // Merge the decl with the existing one if appropriate. If the decl is 6864 // in an outer scope, it isn't the same thing. 6865 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6866 /*AllowInlineNamespace*/false); 6867 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6868 if (!Previous.empty()) { 6869 Redeclaration = true; 6870 MergeTypedefNameDecl(S, NewTD, Previous); 6871 } else { 6872 inferGslPointerAttribute(NewTD); 6873 } 6874 6875 if (ShadowedDecl && !Redeclaration) 6876 CheckShadow(NewTD, ShadowedDecl, Previous); 6877 6878 // If this is the C FILE type, notify the AST context. 6879 if (IdentifierInfo *II = NewTD->getIdentifier()) 6880 if (!NewTD->isInvalidDecl() && 6881 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6882 switch (II->getInterestingIdentifierID()) { 6883 case tok::InterestingIdentifierKind::FILE: 6884 Context.setFILEDecl(NewTD); 6885 break; 6886 case tok::InterestingIdentifierKind::jmp_buf: 6887 Context.setjmp_bufDecl(NewTD); 6888 break; 6889 case tok::InterestingIdentifierKind::sigjmp_buf: 6890 Context.setsigjmp_bufDecl(NewTD); 6891 break; 6892 case tok::InterestingIdentifierKind::ucontext_t: 6893 Context.setucontext_tDecl(NewTD); 6894 break; 6895 case tok::InterestingIdentifierKind::float_t: 6896 case tok::InterestingIdentifierKind::double_t: 6897 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context)); 6898 break; 6899 default: 6900 break; 6901 } 6902 } 6903 6904 return NewTD; 6905 } 6906 6907 /// Determines whether the given declaration is an out-of-scope 6908 /// previous declaration. 6909 /// 6910 /// This routine should be invoked when name lookup has found a 6911 /// previous declaration (PrevDecl) that is not in the scope where a 6912 /// new declaration by the same name is being introduced. If the new 6913 /// declaration occurs in a local scope, previous declarations with 6914 /// linkage may still be considered previous declarations (C99 6915 /// 6.2.2p4-5, C++ [basic.link]p6). 6916 /// 6917 /// \param PrevDecl the previous declaration found by name 6918 /// lookup 6919 /// 6920 /// \param DC the context in which the new declaration is being 6921 /// declared. 6922 /// 6923 /// \returns true if PrevDecl is an out-of-scope previous declaration 6924 /// for a new delcaration with the same name. 6925 static bool 6926 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6927 ASTContext &Context) { 6928 if (!PrevDecl) 6929 return false; 6930 6931 if (!PrevDecl->hasLinkage()) 6932 return false; 6933 6934 if (Context.getLangOpts().CPlusPlus) { 6935 // C++ [basic.link]p6: 6936 // If there is a visible declaration of an entity with linkage 6937 // having the same name and type, ignoring entities declared 6938 // outside the innermost enclosing namespace scope, the block 6939 // scope declaration declares that same entity and receives the 6940 // linkage of the previous declaration. 6941 DeclContext *OuterContext = DC->getRedeclContext(); 6942 if (!OuterContext->isFunctionOrMethod()) 6943 // This rule only applies to block-scope declarations. 6944 return false; 6945 6946 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6947 if (PrevOuterContext->isRecord()) 6948 // We found a member function: ignore it. 6949 return false; 6950 6951 // Find the innermost enclosing namespace for the new and 6952 // previous declarations. 6953 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6954 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6955 6956 // The previous declaration is in a different namespace, so it 6957 // isn't the same function. 6958 if (!OuterContext->Equals(PrevOuterContext)) 6959 return false; 6960 } 6961 6962 return true; 6963 } 6964 6965 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6966 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6967 if (!SS.isSet()) return; 6968 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6969 } 6970 6971 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6972 QualType type = decl->getType(); 6973 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6974 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6975 // Various kinds of declaration aren't allowed to be __autoreleasing. 6976 unsigned kind = -1U; 6977 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6978 if (var->hasAttr<BlocksAttr>()) 6979 kind = 0; // __block 6980 else if (!var->hasLocalStorage()) 6981 kind = 1; // global 6982 } else if (isa<ObjCIvarDecl>(decl)) { 6983 kind = 3; // ivar 6984 } else if (isa<FieldDecl>(decl)) { 6985 kind = 2; // field 6986 } 6987 6988 if (kind != -1U) { 6989 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6990 << kind; 6991 } 6992 } else if (lifetime == Qualifiers::OCL_None) { 6993 // Try to infer lifetime. 6994 if (!type->isObjCLifetimeType()) 6995 return false; 6996 6997 lifetime = type->getObjCARCImplicitLifetime(); 6998 type = Context.getLifetimeQualifiedType(type, lifetime); 6999 decl->setType(type); 7000 } 7001 7002 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 7003 // Thread-local variables cannot have lifetime. 7004 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 7005 var->getTLSKind()) { 7006 Diag(var->getLocation(), diag::err_arc_thread_ownership) 7007 << var->getType(); 7008 return true; 7009 } 7010 } 7011 7012 return false; 7013 } 7014 7015 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 7016 if (Decl->getType().hasAddressSpace()) 7017 return; 7018 if (Decl->getType()->isDependentType()) 7019 return; 7020 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 7021 QualType Type = Var->getType(); 7022 if (Type->isSamplerT() || Type->isVoidType()) 7023 return; 7024 LangAS ImplAS = LangAS::opencl_private; 7025 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 7026 // __opencl_c_program_scope_global_variables feature, the address space 7027 // for a variable at program scope or a static or extern variable inside 7028 // a function are inferred to be __global. 7029 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 7030 Var->hasGlobalStorage()) 7031 ImplAS = LangAS::opencl_global; 7032 // If the original type from a decayed type is an array type and that array 7033 // type has no address space yet, deduce it now. 7034 if (auto DT = dyn_cast<DecayedType>(Type)) { 7035 auto OrigTy = DT->getOriginalType(); 7036 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 7037 // Add the address space to the original array type and then propagate 7038 // that to the element type through `getAsArrayType`. 7039 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 7040 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 7041 // Re-generate the decayed type. 7042 Type = Context.getDecayedType(OrigTy); 7043 } 7044 } 7045 Type = Context.getAddrSpaceQualType(Type, ImplAS); 7046 // Apply any qualifiers (including address space) from the array type to 7047 // the element type. This implements C99 6.7.3p8: "If the specification of 7048 // an array type includes any type qualifiers, the element type is so 7049 // qualified, not the array type." 7050 if (Type->isArrayType()) 7051 Type = QualType(Context.getAsArrayType(Type), 0); 7052 Decl->setType(Type); 7053 } 7054 } 7055 7056 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 7057 // Ensure that an auto decl is deduced otherwise the checks below might cache 7058 // the wrong linkage. 7059 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 7060 7061 // 'weak' only applies to declarations with external linkage. 7062 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 7063 if (!ND.isExternallyVisible()) { 7064 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 7065 ND.dropAttr<WeakAttr>(); 7066 } 7067 } 7068 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 7069 if (ND.isExternallyVisible()) { 7070 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 7071 ND.dropAttrs<WeakRefAttr, AliasAttr>(); 7072 } 7073 } 7074 7075 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 7076 if (VD->hasInit()) { 7077 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 7078 assert(VD->isThisDeclarationADefinition() && 7079 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 7080 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 7081 VD->dropAttr<AliasAttr>(); 7082 } 7083 } 7084 } 7085 7086 // 'selectany' only applies to externally visible variable declarations. 7087 // It does not apply to functions. 7088 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 7089 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 7090 S.Diag(Attr->getLocation(), 7091 diag::err_attribute_selectany_non_extern_data); 7092 ND.dropAttr<SelectAnyAttr>(); 7093 } 7094 } 7095 7096 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 7097 auto *VD = dyn_cast<VarDecl>(&ND); 7098 bool IsAnonymousNS = false; 7099 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 7100 if (VD) { 7101 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 7102 while (NS && !IsAnonymousNS) { 7103 IsAnonymousNS = NS->isAnonymousNamespace(); 7104 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 7105 } 7106 } 7107 // dll attributes require external linkage. Static locals may have external 7108 // linkage but still cannot be explicitly imported or exported. 7109 // In Microsoft mode, a variable defined in anonymous namespace must have 7110 // external linkage in order to be exported. 7111 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 7112 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 7113 (!AnonNSInMicrosoftMode && 7114 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 7115 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 7116 << &ND << Attr; 7117 ND.setInvalidDecl(); 7118 } 7119 } 7120 7121 // Check the attributes on the function type, if any. 7122 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 7123 // Don't declare this variable in the second operand of the for-statement; 7124 // GCC miscompiles that by ending its lifetime before evaluating the 7125 // third operand. See gcc.gnu.org/PR86769. 7126 AttributedTypeLoc ATL; 7127 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 7128 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 7129 TL = ATL.getModifiedLoc()) { 7130 // The [[lifetimebound]] attribute can be applied to the implicit object 7131 // parameter of a non-static member function (other than a ctor or dtor) 7132 // by applying it to the function type. 7133 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 7134 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 7135 if (!MD || MD->isStatic()) { 7136 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 7137 << !MD << A->getRange(); 7138 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 7139 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 7140 << isa<CXXDestructorDecl>(MD) << A->getRange(); 7141 } 7142 } 7143 } 7144 } 7145 } 7146 7147 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 7148 NamedDecl *NewDecl, 7149 bool IsSpecialization, 7150 bool IsDefinition) { 7151 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 7152 return; 7153 7154 bool IsTemplate = false; 7155 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 7156 OldDecl = OldTD->getTemplatedDecl(); 7157 IsTemplate = true; 7158 if (!IsSpecialization) 7159 IsDefinition = false; 7160 } 7161 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 7162 NewDecl = NewTD->getTemplatedDecl(); 7163 IsTemplate = true; 7164 } 7165 7166 if (!OldDecl || !NewDecl) 7167 return; 7168 7169 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 7170 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 7171 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 7172 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 7173 7174 // dllimport and dllexport are inheritable attributes so we have to exclude 7175 // inherited attribute instances. 7176 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 7177 (NewExportAttr && !NewExportAttr->isInherited()); 7178 7179 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 7180 // the only exception being explicit specializations. 7181 // Implicitly generated declarations are also excluded for now because there 7182 // is no other way to switch these to use dllimport or dllexport. 7183 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 7184 7185 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 7186 // Allow with a warning for free functions and global variables. 7187 bool JustWarn = false; 7188 if (!OldDecl->isCXXClassMember()) { 7189 auto *VD = dyn_cast<VarDecl>(OldDecl); 7190 if (VD && !VD->getDescribedVarTemplate()) 7191 JustWarn = true; 7192 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 7193 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 7194 JustWarn = true; 7195 } 7196 7197 // We cannot change a declaration that's been used because IR has already 7198 // been emitted. Dllimported functions will still work though (modulo 7199 // address equality) as they can use the thunk. 7200 if (OldDecl->isUsed()) 7201 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 7202 JustWarn = false; 7203 7204 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 7205 : diag::err_attribute_dll_redeclaration; 7206 S.Diag(NewDecl->getLocation(), DiagID) 7207 << NewDecl 7208 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 7209 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 7210 if (!JustWarn) { 7211 NewDecl->setInvalidDecl(); 7212 return; 7213 } 7214 } 7215 7216 // A redeclaration is not allowed to drop a dllimport attribute, the only 7217 // exceptions being inline function definitions (except for function 7218 // templates), local extern declarations, qualified friend declarations or 7219 // special MSVC extension: in the last case, the declaration is treated as if 7220 // it were marked dllexport. 7221 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 7222 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 7223 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 7224 // Ignore static data because out-of-line definitions are diagnosed 7225 // separately. 7226 IsStaticDataMember = VD->isStaticDataMember(); 7227 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 7228 VarDecl::DeclarationOnly; 7229 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 7230 IsInline = FD->isInlined(); 7231 IsQualifiedFriend = FD->getQualifier() && 7232 FD->getFriendObjectKind() == Decl::FOK_Declared; 7233 } 7234 7235 if (OldImportAttr && !HasNewAttr && 7236 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 7237 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 7238 if (IsMicrosoftABI && IsDefinition) { 7239 if (IsSpecialization) { 7240 S.Diag( 7241 NewDecl->getLocation(), 7242 diag::err_attribute_dllimport_function_specialization_definition); 7243 S.Diag(OldImportAttr->getLocation(), diag::note_attribute); 7244 NewDecl->dropAttr<DLLImportAttr>(); 7245 } else { 7246 S.Diag(NewDecl->getLocation(), 7247 diag::warn_redeclaration_without_import_attribute) 7248 << NewDecl; 7249 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 7250 NewDecl->dropAttr<DLLImportAttr>(); 7251 NewDecl->addAttr(DLLExportAttr::CreateImplicit( 7252 S.Context, NewImportAttr->getRange())); 7253 } 7254 } else if (IsMicrosoftABI && IsSpecialization) { 7255 assert(!IsDefinition); 7256 // MSVC allows this. Keep the inherited attribute. 7257 } else { 7258 S.Diag(NewDecl->getLocation(), 7259 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 7260 << NewDecl << OldImportAttr; 7261 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 7262 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 7263 OldDecl->dropAttr<DLLImportAttr>(); 7264 NewDecl->dropAttr<DLLImportAttr>(); 7265 } 7266 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 7267 // In MinGW, seeing a function declared inline drops the dllimport 7268 // attribute. 7269 OldDecl->dropAttr<DLLImportAttr>(); 7270 NewDecl->dropAttr<DLLImportAttr>(); 7271 S.Diag(NewDecl->getLocation(), 7272 diag::warn_dllimport_dropped_from_inline_function) 7273 << NewDecl << OldImportAttr; 7274 } 7275 7276 // A specialization of a class template member function is processed here 7277 // since it's a redeclaration. If the parent class is dllexport, the 7278 // specialization inherits that attribute. This doesn't happen automatically 7279 // since the parent class isn't instantiated until later. 7280 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 7281 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 7282 !NewImportAttr && !NewExportAttr) { 7283 if (const DLLExportAttr *ParentExportAttr = 7284 MD->getParent()->getAttr<DLLExportAttr>()) { 7285 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 7286 NewAttr->setInherited(true); 7287 NewDecl->addAttr(NewAttr); 7288 } 7289 } 7290 } 7291 } 7292 7293 /// Given that we are within the definition of the given function, 7294 /// will that definition behave like C99's 'inline', where the 7295 /// definition is discarded except for optimization purposes? 7296 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 7297 // Try to avoid calling GetGVALinkageForFunction. 7298 7299 // All cases of this require the 'inline' keyword. 7300 if (!FD->isInlined()) return false; 7301 7302 // This is only possible in C++ with the gnu_inline attribute. 7303 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 7304 return false; 7305 7306 // Okay, go ahead and call the relatively-more-expensive function. 7307 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 7308 } 7309 7310 /// Determine whether a variable is extern "C" prior to attaching 7311 /// an initializer. We can't just call isExternC() here, because that 7312 /// will also compute and cache whether the declaration is externally 7313 /// visible, which might change when we attach the initializer. 7314 /// 7315 /// This can only be used if the declaration is known to not be a 7316 /// redeclaration of an internal linkage declaration. 7317 /// 7318 /// For instance: 7319 /// 7320 /// auto x = []{}; 7321 /// 7322 /// Attaching the initializer here makes this declaration not externally 7323 /// visible, because its type has internal linkage. 7324 /// 7325 /// FIXME: This is a hack. 7326 template<typename T> 7327 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 7328 if (S.getLangOpts().CPlusPlus) { 7329 // In C++, the overloadable attribute negates the effects of extern "C". 7330 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 7331 return false; 7332 7333 // So do CUDA's host/device attributes. 7334 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 7335 D->template hasAttr<CUDAHostAttr>())) 7336 return false; 7337 } 7338 return D->isExternC(); 7339 } 7340 7341 static bool shouldConsiderLinkage(const VarDecl *VD) { 7342 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 7343 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 7344 isa<OMPDeclareMapperDecl>(DC)) 7345 return VD->hasExternalStorage(); 7346 if (DC->isFileContext()) 7347 return true; 7348 if (DC->isRecord()) 7349 return false; 7350 if (DC->getDeclKind() == Decl::HLSLBuffer) 7351 return false; 7352 7353 if (isa<RequiresExprBodyDecl>(DC)) 7354 return false; 7355 llvm_unreachable("Unexpected context"); 7356 } 7357 7358 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 7359 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 7360 if (DC->isFileContext() || DC->isFunctionOrMethod() || 7361 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 7362 return true; 7363 if (DC->isRecord()) 7364 return false; 7365 llvm_unreachable("Unexpected context"); 7366 } 7367 7368 static bool hasParsedAttr(Scope *S, const Declarator &PD, 7369 ParsedAttr::Kind Kind) { 7370 // Check decl attributes on the DeclSpec. 7371 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 7372 return true; 7373 7374 // Walk the declarator structure, checking decl attributes that were in a type 7375 // position to the decl itself. 7376 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 7377 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 7378 return true; 7379 } 7380 7381 // Finally, check attributes on the decl itself. 7382 return PD.getAttributes().hasAttribute(Kind) || 7383 PD.getDeclarationAttributes().hasAttribute(Kind); 7384 } 7385 7386 /// Adjust the \c DeclContext for a function or variable that might be a 7387 /// function-local external declaration. 7388 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 7389 if (!DC->isFunctionOrMethod()) 7390 return false; 7391 7392 // If this is a local extern function or variable declared within a function 7393 // template, don't add it into the enclosing namespace scope until it is 7394 // instantiated; it might have a dependent type right now. 7395 if (DC->isDependentContext()) 7396 return true; 7397 7398 // C++11 [basic.link]p7: 7399 // When a block scope declaration of an entity with linkage is not found to 7400 // refer to some other declaration, then that entity is a member of the 7401 // innermost enclosing namespace. 7402 // 7403 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 7404 // semantically-enclosing namespace, not a lexically-enclosing one. 7405 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 7406 DC = DC->getParent(); 7407 return true; 7408 } 7409 7410 /// Returns true if given declaration has external C language linkage. 7411 static bool isDeclExternC(const Decl *D) { 7412 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 7413 return FD->isExternC(); 7414 if (const auto *VD = dyn_cast<VarDecl>(D)) 7415 return VD->isExternC(); 7416 7417 llvm_unreachable("Unknown type of decl!"); 7418 } 7419 7420 /// Returns true if there hasn't been any invalid type diagnosed. 7421 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 7422 DeclContext *DC = NewVD->getDeclContext(); 7423 QualType R = NewVD->getType(); 7424 7425 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 7426 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 7427 // argument. 7428 if (R->isImageType() || R->isPipeType()) { 7429 Se.Diag(NewVD->getLocation(), 7430 diag::err_opencl_type_can_only_be_used_as_function_parameter) 7431 << R; 7432 NewVD->setInvalidDecl(); 7433 return false; 7434 } 7435 7436 // OpenCL v1.2 s6.9.r: 7437 // The event type cannot be used to declare a program scope variable. 7438 // OpenCL v2.0 s6.9.q: 7439 // The clk_event_t and reserve_id_t types cannot be declared in program 7440 // scope. 7441 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 7442 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 7443 Se.Diag(NewVD->getLocation(), 7444 diag::err_invalid_type_for_program_scope_var) 7445 << R; 7446 NewVD->setInvalidDecl(); 7447 return false; 7448 } 7449 } 7450 7451 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 7452 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 7453 Se.getLangOpts())) { 7454 QualType NR = R.getCanonicalType(); 7455 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 7456 NR->isReferenceType()) { 7457 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 7458 NR->isFunctionReferenceType()) { 7459 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 7460 << NR->isReferenceType(); 7461 NewVD->setInvalidDecl(); 7462 return false; 7463 } 7464 NR = NR->getPointeeType(); 7465 } 7466 } 7467 7468 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 7469 Se.getLangOpts())) { 7470 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 7471 // half array type (unless the cl_khr_fp16 extension is enabled). 7472 if (Se.Context.getBaseElementType(R)->isHalfType()) { 7473 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 7474 NewVD->setInvalidDecl(); 7475 return false; 7476 } 7477 } 7478 7479 // OpenCL v1.2 s6.9.r: 7480 // The event type cannot be used with the __local, __constant and __global 7481 // address space qualifiers. 7482 if (R->isEventT()) { 7483 if (R.getAddressSpace() != LangAS::opencl_private) { 7484 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 7485 NewVD->setInvalidDecl(); 7486 return false; 7487 } 7488 } 7489 7490 if (R->isSamplerT()) { 7491 // OpenCL v1.2 s6.9.b p4: 7492 // The sampler type cannot be used with the __local and __global address 7493 // space qualifiers. 7494 if (R.getAddressSpace() == LangAS::opencl_local || 7495 R.getAddressSpace() == LangAS::opencl_global) { 7496 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 7497 NewVD->setInvalidDecl(); 7498 } 7499 7500 // OpenCL v1.2 s6.12.14.1: 7501 // A global sampler must be declared with either the constant address 7502 // space qualifier or with the const qualifier. 7503 if (DC->isTranslationUnit() && 7504 !(R.getAddressSpace() == LangAS::opencl_constant || 7505 R.isConstQualified())) { 7506 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 7507 NewVD->setInvalidDecl(); 7508 } 7509 if (NewVD->isInvalidDecl()) 7510 return false; 7511 } 7512 7513 return true; 7514 } 7515 7516 template <typename AttrTy> 7517 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 7518 const TypedefNameDecl *TND = TT->getDecl(); 7519 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 7520 AttrTy *Clone = Attribute->clone(S.Context); 7521 Clone->setInherited(true); 7522 D->addAttr(Clone); 7523 } 7524 } 7525 7526 // This function emits warning and a corresponding note based on the 7527 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable 7528 // declarations of an annotated type must be const qualified. 7529 void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) { 7530 QualType VarType = VD->getType().getCanonicalType(); 7531 7532 // Ignore local declarations (for now) and those with const qualification. 7533 // TODO: Local variables should not be allowed if their type declaration has 7534 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch. 7535 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified()) 7536 return; 7537 7538 if (VarType->isArrayType()) { 7539 // Retrieve element type for array declarations. 7540 VarType = S.getASTContext().getBaseElementType(VarType); 7541 } 7542 7543 const RecordDecl *RD = VarType->getAsRecordDecl(); 7544 7545 // Check if the record declaration is present and if it has any attributes. 7546 if (RD == nullptr) 7547 return; 7548 7549 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) { 7550 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD; 7551 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement); 7552 return; 7553 } 7554 } 7555 7556 NamedDecl *Sema::ActOnVariableDeclarator( 7557 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 7558 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 7559 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 7560 QualType R = TInfo->getType(); 7561 DeclarationName Name = GetNameForDeclarator(D).getName(); 7562 7563 IdentifierInfo *II = Name.getAsIdentifierInfo(); 7564 bool IsPlaceholderVariable = false; 7565 7566 if (D.isDecompositionDeclarator()) { 7567 // Take the name of the first declarator as our name for diagnostic 7568 // purposes. 7569 auto &Decomp = D.getDecompositionDeclarator(); 7570 if (!Decomp.bindings().empty()) { 7571 II = Decomp.bindings()[0].Name; 7572 Name = II; 7573 } 7574 } else if (!II) { 7575 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 7576 return nullptr; 7577 } 7578 7579 7580 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 7581 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 7582 7583 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) && 7584 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) { 7585 IsPlaceholderVariable = true; 7586 if (!Previous.empty()) { 7587 NamedDecl *PrevDecl = *Previous.begin(); 7588 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals( 7589 DC->getRedeclContext()); 7590 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) 7591 DiagPlaceholderVariableDefinition(D.getIdentifierLoc()); 7592 } 7593 } 7594 7595 // dllimport globals without explicit storage class are treated as extern. We 7596 // have to change the storage class this early to get the right DeclContext. 7597 if (SC == SC_None && !DC->isRecord() && 7598 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 7599 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 7600 SC = SC_Extern; 7601 7602 DeclContext *OriginalDC = DC; 7603 bool IsLocalExternDecl = SC == SC_Extern && 7604 adjustContextForLocalExternDecl(DC); 7605 7606 if (SCSpec == DeclSpec::SCS_mutable) { 7607 // mutable can only appear on non-static class members, so it's always 7608 // an error here 7609 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 7610 D.setInvalidType(); 7611 SC = SC_None; 7612 } 7613 7614 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 7615 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 7616 D.getDeclSpec().getStorageClassSpecLoc())) { 7617 // In C++11, the 'register' storage class specifier is deprecated. 7618 // Suppress the warning in system macros, it's used in macros in some 7619 // popular C system headers, such as in glibc's htonl() macro. 7620 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7621 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 7622 : diag::warn_deprecated_register) 7623 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7624 } 7625 7626 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 7627 7628 if (!DC->isRecord() && S->getFnParent() == nullptr) { 7629 // C99 6.9p2: The storage-class specifiers auto and register shall not 7630 // appear in the declaration specifiers in an external declaration. 7631 // Global Register+Asm is a GNU extension we support. 7632 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 7633 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 7634 D.setInvalidType(); 7635 } 7636 } 7637 7638 // If this variable has a VLA type and an initializer, try to 7639 // fold to a constant-sized type. This is otherwise invalid. 7640 if (D.hasInitializer() && R->isVariableArrayType()) 7641 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7642 /*DiagID=*/0); 7643 7644 bool IsMemberSpecialization = false; 7645 bool IsVariableTemplateSpecialization = false; 7646 bool IsPartialSpecialization = false; 7647 bool IsVariableTemplate = false; 7648 VarDecl *NewVD = nullptr; 7649 VarTemplateDecl *NewTemplate = nullptr; 7650 TemplateParameterList *TemplateParams = nullptr; 7651 if (!getLangOpts().CPlusPlus) { 7652 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7653 II, R, TInfo, SC); 7654 7655 if (R->getContainedDeducedType()) 7656 ParsingInitForAutoVars.insert(NewVD); 7657 7658 if (D.isInvalidType()) 7659 NewVD->setInvalidDecl(); 7660 7661 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7662 NewVD->hasLocalStorage()) 7663 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7664 NTCUC_AutoVar, NTCUK_Destruct); 7665 } else { 7666 bool Invalid = false; 7667 7668 if (DC->isRecord() && !CurContext->isRecord()) { 7669 // This is an out-of-line definition of a static data member. 7670 switch (SC) { 7671 case SC_None: 7672 break; 7673 case SC_Static: 7674 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7675 diag::err_static_out_of_line) 7676 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7677 break; 7678 case SC_Auto: 7679 case SC_Register: 7680 case SC_Extern: 7681 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7682 // to names of variables declared in a block or to function parameters. 7683 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7684 // of class members 7685 7686 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7687 diag::err_storage_class_for_static_member) 7688 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7689 break; 7690 case SC_PrivateExtern: 7691 llvm_unreachable("C storage class in c++!"); 7692 } 7693 } 7694 7695 if (SC == SC_Static && CurContext->isRecord()) { 7696 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7697 // Walk up the enclosing DeclContexts to check for any that are 7698 // incompatible with static data members. 7699 const DeclContext *FunctionOrMethod = nullptr; 7700 const CXXRecordDecl *AnonStruct = nullptr; 7701 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7702 if (Ctxt->isFunctionOrMethod()) { 7703 FunctionOrMethod = Ctxt; 7704 break; 7705 } 7706 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7707 if (ParentDecl && !ParentDecl->getDeclName()) { 7708 AnonStruct = ParentDecl; 7709 break; 7710 } 7711 } 7712 if (FunctionOrMethod) { 7713 // C++ [class.static.data]p5: A local class shall not have static data 7714 // members. 7715 Diag(D.getIdentifierLoc(), 7716 diag::err_static_data_member_not_allowed_in_local_class) 7717 << Name << RD->getDeclName() 7718 << llvm::to_underlying(RD->getTagKind()); 7719 } else if (AnonStruct) { 7720 // C++ [class.static.data]p4: Unnamed classes and classes contained 7721 // directly or indirectly within unnamed classes shall not contain 7722 // static data members. 7723 Diag(D.getIdentifierLoc(), 7724 diag::err_static_data_member_not_allowed_in_anon_struct) 7725 << Name << llvm::to_underlying(AnonStruct->getTagKind()); 7726 Invalid = true; 7727 } else if (RD->isUnion()) { 7728 // C++98 [class.union]p1: If a union contains a static data member, 7729 // the program is ill-formed. C++11 drops this restriction. 7730 Diag(D.getIdentifierLoc(), 7731 getLangOpts().CPlusPlus11 7732 ? diag::warn_cxx98_compat_static_data_member_in_union 7733 : diag::ext_static_data_member_in_union) << Name; 7734 } 7735 } 7736 } 7737 7738 // Match up the template parameter lists with the scope specifier, then 7739 // determine whether we have a template or a template specialization. 7740 bool InvalidScope = false; 7741 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7742 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7743 D.getCXXScopeSpec(), 7744 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7745 ? D.getName().TemplateId 7746 : nullptr, 7747 TemplateParamLists, 7748 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7749 Invalid |= InvalidScope; 7750 7751 if (TemplateParams) { 7752 if (!TemplateParams->size() && 7753 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7754 // There is an extraneous 'template<>' for this variable. Complain 7755 // about it, but allow the declaration of the variable. 7756 Diag(TemplateParams->getTemplateLoc(), 7757 diag::err_template_variable_noparams) 7758 << II 7759 << SourceRange(TemplateParams->getTemplateLoc(), 7760 TemplateParams->getRAngleLoc()); 7761 TemplateParams = nullptr; 7762 } else { 7763 // Check that we can declare a template here. 7764 if (CheckTemplateDeclScope(S, TemplateParams)) 7765 return nullptr; 7766 7767 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7768 // This is an explicit specialization or a partial specialization. 7769 IsVariableTemplateSpecialization = true; 7770 IsPartialSpecialization = TemplateParams->size() > 0; 7771 } else { // if (TemplateParams->size() > 0) 7772 // This is a template declaration. 7773 IsVariableTemplate = true; 7774 7775 // Only C++1y supports variable templates (N3651). 7776 Diag(D.getIdentifierLoc(), 7777 getLangOpts().CPlusPlus14 7778 ? diag::warn_cxx11_compat_variable_template 7779 : diag::ext_variable_template); 7780 } 7781 } 7782 } else { 7783 // Check that we can declare a member specialization here. 7784 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7785 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7786 return nullptr; 7787 assert((Invalid || 7788 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7789 "should have a 'template<>' for this decl"); 7790 } 7791 7792 if (IsVariableTemplateSpecialization) { 7793 SourceLocation TemplateKWLoc = 7794 TemplateParamLists.size() > 0 7795 ? TemplateParamLists[0]->getTemplateLoc() 7796 : SourceLocation(); 7797 DeclResult Res = ActOnVarTemplateSpecialization( 7798 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7799 IsPartialSpecialization); 7800 if (Res.isInvalid()) 7801 return nullptr; 7802 NewVD = cast<VarDecl>(Res.get()); 7803 AddToScope = false; 7804 } else if (D.isDecompositionDeclarator()) { 7805 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7806 D.getIdentifierLoc(), R, TInfo, SC, 7807 Bindings); 7808 } else 7809 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7810 D.getIdentifierLoc(), II, R, TInfo, SC); 7811 7812 // If this is supposed to be a variable template, create it as such. 7813 if (IsVariableTemplate) { 7814 NewTemplate = 7815 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7816 TemplateParams, NewVD); 7817 NewVD->setDescribedVarTemplate(NewTemplate); 7818 } 7819 7820 // If this decl has an auto type in need of deduction, make a note of the 7821 // Decl so we can diagnose uses of it in its own initializer. 7822 if (R->getContainedDeducedType()) 7823 ParsingInitForAutoVars.insert(NewVD); 7824 7825 if (D.isInvalidType() || Invalid) { 7826 NewVD->setInvalidDecl(); 7827 if (NewTemplate) 7828 NewTemplate->setInvalidDecl(); 7829 } 7830 7831 SetNestedNameSpecifier(*this, NewVD, D); 7832 7833 // If we have any template parameter lists that don't directly belong to 7834 // the variable (matching the scope specifier), store them. 7835 // An explicit variable template specialization does not own any template 7836 // parameter lists. 7837 bool IsExplicitSpecialization = 7838 IsVariableTemplateSpecialization && !IsPartialSpecialization; 7839 unsigned VDTemplateParamLists = 7840 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0; 7841 if (TemplateParamLists.size() > VDTemplateParamLists) 7842 NewVD->setTemplateParameterListsInfo( 7843 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7844 } 7845 7846 if (D.getDeclSpec().isInlineSpecified()) { 7847 if (!getLangOpts().CPlusPlus) { 7848 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7849 << 0; 7850 } else if (CurContext->isFunctionOrMethod()) { 7851 // 'inline' is not allowed on block scope variable declaration. 7852 Diag(D.getDeclSpec().getInlineSpecLoc(), 7853 diag::err_inline_declaration_block_scope) << Name 7854 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7855 } else { 7856 Diag(D.getDeclSpec().getInlineSpecLoc(), 7857 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7858 : diag::ext_inline_variable); 7859 NewVD->setInlineSpecified(); 7860 } 7861 } 7862 7863 // Set the lexical context. If the declarator has a C++ scope specifier, the 7864 // lexical context will be different from the semantic context. 7865 NewVD->setLexicalDeclContext(CurContext); 7866 if (NewTemplate) 7867 NewTemplate->setLexicalDeclContext(CurContext); 7868 7869 if (IsLocalExternDecl) { 7870 if (D.isDecompositionDeclarator()) 7871 for (auto *B : Bindings) 7872 B->setLocalExternDecl(); 7873 else 7874 NewVD->setLocalExternDecl(); 7875 } 7876 7877 bool EmitTLSUnsupportedError = false; 7878 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7879 // C++11 [dcl.stc]p4: 7880 // When thread_local is applied to a variable of block scope the 7881 // storage-class-specifier static is implied if it does not appear 7882 // explicitly. 7883 // Core issue: 'static' is not implied if the variable is declared 7884 // 'extern'. 7885 if (NewVD->hasLocalStorage() && 7886 (SCSpec != DeclSpec::SCS_unspecified || 7887 TSCS != DeclSpec::TSCS_thread_local || 7888 !DC->isFunctionOrMethod())) 7889 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7890 diag::err_thread_non_global) 7891 << DeclSpec::getSpecifierName(TSCS); 7892 else if (!Context.getTargetInfo().isTLSSupported()) { 7893 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice || 7894 getLangOpts().SYCLIsDevice) { 7895 // Postpone error emission until we've collected attributes required to 7896 // figure out whether it's a host or device variable and whether the 7897 // error should be ignored. 7898 EmitTLSUnsupportedError = true; 7899 // We still need to mark the variable as TLS so it shows up in AST with 7900 // proper storage class for other tools to use even if we're not going 7901 // to emit any code for it. 7902 NewVD->setTSCSpec(TSCS); 7903 } else 7904 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7905 diag::err_thread_unsupported); 7906 } else 7907 NewVD->setTSCSpec(TSCS); 7908 } 7909 7910 switch (D.getDeclSpec().getConstexprSpecifier()) { 7911 case ConstexprSpecKind::Unspecified: 7912 break; 7913 7914 case ConstexprSpecKind::Consteval: 7915 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7916 diag::err_constexpr_wrong_decl_kind) 7917 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7918 [[fallthrough]]; 7919 7920 case ConstexprSpecKind::Constexpr: 7921 NewVD->setConstexpr(true); 7922 // C++1z [dcl.spec.constexpr]p1: 7923 // A static data member declared with the constexpr specifier is 7924 // implicitly an inline variable. 7925 if (NewVD->isStaticDataMember() && 7926 (getLangOpts().CPlusPlus17 || 7927 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7928 NewVD->setImplicitlyInline(); 7929 break; 7930 7931 case ConstexprSpecKind::Constinit: 7932 if (!NewVD->hasGlobalStorage()) 7933 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7934 diag::err_constinit_local_variable); 7935 else 7936 NewVD->addAttr( 7937 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(), 7938 ConstInitAttr::Keyword_constinit)); 7939 break; 7940 } 7941 7942 // C99 6.7.4p3 7943 // An inline definition of a function with external linkage shall 7944 // not contain a definition of a modifiable object with static or 7945 // thread storage duration... 7946 // We only apply this when the function is required to be defined 7947 // elsewhere, i.e. when the function is not 'extern inline'. Note 7948 // that a local variable with thread storage duration still has to 7949 // be marked 'static'. Also note that it's possible to get these 7950 // semantics in C++ using __attribute__((gnu_inline)). 7951 if (SC == SC_Static && S->getFnParent() != nullptr && 7952 !NewVD->getType().isConstQualified()) { 7953 FunctionDecl *CurFD = getCurFunctionDecl(); 7954 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7955 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7956 diag::warn_static_local_in_extern_inline); 7957 MaybeSuggestAddingStaticToDecl(CurFD); 7958 } 7959 } 7960 7961 if (D.getDeclSpec().isModulePrivateSpecified()) { 7962 if (IsVariableTemplateSpecialization) 7963 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7964 << (IsPartialSpecialization ? 1 : 0) 7965 << FixItHint::CreateRemoval( 7966 D.getDeclSpec().getModulePrivateSpecLoc()); 7967 else if (IsMemberSpecialization) 7968 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7969 << 2 7970 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7971 else if (NewVD->hasLocalStorage()) 7972 Diag(NewVD->getLocation(), diag::err_module_private_local) 7973 << 0 << NewVD 7974 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7975 << FixItHint::CreateRemoval( 7976 D.getDeclSpec().getModulePrivateSpecLoc()); 7977 else { 7978 NewVD->setModulePrivate(); 7979 if (NewTemplate) 7980 NewTemplate->setModulePrivate(); 7981 for (auto *B : Bindings) 7982 B->setModulePrivate(); 7983 } 7984 } 7985 7986 if (getLangOpts().OpenCL) { 7987 deduceOpenCLAddressSpace(NewVD); 7988 7989 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7990 if (TSC != TSCS_unspecified) { 7991 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7992 diag::err_opencl_unknown_type_specifier) 7993 << getLangOpts().getOpenCLVersionString() 7994 << DeclSpec::getSpecifierName(TSC) << 1; 7995 NewVD->setInvalidDecl(); 7996 } 7997 } 7998 7999 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply 8000 // address space if the table has local storage (semantic checks elsewhere 8001 // will produce an error anyway). 8002 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) { 8003 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() && 8004 !NewVD->hasLocalStorage()) { 8005 QualType Type = Context.getAddrSpaceQualType( 8006 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1)); 8007 NewVD->setType(Type); 8008 } 8009 } 8010 8011 // Handle attributes prior to checking for duplicates in MergeVarDecl 8012 ProcessDeclAttributes(S, NewVD, D); 8013 8014 // FIXME: This is probably the wrong location to be doing this and we should 8015 // probably be doing this for more attributes (especially for function 8016 // pointer attributes such as format, warn_unused_result, etc.). Ideally 8017 // the code to copy attributes would be generated by TableGen. 8018 if (R->isFunctionPointerType()) 8019 if (const auto *TT = R->getAs<TypedefType>()) 8020 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 8021 8022 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice || 8023 getLangOpts().SYCLIsDevice) { 8024 if (EmitTLSUnsupportedError && 8025 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 8026 (getLangOpts().OpenMPIsTargetDevice && 8027 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 8028 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8029 diag::err_thread_unsupported); 8030 8031 if (EmitTLSUnsupportedError && 8032 (LangOpts.SYCLIsDevice || 8033 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice))) 8034 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 8035 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 8036 // storage [duration]." 8037 if (SC == SC_None && S->getFnParent() != nullptr && 8038 (NewVD->hasAttr<CUDASharedAttr>() || 8039 NewVD->hasAttr<CUDAConstantAttr>())) { 8040 NewVD->setStorageClass(SC_Static); 8041 } 8042 } 8043 8044 // Ensure that dllimport globals without explicit storage class are treated as 8045 // extern. The storage class is set above using parsed attributes. Now we can 8046 // check the VarDecl itself. 8047 assert(!NewVD->hasAttr<DLLImportAttr>() || 8048 NewVD->getAttr<DLLImportAttr>()->isInherited() || 8049 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 8050 8051 // In auto-retain/release, infer strong retension for variables of 8052 // retainable type. 8053 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 8054 NewVD->setInvalidDecl(); 8055 8056 // Handle GNU asm-label extension (encoded as an attribute). 8057 if (Expr *E = (Expr*)D.getAsmLabel()) { 8058 // The parser guarantees this is a string. 8059 StringLiteral *SE = cast<StringLiteral>(E); 8060 StringRef Label = SE->getString(); 8061 if (S->getFnParent() != nullptr) { 8062 switch (SC) { 8063 case SC_None: 8064 case SC_Auto: 8065 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 8066 break; 8067 case SC_Register: 8068 // Local Named register 8069 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 8070 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 8071 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 8072 break; 8073 case SC_Static: 8074 case SC_Extern: 8075 case SC_PrivateExtern: 8076 break; 8077 } 8078 } else if (SC == SC_Register) { 8079 // Global Named register 8080 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 8081 const auto &TI = Context.getTargetInfo(); 8082 bool HasSizeMismatch; 8083 8084 if (!TI.isValidGCCRegisterName(Label)) 8085 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 8086 else if (!TI.validateGlobalRegisterVariable(Label, 8087 Context.getTypeSize(R), 8088 HasSizeMismatch)) 8089 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 8090 else if (HasSizeMismatch) 8091 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 8092 } 8093 8094 if (!R->isIntegralType(Context) && !R->isPointerType()) { 8095 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 8096 NewVD->setInvalidDecl(true); 8097 } 8098 } 8099 8100 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 8101 /*IsLiteralLabel=*/true, 8102 SE->getStrTokenLoc(0))); 8103 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8104 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8105 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 8106 if (I != ExtnameUndeclaredIdentifiers.end()) { 8107 if (isDeclExternC(NewVD)) { 8108 NewVD->addAttr(I->second); 8109 ExtnameUndeclaredIdentifiers.erase(I); 8110 } else 8111 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 8112 << /*Variable*/1 << NewVD; 8113 } 8114 } 8115 8116 // Find the shadowed declaration before filtering for scope. 8117 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 8118 ? getShadowedDeclaration(NewVD, Previous) 8119 : nullptr; 8120 8121 // Don't consider existing declarations that are in a different 8122 // scope and are out-of-semantic-context declarations (if the new 8123 // declaration has linkage). 8124 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 8125 D.getCXXScopeSpec().isNotEmpty() || 8126 IsMemberSpecialization || 8127 IsVariableTemplateSpecialization); 8128 8129 // Check whether the previous declaration is in the same block scope. This 8130 // affects whether we merge types with it, per C++11 [dcl.array]p3. 8131 if (getLangOpts().CPlusPlus && 8132 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 8133 NewVD->setPreviousDeclInSameBlockScope( 8134 Previous.isSingleResult() && !Previous.isShadowed() && 8135 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 8136 8137 if (!getLangOpts().CPlusPlus) { 8138 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 8139 } else { 8140 // If this is an explicit specialization of a static data member, check it. 8141 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 8142 CheckMemberSpecialization(NewVD, Previous)) 8143 NewVD->setInvalidDecl(); 8144 8145 // Merge the decl with the existing one if appropriate. 8146 if (!Previous.empty()) { 8147 if (Previous.isSingleResult() && 8148 isa<FieldDecl>(Previous.getFoundDecl()) && 8149 D.getCXXScopeSpec().isSet()) { 8150 // The user tried to define a non-static data member 8151 // out-of-line (C++ [dcl.meaning]p1). 8152 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 8153 << D.getCXXScopeSpec().getRange(); 8154 Previous.clear(); 8155 NewVD->setInvalidDecl(); 8156 } 8157 } else if (D.getCXXScopeSpec().isSet()) { 8158 // No previous declaration in the qualifying scope. 8159 Diag(D.getIdentifierLoc(), diag::err_no_member) 8160 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 8161 << D.getCXXScopeSpec().getRange(); 8162 NewVD->setInvalidDecl(); 8163 } 8164 8165 if (!IsVariableTemplateSpecialization && !IsPlaceholderVariable) 8166 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 8167 8168 // CheckVariableDeclaration will set NewVD as invalid if something is in 8169 // error like WebAssembly tables being declared as arrays with a non-zero 8170 // size, but then parsing continues and emits further errors on that line. 8171 // To avoid that we check here if it happened and return nullptr. 8172 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl()) 8173 return nullptr; 8174 8175 if (NewTemplate) { 8176 VarTemplateDecl *PrevVarTemplate = 8177 NewVD->getPreviousDecl() 8178 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 8179 : nullptr; 8180 8181 // Check the template parameter list of this declaration, possibly 8182 // merging in the template parameter list from the previous variable 8183 // template declaration. 8184 if (CheckTemplateParameterList( 8185 TemplateParams, 8186 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 8187 : nullptr, 8188 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 8189 DC->isDependentContext()) 8190 ? TPC_ClassTemplateMember 8191 : TPC_VarTemplate)) 8192 NewVD->setInvalidDecl(); 8193 8194 // If we are providing an explicit specialization of a static variable 8195 // template, make a note of that. 8196 if (PrevVarTemplate && 8197 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 8198 PrevVarTemplate->setMemberSpecialization(); 8199 } 8200 } 8201 8202 // Diagnose shadowed variables iff this isn't a redeclaration. 8203 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration()) 8204 CheckShadow(NewVD, ShadowedDecl, Previous); 8205 8206 ProcessPragmaWeak(S, NewVD); 8207 8208 // If this is the first declaration of an extern C variable, update 8209 // the map of such variables. 8210 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 8211 isIncompleteDeclExternC(*this, NewVD)) 8212 RegisterLocallyScopedExternCDecl(NewVD, S); 8213 8214 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 8215 MangleNumberingContext *MCtx; 8216 Decl *ManglingContextDecl; 8217 std::tie(MCtx, ManglingContextDecl) = 8218 getCurrentMangleNumberContext(NewVD->getDeclContext()); 8219 if (MCtx) { 8220 Context.setManglingNumber( 8221 NewVD, MCtx->getManglingNumber( 8222 NewVD, getMSManglingNumber(getLangOpts(), S))); 8223 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 8224 } 8225 } 8226 8227 // Special handling of variable named 'main'. 8228 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 8229 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 8230 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 8231 8232 // C++ [basic.start.main]p3 8233 // A program that declares a variable main at global scope is ill-formed. 8234 if (getLangOpts().CPlusPlus) 8235 Diag(D.getBeginLoc(), diag::err_main_global_variable); 8236 8237 // In C, and external-linkage variable named main results in undefined 8238 // behavior. 8239 else if (NewVD->hasExternalFormalLinkage()) 8240 Diag(D.getBeginLoc(), diag::warn_main_redefined); 8241 } 8242 8243 if (D.isRedeclaration() && !Previous.empty()) { 8244 NamedDecl *Prev = Previous.getRepresentativeDecl(); 8245 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 8246 D.isFunctionDefinition()); 8247 } 8248 8249 if (NewTemplate) { 8250 if (NewVD->isInvalidDecl()) 8251 NewTemplate->setInvalidDecl(); 8252 ActOnDocumentableDecl(NewTemplate); 8253 return NewTemplate; 8254 } 8255 8256 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 8257 CompleteMemberSpecialization(NewVD, Previous); 8258 8259 emitReadOnlyPlacementAttrWarning(*this, NewVD); 8260 8261 return NewVD; 8262 } 8263 8264 /// Enum describing the %select options in diag::warn_decl_shadow. 8265 enum ShadowedDeclKind { 8266 SDK_Local, 8267 SDK_Global, 8268 SDK_StaticMember, 8269 SDK_Field, 8270 SDK_Typedef, 8271 SDK_Using, 8272 SDK_StructuredBinding 8273 }; 8274 8275 /// Determine what kind of declaration we're shadowing. 8276 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 8277 const DeclContext *OldDC) { 8278 if (isa<TypeAliasDecl>(ShadowedDecl)) 8279 return SDK_Using; 8280 else if (isa<TypedefDecl>(ShadowedDecl)) 8281 return SDK_Typedef; 8282 else if (isa<BindingDecl>(ShadowedDecl)) 8283 return SDK_StructuredBinding; 8284 else if (isa<RecordDecl>(OldDC)) 8285 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 8286 8287 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 8288 } 8289 8290 /// Return the location of the capture if the given lambda captures the given 8291 /// variable \p VD, or an invalid source location otherwise. 8292 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 8293 const VarDecl *VD) { 8294 for (const Capture &Capture : LSI->Captures) { 8295 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 8296 return Capture.getLocation(); 8297 } 8298 return SourceLocation(); 8299 } 8300 8301 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 8302 const LookupResult &R) { 8303 // Only diagnose if we're shadowing an unambiguous field or variable. 8304 if (R.getResultKind() != LookupResult::Found) 8305 return false; 8306 8307 // Return false if warning is ignored. 8308 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 8309 } 8310 8311 /// Return the declaration shadowed by the given variable \p D, or null 8312 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 8313 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 8314 const LookupResult &R) { 8315 if (!shouldWarnIfShadowedDecl(Diags, R)) 8316 return nullptr; 8317 8318 // Don't diagnose declarations at file scope. 8319 if (D->hasGlobalStorage() && !D->isStaticLocal()) 8320 return nullptr; 8321 8322 NamedDecl *ShadowedDecl = R.getFoundDecl(); 8323 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 8324 : nullptr; 8325 } 8326 8327 /// Return the declaration shadowed by the given typedef \p D, or null 8328 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 8329 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 8330 const LookupResult &R) { 8331 // Don't warn if typedef declaration is part of a class 8332 if (D->getDeclContext()->isRecord()) 8333 return nullptr; 8334 8335 if (!shouldWarnIfShadowedDecl(Diags, R)) 8336 return nullptr; 8337 8338 NamedDecl *ShadowedDecl = R.getFoundDecl(); 8339 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 8340 } 8341 8342 /// Return the declaration shadowed by the given variable \p D, or null 8343 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 8344 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 8345 const LookupResult &R) { 8346 if (!shouldWarnIfShadowedDecl(Diags, R)) 8347 return nullptr; 8348 8349 NamedDecl *ShadowedDecl = R.getFoundDecl(); 8350 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 8351 : nullptr; 8352 } 8353 8354 /// Diagnose variable or built-in function shadowing. Implements 8355 /// -Wshadow. 8356 /// 8357 /// This method is called whenever a VarDecl is added to a "useful" 8358 /// scope. 8359 /// 8360 /// \param ShadowedDecl the declaration that is shadowed by the given variable 8361 /// \param R the lookup of the name 8362 /// 8363 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 8364 const LookupResult &R) { 8365 DeclContext *NewDC = D->getDeclContext(); 8366 8367 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 8368 // Fields are not shadowed by variables in C++ static methods. 8369 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 8370 if (MD->isStatic()) 8371 return; 8372 8373 // Fields shadowed by constructor parameters are a special case. Usually 8374 // the constructor initializes the field with the parameter. 8375 if (isa<CXXConstructorDecl>(NewDC)) 8376 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 8377 // Remember that this was shadowed so we can either warn about its 8378 // modification or its existence depending on warning settings. 8379 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 8380 return; 8381 } 8382 } 8383 8384 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 8385 if (shadowedVar->isExternC()) { 8386 // For shadowing external vars, make sure that we point to the global 8387 // declaration, not a locally scoped extern declaration. 8388 for (auto *I : shadowedVar->redecls()) 8389 if (I->isFileVarDecl()) { 8390 ShadowedDecl = I; 8391 break; 8392 } 8393 } 8394 8395 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 8396 8397 unsigned WarningDiag = diag::warn_decl_shadow; 8398 SourceLocation CaptureLoc; 8399 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) { 8400 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 8401 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 8402 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) { 8403 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 8404 if (RD->getLambdaCaptureDefault() == LCD_None) { 8405 // Try to avoid warnings for lambdas with an explicit capture 8406 // list. Warn only when the lambda captures the shadowed decl 8407 // explicitly. 8408 CaptureLoc = getCaptureLocation(LSI, VD); 8409 if (CaptureLoc.isInvalid()) 8410 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 8411 } else { 8412 // Remember that this was shadowed so we can avoid the warning if 8413 // the shadowed decl isn't captured and the warning settings allow 8414 // it. 8415 cast<LambdaScopeInfo>(getCurFunction()) 8416 ->ShadowingDecls.push_back({D, VD}); 8417 return; 8418 } 8419 } 8420 if (isa<FieldDecl>(ShadowedDecl)) { 8421 // If lambda can capture this, then emit default shadowing warning, 8422 // Otherwise it is not really a shadowing case since field is not 8423 // available in lambda's body. 8424 // At this point we don't know that lambda can capture this, so 8425 // remember that this was shadowed and delay until we know. 8426 cast<LambdaScopeInfo>(getCurFunction()) 8427 ->ShadowingDecls.push_back({D, ShadowedDecl}); 8428 return; 8429 } 8430 } 8431 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl); 8432 VD && VD->hasLocalStorage()) { 8433 // A variable can't shadow a local variable in an enclosing scope, if 8434 // they are separated by a non-capturing declaration context. 8435 for (DeclContext *ParentDC = NewDC; 8436 ParentDC && !ParentDC->Equals(OldDC); 8437 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 8438 // Only block literals, captured statements, and lambda expressions 8439 // can capture; other scopes don't. 8440 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 8441 !isLambdaCallOperator(ParentDC)) { 8442 return; 8443 } 8444 } 8445 } 8446 } 8447 } 8448 8449 // Never warn about shadowing a placeholder variable. 8450 if (ShadowedDecl->isPlaceholderVar(getLangOpts())) 8451 return; 8452 8453 // Only warn about certain kinds of shadowing for class members. 8454 if (NewDC && NewDC->isRecord()) { 8455 // In particular, don't warn about shadowing non-class members. 8456 if (!OldDC->isRecord()) 8457 return; 8458 8459 // TODO: should we warn about static data members shadowing 8460 // static data members from base classes? 8461 8462 // TODO: don't diagnose for inaccessible shadowed members. 8463 // This is hard to do perfectly because we might friend the 8464 // shadowing context, but that's just a false negative. 8465 } 8466 8467 8468 DeclarationName Name = R.getLookupName(); 8469 8470 // Emit warning and note. 8471 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 8472 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 8473 if (!CaptureLoc.isInvalid()) 8474 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8475 << Name << /*explicitly*/ 1; 8476 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8477 } 8478 8479 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 8480 /// when these variables are captured by the lambda. 8481 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 8482 for (const auto &Shadow : LSI->ShadowingDecls) { 8483 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl; 8484 // Try to avoid the warning when the shadowed decl isn't captured. 8485 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8486 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) { 8487 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD); 8488 Diag(Shadow.VD->getLocation(), 8489 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local 8490 : diag::warn_decl_shadow) 8491 << Shadow.VD->getDeclName() 8492 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 8493 if (CaptureLoc.isValid()) 8494 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8495 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 8496 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8497 } else if (isa<FieldDecl>(ShadowedDecl)) { 8498 Diag(Shadow.VD->getLocation(), 8499 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow 8500 : diag::warn_decl_shadow_uncaptured_local) 8501 << Shadow.VD->getDeclName() 8502 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 8503 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8504 } 8505 } 8506 } 8507 8508 /// Check -Wshadow without the advantage of a previous lookup. 8509 void Sema::CheckShadow(Scope *S, VarDecl *D) { 8510 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 8511 return; 8512 8513 LookupResult R(*this, D->getDeclName(), D->getLocation(), 8514 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 8515 LookupName(R, S); 8516 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 8517 CheckShadow(D, ShadowedDecl, R); 8518 } 8519 8520 /// Check if 'E', which is an expression that is about to be modified, refers 8521 /// to a constructor parameter that shadows a field. 8522 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 8523 // Quickly ignore expressions that can't be shadowing ctor parameters. 8524 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 8525 return; 8526 E = E->IgnoreParenImpCasts(); 8527 auto *DRE = dyn_cast<DeclRefExpr>(E); 8528 if (!DRE) 8529 return; 8530 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 8531 auto I = ShadowingDecls.find(D); 8532 if (I == ShadowingDecls.end()) 8533 return; 8534 const NamedDecl *ShadowedDecl = I->second; 8535 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8536 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 8537 Diag(D->getLocation(), diag::note_var_declared_here) << D; 8538 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8539 8540 // Avoid issuing multiple warnings about the same decl. 8541 ShadowingDecls.erase(I); 8542 } 8543 8544 /// Check for conflict between this global or extern "C" declaration and 8545 /// previous global or extern "C" declarations. This is only used in C++. 8546 template<typename T> 8547 static bool checkGlobalOrExternCConflict( 8548 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 8549 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 8550 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 8551 8552 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 8553 // The common case: this global doesn't conflict with any extern "C" 8554 // declaration. 8555 return false; 8556 } 8557 8558 if (Prev) { 8559 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 8560 // Both the old and new declarations have C language linkage. This is a 8561 // redeclaration. 8562 Previous.clear(); 8563 Previous.addDecl(Prev); 8564 return true; 8565 } 8566 8567 // This is a global, non-extern "C" declaration, and there is a previous 8568 // non-global extern "C" declaration. Diagnose if this is a variable 8569 // declaration. 8570 if (!isa<VarDecl>(ND)) 8571 return false; 8572 } else { 8573 // The declaration is extern "C". Check for any declaration in the 8574 // translation unit which might conflict. 8575 if (IsGlobal) { 8576 // We have already performed the lookup into the translation unit. 8577 IsGlobal = false; 8578 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8579 I != E; ++I) { 8580 if (isa<VarDecl>(*I)) { 8581 Prev = *I; 8582 break; 8583 } 8584 } 8585 } else { 8586 DeclContext::lookup_result R = 8587 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 8588 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 8589 I != E; ++I) { 8590 if (isa<VarDecl>(*I)) { 8591 Prev = *I; 8592 break; 8593 } 8594 // FIXME: If we have any other entity with this name in global scope, 8595 // the declaration is ill-formed, but that is a defect: it breaks the 8596 // 'stat' hack, for instance. Only variables can have mangled name 8597 // clashes with extern "C" declarations, so only they deserve a 8598 // diagnostic. 8599 } 8600 } 8601 8602 if (!Prev) 8603 return false; 8604 } 8605 8606 // Use the first declaration's location to ensure we point at something which 8607 // is lexically inside an extern "C" linkage-spec. 8608 assert(Prev && "should have found a previous declaration to diagnose"); 8609 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 8610 Prev = FD->getFirstDecl(); 8611 else 8612 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 8613 8614 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 8615 << IsGlobal << ND; 8616 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 8617 << IsGlobal; 8618 return false; 8619 } 8620 8621 /// Apply special rules for handling extern "C" declarations. Returns \c true 8622 /// if we have found that this is a redeclaration of some prior entity. 8623 /// 8624 /// Per C++ [dcl.link]p6: 8625 /// Two declarations [for a function or variable] with C language linkage 8626 /// with the same name that appear in different scopes refer to the same 8627 /// [entity]. An entity with C language linkage shall not be declared with 8628 /// the same name as an entity in global scope. 8629 template<typename T> 8630 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 8631 LookupResult &Previous) { 8632 if (!S.getLangOpts().CPlusPlus) { 8633 // In C, when declaring a global variable, look for a corresponding 'extern' 8634 // variable declared in function scope. We don't need this in C++, because 8635 // we find local extern decls in the surrounding file-scope DeclContext. 8636 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8637 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 8638 Previous.clear(); 8639 Previous.addDecl(Prev); 8640 return true; 8641 } 8642 } 8643 return false; 8644 } 8645 8646 // A declaration in the translation unit can conflict with an extern "C" 8647 // declaration. 8648 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 8649 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 8650 8651 // An extern "C" declaration can conflict with a declaration in the 8652 // translation unit or can be a redeclaration of an extern "C" declaration 8653 // in another scope. 8654 if (isIncompleteDeclExternC(S,ND)) 8655 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 8656 8657 // Neither global nor extern "C": nothing to do. 8658 return false; 8659 } 8660 8661 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 8662 // If the decl is already known invalid, don't check it. 8663 if (NewVD->isInvalidDecl()) 8664 return; 8665 8666 QualType T = NewVD->getType(); 8667 8668 // Defer checking an 'auto' type until its initializer is attached. 8669 if (T->isUndeducedType()) 8670 return; 8671 8672 if (NewVD->hasAttrs()) 8673 CheckAlignasUnderalignment(NewVD); 8674 8675 if (T->isObjCObjectType()) { 8676 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 8677 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 8678 T = Context.getObjCObjectPointerType(T); 8679 NewVD->setType(T); 8680 } 8681 8682 // Emit an error if an address space was applied to decl with local storage. 8683 // This includes arrays of objects with address space qualifiers, but not 8684 // automatic variables that point to other address spaces. 8685 // ISO/IEC TR 18037 S5.1.2 8686 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 8687 T.getAddressSpace() != LangAS::Default) { 8688 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 8689 NewVD->setInvalidDecl(); 8690 return; 8691 } 8692 8693 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8694 // scope. 8695 if (getLangOpts().OpenCLVersion == 120 && 8696 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8697 getLangOpts()) && 8698 NewVD->isStaticLocal()) { 8699 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8700 NewVD->setInvalidDecl(); 8701 return; 8702 } 8703 8704 if (getLangOpts().OpenCL) { 8705 if (!diagnoseOpenCLTypes(*this, NewVD)) 8706 return; 8707 8708 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8709 if (NewVD->hasAttr<BlocksAttr>()) { 8710 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8711 return; 8712 } 8713 8714 if (T->isBlockPointerType()) { 8715 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8716 // can't use 'extern' storage class. 8717 if (!T.isConstQualified()) { 8718 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8719 << 0 /*const*/; 8720 NewVD->setInvalidDecl(); 8721 return; 8722 } 8723 if (NewVD->hasExternalStorage()) { 8724 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8725 NewVD->setInvalidDecl(); 8726 return; 8727 } 8728 } 8729 8730 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8731 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8732 NewVD->hasExternalStorage()) { 8733 if (!T->isSamplerT() && !T->isDependentType() && 8734 !(T.getAddressSpace() == LangAS::opencl_constant || 8735 (T.getAddressSpace() == LangAS::opencl_global && 8736 getOpenCLOptions().areProgramScopeVariablesSupported( 8737 getLangOpts())))) { 8738 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8739 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8740 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8741 << Scope << "global or constant"; 8742 else 8743 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8744 << Scope << "constant"; 8745 NewVD->setInvalidDecl(); 8746 return; 8747 } 8748 } else { 8749 if (T.getAddressSpace() == LangAS::opencl_global) { 8750 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8751 << 1 /*is any function*/ << "global"; 8752 NewVD->setInvalidDecl(); 8753 return; 8754 } 8755 if (T.getAddressSpace() == LangAS::opencl_constant || 8756 T.getAddressSpace() == LangAS::opencl_local) { 8757 FunctionDecl *FD = getCurFunctionDecl(); 8758 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8759 // in functions. 8760 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8761 if (T.getAddressSpace() == LangAS::opencl_constant) 8762 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8763 << 0 /*non-kernel only*/ << "constant"; 8764 else 8765 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8766 << 0 /*non-kernel only*/ << "local"; 8767 NewVD->setInvalidDecl(); 8768 return; 8769 } 8770 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8771 // in the outermost scope of a kernel function. 8772 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8773 if (!getCurScope()->isFunctionScope()) { 8774 if (T.getAddressSpace() == LangAS::opencl_constant) 8775 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8776 << "constant"; 8777 else 8778 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8779 << "local"; 8780 NewVD->setInvalidDecl(); 8781 return; 8782 } 8783 } 8784 } else if (T.getAddressSpace() != LangAS::opencl_private && 8785 // If we are parsing a template we didn't deduce an addr 8786 // space yet. 8787 T.getAddressSpace() != LangAS::Default) { 8788 // Do not allow other address spaces on automatic variable. 8789 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8790 NewVD->setInvalidDecl(); 8791 return; 8792 } 8793 } 8794 } 8795 8796 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8797 && !NewVD->hasAttr<BlocksAttr>()) { 8798 if (getLangOpts().getGC() != LangOptions::NonGC) 8799 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8800 else { 8801 assert(!getLangOpts().ObjCAutoRefCount); 8802 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8803 } 8804 } 8805 8806 // WebAssembly tables must be static with a zero length and can't be 8807 // declared within functions. 8808 if (T->isWebAssemblyTableType()) { 8809 if (getCurScope()->getParent()) { // Parent is null at top-level 8810 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function); 8811 NewVD->setInvalidDecl(); 8812 return; 8813 } 8814 if (NewVD->getStorageClass() != SC_Static) { 8815 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static); 8816 NewVD->setInvalidDecl(); 8817 return; 8818 } 8819 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr()); 8820 if (!ATy || ATy->getSize().getSExtValue() != 0) { 8821 Diag(NewVD->getLocation(), 8822 diag::err_typecheck_wasm_table_must_have_zero_length); 8823 NewVD->setInvalidDecl(); 8824 return; 8825 } 8826 } 8827 8828 bool isVM = T->isVariablyModifiedType(); 8829 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8830 NewVD->hasAttr<BlocksAttr>()) 8831 setFunctionHasBranchProtectedScope(); 8832 8833 if ((isVM && NewVD->hasLinkage()) || 8834 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8835 bool SizeIsNegative; 8836 llvm::APSInt Oversized; 8837 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8838 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8839 QualType FixedT; 8840 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8841 FixedT = FixedTInfo->getType(); 8842 else if (FixedTInfo) { 8843 // Type and type-as-written are canonically different. We need to fix up 8844 // both types separately. 8845 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8846 Oversized); 8847 } 8848 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8849 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8850 // FIXME: This won't give the correct result for 8851 // int a[10][n]; 8852 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8853 8854 if (NewVD->isFileVarDecl()) 8855 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8856 << SizeRange; 8857 else if (NewVD->isStaticLocal()) 8858 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8859 << SizeRange; 8860 else 8861 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8862 << SizeRange; 8863 NewVD->setInvalidDecl(); 8864 return; 8865 } 8866 8867 if (!FixedTInfo) { 8868 if (NewVD->isFileVarDecl()) 8869 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8870 else 8871 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8872 NewVD->setInvalidDecl(); 8873 return; 8874 } 8875 8876 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8877 NewVD->setType(FixedT); 8878 NewVD->setTypeSourceInfo(FixedTInfo); 8879 } 8880 8881 if (T->isVoidType()) { 8882 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8883 // of objects and functions. 8884 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8885 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8886 << T; 8887 NewVD->setInvalidDecl(); 8888 return; 8889 } 8890 } 8891 8892 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8893 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8894 NewVD->setInvalidDecl(); 8895 return; 8896 } 8897 8898 if (!NewVD->hasLocalStorage() && T->isSizelessType() && 8899 !T.isWebAssemblyReferenceType()) { 8900 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8901 NewVD->setInvalidDecl(); 8902 return; 8903 } 8904 8905 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8906 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8907 NewVD->setInvalidDecl(); 8908 return; 8909 } 8910 8911 if (NewVD->isConstexpr() && !T->isDependentType() && 8912 RequireLiteralType(NewVD->getLocation(), T, 8913 diag::err_constexpr_var_non_literal)) { 8914 NewVD->setInvalidDecl(); 8915 return; 8916 } 8917 8918 // PPC MMA non-pointer types are not allowed as non-local variable types. 8919 if (Context.getTargetInfo().getTriple().isPPC64() && 8920 !NewVD->isLocalVarDecl() && 8921 CheckPPCMMAType(T, NewVD->getLocation())) { 8922 NewVD->setInvalidDecl(); 8923 return; 8924 } 8925 8926 // Check that SVE types are only used in functions with SVE available. 8927 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) { 8928 const FunctionDecl *FD = cast<FunctionDecl>(CurContext); 8929 llvm::StringMap<bool> CallerFeatureMap; 8930 Context.getFunctionFeatureMap(CallerFeatureMap, FD); 8931 if (!Builtin::evaluateRequiredTargetFeatures( 8932 "sve", CallerFeatureMap)) { 8933 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T; 8934 NewVD->setInvalidDecl(); 8935 return; 8936 } 8937 } 8938 8939 if (T->isRVVSizelessBuiltinType()) 8940 checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext)); 8941 } 8942 8943 /// Perform semantic checking on a newly-created variable 8944 /// declaration. 8945 /// 8946 /// This routine performs all of the type-checking required for a 8947 /// variable declaration once it has been built. It is used both to 8948 /// check variables after they have been parsed and their declarators 8949 /// have been translated into a declaration, and to check variables 8950 /// that have been instantiated from a template. 8951 /// 8952 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8953 /// 8954 /// Returns true if the variable declaration is a redeclaration. 8955 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8956 CheckVariableDeclarationType(NewVD); 8957 8958 // If the decl is already known invalid, don't check it. 8959 if (NewVD->isInvalidDecl()) 8960 return false; 8961 8962 // If we did not find anything by this name, look for a non-visible 8963 // extern "C" declaration with the same name. 8964 if (Previous.empty() && 8965 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8966 Previous.setShadowed(); 8967 8968 if (!Previous.empty()) { 8969 MergeVarDecl(NewVD, Previous); 8970 return true; 8971 } 8972 return false; 8973 } 8974 8975 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8976 /// and if so, check that it's a valid override and remember it. 8977 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8978 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8979 8980 // Look for methods in base classes that this method might override. 8981 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8982 /*DetectVirtual=*/false); 8983 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8984 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8985 DeclarationName Name = MD->getDeclName(); 8986 8987 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8988 // We really want to find the base class destructor here. 8989 QualType T = Context.getTypeDeclType(BaseRecord); 8990 CanQualType CT = Context.getCanonicalType(T); 8991 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8992 } 8993 8994 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8995 CXXMethodDecl *BaseMD = 8996 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8997 if (!BaseMD || !BaseMD->isVirtual() || 8998 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8999 /*ConsiderCudaAttrs=*/true)) 9000 continue; 9001 if (!CheckExplicitObjectOverride(MD, BaseMD)) 9002 continue; 9003 if (Overridden.insert(BaseMD).second) { 9004 MD->addOverriddenMethod(BaseMD); 9005 CheckOverridingFunctionReturnType(MD, BaseMD); 9006 CheckOverridingFunctionAttributes(MD, BaseMD); 9007 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 9008 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 9009 } 9010 9011 // A method can only override one function from each base class. We 9012 // don't track indirectly overridden methods from bases of bases. 9013 return true; 9014 } 9015 9016 return false; 9017 }; 9018 9019 DC->lookupInBases(VisitBase, Paths); 9020 return !Overridden.empty(); 9021 } 9022 9023 namespace { 9024 // Struct for holding all of the extra arguments needed by 9025 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 9026 struct ActOnFDArgs { 9027 Scope *S; 9028 Declarator &D; 9029 MultiTemplateParamsArg TemplateParamLists; 9030 bool AddToScope; 9031 }; 9032 } // end anonymous namespace 9033 9034 namespace { 9035 9036 // Callback to only accept typo corrections that have a non-zero edit distance. 9037 // Also only accept corrections that have the same parent decl. 9038 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 9039 public: 9040 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 9041 CXXRecordDecl *Parent) 9042 : Context(Context), OriginalFD(TypoFD), 9043 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 9044 9045 bool ValidateCandidate(const TypoCorrection &candidate) override { 9046 if (candidate.getEditDistance() == 0) 9047 return false; 9048 9049 SmallVector<unsigned, 1> MismatchedParams; 9050 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 9051 CDeclEnd = candidate.end(); 9052 CDecl != CDeclEnd; ++CDecl) { 9053 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 9054 9055 if (FD && !FD->hasBody() && 9056 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 9057 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 9058 CXXRecordDecl *Parent = MD->getParent(); 9059 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 9060 return true; 9061 } else if (!ExpectedParent) { 9062 return true; 9063 } 9064 } 9065 } 9066 9067 return false; 9068 } 9069 9070 std::unique_ptr<CorrectionCandidateCallback> clone() override { 9071 return std::make_unique<DifferentNameValidatorCCC>(*this); 9072 } 9073 9074 private: 9075 ASTContext &Context; 9076 FunctionDecl *OriginalFD; 9077 CXXRecordDecl *ExpectedParent; 9078 }; 9079 9080 } // end anonymous namespace 9081 9082 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 9083 TypoCorrectedFunctionDefinitions.insert(F); 9084 } 9085 9086 /// Generate diagnostics for an invalid function redeclaration. 9087 /// 9088 /// This routine handles generating the diagnostic messages for an invalid 9089 /// function redeclaration, including finding possible similar declarations 9090 /// or performing typo correction if there are no previous declarations with 9091 /// the same name. 9092 /// 9093 /// Returns a NamedDecl iff typo correction was performed and substituting in 9094 /// the new declaration name does not cause new errors. 9095 static NamedDecl *DiagnoseInvalidRedeclaration( 9096 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 9097 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 9098 DeclarationName Name = NewFD->getDeclName(); 9099 DeclContext *NewDC = NewFD->getDeclContext(); 9100 SmallVector<unsigned, 1> MismatchedParams; 9101 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 9102 TypoCorrection Correction; 9103 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 9104 unsigned DiagMsg = 9105 IsLocalFriend ? diag::err_no_matching_local_friend : 9106 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 9107 diag::err_member_decl_does_not_match; 9108 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 9109 IsLocalFriend ? Sema::LookupLocalFriendName 9110 : Sema::LookupOrdinaryName, 9111 Sema::ForVisibleRedeclaration); 9112 9113 NewFD->setInvalidDecl(); 9114 if (IsLocalFriend) 9115 SemaRef.LookupName(Prev, S); 9116 else 9117 SemaRef.LookupQualifiedName(Prev, NewDC); 9118 assert(!Prev.isAmbiguous() && 9119 "Cannot have an ambiguity in previous-declaration lookup"); 9120 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9121 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 9122 MD ? MD->getParent() : nullptr); 9123 if (!Prev.empty()) { 9124 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 9125 Func != FuncEnd; ++Func) { 9126 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 9127 if (FD && 9128 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 9129 // Add 1 to the index so that 0 can mean the mismatch didn't 9130 // involve a parameter 9131 unsigned ParamNum = 9132 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 9133 NearMatches.push_back(std::make_pair(FD, ParamNum)); 9134 } 9135 } 9136 // If the qualified name lookup yielded nothing, try typo correction 9137 } else if ((Correction = SemaRef.CorrectTypo( 9138 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 9139 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 9140 IsLocalFriend ? nullptr : NewDC))) { 9141 // Set up everything for the call to ActOnFunctionDeclarator 9142 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 9143 ExtraArgs.D.getIdentifierLoc()); 9144 Previous.clear(); 9145 Previous.setLookupName(Correction.getCorrection()); 9146 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 9147 CDeclEnd = Correction.end(); 9148 CDecl != CDeclEnd; ++CDecl) { 9149 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 9150 if (FD && !FD->hasBody() && 9151 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 9152 Previous.addDecl(FD); 9153 } 9154 } 9155 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 9156 9157 NamedDecl *Result; 9158 // Retry building the function declaration with the new previous 9159 // declarations, and with errors suppressed. 9160 { 9161 // Trap errors. 9162 Sema::SFINAETrap Trap(SemaRef); 9163 9164 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 9165 // pieces need to verify the typo-corrected C++ declaration and hopefully 9166 // eliminate the need for the parameter pack ExtraArgs. 9167 Result = SemaRef.ActOnFunctionDeclarator( 9168 ExtraArgs.S, ExtraArgs.D, 9169 Correction.getCorrectionDecl()->getDeclContext(), 9170 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 9171 ExtraArgs.AddToScope); 9172 9173 if (Trap.hasErrorOccurred()) 9174 Result = nullptr; 9175 } 9176 9177 if (Result) { 9178 // Determine which correction we picked. 9179 Decl *Canonical = Result->getCanonicalDecl(); 9180 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9181 I != E; ++I) 9182 if ((*I)->getCanonicalDecl() == Canonical) 9183 Correction.setCorrectionDecl(*I); 9184 9185 // Let Sema know about the correction. 9186 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 9187 SemaRef.diagnoseTypo( 9188 Correction, 9189 SemaRef.PDiag(IsLocalFriend 9190 ? diag::err_no_matching_local_friend_suggest 9191 : diag::err_member_decl_does_not_match_suggest) 9192 << Name << NewDC << IsDefinition); 9193 return Result; 9194 } 9195 9196 // Pretend the typo correction never occurred 9197 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 9198 ExtraArgs.D.getIdentifierLoc()); 9199 ExtraArgs.D.setRedeclaration(wasRedeclaration); 9200 Previous.clear(); 9201 Previous.setLookupName(Name); 9202 } 9203 9204 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 9205 << Name << NewDC << IsDefinition << NewFD->getLocation(); 9206 9207 bool NewFDisConst = false; 9208 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 9209 NewFDisConst = NewMD->isConst(); 9210 9211 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 9212 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 9213 NearMatch != NearMatchEnd; ++NearMatch) { 9214 FunctionDecl *FD = NearMatch->first; 9215 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 9216 bool FDisConst = MD && MD->isConst(); 9217 bool IsMember = MD || !IsLocalFriend; 9218 9219 // FIXME: These notes are poorly worded for the local friend case. 9220 if (unsigned Idx = NearMatch->second) { 9221 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 9222 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 9223 if (Loc.isInvalid()) Loc = FD->getLocation(); 9224 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 9225 : diag::note_local_decl_close_param_match) 9226 << Idx << FDParam->getType() 9227 << NewFD->getParamDecl(Idx - 1)->getType(); 9228 } else if (FDisConst != NewFDisConst) { 9229 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 9230 << NewFDisConst << FD->getSourceRange().getEnd() 9231 << (NewFDisConst 9232 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo() 9233 .getConstQualifierLoc()) 9234 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo() 9235 .getRParenLoc() 9236 .getLocWithOffset(1), 9237 " const")); 9238 } else 9239 SemaRef.Diag(FD->getLocation(), 9240 IsMember ? diag::note_member_def_close_match 9241 : diag::note_local_decl_close_match); 9242 } 9243 return nullptr; 9244 } 9245 9246 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 9247 switch (D.getDeclSpec().getStorageClassSpec()) { 9248 default: llvm_unreachable("Unknown storage class!"); 9249 case DeclSpec::SCS_auto: 9250 case DeclSpec::SCS_register: 9251 case DeclSpec::SCS_mutable: 9252 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9253 diag::err_typecheck_sclass_func); 9254 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9255 D.setInvalidType(); 9256 break; 9257 case DeclSpec::SCS_unspecified: break; 9258 case DeclSpec::SCS_extern: 9259 if (D.getDeclSpec().isExternInLinkageSpec()) 9260 return SC_None; 9261 return SC_Extern; 9262 case DeclSpec::SCS_static: { 9263 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 9264 // C99 6.7.1p5: 9265 // The declaration of an identifier for a function that has 9266 // block scope shall have no explicit storage-class specifier 9267 // other than extern 9268 // See also (C++ [dcl.stc]p4). 9269 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9270 diag::err_static_block_func); 9271 break; 9272 } else 9273 return SC_Static; 9274 } 9275 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 9276 } 9277 9278 // No explicit storage class has already been returned 9279 return SC_None; 9280 } 9281 9282 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 9283 DeclContext *DC, QualType &R, 9284 TypeSourceInfo *TInfo, 9285 StorageClass SC, 9286 bool &IsVirtualOkay) { 9287 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 9288 DeclarationName Name = NameInfo.getName(); 9289 9290 FunctionDecl *NewFD = nullptr; 9291 bool isInline = D.getDeclSpec().isInlineSpecified(); 9292 9293 if (!SemaRef.getLangOpts().CPlusPlus) { 9294 // Determine whether the function was written with a prototype. This is 9295 // true when: 9296 // - there is a prototype in the declarator, or 9297 // - the type R of the function is some kind of typedef or other non- 9298 // attributed reference to a type name (which eventually refers to a 9299 // function type). Note, we can't always look at the adjusted type to 9300 // check this case because attributes may cause a non-function 9301 // declarator to still have a function type. e.g., 9302 // typedef void func(int a); 9303 // __attribute__((noreturn)) func other_func; // This has a prototype 9304 bool HasPrototype = 9305 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 9306 (D.getDeclSpec().isTypeRep() && 9307 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr) 9308 ->isFunctionProtoType()) || 9309 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 9310 assert( 9311 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) && 9312 "Strict prototypes are required"); 9313 9314 NewFD = FunctionDecl::Create( 9315 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 9316 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 9317 ConstexprSpecKind::Unspecified, 9318 /*TrailingRequiresClause=*/nullptr); 9319 if (D.isInvalidType()) 9320 NewFD->setInvalidDecl(); 9321 9322 return NewFD; 9323 } 9324 9325 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 9326 9327 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9328 if (ConstexprKind == ConstexprSpecKind::Constinit) { 9329 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 9330 diag::err_constexpr_wrong_decl_kind) 9331 << static_cast<int>(ConstexprKind); 9332 ConstexprKind = ConstexprSpecKind::Unspecified; 9333 D.getMutableDeclSpec().ClearConstexprSpec(); 9334 } 9335 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 9336 9337 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R); 9338 9339 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 9340 // This is a C++ constructor declaration. 9341 assert(DC->isRecord() && 9342 "Constructors can only be declared in a member context"); 9343 9344 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 9345 return CXXConstructorDecl::Create( 9346 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 9347 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 9348 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 9349 InheritedConstructor(), TrailingRequiresClause); 9350 9351 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9352 // This is a C++ destructor declaration. 9353 if (DC->isRecord()) { 9354 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 9355 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 9356 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 9357 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 9358 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9359 /*isImplicitlyDeclared=*/false, ConstexprKind, 9360 TrailingRequiresClause); 9361 // User defined destructors start as not selected if the class definition is still 9362 // not done. 9363 if (Record->isBeingDefined()) 9364 NewDD->setIneligibleOrNotSelected(true); 9365 9366 // If the destructor needs an implicit exception specification, set it 9367 // now. FIXME: It'd be nice to be able to create the right type to start 9368 // with, but the type needs to reference the destructor declaration. 9369 if (SemaRef.getLangOpts().CPlusPlus11) 9370 SemaRef.AdjustDestructorExceptionSpec(NewDD); 9371 9372 IsVirtualOkay = true; 9373 return NewDD; 9374 9375 } else { 9376 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 9377 D.setInvalidType(); 9378 9379 // Create a FunctionDecl to satisfy the function definition parsing 9380 // code path. 9381 return FunctionDecl::Create( 9382 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 9383 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9384 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 9385 } 9386 9387 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 9388 if (!DC->isRecord()) { 9389 SemaRef.Diag(D.getIdentifierLoc(), 9390 diag::err_conv_function_not_member); 9391 return nullptr; 9392 } 9393 9394 SemaRef.CheckConversionDeclarator(D, R, SC); 9395 if (D.isInvalidType()) 9396 return nullptr; 9397 9398 IsVirtualOkay = true; 9399 return CXXConversionDecl::Create( 9400 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 9401 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9402 ExplicitSpecifier, ConstexprKind, SourceLocation(), 9403 TrailingRequiresClause); 9404 9405 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 9406 if (TrailingRequiresClause) 9407 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 9408 diag::err_trailing_requires_clause_on_deduction_guide) 9409 << TrailingRequiresClause->getSourceRange(); 9410 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC)) 9411 return nullptr; 9412 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 9413 ExplicitSpecifier, NameInfo, R, TInfo, 9414 D.getEndLoc()); 9415 } else if (DC->isRecord()) { 9416 // If the name of the function is the same as the name of the record, 9417 // then this must be an invalid constructor that has a return type. 9418 // (The parser checks for a return type and makes the declarator a 9419 // constructor if it has no return type). 9420 if (Name.getAsIdentifierInfo() && 9421 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 9422 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 9423 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 9424 << SourceRange(D.getIdentifierLoc()); 9425 return nullptr; 9426 } 9427 9428 // This is a C++ method declaration. 9429 CXXMethodDecl *Ret = CXXMethodDecl::Create( 9430 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 9431 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9432 ConstexprKind, SourceLocation(), TrailingRequiresClause); 9433 IsVirtualOkay = !Ret->isStatic(); 9434 return Ret; 9435 } else { 9436 bool isFriend = 9437 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 9438 if (!isFriend && SemaRef.CurContext->isRecord()) 9439 return nullptr; 9440 9441 // Determine whether the function was written with a 9442 // prototype. This true when: 9443 // - we're in C++ (where every function has a prototype), 9444 return FunctionDecl::Create( 9445 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 9446 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9447 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 9448 } 9449 } 9450 9451 enum OpenCLParamType { 9452 ValidKernelParam, 9453 PtrPtrKernelParam, 9454 PtrKernelParam, 9455 InvalidAddrSpacePtrKernelParam, 9456 InvalidKernelParam, 9457 RecordKernelParam 9458 }; 9459 9460 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 9461 // Size dependent types are just typedefs to normal integer types 9462 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 9463 // integers other than by their names. 9464 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 9465 9466 // Remove typedefs one by one until we reach a typedef 9467 // for a size dependent type. 9468 QualType DesugaredTy = Ty; 9469 do { 9470 ArrayRef<StringRef> Names(SizeTypeNames); 9471 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 9472 if (Names.end() != Match) 9473 return true; 9474 9475 Ty = DesugaredTy; 9476 DesugaredTy = Ty.getSingleStepDesugaredType(C); 9477 } while (DesugaredTy != Ty); 9478 9479 return false; 9480 } 9481 9482 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 9483 if (PT->isDependentType()) 9484 return InvalidKernelParam; 9485 9486 if (PT->isPointerType() || PT->isReferenceType()) { 9487 QualType PointeeType = PT->getPointeeType(); 9488 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 9489 PointeeType.getAddressSpace() == LangAS::opencl_private || 9490 PointeeType.getAddressSpace() == LangAS::Default) 9491 return InvalidAddrSpacePtrKernelParam; 9492 9493 if (PointeeType->isPointerType()) { 9494 // This is a pointer to pointer parameter. 9495 // Recursively check inner type. 9496 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 9497 if (ParamKind == InvalidAddrSpacePtrKernelParam || 9498 ParamKind == InvalidKernelParam) 9499 return ParamKind; 9500 9501 // OpenCL v3.0 s6.11.a: 9502 // A restriction to pass pointers to pointers only applies to OpenCL C 9503 // v1.2 or below. 9504 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120) 9505 return ValidKernelParam; 9506 9507 return PtrPtrKernelParam; 9508 } 9509 9510 // C++ for OpenCL v1.0 s2.4: 9511 // Moreover the types used in parameters of the kernel functions must be: 9512 // Standard layout types for pointer parameters. The same applies to 9513 // reference if an implementation supports them in kernel parameters. 9514 if (S.getLangOpts().OpenCLCPlusPlus && 9515 !S.getOpenCLOptions().isAvailableOption( 9516 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) { 9517 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl(); 9518 bool IsStandardLayoutType = true; 9519 if (CXXRec) { 9520 // If template type is not ODR-used its definition is only available 9521 // in the template definition not its instantiation. 9522 // FIXME: This logic doesn't work for types that depend on template 9523 // parameter (PR58590). 9524 if (!CXXRec->hasDefinition()) 9525 CXXRec = CXXRec->getTemplateInstantiationPattern(); 9526 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout()) 9527 IsStandardLayoutType = false; 9528 } 9529 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() && 9530 !IsStandardLayoutType) 9531 return InvalidKernelParam; 9532 } 9533 9534 // OpenCL v1.2 s6.9.p: 9535 // A restriction to pass pointers only applies to OpenCL C v1.2 or below. 9536 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120) 9537 return ValidKernelParam; 9538 9539 return PtrKernelParam; 9540 } 9541 9542 // OpenCL v1.2 s6.9.k: 9543 // Arguments to kernel functions in a program cannot be declared with the 9544 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9545 // uintptr_t or a struct and/or union that contain fields declared to be one 9546 // of these built-in scalar types. 9547 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 9548 return InvalidKernelParam; 9549 9550 if (PT->isImageType()) 9551 return PtrKernelParam; 9552 9553 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 9554 return InvalidKernelParam; 9555 9556 // OpenCL extension spec v1.2 s9.5: 9557 // This extension adds support for half scalar and vector types as built-in 9558 // types that can be used for arithmetic operations, conversions etc. 9559 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 9560 PT->isHalfType()) 9561 return InvalidKernelParam; 9562 9563 // Look into an array argument to check if it has a forbidden type. 9564 if (PT->isArrayType()) { 9565 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 9566 // Call ourself to check an underlying type of an array. Since the 9567 // getPointeeOrArrayElementType returns an innermost type which is not an 9568 // array, this recursive call only happens once. 9569 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 9570 } 9571 9572 // C++ for OpenCL v1.0 s2.4: 9573 // Moreover the types used in parameters of the kernel functions must be: 9574 // Trivial and standard-layout types C++17 [basic.types] (plain old data 9575 // types) for parameters passed by value; 9576 if (S.getLangOpts().OpenCLCPlusPlus && 9577 !S.getOpenCLOptions().isAvailableOption( 9578 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 9579 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 9580 return InvalidKernelParam; 9581 9582 if (PT->isRecordType()) 9583 return RecordKernelParam; 9584 9585 return ValidKernelParam; 9586 } 9587 9588 static void checkIsValidOpenCLKernelParameter( 9589 Sema &S, 9590 Declarator &D, 9591 ParmVarDecl *Param, 9592 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 9593 QualType PT = Param->getType(); 9594 9595 // Cache the valid types we encounter to avoid rechecking structs that are 9596 // used again 9597 if (ValidTypes.count(PT.getTypePtr())) 9598 return; 9599 9600 switch (getOpenCLKernelParameterType(S, PT)) { 9601 case PtrPtrKernelParam: 9602 // OpenCL v3.0 s6.11.a: 9603 // A kernel function argument cannot be declared as a pointer to a pointer 9604 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 9605 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 9606 D.setInvalidType(); 9607 return; 9608 9609 case InvalidAddrSpacePtrKernelParam: 9610 // OpenCL v1.0 s6.5: 9611 // __kernel function arguments declared to be a pointer of a type can point 9612 // to one of the following address spaces only : __global, __local or 9613 // __constant. 9614 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 9615 D.setInvalidType(); 9616 return; 9617 9618 // OpenCL v1.2 s6.9.k: 9619 // Arguments to kernel functions in a program cannot be declared with the 9620 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9621 // uintptr_t or a struct and/or union that contain fields declared to be 9622 // one of these built-in scalar types. 9623 9624 case InvalidKernelParam: 9625 // OpenCL v1.2 s6.8 n: 9626 // A kernel function argument cannot be declared 9627 // of event_t type. 9628 // Do not diagnose half type since it is diagnosed as invalid argument 9629 // type for any function elsewhere. 9630 if (!PT->isHalfType()) { 9631 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9632 9633 // Explain what typedefs are involved. 9634 const TypedefType *Typedef = nullptr; 9635 while ((Typedef = PT->getAs<TypedefType>())) { 9636 SourceLocation Loc = Typedef->getDecl()->getLocation(); 9637 // SourceLocation may be invalid for a built-in type. 9638 if (Loc.isValid()) 9639 S.Diag(Loc, diag::note_entity_declared_at) << PT; 9640 PT = Typedef->desugar(); 9641 } 9642 } 9643 9644 D.setInvalidType(); 9645 return; 9646 9647 case PtrKernelParam: 9648 case ValidKernelParam: 9649 ValidTypes.insert(PT.getTypePtr()); 9650 return; 9651 9652 case RecordKernelParam: 9653 break; 9654 } 9655 9656 // Track nested structs we will inspect 9657 SmallVector<const Decl *, 4> VisitStack; 9658 9659 // Track where we are in the nested structs. Items will migrate from 9660 // VisitStack to HistoryStack as we do the DFS for bad field. 9661 SmallVector<const FieldDecl *, 4> HistoryStack; 9662 HistoryStack.push_back(nullptr); 9663 9664 // At this point we already handled everything except of a RecordType or 9665 // an ArrayType of a RecordType. 9666 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 9667 const RecordType *RecTy = 9668 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 9669 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 9670 9671 VisitStack.push_back(RecTy->getDecl()); 9672 assert(VisitStack.back() && "First decl null?"); 9673 9674 do { 9675 const Decl *Next = VisitStack.pop_back_val(); 9676 if (!Next) { 9677 assert(!HistoryStack.empty()); 9678 // Found a marker, we have gone up a level 9679 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 9680 ValidTypes.insert(Hist->getType().getTypePtr()); 9681 9682 continue; 9683 } 9684 9685 // Adds everything except the original parameter declaration (which is not a 9686 // field itself) to the history stack. 9687 const RecordDecl *RD; 9688 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 9689 HistoryStack.push_back(Field); 9690 9691 QualType FieldTy = Field->getType(); 9692 // Other field types (known to be valid or invalid) are handled while we 9693 // walk around RecordDecl::fields(). 9694 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 9695 "Unexpected type."); 9696 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 9697 9698 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 9699 } else { 9700 RD = cast<RecordDecl>(Next); 9701 } 9702 9703 // Add a null marker so we know when we've gone back up a level 9704 VisitStack.push_back(nullptr); 9705 9706 for (const auto *FD : RD->fields()) { 9707 QualType QT = FD->getType(); 9708 9709 if (ValidTypes.count(QT.getTypePtr())) 9710 continue; 9711 9712 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 9713 if (ParamType == ValidKernelParam) 9714 continue; 9715 9716 if (ParamType == RecordKernelParam) { 9717 VisitStack.push_back(FD); 9718 continue; 9719 } 9720 9721 // OpenCL v1.2 s6.9.p: 9722 // Arguments to kernel functions that are declared to be a struct or union 9723 // do not allow OpenCL objects to be passed as elements of the struct or 9724 // union. This restriction was lifted in OpenCL v2.0 with the introduction 9725 // of SVM. 9726 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 9727 ParamType == InvalidAddrSpacePtrKernelParam) { 9728 S.Diag(Param->getLocation(), 9729 diag::err_record_with_pointers_kernel_param) 9730 << PT->isUnionType() 9731 << PT; 9732 } else { 9733 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9734 } 9735 9736 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 9737 << OrigRecDecl->getDeclName(); 9738 9739 // We have an error, now let's go back up through history and show where 9740 // the offending field came from 9741 for (ArrayRef<const FieldDecl *>::const_iterator 9742 I = HistoryStack.begin() + 1, 9743 E = HistoryStack.end(); 9744 I != E; ++I) { 9745 const FieldDecl *OuterField = *I; 9746 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 9747 << OuterField->getType(); 9748 } 9749 9750 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 9751 << QT->isPointerType() 9752 << QT; 9753 D.setInvalidType(); 9754 return; 9755 } 9756 } while (!VisitStack.empty()); 9757 } 9758 9759 /// Find the DeclContext in which a tag is implicitly declared if we see an 9760 /// elaborated type specifier in the specified context, and lookup finds 9761 /// nothing. 9762 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9763 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9764 DC = DC->getParent(); 9765 return DC; 9766 } 9767 9768 /// Find the Scope in which a tag is implicitly declared if we see an 9769 /// elaborated type specifier in the specified context, and lookup finds 9770 /// nothing. 9771 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9772 while (S->isClassScope() || 9773 (LangOpts.CPlusPlus && 9774 S->isFunctionPrototypeScope()) || 9775 ((S->getFlags() & Scope::DeclScope) == 0) || 9776 (S->getEntity() && S->getEntity()->isTransparentContext())) 9777 S = S->getParent(); 9778 return S; 9779 } 9780 9781 /// Determine whether a declaration matches a known function in namespace std. 9782 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, 9783 unsigned BuiltinID) { 9784 switch (BuiltinID) { 9785 case Builtin::BI__GetExceptionInfo: 9786 // No type checking whatsoever. 9787 return Ctx.getTargetInfo().getCXXABI().isMicrosoft(); 9788 9789 case Builtin::BIaddressof: 9790 case Builtin::BI__addressof: 9791 case Builtin::BIforward: 9792 case Builtin::BIforward_like: 9793 case Builtin::BImove: 9794 case Builtin::BImove_if_noexcept: 9795 case Builtin::BIas_const: { 9796 // Ensure that we don't treat the algorithm 9797 // OutputIt std::move(InputIt, InputIt, OutputIt) 9798 // as the builtin std::move. 9799 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 9800 return FPT->getNumParams() == 1 && !FPT->isVariadic(); 9801 } 9802 9803 default: 9804 return false; 9805 } 9806 } 9807 9808 NamedDecl* 9809 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9810 TypeSourceInfo *TInfo, LookupResult &Previous, 9811 MultiTemplateParamsArg TemplateParamListsRef, 9812 bool &AddToScope) { 9813 QualType R = TInfo->getType(); 9814 9815 assert(R->isFunctionType()); 9816 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9817 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9818 9819 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9820 llvm::append_range(TemplateParamLists, TemplateParamListsRef); 9821 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9822 if (!TemplateParamLists.empty() && 9823 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9824 TemplateParamLists.back() = Invented; 9825 else 9826 TemplateParamLists.push_back(Invented); 9827 } 9828 9829 // TODO: consider using NameInfo for diagnostic. 9830 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9831 DeclarationName Name = NameInfo.getName(); 9832 StorageClass SC = getFunctionStorageClass(*this, D); 9833 9834 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9835 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9836 diag::err_invalid_thread) 9837 << DeclSpec::getSpecifierName(TSCS); 9838 9839 if (D.isFirstDeclarationOfMember()) 9840 adjustMemberFunctionCC( 9841 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()), 9842 D.isCtorOrDtor(), D.getIdentifierLoc()); 9843 9844 bool isFriend = false; 9845 FunctionTemplateDecl *FunctionTemplate = nullptr; 9846 bool isMemberSpecialization = false; 9847 bool isFunctionTemplateSpecialization = false; 9848 9849 bool HasExplicitTemplateArgs = false; 9850 TemplateArgumentListInfo TemplateArgs; 9851 9852 bool isVirtualOkay = false; 9853 9854 DeclContext *OriginalDC = DC; 9855 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9856 9857 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9858 isVirtualOkay); 9859 if (!NewFD) return nullptr; 9860 9861 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9862 NewFD->setTopLevelDeclInObjCContainer(); 9863 9864 // Set the lexical context. If this is a function-scope declaration, or has a 9865 // C++ scope specifier, or is the object of a friend declaration, the lexical 9866 // context will be different from the semantic context. 9867 NewFD->setLexicalDeclContext(CurContext); 9868 9869 if (IsLocalExternDecl) 9870 NewFD->setLocalExternDecl(); 9871 9872 if (getLangOpts().CPlusPlus) { 9873 // The rules for implicit inlines changed in C++20 for methods and friends 9874 // with an in-class definition (when such a definition is not attached to 9875 // the global module). User-specified 'inline' overrides this (set when 9876 // the function decl is created above). 9877 // FIXME: We need a better way to separate C++ standard and clang modules. 9878 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules || 9879 !NewFD->getOwningModule() || 9880 NewFD->getOwningModule()->isGlobalModule() || 9881 NewFD->getOwningModule()->isHeaderLikeModule(); 9882 bool isInline = D.getDeclSpec().isInlineSpecified(); 9883 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9884 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9885 isFriend = D.getDeclSpec().isFriendSpecified(); 9886 if (isFriend && !isInline && D.isFunctionDefinition()) { 9887 // Pre-C++20 [class.friend]p5 9888 // A function can be defined in a friend declaration of a 9889 // class . . . . Such a function is implicitly inline. 9890 // Post C++20 [class.friend]p7 9891 // Such a function is implicitly an inline function if it is attached 9892 // to the global module. 9893 NewFD->setImplicitlyInline(ImplicitInlineCXX20); 9894 } 9895 9896 // If this is a method defined in an __interface, and is not a constructor 9897 // or an overloaded operator, then set the pure flag (isVirtual will already 9898 // return true). 9899 if (const CXXRecordDecl *Parent = 9900 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9901 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9902 NewFD->setIsPureVirtual(true); 9903 9904 // C++ [class.union]p2 9905 // A union can have member functions, but not virtual functions. 9906 if (isVirtual && Parent->isUnion()) { 9907 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9908 NewFD->setInvalidDecl(); 9909 } 9910 if ((Parent->isClass() || Parent->isStruct()) && 9911 Parent->hasAttr<SYCLSpecialClassAttr>() && 9912 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() && 9913 NewFD->getName() == "__init" && D.isFunctionDefinition()) { 9914 if (auto *Def = Parent->getDefinition()) 9915 Def->setInitMethod(true); 9916 } 9917 } 9918 9919 SetNestedNameSpecifier(*this, NewFD, D); 9920 isMemberSpecialization = false; 9921 isFunctionTemplateSpecialization = false; 9922 if (D.isInvalidType()) 9923 NewFD->setInvalidDecl(); 9924 9925 // Match up the template parameter lists with the scope specifier, then 9926 // determine whether we have a template or a template specialization. 9927 bool Invalid = false; 9928 TemplateIdAnnotation *TemplateId = 9929 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9930 ? D.getName().TemplateId 9931 : nullptr; 9932 TemplateParameterList *TemplateParams = 9933 MatchTemplateParametersToScopeSpecifier( 9934 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9935 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend, 9936 isMemberSpecialization, Invalid); 9937 if (TemplateParams) { 9938 // Check that we can declare a template here. 9939 if (CheckTemplateDeclScope(S, TemplateParams)) 9940 NewFD->setInvalidDecl(); 9941 9942 if (TemplateParams->size() > 0) { 9943 // This is a function template 9944 9945 // A destructor cannot be a template. 9946 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9947 Diag(NewFD->getLocation(), diag::err_destructor_template); 9948 NewFD->setInvalidDecl(); 9949 // Function template with explicit template arguments. 9950 } else if (TemplateId) { 9951 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9952 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9953 NewFD->setInvalidDecl(); 9954 } 9955 9956 // If we're adding a template to a dependent context, we may need to 9957 // rebuilding some of the types used within the template parameter list, 9958 // now that we know what the current instantiation is. 9959 if (DC->isDependentContext()) { 9960 ContextRAII SavedContext(*this, DC); 9961 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9962 Invalid = true; 9963 } 9964 9965 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9966 NewFD->getLocation(), 9967 Name, TemplateParams, 9968 NewFD); 9969 FunctionTemplate->setLexicalDeclContext(CurContext); 9970 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9971 9972 // For source fidelity, store the other template param lists. 9973 if (TemplateParamLists.size() > 1) { 9974 NewFD->setTemplateParameterListsInfo(Context, 9975 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9976 .drop_back(1)); 9977 } 9978 } else { 9979 // This is a function template specialization. 9980 isFunctionTemplateSpecialization = true; 9981 // For source fidelity, store all the template param lists. 9982 if (TemplateParamLists.size() > 0) 9983 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9984 9985 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9986 if (isFriend) { 9987 // We want to remove the "template<>", found here. 9988 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9989 9990 // If we remove the template<> and the name is not a 9991 // template-id, we're actually silently creating a problem: 9992 // the friend declaration will refer to an untemplated decl, 9993 // and clearly the user wants a template specialization. So 9994 // we need to insert '<>' after the name. 9995 SourceLocation InsertLoc; 9996 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9997 InsertLoc = D.getName().getSourceRange().getEnd(); 9998 InsertLoc = getLocForEndOfToken(InsertLoc); 9999 } 10000 10001 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 10002 << Name << RemoveRange 10003 << FixItHint::CreateRemoval(RemoveRange) 10004 << FixItHint::CreateInsertion(InsertLoc, "<>"); 10005 Invalid = true; 10006 10007 // Recover by faking up an empty template argument list. 10008 HasExplicitTemplateArgs = true; 10009 TemplateArgs.setLAngleLoc(InsertLoc); 10010 TemplateArgs.setRAngleLoc(InsertLoc); 10011 } 10012 } 10013 } else { 10014 // Check that we can declare a template here. 10015 if (!TemplateParamLists.empty() && isMemberSpecialization && 10016 CheckTemplateDeclScope(S, TemplateParamLists.back())) 10017 NewFD->setInvalidDecl(); 10018 10019 // All template param lists were matched against the scope specifier: 10020 // this is NOT (an explicit specialization of) a template. 10021 if (TemplateParamLists.size() > 0) 10022 // For source fidelity, store all the template param lists. 10023 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 10024 10025 // "friend void foo<>(int);" is an implicit specialization decl. 10026 if (isFriend && TemplateId) 10027 isFunctionTemplateSpecialization = true; 10028 } 10029 10030 // If this is a function template specialization and the unqualified-id of 10031 // the declarator-id is a template-id, convert the template argument list 10032 // into our AST format and check for unexpanded packs. 10033 if (isFunctionTemplateSpecialization && TemplateId) { 10034 HasExplicitTemplateArgs = true; 10035 10036 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 10037 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 10038 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 10039 TemplateId->NumArgs); 10040 translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 10041 10042 // FIXME: Should we check for unexpanded packs if this was an (invalid) 10043 // declaration of a function template partial specialization? Should we 10044 // consider the unexpanded pack context to be a partial specialization? 10045 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) { 10046 if (DiagnoseUnexpandedParameterPack( 10047 ArgLoc, isFriend ? UPPC_FriendDeclaration 10048 : UPPC_ExplicitSpecialization)) 10049 NewFD->setInvalidDecl(); 10050 } 10051 } 10052 10053 if (Invalid) { 10054 NewFD->setInvalidDecl(); 10055 if (FunctionTemplate) 10056 FunctionTemplate->setInvalidDecl(); 10057 } 10058 10059 // C++ [dcl.fct.spec]p5: 10060 // The virtual specifier shall only be used in declarations of 10061 // nonstatic class member functions that appear within a 10062 // member-specification of a class declaration; see 10.3. 10063 // 10064 if (isVirtual && !NewFD->isInvalidDecl()) { 10065 if (!isVirtualOkay) { 10066 Diag(D.getDeclSpec().getVirtualSpecLoc(), 10067 diag::err_virtual_non_function); 10068 } else if (!CurContext->isRecord()) { 10069 // 'virtual' was specified outside of the class. 10070 Diag(D.getDeclSpec().getVirtualSpecLoc(), 10071 diag::err_virtual_out_of_class) 10072 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 10073 } else if (NewFD->getDescribedFunctionTemplate()) { 10074 // C++ [temp.mem]p3: 10075 // A member function template shall not be virtual. 10076 Diag(D.getDeclSpec().getVirtualSpecLoc(), 10077 diag::err_virtual_member_function_template) 10078 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 10079 } else { 10080 // Okay: Add virtual to the method. 10081 NewFD->setVirtualAsWritten(true); 10082 } 10083 10084 if (getLangOpts().CPlusPlus14 && 10085 NewFD->getReturnType()->isUndeducedType()) 10086 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 10087 } 10088 10089 if (getLangOpts().CPlusPlus14 && 10090 (NewFD->isDependentContext() || 10091 (isFriend && CurContext->isDependentContext())) && 10092 NewFD->getReturnType()->isUndeducedType()) { 10093 // If the function template is referenced directly (for instance, as a 10094 // member of the current instantiation), pretend it has a dependent type. 10095 // This is not really justified by the standard, but is the only sane 10096 // thing to do. 10097 // FIXME: For a friend function, we have not marked the function as being 10098 // a friend yet, so 'isDependentContext' on the FD doesn't work. 10099 const FunctionProtoType *FPT = 10100 NewFD->getType()->castAs<FunctionProtoType>(); 10101 QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); 10102 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 10103 FPT->getExtProtoInfo())); 10104 } 10105 10106 // C++ [dcl.fct.spec]p3: 10107 // The inline specifier shall not appear on a block scope function 10108 // declaration. 10109 if (isInline && !NewFD->isInvalidDecl()) { 10110 if (CurContext->isFunctionOrMethod()) { 10111 // 'inline' is not allowed on block scope function declaration. 10112 Diag(D.getDeclSpec().getInlineSpecLoc(), 10113 diag::err_inline_declaration_block_scope) << Name 10114 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 10115 } 10116 } 10117 10118 // C++ [dcl.fct.spec]p6: 10119 // The explicit specifier shall be used only in the declaration of a 10120 // constructor or conversion function within its class definition; 10121 // see 12.3.1 and 12.3.2. 10122 if (hasExplicit && !NewFD->isInvalidDecl() && 10123 !isa<CXXDeductionGuideDecl>(NewFD)) { 10124 if (!CurContext->isRecord()) { 10125 // 'explicit' was specified outside of the class. 10126 Diag(D.getDeclSpec().getExplicitSpecLoc(), 10127 diag::err_explicit_out_of_class) 10128 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 10129 } else if (!isa<CXXConstructorDecl>(NewFD) && 10130 !isa<CXXConversionDecl>(NewFD)) { 10131 // 'explicit' was specified on a function that wasn't a constructor 10132 // or conversion function. 10133 Diag(D.getDeclSpec().getExplicitSpecLoc(), 10134 diag::err_explicit_non_ctor_or_conv_function) 10135 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 10136 } 10137 } 10138 10139 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 10140 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 10141 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 10142 // are implicitly inline. 10143 NewFD->setImplicitlyInline(); 10144 10145 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 10146 // be either constructors or to return a literal type. Therefore, 10147 // destructors cannot be declared constexpr. 10148 if (isa<CXXDestructorDecl>(NewFD) && 10149 (!getLangOpts().CPlusPlus20 || 10150 ConstexprKind == ConstexprSpecKind::Consteval)) { 10151 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 10152 << static_cast<int>(ConstexprKind); 10153 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 10154 ? ConstexprSpecKind::Unspecified 10155 : ConstexprSpecKind::Constexpr); 10156 } 10157 // C++20 [dcl.constexpr]p2: An allocation function, or a 10158 // deallocation function shall not be declared with the consteval 10159 // specifier. 10160 if (ConstexprKind == ConstexprSpecKind::Consteval && 10161 (NewFD->getOverloadedOperator() == OO_New || 10162 NewFD->getOverloadedOperator() == OO_Array_New || 10163 NewFD->getOverloadedOperator() == OO_Delete || 10164 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 10165 Diag(D.getDeclSpec().getConstexprSpecLoc(), 10166 diag::err_invalid_consteval_decl_kind) 10167 << NewFD; 10168 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 10169 } 10170 } 10171 10172 // If __module_private__ was specified, mark the function accordingly. 10173 if (D.getDeclSpec().isModulePrivateSpecified()) { 10174 if (isFunctionTemplateSpecialization) { 10175 SourceLocation ModulePrivateLoc 10176 = D.getDeclSpec().getModulePrivateSpecLoc(); 10177 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 10178 << 0 10179 << FixItHint::CreateRemoval(ModulePrivateLoc); 10180 } else { 10181 NewFD->setModulePrivate(); 10182 if (FunctionTemplate) 10183 FunctionTemplate->setModulePrivate(); 10184 } 10185 } 10186 10187 if (isFriend) { 10188 if (FunctionTemplate) { 10189 FunctionTemplate->setObjectOfFriendDecl(); 10190 FunctionTemplate->setAccess(AS_public); 10191 } 10192 NewFD->setObjectOfFriendDecl(); 10193 NewFD->setAccess(AS_public); 10194 } 10195 10196 // If a function is defined as defaulted or deleted, mark it as such now. 10197 // We'll do the relevant checks on defaulted / deleted functions later. 10198 switch (D.getFunctionDefinitionKind()) { 10199 case FunctionDefinitionKind::Declaration: 10200 case FunctionDefinitionKind::Definition: 10201 break; 10202 10203 case FunctionDefinitionKind::Defaulted: 10204 NewFD->setDefaulted(); 10205 break; 10206 10207 case FunctionDefinitionKind::Deleted: 10208 NewFD->setDeletedAsWritten(); 10209 break; 10210 } 10211 10212 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 10213 D.isFunctionDefinition() && !isInline) { 10214 // Pre C++20 [class.mfct]p2: 10215 // A member function may be defined (8.4) in its class definition, in 10216 // which case it is an inline member function (7.1.2) 10217 // Post C++20 [class.mfct]p1: 10218 // If a member function is attached to the global module and is defined 10219 // in its class definition, it is inline. 10220 NewFD->setImplicitlyInline(ImplicitInlineCXX20); 10221 } 10222 10223 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 10224 !CurContext->isRecord()) { 10225 // C++ [class.static]p1: 10226 // A data or function member of a class may be declared static 10227 // in a class definition, in which case it is a static member of 10228 // the class. 10229 10230 // Complain about the 'static' specifier if it's on an out-of-line 10231 // member function definition. 10232 10233 // MSVC permits the use of a 'static' storage specifier on an out-of-line 10234 // member function template declaration and class member template 10235 // declaration (MSVC versions before 2015), warn about this. 10236 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 10237 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 10238 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 10239 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 10240 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 10241 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10242 } 10243 10244 // C++11 [except.spec]p15: 10245 // A deallocation function with no exception-specification is treated 10246 // as if it were specified with noexcept(true). 10247 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 10248 if ((Name.getCXXOverloadedOperator() == OO_Delete || 10249 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 10250 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 10251 NewFD->setType(Context.getFunctionType( 10252 FPT->getReturnType(), FPT->getParamTypes(), 10253 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 10254 10255 // C++20 [dcl.inline]/7 10256 // If an inline function or variable that is attached to a named module 10257 // is declared in a definition domain, it shall be defined in that 10258 // domain. 10259 // So, if the current declaration does not have a definition, we must 10260 // check at the end of the TU (or when the PMF starts) to see that we 10261 // have a definition at that point. 10262 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 && 10263 NewFD->hasOwningModule() && NewFD->getOwningModule()->isNamedModule()) { 10264 PendingInlineFuncDecls.insert(NewFD); 10265 } 10266 } 10267 10268 // Filter out previous declarations that don't match the scope. 10269 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 10270 D.getCXXScopeSpec().isNotEmpty() || 10271 isMemberSpecialization || 10272 isFunctionTemplateSpecialization); 10273 10274 // Handle GNU asm-label extension (encoded as an attribute). 10275 if (Expr *E = (Expr*) D.getAsmLabel()) { 10276 // The parser guarantees this is a string. 10277 StringLiteral *SE = cast<StringLiteral>(E); 10278 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 10279 /*IsLiteralLabel=*/true, 10280 SE->getStrTokenLoc(0))); 10281 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 10282 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 10283 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 10284 if (I != ExtnameUndeclaredIdentifiers.end()) { 10285 if (isDeclExternC(NewFD)) { 10286 NewFD->addAttr(I->second); 10287 ExtnameUndeclaredIdentifiers.erase(I); 10288 } else 10289 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 10290 << /*Variable*/0 << NewFD; 10291 } 10292 } 10293 10294 // Copy the parameter declarations from the declarator D to the function 10295 // declaration NewFD, if they are available. First scavenge them into Params. 10296 SmallVector<ParmVarDecl*, 16> Params; 10297 unsigned FTIIdx; 10298 if (D.isFunctionDeclarator(FTIIdx)) { 10299 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 10300 10301 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 10302 // function that takes no arguments, not a function that takes a 10303 // single void argument. 10304 // We let through "const void" here because Sema::GetTypeForDeclarator 10305 // already checks for that case. 10306 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 10307 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 10308 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 10309 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 10310 Param->setDeclContext(NewFD); 10311 Params.push_back(Param); 10312 10313 if (Param->isInvalidDecl()) 10314 NewFD->setInvalidDecl(); 10315 } 10316 } 10317 10318 if (!getLangOpts().CPlusPlus) { 10319 // In C, find all the tag declarations from the prototype and move them 10320 // into the function DeclContext. Remove them from the surrounding tag 10321 // injection context of the function, which is typically but not always 10322 // the TU. 10323 DeclContext *PrototypeTagContext = 10324 getTagInjectionContext(NewFD->getLexicalDeclContext()); 10325 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 10326 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 10327 10328 // We don't want to reparent enumerators. Look at their parent enum 10329 // instead. 10330 if (!TD) { 10331 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 10332 TD = cast<EnumDecl>(ECD->getDeclContext()); 10333 } 10334 if (!TD) 10335 continue; 10336 DeclContext *TagDC = TD->getLexicalDeclContext(); 10337 if (!TagDC->containsDecl(TD)) 10338 continue; 10339 TagDC->removeDecl(TD); 10340 TD->setDeclContext(NewFD); 10341 NewFD->addDecl(TD); 10342 10343 // Preserve the lexical DeclContext if it is not the surrounding tag 10344 // injection context of the FD. In this example, the semantic context of 10345 // E will be f and the lexical context will be S, while both the 10346 // semantic and lexical contexts of S will be f: 10347 // void f(struct S { enum E { a } f; } s); 10348 if (TagDC != PrototypeTagContext) 10349 TD->setLexicalDeclContext(TagDC); 10350 } 10351 } 10352 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 10353 // When we're declaring a function with a typedef, typeof, etc as in the 10354 // following example, we'll need to synthesize (unnamed) 10355 // parameters for use in the declaration. 10356 // 10357 // @code 10358 // typedef void fn(int); 10359 // fn f; 10360 // @endcode 10361 10362 // Synthesize a parameter for each argument type. 10363 for (const auto &AI : FT->param_types()) { 10364 ParmVarDecl *Param = 10365 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 10366 Param->setScopeInfo(0, Params.size()); 10367 Params.push_back(Param); 10368 } 10369 } else { 10370 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 10371 "Should not need args for typedef of non-prototype fn"); 10372 } 10373 10374 // Finally, we know we have the right number of parameters, install them. 10375 NewFD->setParams(Params); 10376 10377 if (D.getDeclSpec().isNoreturnSpecified()) 10378 NewFD->addAttr( 10379 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc())); 10380 10381 // Functions returning a variably modified type violate C99 6.7.5.2p2 10382 // because all functions have linkage. 10383 if (!NewFD->isInvalidDecl() && 10384 NewFD->getReturnType()->isVariablyModifiedType()) { 10385 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 10386 NewFD->setInvalidDecl(); 10387 } 10388 10389 // Apply an implicit SectionAttr if '#pragma clang section text' is active 10390 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 10391 !NewFD->hasAttr<SectionAttr>()) 10392 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 10393 Context, PragmaClangTextSection.SectionName, 10394 PragmaClangTextSection.PragmaLocation)); 10395 10396 // Apply an implicit SectionAttr if #pragma code_seg is active. 10397 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 10398 !NewFD->hasAttr<SectionAttr>()) { 10399 NewFD->addAttr(SectionAttr::CreateImplicit( 10400 Context, CodeSegStack.CurrentValue->getString(), 10401 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate)); 10402 if (UnifySection(CodeSegStack.CurrentValue->getString(), 10403 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 10404 ASTContext::PSF_Read, 10405 NewFD)) 10406 NewFD->dropAttr<SectionAttr>(); 10407 } 10408 10409 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is 10410 // active. 10411 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() && 10412 !NewFD->hasAttr<StrictGuardStackCheckAttr>()) 10413 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit( 10414 Context, PragmaClangTextSection.PragmaLocation)); 10415 10416 // Apply an implicit CodeSegAttr from class declspec or 10417 // apply an implicit SectionAttr from #pragma code_seg if active. 10418 if (!NewFD->hasAttr<CodeSegAttr>()) { 10419 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 10420 D.isFunctionDefinition())) { 10421 NewFD->addAttr(SAttr); 10422 } 10423 } 10424 10425 // Handle attributes. 10426 ProcessDeclAttributes(S, NewFD, D); 10427 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 10428 if (NewTVA && !NewTVA->isDefaultVersion() && 10429 !Context.getTargetInfo().hasFeature("fmv")) { 10430 // Don't add to scope fmv functions declarations if fmv disabled 10431 AddToScope = false; 10432 return NewFD; 10433 } 10434 10435 if (getLangOpts().OpenCL || getLangOpts().HLSL) { 10436 // Neither OpenCL nor HLSL allow an address space qualifyer on a return 10437 // type. 10438 // 10439 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 10440 // type declaration will generate a compilation error. 10441 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 10442 if (AddressSpace != LangAS::Default) { 10443 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space); 10444 NewFD->setInvalidDecl(); 10445 } 10446 } 10447 10448 if (!getLangOpts().CPlusPlus) { 10449 // Perform semantic checking on the function declaration. 10450 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 10451 CheckMain(NewFD, D.getDeclSpec()); 10452 10453 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 10454 CheckMSVCRTEntryPoint(NewFD); 10455 10456 if (!NewFD->isInvalidDecl()) 10457 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 10458 isMemberSpecialization, 10459 D.isFunctionDefinition())); 10460 else if (!Previous.empty()) 10461 // Recover gracefully from an invalid redeclaration. 10462 D.setRedeclaration(true); 10463 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 10464 Previous.getResultKind() != LookupResult::FoundOverloaded) && 10465 "previous declaration set still overloaded"); 10466 10467 // Diagnose no-prototype function declarations with calling conventions that 10468 // don't support variadic calls. Only do this in C and do it after merging 10469 // possibly prototyped redeclarations. 10470 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 10471 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 10472 CallingConv CC = FT->getExtInfo().getCC(); 10473 if (!supportsVariadicCall(CC)) { 10474 // Windows system headers sometimes accidentally use stdcall without 10475 // (void) parameters, so we relax this to a warning. 10476 int DiagID = 10477 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 10478 Diag(NewFD->getLocation(), DiagID) 10479 << FunctionType::getNameForCallConv(CC); 10480 } 10481 } 10482 10483 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 10484 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 10485 checkNonTrivialCUnion(NewFD->getReturnType(), 10486 NewFD->getReturnTypeSourceRange().getBegin(), 10487 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 10488 } else { 10489 // C++11 [replacement.functions]p3: 10490 // The program's definitions shall not be specified as inline. 10491 // 10492 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 10493 // 10494 // Suppress the diagnostic if the function is __attribute__((used)), since 10495 // that forces an external definition to be emitted. 10496 if (D.getDeclSpec().isInlineSpecified() && 10497 NewFD->isReplaceableGlobalAllocationFunction() && 10498 !NewFD->hasAttr<UsedAttr>()) 10499 Diag(D.getDeclSpec().getInlineSpecLoc(), 10500 diag::ext_operator_new_delete_declared_inline) 10501 << NewFD->getDeclName(); 10502 10503 // We do not add HD attributes to specializations here because 10504 // they may have different constexpr-ness compared to their 10505 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 10506 // may end up with different effective targets. Instead, a 10507 // specialization inherits its target attributes from its template 10508 // in the CheckFunctionTemplateSpecialization() call below. 10509 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 10510 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 10511 10512 // Handle explict specializations of function templates 10513 // and friend function declarations with an explicit 10514 // template argument list. 10515 if (isFunctionTemplateSpecialization) { 10516 bool isDependentSpecialization = false; 10517 if (isFriend) { 10518 // For friend function specializations, this is a dependent 10519 // specialization if its semantic context is dependent, its 10520 // type is dependent, or if its template-id is dependent. 10521 isDependentSpecialization = 10522 DC->isDependentContext() || NewFD->getType()->isDependentType() || 10523 (HasExplicitTemplateArgs && 10524 TemplateSpecializationType:: 10525 anyInstantiationDependentTemplateArguments( 10526 TemplateArgs.arguments())); 10527 assert((!isDependentSpecialization || 10528 (HasExplicitTemplateArgs == isDependentSpecialization)) && 10529 "dependent friend function specialization without template " 10530 "args"); 10531 } else { 10532 // For class-scope explicit specializations of function templates, 10533 // if the lexical context is dependent, then the specialization 10534 // is dependent. 10535 isDependentSpecialization = 10536 CurContext->isRecord() && CurContext->isDependentContext(); 10537 } 10538 10539 TemplateArgumentListInfo *ExplicitTemplateArgs = 10540 HasExplicitTemplateArgs ? &TemplateArgs : nullptr; 10541 if (isDependentSpecialization) { 10542 // If it's a dependent specialization, it may not be possible 10543 // to determine the primary template (for explicit specializations) 10544 // or befriended declaration (for friends) until the enclosing 10545 // template is instantiated. In such cases, we store the declarations 10546 // found by name lookup and defer resolution until instantiation. 10547 if (CheckDependentFunctionTemplateSpecialization( 10548 NewFD, ExplicitTemplateArgs, Previous)) 10549 NewFD->setInvalidDecl(); 10550 } else if (!NewFD->isInvalidDecl()) { 10551 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs, 10552 Previous)) 10553 NewFD->setInvalidDecl(); 10554 } 10555 10556 // C++ [dcl.stc]p1: 10557 // A storage-class-specifier shall not be specified in an explicit 10558 // specialization (14.7.3) 10559 // FIXME: We should be checking this for dependent specializations. 10560 FunctionTemplateSpecializationInfo *Info = 10561 NewFD->getTemplateSpecializationInfo(); 10562 if (Info && SC != SC_None) { 10563 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 10564 Diag(NewFD->getLocation(), 10565 diag::err_explicit_specialization_inconsistent_storage_class) 10566 << SC 10567 << FixItHint::CreateRemoval( 10568 D.getDeclSpec().getStorageClassSpecLoc()); 10569 10570 else 10571 Diag(NewFD->getLocation(), 10572 diag::ext_explicit_specialization_storage_class) 10573 << FixItHint::CreateRemoval( 10574 D.getDeclSpec().getStorageClassSpecLoc()); 10575 } 10576 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 10577 if (CheckMemberSpecialization(NewFD, Previous)) 10578 NewFD->setInvalidDecl(); 10579 } 10580 10581 // Perform semantic checking on the function declaration. 10582 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 10583 CheckMain(NewFD, D.getDeclSpec()); 10584 10585 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 10586 CheckMSVCRTEntryPoint(NewFD); 10587 10588 if (!NewFD->isInvalidDecl()) 10589 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 10590 isMemberSpecialization, 10591 D.isFunctionDefinition())); 10592 else if (!Previous.empty()) 10593 // Recover gracefully from an invalid redeclaration. 10594 D.setRedeclaration(true); 10595 10596 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() || 10597 !D.isRedeclaration() || 10598 Previous.getResultKind() != LookupResult::FoundOverloaded) && 10599 "previous declaration set still overloaded"); 10600 10601 NamedDecl *PrincipalDecl = (FunctionTemplate 10602 ? cast<NamedDecl>(FunctionTemplate) 10603 : NewFD); 10604 10605 if (isFriend && NewFD->getPreviousDecl()) { 10606 AccessSpecifier Access = AS_public; 10607 if (!NewFD->isInvalidDecl()) 10608 Access = NewFD->getPreviousDecl()->getAccess(); 10609 10610 NewFD->setAccess(Access); 10611 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 10612 } 10613 10614 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 10615 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 10616 PrincipalDecl->setNonMemberOperator(); 10617 10618 // If we have a function template, check the template parameter 10619 // list. This will check and merge default template arguments. 10620 if (FunctionTemplate) { 10621 FunctionTemplateDecl *PrevTemplate = 10622 FunctionTemplate->getPreviousDecl(); 10623 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 10624 PrevTemplate ? PrevTemplate->getTemplateParameters() 10625 : nullptr, 10626 D.getDeclSpec().isFriendSpecified() 10627 ? (D.isFunctionDefinition() 10628 ? TPC_FriendFunctionTemplateDefinition 10629 : TPC_FriendFunctionTemplate) 10630 : (D.getCXXScopeSpec().isSet() && 10631 DC && DC->isRecord() && 10632 DC->isDependentContext()) 10633 ? TPC_ClassTemplateMember 10634 : TPC_FunctionTemplate); 10635 } 10636 10637 if (NewFD->isInvalidDecl()) { 10638 // Ignore all the rest of this. 10639 } else if (!D.isRedeclaration()) { 10640 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 10641 AddToScope }; 10642 // Fake up an access specifier if it's supposed to be a class member. 10643 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 10644 NewFD->setAccess(AS_public); 10645 10646 // Qualified decls generally require a previous declaration. 10647 if (D.getCXXScopeSpec().isSet()) { 10648 // ...with the major exception of templated-scope or 10649 // dependent-scope friend declarations. 10650 10651 // TODO: we currently also suppress this check in dependent 10652 // contexts because (1) the parameter depth will be off when 10653 // matching friend templates and (2) we might actually be 10654 // selecting a friend based on a dependent factor. But there 10655 // are situations where these conditions don't apply and we 10656 // can actually do this check immediately. 10657 // 10658 // Unless the scope is dependent, it's always an error if qualified 10659 // redeclaration lookup found nothing at all. Diagnose that now; 10660 // nothing will diagnose that error later. 10661 if (isFriend && 10662 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 10663 (!Previous.empty() && CurContext->isDependentContext()))) { 10664 // ignore these 10665 } else if (NewFD->isCPUDispatchMultiVersion() || 10666 NewFD->isCPUSpecificMultiVersion()) { 10667 // ignore this, we allow the redeclaration behavior here to create new 10668 // versions of the function. 10669 } else { 10670 // The user tried to provide an out-of-line definition for a 10671 // function that is a member of a class or namespace, but there 10672 // was no such member function declared (C++ [class.mfct]p2, 10673 // C++ [namespace.memdef]p2). For example: 10674 // 10675 // class X { 10676 // void f() const; 10677 // }; 10678 // 10679 // void X::f() { } // ill-formed 10680 // 10681 // Complain about this problem, and attempt to suggest close 10682 // matches (e.g., those that differ only in cv-qualifiers and 10683 // whether the parameter types are references). 10684 10685 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10686 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 10687 AddToScope = ExtraArgs.AddToScope; 10688 return Result; 10689 } 10690 } 10691 10692 // Unqualified local friend declarations are required to resolve 10693 // to something. 10694 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 10695 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10696 *this, Previous, NewFD, ExtraArgs, true, S)) { 10697 AddToScope = ExtraArgs.AddToScope; 10698 return Result; 10699 } 10700 } 10701 } else if (!D.isFunctionDefinition() && 10702 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 10703 !isFriend && !isFunctionTemplateSpecialization && 10704 !isMemberSpecialization) { 10705 // An out-of-line member function declaration must also be a 10706 // definition (C++ [class.mfct]p2). 10707 // Note that this is not the case for explicit specializations of 10708 // function templates or member functions of class templates, per 10709 // C++ [temp.expl.spec]p2. We also allow these declarations as an 10710 // extension for compatibility with old SWIG code which likes to 10711 // generate them. 10712 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 10713 << D.getCXXScopeSpec().getRange(); 10714 } 10715 } 10716 10717 if (getLangOpts().HLSL && D.isFunctionDefinition()) { 10718 // Any top level function could potentially be specified as an entry. 10719 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier()) 10720 ActOnHLSLTopLevelFunction(NewFD); 10721 10722 if (NewFD->hasAttr<HLSLShaderAttr>()) 10723 CheckHLSLEntryPoint(NewFD); 10724 } 10725 10726 // If this is the first declaration of a library builtin function, add 10727 // attributes as appropriate. 10728 if (!D.isRedeclaration()) { 10729 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 10730 if (unsigned BuiltinID = II->getBuiltinID()) { 10731 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID); 10732 if (!InStdNamespace && 10733 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 10734 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 10735 // Validate the type matches unless this builtin is specified as 10736 // matching regardless of its declared type. 10737 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 10738 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10739 } else { 10740 ASTContext::GetBuiltinTypeError Error; 10741 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10742 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 10743 10744 if (!Error && !BuiltinType.isNull() && 10745 Context.hasSameFunctionTypeIgnoringExceptionSpec( 10746 NewFD->getType(), BuiltinType)) 10747 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10748 } 10749 } 10750 } else if (InStdNamespace && NewFD->isInStdNamespace() && 10751 isStdBuiltin(Context, NewFD, BuiltinID)) { 10752 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10753 } 10754 } 10755 } 10756 } 10757 10758 ProcessPragmaWeak(S, NewFD); 10759 checkAttributesAfterMerging(*this, *NewFD); 10760 10761 AddKnownFunctionAttributes(NewFD); 10762 10763 if (NewFD->hasAttr<OverloadableAttr>() && 10764 !NewFD->getType()->getAs<FunctionProtoType>()) { 10765 Diag(NewFD->getLocation(), 10766 diag::err_attribute_overloadable_no_prototype) 10767 << NewFD; 10768 NewFD->dropAttr<OverloadableAttr>(); 10769 } 10770 10771 // If there's a #pragma GCC visibility in scope, and this isn't a class 10772 // member, set the visibility of this function. 10773 if (!DC->isRecord() && NewFD->isExternallyVisible()) 10774 AddPushedVisibilityAttribute(NewFD); 10775 10776 // If there's a #pragma clang arc_cf_code_audited in scope, consider 10777 // marking the function. 10778 AddCFAuditedAttribute(NewFD); 10779 10780 // If this is a function definition, check if we have to apply any 10781 // attributes (i.e. optnone and no_builtin) due to a pragma. 10782 if (D.isFunctionDefinition()) { 10783 AddRangeBasedOptnone(NewFD); 10784 AddImplicitMSFunctionNoBuiltinAttr(NewFD); 10785 AddSectionMSAllocText(NewFD); 10786 ModifyFnAttributesMSPragmaOptimize(NewFD); 10787 } 10788 10789 // If this is the first declaration of an extern C variable, update 10790 // the map of such variables. 10791 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 10792 isIncompleteDeclExternC(*this, NewFD)) 10793 RegisterLocallyScopedExternCDecl(NewFD, S); 10794 10795 // Set this FunctionDecl's range up to the right paren. 10796 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 10797 10798 if (D.isRedeclaration() && !Previous.empty()) { 10799 NamedDecl *Prev = Previous.getRepresentativeDecl(); 10800 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 10801 isMemberSpecialization || 10802 isFunctionTemplateSpecialization, 10803 D.isFunctionDefinition()); 10804 } 10805 10806 if (getLangOpts().CUDA) { 10807 IdentifierInfo *II = NewFD->getIdentifier(); 10808 if (II && II->isStr(getCudaConfigureFuncName()) && 10809 !NewFD->isInvalidDecl() && 10810 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 10811 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 10812 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 10813 << getCudaConfigureFuncName(); 10814 Context.setcudaConfigureCallDecl(NewFD); 10815 } 10816 10817 // Variadic functions, other than a *declaration* of printf, are not allowed 10818 // in device-side CUDA code, unless someone passed 10819 // -fcuda-allow-variadic-functions. 10820 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 10821 (NewFD->hasAttr<CUDADeviceAttr>() || 10822 NewFD->hasAttr<CUDAGlobalAttr>()) && 10823 !(II && II->isStr("printf") && NewFD->isExternC() && 10824 !D.isFunctionDefinition())) { 10825 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 10826 } 10827 } 10828 10829 MarkUnusedFileScopedDecl(NewFD); 10830 10831 10832 10833 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 10834 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 10835 if (SC == SC_Static) { 10836 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 10837 D.setInvalidType(); 10838 } 10839 10840 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 10841 if (!NewFD->getReturnType()->isVoidType()) { 10842 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 10843 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 10844 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 10845 : FixItHint()); 10846 D.setInvalidType(); 10847 } 10848 10849 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 10850 for (auto *Param : NewFD->parameters()) 10851 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 10852 10853 if (getLangOpts().OpenCLCPlusPlus) { 10854 if (DC->isRecord()) { 10855 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 10856 D.setInvalidType(); 10857 } 10858 if (FunctionTemplate) { 10859 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10860 D.setInvalidType(); 10861 } 10862 } 10863 } 10864 10865 if (getLangOpts().CPlusPlus) { 10866 // Precalculate whether this is a friend function template with a constraint 10867 // that depends on an enclosing template, per [temp.friend]p9. 10868 if (isFriend && FunctionTemplate && 10869 FriendConstraintsDependOnEnclosingTemplate(NewFD)) { 10870 NewFD->setFriendConstraintRefersToEnclosingTemplate(true); 10871 10872 // C++ [temp.friend]p9: 10873 // A friend function template with a constraint that depends on a 10874 // template parameter from an enclosing template shall be a definition. 10875 if (!D.isFunctionDefinition()) { 10876 Diag(NewFD->getBeginLoc(), 10877 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def); 10878 NewFD->setInvalidDecl(); 10879 } 10880 } 10881 10882 if (FunctionTemplate) { 10883 if (NewFD->isInvalidDecl()) 10884 FunctionTemplate->setInvalidDecl(); 10885 return FunctionTemplate; 10886 } 10887 10888 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10889 CompleteMemberSpecialization(NewFD, Previous); 10890 } 10891 10892 for (const ParmVarDecl *Param : NewFD->parameters()) { 10893 QualType PT = Param->getType(); 10894 10895 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10896 // types. 10897 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10898 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10899 QualType ElemTy = PipeTy->getElementType(); 10900 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10901 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10902 D.setInvalidType(); 10903 } 10904 } 10905 } 10906 // WebAssembly tables can't be used as function parameters. 10907 if (Context.getTargetInfo().getTriple().isWasm()) { 10908 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) { 10909 Diag(Param->getTypeSpecStartLoc(), 10910 diag::err_wasm_table_as_function_parameter); 10911 D.setInvalidType(); 10912 } 10913 } 10914 } 10915 10916 // Diagnose availability attributes. Availability cannot be used on functions 10917 // that are run during load/unload. 10918 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10919 if (NewFD->hasAttr<ConstructorAttr>()) { 10920 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10921 << 1; 10922 NewFD->dropAttr<AvailabilityAttr>(); 10923 } 10924 if (NewFD->hasAttr<DestructorAttr>()) { 10925 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10926 << 2; 10927 NewFD->dropAttr<AvailabilityAttr>(); 10928 } 10929 } 10930 10931 // Diagnose no_builtin attribute on function declaration that are not a 10932 // definition. 10933 // FIXME: We should really be doing this in 10934 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10935 // the FunctionDecl and at this point of the code 10936 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10937 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10938 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10939 switch (D.getFunctionDefinitionKind()) { 10940 case FunctionDefinitionKind::Defaulted: 10941 case FunctionDefinitionKind::Deleted: 10942 Diag(NBA->getLocation(), 10943 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10944 << NBA->getSpelling(); 10945 break; 10946 case FunctionDefinitionKind::Declaration: 10947 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10948 << NBA->getSpelling(); 10949 break; 10950 case FunctionDefinitionKind::Definition: 10951 break; 10952 } 10953 10954 return NewFD; 10955 } 10956 10957 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10958 /// when __declspec(code_seg) "is applied to a class, all member functions of 10959 /// the class and nested classes -- this includes compiler-generated special 10960 /// member functions -- are put in the specified segment." 10961 /// The actual behavior is a little more complicated. The Microsoft compiler 10962 /// won't check outer classes if there is an active value from #pragma code_seg. 10963 /// The CodeSeg is always applied from the direct parent but only from outer 10964 /// classes when the #pragma code_seg stack is empty. See: 10965 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10966 /// available since MS has removed the page. 10967 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10968 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10969 if (!Method) 10970 return nullptr; 10971 const CXXRecordDecl *Parent = Method->getParent(); 10972 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10973 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10974 NewAttr->setImplicit(true); 10975 return NewAttr; 10976 } 10977 10978 // The Microsoft compiler won't check outer classes for the CodeSeg 10979 // when the #pragma code_seg stack is active. 10980 if (S.CodeSegStack.CurrentValue) 10981 return nullptr; 10982 10983 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10984 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10985 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10986 NewAttr->setImplicit(true); 10987 return NewAttr; 10988 } 10989 } 10990 return nullptr; 10991 } 10992 10993 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10994 /// containing class. Otherwise it will return implicit SectionAttr if the 10995 /// function is a definition and there is an active value on CodeSegStack 10996 /// (from the current #pragma code-seg value). 10997 /// 10998 /// \param FD Function being declared. 10999 /// \param IsDefinition Whether it is a definition or just a declaration. 11000 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 11001 /// nullptr if no attribute should be added. 11002 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 11003 bool IsDefinition) { 11004 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 11005 return A; 11006 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 11007 CodeSegStack.CurrentValue) 11008 return SectionAttr::CreateImplicit( 11009 getASTContext(), CodeSegStack.CurrentValue->getString(), 11010 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate); 11011 return nullptr; 11012 } 11013 11014 /// Determines if we can perform a correct type check for \p D as a 11015 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 11016 /// best-effort check. 11017 /// 11018 /// \param NewD The new declaration. 11019 /// \param OldD The old declaration. 11020 /// \param NewT The portion of the type of the new declaration to check. 11021 /// \param OldT The portion of the type of the old declaration to check. 11022 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 11023 QualType NewT, QualType OldT) { 11024 if (!NewD->getLexicalDeclContext()->isDependentContext()) 11025 return true; 11026 11027 // For dependently-typed local extern declarations and friends, we can't 11028 // perform a correct type check in general until instantiation: 11029 // 11030 // int f(); 11031 // template<typename T> void g() { T f(); } 11032 // 11033 // (valid if g() is only instantiated with T = int). 11034 if (NewT->isDependentType() && 11035 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 11036 return false; 11037 11038 // Similarly, if the previous declaration was a dependent local extern 11039 // declaration, we don't really know its type yet. 11040 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 11041 return false; 11042 11043 return true; 11044 } 11045 11046 /// Checks if the new declaration declared in dependent context must be 11047 /// put in the same redeclaration chain as the specified declaration. 11048 /// 11049 /// \param D Declaration that is checked. 11050 /// \param PrevDecl Previous declaration found with proper lookup method for the 11051 /// same declaration name. 11052 /// \returns True if D must be added to the redeclaration chain which PrevDecl 11053 /// belongs to. 11054 /// 11055 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 11056 if (!D->getLexicalDeclContext()->isDependentContext()) 11057 return true; 11058 11059 // Don't chain dependent friend function definitions until instantiation, to 11060 // permit cases like 11061 // 11062 // void func(); 11063 // template<typename T> class C1 { friend void func() {} }; 11064 // template<typename T> class C2 { friend void func() {} }; 11065 // 11066 // ... which is valid if only one of C1 and C2 is ever instantiated. 11067 // 11068 // FIXME: This need only apply to function definitions. For now, we proxy 11069 // this by checking for a file-scope function. We do not want this to apply 11070 // to friend declarations nominating member functions, because that gets in 11071 // the way of access checks. 11072 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 11073 return false; 11074 11075 auto *VD = dyn_cast<ValueDecl>(D); 11076 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 11077 return !VD || !PrevVD || 11078 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 11079 PrevVD->getType()); 11080 } 11081 11082 /// Check the target or target_version attribute of the function for 11083 /// MultiVersion validity. 11084 /// 11085 /// Returns true if there was an error, false otherwise. 11086 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 11087 const auto *TA = FD->getAttr<TargetAttr>(); 11088 const auto *TVA = FD->getAttr<TargetVersionAttr>(); 11089 assert( 11090 (TA || TVA) && 11091 "MultiVersion candidate requires a target or target_version attribute"); 11092 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 11093 enum ErrType { Feature = 0, Architecture = 1 }; 11094 11095 if (TA) { 11096 ParsedTargetAttr ParseInfo = 11097 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr()); 11098 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) { 11099 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11100 << Architecture << ParseInfo.CPU; 11101 return true; 11102 } 11103 for (const auto &Feat : ParseInfo.Features) { 11104 auto BareFeat = StringRef{Feat}.substr(1); 11105 if (Feat[0] == '-') { 11106 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11107 << Feature << ("no-" + BareFeat).str(); 11108 return true; 11109 } 11110 11111 if (!TargetInfo.validateCpuSupports(BareFeat) || 11112 !TargetInfo.isValidFeatureName(BareFeat)) { 11113 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11114 << Feature << BareFeat; 11115 return true; 11116 } 11117 } 11118 } 11119 11120 if (TVA) { 11121 llvm::SmallVector<StringRef, 8> Feats; 11122 TVA->getFeatures(Feats); 11123 for (const auto &Feat : Feats) { 11124 if (!TargetInfo.validateCpuSupports(Feat)) { 11125 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11126 << Feature << Feat; 11127 return true; 11128 } 11129 } 11130 } 11131 return false; 11132 } 11133 11134 // Provide a white-list of attributes that are allowed to be combined with 11135 // multiversion functions. 11136 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 11137 MultiVersionKind MVKind) { 11138 // Note: this list/diagnosis must match the list in 11139 // checkMultiversionAttributesAllSame. 11140 switch (Kind) { 11141 default: 11142 return false; 11143 case attr::Used: 11144 return MVKind == MultiVersionKind::Target; 11145 case attr::NonNull: 11146 case attr::NoThrow: 11147 return true; 11148 } 11149 } 11150 11151 static bool checkNonMultiVersionCompatAttributes(Sema &S, 11152 const FunctionDecl *FD, 11153 const FunctionDecl *CausedFD, 11154 MultiVersionKind MVKind) { 11155 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) { 11156 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 11157 << static_cast<unsigned>(MVKind) << A; 11158 if (CausedFD) 11159 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 11160 return true; 11161 }; 11162 11163 for (const Attr *A : FD->attrs()) { 11164 switch (A->getKind()) { 11165 case attr::CPUDispatch: 11166 case attr::CPUSpecific: 11167 if (MVKind != MultiVersionKind::CPUDispatch && 11168 MVKind != MultiVersionKind::CPUSpecific) 11169 return Diagnose(S, A); 11170 break; 11171 case attr::Target: 11172 if (MVKind != MultiVersionKind::Target) 11173 return Diagnose(S, A); 11174 break; 11175 case attr::TargetVersion: 11176 if (MVKind != MultiVersionKind::TargetVersion) 11177 return Diagnose(S, A); 11178 break; 11179 case attr::TargetClones: 11180 if (MVKind != MultiVersionKind::TargetClones) 11181 return Diagnose(S, A); 11182 break; 11183 default: 11184 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind)) 11185 return Diagnose(S, A); 11186 break; 11187 } 11188 } 11189 return false; 11190 } 11191 11192 bool Sema::areMultiversionVariantFunctionsCompatible( 11193 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 11194 const PartialDiagnostic &NoProtoDiagID, 11195 const PartialDiagnosticAt &NoteCausedDiagIDAt, 11196 const PartialDiagnosticAt &NoSupportDiagIDAt, 11197 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 11198 bool ConstexprSupported, bool CLinkageMayDiffer) { 11199 enum DoesntSupport { 11200 FuncTemplates = 0, 11201 VirtFuncs = 1, 11202 DeducedReturn = 2, 11203 Constructors = 3, 11204 Destructors = 4, 11205 DeletedFuncs = 5, 11206 DefaultedFuncs = 6, 11207 ConstexprFuncs = 7, 11208 ConstevalFuncs = 8, 11209 Lambda = 9, 11210 }; 11211 enum Different { 11212 CallingConv = 0, 11213 ReturnType = 1, 11214 ConstexprSpec = 2, 11215 InlineSpec = 3, 11216 Linkage = 4, 11217 LanguageLinkage = 5, 11218 }; 11219 11220 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 11221 !OldFD->getType()->getAs<FunctionProtoType>()) { 11222 Diag(OldFD->getLocation(), NoProtoDiagID); 11223 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 11224 return true; 11225 } 11226 11227 if (NoProtoDiagID.getDiagID() != 0 && 11228 !NewFD->getType()->getAs<FunctionProtoType>()) 11229 return Diag(NewFD->getLocation(), NoProtoDiagID); 11230 11231 if (!TemplatesSupported && 11232 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11233 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11234 << FuncTemplates; 11235 11236 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 11237 if (NewCXXFD->isVirtual()) 11238 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11239 << VirtFuncs; 11240 11241 if (isa<CXXConstructorDecl>(NewCXXFD)) 11242 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11243 << Constructors; 11244 11245 if (isa<CXXDestructorDecl>(NewCXXFD)) 11246 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11247 << Destructors; 11248 } 11249 11250 if (NewFD->isDeleted()) 11251 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11252 << DeletedFuncs; 11253 11254 if (NewFD->isDefaulted()) 11255 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11256 << DefaultedFuncs; 11257 11258 if (!ConstexprSupported && NewFD->isConstexpr()) 11259 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11260 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 11261 11262 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 11263 const auto *NewType = cast<FunctionType>(NewQType); 11264 QualType NewReturnType = NewType->getReturnType(); 11265 11266 if (NewReturnType->isUndeducedType()) 11267 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11268 << DeducedReturn; 11269 11270 // Ensure the return type is identical. 11271 if (OldFD) { 11272 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 11273 const auto *OldType = cast<FunctionType>(OldQType); 11274 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 11275 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 11276 11277 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 11278 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 11279 11280 QualType OldReturnType = OldType->getReturnType(); 11281 11282 if (OldReturnType != NewReturnType) 11283 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 11284 11285 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 11286 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 11287 11288 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 11289 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 11290 11291 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 11292 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 11293 11294 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 11295 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 11296 11297 if (CheckEquivalentExceptionSpec( 11298 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 11299 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 11300 return true; 11301 } 11302 return false; 11303 } 11304 11305 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 11306 const FunctionDecl *NewFD, 11307 bool CausesMV, 11308 MultiVersionKind MVKind) { 11309 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 11310 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 11311 if (OldFD) 11312 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11313 return true; 11314 } 11315 11316 bool IsCPUSpecificCPUDispatchMVKind = 11317 MVKind == MultiVersionKind::CPUDispatch || 11318 MVKind == MultiVersionKind::CPUSpecific; 11319 11320 if (CausesMV && OldFD && 11321 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind)) 11322 return true; 11323 11324 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind)) 11325 return true; 11326 11327 // Only allow transition to MultiVersion if it hasn't been used. 11328 if (OldFD && CausesMV && OldFD->isUsed(false)) 11329 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 11330 11331 return S.areMultiversionVariantFunctionsCompatible( 11332 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 11333 PartialDiagnosticAt(NewFD->getLocation(), 11334 S.PDiag(diag::note_multiversioning_caused_here)), 11335 PartialDiagnosticAt(NewFD->getLocation(), 11336 S.PDiag(diag::err_multiversion_doesnt_support) 11337 << static_cast<unsigned>(MVKind)), 11338 PartialDiagnosticAt(NewFD->getLocation(), 11339 S.PDiag(diag::err_multiversion_diff)), 11340 /*TemplatesSupported=*/false, 11341 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind, 11342 /*CLinkageMayDiffer=*/false); 11343 } 11344 11345 /// Check the validity of a multiversion function declaration that is the 11346 /// first of its kind. Also sets the multiversion'ness' of the function itself. 11347 /// 11348 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11349 /// 11350 /// Returns true if there was an error, false otherwise. 11351 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) { 11352 MultiVersionKind MVKind = FD->getMultiVersionKind(); 11353 assert(MVKind != MultiVersionKind::None && 11354 "Function lacks multiversion attribute"); 11355 const auto *TA = FD->getAttr<TargetAttr>(); 11356 const auto *TVA = FD->getAttr<TargetVersionAttr>(); 11357 // Target and target_version only causes MV if it is default, otherwise this 11358 // is a normal function. 11359 if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion())) 11360 return false; 11361 11362 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) { 11363 FD->setInvalidDecl(); 11364 return true; 11365 } 11366 11367 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) { 11368 FD->setInvalidDecl(); 11369 return true; 11370 } 11371 11372 FD->setIsMultiVersion(); 11373 return false; 11374 } 11375 11376 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 11377 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 11378 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 11379 return true; 11380 } 11381 11382 return false; 11383 } 11384 11385 static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, 11386 FunctionDecl *NewFD, 11387 bool &Redeclaration, 11388 NamedDecl *&OldDecl, 11389 LookupResult &Previous) { 11390 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11391 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11392 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 11393 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>(); 11394 // If the old decl is NOT MultiVersioned yet, and we don't cause that 11395 // to change, this is a simple redeclaration. 11396 if ((NewTA && !NewTA->isDefaultVersion() && 11397 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) || 11398 (NewTVA && !NewTVA->isDefaultVersion() && 11399 (!OldTVA || OldTVA->getName() == NewTVA->getName()))) 11400 return false; 11401 11402 // Otherwise, this decl causes MultiVersioning. 11403 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 11404 NewTVA ? MultiVersionKind::TargetVersion 11405 : MultiVersionKind::Target)) { 11406 NewFD->setInvalidDecl(); 11407 return true; 11408 } 11409 11410 if (CheckMultiVersionValue(S, NewFD)) { 11411 NewFD->setInvalidDecl(); 11412 return true; 11413 } 11414 11415 // If this is 'default', permit the forward declaration. 11416 if (!OldFD->isMultiVersion() && 11417 ((NewTA && NewTA->isDefaultVersion() && !OldTA) || 11418 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) { 11419 Redeclaration = true; 11420 OldDecl = OldFD; 11421 OldFD->setIsMultiVersion(); 11422 NewFD->setIsMultiVersion(); 11423 return false; 11424 } 11425 11426 if (CheckMultiVersionValue(S, OldFD)) { 11427 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 11428 NewFD->setInvalidDecl(); 11429 return true; 11430 } 11431 11432 if (NewTA) { 11433 ParsedTargetAttr OldParsed = 11434 S.getASTContext().getTargetInfo().parseTargetAttr( 11435 OldTA->getFeaturesStr()); 11436 llvm::sort(OldParsed.Features); 11437 ParsedTargetAttr NewParsed = 11438 S.getASTContext().getTargetInfo().parseTargetAttr( 11439 NewTA->getFeaturesStr()); 11440 // Sort order doesn't matter, it just needs to be consistent. 11441 llvm::sort(NewParsed.Features); 11442 if (OldParsed == NewParsed) { 11443 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11444 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11445 NewFD->setInvalidDecl(); 11446 return true; 11447 } 11448 } 11449 11450 if (NewTVA) { 11451 llvm::SmallVector<StringRef, 8> Feats; 11452 OldTVA->getFeatures(Feats); 11453 llvm::sort(Feats); 11454 llvm::SmallVector<StringRef, 8> NewFeats; 11455 NewTVA->getFeatures(NewFeats); 11456 llvm::sort(NewFeats); 11457 11458 if (Feats == NewFeats) { 11459 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11460 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11461 NewFD->setInvalidDecl(); 11462 return true; 11463 } 11464 } 11465 11466 for (const auto *FD : OldFD->redecls()) { 11467 const auto *CurTA = FD->getAttr<TargetAttr>(); 11468 const auto *CurTVA = FD->getAttr<TargetVersionAttr>(); 11469 // We allow forward declarations before ANY multiversioning attributes, but 11470 // nothing after the fact. 11471 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 11472 ((NewTA && (!CurTA || CurTA->isInherited())) || 11473 (NewTVA && (!CurTVA || CurTVA->isInherited())))) { 11474 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 11475 << (NewTA ? 0 : 2); 11476 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 11477 NewFD->setInvalidDecl(); 11478 return true; 11479 } 11480 } 11481 11482 OldFD->setIsMultiVersion(); 11483 NewFD->setIsMultiVersion(); 11484 Redeclaration = false; 11485 OldDecl = nullptr; 11486 Previous.clear(); 11487 return false; 11488 } 11489 11490 static bool MultiVersionTypesCompatible(MultiVersionKind Old, 11491 MultiVersionKind New) { 11492 if (Old == New || Old == MultiVersionKind::None || 11493 New == MultiVersionKind::None) 11494 return true; 11495 11496 return (Old == MultiVersionKind::CPUDispatch && 11497 New == MultiVersionKind::CPUSpecific) || 11498 (Old == MultiVersionKind::CPUSpecific && 11499 New == MultiVersionKind::CPUDispatch); 11500 } 11501 11502 /// Check the validity of a new function declaration being added to an existing 11503 /// multiversioned declaration collection. 11504 static bool CheckMultiVersionAdditionalDecl( 11505 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 11506 MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp, 11507 const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, 11508 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) { 11509 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11510 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11511 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind(); 11512 // Disallow mixing of multiversioning types. 11513 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) { 11514 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 11515 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11516 NewFD->setInvalidDecl(); 11517 return true; 11518 } 11519 11520 ParsedTargetAttr NewParsed; 11521 if (NewTA) { 11522 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr( 11523 NewTA->getFeaturesStr()); 11524 llvm::sort(NewParsed.Features); 11525 } 11526 llvm::SmallVector<StringRef, 8> NewFeats; 11527 if (NewTVA) { 11528 NewTVA->getFeatures(NewFeats); 11529 llvm::sort(NewFeats); 11530 } 11531 11532 bool UseMemberUsingDeclRules = 11533 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 11534 11535 bool MayNeedOverloadableChecks = 11536 AllowOverloadingOfFunction(Previous, S.Context, NewFD); 11537 11538 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration 11539 // of a previous member of the MultiVersion set. 11540 for (NamedDecl *ND : Previous) { 11541 FunctionDecl *CurFD = ND->getAsFunction(); 11542 if (!CurFD || CurFD->isInvalidDecl()) 11543 continue; 11544 if (MayNeedOverloadableChecks && 11545 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 11546 continue; 11547 11548 if (NewMVKind == MultiVersionKind::None && 11549 OldMVKind == MultiVersionKind::TargetVersion) { 11550 NewFD->addAttr(TargetVersionAttr::CreateImplicit( 11551 S.Context, "default", NewFD->getSourceRange())); 11552 NewFD->setIsMultiVersion(); 11553 NewMVKind = MultiVersionKind::TargetVersion; 11554 if (!NewTVA) { 11555 NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11556 NewTVA->getFeatures(NewFeats); 11557 llvm::sort(NewFeats); 11558 } 11559 } 11560 11561 switch (NewMVKind) { 11562 case MultiVersionKind::None: 11563 assert(OldMVKind == MultiVersionKind::TargetClones && 11564 "Only target_clones can be omitted in subsequent declarations"); 11565 break; 11566 case MultiVersionKind::Target: { 11567 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 11568 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 11569 NewFD->setIsMultiVersion(); 11570 Redeclaration = true; 11571 OldDecl = ND; 11572 return false; 11573 } 11574 11575 ParsedTargetAttr CurParsed = 11576 S.getASTContext().getTargetInfo().parseTargetAttr( 11577 CurTA->getFeaturesStr()); 11578 llvm::sort(CurParsed.Features); 11579 if (CurParsed == NewParsed) { 11580 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11581 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11582 NewFD->setInvalidDecl(); 11583 return true; 11584 } 11585 break; 11586 } 11587 case MultiVersionKind::TargetVersion: { 11588 const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>(); 11589 if (CurTVA->getName() == NewTVA->getName()) { 11590 NewFD->setIsMultiVersion(); 11591 Redeclaration = true; 11592 OldDecl = ND; 11593 return false; 11594 } 11595 llvm::SmallVector<StringRef, 8> CurFeats; 11596 if (CurTVA) { 11597 CurTVA->getFeatures(CurFeats); 11598 llvm::sort(CurFeats); 11599 } 11600 if (CurFeats == NewFeats) { 11601 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11602 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11603 NewFD->setInvalidDecl(); 11604 return true; 11605 } 11606 break; 11607 } 11608 case MultiVersionKind::TargetClones: { 11609 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>(); 11610 Redeclaration = true; 11611 OldDecl = CurFD; 11612 NewFD->setIsMultiVersion(); 11613 11614 if (CurClones && NewClones && 11615 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || 11616 !std::equal(CurClones->featuresStrs_begin(), 11617 CurClones->featuresStrs_end(), 11618 NewClones->featuresStrs_begin()))) { 11619 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match); 11620 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11621 NewFD->setInvalidDecl(); 11622 return true; 11623 } 11624 11625 return false; 11626 } 11627 case MultiVersionKind::CPUSpecific: 11628 case MultiVersionKind::CPUDispatch: { 11629 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 11630 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 11631 // Handle CPUDispatch/CPUSpecific versions. 11632 // Only 1 CPUDispatch function is allowed, this will make it go through 11633 // the redeclaration errors. 11634 if (NewMVKind == MultiVersionKind::CPUDispatch && 11635 CurFD->hasAttr<CPUDispatchAttr>()) { 11636 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 11637 std::equal( 11638 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 11639 NewCPUDisp->cpus_begin(), 11640 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 11641 return Cur->getName() == New->getName(); 11642 })) { 11643 NewFD->setIsMultiVersion(); 11644 Redeclaration = true; 11645 OldDecl = ND; 11646 return false; 11647 } 11648 11649 // If the declarations don't match, this is an error condition. 11650 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 11651 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11652 NewFD->setInvalidDecl(); 11653 return true; 11654 } 11655 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) { 11656 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 11657 std::equal( 11658 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 11659 NewCPUSpec->cpus_begin(), 11660 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 11661 return Cur->getName() == New->getName(); 11662 })) { 11663 NewFD->setIsMultiVersion(); 11664 Redeclaration = true; 11665 OldDecl = ND; 11666 return false; 11667 } 11668 11669 // Only 1 version of CPUSpecific is allowed for each CPU. 11670 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 11671 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 11672 if (CurII == NewII) { 11673 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 11674 << NewII; 11675 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11676 NewFD->setInvalidDecl(); 11677 return true; 11678 } 11679 } 11680 } 11681 } 11682 break; 11683 } 11684 } 11685 } 11686 11687 // Else, this is simply a non-redecl case. Checking the 'value' is only 11688 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 11689 // handled in the attribute adding step. 11690 if ((NewMVKind == MultiVersionKind::TargetVersion || 11691 NewMVKind == MultiVersionKind::Target) && 11692 CheckMultiVersionValue(S, NewFD)) { 11693 NewFD->setInvalidDecl(); 11694 return true; 11695 } 11696 11697 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 11698 !OldFD->isMultiVersion(), NewMVKind)) { 11699 NewFD->setInvalidDecl(); 11700 return true; 11701 } 11702 11703 // Permit forward declarations in the case where these two are compatible. 11704 if (!OldFD->isMultiVersion()) { 11705 OldFD->setIsMultiVersion(); 11706 NewFD->setIsMultiVersion(); 11707 Redeclaration = true; 11708 OldDecl = OldFD; 11709 return false; 11710 } 11711 11712 NewFD->setIsMultiVersion(); 11713 Redeclaration = false; 11714 OldDecl = nullptr; 11715 Previous.clear(); 11716 return false; 11717 } 11718 11719 /// Check the validity of a mulitversion function declaration. 11720 /// Also sets the multiversion'ness' of the function itself. 11721 /// 11722 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11723 /// 11724 /// Returns true if there was an error, false otherwise. 11725 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 11726 bool &Redeclaration, NamedDecl *&OldDecl, 11727 LookupResult &Previous) { 11728 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11729 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11730 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 11731 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 11732 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); 11733 MultiVersionKind MVKind = NewFD->getMultiVersionKind(); 11734 11735 // Main isn't allowed to become a multiversion function, however it IS 11736 // permitted to have 'main' be marked with the 'target' optimization hint, 11737 // for 'target_version' only default is allowed. 11738 if (NewFD->isMain()) { 11739 if (MVKind != MultiVersionKind::None && 11740 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) && 11741 !(MVKind == MultiVersionKind::TargetVersion && 11742 NewTVA->isDefaultVersion())) { 11743 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 11744 NewFD->setInvalidDecl(); 11745 return true; 11746 } 11747 return false; 11748 } 11749 11750 // Target attribute on AArch64 is not used for multiversioning 11751 if (NewTA && S.getASTContext().getTargetInfo().getTriple().isAArch64()) 11752 return false; 11753 11754 if (!OldDecl || !OldDecl->getAsFunction() || 11755 OldDecl->getDeclContext()->getRedeclContext() != 11756 NewFD->getDeclContext()->getRedeclContext()) { 11757 // If there's no previous declaration, AND this isn't attempting to cause 11758 // multiversioning, this isn't an error condition. 11759 if (MVKind == MultiVersionKind::None) 11760 return false; 11761 return CheckMultiVersionFirstFunction(S, NewFD); 11762 } 11763 11764 FunctionDecl *OldFD = OldDecl->getAsFunction(); 11765 11766 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) { 11767 if (NewTVA || !OldFD->getAttr<TargetVersionAttr>()) 11768 return false; 11769 if (!NewFD->getType()->getAs<FunctionProtoType>()) { 11770 // Multiversion declaration doesn't have prototype. 11771 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 11772 NewFD->setInvalidDecl(); 11773 } else { 11774 // No "target_version" attribute is equivalent to "default" attribute. 11775 NewFD->addAttr(TargetVersionAttr::CreateImplicit( 11776 S.Context, "default", NewFD->getSourceRange())); 11777 NewFD->setIsMultiVersion(); 11778 OldFD->setIsMultiVersion(); 11779 OldDecl = OldFD; 11780 Redeclaration = true; 11781 } 11782 return true; 11783 } 11784 11785 // Multiversioned redeclarations aren't allowed to omit the attribute, except 11786 // for target_clones and target_version. 11787 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None && 11788 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones && 11789 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) { 11790 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 11791 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 11792 NewFD->setInvalidDecl(); 11793 return true; 11794 } 11795 11796 if (!OldFD->isMultiVersion()) { 11797 switch (MVKind) { 11798 case MultiVersionKind::Target: 11799 case MultiVersionKind::TargetVersion: 11800 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration, 11801 OldDecl, Previous); 11802 case MultiVersionKind::TargetClones: 11803 if (OldFD->isUsed(false)) { 11804 NewFD->setInvalidDecl(); 11805 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 11806 } 11807 OldFD->setIsMultiVersion(); 11808 break; 11809 11810 case MultiVersionKind::CPUDispatch: 11811 case MultiVersionKind::CPUSpecific: 11812 case MultiVersionKind::None: 11813 break; 11814 } 11815 } 11816 11817 // At this point, we have a multiversion function decl (in OldFD) AND an 11818 // appropriate attribute in the current function decl. Resolve that these are 11819 // still compatible with previous declarations. 11820 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp, 11821 NewCPUSpec, NewClones, Redeclaration, 11822 OldDecl, Previous); 11823 } 11824 11825 static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) { 11826 bool IsPure = NewFD->hasAttr<PureAttr>(); 11827 bool IsConst = NewFD->hasAttr<ConstAttr>(); 11828 11829 // If there are no pure or const attributes, there's nothing to check. 11830 if (!IsPure && !IsConst) 11831 return; 11832 11833 // If the function is marked both pure and const, we retain the const 11834 // attribute because it makes stronger guarantees than the pure attribute, and 11835 // we drop the pure attribute explicitly to prevent later confusion about 11836 // semantics. 11837 if (IsPure && IsConst) { 11838 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr); 11839 NewFD->dropAttrs<PureAttr>(); 11840 } 11841 11842 // Constructors and destructors are functions which return void, so are 11843 // handled here as well. 11844 if (NewFD->getReturnType()->isVoidType()) { 11845 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void) 11846 << IsConst; 11847 NewFD->dropAttrs<PureAttr, ConstAttr>(); 11848 } 11849 } 11850 11851 /// Perform semantic checking of a new function declaration. 11852 /// 11853 /// Performs semantic analysis of the new function declaration 11854 /// NewFD. This routine performs all semantic checking that does not 11855 /// require the actual declarator involved in the declaration, and is 11856 /// used both for the declaration of functions as they are parsed 11857 /// (called via ActOnDeclarator) and for the declaration of functions 11858 /// that have been instantiated via C++ template instantiation (called 11859 /// via InstantiateDecl). 11860 /// 11861 /// \param IsMemberSpecialization whether this new function declaration is 11862 /// a member specialization (that replaces any definition provided by the 11863 /// previous declaration). 11864 /// 11865 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11866 /// 11867 /// \returns true if the function declaration is a redeclaration. 11868 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 11869 LookupResult &Previous, 11870 bool IsMemberSpecialization, 11871 bool DeclIsDefn) { 11872 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 11873 "Variably modified return types are not handled here"); 11874 11875 // Determine whether the type of this function should be merged with 11876 // a previous visible declaration. This never happens for functions in C++, 11877 // and always happens in C if the previous declaration was visible. 11878 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 11879 !Previous.isShadowed(); 11880 11881 bool Redeclaration = false; 11882 NamedDecl *OldDecl = nullptr; 11883 bool MayNeedOverloadableChecks = false; 11884 11885 // Merge or overload the declaration with an existing declaration of 11886 // the same name, if appropriate. 11887 if (!Previous.empty()) { 11888 // Determine whether NewFD is an overload of PrevDecl or 11889 // a declaration that requires merging. If it's an overload, 11890 // there's no more work to do here; we'll just add the new 11891 // function to the scope. 11892 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 11893 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 11894 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 11895 Redeclaration = true; 11896 OldDecl = Candidate; 11897 } 11898 } else { 11899 MayNeedOverloadableChecks = true; 11900 switch (CheckOverload(S, NewFD, Previous, OldDecl, 11901 /*NewIsUsingDecl*/ false)) { 11902 case Ovl_Match: 11903 Redeclaration = true; 11904 break; 11905 11906 case Ovl_NonFunction: 11907 Redeclaration = true; 11908 break; 11909 11910 case Ovl_Overload: 11911 Redeclaration = false; 11912 break; 11913 } 11914 } 11915 } 11916 11917 // Check for a previous extern "C" declaration with this name. 11918 if (!Redeclaration && 11919 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 11920 if (!Previous.empty()) { 11921 // This is an extern "C" declaration with the same name as a previous 11922 // declaration, and thus redeclares that entity... 11923 Redeclaration = true; 11924 OldDecl = Previous.getFoundDecl(); 11925 MergeTypeWithPrevious = false; 11926 11927 // ... except in the presence of __attribute__((overloadable)). 11928 if (OldDecl->hasAttr<OverloadableAttr>() || 11929 NewFD->hasAttr<OverloadableAttr>()) { 11930 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 11931 MayNeedOverloadableChecks = true; 11932 Redeclaration = false; 11933 OldDecl = nullptr; 11934 } 11935 } 11936 } 11937 } 11938 11939 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous)) 11940 return Redeclaration; 11941 11942 // PPC MMA non-pointer types are not allowed as function return types. 11943 if (Context.getTargetInfo().getTriple().isPPC64() && 11944 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 11945 NewFD->setInvalidDecl(); 11946 } 11947 11948 CheckConstPureAttributesUsage(*this, NewFD); 11949 11950 // C++11 [dcl.constexpr]p8: 11951 // A constexpr specifier for a non-static member function that is not 11952 // a constructor declares that member function to be const. 11953 // 11954 // This needs to be delayed until we know whether this is an out-of-line 11955 // definition of a static member function. 11956 // 11957 // This rule is not present in C++1y, so we produce a backwards 11958 // compatibility warning whenever it happens in C++11. 11959 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 11960 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 11961 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 11962 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 11963 CXXMethodDecl *OldMD = nullptr; 11964 if (OldDecl) 11965 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 11966 if (!OldMD || !OldMD->isStatic()) { 11967 const FunctionProtoType *FPT = 11968 MD->getType()->castAs<FunctionProtoType>(); 11969 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11970 EPI.TypeQuals.addConst(); 11971 MD->setType(Context.getFunctionType(FPT->getReturnType(), 11972 FPT->getParamTypes(), EPI)); 11973 11974 // Warn that we did this, if we're not performing template instantiation. 11975 // In that case, we'll have warned already when the template was defined. 11976 if (!inTemplateInstantiation()) { 11977 SourceLocation AddConstLoc; 11978 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 11979 .IgnoreParens().getAs<FunctionTypeLoc>()) 11980 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 11981 11982 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 11983 << FixItHint::CreateInsertion(AddConstLoc, " const"); 11984 } 11985 } 11986 } 11987 11988 if (Redeclaration) { 11989 // NewFD and OldDecl represent declarations that need to be 11990 // merged. 11991 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious, 11992 DeclIsDefn)) { 11993 NewFD->setInvalidDecl(); 11994 return Redeclaration; 11995 } 11996 11997 Previous.clear(); 11998 Previous.addDecl(OldDecl); 11999 12000 if (FunctionTemplateDecl *OldTemplateDecl = 12001 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 12002 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 12003 FunctionTemplateDecl *NewTemplateDecl 12004 = NewFD->getDescribedFunctionTemplate(); 12005 assert(NewTemplateDecl && "Template/non-template mismatch"); 12006 12007 // The call to MergeFunctionDecl above may have created some state in 12008 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 12009 // can add it as a redeclaration. 12010 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 12011 12012 NewFD->setPreviousDeclaration(OldFD); 12013 if (NewFD->isCXXClassMember()) { 12014 NewFD->setAccess(OldTemplateDecl->getAccess()); 12015 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 12016 } 12017 12018 // If this is an explicit specialization of a member that is a function 12019 // template, mark it as a member specialization. 12020 if (IsMemberSpecialization && 12021 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 12022 NewTemplateDecl->setMemberSpecialization(); 12023 assert(OldTemplateDecl->isMemberSpecialization()); 12024 // Explicit specializations of a member template do not inherit deleted 12025 // status from the parent member template that they are specializing. 12026 if (OldFD->isDeleted()) { 12027 // FIXME: This assert will not hold in the presence of modules. 12028 assert(OldFD->getCanonicalDecl() == OldFD); 12029 // FIXME: We need an update record for this AST mutation. 12030 OldFD->setDeletedAsWritten(false); 12031 } 12032 } 12033 12034 } else { 12035 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 12036 auto *OldFD = cast<FunctionDecl>(OldDecl); 12037 // This needs to happen first so that 'inline' propagates. 12038 NewFD->setPreviousDeclaration(OldFD); 12039 if (NewFD->isCXXClassMember()) 12040 NewFD->setAccess(OldFD->getAccess()); 12041 } 12042 } 12043 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 12044 !NewFD->getAttr<OverloadableAttr>()) { 12045 assert((Previous.empty() || 12046 llvm::any_of(Previous, 12047 [](const NamedDecl *ND) { 12048 return ND->hasAttr<OverloadableAttr>(); 12049 })) && 12050 "Non-redecls shouldn't happen without overloadable present"); 12051 12052 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 12053 const auto *FD = dyn_cast<FunctionDecl>(ND); 12054 return FD && !FD->hasAttr<OverloadableAttr>(); 12055 }); 12056 12057 if (OtherUnmarkedIter != Previous.end()) { 12058 Diag(NewFD->getLocation(), 12059 diag::err_attribute_overloadable_multiple_unmarked_overloads); 12060 Diag((*OtherUnmarkedIter)->getLocation(), 12061 diag::note_attribute_overloadable_prev_overload) 12062 << false; 12063 12064 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 12065 } 12066 } 12067 12068 if (LangOpts.OpenMP) 12069 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 12070 12071 // Semantic checking for this function declaration (in isolation). 12072 12073 if (getLangOpts().CPlusPlus) { 12074 // C++-specific checks. 12075 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 12076 CheckConstructor(Constructor); 12077 } else if (CXXDestructorDecl *Destructor = 12078 dyn_cast<CXXDestructorDecl>(NewFD)) { 12079 // We check here for invalid destructor names. 12080 // If we have a friend destructor declaration that is dependent, we can't 12081 // diagnose right away because cases like this are still valid: 12082 // template <class T> struct A { friend T::X::~Y(); }; 12083 // struct B { struct Y { ~Y(); }; using X = Y; }; 12084 // template struct A<B>; 12085 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None || 12086 !Destructor->getFunctionObjectParameterType()->isDependentType()) { 12087 CXXRecordDecl *Record = Destructor->getParent(); 12088 QualType ClassType = Context.getTypeDeclType(Record); 12089 12090 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName( 12091 Context.getCanonicalType(ClassType)); 12092 if (NewFD->getDeclName() != Name) { 12093 Diag(NewFD->getLocation(), diag::err_destructor_name); 12094 NewFD->setInvalidDecl(); 12095 return Redeclaration; 12096 } 12097 } 12098 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 12099 if (auto *TD = Guide->getDescribedFunctionTemplate()) 12100 CheckDeductionGuideTemplate(TD); 12101 12102 // A deduction guide is not on the list of entities that can be 12103 // explicitly specialized. 12104 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 12105 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 12106 << /*explicit specialization*/ 1; 12107 } 12108 12109 // Find any virtual functions that this function overrides. 12110 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 12111 if (!Method->isFunctionTemplateSpecialization() && 12112 !Method->getDescribedFunctionTemplate() && 12113 Method->isCanonicalDecl()) { 12114 AddOverriddenMethods(Method->getParent(), Method); 12115 } 12116 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 12117 // C++2a [class.virtual]p6 12118 // A virtual method shall not have a requires-clause. 12119 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 12120 diag::err_constrained_virtual_method); 12121 12122 if (Method->isStatic()) 12123 checkThisInStaticMemberFunctionType(Method); 12124 } 12125 12126 if (Expr *TRC = NewFD->getTrailingRequiresClause()) { 12127 // C++20: dcl.decl.general p4: 12128 // The optional requires-clause ([temp.pre]) in an init-declarator or 12129 // member-declarator shall be present only if the declarator declares a 12130 // templated function ([dcl.fct]). 12131 // 12132 // [temp.pre]/8: 12133 // An entity is templated if it is 12134 // - a template, 12135 // - an entity defined ([basic.def]) or created ([class.temporary]) in a 12136 // templated entity, 12137 // - a member of a templated entity, 12138 // - an enumerator for an enumeration that is a templated entity, or 12139 // - the closure type of a lambda-expression ([expr.prim.lambda.closure]) 12140 // appearing in the declaration of a templated entity. [Note 6: A local 12141 // class, a local or block variable, or a friend function defined in a 12142 // templated entity is a templated entity. — end note] 12143 // 12144 // A templated function is a function template or a function that is 12145 // templated. A templated class is a class template or a class that is 12146 // templated. A templated variable is a variable template or a variable 12147 // that is templated. 12148 12149 bool IsTemplate = NewFD->getDescribedFunctionTemplate(); 12150 bool IsFriend = NewFD->getFriendObjectKind(); 12151 if (!IsTemplate && // -a template 12152 // defined... in a templated entity 12153 !(DeclIsDefn && NewFD->isTemplated()) && 12154 // a member of a templated entity 12155 !(isa<CXXMethodDecl>(NewFD) && NewFD->isTemplated()) && 12156 // Don't complain about instantiations, they've already had these 12157 // rules + others enforced. 12158 !NewFD->isTemplateInstantiation() && 12159 // If the function violates [temp.friend]p9 because it is missing 12160 // a definition, and adding a definition would make it templated, 12161 // then let that error take precedence. 12162 !(!DeclIsDefn && IsFriend && NewFD->isTemplated())) { 12163 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function); 12164 } else if (!DeclIsDefn && !IsTemplate && IsFriend && 12165 !NewFD->isTemplateInstantiation()) { 12166 // C++ [temp.friend]p9: 12167 // A non-template friend declaration with a requires-clause shall be a 12168 // definition. 12169 Diag(NewFD->getBeginLoc(), 12170 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def); 12171 NewFD->setInvalidDecl(); 12172 } 12173 } 12174 12175 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 12176 ActOnConversionDeclarator(Conversion); 12177 12178 // Extra checking for C++ overloaded operators (C++ [over.oper]). 12179 if (NewFD->isOverloadedOperator() && 12180 CheckOverloadedOperatorDeclaration(NewFD)) { 12181 NewFD->setInvalidDecl(); 12182 return Redeclaration; 12183 } 12184 12185 // Extra checking for C++0x literal operators (C++0x [over.literal]). 12186 if (NewFD->getLiteralIdentifier() && 12187 CheckLiteralOperatorDeclaration(NewFD)) { 12188 NewFD->setInvalidDecl(); 12189 return Redeclaration; 12190 } 12191 12192 // In C++, check default arguments now that we have merged decls. Unless 12193 // the lexical context is the class, because in this case this is done 12194 // during delayed parsing anyway. 12195 if (!CurContext->isRecord()) 12196 CheckCXXDefaultArguments(NewFD); 12197 12198 // If this function is declared as being extern "C", then check to see if 12199 // the function returns a UDT (class, struct, or union type) that is not C 12200 // compatible, and if it does, warn the user. 12201 // But, issue any diagnostic on the first declaration only. 12202 if (Previous.empty() && NewFD->isExternC()) { 12203 QualType R = NewFD->getReturnType(); 12204 if (R->isIncompleteType() && !R->isVoidType()) 12205 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 12206 << NewFD << R; 12207 else if (!R.isPODType(Context) && !R->isVoidType() && 12208 !R->isObjCObjectPointerType()) 12209 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 12210 } 12211 12212 // C++1z [dcl.fct]p6: 12213 // [...] whether the function has a non-throwing exception-specification 12214 // [is] part of the function type 12215 // 12216 // This results in an ABI break between C++14 and C++17 for functions whose 12217 // declared type includes an exception-specification in a parameter or 12218 // return type. (Exception specifications on the function itself are OK in 12219 // most cases, and exception specifications are not permitted in most other 12220 // contexts where they could make it into a mangling.) 12221 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 12222 auto HasNoexcept = [&](QualType T) -> bool { 12223 // Strip off declarator chunks that could be between us and a function 12224 // type. We don't need to look far, exception specifications are very 12225 // restricted prior to C++17. 12226 if (auto *RT = T->getAs<ReferenceType>()) 12227 T = RT->getPointeeType(); 12228 else if (T->isAnyPointerType()) 12229 T = T->getPointeeType(); 12230 else if (auto *MPT = T->getAs<MemberPointerType>()) 12231 T = MPT->getPointeeType(); 12232 if (auto *FPT = T->getAs<FunctionProtoType>()) 12233 if (FPT->isNothrow()) 12234 return true; 12235 return false; 12236 }; 12237 12238 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 12239 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 12240 for (QualType T : FPT->param_types()) 12241 AnyNoexcept |= HasNoexcept(T); 12242 if (AnyNoexcept) 12243 Diag(NewFD->getLocation(), 12244 diag::warn_cxx17_compat_exception_spec_in_signature) 12245 << NewFD; 12246 } 12247 12248 if (!Redeclaration && LangOpts.CUDA) 12249 checkCUDATargetOverload(NewFD, Previous); 12250 } 12251 12252 // Check if the function definition uses any AArch64 SME features without 12253 // having the '+sme' feature enabled. 12254 if (DeclIsDefn) { 12255 const auto *Attr = NewFD->getAttr<ArmNewAttr>(); 12256 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>(); 12257 bool UsesZA = Attr && Attr->isNewZA(); 12258 bool UsesZT0 = Attr && Attr->isNewZT0(); 12259 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) { 12260 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12261 UsesSM |= 12262 EPI.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask; 12263 UsesZA |= FunctionType::getArmZAState(EPI.AArch64SMEAttributes) != 12264 FunctionType::ARM_None; 12265 UsesZT0 |= FunctionType::getArmZT0State(EPI.AArch64SMEAttributes) != 12266 FunctionType::ARM_None; 12267 } 12268 12269 if (UsesSM || UsesZA) { 12270 llvm::StringMap<bool> FeatureMap; 12271 Context.getFunctionFeatureMap(FeatureMap, NewFD); 12272 if (!FeatureMap.contains("sme")) { 12273 if (UsesSM) 12274 Diag(NewFD->getLocation(), 12275 diag::err_sme_definition_using_sm_in_non_sme_target); 12276 else 12277 Diag(NewFD->getLocation(), 12278 diag::err_sme_definition_using_za_in_non_sme_target); 12279 } 12280 } 12281 if (UsesZT0) { 12282 llvm::StringMap<bool> FeatureMap; 12283 Context.getFunctionFeatureMap(FeatureMap, NewFD); 12284 if (!FeatureMap.contains("sme2")) { 12285 Diag(NewFD->getLocation(), 12286 diag::err_sme_definition_using_zt0_in_non_sme2_target); 12287 } 12288 } 12289 } 12290 12291 return Redeclaration; 12292 } 12293 12294 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 12295 // C++11 [basic.start.main]p3: 12296 // A program that [...] declares main to be inline, static or 12297 // constexpr is ill-formed. 12298 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 12299 // appear in a declaration of main. 12300 // static main is not an error under C99, but we should warn about it. 12301 // We accept _Noreturn main as an extension. 12302 if (FD->getStorageClass() == SC_Static) 12303 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 12304 ? diag::err_static_main : diag::warn_static_main) 12305 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 12306 if (FD->isInlineSpecified()) 12307 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 12308 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 12309 if (DS.isNoreturnSpecified()) { 12310 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 12311 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 12312 Diag(NoreturnLoc, diag::ext_noreturn_main); 12313 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 12314 << FixItHint::CreateRemoval(NoreturnRange); 12315 } 12316 if (FD->isConstexpr()) { 12317 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 12318 << FD->isConsteval() 12319 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 12320 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 12321 } 12322 12323 if (getLangOpts().OpenCL) { 12324 Diag(FD->getLocation(), diag::err_opencl_no_main) 12325 << FD->hasAttr<OpenCLKernelAttr>(); 12326 FD->setInvalidDecl(); 12327 return; 12328 } 12329 12330 // Functions named main in hlsl are default entries, but don't have specific 12331 // signatures they are required to conform to. 12332 if (getLangOpts().HLSL) 12333 return; 12334 12335 QualType T = FD->getType(); 12336 assert(T->isFunctionType() && "function decl is not of function type"); 12337 const FunctionType* FT = T->castAs<FunctionType>(); 12338 12339 // Set default calling convention for main() 12340 if (FT->getCallConv() != CC_C) { 12341 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 12342 FD->setType(QualType(FT, 0)); 12343 T = Context.getCanonicalType(FD->getType()); 12344 } 12345 12346 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 12347 // In C with GNU extensions we allow main() to have non-integer return 12348 // type, but we should warn about the extension, and we disable the 12349 // implicit-return-zero rule. 12350 12351 // GCC in C mode accepts qualified 'int'. 12352 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 12353 FD->setHasImplicitReturnZero(true); 12354 else { 12355 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 12356 SourceRange RTRange = FD->getReturnTypeSourceRange(); 12357 if (RTRange.isValid()) 12358 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 12359 << FixItHint::CreateReplacement(RTRange, "int"); 12360 } 12361 } else { 12362 // In C and C++, main magically returns 0 if you fall off the end; 12363 // set the flag which tells us that. 12364 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 12365 12366 // All the standards say that main() should return 'int'. 12367 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 12368 FD->setHasImplicitReturnZero(true); 12369 else { 12370 // Otherwise, this is just a flat-out error. 12371 SourceRange RTRange = FD->getReturnTypeSourceRange(); 12372 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 12373 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 12374 : FixItHint()); 12375 FD->setInvalidDecl(true); 12376 } 12377 } 12378 12379 // Treat protoless main() as nullary. 12380 if (isa<FunctionNoProtoType>(FT)) return; 12381 12382 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 12383 unsigned nparams = FTP->getNumParams(); 12384 assert(FD->getNumParams() == nparams); 12385 12386 bool HasExtraParameters = (nparams > 3); 12387 12388 if (FTP->isVariadic()) { 12389 Diag(FD->getLocation(), diag::ext_variadic_main); 12390 // FIXME: if we had information about the location of the ellipsis, we 12391 // could add a FixIt hint to remove it as a parameter. 12392 } 12393 12394 // Darwin passes an undocumented fourth argument of type char**. If 12395 // other platforms start sprouting these, the logic below will start 12396 // getting shifty. 12397 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 12398 HasExtraParameters = false; 12399 12400 if (HasExtraParameters) { 12401 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 12402 FD->setInvalidDecl(true); 12403 nparams = 3; 12404 } 12405 12406 // FIXME: a lot of the following diagnostics would be improved 12407 // if we had some location information about types. 12408 12409 QualType CharPP = 12410 Context.getPointerType(Context.getPointerType(Context.CharTy)); 12411 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 12412 12413 for (unsigned i = 0; i < nparams; ++i) { 12414 QualType AT = FTP->getParamType(i); 12415 12416 bool mismatch = true; 12417 12418 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 12419 mismatch = false; 12420 else if (Expected[i] == CharPP) { 12421 // As an extension, the following forms are okay: 12422 // char const ** 12423 // char const * const * 12424 // char * const * 12425 12426 QualifierCollector qs; 12427 const PointerType* PT; 12428 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 12429 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 12430 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 12431 Context.CharTy)) { 12432 qs.removeConst(); 12433 mismatch = !qs.empty(); 12434 } 12435 } 12436 12437 if (mismatch) { 12438 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 12439 // TODO: suggest replacing given type with expected type 12440 FD->setInvalidDecl(true); 12441 } 12442 } 12443 12444 if (nparams == 1 && !FD->isInvalidDecl()) { 12445 Diag(FD->getLocation(), diag::warn_main_one_arg); 12446 } 12447 12448 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 12449 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 12450 FD->setInvalidDecl(); 12451 } 12452 } 12453 12454 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 12455 12456 // Default calling convention for main and wmain is __cdecl 12457 if (FD->getName() == "main" || FD->getName() == "wmain") 12458 return false; 12459 12460 // Default calling convention for MinGW is __cdecl 12461 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 12462 if (T.isWindowsGNUEnvironment()) 12463 return false; 12464 12465 // Default calling convention for WinMain, wWinMain and DllMain 12466 // is __stdcall on 32 bit Windows 12467 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 12468 return true; 12469 12470 return false; 12471 } 12472 12473 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 12474 QualType T = FD->getType(); 12475 assert(T->isFunctionType() && "function decl is not of function type"); 12476 const FunctionType *FT = T->castAs<FunctionType>(); 12477 12478 // Set an implicit return of 'zero' if the function can return some integral, 12479 // enumeration, pointer or nullptr type. 12480 if (FT->getReturnType()->isIntegralOrEnumerationType() || 12481 FT->getReturnType()->isAnyPointerType() || 12482 FT->getReturnType()->isNullPtrType()) 12483 // DllMain is exempt because a return value of zero means it failed. 12484 if (FD->getName() != "DllMain") 12485 FD->setHasImplicitReturnZero(true); 12486 12487 // Explicity specified calling conventions are applied to MSVC entry points 12488 if (!hasExplicitCallingConv(T)) { 12489 if (isDefaultStdCall(FD, *this)) { 12490 if (FT->getCallConv() != CC_X86StdCall) { 12491 FT = Context.adjustFunctionType( 12492 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 12493 FD->setType(QualType(FT, 0)); 12494 } 12495 } else if (FT->getCallConv() != CC_C) { 12496 FT = Context.adjustFunctionType(FT, 12497 FT->getExtInfo().withCallingConv(CC_C)); 12498 FD->setType(QualType(FT, 0)); 12499 } 12500 } 12501 12502 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 12503 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 12504 FD->setInvalidDecl(); 12505 } 12506 } 12507 12508 void Sema::ActOnHLSLTopLevelFunction(FunctionDecl *FD) { 12509 auto &TargetInfo = getASTContext().getTargetInfo(); 12510 12511 if (FD->getName() != TargetInfo.getTargetOpts().HLSLEntry) 12512 return; 12513 12514 StringRef Env = TargetInfo.getTriple().getEnvironmentName(); 12515 HLSLShaderAttr::ShaderType ShaderType; 12516 if (HLSLShaderAttr::ConvertStrToShaderType(Env, ShaderType)) { 12517 if (const auto *Shader = FD->getAttr<HLSLShaderAttr>()) { 12518 // The entry point is already annotated - check that it matches the 12519 // triple. 12520 if (Shader->getType() != ShaderType) { 12521 Diag(Shader->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch) 12522 << Shader; 12523 FD->setInvalidDecl(); 12524 } 12525 } else { 12526 // Implicitly add the shader attribute if the entry function isn't 12527 // explicitly annotated. 12528 FD->addAttr(HLSLShaderAttr::CreateImplicit(Context, ShaderType, 12529 FD->getBeginLoc())); 12530 } 12531 } else { 12532 switch (TargetInfo.getTriple().getEnvironment()) { 12533 case llvm::Triple::UnknownEnvironment: 12534 case llvm::Triple::Library: 12535 break; 12536 default: 12537 llvm_unreachable("Unhandled environment in triple"); 12538 } 12539 } 12540 } 12541 12542 void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) { 12543 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>(); 12544 assert(ShaderAttr && "Entry point has no shader attribute"); 12545 HLSLShaderAttr::ShaderType ST = ShaderAttr->getType(); 12546 12547 switch (ST) { 12548 case HLSLShaderAttr::Pixel: 12549 case HLSLShaderAttr::Vertex: 12550 case HLSLShaderAttr::Geometry: 12551 case HLSLShaderAttr::Hull: 12552 case HLSLShaderAttr::Domain: 12553 case HLSLShaderAttr::RayGeneration: 12554 case HLSLShaderAttr::Intersection: 12555 case HLSLShaderAttr::AnyHit: 12556 case HLSLShaderAttr::ClosestHit: 12557 case HLSLShaderAttr::Miss: 12558 case HLSLShaderAttr::Callable: 12559 if (const auto *NT = FD->getAttr<HLSLNumThreadsAttr>()) { 12560 DiagnoseHLSLAttrStageMismatch(NT, ST, 12561 {HLSLShaderAttr::Compute, 12562 HLSLShaderAttr::Amplification, 12563 HLSLShaderAttr::Mesh}); 12564 FD->setInvalidDecl(); 12565 } 12566 break; 12567 12568 case HLSLShaderAttr::Compute: 12569 case HLSLShaderAttr::Amplification: 12570 case HLSLShaderAttr::Mesh: 12571 if (!FD->hasAttr<HLSLNumThreadsAttr>()) { 12572 Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads) 12573 << HLSLShaderAttr::ConvertShaderTypeToStr(ST); 12574 FD->setInvalidDecl(); 12575 } 12576 break; 12577 } 12578 12579 for (ParmVarDecl *Param : FD->parameters()) { 12580 if (const auto *AnnotationAttr = Param->getAttr<HLSLAnnotationAttr>()) { 12581 CheckHLSLSemanticAnnotation(FD, Param, AnnotationAttr); 12582 } else { 12583 // FIXME: Handle struct parameters where annotations are on struct fields. 12584 // See: https://github.com/llvm/llvm-project/issues/57875 12585 Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation); 12586 Diag(Param->getLocation(), diag::note_previous_decl) << Param; 12587 FD->setInvalidDecl(); 12588 } 12589 } 12590 // FIXME: Verify return type semantic annotation. 12591 } 12592 12593 void Sema::CheckHLSLSemanticAnnotation( 12594 FunctionDecl *EntryPoint, const Decl *Param, 12595 const HLSLAnnotationAttr *AnnotationAttr) { 12596 auto *ShaderAttr = EntryPoint->getAttr<HLSLShaderAttr>(); 12597 assert(ShaderAttr && "Entry point has no shader attribute"); 12598 HLSLShaderAttr::ShaderType ST = ShaderAttr->getType(); 12599 12600 switch (AnnotationAttr->getKind()) { 12601 case attr::HLSLSV_DispatchThreadID: 12602 case attr::HLSLSV_GroupIndex: 12603 if (ST == HLSLShaderAttr::Compute) 12604 return; 12605 DiagnoseHLSLAttrStageMismatch(AnnotationAttr, ST, 12606 {HLSLShaderAttr::Compute}); 12607 break; 12608 default: 12609 llvm_unreachable("Unknown HLSLAnnotationAttr"); 12610 } 12611 } 12612 12613 void Sema::DiagnoseHLSLAttrStageMismatch( 12614 const Attr *A, HLSLShaderAttr::ShaderType Stage, 12615 std::initializer_list<HLSLShaderAttr::ShaderType> AllowedStages) { 12616 SmallVector<StringRef, 8> StageStrings; 12617 llvm::transform(AllowedStages, std::back_inserter(StageStrings), 12618 [](HLSLShaderAttr::ShaderType ST) { 12619 return StringRef( 12620 HLSLShaderAttr::ConvertShaderTypeToStr(ST)); 12621 }); 12622 Diag(A->getLoc(), diag::err_hlsl_attr_unsupported_in_stage) 12623 << A << HLSLShaderAttr::ConvertShaderTypeToStr(Stage) 12624 << (AllowedStages.size() != 1) << join(StageStrings, ", "); 12625 } 12626 12627 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 12628 // FIXME: Need strict checking. In C89, we need to check for 12629 // any assignment, increment, decrement, function-calls, or 12630 // commas outside of a sizeof. In C99, it's the same list, 12631 // except that the aforementioned are allowed in unevaluated 12632 // expressions. Everything else falls under the 12633 // "may accept other forms of constant expressions" exception. 12634 // 12635 // Regular C++ code will not end up here (exceptions: language extensions, 12636 // OpenCL C++ etc), so the constant expression rules there don't matter. 12637 if (Init->isValueDependent()) { 12638 assert(Init->containsErrors() && 12639 "Dependent code should only occur in error-recovery path."); 12640 return true; 12641 } 12642 const Expr *Culprit; 12643 if (Init->isConstantInitializer(Context, false, &Culprit)) 12644 return false; 12645 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 12646 << Culprit->getSourceRange(); 12647 return true; 12648 } 12649 12650 namespace { 12651 // Visits an initialization expression to see if OrigDecl is evaluated in 12652 // its own initialization and throws a warning if it does. 12653 class SelfReferenceChecker 12654 : public EvaluatedExprVisitor<SelfReferenceChecker> { 12655 Sema &S; 12656 Decl *OrigDecl; 12657 bool isRecordType; 12658 bool isPODType; 12659 bool isReferenceType; 12660 12661 bool isInitList; 12662 llvm::SmallVector<unsigned, 4> InitFieldIndex; 12663 12664 public: 12665 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 12666 12667 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 12668 S(S), OrigDecl(OrigDecl) { 12669 isPODType = false; 12670 isRecordType = false; 12671 isReferenceType = false; 12672 isInitList = false; 12673 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 12674 isPODType = VD->getType().isPODType(S.Context); 12675 isRecordType = VD->getType()->isRecordType(); 12676 isReferenceType = VD->getType()->isReferenceType(); 12677 } 12678 } 12679 12680 // For most expressions, just call the visitor. For initializer lists, 12681 // track the index of the field being initialized since fields are 12682 // initialized in order allowing use of previously initialized fields. 12683 void CheckExpr(Expr *E) { 12684 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 12685 if (!InitList) { 12686 Visit(E); 12687 return; 12688 } 12689 12690 // Track and increment the index here. 12691 isInitList = true; 12692 InitFieldIndex.push_back(0); 12693 for (auto *Child : InitList->children()) { 12694 CheckExpr(cast<Expr>(Child)); 12695 ++InitFieldIndex.back(); 12696 } 12697 InitFieldIndex.pop_back(); 12698 } 12699 12700 // Returns true if MemberExpr is checked and no further checking is needed. 12701 // Returns false if additional checking is required. 12702 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 12703 llvm::SmallVector<FieldDecl*, 4> Fields; 12704 Expr *Base = E; 12705 bool ReferenceField = false; 12706 12707 // Get the field members used. 12708 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 12709 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 12710 if (!FD) 12711 return false; 12712 Fields.push_back(FD); 12713 if (FD->getType()->isReferenceType()) 12714 ReferenceField = true; 12715 Base = ME->getBase()->IgnoreParenImpCasts(); 12716 } 12717 12718 // Keep checking only if the base Decl is the same. 12719 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 12720 if (!DRE || DRE->getDecl() != OrigDecl) 12721 return false; 12722 12723 // A reference field can be bound to an unininitialized field. 12724 if (CheckReference && !ReferenceField) 12725 return true; 12726 12727 // Convert FieldDecls to their index number. 12728 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 12729 for (const FieldDecl *I : llvm::reverse(Fields)) 12730 UsedFieldIndex.push_back(I->getFieldIndex()); 12731 12732 // See if a warning is needed by checking the first difference in index 12733 // numbers. If field being used has index less than the field being 12734 // initialized, then the use is safe. 12735 for (auto UsedIter = UsedFieldIndex.begin(), 12736 UsedEnd = UsedFieldIndex.end(), 12737 OrigIter = InitFieldIndex.begin(), 12738 OrigEnd = InitFieldIndex.end(); 12739 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 12740 if (*UsedIter < *OrigIter) 12741 return true; 12742 if (*UsedIter > *OrigIter) 12743 break; 12744 } 12745 12746 // TODO: Add a different warning which will print the field names. 12747 HandleDeclRefExpr(DRE); 12748 return true; 12749 } 12750 12751 // For most expressions, the cast is directly above the DeclRefExpr. 12752 // For conditional operators, the cast can be outside the conditional 12753 // operator if both expressions are DeclRefExpr's. 12754 void HandleValue(Expr *E) { 12755 E = E->IgnoreParens(); 12756 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 12757 HandleDeclRefExpr(DRE); 12758 return; 12759 } 12760 12761 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 12762 Visit(CO->getCond()); 12763 HandleValue(CO->getTrueExpr()); 12764 HandleValue(CO->getFalseExpr()); 12765 return; 12766 } 12767 12768 if (BinaryConditionalOperator *BCO = 12769 dyn_cast<BinaryConditionalOperator>(E)) { 12770 Visit(BCO->getCond()); 12771 HandleValue(BCO->getFalseExpr()); 12772 return; 12773 } 12774 12775 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 12776 if (Expr *SE = OVE->getSourceExpr()) 12777 HandleValue(SE); 12778 return; 12779 } 12780 12781 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12782 if (BO->getOpcode() == BO_Comma) { 12783 Visit(BO->getLHS()); 12784 HandleValue(BO->getRHS()); 12785 return; 12786 } 12787 } 12788 12789 if (isa<MemberExpr>(E)) { 12790 if (isInitList) { 12791 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 12792 false /*CheckReference*/)) 12793 return; 12794 } 12795 12796 Expr *Base = E->IgnoreParenImpCasts(); 12797 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 12798 // Check for static member variables and don't warn on them. 12799 if (!isa<FieldDecl>(ME->getMemberDecl())) 12800 return; 12801 Base = ME->getBase()->IgnoreParenImpCasts(); 12802 } 12803 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 12804 HandleDeclRefExpr(DRE); 12805 return; 12806 } 12807 12808 Visit(E); 12809 } 12810 12811 // Reference types not handled in HandleValue are handled here since all 12812 // uses of references are bad, not just r-value uses. 12813 void VisitDeclRefExpr(DeclRefExpr *E) { 12814 if (isReferenceType) 12815 HandleDeclRefExpr(E); 12816 } 12817 12818 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12819 if (E->getCastKind() == CK_LValueToRValue) { 12820 HandleValue(E->getSubExpr()); 12821 return; 12822 } 12823 12824 Inherited::VisitImplicitCastExpr(E); 12825 } 12826 12827 void VisitMemberExpr(MemberExpr *E) { 12828 if (isInitList) { 12829 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 12830 return; 12831 } 12832 12833 // Don't warn on arrays since they can be treated as pointers. 12834 if (E->getType()->canDecayToPointerType()) return; 12835 12836 // Warn when a non-static method call is followed by non-static member 12837 // field accesses, which is followed by a DeclRefExpr. 12838 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 12839 bool Warn = (MD && !MD->isStatic()); 12840 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 12841 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 12842 if (!isa<FieldDecl>(ME->getMemberDecl())) 12843 Warn = false; 12844 Base = ME->getBase()->IgnoreParenImpCasts(); 12845 } 12846 12847 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 12848 if (Warn) 12849 HandleDeclRefExpr(DRE); 12850 return; 12851 } 12852 12853 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 12854 // Visit that expression. 12855 Visit(Base); 12856 } 12857 12858 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 12859 Expr *Callee = E->getCallee(); 12860 12861 if (isa<UnresolvedLookupExpr>(Callee)) 12862 return Inherited::VisitCXXOperatorCallExpr(E); 12863 12864 Visit(Callee); 12865 for (auto Arg: E->arguments()) 12866 HandleValue(Arg->IgnoreParenImpCasts()); 12867 } 12868 12869 void VisitUnaryOperator(UnaryOperator *E) { 12870 // For POD record types, addresses of its own members are well-defined. 12871 if (E->getOpcode() == UO_AddrOf && isRecordType && 12872 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 12873 if (!isPODType) 12874 HandleValue(E->getSubExpr()); 12875 return; 12876 } 12877 12878 if (E->isIncrementDecrementOp()) { 12879 HandleValue(E->getSubExpr()); 12880 return; 12881 } 12882 12883 Inherited::VisitUnaryOperator(E); 12884 } 12885 12886 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 12887 12888 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12889 if (E->getConstructor()->isCopyConstructor()) { 12890 Expr *ArgExpr = E->getArg(0); 12891 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 12892 if (ILE->getNumInits() == 1) 12893 ArgExpr = ILE->getInit(0); 12894 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 12895 if (ICE->getCastKind() == CK_NoOp) 12896 ArgExpr = ICE->getSubExpr(); 12897 HandleValue(ArgExpr); 12898 return; 12899 } 12900 Inherited::VisitCXXConstructExpr(E); 12901 } 12902 12903 void VisitCallExpr(CallExpr *E) { 12904 // Treat std::move as a use. 12905 if (E->isCallToStdMove()) { 12906 HandleValue(E->getArg(0)); 12907 return; 12908 } 12909 12910 Inherited::VisitCallExpr(E); 12911 } 12912 12913 void VisitBinaryOperator(BinaryOperator *E) { 12914 if (E->isCompoundAssignmentOp()) { 12915 HandleValue(E->getLHS()); 12916 Visit(E->getRHS()); 12917 return; 12918 } 12919 12920 Inherited::VisitBinaryOperator(E); 12921 } 12922 12923 // A custom visitor for BinaryConditionalOperator is needed because the 12924 // regular visitor would check the condition and true expression separately 12925 // but both point to the same place giving duplicate diagnostics. 12926 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 12927 Visit(E->getCond()); 12928 Visit(E->getFalseExpr()); 12929 } 12930 12931 void HandleDeclRefExpr(DeclRefExpr *DRE) { 12932 Decl* ReferenceDecl = DRE->getDecl(); 12933 if (OrigDecl != ReferenceDecl) return; 12934 unsigned diag; 12935 if (isReferenceType) { 12936 diag = diag::warn_uninit_self_reference_in_reference_init; 12937 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 12938 diag = diag::warn_static_self_reference_in_init; 12939 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 12940 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 12941 DRE->getDecl()->getType()->isRecordType()) { 12942 diag = diag::warn_uninit_self_reference_in_init; 12943 } else { 12944 // Local variables will be handled by the CFG analysis. 12945 return; 12946 } 12947 12948 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 12949 S.PDiag(diag) 12950 << DRE->getDecl() << OrigDecl->getLocation() 12951 << DRE->getSourceRange()); 12952 } 12953 }; 12954 12955 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 12956 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 12957 bool DirectInit) { 12958 // Parameters arguments are occassionially constructed with itself, 12959 // for instance, in recursive functions. Skip them. 12960 if (isa<ParmVarDecl>(OrigDecl)) 12961 return; 12962 12963 E = E->IgnoreParens(); 12964 12965 // Skip checking T a = a where T is not a record or reference type. 12966 // Doing so is a way to silence uninitialized warnings. 12967 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 12968 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 12969 if (ICE->getCastKind() == CK_LValueToRValue) 12970 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 12971 if (DRE->getDecl() == OrigDecl) 12972 return; 12973 12974 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 12975 } 12976 } // end anonymous namespace 12977 12978 namespace { 12979 // Simple wrapper to add the name of a variable or (if no variable is 12980 // available) a DeclarationName into a diagnostic. 12981 struct VarDeclOrName { 12982 VarDecl *VDecl; 12983 DeclarationName Name; 12984 12985 friend const Sema::SemaDiagnosticBuilder & 12986 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 12987 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 12988 } 12989 }; 12990 } // end anonymous namespace 12991 12992 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 12993 DeclarationName Name, QualType Type, 12994 TypeSourceInfo *TSI, 12995 SourceRange Range, bool DirectInit, 12996 Expr *Init) { 12997 bool IsInitCapture = !VDecl; 12998 assert((!VDecl || !VDecl->isInitCapture()) && 12999 "init captures are expected to be deduced prior to initialization"); 13000 13001 VarDeclOrName VN{VDecl, Name}; 13002 13003 DeducedType *Deduced = Type->getContainedDeducedType(); 13004 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 13005 13006 // Diagnose auto array declarations in C23, unless it's a supported extension. 13007 if (getLangOpts().C23 && Type->isArrayType() && 13008 !isa_and_present<StringLiteral, InitListExpr>(Init)) { 13009 Diag(Range.getBegin(), diag::err_auto_not_allowed) 13010 << (int)Deduced->getContainedAutoType()->getKeyword() 13011 << /*in array decl*/ 23 << Range; 13012 return QualType(); 13013 } 13014 13015 // C++11 [dcl.spec.auto]p3 13016 if (!Init) { 13017 assert(VDecl && "no init for init capture deduction?"); 13018 13019 // Except for class argument deduction, and then for an initializing 13020 // declaration only, i.e. no static at class scope or extern. 13021 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 13022 VDecl->hasExternalStorage() || 13023 VDecl->isStaticDataMember()) { 13024 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 13025 << VDecl->getDeclName() << Type; 13026 return QualType(); 13027 } 13028 } 13029 13030 ArrayRef<Expr*> DeduceInits; 13031 if (Init) 13032 DeduceInits = Init; 13033 13034 auto *PL = dyn_cast_if_present<ParenListExpr>(Init); 13035 if (DirectInit && PL) 13036 DeduceInits = PL->exprs(); 13037 13038 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 13039 assert(VDecl && "non-auto type for init capture deduction?"); 13040 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 13041 InitializationKind Kind = InitializationKind::CreateForInit( 13042 VDecl->getLocation(), DirectInit, Init); 13043 // FIXME: Initialization should not be taking a mutable list of inits. 13044 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 13045 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 13046 InitsCopy); 13047 } 13048 13049 if (DirectInit) { 13050 if (auto *IL = dyn_cast<InitListExpr>(Init)) 13051 DeduceInits = IL->inits(); 13052 } 13053 13054 // Deduction only works if we have exactly one source expression. 13055 if (DeduceInits.empty()) { 13056 // It isn't possible to write this directly, but it is possible to 13057 // end up in this situation with "auto x(some_pack...);" 13058 Diag(Init->getBeginLoc(), IsInitCapture 13059 ? diag::err_init_capture_no_expression 13060 : diag::err_auto_var_init_no_expression) 13061 << VN << Type << Range; 13062 return QualType(); 13063 } 13064 13065 if (DeduceInits.size() > 1) { 13066 Diag(DeduceInits[1]->getBeginLoc(), 13067 IsInitCapture ? diag::err_init_capture_multiple_expressions 13068 : diag::err_auto_var_init_multiple_expressions) 13069 << VN << Type << Range; 13070 return QualType(); 13071 } 13072 13073 Expr *DeduceInit = DeduceInits[0]; 13074 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 13075 Diag(Init->getBeginLoc(), IsInitCapture 13076 ? diag::err_init_capture_paren_braces 13077 : diag::err_auto_var_init_paren_braces) 13078 << isa<InitListExpr>(Init) << VN << Type << Range; 13079 return QualType(); 13080 } 13081 13082 // Expressions default to 'id' when we're in a debugger. 13083 bool DefaultedAnyToId = false; 13084 if (getLangOpts().DebuggerCastResultToId && 13085 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 13086 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 13087 if (Result.isInvalid()) { 13088 return QualType(); 13089 } 13090 Init = Result.get(); 13091 DefaultedAnyToId = true; 13092 } 13093 13094 // C++ [dcl.decomp]p1: 13095 // If the assignment-expression [...] has array type A and no ref-qualifier 13096 // is present, e has type cv A 13097 if (VDecl && isa<DecompositionDecl>(VDecl) && 13098 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 13099 DeduceInit->getType()->isConstantArrayType()) 13100 return Context.getQualifiedType(DeduceInit->getType(), 13101 Type.getQualifiers()); 13102 13103 QualType DeducedType; 13104 TemplateDeductionInfo Info(DeduceInit->getExprLoc()); 13105 TemplateDeductionResult Result = 13106 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info); 13107 if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) { 13108 if (!IsInitCapture) 13109 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 13110 else if (isa<InitListExpr>(Init)) 13111 Diag(Range.getBegin(), 13112 diag::err_init_capture_deduction_failure_from_init_list) 13113 << VN 13114 << (DeduceInit->getType().isNull() ? TSI->getType() 13115 : DeduceInit->getType()) 13116 << DeduceInit->getSourceRange(); 13117 else 13118 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 13119 << VN << TSI->getType() 13120 << (DeduceInit->getType().isNull() ? TSI->getType() 13121 : DeduceInit->getType()) 13122 << DeduceInit->getSourceRange(); 13123 } 13124 13125 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 13126 // 'id' instead of a specific object type prevents most of our usual 13127 // checks. 13128 // We only want to warn outside of template instantiations, though: 13129 // inside a template, the 'id' could have come from a parameter. 13130 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 13131 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 13132 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 13133 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 13134 } 13135 13136 return DeducedType; 13137 } 13138 13139 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 13140 Expr *Init) { 13141 assert(!Init || !Init->containsErrors()); 13142 QualType DeducedType = deduceVarTypeFromInitializer( 13143 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 13144 VDecl->getSourceRange(), DirectInit, Init); 13145 if (DeducedType.isNull()) { 13146 VDecl->setInvalidDecl(); 13147 return true; 13148 } 13149 13150 VDecl->setType(DeducedType); 13151 assert(VDecl->isLinkageValid()); 13152 13153 // In ARC, infer lifetime. 13154 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 13155 VDecl->setInvalidDecl(); 13156 13157 if (getLangOpts().OpenCL) 13158 deduceOpenCLAddressSpace(VDecl); 13159 13160 // If this is a redeclaration, check that the type we just deduced matches 13161 // the previously declared type. 13162 if (VarDecl *Old = VDecl->getPreviousDecl()) { 13163 // We never need to merge the type, because we cannot form an incomplete 13164 // array of auto, nor deduce such a type. 13165 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 13166 } 13167 13168 // Check the deduced type is valid for a variable declaration. 13169 CheckVariableDeclarationType(VDecl); 13170 return VDecl->isInvalidDecl(); 13171 } 13172 13173 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 13174 SourceLocation Loc) { 13175 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 13176 Init = EWC->getSubExpr(); 13177 13178 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 13179 Init = CE->getSubExpr(); 13180 13181 QualType InitType = Init->getType(); 13182 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 13183 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 13184 "shouldn't be called if type doesn't have a non-trivial C struct"); 13185 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 13186 for (auto *I : ILE->inits()) { 13187 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 13188 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13189 continue; 13190 SourceLocation SL = I->getExprLoc(); 13191 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 13192 } 13193 return; 13194 } 13195 13196 if (isa<ImplicitValueInitExpr>(Init)) { 13197 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 13198 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 13199 NTCUK_Init); 13200 } else { 13201 // Assume all other explicit initializers involving copying some existing 13202 // object. 13203 // TODO: ignore any explicit initializers where we can guarantee 13204 // copy-elision. 13205 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 13206 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 13207 } 13208 } 13209 13210 namespace { 13211 13212 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 13213 // Ignore unavailable fields. A field can be marked as unavailable explicitly 13214 // in the source code or implicitly by the compiler if it is in a union 13215 // defined in a system header and has non-trivial ObjC ownership 13216 // qualifications. We don't want those fields to participate in determining 13217 // whether the containing union is non-trivial. 13218 return FD->hasAttr<UnavailableAttr>(); 13219 } 13220 13221 struct DiagNonTrivalCUnionDefaultInitializeVisitor 13222 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 13223 void> { 13224 using Super = 13225 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 13226 void>; 13227 13228 DiagNonTrivalCUnionDefaultInitializeVisitor( 13229 QualType OrigTy, SourceLocation OrigLoc, 13230 Sema::NonTrivialCUnionContext UseContext, Sema &S) 13231 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 13232 13233 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 13234 const FieldDecl *FD, bool InNonTrivialUnion) { 13235 if (const auto *AT = S.Context.getAsArrayType(QT)) 13236 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 13237 InNonTrivialUnion); 13238 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 13239 } 13240 13241 void visitARCStrong(QualType QT, const FieldDecl *FD, 13242 bool InNonTrivialUnion) { 13243 if (InNonTrivialUnion) 13244 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13245 << 1 << 0 << QT << FD->getName(); 13246 } 13247 13248 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13249 if (InNonTrivialUnion) 13250 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13251 << 1 << 0 << QT << FD->getName(); 13252 } 13253 13254 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13255 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 13256 if (RD->isUnion()) { 13257 if (OrigLoc.isValid()) { 13258 bool IsUnion = false; 13259 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 13260 IsUnion = OrigRD->isUnion(); 13261 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 13262 << 0 << OrigTy << IsUnion << UseContext; 13263 // Reset OrigLoc so that this diagnostic is emitted only once. 13264 OrigLoc = SourceLocation(); 13265 } 13266 InNonTrivialUnion = true; 13267 } 13268 13269 if (InNonTrivialUnion) 13270 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 13271 << 0 << 0 << QT.getUnqualifiedType() << ""; 13272 13273 for (const FieldDecl *FD : RD->fields()) 13274 if (!shouldIgnoreForRecordTriviality(FD)) 13275 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 13276 } 13277 13278 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 13279 13280 // The non-trivial C union type or the struct/union type that contains a 13281 // non-trivial C union. 13282 QualType OrigTy; 13283 SourceLocation OrigLoc; 13284 Sema::NonTrivialCUnionContext UseContext; 13285 Sema &S; 13286 }; 13287 13288 struct DiagNonTrivalCUnionDestructedTypeVisitor 13289 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 13290 using Super = 13291 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 13292 13293 DiagNonTrivalCUnionDestructedTypeVisitor( 13294 QualType OrigTy, SourceLocation OrigLoc, 13295 Sema::NonTrivialCUnionContext UseContext, Sema &S) 13296 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 13297 13298 void visitWithKind(QualType::DestructionKind DK, QualType QT, 13299 const FieldDecl *FD, bool InNonTrivialUnion) { 13300 if (const auto *AT = S.Context.getAsArrayType(QT)) 13301 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 13302 InNonTrivialUnion); 13303 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 13304 } 13305 13306 void visitARCStrong(QualType QT, const FieldDecl *FD, 13307 bool InNonTrivialUnion) { 13308 if (InNonTrivialUnion) 13309 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13310 << 1 << 1 << QT << FD->getName(); 13311 } 13312 13313 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13314 if (InNonTrivialUnion) 13315 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13316 << 1 << 1 << QT << FD->getName(); 13317 } 13318 13319 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13320 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 13321 if (RD->isUnion()) { 13322 if (OrigLoc.isValid()) { 13323 bool IsUnion = false; 13324 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 13325 IsUnion = OrigRD->isUnion(); 13326 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 13327 << 1 << OrigTy << IsUnion << UseContext; 13328 // Reset OrigLoc so that this diagnostic is emitted only once. 13329 OrigLoc = SourceLocation(); 13330 } 13331 InNonTrivialUnion = true; 13332 } 13333 13334 if (InNonTrivialUnion) 13335 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 13336 << 0 << 1 << QT.getUnqualifiedType() << ""; 13337 13338 for (const FieldDecl *FD : RD->fields()) 13339 if (!shouldIgnoreForRecordTriviality(FD)) 13340 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 13341 } 13342 13343 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 13344 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 13345 bool InNonTrivialUnion) {} 13346 13347 // The non-trivial C union type or the struct/union type that contains a 13348 // non-trivial C union. 13349 QualType OrigTy; 13350 SourceLocation OrigLoc; 13351 Sema::NonTrivialCUnionContext UseContext; 13352 Sema &S; 13353 }; 13354 13355 struct DiagNonTrivalCUnionCopyVisitor 13356 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 13357 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 13358 13359 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 13360 Sema::NonTrivialCUnionContext UseContext, 13361 Sema &S) 13362 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 13363 13364 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 13365 const FieldDecl *FD, bool InNonTrivialUnion) { 13366 if (const auto *AT = S.Context.getAsArrayType(QT)) 13367 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 13368 InNonTrivialUnion); 13369 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 13370 } 13371 13372 void visitARCStrong(QualType QT, const FieldDecl *FD, 13373 bool InNonTrivialUnion) { 13374 if (InNonTrivialUnion) 13375 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13376 << 1 << 2 << QT << FD->getName(); 13377 } 13378 13379 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13380 if (InNonTrivialUnion) 13381 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13382 << 1 << 2 << QT << FD->getName(); 13383 } 13384 13385 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13386 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 13387 if (RD->isUnion()) { 13388 if (OrigLoc.isValid()) { 13389 bool IsUnion = false; 13390 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 13391 IsUnion = OrigRD->isUnion(); 13392 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 13393 << 2 << OrigTy << IsUnion << UseContext; 13394 // Reset OrigLoc so that this diagnostic is emitted only once. 13395 OrigLoc = SourceLocation(); 13396 } 13397 InNonTrivialUnion = true; 13398 } 13399 13400 if (InNonTrivialUnion) 13401 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 13402 << 0 << 2 << QT.getUnqualifiedType() << ""; 13403 13404 for (const FieldDecl *FD : RD->fields()) 13405 if (!shouldIgnoreForRecordTriviality(FD)) 13406 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 13407 } 13408 13409 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 13410 const FieldDecl *FD, bool InNonTrivialUnion) {} 13411 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 13412 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 13413 bool InNonTrivialUnion) {} 13414 13415 // The non-trivial C union type or the struct/union type that contains a 13416 // non-trivial C union. 13417 QualType OrigTy; 13418 SourceLocation OrigLoc; 13419 Sema::NonTrivialCUnionContext UseContext; 13420 Sema &S; 13421 }; 13422 13423 } // namespace 13424 13425 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 13426 NonTrivialCUnionContext UseContext, 13427 unsigned NonTrivialKind) { 13428 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 13429 QT.hasNonTrivialToPrimitiveDestructCUnion() || 13430 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 13431 "shouldn't be called if type doesn't have a non-trivial C union"); 13432 13433 if ((NonTrivialKind & NTCUK_Init) && 13434 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 13435 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 13436 .visit(QT, nullptr, false); 13437 if ((NonTrivialKind & NTCUK_Destruct) && 13438 QT.hasNonTrivialToPrimitiveDestructCUnion()) 13439 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 13440 .visit(QT, nullptr, false); 13441 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 13442 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 13443 .visit(QT, nullptr, false); 13444 } 13445 13446 /// AddInitializerToDecl - Adds the initializer Init to the 13447 /// declaration dcl. If DirectInit is true, this is C++ direct 13448 /// initialization rather than copy initialization. 13449 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 13450 // If there is no declaration, there was an error parsing it. Just ignore 13451 // the initializer. 13452 if (!RealDecl || RealDecl->isInvalidDecl()) { 13453 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 13454 return; 13455 } 13456 13457 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 13458 // Pure-specifiers are handled in ActOnPureSpecifier. 13459 Diag(Method->getLocation(), diag::err_member_function_initialization) 13460 << Method->getDeclName() << Init->getSourceRange(); 13461 Method->setInvalidDecl(); 13462 return; 13463 } 13464 13465 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 13466 if (!VDecl) { 13467 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 13468 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 13469 RealDecl->setInvalidDecl(); 13470 return; 13471 } 13472 13473 // WebAssembly tables can't be used to initialise a variable. 13474 if (Init && !Init->getType().isNull() && 13475 Init->getType()->isWebAssemblyTableType()) { 13476 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0; 13477 VDecl->setInvalidDecl(); 13478 return; 13479 } 13480 13481 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 13482 if (VDecl->getType()->isUndeducedType()) { 13483 // Attempt typo correction early so that the type of the init expression can 13484 // be deduced based on the chosen correction if the original init contains a 13485 // TypoExpr. 13486 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 13487 if (!Res.isUsable()) { 13488 // There are unresolved typos in Init, just drop them. 13489 // FIXME: improve the recovery strategy to preserve the Init. 13490 RealDecl->setInvalidDecl(); 13491 return; 13492 } 13493 if (Res.get()->containsErrors()) { 13494 // Invalidate the decl as we don't know the type for recovery-expr yet. 13495 RealDecl->setInvalidDecl(); 13496 VDecl->setInit(Res.get()); 13497 return; 13498 } 13499 Init = Res.get(); 13500 13501 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 13502 return; 13503 } 13504 13505 // dllimport cannot be used on variable definitions. 13506 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 13507 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 13508 VDecl->setInvalidDecl(); 13509 return; 13510 } 13511 13512 // C99 6.7.8p5. If the declaration of an identifier has block scope, and 13513 // the identifier has external or internal linkage, the declaration shall 13514 // have no initializer for the identifier. 13515 // C++14 [dcl.init]p5 is the same restriction for C++. 13516 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 13517 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 13518 VDecl->setInvalidDecl(); 13519 return; 13520 } 13521 13522 if (!VDecl->getType()->isDependentType()) { 13523 // A definition must end up with a complete type, which means it must be 13524 // complete with the restriction that an array type might be completed by 13525 // the initializer; note that later code assumes this restriction. 13526 QualType BaseDeclType = VDecl->getType(); 13527 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 13528 BaseDeclType = Array->getElementType(); 13529 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 13530 diag::err_typecheck_decl_incomplete_type)) { 13531 RealDecl->setInvalidDecl(); 13532 return; 13533 } 13534 13535 // The variable can not have an abstract class type. 13536 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 13537 diag::err_abstract_type_in_decl, 13538 AbstractVariableType)) 13539 VDecl->setInvalidDecl(); 13540 } 13541 13542 // C++ [module.import/6] external definitions are not permitted in header 13543 // units. 13544 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() && 13545 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() && 13546 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() && 13547 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl)) { 13548 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit); 13549 VDecl->setInvalidDecl(); 13550 } 13551 13552 // If adding the initializer will turn this declaration into a definition, 13553 // and we already have a definition for this variable, diagnose or otherwise 13554 // handle the situation. 13555 if (VarDecl *Def = VDecl->getDefinition()) 13556 if (Def != VDecl && 13557 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 13558 !VDecl->isThisDeclarationADemotedDefinition() && 13559 checkVarDeclRedefinition(Def, VDecl)) 13560 return; 13561 13562 if (getLangOpts().CPlusPlus) { 13563 // C++ [class.static.data]p4 13564 // If a static data member is of const integral or const 13565 // enumeration type, its declaration in the class definition can 13566 // specify a constant-initializer which shall be an integral 13567 // constant expression (5.19). In that case, the member can appear 13568 // in integral constant expressions. The member shall still be 13569 // defined in a namespace scope if it is used in the program and the 13570 // namespace scope definition shall not contain an initializer. 13571 // 13572 // We already performed a redefinition check above, but for static 13573 // data members we also need to check whether there was an in-class 13574 // declaration with an initializer. 13575 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 13576 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 13577 << VDecl->getDeclName(); 13578 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 13579 diag::note_previous_initializer) 13580 << 0; 13581 return; 13582 } 13583 13584 if (VDecl->hasLocalStorage()) 13585 setFunctionHasBranchProtectedScope(); 13586 13587 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 13588 VDecl->setInvalidDecl(); 13589 return; 13590 } 13591 } 13592 13593 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 13594 // a kernel function cannot be initialized." 13595 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 13596 Diag(VDecl->getLocation(), diag::err_local_cant_init); 13597 VDecl->setInvalidDecl(); 13598 return; 13599 } 13600 13601 // The LoaderUninitialized attribute acts as a definition (of undef). 13602 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 13603 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 13604 VDecl->setInvalidDecl(); 13605 return; 13606 } 13607 13608 // Get the decls type and save a reference for later, since 13609 // CheckInitializerTypes may change it. 13610 QualType DclT = VDecl->getType(), SavT = DclT; 13611 13612 // Expressions default to 'id' when we're in a debugger 13613 // and we are assigning it to a variable of Objective-C pointer type. 13614 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 13615 Init->getType() == Context.UnknownAnyTy) { 13616 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 13617 if (Result.isInvalid()) { 13618 VDecl->setInvalidDecl(); 13619 return; 13620 } 13621 Init = Result.get(); 13622 } 13623 13624 // Perform the initialization. 13625 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 13626 bool IsParenListInit = false; 13627 if (!VDecl->isInvalidDecl()) { 13628 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 13629 InitializationKind Kind = InitializationKind::CreateForInit( 13630 VDecl->getLocation(), DirectInit, Init); 13631 13632 MultiExprArg Args = Init; 13633 if (CXXDirectInit) 13634 Args = MultiExprArg(CXXDirectInit->getExprs(), 13635 CXXDirectInit->getNumExprs()); 13636 13637 // Try to correct any TypoExprs in the initialization arguments. 13638 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 13639 ExprResult Res = CorrectDelayedTyposInExpr( 13640 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 13641 [this, Entity, Kind](Expr *E) { 13642 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 13643 return Init.Failed() ? ExprError() : E; 13644 }); 13645 if (Res.isInvalid()) { 13646 VDecl->setInvalidDecl(); 13647 } else if (Res.get() != Args[Idx]) { 13648 Args[Idx] = Res.get(); 13649 } 13650 } 13651 if (VDecl->isInvalidDecl()) 13652 return; 13653 13654 InitializationSequence InitSeq(*this, Entity, Kind, Args, 13655 /*TopLevelOfInitList=*/false, 13656 /*TreatUnavailableAsInvalid=*/false); 13657 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 13658 if (Result.isInvalid()) { 13659 // If the provided initializer fails to initialize the var decl, 13660 // we attach a recovery expr for better recovery. 13661 auto RecoveryExpr = 13662 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 13663 if (RecoveryExpr.get()) 13664 VDecl->setInit(RecoveryExpr.get()); 13665 // In general, for error recovery purposes, the initalizer doesn't play 13666 // part in the valid bit of the declaration. There are a few exceptions: 13667 // 1) if the var decl has a deduced auto type, and the type cannot be 13668 // deduced by an invalid initializer; 13669 // 2) if the var decl is decompsition decl with a non-deduced type, and 13670 // the initialization fails (e.g. `int [a] = {1, 2};`); 13671 // Case 1) was already handled elsewhere. 13672 if (isa<DecompositionDecl>(VDecl)) // Case 2) 13673 VDecl->setInvalidDecl(); 13674 return; 13675 } 13676 13677 Init = Result.getAs<Expr>(); 13678 IsParenListInit = !InitSeq.steps().empty() && 13679 InitSeq.step_begin()->Kind == 13680 InitializationSequence::SK_ParenthesizedListInit; 13681 QualType VDeclType = VDecl->getType(); 13682 if (Init && !Init->getType().isNull() && 13683 !Init->getType()->isDependentType() && !VDeclType->isDependentType() && 13684 Context.getAsIncompleteArrayType(VDeclType) && 13685 Context.getAsIncompleteArrayType(Init->getType())) { 13686 // Bail out if it is not possible to deduce array size from the 13687 // initializer. 13688 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type) 13689 << VDeclType; 13690 VDecl->setInvalidDecl(); 13691 return; 13692 } 13693 } 13694 13695 // Check for self-references within variable initializers. 13696 // Variables declared within a function/method body (except for references) 13697 // are handled by a dataflow analysis. 13698 // This is undefined behavior in C++, but valid in C. 13699 if (getLangOpts().CPlusPlus) 13700 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 13701 VDecl->getType()->isReferenceType()) 13702 CheckSelfReference(*this, RealDecl, Init, DirectInit); 13703 13704 // If the type changed, it means we had an incomplete type that was 13705 // completed by the initializer. For example: 13706 // int ary[] = { 1, 3, 5 }; 13707 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 13708 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 13709 VDecl->setType(DclT); 13710 13711 if (!VDecl->isInvalidDecl()) { 13712 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 13713 13714 if (VDecl->hasAttr<BlocksAttr>()) 13715 checkRetainCycles(VDecl, Init); 13716 13717 // It is safe to assign a weak reference into a strong variable. 13718 // Although this code can still have problems: 13719 // id x = self.weakProp; 13720 // id y = self.weakProp; 13721 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13722 // paths through the function. This should be revisited if 13723 // -Wrepeated-use-of-weak is made flow-sensitive. 13724 if (FunctionScopeInfo *FSI = getCurFunction()) 13725 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 13726 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 13727 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13728 Init->getBeginLoc())) 13729 FSI->markSafeWeakUse(Init); 13730 } 13731 13732 // The initialization is usually a full-expression. 13733 // 13734 // FIXME: If this is a braced initialization of an aggregate, it is not 13735 // an expression, and each individual field initializer is a separate 13736 // full-expression. For instance, in: 13737 // 13738 // struct Temp { ~Temp(); }; 13739 // struct S { S(Temp); }; 13740 // struct T { S a, b; } t = { Temp(), Temp() } 13741 // 13742 // we should destroy the first Temp before constructing the second. 13743 ExprResult Result = 13744 ActOnFinishFullExpr(Init, VDecl->getLocation(), 13745 /*DiscardedValue*/ false, VDecl->isConstexpr()); 13746 if (Result.isInvalid()) { 13747 VDecl->setInvalidDecl(); 13748 return; 13749 } 13750 Init = Result.get(); 13751 13752 // Attach the initializer to the decl. 13753 VDecl->setInit(Init); 13754 13755 if (VDecl->isLocalVarDecl()) { 13756 // Don't check the initializer if the declaration is malformed. 13757 if (VDecl->isInvalidDecl()) { 13758 // do nothing 13759 13760 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 13761 // This is true even in C++ for OpenCL. 13762 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 13763 CheckForConstantInitializer(Init, DclT); 13764 13765 // Otherwise, C++ does not restrict the initializer. 13766 } else if (getLangOpts().CPlusPlus) { 13767 // do nothing 13768 13769 // C99 6.7.8p4: All the expressions in an initializer for an object that has 13770 // static storage duration shall be constant expressions or string literals. 13771 } else if (VDecl->getStorageClass() == SC_Static) { 13772 CheckForConstantInitializer(Init, DclT); 13773 13774 // C89 is stricter than C99 for aggregate initializers. 13775 // C89 6.5.7p3: All the expressions [...] in an initializer list 13776 // for an object that has aggregate or union type shall be 13777 // constant expressions. 13778 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 13779 isa<InitListExpr>(Init)) { 13780 const Expr *Culprit; 13781 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 13782 Diag(Culprit->getExprLoc(), 13783 diag::ext_aggregate_init_not_constant) 13784 << Culprit->getSourceRange(); 13785 } 13786 } 13787 13788 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 13789 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 13790 if (VDecl->hasLocalStorage()) 13791 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13792 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 13793 VDecl->getLexicalDeclContext()->isRecord()) { 13794 // This is an in-class initialization for a static data member, e.g., 13795 // 13796 // struct S { 13797 // static const int value = 17; 13798 // }; 13799 13800 // C++ [class.mem]p4: 13801 // A member-declarator can contain a constant-initializer only 13802 // if it declares a static member (9.4) of const integral or 13803 // const enumeration type, see 9.4.2. 13804 // 13805 // C++11 [class.static.data]p3: 13806 // If a non-volatile non-inline const static data member is of integral 13807 // or enumeration type, its declaration in the class definition can 13808 // specify a brace-or-equal-initializer in which every initializer-clause 13809 // that is an assignment-expression is a constant expression. A static 13810 // data member of literal type can be declared in the class definition 13811 // with the constexpr specifier; if so, its declaration shall specify a 13812 // brace-or-equal-initializer in which every initializer-clause that is 13813 // an assignment-expression is a constant expression. 13814 13815 // Do nothing on dependent types. 13816 if (DclT->isDependentType()) { 13817 13818 // Allow any 'static constexpr' members, whether or not they are of literal 13819 // type. We separately check that every constexpr variable is of literal 13820 // type. 13821 } else if (VDecl->isConstexpr()) { 13822 13823 // Require constness. 13824 } else if (!DclT.isConstQualified()) { 13825 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 13826 << Init->getSourceRange(); 13827 VDecl->setInvalidDecl(); 13828 13829 // We allow integer constant expressions in all cases. 13830 } else if (DclT->isIntegralOrEnumerationType()) { 13831 // Check whether the expression is a constant expression. 13832 SourceLocation Loc; 13833 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 13834 // In C++11, a non-constexpr const static data member with an 13835 // in-class initializer cannot be volatile. 13836 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 13837 else if (Init->isValueDependent()) 13838 ; // Nothing to check. 13839 else if (Init->isIntegerConstantExpr(Context, &Loc)) 13840 ; // Ok, it's an ICE! 13841 else if (Init->getType()->isScopedEnumeralType() && 13842 Init->isCXX11ConstantExpr(Context)) 13843 ; // Ok, it is a scoped-enum constant expression. 13844 else if (Init->isEvaluatable(Context)) { 13845 // If we can constant fold the initializer through heroics, accept it, 13846 // but report this as a use of an extension for -pedantic. 13847 Diag(Loc, diag::ext_in_class_initializer_non_constant) 13848 << Init->getSourceRange(); 13849 } else { 13850 // Otherwise, this is some crazy unknown case. Report the issue at the 13851 // location provided by the isIntegerConstantExpr failed check. 13852 Diag(Loc, diag::err_in_class_initializer_non_constant) 13853 << Init->getSourceRange(); 13854 VDecl->setInvalidDecl(); 13855 } 13856 13857 // We allow foldable floating-point constants as an extension. 13858 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 13859 // In C++98, this is a GNU extension. In C++11, it is not, but we support 13860 // it anyway and provide a fixit to add the 'constexpr'. 13861 if (getLangOpts().CPlusPlus11) { 13862 Diag(VDecl->getLocation(), 13863 diag::ext_in_class_initializer_float_type_cxx11) 13864 << DclT << Init->getSourceRange(); 13865 Diag(VDecl->getBeginLoc(), 13866 diag::note_in_class_initializer_float_type_cxx11) 13867 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 13868 } else { 13869 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 13870 << DclT << Init->getSourceRange(); 13871 13872 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 13873 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 13874 << Init->getSourceRange(); 13875 VDecl->setInvalidDecl(); 13876 } 13877 } 13878 13879 // Suggest adding 'constexpr' in C++11 for literal types. 13880 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 13881 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 13882 << DclT << Init->getSourceRange() 13883 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 13884 VDecl->setConstexpr(true); 13885 13886 } else { 13887 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 13888 << DclT << Init->getSourceRange(); 13889 VDecl->setInvalidDecl(); 13890 } 13891 } else if (VDecl->isFileVarDecl()) { 13892 // In C, extern is typically used to avoid tentative definitions when 13893 // declaring variables in headers, but adding an intializer makes it a 13894 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 13895 // In C++, extern is often used to give implictly static const variables 13896 // external linkage, so don't warn in that case. If selectany is present, 13897 // this might be header code intended for C and C++ inclusion, so apply the 13898 // C++ rules. 13899 if (VDecl->getStorageClass() == SC_Extern && 13900 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 13901 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 13902 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 13903 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 13904 Diag(VDecl->getLocation(), diag::warn_extern_init); 13905 13906 // In Microsoft C++ mode, a const variable defined in namespace scope has 13907 // external linkage by default if the variable is declared with 13908 // __declspec(dllexport). 13909 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 13910 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 13911 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 13912 VDecl->setStorageClass(SC_Extern); 13913 13914 // C99 6.7.8p4. All file scoped initializers need to be constant. 13915 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 13916 CheckForConstantInitializer(Init, DclT); 13917 } 13918 13919 QualType InitType = Init->getType(); 13920 if (!InitType.isNull() && 13921 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 13922 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 13923 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 13924 13925 // We will represent direct-initialization similarly to copy-initialization: 13926 // int x(1); -as-> int x = 1; 13927 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 13928 // 13929 // Clients that want to distinguish between the two forms, can check for 13930 // direct initializer using VarDecl::getInitStyle(). 13931 // A major benefit is that clients that don't particularly care about which 13932 // exactly form was it (like the CodeGen) can handle both cases without 13933 // special case code. 13934 13935 // C++ 8.5p11: 13936 // The form of initialization (using parentheses or '=') is generally 13937 // insignificant, but does matter when the entity being initialized has a 13938 // class type. 13939 if (CXXDirectInit) { 13940 assert(DirectInit && "Call-style initializer must be direct init."); 13941 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit 13942 : VarDecl::CallInit); 13943 } else if (DirectInit) { 13944 // This must be list-initialization. No other way is direct-initialization. 13945 VDecl->setInitStyle(VarDecl::ListInit); 13946 } 13947 13948 if (LangOpts.OpenMP && 13949 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) && 13950 VDecl->isFileVarDecl()) 13951 DeclsToCheckForDeferredDiags.insert(VDecl); 13952 CheckCompleteVariableDeclaration(VDecl); 13953 } 13954 13955 /// ActOnInitializerError - Given that there was an error parsing an 13956 /// initializer for the given declaration, try to at least re-establish 13957 /// invariants such as whether a variable's type is either dependent or 13958 /// complete. 13959 void Sema::ActOnInitializerError(Decl *D) { 13960 // Our main concern here is re-establishing invariants like "a 13961 // variable's type is either dependent or complete". 13962 if (!D || D->isInvalidDecl()) return; 13963 13964 VarDecl *VD = dyn_cast<VarDecl>(D); 13965 if (!VD) return; 13966 13967 // Bindings are not usable if we can't make sense of the initializer. 13968 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 13969 for (auto *BD : DD->bindings()) 13970 BD->setInvalidDecl(); 13971 13972 // Auto types are meaningless if we can't make sense of the initializer. 13973 if (VD->getType()->isUndeducedType()) { 13974 D->setInvalidDecl(); 13975 return; 13976 } 13977 13978 QualType Ty = VD->getType(); 13979 if (Ty->isDependentType()) return; 13980 13981 // Require a complete type. 13982 if (RequireCompleteType(VD->getLocation(), 13983 Context.getBaseElementType(Ty), 13984 diag::err_typecheck_decl_incomplete_type)) { 13985 VD->setInvalidDecl(); 13986 return; 13987 } 13988 13989 // Require a non-abstract type. 13990 if (RequireNonAbstractType(VD->getLocation(), Ty, 13991 diag::err_abstract_type_in_decl, 13992 AbstractVariableType)) { 13993 VD->setInvalidDecl(); 13994 return; 13995 } 13996 13997 // Don't bother complaining about constructors or destructors, 13998 // though. 13999 } 14000 14001 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 14002 // If there is no declaration, there was an error parsing it. Just ignore it. 14003 if (!RealDecl) 14004 return; 14005 14006 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 14007 QualType Type = Var->getType(); 14008 14009 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 14010 if (isa<DecompositionDecl>(RealDecl)) { 14011 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 14012 Var->setInvalidDecl(); 14013 return; 14014 } 14015 14016 if (Type->isUndeducedType() && 14017 DeduceVariableDeclarationType(Var, false, nullptr)) 14018 return; 14019 14020 // C++11 [class.static.data]p3: A static data member can be declared with 14021 // the constexpr specifier; if so, its declaration shall specify 14022 // a brace-or-equal-initializer. 14023 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 14024 // the definition of a variable [...] or the declaration of a static data 14025 // member. 14026 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 14027 !Var->isThisDeclarationADemotedDefinition()) { 14028 if (Var->isStaticDataMember()) { 14029 // C++1z removes the relevant rule; the in-class declaration is always 14030 // a definition there. 14031 if (!getLangOpts().CPlusPlus17 && 14032 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14033 Diag(Var->getLocation(), 14034 diag::err_constexpr_static_mem_var_requires_init) 14035 << Var; 14036 Var->setInvalidDecl(); 14037 return; 14038 } 14039 } else { 14040 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 14041 Var->setInvalidDecl(); 14042 return; 14043 } 14044 } 14045 14046 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 14047 // be initialized. 14048 if (!Var->isInvalidDecl() && 14049 Var->getType().getAddressSpace() == LangAS::opencl_constant && 14050 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 14051 bool HasConstExprDefaultConstructor = false; 14052 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 14053 for (auto *Ctor : RD->ctors()) { 14054 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 14055 Ctor->getMethodQualifiers().getAddressSpace() == 14056 LangAS::opencl_constant) { 14057 HasConstExprDefaultConstructor = true; 14058 } 14059 } 14060 } 14061 if (!HasConstExprDefaultConstructor) { 14062 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 14063 Var->setInvalidDecl(); 14064 return; 14065 } 14066 } 14067 14068 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 14069 if (Var->getStorageClass() == SC_Extern) { 14070 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 14071 << Var; 14072 Var->setInvalidDecl(); 14073 return; 14074 } 14075 if (RequireCompleteType(Var->getLocation(), Var->getType(), 14076 diag::err_typecheck_decl_incomplete_type)) { 14077 Var->setInvalidDecl(); 14078 return; 14079 } 14080 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 14081 if (!RD->hasTrivialDefaultConstructor()) { 14082 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 14083 Var->setInvalidDecl(); 14084 return; 14085 } 14086 } 14087 // The declaration is unitialized, no need for further checks. 14088 return; 14089 } 14090 14091 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 14092 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 14093 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 14094 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 14095 NTCUC_DefaultInitializedObject, NTCUK_Init); 14096 14097 14098 switch (DefKind) { 14099 case VarDecl::Definition: 14100 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 14101 break; 14102 14103 // We have an out-of-line definition of a static data member 14104 // that has an in-class initializer, so we type-check this like 14105 // a declaration. 14106 // 14107 [[fallthrough]]; 14108 14109 case VarDecl::DeclarationOnly: 14110 // It's only a declaration. 14111 14112 // Block scope. C99 6.7p7: If an identifier for an object is 14113 // declared with no linkage (C99 6.2.2p6), the type for the 14114 // object shall be complete. 14115 if (!Type->isDependentType() && Var->isLocalVarDecl() && 14116 !Var->hasLinkage() && !Var->isInvalidDecl() && 14117 RequireCompleteType(Var->getLocation(), Type, 14118 diag::err_typecheck_decl_incomplete_type)) 14119 Var->setInvalidDecl(); 14120 14121 // Make sure that the type is not abstract. 14122 if (!Type->isDependentType() && !Var->isInvalidDecl() && 14123 RequireNonAbstractType(Var->getLocation(), Type, 14124 diag::err_abstract_type_in_decl, 14125 AbstractVariableType)) 14126 Var->setInvalidDecl(); 14127 if (!Type->isDependentType() && !Var->isInvalidDecl() && 14128 Var->getStorageClass() == SC_PrivateExtern) { 14129 Diag(Var->getLocation(), diag::warn_private_extern); 14130 Diag(Var->getLocation(), diag::note_private_extern); 14131 } 14132 14133 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 14134 !Var->isInvalidDecl()) 14135 ExternalDeclarations.push_back(Var); 14136 14137 return; 14138 14139 case VarDecl::TentativeDefinition: 14140 // File scope. C99 6.9.2p2: A declaration of an identifier for an 14141 // object that has file scope without an initializer, and without a 14142 // storage-class specifier or with the storage-class specifier "static", 14143 // constitutes a tentative definition. Note: A tentative definition with 14144 // external linkage is valid (C99 6.2.2p5). 14145 if (!Var->isInvalidDecl()) { 14146 if (const IncompleteArrayType *ArrayT 14147 = Context.getAsIncompleteArrayType(Type)) { 14148 if (RequireCompleteSizedType( 14149 Var->getLocation(), ArrayT->getElementType(), 14150 diag::err_array_incomplete_or_sizeless_type)) 14151 Var->setInvalidDecl(); 14152 } else if (Var->getStorageClass() == SC_Static) { 14153 // C99 6.9.2p3: If the declaration of an identifier for an object is 14154 // a tentative definition and has internal linkage (C99 6.2.2p3), the 14155 // declared type shall not be an incomplete type. 14156 // NOTE: code such as the following 14157 // static struct s; 14158 // struct s { int a; }; 14159 // is accepted by gcc. Hence here we issue a warning instead of 14160 // an error and we do not invalidate the static declaration. 14161 // NOTE: to avoid multiple warnings, only check the first declaration. 14162 if (Var->isFirstDecl()) 14163 RequireCompleteType(Var->getLocation(), Type, 14164 diag::ext_typecheck_decl_incomplete_type); 14165 } 14166 } 14167 14168 // Record the tentative definition; we're done. 14169 if (!Var->isInvalidDecl()) 14170 TentativeDefinitions.push_back(Var); 14171 return; 14172 } 14173 14174 // Provide a specific diagnostic for uninitialized variable 14175 // definitions with incomplete array type. 14176 if (Type->isIncompleteArrayType()) { 14177 if (Var->isConstexpr()) 14178 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init) 14179 << Var; 14180 else 14181 Diag(Var->getLocation(), 14182 diag::err_typecheck_incomplete_array_needs_initializer); 14183 Var->setInvalidDecl(); 14184 return; 14185 } 14186 14187 // Provide a specific diagnostic for uninitialized variable 14188 // definitions with reference type. 14189 if (Type->isReferenceType()) { 14190 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 14191 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 14192 return; 14193 } 14194 14195 // Do not attempt to type-check the default initializer for a 14196 // variable with dependent type. 14197 if (Type->isDependentType()) 14198 return; 14199 14200 if (Var->isInvalidDecl()) 14201 return; 14202 14203 if (!Var->hasAttr<AliasAttr>()) { 14204 if (RequireCompleteType(Var->getLocation(), 14205 Context.getBaseElementType(Type), 14206 diag::err_typecheck_decl_incomplete_type)) { 14207 Var->setInvalidDecl(); 14208 return; 14209 } 14210 } else { 14211 return; 14212 } 14213 14214 // The variable can not have an abstract class type. 14215 if (RequireNonAbstractType(Var->getLocation(), Type, 14216 diag::err_abstract_type_in_decl, 14217 AbstractVariableType)) { 14218 Var->setInvalidDecl(); 14219 return; 14220 } 14221 14222 // Check for jumps past the implicit initializer. C++0x 14223 // clarifies that this applies to a "variable with automatic 14224 // storage duration", not a "local variable". 14225 // C++11 [stmt.dcl]p3 14226 // A program that jumps from a point where a variable with automatic 14227 // storage duration is not in scope to a point where it is in scope is 14228 // ill-formed unless the variable has scalar type, class type with a 14229 // trivial default constructor and a trivial destructor, a cv-qualified 14230 // version of one of these types, or an array of one of the preceding 14231 // types and is declared without an initializer. 14232 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 14233 if (const RecordType *Record 14234 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 14235 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 14236 // Mark the function (if we're in one) for further checking even if the 14237 // looser rules of C++11 do not require such checks, so that we can 14238 // diagnose incompatibilities with C++98. 14239 if (!CXXRecord->isPOD()) 14240 setFunctionHasBranchProtectedScope(); 14241 } 14242 } 14243 // In OpenCL, we can't initialize objects in the __local address space, 14244 // even implicitly, so don't synthesize an implicit initializer. 14245 if (getLangOpts().OpenCL && 14246 Var->getType().getAddressSpace() == LangAS::opencl_local) 14247 return; 14248 // C++03 [dcl.init]p9: 14249 // If no initializer is specified for an object, and the 14250 // object is of (possibly cv-qualified) non-POD class type (or 14251 // array thereof), the object shall be default-initialized; if 14252 // the object is of const-qualified type, the underlying class 14253 // type shall have a user-declared default 14254 // constructor. Otherwise, if no initializer is specified for 14255 // a non- static object, the object and its subobjects, if 14256 // any, have an indeterminate initial value); if the object 14257 // or any of its subobjects are of const-qualified type, the 14258 // program is ill-formed. 14259 // C++0x [dcl.init]p11: 14260 // If no initializer is specified for an object, the object is 14261 // default-initialized; [...]. 14262 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 14263 InitializationKind Kind 14264 = InitializationKind::CreateDefault(Var->getLocation()); 14265 14266 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt); 14267 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt); 14268 14269 if (Init.get()) { 14270 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 14271 // This is important for template substitution. 14272 Var->setInitStyle(VarDecl::CallInit); 14273 } else if (Init.isInvalid()) { 14274 // If default-init fails, attach a recovery-expr initializer to track 14275 // that initialization was attempted and failed. 14276 auto RecoveryExpr = 14277 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 14278 if (RecoveryExpr.get()) 14279 Var->setInit(RecoveryExpr.get()); 14280 } 14281 14282 CheckCompleteVariableDeclaration(Var); 14283 } 14284 } 14285 14286 void Sema::ActOnCXXForRangeDecl(Decl *D) { 14287 // If there is no declaration, there was an error parsing it. Ignore it. 14288 if (!D) 14289 return; 14290 14291 VarDecl *VD = dyn_cast<VarDecl>(D); 14292 if (!VD) { 14293 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 14294 D->setInvalidDecl(); 14295 return; 14296 } 14297 14298 VD->setCXXForRangeDecl(true); 14299 14300 // for-range-declaration cannot be given a storage class specifier. 14301 int Error = -1; 14302 switch (VD->getStorageClass()) { 14303 case SC_None: 14304 break; 14305 case SC_Extern: 14306 Error = 0; 14307 break; 14308 case SC_Static: 14309 Error = 1; 14310 break; 14311 case SC_PrivateExtern: 14312 Error = 2; 14313 break; 14314 case SC_Auto: 14315 Error = 3; 14316 break; 14317 case SC_Register: 14318 Error = 4; 14319 break; 14320 } 14321 14322 // for-range-declaration cannot be given a storage class specifier con't. 14323 switch (VD->getTSCSpec()) { 14324 case TSCS_thread_local: 14325 Error = 6; 14326 break; 14327 case TSCS___thread: 14328 case TSCS__Thread_local: 14329 case TSCS_unspecified: 14330 break; 14331 } 14332 14333 if (Error != -1) { 14334 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 14335 << VD << Error; 14336 D->setInvalidDecl(); 14337 } 14338 } 14339 14340 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 14341 IdentifierInfo *Ident, 14342 ParsedAttributes &Attrs) { 14343 // C++1y [stmt.iter]p1: 14344 // A range-based for statement of the form 14345 // for ( for-range-identifier : for-range-initializer ) statement 14346 // is equivalent to 14347 // for ( auto&& for-range-identifier : for-range-initializer ) statement 14348 DeclSpec DS(Attrs.getPool().getFactory()); 14349 14350 const char *PrevSpec; 14351 unsigned DiagID; 14352 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 14353 getPrintingPolicy()); 14354 14355 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit); 14356 D.SetIdentifier(Ident, IdentLoc); 14357 D.takeAttributes(Attrs); 14358 14359 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 14360 IdentLoc); 14361 Decl *Var = ActOnDeclarator(S, D); 14362 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 14363 FinalizeDeclaration(Var); 14364 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 14365 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd() 14366 : IdentLoc); 14367 } 14368 14369 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 14370 if (var->isInvalidDecl()) return; 14371 14372 MaybeAddCUDAConstantAttr(var); 14373 14374 if (getLangOpts().OpenCL) { 14375 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 14376 // initialiser 14377 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 14378 !var->hasInit()) { 14379 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 14380 << 1 /*Init*/; 14381 var->setInvalidDecl(); 14382 return; 14383 } 14384 } 14385 14386 // In Objective-C, don't allow jumps past the implicit initialization of a 14387 // local retaining variable. 14388 if (getLangOpts().ObjC && 14389 var->hasLocalStorage()) { 14390 switch (var->getType().getObjCLifetime()) { 14391 case Qualifiers::OCL_None: 14392 case Qualifiers::OCL_ExplicitNone: 14393 case Qualifiers::OCL_Autoreleasing: 14394 break; 14395 14396 case Qualifiers::OCL_Weak: 14397 case Qualifiers::OCL_Strong: 14398 setFunctionHasBranchProtectedScope(); 14399 break; 14400 } 14401 } 14402 14403 if (var->hasLocalStorage() && 14404 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 14405 setFunctionHasBranchProtectedScope(); 14406 14407 // Warn about externally-visible variables being defined without a 14408 // prior declaration. We only want to do this for global 14409 // declarations, but we also specifically need to avoid doing it for 14410 // class members because the linkage of an anonymous class can 14411 // change if it's later given a typedef name. 14412 if (var->isThisDeclarationADefinition() && 14413 var->getDeclContext()->getRedeclContext()->isFileContext() && 14414 var->isExternallyVisible() && var->hasLinkage() && 14415 !var->isInline() && !var->getDescribedVarTemplate() && 14416 var->getStorageClass() != SC_Register && 14417 !isa<VarTemplatePartialSpecializationDecl>(var) && 14418 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 14419 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 14420 var->getLocation())) { 14421 // Find a previous declaration that's not a definition. 14422 VarDecl *prev = var->getPreviousDecl(); 14423 while (prev && prev->isThisDeclarationADefinition()) 14424 prev = prev->getPreviousDecl(); 14425 14426 if (!prev) { 14427 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 14428 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14429 << /* variable */ 0; 14430 } 14431 } 14432 14433 // Cache the result of checking for constant initialization. 14434 std::optional<bool> CacheHasConstInit; 14435 const Expr *CacheCulprit = nullptr; 14436 auto checkConstInit = [&]() mutable { 14437 if (!CacheHasConstInit) 14438 CacheHasConstInit = var->getInit()->isConstantInitializer( 14439 Context, var->getType()->isReferenceType(), &CacheCulprit); 14440 return *CacheHasConstInit; 14441 }; 14442 14443 if (var->getTLSKind() == VarDecl::TLS_Static) { 14444 if (var->getType().isDestructedType()) { 14445 // GNU C++98 edits for __thread, [basic.start.term]p3: 14446 // The type of an object with thread storage duration shall not 14447 // have a non-trivial destructor. 14448 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 14449 if (getLangOpts().CPlusPlus11) 14450 Diag(var->getLocation(), diag::note_use_thread_local); 14451 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 14452 if (!checkConstInit()) { 14453 // GNU C++98 edits for __thread, [basic.start.init]p4: 14454 // An object of thread storage duration shall not require dynamic 14455 // initialization. 14456 // FIXME: Need strict checking here. 14457 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 14458 << CacheCulprit->getSourceRange(); 14459 if (getLangOpts().CPlusPlus11) 14460 Diag(var->getLocation(), diag::note_use_thread_local); 14461 } 14462 } 14463 } 14464 14465 14466 if (!var->getType()->isStructureType() && var->hasInit() && 14467 isa<InitListExpr>(var->getInit())) { 14468 const auto *ILE = cast<InitListExpr>(var->getInit()); 14469 unsigned NumInits = ILE->getNumInits(); 14470 if (NumInits > 2) 14471 for (unsigned I = 0; I < NumInits; ++I) { 14472 const auto *Init = ILE->getInit(I); 14473 if (!Init) 14474 break; 14475 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 14476 if (!SL) 14477 break; 14478 14479 unsigned NumConcat = SL->getNumConcatenated(); 14480 // Diagnose missing comma in string array initialization. 14481 // Do not warn when all the elements in the initializer are concatenated 14482 // together. Do not warn for macros too. 14483 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 14484 bool OnlyOneMissingComma = true; 14485 for (unsigned J = I + 1; J < NumInits; ++J) { 14486 const auto *Init = ILE->getInit(J); 14487 if (!Init) 14488 break; 14489 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 14490 if (!SLJ || SLJ->getNumConcatenated() > 1) { 14491 OnlyOneMissingComma = false; 14492 break; 14493 } 14494 } 14495 14496 if (OnlyOneMissingComma) { 14497 SmallVector<FixItHint, 1> Hints; 14498 for (unsigned i = 0; i < NumConcat - 1; ++i) 14499 Hints.push_back(FixItHint::CreateInsertion( 14500 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 14501 14502 Diag(SL->getStrTokenLoc(1), 14503 diag::warn_concatenated_literal_array_init) 14504 << Hints; 14505 Diag(SL->getBeginLoc(), 14506 diag::note_concatenated_string_literal_silence); 14507 } 14508 // In any case, stop now. 14509 break; 14510 } 14511 } 14512 } 14513 14514 14515 QualType type = var->getType(); 14516 14517 if (var->hasAttr<BlocksAttr>()) 14518 getCurFunction()->addByrefBlockVar(var); 14519 14520 Expr *Init = var->getInit(); 14521 bool GlobalStorage = var->hasGlobalStorage(); 14522 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 14523 QualType baseType = Context.getBaseElementType(type); 14524 bool HasConstInit = true; 14525 14526 // Check whether the initializer is sufficiently constant. 14527 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 14528 !Init->isValueDependent() && 14529 (GlobalStorage || var->isConstexpr() || 14530 var->mightBeUsableInConstantExpressions(Context))) { 14531 // If this variable might have a constant initializer or might be usable in 14532 // constant expressions, check whether or not it actually is now. We can't 14533 // do this lazily, because the result might depend on things that change 14534 // later, such as which constexpr functions happen to be defined. 14535 SmallVector<PartialDiagnosticAt, 8> Notes; 14536 if (!getLangOpts().CPlusPlus11) { 14537 // Prior to C++11, in contexts where a constant initializer is required, 14538 // the set of valid constant initializers is described by syntactic rules 14539 // in [expr.const]p2-6. 14540 // FIXME: Stricter checking for these rules would be useful for constinit / 14541 // -Wglobal-constructors. 14542 HasConstInit = checkConstInit(); 14543 14544 // Compute and cache the constant value, and remember that we have a 14545 // constant initializer. 14546 if (HasConstInit) { 14547 (void)var->checkForConstantInitialization(Notes); 14548 Notes.clear(); 14549 } else if (CacheCulprit) { 14550 Notes.emplace_back(CacheCulprit->getExprLoc(), 14551 PDiag(diag::note_invalid_subexpr_in_const_expr)); 14552 Notes.back().second << CacheCulprit->getSourceRange(); 14553 } 14554 } else { 14555 // Evaluate the initializer to see if it's a constant initializer. 14556 HasConstInit = var->checkForConstantInitialization(Notes); 14557 } 14558 14559 if (HasConstInit) { 14560 // FIXME: Consider replacing the initializer with a ConstantExpr. 14561 } else if (var->isConstexpr()) { 14562 SourceLocation DiagLoc = var->getLocation(); 14563 // If the note doesn't add any useful information other than a source 14564 // location, fold it into the primary diagnostic. 14565 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14566 diag::note_invalid_subexpr_in_const_expr) { 14567 DiagLoc = Notes[0].first; 14568 Notes.clear(); 14569 } 14570 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 14571 << var << Init->getSourceRange(); 14572 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 14573 Diag(Notes[I].first, Notes[I].second); 14574 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 14575 auto *Attr = var->getAttr<ConstInitAttr>(); 14576 Diag(var->getLocation(), diag::err_require_constant_init_failed) 14577 << Init->getSourceRange(); 14578 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 14579 << Attr->getRange() << Attr->isConstinit(); 14580 for (auto &it : Notes) 14581 Diag(it.first, it.second); 14582 } else if (IsGlobal && 14583 !getDiagnostics().isIgnored(diag::warn_global_constructor, 14584 var->getLocation())) { 14585 // Warn about globals which don't have a constant initializer. Don't 14586 // warn about globals with a non-trivial destructor because we already 14587 // warned about them. 14588 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 14589 if (!(RD && !RD->hasTrivialDestructor())) { 14590 // checkConstInit() here permits trivial default initialization even in 14591 // C++11 onwards, where such an initializer is not a constant initializer 14592 // but nonetheless doesn't require a global constructor. 14593 if (!checkConstInit()) 14594 Diag(var->getLocation(), diag::warn_global_constructor) 14595 << Init->getSourceRange(); 14596 } 14597 } 14598 } 14599 14600 // Apply section attributes and pragmas to global variables. 14601 if (GlobalStorage && var->isThisDeclarationADefinition() && 14602 !inTemplateInstantiation()) { 14603 PragmaStack<StringLiteral *> *Stack = nullptr; 14604 int SectionFlags = ASTContext::PSF_Read; 14605 bool MSVCEnv = 14606 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment(); 14607 std::optional<QualType::NonConstantStorageReason> Reason; 14608 if (HasConstInit && 14609 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) { 14610 Stack = &ConstSegStack; 14611 } else { 14612 SectionFlags |= ASTContext::PSF_Write; 14613 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack; 14614 } 14615 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 14616 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 14617 SectionFlags |= ASTContext::PSF_Implicit; 14618 UnifySection(SA->getName(), SectionFlags, var); 14619 } else if (Stack->CurrentValue) { 14620 if (Stack != &ConstSegStack && MSVCEnv && 14621 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue && 14622 var->getType().isConstQualified()) { 14623 assert((!Reason || Reason != QualType::NonConstantStorageReason:: 14624 NonConstNonReferenceType) && 14625 "This case should've already been handled elsewhere"); 14626 Diag(var->getLocation(), diag::warn_section_msvc_compat) 14627 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit 14628 ? QualType::NonConstantStorageReason::NonTrivialCtor 14629 : *Reason); 14630 } 14631 SectionFlags |= ASTContext::PSF_Implicit; 14632 auto SectionName = Stack->CurrentValue->getString(); 14633 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName, 14634 Stack->CurrentPragmaLocation, 14635 SectionAttr::Declspec_allocate)); 14636 if (UnifySection(SectionName, SectionFlags, var)) 14637 var->dropAttr<SectionAttr>(); 14638 } 14639 14640 // Apply the init_seg attribute if this has an initializer. If the 14641 // initializer turns out to not be dynamic, we'll end up ignoring this 14642 // attribute. 14643 if (CurInitSeg && var->getInit()) 14644 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 14645 CurInitSegLoc)); 14646 } 14647 14648 // All the following checks are C++ only. 14649 if (!getLangOpts().CPlusPlus) { 14650 // If this variable must be emitted, add it as an initializer for the 14651 // current module. 14652 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 14653 Context.addModuleInitializer(ModuleScopes.back().Module, var); 14654 return; 14655 } 14656 14657 // Require the destructor. 14658 if (!type->isDependentType()) 14659 if (const RecordType *recordType = baseType->getAs<RecordType>()) 14660 FinalizeVarWithDestructor(var, recordType); 14661 14662 // If this variable must be emitted, add it as an initializer for the current 14663 // module. 14664 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 14665 Context.addModuleInitializer(ModuleScopes.back().Module, var); 14666 14667 // Build the bindings if this is a structured binding declaration. 14668 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 14669 CheckCompleteDecompositionDeclaration(DD); 14670 } 14671 14672 /// Check if VD needs to be dllexport/dllimport due to being in a 14673 /// dllexport/import function. 14674 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 14675 assert(VD->isStaticLocal()); 14676 14677 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 14678 14679 // Find outermost function when VD is in lambda function. 14680 while (FD && !getDLLAttr(FD) && 14681 !FD->hasAttr<DLLExportStaticLocalAttr>() && 14682 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 14683 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 14684 } 14685 14686 if (!FD) 14687 return; 14688 14689 // Static locals inherit dll attributes from their function. 14690 if (Attr *A = getDLLAttr(FD)) { 14691 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 14692 NewAttr->setInherited(true); 14693 VD->addAttr(NewAttr); 14694 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 14695 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 14696 NewAttr->setInherited(true); 14697 VD->addAttr(NewAttr); 14698 14699 // Export this function to enforce exporting this static variable even 14700 // if it is not used in this compilation unit. 14701 if (!FD->hasAttr<DLLExportAttr>()) 14702 FD->addAttr(NewAttr); 14703 14704 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 14705 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 14706 NewAttr->setInherited(true); 14707 VD->addAttr(NewAttr); 14708 } 14709 } 14710 14711 void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) { 14712 assert(VD->getTLSKind()); 14713 14714 // Perform TLS alignment check here after attributes attached to the variable 14715 // which may affect the alignment have been processed. Only perform the check 14716 // if the target has a maximum TLS alignment (zero means no constraints). 14717 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 14718 // Protect the check so that it's not performed on dependent types and 14719 // dependent alignments (we can't determine the alignment in that case). 14720 if (!VD->hasDependentAlignment()) { 14721 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 14722 if (Context.getDeclAlign(VD) > MaxAlignChars) { 14723 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 14724 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 14725 << (unsigned)MaxAlignChars.getQuantity(); 14726 } 14727 } 14728 } 14729 } 14730 14731 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 14732 /// any semantic actions necessary after any initializer has been attached. 14733 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 14734 // Note that we are no longer parsing the initializer for this declaration. 14735 ParsingInitForAutoVars.erase(ThisDecl); 14736 14737 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 14738 if (!VD) 14739 return; 14740 14741 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 14742 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 14743 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 14744 if (PragmaClangBSSSection.Valid) 14745 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 14746 Context, PragmaClangBSSSection.SectionName, 14747 PragmaClangBSSSection.PragmaLocation)); 14748 if (PragmaClangDataSection.Valid) 14749 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 14750 Context, PragmaClangDataSection.SectionName, 14751 PragmaClangDataSection.PragmaLocation)); 14752 if (PragmaClangRodataSection.Valid) 14753 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 14754 Context, PragmaClangRodataSection.SectionName, 14755 PragmaClangRodataSection.PragmaLocation)); 14756 if (PragmaClangRelroSection.Valid) 14757 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 14758 Context, PragmaClangRelroSection.SectionName, 14759 PragmaClangRelroSection.PragmaLocation)); 14760 } 14761 14762 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 14763 for (auto *BD : DD->bindings()) { 14764 FinalizeDeclaration(BD); 14765 } 14766 } 14767 14768 checkAttributesAfterMerging(*this, *VD); 14769 14770 if (VD->isStaticLocal()) 14771 CheckStaticLocalForDllExport(VD); 14772 14773 if (VD->getTLSKind()) 14774 CheckThreadLocalForLargeAlignment(VD); 14775 14776 // Perform check for initializers of device-side global variables. 14777 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 14778 // 7.5). We must also apply the same checks to all __shared__ 14779 // variables whether they are local or not. CUDA also allows 14780 // constant initializers for __constant__ and __device__ variables. 14781 if (getLangOpts().CUDA) 14782 checkAllowedCUDAInitializer(VD); 14783 14784 // Grab the dllimport or dllexport attribute off of the VarDecl. 14785 const InheritableAttr *DLLAttr = getDLLAttr(VD); 14786 14787 // Imported static data members cannot be defined out-of-line. 14788 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 14789 if (VD->isStaticDataMember() && VD->isOutOfLine() && 14790 VD->isThisDeclarationADefinition()) { 14791 // We allow definitions of dllimport class template static data members 14792 // with a warning. 14793 CXXRecordDecl *Context = 14794 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 14795 bool IsClassTemplateMember = 14796 isa<ClassTemplatePartialSpecializationDecl>(Context) || 14797 Context->getDescribedClassTemplate(); 14798 14799 Diag(VD->getLocation(), 14800 IsClassTemplateMember 14801 ? diag::warn_attribute_dllimport_static_field_definition 14802 : diag::err_attribute_dllimport_static_field_definition); 14803 Diag(IA->getLocation(), diag::note_attribute); 14804 if (!IsClassTemplateMember) 14805 VD->setInvalidDecl(); 14806 } 14807 } 14808 14809 // dllimport/dllexport variables cannot be thread local, their TLS index 14810 // isn't exported with the variable. 14811 if (DLLAttr && VD->getTLSKind()) { 14812 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 14813 if (F && getDLLAttr(F)) { 14814 assert(VD->isStaticLocal()); 14815 // But if this is a static local in a dlimport/dllexport function, the 14816 // function will never be inlined, which means the var would never be 14817 // imported, so having it marked import/export is safe. 14818 } else { 14819 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 14820 << DLLAttr; 14821 VD->setInvalidDecl(); 14822 } 14823 } 14824 14825 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 14826 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 14827 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 14828 << Attr; 14829 VD->dropAttr<UsedAttr>(); 14830 } 14831 } 14832 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 14833 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 14834 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 14835 << Attr; 14836 VD->dropAttr<RetainAttr>(); 14837 } 14838 } 14839 14840 const DeclContext *DC = VD->getDeclContext(); 14841 // If there's a #pragma GCC visibility in scope, and this isn't a class 14842 // member, set the visibility of this variable. 14843 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 14844 AddPushedVisibilityAttribute(VD); 14845 14846 // FIXME: Warn on unused var template partial specializations. 14847 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 14848 MarkUnusedFileScopedDecl(VD); 14849 14850 // Now we have parsed the initializer and can update the table of magic 14851 // tag values. 14852 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 14853 !VD->getType()->isIntegralOrEnumerationType()) 14854 return; 14855 14856 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 14857 const Expr *MagicValueExpr = VD->getInit(); 14858 if (!MagicValueExpr) { 14859 continue; 14860 } 14861 std::optional<llvm::APSInt> MagicValueInt; 14862 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 14863 Diag(I->getRange().getBegin(), 14864 diag::err_type_tag_for_datatype_not_ice) 14865 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 14866 continue; 14867 } 14868 if (MagicValueInt->getActiveBits() > 64) { 14869 Diag(I->getRange().getBegin(), 14870 diag::err_type_tag_for_datatype_too_large) 14871 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 14872 continue; 14873 } 14874 uint64_t MagicValue = MagicValueInt->getZExtValue(); 14875 RegisterTypeTagForDatatype(I->getArgumentKind(), 14876 MagicValue, 14877 I->getMatchingCType(), 14878 I->getLayoutCompatible(), 14879 I->getMustBeNull()); 14880 } 14881 } 14882 14883 static bool hasDeducedAuto(DeclaratorDecl *DD) { 14884 auto *VD = dyn_cast<VarDecl>(DD); 14885 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 14886 } 14887 14888 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 14889 ArrayRef<Decl *> Group) { 14890 SmallVector<Decl*, 8> Decls; 14891 14892 if (DS.isTypeSpecOwned()) 14893 Decls.push_back(DS.getRepAsDecl()); 14894 14895 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 14896 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 14897 bool DiagnosedMultipleDecomps = false; 14898 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 14899 bool DiagnosedNonDeducedAuto = false; 14900 14901 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 14902 if (Decl *D = Group[i]) { 14903 // Check if the Decl has been declared in '#pragma omp declare target' 14904 // directive and has static storage duration. 14905 if (auto *VD = dyn_cast<VarDecl>(D); 14906 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() && 14907 VD->hasGlobalStorage()) 14908 ActOnOpenMPDeclareTargetInitializer(D); 14909 // For declarators, there are some additional syntactic-ish checks we need 14910 // to perform. 14911 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 14912 if (!FirstDeclaratorInGroup) 14913 FirstDeclaratorInGroup = DD; 14914 if (!FirstDecompDeclaratorInGroup) 14915 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 14916 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 14917 !hasDeducedAuto(DD)) 14918 FirstNonDeducedAutoInGroup = DD; 14919 14920 if (FirstDeclaratorInGroup != DD) { 14921 // A decomposition declaration cannot be combined with any other 14922 // declaration in the same group. 14923 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 14924 Diag(FirstDecompDeclaratorInGroup->getLocation(), 14925 diag::err_decomp_decl_not_alone) 14926 << FirstDeclaratorInGroup->getSourceRange() 14927 << DD->getSourceRange(); 14928 DiagnosedMultipleDecomps = true; 14929 } 14930 14931 // A declarator that uses 'auto' in any way other than to declare a 14932 // variable with a deduced type cannot be combined with any other 14933 // declarator in the same group. 14934 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 14935 Diag(FirstNonDeducedAutoInGroup->getLocation(), 14936 diag::err_auto_non_deduced_not_alone) 14937 << FirstNonDeducedAutoInGroup->getType() 14938 ->hasAutoForTrailingReturnType() 14939 << FirstDeclaratorInGroup->getSourceRange() 14940 << DD->getSourceRange(); 14941 DiagnosedNonDeducedAuto = true; 14942 } 14943 } 14944 } 14945 14946 Decls.push_back(D); 14947 } 14948 } 14949 14950 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 14951 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 14952 handleTagNumbering(Tag, S); 14953 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 14954 getLangOpts().CPlusPlus) 14955 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 14956 } 14957 } 14958 14959 return BuildDeclaratorGroup(Decls); 14960 } 14961 14962 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 14963 /// group, performing any necessary semantic checking. 14964 Sema::DeclGroupPtrTy 14965 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 14966 // C++14 [dcl.spec.auto]p7: (DR1347) 14967 // If the type that replaces the placeholder type is not the same in each 14968 // deduction, the program is ill-formed. 14969 if (Group.size() > 1) { 14970 QualType Deduced; 14971 VarDecl *DeducedDecl = nullptr; 14972 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 14973 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 14974 if (!D || D->isInvalidDecl()) 14975 break; 14976 DeducedType *DT = D->getType()->getContainedDeducedType(); 14977 if (!DT || DT->getDeducedType().isNull()) 14978 continue; 14979 if (Deduced.isNull()) { 14980 Deduced = DT->getDeducedType(); 14981 DeducedDecl = D; 14982 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 14983 auto *AT = dyn_cast<AutoType>(DT); 14984 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 14985 diag::err_auto_different_deductions) 14986 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 14987 << DeducedDecl->getDeclName() << DT->getDeducedType() 14988 << D->getDeclName(); 14989 if (DeducedDecl->hasInit()) 14990 Dia << DeducedDecl->getInit()->getSourceRange(); 14991 if (D->getInit()) 14992 Dia << D->getInit()->getSourceRange(); 14993 D->setInvalidDecl(); 14994 break; 14995 } 14996 } 14997 } 14998 14999 ActOnDocumentableDecls(Group); 15000 15001 return DeclGroupPtrTy::make( 15002 DeclGroupRef::Create(Context, Group.data(), Group.size())); 15003 } 15004 15005 void Sema::ActOnDocumentableDecl(Decl *D) { 15006 ActOnDocumentableDecls(D); 15007 } 15008 15009 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 15010 // Don't parse the comment if Doxygen diagnostics are ignored. 15011 if (Group.empty() || !Group[0]) 15012 return; 15013 15014 if (Diags.isIgnored(diag::warn_doc_param_not_found, 15015 Group[0]->getLocation()) && 15016 Diags.isIgnored(diag::warn_unknown_comment_command_name, 15017 Group[0]->getLocation())) 15018 return; 15019 15020 if (Group.size() >= 2) { 15021 // This is a decl group. Normally it will contain only declarations 15022 // produced from declarator list. But in case we have any definitions or 15023 // additional declaration references: 15024 // 'typedef struct S {} S;' 15025 // 'typedef struct S *S;' 15026 // 'struct S *pS;' 15027 // FinalizeDeclaratorGroup adds these as separate declarations. 15028 Decl *MaybeTagDecl = Group[0]; 15029 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 15030 Group = Group.slice(1); 15031 } 15032 } 15033 15034 // FIMXE: We assume every Decl in the group is in the same file. 15035 // This is false when preprocessor constructs the group from decls in 15036 // different files (e. g. macros or #include). 15037 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 15038 } 15039 15040 /// Common checks for a parameter-declaration that should apply to both function 15041 /// parameters and non-type template parameters. 15042 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 15043 // Check that there are no default arguments inside the type of this 15044 // parameter. 15045 if (getLangOpts().CPlusPlus) 15046 CheckExtraCXXDefaultArguments(D); 15047 15048 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 15049 if (D.getCXXScopeSpec().isSet()) { 15050 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 15051 << D.getCXXScopeSpec().getRange(); 15052 } 15053 15054 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 15055 // simple identifier except [...irrelevant cases...]. 15056 switch (D.getName().getKind()) { 15057 case UnqualifiedIdKind::IK_Identifier: 15058 break; 15059 15060 case UnqualifiedIdKind::IK_OperatorFunctionId: 15061 case UnqualifiedIdKind::IK_ConversionFunctionId: 15062 case UnqualifiedIdKind::IK_LiteralOperatorId: 15063 case UnqualifiedIdKind::IK_ConstructorName: 15064 case UnqualifiedIdKind::IK_DestructorName: 15065 case UnqualifiedIdKind::IK_ImplicitSelfParam: 15066 case UnqualifiedIdKind::IK_DeductionGuideName: 15067 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 15068 << GetNameForDeclarator(D).getName(); 15069 break; 15070 15071 case UnqualifiedIdKind::IK_TemplateId: 15072 case UnqualifiedIdKind::IK_ConstructorTemplateId: 15073 // GetNameForDeclarator would not produce a useful name in this case. 15074 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 15075 break; 15076 } 15077 } 15078 15079 static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, 15080 SourceLocation ExplicitThisLoc) { 15081 if (!ExplicitThisLoc.isValid()) 15082 return; 15083 assert(S.getLangOpts().CPlusPlus && 15084 "explicit parameter in non-cplusplus mode"); 15085 if (!S.getLangOpts().CPlusPlus23) 15086 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this) 15087 << P->getSourceRange(); 15088 15089 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function 15090 // parameter pack. 15091 if (P->isParameterPack()) { 15092 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack) 15093 << P->getSourceRange(); 15094 return; 15095 } 15096 P->setExplicitObjectParameterLoc(ExplicitThisLoc); 15097 if (LambdaScopeInfo *LSI = S.getCurLambda()) 15098 LSI->ExplicitObjectParameter = P; 15099 } 15100 15101 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 15102 /// to introduce parameters into function prototype scope. 15103 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D, 15104 SourceLocation ExplicitThisLoc) { 15105 const DeclSpec &DS = D.getDeclSpec(); 15106 15107 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 15108 15109 // C++03 [dcl.stc]p2 also permits 'auto'. 15110 StorageClass SC = SC_None; 15111 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 15112 SC = SC_Register; 15113 // In C++11, the 'register' storage class specifier is deprecated. 15114 // In C++17, it is not allowed, but we tolerate it as an extension. 15115 if (getLangOpts().CPlusPlus11) { 15116 Diag(DS.getStorageClassSpecLoc(), 15117 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 15118 : diag::warn_deprecated_register) 15119 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 15120 } 15121 } else if (getLangOpts().CPlusPlus && 15122 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 15123 SC = SC_Auto; 15124 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 15125 Diag(DS.getStorageClassSpecLoc(), 15126 diag::err_invalid_storage_class_in_func_decl); 15127 D.getMutableDeclSpec().ClearStorageClassSpecs(); 15128 } 15129 15130 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 15131 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 15132 << DeclSpec::getSpecifierName(TSCS); 15133 if (DS.isInlineSpecified()) 15134 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 15135 << getLangOpts().CPlusPlus17; 15136 if (DS.hasConstexprSpecifier()) 15137 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 15138 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 15139 15140 DiagnoseFunctionSpecifiers(DS); 15141 15142 CheckFunctionOrTemplateParamDeclarator(S, D); 15143 15144 TypeSourceInfo *TInfo = GetTypeForDeclarator(D); 15145 QualType parmDeclType = TInfo->getType(); 15146 15147 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 15148 IdentifierInfo *II = D.getIdentifier(); 15149 if (II) { 15150 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 15151 ForVisibleRedeclaration); 15152 LookupName(R, S); 15153 if (!R.empty()) { 15154 NamedDecl *PrevDecl = *R.begin(); 15155 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) { 15156 // Maybe we will complain about the shadowed template parameter. 15157 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15158 // Just pretend that we didn't see the previous declaration. 15159 PrevDecl = nullptr; 15160 } 15161 if (PrevDecl && S->isDeclScope(PrevDecl)) { 15162 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 15163 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15164 // Recover by removing the name 15165 II = nullptr; 15166 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 15167 D.setInvalidType(true); 15168 } 15169 } 15170 } 15171 15172 // Temporarily put parameter variables in the translation unit, not 15173 // the enclosing context. This prevents them from accidentally 15174 // looking like class members in C++. 15175 ParmVarDecl *New = 15176 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 15177 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 15178 15179 if (D.isInvalidType()) 15180 New->setInvalidDecl(); 15181 15182 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc); 15183 15184 assert(S->isFunctionPrototypeScope()); 15185 assert(S->getFunctionPrototypeDepth() >= 1); 15186 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 15187 S->getNextFunctionPrototypeIndex()); 15188 15189 // Add the parameter declaration into this scope. 15190 S->AddDecl(New); 15191 if (II) 15192 IdResolver.AddDecl(New); 15193 15194 ProcessDeclAttributes(S, New, D); 15195 15196 if (D.getDeclSpec().isModulePrivateSpecified()) 15197 Diag(New->getLocation(), diag::err_module_private_local) 15198 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15199 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 15200 15201 if (New->hasAttr<BlocksAttr>()) { 15202 Diag(New->getLocation(), diag::err_block_on_nonlocal); 15203 } 15204 15205 if (getLangOpts().OpenCL) 15206 deduceOpenCLAddressSpace(New); 15207 15208 return New; 15209 } 15210 15211 /// Synthesizes a variable for a parameter arising from a 15212 /// typedef. 15213 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 15214 SourceLocation Loc, 15215 QualType T) { 15216 /* FIXME: setting StartLoc == Loc. 15217 Would it be worth to modify callers so as to provide proper source 15218 location for the unnamed parameters, embedding the parameter's type? */ 15219 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 15220 T, Context.getTrivialTypeSourceInfo(T, Loc), 15221 SC_None, nullptr); 15222 Param->setImplicit(); 15223 return Param; 15224 } 15225 15226 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 15227 // Don't diagnose unused-parameter errors in template instantiations; we 15228 // will already have done so in the template itself. 15229 if (inTemplateInstantiation()) 15230 return; 15231 15232 for (const ParmVarDecl *Parameter : Parameters) { 15233 if (!Parameter->isReferenced() && Parameter->getDeclName() && 15234 !Parameter->hasAttr<UnusedAttr>() && 15235 !Parameter->getIdentifier()->isPlaceholder()) { 15236 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 15237 << Parameter->getDeclName(); 15238 } 15239 } 15240 } 15241 15242 void Sema::DiagnoseSizeOfParametersAndReturnValue( 15243 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 15244 if (LangOpts.NumLargeByValueCopy == 0) // No check. 15245 return; 15246 15247 // Warn if the return value is pass-by-value and larger than the specified 15248 // threshold. 15249 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 15250 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 15251 if (Size > LangOpts.NumLargeByValueCopy) 15252 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 15253 } 15254 15255 // Warn if any parameter is pass-by-value and larger than the specified 15256 // threshold. 15257 for (const ParmVarDecl *Parameter : Parameters) { 15258 QualType T = Parameter->getType(); 15259 if (T->isDependentType() || !T.isPODType(Context)) 15260 continue; 15261 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 15262 if (Size > LangOpts.NumLargeByValueCopy) 15263 Diag(Parameter->getLocation(), diag::warn_parameter_size) 15264 << Parameter << Size; 15265 } 15266 } 15267 15268 QualType Sema::AdjustParameterTypeForObjCAutoRefCount(QualType T, 15269 SourceLocation NameLoc, 15270 TypeSourceInfo *TSInfo) { 15271 // In ARC, infer a lifetime qualifier for appropriate parameter types. 15272 if (!getLangOpts().ObjCAutoRefCount || 15273 T.getObjCLifetime() != Qualifiers::OCL_None || !T->isObjCLifetimeType()) 15274 return T; 15275 15276 Qualifiers::ObjCLifetime Lifetime; 15277 15278 // Special cases for arrays: 15279 // - if it's const, use __unsafe_unretained 15280 // - otherwise, it's an error 15281 if (T->isArrayType()) { 15282 if (!T.isConstQualified()) { 15283 if (DelayedDiagnostics.shouldDelayDiagnostics()) 15284 DelayedDiagnostics.add(sema::DelayedDiagnostic::makeForbiddenType( 15285 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 15286 else 15287 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 15288 << TSInfo->getTypeLoc().getSourceRange(); 15289 } 15290 Lifetime = Qualifiers::OCL_ExplicitNone; 15291 } else { 15292 Lifetime = T->getObjCARCImplicitLifetime(); 15293 } 15294 T = Context.getLifetimeQualifiedType(T, Lifetime); 15295 15296 return T; 15297 } 15298 15299 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 15300 SourceLocation NameLoc, IdentifierInfo *Name, 15301 QualType T, TypeSourceInfo *TSInfo, 15302 StorageClass SC) { 15303 // In ARC, infer a lifetime qualifier for appropriate parameter types. 15304 if (getLangOpts().ObjCAutoRefCount && 15305 T.getObjCLifetime() == Qualifiers::OCL_None && 15306 T->isObjCLifetimeType()) { 15307 15308 Qualifiers::ObjCLifetime lifetime; 15309 15310 // Special cases for arrays: 15311 // - if it's const, use __unsafe_unretained 15312 // - otherwise, it's an error 15313 if (T->isArrayType()) { 15314 if (!T.isConstQualified()) { 15315 if (DelayedDiagnostics.shouldDelayDiagnostics()) 15316 DelayedDiagnostics.add( 15317 sema::DelayedDiagnostic::makeForbiddenType( 15318 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 15319 else 15320 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 15321 << TSInfo->getTypeLoc().getSourceRange(); 15322 } 15323 lifetime = Qualifiers::OCL_ExplicitNone; 15324 } else { 15325 lifetime = T->getObjCARCImplicitLifetime(); 15326 } 15327 T = Context.getLifetimeQualifiedType(T, lifetime); 15328 } 15329 15330 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 15331 Context.getAdjustedParameterType(T), 15332 TSInfo, SC, nullptr); 15333 15334 // Make a note if we created a new pack in the scope of a lambda, so that 15335 // we know that references to that pack must also be expanded within the 15336 // lambda scope. 15337 if (New->isParameterPack()) 15338 if (auto *LSI = getEnclosingLambda()) 15339 LSI->LocalPacks.push_back(New); 15340 15341 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 15342 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 15343 checkNonTrivialCUnion(New->getType(), New->getLocation(), 15344 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 15345 15346 // Parameter declarators cannot be interface types. All ObjC objects are 15347 // passed by reference. 15348 if (T->isObjCObjectType()) { 15349 SourceLocation TypeEndLoc = 15350 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 15351 Diag(NameLoc, 15352 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 15353 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 15354 T = Context.getObjCObjectPointerType(T); 15355 New->setType(T); 15356 } 15357 15358 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 15359 // duration shall not be qualified by an address-space qualifier." 15360 // Since all parameters have automatic store duration, they can not have 15361 // an address space. 15362 if (T.getAddressSpace() != LangAS::Default && 15363 // OpenCL allows function arguments declared to be an array of a type 15364 // to be qualified with an address space. 15365 !(getLangOpts().OpenCL && 15366 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) && 15367 // WebAssembly allows reference types as parameters. Funcref in particular 15368 // lives in a different address space. 15369 !(T->isFunctionPointerType() && 15370 T.getAddressSpace() == LangAS::wasm_funcref)) { 15371 Diag(NameLoc, diag::err_arg_with_address_space); 15372 New->setInvalidDecl(); 15373 } 15374 15375 // PPC MMA non-pointer types are not allowed as function argument types. 15376 if (Context.getTargetInfo().getTriple().isPPC64() && 15377 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 15378 New->setInvalidDecl(); 15379 } 15380 15381 return New; 15382 } 15383 15384 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 15385 SourceLocation LocAfterDecls) { 15386 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 15387 15388 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration 15389 // in the declaration list shall have at least one declarator, those 15390 // declarators shall only declare identifiers from the identifier list, and 15391 // every identifier in the identifier list shall be declared. 15392 // 15393 // C89 3.7.1p5 "If a declarator includes an identifier list, only the 15394 // identifiers it names shall be declared in the declaration list." 15395 // 15396 // This is why we only diagnose in C99 and later. Note, the other conditions 15397 // listed are checked elsewhere. 15398 if (!FTI.hasPrototype) { 15399 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 15400 --i; 15401 if (FTI.Params[i].Param == nullptr) { 15402 if (getLangOpts().C99) { 15403 SmallString<256> Code; 15404 llvm::raw_svector_ostream(Code) 15405 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 15406 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 15407 << FTI.Params[i].Ident 15408 << FixItHint::CreateInsertion(LocAfterDecls, Code); 15409 } 15410 15411 // Implicitly declare the argument as type 'int' for lack of a better 15412 // type. 15413 AttributeFactory attrs; 15414 DeclSpec DS(attrs); 15415 const char* PrevSpec; // unused 15416 unsigned DiagID; // unused 15417 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 15418 DiagID, Context.getPrintingPolicy()); 15419 // Use the identifier location for the type source range. 15420 DS.SetRangeStart(FTI.Params[i].IdentLoc); 15421 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 15422 Declarator ParamD(DS, ParsedAttributesView::none(), 15423 DeclaratorContext::KNRTypeList); 15424 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 15425 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 15426 } 15427 } 15428 } 15429 } 15430 15431 Decl * 15432 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 15433 MultiTemplateParamsArg TemplateParameterLists, 15434 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) { 15435 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 15436 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 15437 Scope *ParentScope = FnBodyScope->getParent(); 15438 15439 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 15440 // we define a non-templated function definition, we will create a declaration 15441 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 15442 // The base function declaration will have the equivalent of an `omp declare 15443 // variant` annotation which specifies the mangled definition as a 15444 // specialization function under the OpenMP context defined as part of the 15445 // `omp begin declare variant`. 15446 SmallVector<FunctionDecl *, 4> Bases; 15447 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 15448 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 15449 ParentScope, D, TemplateParameterLists, Bases); 15450 15451 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 15452 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 15453 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind); 15454 15455 if (!Bases.empty()) 15456 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 15457 15458 return Dcl; 15459 } 15460 15461 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 15462 Consumer.HandleInlineFunctionDefinition(D); 15463 } 15464 15465 static bool FindPossiblePrototype(const FunctionDecl *FD, 15466 const FunctionDecl *&PossiblePrototype) { 15467 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev; 15468 Prev = Prev->getPreviousDecl()) { 15469 // Ignore any declarations that occur in function or method 15470 // scope, because they aren't visible from the header. 15471 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 15472 continue; 15473 15474 PossiblePrototype = Prev; 15475 return Prev->getType()->isFunctionProtoType(); 15476 } 15477 return false; 15478 } 15479 15480 static bool 15481 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 15482 const FunctionDecl *&PossiblePrototype) { 15483 // Don't warn about invalid declarations. 15484 if (FD->isInvalidDecl()) 15485 return false; 15486 15487 // Or declarations that aren't global. 15488 if (!FD->isGlobal()) 15489 return false; 15490 15491 // Don't warn about C++ member functions. 15492 if (isa<CXXMethodDecl>(FD)) 15493 return false; 15494 15495 // Don't warn about 'main'. 15496 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 15497 if (IdentifierInfo *II = FD->getIdentifier()) 15498 if (II->isStr("main") || II->isStr("efi_main")) 15499 return false; 15500 15501 // Don't warn about inline functions. 15502 if (FD->isInlined()) 15503 return false; 15504 15505 // Don't warn about function templates. 15506 if (FD->getDescribedFunctionTemplate()) 15507 return false; 15508 15509 // Don't warn about function template specializations. 15510 if (FD->isFunctionTemplateSpecialization()) 15511 return false; 15512 15513 // Don't warn for OpenCL kernels. 15514 if (FD->hasAttr<OpenCLKernelAttr>()) 15515 return false; 15516 15517 // Don't warn on explicitly deleted functions. 15518 if (FD->isDeleted()) 15519 return false; 15520 15521 // Don't warn on implicitly local functions (such as having local-typed 15522 // parameters). 15523 if (!FD->isExternallyVisible()) 15524 return false; 15525 15526 // If we were able to find a potential prototype, don't warn. 15527 if (FindPossiblePrototype(FD, PossiblePrototype)) 15528 return false; 15529 15530 return true; 15531 } 15532 15533 void 15534 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 15535 const FunctionDecl *EffectiveDefinition, 15536 SkipBodyInfo *SkipBody) { 15537 const FunctionDecl *Definition = EffectiveDefinition; 15538 if (!Definition && 15539 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 15540 return; 15541 15542 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 15543 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 15544 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 15545 // A merged copy of the same function, instantiated as a member of 15546 // the same class, is OK. 15547 if (declaresSameEntity(OrigFD, OrigDef) && 15548 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 15549 cast<Decl>(FD->getLexicalDeclContext()))) 15550 return; 15551 } 15552 } 15553 } 15554 15555 if (canRedefineFunction(Definition, getLangOpts())) 15556 return; 15557 15558 // Don't emit an error when this is redefinition of a typo-corrected 15559 // definition. 15560 if (TypoCorrectedFunctionDefinitions.count(Definition)) 15561 return; 15562 15563 // If we don't have a visible definition of the function, and it's inline or 15564 // a template, skip the new definition. 15565 if (SkipBody && !hasVisibleDefinition(Definition) && 15566 (Definition->getFormalLinkage() == Linkage::Internal || 15567 Definition->isInlined() || Definition->getDescribedFunctionTemplate() || 15568 Definition->getNumTemplateParameterLists())) { 15569 SkipBody->ShouldSkip = true; 15570 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 15571 if (auto *TD = Definition->getDescribedFunctionTemplate()) 15572 makeMergedDefinitionVisible(TD); 15573 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 15574 return; 15575 } 15576 15577 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 15578 Definition->getStorageClass() == SC_Extern) 15579 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 15580 << FD << getLangOpts().CPlusPlus; 15581 else 15582 Diag(FD->getLocation(), diag::err_redefinition) << FD; 15583 15584 Diag(Definition->getLocation(), diag::note_previous_definition); 15585 FD->setInvalidDecl(); 15586 } 15587 15588 LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) { 15589 CXXRecordDecl *LambdaClass = CallOperator->getParent(); 15590 15591 LambdaScopeInfo *LSI = PushLambdaScope(); 15592 LSI->CallOperator = CallOperator; 15593 LSI->Lambda = LambdaClass; 15594 LSI->ReturnType = CallOperator->getReturnType(); 15595 // This function in calls in situation where the context of the call operator 15596 // is not entered, so we set AfterParameterList to false, so that 15597 // `tryCaptureVariable` finds explicit captures in the appropriate context. 15598 LSI->AfterParameterList = false; 15599 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 15600 15601 if (LCD == LCD_None) 15602 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 15603 else if (LCD == LCD_ByCopy) 15604 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 15605 else if (LCD == LCD_ByRef) 15606 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 15607 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 15608 15609 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 15610 LSI->Mutable = !CallOperator->isConst(); 15611 if (CallOperator->isExplicitObjectMemberFunction()) 15612 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0); 15613 15614 // Add the captures to the LSI so they can be noted as already 15615 // captured within tryCaptureVar. 15616 auto I = LambdaClass->field_begin(); 15617 for (const auto &C : LambdaClass->captures()) { 15618 if (C.capturesVariable()) { 15619 ValueDecl *VD = C.getCapturedVar(); 15620 if (VD->isInitCapture()) 15621 CurrentInstantiationScope->InstantiatedLocal(VD, VD); 15622 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 15623 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 15624 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 15625 /*EllipsisLoc*/C.isPackExpansion() 15626 ? C.getEllipsisLoc() : SourceLocation(), 15627 I->getType(), /*Invalid*/false); 15628 15629 } else if (C.capturesThis()) { 15630 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 15631 C.getCaptureKind() == LCK_StarThis); 15632 } else { 15633 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 15634 I->getType()); 15635 } 15636 ++I; 15637 } 15638 return LSI; 15639 } 15640 15641 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 15642 SkipBodyInfo *SkipBody, 15643 FnBodyKind BodyKind) { 15644 if (!D) { 15645 // Parsing the function declaration failed in some way. Push on a fake scope 15646 // anyway so we can try to parse the function body. 15647 PushFunctionScope(); 15648 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15649 return D; 15650 } 15651 15652 FunctionDecl *FD = nullptr; 15653 15654 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 15655 FD = FunTmpl->getTemplatedDecl(); 15656 else 15657 FD = cast<FunctionDecl>(D); 15658 15659 // Do not push if it is a lambda because one is already pushed when building 15660 // the lambda in ActOnStartOfLambdaDefinition(). 15661 if (!isLambdaCallOperator(FD)) 15662 // [expr.const]/p14.1 15663 // An expression or conversion is in an immediate function context if it is 15664 // potentially evaluated and either: its innermost enclosing non-block scope 15665 // is a function parameter scope of an immediate function. 15666 PushExpressionEvaluationContext( 15667 FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext 15668 : ExprEvalContexts.back().Context); 15669 15670 // Each ExpressionEvaluationContextRecord also keeps track of whether the 15671 // context is nested in an immediate function context, so smaller contexts 15672 // that appear inside immediate functions (like variable initializers) are 15673 // considered to be inside an immediate function context even though by 15674 // themselves they are not immediate function contexts. But when a new 15675 // function is entered, we need to reset this tracking, since the entered 15676 // function might be not an immediate function. 15677 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval(); 15678 ExprEvalContexts.back().InImmediateEscalatingFunctionContext = 15679 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating(); 15680 15681 // Check for defining attributes before the check for redefinition. 15682 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 15683 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 15684 FD->dropAttr<AliasAttr>(); 15685 FD->setInvalidDecl(); 15686 } 15687 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 15688 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 15689 FD->dropAttr<IFuncAttr>(); 15690 FD->setInvalidDecl(); 15691 } 15692 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) { 15693 if (!Context.getTargetInfo().hasFeature("fmv") && 15694 !Attr->isDefaultVersion()) { 15695 // If function multi versioning disabled skip parsing function body 15696 // defined with non-default target_version attribute 15697 if (SkipBody) 15698 SkipBody->ShouldSkip = true; 15699 return nullptr; 15700 } 15701 } 15702 15703 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 15704 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 15705 Ctor->isDefaultConstructor() && 15706 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 15707 // If this is an MS ABI dllexport default constructor, instantiate any 15708 // default arguments. 15709 InstantiateDefaultCtorDefaultArgs(Ctor); 15710 } 15711 } 15712 15713 // See if this is a redefinition. If 'will have body' (or similar) is already 15714 // set, then these checks were already performed when it was set. 15715 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 15716 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 15717 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 15718 15719 // If we're skipping the body, we're done. Don't enter the scope. 15720 if (SkipBody && SkipBody->ShouldSkip) 15721 return D; 15722 } 15723 15724 // Mark this function as "will have a body eventually". This lets users to 15725 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 15726 // this function. 15727 FD->setWillHaveBody(); 15728 15729 // If we are instantiating a generic lambda call operator, push 15730 // a LambdaScopeInfo onto the function stack. But use the information 15731 // that's already been calculated (ActOnLambdaExpr) to prime the current 15732 // LambdaScopeInfo. 15733 // When the template operator is being specialized, the LambdaScopeInfo, 15734 // has to be properly restored so that tryCaptureVariable doesn't try 15735 // and capture any new variables. In addition when calculating potential 15736 // captures during transformation of nested lambdas, it is necessary to 15737 // have the LSI properly restored. 15738 if (isGenericLambdaCallOperatorSpecialization(FD)) { 15739 assert(inTemplateInstantiation() && 15740 "There should be an active template instantiation on the stack " 15741 "when instantiating a generic lambda!"); 15742 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D)); 15743 } else { 15744 // Enter a new function scope 15745 PushFunctionScope(); 15746 } 15747 15748 // Builtin functions cannot be defined. 15749 if (unsigned BuiltinID = FD->getBuiltinID()) { 15750 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 15751 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 15752 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 15753 FD->setInvalidDecl(); 15754 } 15755 } 15756 15757 // The return type of a function definition must be complete (C99 6.9.1p3). 15758 // C++23 [dcl.fct.def.general]/p2 15759 // The type of [...] the return for a function definition 15760 // shall not be a (possibly cv-qualified) class type that is incomplete 15761 // or abstract within the function body unless the function is deleted. 15762 QualType ResultType = FD->getReturnType(); 15763 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 15764 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete && 15765 (RequireCompleteType(FD->getLocation(), ResultType, 15766 diag::err_func_def_incomplete_result) || 15767 RequireNonAbstractType(FD->getLocation(), FD->getReturnType(), 15768 diag::err_abstract_type_in_decl, 15769 AbstractReturnType))) 15770 FD->setInvalidDecl(); 15771 15772 if (FnBodyScope) 15773 PushDeclContext(FnBodyScope, FD); 15774 15775 // Check the validity of our function parameters 15776 if (BodyKind != FnBodyKind::Delete) 15777 CheckParmsForFunctionDef(FD->parameters(), 15778 /*CheckParameterNames=*/true); 15779 15780 // Add non-parameter declarations already in the function to the current 15781 // scope. 15782 if (FnBodyScope) { 15783 for (Decl *NPD : FD->decls()) { 15784 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 15785 if (!NonParmDecl) 15786 continue; 15787 assert(!isa<ParmVarDecl>(NonParmDecl) && 15788 "parameters should not be in newly created FD yet"); 15789 15790 // If the decl has a name, make it accessible in the current scope. 15791 if (NonParmDecl->getDeclName()) 15792 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 15793 15794 // Similarly, dive into enums and fish their constants out, making them 15795 // accessible in this scope. 15796 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 15797 for (auto *EI : ED->enumerators()) 15798 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 15799 } 15800 } 15801 } 15802 15803 // Introduce our parameters into the function scope 15804 for (auto *Param : FD->parameters()) { 15805 Param->setOwningFunction(FD); 15806 15807 // If this has an identifier, add it to the scope stack. 15808 if (Param->getIdentifier() && FnBodyScope) { 15809 CheckShadow(FnBodyScope, Param); 15810 15811 PushOnScopeChains(Param, FnBodyScope); 15812 } 15813 } 15814 15815 // C++ [module.import/6] external definitions are not permitted in header 15816 // units. Deleted and Defaulted functions are implicitly inline (but the 15817 // inline state is not set at this point, so check the BodyKind explicitly). 15818 // FIXME: Consider an alternate location for the test where the inlined() 15819 // state is complete. 15820 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() && 15821 !FD->isInvalidDecl() && !FD->isInlined() && 15822 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default && 15823 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() && 15824 !FD->isTemplateInstantiation()) { 15825 assert(FD->isThisDeclarationADefinition()); 15826 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit); 15827 FD->setInvalidDecl(); 15828 } 15829 15830 // Ensure that the function's exception specification is instantiated. 15831 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 15832 ResolveExceptionSpec(D->getLocation(), FPT); 15833 15834 // dllimport cannot be applied to non-inline function definitions. 15835 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 15836 !FD->isTemplateInstantiation()) { 15837 assert(!FD->hasAttr<DLLExportAttr>()); 15838 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 15839 FD->setInvalidDecl(); 15840 return D; 15841 } 15842 // We want to attach documentation to original Decl (which might be 15843 // a function template). 15844 ActOnDocumentableDecl(D); 15845 if (getCurLexicalContext()->isObjCContainer() && 15846 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 15847 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 15848 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 15849 15850 return D; 15851 } 15852 15853 /// Given the set of return statements within a function body, 15854 /// compute the variables that are subject to the named return value 15855 /// optimization. 15856 /// 15857 /// Each of the variables that is subject to the named return value 15858 /// optimization will be marked as NRVO variables in the AST, and any 15859 /// return statement that has a marked NRVO variable as its NRVO candidate can 15860 /// use the named return value optimization. 15861 /// 15862 /// This function applies a very simplistic algorithm for NRVO: if every return 15863 /// statement in the scope of a variable has the same NRVO candidate, that 15864 /// candidate is an NRVO variable. 15865 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 15866 ReturnStmt **Returns = Scope->Returns.data(); 15867 15868 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 15869 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 15870 if (!NRVOCandidate->isNRVOVariable()) 15871 Returns[I]->setNRVOCandidate(nullptr); 15872 } 15873 } 15874 } 15875 15876 bool Sema::canDelayFunctionBody(const Declarator &D) { 15877 // We can't delay parsing the body of a constexpr function template (yet). 15878 if (D.getDeclSpec().hasConstexprSpecifier()) 15879 return false; 15880 15881 // We can't delay parsing the body of a function template with a deduced 15882 // return type (yet). 15883 if (D.getDeclSpec().hasAutoTypeSpec()) { 15884 // If the placeholder introduces a non-deduced trailing return type, 15885 // we can still delay parsing it. 15886 if (D.getNumTypeObjects()) { 15887 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 15888 if (Outer.Kind == DeclaratorChunk::Function && 15889 Outer.Fun.hasTrailingReturnType()) { 15890 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 15891 return Ty.isNull() || !Ty->isUndeducedType(); 15892 } 15893 } 15894 return false; 15895 } 15896 15897 return true; 15898 } 15899 15900 bool Sema::canSkipFunctionBody(Decl *D) { 15901 // We cannot skip the body of a function (or function template) which is 15902 // constexpr, since we may need to evaluate its body in order to parse the 15903 // rest of the file. 15904 // We cannot skip the body of a function with an undeduced return type, 15905 // because any callers of that function need to know the type. 15906 if (const FunctionDecl *FD = D->getAsFunction()) { 15907 if (FD->isConstexpr()) 15908 return false; 15909 // We can't simply call Type::isUndeducedType here, because inside template 15910 // auto can be deduced to a dependent type, which is not considered 15911 // "undeduced". 15912 if (FD->getReturnType()->getContainedDeducedType()) 15913 return false; 15914 } 15915 return Consumer.shouldSkipFunctionBody(D); 15916 } 15917 15918 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 15919 if (!Decl) 15920 return nullptr; 15921 if (FunctionDecl *FD = Decl->getAsFunction()) 15922 FD->setHasSkippedBody(); 15923 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 15924 MD->setHasSkippedBody(); 15925 return Decl; 15926 } 15927 15928 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 15929 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false); 15930 } 15931 15932 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 15933 /// body. 15934 class ExitFunctionBodyRAII { 15935 public: 15936 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 15937 ~ExitFunctionBodyRAII() { 15938 if (!IsLambda) 15939 S.PopExpressionEvaluationContext(); 15940 } 15941 15942 private: 15943 Sema &S; 15944 bool IsLambda = false; 15945 }; 15946 15947 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 15948 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 15949 15950 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 15951 if (EscapeInfo.count(BD)) 15952 return EscapeInfo[BD]; 15953 15954 bool R = false; 15955 const BlockDecl *CurBD = BD; 15956 15957 do { 15958 R = !CurBD->doesNotEscape(); 15959 if (R) 15960 break; 15961 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 15962 } while (CurBD); 15963 15964 return EscapeInfo[BD] = R; 15965 }; 15966 15967 // If the location where 'self' is implicitly retained is inside a escaping 15968 // block, emit a diagnostic. 15969 for (const std::pair<SourceLocation, const BlockDecl *> &P : 15970 S.ImplicitlyRetainedSelfLocs) 15971 if (IsOrNestedInEscapingBlock(P.second)) 15972 S.Diag(P.first, diag::warn_implicitly_retains_self) 15973 << FixItHint::CreateInsertion(P.first, "self->"); 15974 } 15975 15976 static bool methodHasName(const FunctionDecl *FD, StringRef Name) { 15977 return isa<CXXMethodDecl>(FD) && FD->param_empty() && 15978 FD->getDeclName().isIdentifier() && FD->getName().equals(Name); 15979 } 15980 15981 bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) { 15982 return methodHasName(FD, "get_return_object"); 15983 } 15984 15985 bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) { 15986 return FD->isStatic() && 15987 methodHasName(FD, "get_return_object_on_allocation_failure"); 15988 } 15989 15990 void Sema::CheckCoroutineWrapper(FunctionDecl *FD) { 15991 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl(); 15992 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>()) 15993 return; 15994 // Allow some_promise_type::get_return_object(). 15995 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD)) 15996 return; 15997 if (!FD->hasAttr<CoroWrapperAttr>()) 15998 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD; 15999 } 16000 16001 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 16002 bool IsInstantiation) { 16003 FunctionScopeInfo *FSI = getCurFunction(); 16004 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 16005 16006 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 16007 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 16008 16009 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 16010 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 16011 16012 // If we skip function body, we can't tell if a function is a coroutine. 16013 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) { 16014 if (FSI->isCoroutine()) 16015 CheckCompletedCoroutineBody(FD, Body); 16016 else 16017 CheckCoroutineWrapper(FD); 16018 } 16019 16020 { 16021 // Do not call PopExpressionEvaluationContext() if it is a lambda because 16022 // one is already popped when finishing the lambda in BuildLambdaExpr(). 16023 // This is meant to pop the context added in ActOnStartOfFunctionDef(). 16024 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 16025 if (FD) { 16026 FD->setBody(Body); 16027 FD->setWillHaveBody(false); 16028 CheckImmediateEscalatingFunctionDefinition(FD, FSI); 16029 16030 if (getLangOpts().CPlusPlus14) { 16031 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 16032 FD->getReturnType()->isUndeducedType()) { 16033 // For a function with a deduced result type to return void, 16034 // the result type as written must be 'auto' or 'decltype(auto)', 16035 // possibly cv-qualified or constrained, but not ref-qualified. 16036 if (!FD->getReturnType()->getAs<AutoType>()) { 16037 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 16038 << FD->getReturnType(); 16039 FD->setInvalidDecl(); 16040 } else { 16041 // Falling off the end of the function is the same as 'return;'. 16042 Expr *Dummy = nullptr; 16043 if (DeduceFunctionTypeFromReturnExpr( 16044 FD, dcl->getLocation(), Dummy, 16045 FD->getReturnType()->getAs<AutoType>())) 16046 FD->setInvalidDecl(); 16047 } 16048 } 16049 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 16050 // In C++11, we don't use 'auto' deduction rules for lambda call 16051 // operators because we don't support return type deduction. 16052 auto *LSI = getCurLambda(); 16053 if (LSI->HasImplicitReturnType) { 16054 deduceClosureReturnType(*LSI); 16055 16056 // C++11 [expr.prim.lambda]p4: 16057 // [...] if there are no return statements in the compound-statement 16058 // [the deduced type is] the type void 16059 QualType RetType = 16060 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 16061 16062 // Update the return type to the deduced type. 16063 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 16064 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 16065 Proto->getExtProtoInfo())); 16066 } 16067 } 16068 16069 // If the function implicitly returns zero (like 'main') or is naked, 16070 // don't complain about missing return statements. 16071 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 16072 WP.disableCheckFallThrough(); 16073 16074 // MSVC permits the use of pure specifier (=0) on function definition, 16075 // defined at class scope, warn about this non-standard construct. 16076 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() && 16077 !FD->isOutOfLine()) 16078 Diag(FD->getLocation(), diag::ext_pure_function_definition); 16079 16080 if (!FD->isInvalidDecl()) { 16081 // Don't diagnose unused parameters of defaulted, deleted or naked 16082 // functions. 16083 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() && 16084 !FD->hasAttr<NakedAttr>()) 16085 DiagnoseUnusedParameters(FD->parameters()); 16086 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 16087 FD->getReturnType(), FD); 16088 16089 // If this is a structor, we need a vtable. 16090 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 16091 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 16092 else if (CXXDestructorDecl *Destructor = 16093 dyn_cast<CXXDestructorDecl>(FD)) 16094 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 16095 16096 // Try to apply the named return value optimization. We have to check 16097 // if we can do this here because lambdas keep return statements around 16098 // to deduce an implicit return type. 16099 if (FD->getReturnType()->isRecordType() && 16100 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 16101 computeNRVO(Body, FSI); 16102 } 16103 16104 // GNU warning -Wmissing-prototypes: 16105 // Warn if a global function is defined without a previous 16106 // prototype declaration. This warning is issued even if the 16107 // definition itself provides a prototype. The aim is to detect 16108 // global functions that fail to be declared in header files. 16109 const FunctionDecl *PossiblePrototype = nullptr; 16110 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 16111 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 16112 16113 if (PossiblePrototype) { 16114 // We found a declaration that is not a prototype, 16115 // but that could be a zero-parameter prototype 16116 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 16117 TypeLoc TL = TI->getTypeLoc(); 16118 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 16119 Diag(PossiblePrototype->getLocation(), 16120 diag::note_declaration_not_a_prototype) 16121 << (FD->getNumParams() != 0) 16122 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( 16123 FTL.getRParenLoc(), "void") 16124 : FixItHint{}); 16125 } 16126 } else { 16127 // Returns true if the token beginning at this Loc is `const`. 16128 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 16129 const LangOptions &LangOpts) { 16130 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 16131 if (LocInfo.first.isInvalid()) 16132 return false; 16133 16134 bool Invalid = false; 16135 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 16136 if (Invalid) 16137 return false; 16138 16139 if (LocInfo.second > Buffer.size()) 16140 return false; 16141 16142 const char *LexStart = Buffer.data() + LocInfo.second; 16143 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 16144 16145 return StartTok.consume_front("const") && 16146 (StartTok.empty() || isWhitespace(StartTok[0]) || 16147 StartTok.starts_with("/*") || StartTok.starts_with("//")); 16148 }; 16149 16150 auto findBeginLoc = [&]() { 16151 // If the return type has `const` qualifier, we want to insert 16152 // `static` before `const` (and not before the typename). 16153 if ((FD->getReturnType()->isAnyPointerType() && 16154 FD->getReturnType()->getPointeeType().isConstQualified()) || 16155 FD->getReturnType().isConstQualified()) { 16156 // But only do this if we can determine where the `const` is. 16157 16158 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 16159 getLangOpts())) 16160 16161 return FD->getBeginLoc(); 16162 } 16163 return FD->getTypeSpecStartLoc(); 16164 }; 16165 Diag(FD->getTypeSpecStartLoc(), 16166 diag::note_static_for_internal_linkage) 16167 << /* function */ 1 16168 << (FD->getStorageClass() == SC_None 16169 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 16170 : FixItHint{}); 16171 } 16172 } 16173 16174 // We might not have found a prototype because we didn't wish to warn on 16175 // the lack of a missing prototype. Try again without the checks for 16176 // whether we want to warn on the missing prototype. 16177 if (!PossiblePrototype) 16178 (void)FindPossiblePrototype(FD, PossiblePrototype); 16179 16180 // If the function being defined does not have a prototype, then we may 16181 // need to diagnose it as changing behavior in C23 because we now know 16182 // whether the function accepts arguments or not. This only handles the 16183 // case where the definition has no prototype but does have parameters 16184 // and either there is no previous potential prototype, or the previous 16185 // potential prototype also has no actual prototype. This handles cases 16186 // like: 16187 // void f(); void f(a) int a; {} 16188 // void g(a) int a; {} 16189 // See MergeFunctionDecl() for other cases of the behavior change 16190 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 16191 // type without a prototype. 16192 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 && 16193 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() && 16194 !PossiblePrototype->isImplicit()))) { 16195 // The function definition has parameters, so this will change behavior 16196 // in C23. If there is a possible prototype, it comes before the 16197 // function definition. 16198 // FIXME: The declaration may have already been diagnosed as being 16199 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but 16200 // there's no way to test for the "changes behavior" condition in 16201 // SemaType.cpp when forming the declaration's function type. So, we do 16202 // this awkward dance instead. 16203 // 16204 // If we have a possible prototype and it declares a function with a 16205 // prototype, we don't want to diagnose it; if we have a possible 16206 // prototype and it has no prototype, it may have already been 16207 // diagnosed in SemaType.cpp as deprecated depending on whether 16208 // -Wstrict-prototypes is enabled. If we already warned about it being 16209 // deprecated, add a note that it also changes behavior. If we didn't 16210 // warn about it being deprecated (because the diagnostic is not 16211 // enabled), warn now that it is deprecated and changes behavior. 16212 16213 // This K&R C function definition definitely changes behavior in C23, 16214 // so diagnose it. 16215 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior) 16216 << /*definition*/ 1 << /* not supported in C23 */ 0; 16217 16218 // If we have a possible prototype for the function which is a user- 16219 // visible declaration, we already tested that it has no prototype. 16220 // This will change behavior in C23. This gets a warning rather than a 16221 // note because it's the same behavior-changing problem as with the 16222 // definition. 16223 if (PossiblePrototype) 16224 Diag(PossiblePrototype->getLocation(), 16225 diag::warn_non_prototype_changes_behavior) 16226 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1 16227 << /*definition*/ 1; 16228 } 16229 16230 // Warn on CPUDispatch with an actual body. 16231 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 16232 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 16233 if (!CmpndBody->body_empty()) 16234 Diag(CmpndBody->body_front()->getBeginLoc(), 16235 diag::warn_dispatch_body_ignored); 16236 16237 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 16238 const CXXMethodDecl *KeyFunction; 16239 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 16240 MD->isVirtual() && 16241 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 16242 MD == KeyFunction->getCanonicalDecl()) { 16243 // Update the key-function state if necessary for this ABI. 16244 if (FD->isInlined() && 16245 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 16246 Context.setNonKeyFunction(MD); 16247 16248 // If the newly-chosen key function is already defined, then we 16249 // need to mark the vtable as used retroactively. 16250 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 16251 const FunctionDecl *Definition; 16252 if (KeyFunction && KeyFunction->isDefined(Definition)) 16253 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 16254 } else { 16255 // We just defined they key function; mark the vtable as used. 16256 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 16257 } 16258 } 16259 } 16260 16261 assert( 16262 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 16263 "Function parsing confused"); 16264 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 16265 assert(MD == getCurMethodDecl() && "Method parsing confused"); 16266 MD->setBody(Body); 16267 if (!MD->isInvalidDecl()) { 16268 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 16269 MD->getReturnType(), MD); 16270 16271 if (Body) 16272 computeNRVO(Body, FSI); 16273 } 16274 if (FSI->ObjCShouldCallSuper) { 16275 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 16276 << MD->getSelector().getAsString(); 16277 FSI->ObjCShouldCallSuper = false; 16278 } 16279 if (FSI->ObjCWarnForNoDesignatedInitChain) { 16280 const ObjCMethodDecl *InitMethod = nullptr; 16281 bool isDesignated = 16282 MD->isDesignatedInitializerForTheInterface(&InitMethod); 16283 assert(isDesignated && InitMethod); 16284 (void)isDesignated; 16285 16286 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 16287 auto IFace = MD->getClassInterface(); 16288 if (!IFace) 16289 return false; 16290 auto SuperD = IFace->getSuperClass(); 16291 if (!SuperD) 16292 return false; 16293 return SuperD->getIdentifier() == 16294 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 16295 }; 16296 // Don't issue this warning for unavailable inits or direct subclasses 16297 // of NSObject. 16298 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 16299 Diag(MD->getLocation(), 16300 diag::warn_objc_designated_init_missing_super_call); 16301 Diag(InitMethod->getLocation(), 16302 diag::note_objc_designated_init_marked_here); 16303 } 16304 FSI->ObjCWarnForNoDesignatedInitChain = false; 16305 } 16306 if (FSI->ObjCWarnForNoInitDelegation) { 16307 // Don't issue this warning for unavaialable inits. 16308 if (!MD->isUnavailable()) 16309 Diag(MD->getLocation(), 16310 diag::warn_objc_secondary_init_missing_init_call); 16311 FSI->ObjCWarnForNoInitDelegation = false; 16312 } 16313 16314 diagnoseImplicitlyRetainedSelf(*this); 16315 } else { 16316 // Parsing the function declaration failed in some way. Pop the fake scope 16317 // we pushed on. 16318 PopFunctionScopeInfo(ActivePolicy, dcl); 16319 return nullptr; 16320 } 16321 16322 if (Body && FSI->HasPotentialAvailabilityViolations) 16323 DiagnoseUnguardedAvailabilityViolations(dcl); 16324 16325 assert(!FSI->ObjCShouldCallSuper && 16326 "This should only be set for ObjC methods, which should have been " 16327 "handled in the block above."); 16328 16329 // Verify and clean out per-function state. 16330 if (Body && (!FD || !FD->isDefaulted())) { 16331 // C++ constructors that have function-try-blocks can't have return 16332 // statements in the handlers of that block. (C++ [except.handle]p14) 16333 // Verify this. 16334 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 16335 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 16336 16337 // Verify that gotos and switch cases don't jump into scopes illegally. 16338 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) 16339 DiagnoseInvalidJumps(Body); 16340 16341 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 16342 if (!Destructor->getParent()->isDependentType()) 16343 CheckDestructor(Destructor); 16344 16345 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 16346 Destructor->getParent()); 16347 } 16348 16349 // If any errors have occurred, clear out any temporaries that may have 16350 // been leftover. This ensures that these temporaries won't be picked up 16351 // for deletion in some later function. 16352 if (hasUncompilableErrorOccurred() || 16353 hasAnyUnrecoverableErrorsInThisFunction() || 16354 getDiagnostics().getSuppressAllDiagnostics()) { 16355 DiscardCleanupsInEvaluationContext(); 16356 } 16357 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { 16358 // Since the body is valid, issue any analysis-based warnings that are 16359 // enabled. 16360 ActivePolicy = &WP; 16361 } 16362 16363 if (!IsInstantiation && FD && 16364 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) && 16365 !FD->isInvalidDecl() && 16366 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 16367 FD->setInvalidDecl(); 16368 16369 if (FD && FD->hasAttr<NakedAttr>()) { 16370 for (const Stmt *S : Body->children()) { 16371 // Allow local register variables without initializer as they don't 16372 // require prologue. 16373 bool RegisterVariables = false; 16374 if (auto *DS = dyn_cast<DeclStmt>(S)) { 16375 for (const auto *Decl : DS->decls()) { 16376 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 16377 RegisterVariables = 16378 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 16379 if (!RegisterVariables) 16380 break; 16381 } 16382 } 16383 } 16384 if (RegisterVariables) 16385 continue; 16386 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 16387 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 16388 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 16389 FD->setInvalidDecl(); 16390 break; 16391 } 16392 } 16393 } 16394 16395 assert(ExprCleanupObjects.size() == 16396 ExprEvalContexts.back().NumCleanupObjects && 16397 "Leftover temporaries in function"); 16398 assert(!Cleanup.exprNeedsCleanups() && 16399 "Unaccounted cleanups in function"); 16400 assert(MaybeODRUseExprs.empty() && 16401 "Leftover expressions for odr-use checking"); 16402 } 16403 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop 16404 // the declaration context below. Otherwise, we're unable to transform 16405 // 'this' expressions when transforming immediate context functions. 16406 16407 if (!IsInstantiation) 16408 PopDeclContext(); 16409 16410 PopFunctionScopeInfo(ActivePolicy, dcl); 16411 // If any errors have occurred, clear out any temporaries that may have 16412 // been leftover. This ensures that these temporaries won't be picked up for 16413 // deletion in some later function. 16414 if (hasUncompilableErrorOccurred()) { 16415 DiscardCleanupsInEvaluationContext(); 16416 } 16417 16418 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice || 16419 !LangOpts.OMPTargetTriples.empty())) || 16420 LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 16421 auto ES = getEmissionStatus(FD); 16422 if (ES == Sema::FunctionEmissionStatus::Emitted || 16423 ES == Sema::FunctionEmissionStatus::Unknown) 16424 DeclsToCheckForDeferredDiags.insert(FD); 16425 } 16426 16427 if (FD && !FD->isDeleted()) 16428 checkTypeSupport(FD->getType(), FD->getLocation(), FD); 16429 16430 return dcl; 16431 } 16432 16433 /// When we finish delayed parsing of an attribute, we must attach it to the 16434 /// relevant Decl. 16435 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 16436 ParsedAttributes &Attrs) { 16437 // Always attach attributes to the underlying decl. 16438 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 16439 D = TD->getTemplatedDecl(); 16440 ProcessDeclAttributeList(S, D, Attrs); 16441 16442 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 16443 if (Method->isStatic()) 16444 checkThisInStaticMemberFunctionAttributes(Method); 16445 } 16446 16447 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 16448 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 16449 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 16450 IdentifierInfo &II, Scope *S) { 16451 // It is not valid to implicitly define a function in C23. 16452 assert(LangOpts.implicitFunctionsAllowed() && 16453 "Implicit function declarations aren't allowed in this language mode"); 16454 16455 // Find the scope in which the identifier is injected and the corresponding 16456 // DeclContext. 16457 // FIXME: C89 does not say what happens if there is no enclosing block scope. 16458 // In that case, we inject the declaration into the translation unit scope 16459 // instead. 16460 Scope *BlockScope = S; 16461 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 16462 BlockScope = BlockScope->getParent(); 16463 16464 // Loop until we find a DeclContext that is either a function/method or the 16465 // translation unit, which are the only two valid places to implicitly define 16466 // a function. This avoids accidentally defining the function within a tag 16467 // declaration, for example. 16468 Scope *ContextScope = BlockScope; 16469 while (!ContextScope->getEntity() || 16470 (!ContextScope->getEntity()->isFunctionOrMethod() && 16471 !ContextScope->getEntity()->isTranslationUnit())) 16472 ContextScope = ContextScope->getParent(); 16473 ContextRAII SavedContext(*this, ContextScope->getEntity()); 16474 16475 // Before we produce a declaration for an implicitly defined 16476 // function, see whether there was a locally-scoped declaration of 16477 // this name as a function or variable. If so, use that 16478 // (non-visible) declaration, and complain about it. 16479 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 16480 if (ExternCPrev) { 16481 // We still need to inject the function into the enclosing block scope so 16482 // that later (non-call) uses can see it. 16483 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 16484 16485 // C89 footnote 38: 16486 // If in fact it is not defined as having type "function returning int", 16487 // the behavior is undefined. 16488 if (!isa<FunctionDecl>(ExternCPrev) || 16489 !Context.typesAreCompatible( 16490 cast<FunctionDecl>(ExternCPrev)->getType(), 16491 Context.getFunctionNoProtoType(Context.IntTy))) { 16492 Diag(Loc, diag::ext_use_out_of_scope_declaration) 16493 << ExternCPrev << !getLangOpts().C99; 16494 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 16495 return ExternCPrev; 16496 } 16497 } 16498 16499 // Extension in C99 (defaults to error). Legal in C89, but warn about it. 16500 unsigned diag_id; 16501 if (II.getName().starts_with("__builtin_")) 16502 diag_id = diag::warn_builtin_unknown; 16503 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 16504 else if (getLangOpts().C99) 16505 diag_id = diag::ext_implicit_function_decl_c99; 16506 else 16507 diag_id = diag::warn_implicit_function_decl; 16508 16509 TypoCorrection Corrected; 16510 // Because typo correction is expensive, only do it if the implicit 16511 // function declaration is going to be treated as an error. 16512 // 16513 // Perform the correction before issuing the main diagnostic, as some 16514 // consumers use typo-correction callbacks to enhance the main diagnostic. 16515 if (S && !ExternCPrev && 16516 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) { 16517 DeclFilterCCC<FunctionDecl> CCC{}; 16518 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 16519 S, nullptr, CCC, CTK_NonError); 16520 } 16521 16522 Diag(Loc, diag_id) << &II; 16523 if (Corrected) { 16524 // If the correction is going to suggest an implicitly defined function, 16525 // skip the correction as not being a particularly good idea. 16526 bool Diagnose = true; 16527 if (const auto *D = Corrected.getCorrectionDecl()) 16528 Diagnose = !D->isImplicit(); 16529 if (Diagnose) 16530 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 16531 /*ErrorRecovery*/ false); 16532 } 16533 16534 // If we found a prior declaration of this function, don't bother building 16535 // another one. We've already pushed that one into scope, so there's nothing 16536 // more to do. 16537 if (ExternCPrev) 16538 return ExternCPrev; 16539 16540 // Set a Declarator for the implicit definition: int foo(); 16541 const char *Dummy; 16542 AttributeFactory attrFactory; 16543 DeclSpec DS(attrFactory); 16544 unsigned DiagID; 16545 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 16546 Context.getPrintingPolicy()); 16547 (void)Error; // Silence warning. 16548 assert(!Error && "Error setting up implicit decl!"); 16549 SourceLocation NoLoc; 16550 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block); 16551 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 16552 /*IsAmbiguous=*/false, 16553 /*LParenLoc=*/NoLoc, 16554 /*Params=*/nullptr, 16555 /*NumParams=*/0, 16556 /*EllipsisLoc=*/NoLoc, 16557 /*RParenLoc=*/NoLoc, 16558 /*RefQualifierIsLvalueRef=*/true, 16559 /*RefQualifierLoc=*/NoLoc, 16560 /*MutableLoc=*/NoLoc, EST_None, 16561 /*ESpecRange=*/SourceRange(), 16562 /*Exceptions=*/nullptr, 16563 /*ExceptionRanges=*/nullptr, 16564 /*NumExceptions=*/0, 16565 /*NoexceptExpr=*/nullptr, 16566 /*ExceptionSpecTokens=*/nullptr, 16567 /*DeclsInPrototype=*/std::nullopt, 16568 Loc, Loc, D), 16569 std::move(DS.getAttributes()), SourceLocation()); 16570 D.SetIdentifier(&II, Loc); 16571 16572 // Insert this function into the enclosing block scope. 16573 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 16574 FD->setImplicit(); 16575 16576 AddKnownFunctionAttributes(FD); 16577 16578 return FD; 16579 } 16580 16581 /// If this function is a C++ replaceable global allocation function 16582 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 16583 /// adds any function attributes that we know a priori based on the standard. 16584 /// 16585 /// We need to check for duplicate attributes both here and where user-written 16586 /// attributes are applied to declarations. 16587 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 16588 FunctionDecl *FD) { 16589 if (FD->isInvalidDecl()) 16590 return; 16591 16592 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 16593 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 16594 return; 16595 16596 std::optional<unsigned> AlignmentParam; 16597 bool IsNothrow = false; 16598 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 16599 return; 16600 16601 // C++2a [basic.stc.dynamic.allocation]p4: 16602 // An allocation function that has a non-throwing exception specification 16603 // indicates failure by returning a null pointer value. Any other allocation 16604 // function never returns a null pointer value and indicates failure only by 16605 // throwing an exception [...] 16606 // 16607 // However, -fcheck-new invalidates this possible assumption, so don't add 16608 // NonNull when that is enabled. 16609 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() && 16610 !getLangOpts().CheckNew) 16611 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 16612 16613 // C++2a [basic.stc.dynamic.allocation]p2: 16614 // An allocation function attempts to allocate the requested amount of 16615 // storage. [...] If the request succeeds, the value returned by a 16616 // replaceable allocation function is a [...] pointer value p0 different 16617 // from any previously returned value p1 [...] 16618 // 16619 // However, this particular information is being added in codegen, 16620 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 16621 16622 // C++2a [basic.stc.dynamic.allocation]p2: 16623 // An allocation function attempts to allocate the requested amount of 16624 // storage. If it is successful, it returns the address of the start of a 16625 // block of storage whose length in bytes is at least as large as the 16626 // requested size. 16627 if (!FD->hasAttr<AllocSizeAttr>()) { 16628 FD->addAttr(AllocSizeAttr::CreateImplicit( 16629 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 16630 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 16631 } 16632 16633 // C++2a [basic.stc.dynamic.allocation]p3: 16634 // For an allocation function [...], the pointer returned on a successful 16635 // call shall represent the address of storage that is aligned as follows: 16636 // (3.1) If the allocation function takes an argument of type 16637 // std::align_val_t, the storage will have the alignment 16638 // specified by the value of this argument. 16639 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) { 16640 FD->addAttr(AllocAlignAttr::CreateImplicit( 16641 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation())); 16642 } 16643 16644 // FIXME: 16645 // C++2a [basic.stc.dynamic.allocation]p3: 16646 // For an allocation function [...], the pointer returned on a successful 16647 // call shall represent the address of storage that is aligned as follows: 16648 // (3.2) Otherwise, if the allocation function is named operator new[], 16649 // the storage is aligned for any object that does not have 16650 // new-extended alignment ([basic.align]) and is no larger than the 16651 // requested size. 16652 // (3.3) Otherwise, the storage is aligned for any object that does not 16653 // have new-extended alignment and is of the requested size. 16654 } 16655 16656 /// Adds any function attributes that we know a priori based on 16657 /// the declaration of this function. 16658 /// 16659 /// These attributes can apply both to implicitly-declared builtins 16660 /// (like __builtin___printf_chk) or to library-declared functions 16661 /// like NSLog or printf. 16662 /// 16663 /// We need to check for duplicate attributes both here and where user-written 16664 /// attributes are applied to declarations. 16665 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 16666 if (FD->isInvalidDecl()) 16667 return; 16668 16669 // If this is a built-in function, map its builtin attributes to 16670 // actual attributes. 16671 if (unsigned BuiltinID = FD->getBuiltinID()) { 16672 // Handle printf-formatting attributes. 16673 unsigned FormatIdx; 16674 bool HasVAListArg; 16675 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 16676 if (!FD->hasAttr<FormatAttr>()) { 16677 const char *fmt = "printf"; 16678 unsigned int NumParams = FD->getNumParams(); 16679 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 16680 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 16681 fmt = "NSString"; 16682 FD->addAttr(FormatAttr::CreateImplicit(Context, 16683 &Context.Idents.get(fmt), 16684 FormatIdx+1, 16685 HasVAListArg ? 0 : FormatIdx+2, 16686 FD->getLocation())); 16687 } 16688 } 16689 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 16690 HasVAListArg)) { 16691 if (!FD->hasAttr<FormatAttr>()) 16692 FD->addAttr(FormatAttr::CreateImplicit(Context, 16693 &Context.Idents.get("scanf"), 16694 FormatIdx+1, 16695 HasVAListArg ? 0 : FormatIdx+2, 16696 FD->getLocation())); 16697 } 16698 16699 // Handle automatically recognized callbacks. 16700 SmallVector<int, 4> Encoding; 16701 if (!FD->hasAttr<CallbackAttr>() && 16702 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 16703 FD->addAttr(CallbackAttr::CreateImplicit( 16704 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 16705 16706 // Mark const if we don't care about errno and/or floating point exceptions 16707 // that are the only thing preventing the function from being const. This 16708 // allows IRgen to use LLVM intrinsics for such functions. 16709 bool NoExceptions = 16710 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore; 16711 bool ConstWithoutErrnoAndExceptions = 16712 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID); 16713 bool ConstWithoutExceptions = 16714 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID); 16715 if (!FD->hasAttr<ConstAttr>() && 16716 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) && 16717 (!ConstWithoutErrnoAndExceptions || 16718 (!getLangOpts().MathErrno && NoExceptions)) && 16719 (!ConstWithoutExceptions || NoExceptions)) 16720 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 16721 16722 // We make "fma" on GNU or Windows const because we know it does not set 16723 // errno in those environments even though it could set errno based on the 16724 // C standard. 16725 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 16726 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) && 16727 !FD->hasAttr<ConstAttr>()) { 16728 switch (BuiltinID) { 16729 case Builtin::BI__builtin_fma: 16730 case Builtin::BI__builtin_fmaf: 16731 case Builtin::BI__builtin_fmal: 16732 case Builtin::BIfma: 16733 case Builtin::BIfmaf: 16734 case Builtin::BIfmal: 16735 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 16736 break; 16737 default: 16738 break; 16739 } 16740 } 16741 16742 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 16743 !FD->hasAttr<ReturnsTwiceAttr>()) 16744 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 16745 FD->getLocation())); 16746 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 16747 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 16748 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 16749 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 16750 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 16751 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 16752 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 16753 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 16754 // Add the appropriate attribute, depending on the CUDA compilation mode 16755 // and which target the builtin belongs to. For example, during host 16756 // compilation, aux builtins are __device__, while the rest are __host__. 16757 if (getLangOpts().CUDAIsDevice != 16758 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 16759 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 16760 else 16761 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 16762 } 16763 16764 // Add known guaranteed alignment for allocation functions. 16765 switch (BuiltinID) { 16766 case Builtin::BImemalign: 16767 case Builtin::BIaligned_alloc: 16768 if (!FD->hasAttr<AllocAlignAttr>()) 16769 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 16770 FD->getLocation())); 16771 break; 16772 default: 16773 break; 16774 } 16775 16776 // Add allocsize attribute for allocation functions. 16777 switch (BuiltinID) { 16778 case Builtin::BIcalloc: 16779 FD->addAttr(AllocSizeAttr::CreateImplicit( 16780 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation())); 16781 break; 16782 case Builtin::BImemalign: 16783 case Builtin::BIaligned_alloc: 16784 case Builtin::BIrealloc: 16785 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD), 16786 ParamIdx(), FD->getLocation())); 16787 break; 16788 case Builtin::BImalloc: 16789 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD), 16790 ParamIdx(), FD->getLocation())); 16791 break; 16792 default: 16793 break; 16794 } 16795 16796 // Add lifetime attribute to std::move, std::fowrard et al. 16797 switch (BuiltinID) { 16798 case Builtin::BIaddressof: 16799 case Builtin::BI__addressof: 16800 case Builtin::BI__builtin_addressof: 16801 case Builtin::BIas_const: 16802 case Builtin::BIforward: 16803 case Builtin::BIforward_like: 16804 case Builtin::BImove: 16805 case Builtin::BImove_if_noexcept: 16806 if (ParmVarDecl *P = FD->getParamDecl(0u); 16807 !P->hasAttr<LifetimeBoundAttr>()) 16808 P->addAttr( 16809 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation())); 16810 break; 16811 default: 16812 break; 16813 } 16814 } 16815 16816 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 16817 16818 // If C++ exceptions are enabled but we are told extern "C" functions cannot 16819 // throw, add an implicit nothrow attribute to any extern "C" function we come 16820 // across. 16821 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 16822 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 16823 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 16824 if (!FPT || FPT->getExceptionSpecType() == EST_None) 16825 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 16826 } 16827 16828 IdentifierInfo *Name = FD->getIdentifier(); 16829 if (!Name) 16830 return; 16831 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) || 16832 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 16833 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 16834 LinkageSpecLanguageIDs::C)) { 16835 // Okay: this could be a libc/libm/Objective-C function we know 16836 // about. 16837 } else 16838 return; 16839 16840 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 16841 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 16842 // target-specific builtins, perhaps? 16843 if (!FD->hasAttr<FormatAttr>()) 16844 FD->addAttr(FormatAttr::CreateImplicit(Context, 16845 &Context.Idents.get("printf"), 2, 16846 Name->isStr("vasprintf") ? 0 : 3, 16847 FD->getLocation())); 16848 } 16849 16850 if (Name->isStr("__CFStringMakeConstantString")) { 16851 // We already have a __builtin___CFStringMakeConstantString, 16852 // but builds that use -fno-constant-cfstrings don't go through that. 16853 if (!FD->hasAttr<FormatArgAttr>()) 16854 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 16855 FD->getLocation())); 16856 } 16857 } 16858 16859 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 16860 TypeSourceInfo *TInfo) { 16861 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 16862 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 16863 16864 if (!TInfo) { 16865 assert(D.isInvalidType() && "no declarator info for valid type"); 16866 TInfo = Context.getTrivialTypeSourceInfo(T); 16867 } 16868 16869 // Scope manipulation handled by caller. 16870 TypedefDecl *NewTD = 16871 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 16872 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 16873 16874 // Bail out immediately if we have an invalid declaration. 16875 if (D.isInvalidType()) { 16876 NewTD->setInvalidDecl(); 16877 return NewTD; 16878 } 16879 16880 if (D.getDeclSpec().isModulePrivateSpecified()) { 16881 if (CurContext->isFunctionOrMethod()) 16882 Diag(NewTD->getLocation(), diag::err_module_private_local) 16883 << 2 << NewTD 16884 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 16885 << FixItHint::CreateRemoval( 16886 D.getDeclSpec().getModulePrivateSpecLoc()); 16887 else 16888 NewTD->setModulePrivate(); 16889 } 16890 16891 // C++ [dcl.typedef]p8: 16892 // If the typedef declaration defines an unnamed class (or 16893 // enum), the first typedef-name declared by the declaration 16894 // to be that class type (or enum type) is used to denote the 16895 // class type (or enum type) for linkage purposes only. 16896 // We need to check whether the type was declared in the declaration. 16897 switch (D.getDeclSpec().getTypeSpecType()) { 16898 case TST_enum: 16899 case TST_struct: 16900 case TST_interface: 16901 case TST_union: 16902 case TST_class: { 16903 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 16904 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 16905 break; 16906 } 16907 16908 default: 16909 break; 16910 } 16911 16912 return NewTD; 16913 } 16914 16915 /// Check that this is a valid underlying type for an enum declaration. 16916 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 16917 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 16918 QualType T = TI->getType(); 16919 16920 if (T->isDependentType()) 16921 return false; 16922 16923 // This doesn't use 'isIntegralType' despite the error message mentioning 16924 // integral type because isIntegralType would also allow enum types in C. 16925 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 16926 if (BT->isInteger()) 16927 return false; 16928 16929 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) 16930 << T << T->isBitIntType(); 16931 } 16932 16933 /// Check whether this is a valid redeclaration of a previous enumeration. 16934 /// \return true if the redeclaration was invalid. 16935 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 16936 QualType EnumUnderlyingTy, bool IsFixed, 16937 const EnumDecl *Prev) { 16938 if (IsScoped != Prev->isScoped()) { 16939 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 16940 << Prev->isScoped(); 16941 Diag(Prev->getLocation(), diag::note_previous_declaration); 16942 return true; 16943 } 16944 16945 if (IsFixed && Prev->isFixed()) { 16946 if (!EnumUnderlyingTy->isDependentType() && 16947 !Prev->getIntegerType()->isDependentType() && 16948 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 16949 Prev->getIntegerType())) { 16950 // TODO: Highlight the underlying type of the redeclaration. 16951 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 16952 << EnumUnderlyingTy << Prev->getIntegerType(); 16953 Diag(Prev->getLocation(), diag::note_previous_declaration) 16954 << Prev->getIntegerTypeRange(); 16955 return true; 16956 } 16957 } else if (IsFixed != Prev->isFixed()) { 16958 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 16959 << Prev->isFixed(); 16960 Diag(Prev->getLocation(), diag::note_previous_declaration); 16961 return true; 16962 } 16963 16964 return false; 16965 } 16966 16967 /// Get diagnostic %select index for tag kind for 16968 /// redeclaration diagnostic message. 16969 /// WARNING: Indexes apply to particular diagnostics only! 16970 /// 16971 /// \returns diagnostic %select index. 16972 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 16973 switch (Tag) { 16974 case TagTypeKind::Struct: 16975 return 0; 16976 case TagTypeKind::Interface: 16977 return 1; 16978 case TagTypeKind::Class: 16979 return 2; 16980 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 16981 } 16982 } 16983 16984 /// Determine if tag kind is a class-key compatible with 16985 /// class for redeclaration (class, struct, or __interface). 16986 /// 16987 /// \returns true iff the tag kind is compatible. 16988 static bool isClassCompatTagKind(TagTypeKind Tag) 16989 { 16990 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class || 16991 Tag == TagTypeKind::Interface; 16992 } 16993 16994 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 16995 TagTypeKind TTK) { 16996 if (isa<TypedefDecl>(PrevDecl)) 16997 return NTK_Typedef; 16998 else if (isa<TypeAliasDecl>(PrevDecl)) 16999 return NTK_TypeAlias; 17000 else if (isa<ClassTemplateDecl>(PrevDecl)) 17001 return NTK_Template; 17002 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 17003 return NTK_TypeAliasTemplate; 17004 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 17005 return NTK_TemplateTemplateArgument; 17006 switch (TTK) { 17007 case TagTypeKind::Struct: 17008 case TagTypeKind::Interface: 17009 case TagTypeKind::Class: 17010 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 17011 case TagTypeKind::Union: 17012 return NTK_NonUnion; 17013 case TagTypeKind::Enum: 17014 return NTK_NonEnum; 17015 } 17016 llvm_unreachable("invalid TTK"); 17017 } 17018 17019 /// Determine whether a tag with a given kind is acceptable 17020 /// as a redeclaration of the given tag declaration. 17021 /// 17022 /// \returns true if the new tag kind is acceptable, false otherwise. 17023 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 17024 TagTypeKind NewTag, bool isDefinition, 17025 SourceLocation NewTagLoc, 17026 const IdentifierInfo *Name) { 17027 // C++ [dcl.type.elab]p3: 17028 // The class-key or enum keyword present in the 17029 // elaborated-type-specifier shall agree in kind with the 17030 // declaration to which the name in the elaborated-type-specifier 17031 // refers. This rule also applies to the form of 17032 // elaborated-type-specifier that declares a class-name or 17033 // friend class since it can be construed as referring to the 17034 // definition of the class. Thus, in any 17035 // elaborated-type-specifier, the enum keyword shall be used to 17036 // refer to an enumeration (7.2), the union class-key shall be 17037 // used to refer to a union (clause 9), and either the class or 17038 // struct class-key shall be used to refer to a class (clause 9) 17039 // declared using the class or struct class-key. 17040 TagTypeKind OldTag = Previous->getTagKind(); 17041 if (OldTag != NewTag && 17042 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 17043 return false; 17044 17045 // Tags are compatible, but we might still want to warn on mismatched tags. 17046 // Non-class tags can't be mismatched at this point. 17047 if (!isClassCompatTagKind(NewTag)) 17048 return true; 17049 17050 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 17051 // by our warning analysis. We don't want to warn about mismatches with (eg) 17052 // declarations in system headers that are designed to be specialized, but if 17053 // a user asks us to warn, we should warn if their code contains mismatched 17054 // declarations. 17055 auto IsIgnoredLoc = [&](SourceLocation Loc) { 17056 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 17057 Loc); 17058 }; 17059 if (IsIgnoredLoc(NewTagLoc)) 17060 return true; 17061 17062 auto IsIgnored = [&](const TagDecl *Tag) { 17063 return IsIgnoredLoc(Tag->getLocation()); 17064 }; 17065 while (IsIgnored(Previous)) { 17066 Previous = Previous->getPreviousDecl(); 17067 if (!Previous) 17068 return true; 17069 OldTag = Previous->getTagKind(); 17070 } 17071 17072 bool isTemplate = false; 17073 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 17074 isTemplate = Record->getDescribedClassTemplate(); 17075 17076 if (inTemplateInstantiation()) { 17077 if (OldTag != NewTag) { 17078 // In a template instantiation, do not offer fix-its for tag mismatches 17079 // since they usually mess up the template instead of fixing the problem. 17080 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 17081 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 17082 << getRedeclDiagFromTagKind(OldTag); 17083 // FIXME: Note previous location? 17084 } 17085 return true; 17086 } 17087 17088 if (isDefinition) { 17089 // On definitions, check all previous tags and issue a fix-it for each 17090 // one that doesn't match the current tag. 17091 if (Previous->getDefinition()) { 17092 // Don't suggest fix-its for redefinitions. 17093 return true; 17094 } 17095 17096 bool previousMismatch = false; 17097 for (const TagDecl *I : Previous->redecls()) { 17098 if (I->getTagKind() != NewTag) { 17099 // Ignore previous declarations for which the warning was disabled. 17100 if (IsIgnored(I)) 17101 continue; 17102 17103 if (!previousMismatch) { 17104 previousMismatch = true; 17105 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 17106 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 17107 << getRedeclDiagFromTagKind(I->getTagKind()); 17108 } 17109 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 17110 << getRedeclDiagFromTagKind(NewTag) 17111 << FixItHint::CreateReplacement(I->getInnerLocStart(), 17112 TypeWithKeyword::getTagTypeKindName(NewTag)); 17113 } 17114 } 17115 return true; 17116 } 17117 17118 // Identify the prevailing tag kind: this is the kind of the definition (if 17119 // there is a non-ignored definition), or otherwise the kind of the prior 17120 // (non-ignored) declaration. 17121 const TagDecl *PrevDef = Previous->getDefinition(); 17122 if (PrevDef && IsIgnored(PrevDef)) 17123 PrevDef = nullptr; 17124 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 17125 if (Redecl->getTagKind() != NewTag) { 17126 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 17127 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 17128 << getRedeclDiagFromTagKind(OldTag); 17129 Diag(Redecl->getLocation(), diag::note_previous_use); 17130 17131 // If there is a previous definition, suggest a fix-it. 17132 if (PrevDef) { 17133 Diag(NewTagLoc, diag::note_struct_class_suggestion) 17134 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 17135 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 17136 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 17137 } 17138 } 17139 17140 return true; 17141 } 17142 17143 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 17144 /// from an outer enclosing namespace or file scope inside a friend declaration. 17145 /// This should provide the commented out code in the following snippet: 17146 /// namespace N { 17147 /// struct X; 17148 /// namespace M { 17149 /// struct Y { friend struct /*N::*/ X; }; 17150 /// } 17151 /// } 17152 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 17153 SourceLocation NameLoc) { 17154 // While the decl is in a namespace, do repeated lookup of that name and see 17155 // if we get the same namespace back. If we do not, continue until 17156 // translation unit scope, at which point we have a fully qualified NNS. 17157 SmallVector<IdentifierInfo *, 4> Namespaces; 17158 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 17159 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 17160 // This tag should be declared in a namespace, which can only be enclosed by 17161 // other namespaces. Bail if there's an anonymous namespace in the chain. 17162 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 17163 if (!Namespace || Namespace->isAnonymousNamespace()) 17164 return FixItHint(); 17165 IdentifierInfo *II = Namespace->getIdentifier(); 17166 Namespaces.push_back(II); 17167 NamedDecl *Lookup = SemaRef.LookupSingleName( 17168 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 17169 if (Lookup == Namespace) 17170 break; 17171 } 17172 17173 // Once we have all the namespaces, reverse them to go outermost first, and 17174 // build an NNS. 17175 SmallString<64> Insertion; 17176 llvm::raw_svector_ostream OS(Insertion); 17177 if (DC->isTranslationUnit()) 17178 OS << "::"; 17179 std::reverse(Namespaces.begin(), Namespaces.end()); 17180 for (auto *II : Namespaces) 17181 OS << II->getName() << "::"; 17182 return FixItHint::CreateInsertion(NameLoc, Insertion); 17183 } 17184 17185 /// Determine whether a tag originally declared in context \p OldDC can 17186 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 17187 /// found a declaration in \p OldDC as a previous decl, perhaps through a 17188 /// using-declaration). 17189 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 17190 DeclContext *NewDC) { 17191 OldDC = OldDC->getRedeclContext(); 17192 NewDC = NewDC->getRedeclContext(); 17193 17194 if (OldDC->Equals(NewDC)) 17195 return true; 17196 17197 // In MSVC mode, we allow a redeclaration if the contexts are related (either 17198 // encloses the other). 17199 if (S.getLangOpts().MSVCCompat && 17200 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 17201 return true; 17202 17203 return false; 17204 } 17205 17206 /// This is invoked when we see 'struct foo' or 'struct {'. In the 17207 /// former case, Name will be non-null. In the later case, Name will be null. 17208 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 17209 /// reference/declaration/definition of a tag. 17210 /// 17211 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 17212 /// trailing-type-specifier) other than one in an alias-declaration. 17213 /// 17214 /// \param SkipBody If non-null, will be set to indicate if the caller should 17215 /// skip the definition of this tag and treat it as if it were a declaration. 17216 DeclResult 17217 Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 17218 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, 17219 const ParsedAttributesView &Attrs, AccessSpecifier AS, 17220 SourceLocation ModulePrivateLoc, 17221 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, 17222 bool &IsDependent, SourceLocation ScopedEnumKWLoc, 17223 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 17224 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 17225 OffsetOfKind OOK, SkipBodyInfo *SkipBody) { 17226 // If this is not a definition, it must have a name. 17227 IdentifierInfo *OrigName = Name; 17228 assert((Name != nullptr || TUK == TUK_Definition) && 17229 "Nameless record must be a definition!"); 17230 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 17231 17232 OwnedDecl = false; 17233 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 17234 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 17235 17236 // FIXME: Check member specializations more carefully. 17237 bool isMemberSpecialization = false; 17238 bool Invalid = false; 17239 17240 // We only need to do this matching if we have template parameters 17241 // or a scope specifier, which also conveniently avoids this work 17242 // for non-C++ cases. 17243 if (TemplateParameterLists.size() > 0 || 17244 (SS.isNotEmpty() && TUK != TUK_Reference)) { 17245 if (TemplateParameterList *TemplateParams = 17246 MatchTemplateParametersToScopeSpecifier( 17247 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 17248 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 17249 if (Kind == TagTypeKind::Enum) { 17250 Diag(KWLoc, diag::err_enum_template); 17251 return true; 17252 } 17253 17254 if (TemplateParams->size() > 0) { 17255 // This is a declaration or definition of a class template (which may 17256 // be a member of another template). 17257 17258 if (Invalid) 17259 return true; 17260 17261 OwnedDecl = false; 17262 DeclResult Result = CheckClassTemplate( 17263 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 17264 AS, ModulePrivateLoc, 17265 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 17266 TemplateParameterLists.data(), SkipBody); 17267 return Result.get(); 17268 } else { 17269 // The "template<>" header is extraneous. 17270 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 17271 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 17272 isMemberSpecialization = true; 17273 } 17274 } 17275 17276 if (!TemplateParameterLists.empty() && isMemberSpecialization && 17277 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 17278 return true; 17279 } 17280 17281 // Figure out the underlying type if this a enum declaration. We need to do 17282 // this early, because it's needed to detect if this is an incompatible 17283 // redeclaration. 17284 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 17285 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 17286 17287 if (Kind == TagTypeKind::Enum) { 17288 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 17289 // No underlying type explicitly specified, or we failed to parse the 17290 // type, default to int. 17291 EnumUnderlying = Context.IntTy.getTypePtr(); 17292 } else if (UnderlyingType.get()) { 17293 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 17294 // integral type; any cv-qualification is ignored. 17295 TypeSourceInfo *TI = nullptr; 17296 GetTypeFromParser(UnderlyingType.get(), &TI); 17297 EnumUnderlying = TI; 17298 17299 if (CheckEnumUnderlyingType(TI)) 17300 // Recover by falling back to int. 17301 EnumUnderlying = Context.IntTy.getTypePtr(); 17302 17303 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 17304 UPPC_FixedUnderlyingType)) 17305 EnumUnderlying = Context.IntTy.getTypePtr(); 17306 17307 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 17308 // For MSVC ABI compatibility, unfixed enums must use an underlying type 17309 // of 'int'. However, if this is an unfixed forward declaration, don't set 17310 // the underlying type unless the user enables -fms-compatibility. This 17311 // makes unfixed forward declared enums incomplete and is more conforming. 17312 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 17313 EnumUnderlying = Context.IntTy.getTypePtr(); 17314 } 17315 } 17316 17317 DeclContext *SearchDC = CurContext; 17318 DeclContext *DC = CurContext; 17319 bool isStdBadAlloc = false; 17320 bool isStdAlignValT = false; 17321 17322 RedeclarationKind Redecl = forRedeclarationInCurContext(); 17323 if (TUK == TUK_Friend || TUK == TUK_Reference) 17324 Redecl = NotForRedeclaration; 17325 17326 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 17327 /// implemented asks for structural equivalence checking, the returned decl 17328 /// here is passed back to the parser, allowing the tag body to be parsed. 17329 auto createTagFromNewDecl = [&]() -> TagDecl * { 17330 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 17331 // If there is an identifier, use the location of the identifier as the 17332 // location of the decl, otherwise use the location of the struct/union 17333 // keyword. 17334 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 17335 TagDecl *New = nullptr; 17336 17337 if (Kind == TagTypeKind::Enum) { 17338 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 17339 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 17340 // If this is an undefined enum, bail. 17341 if (TUK != TUK_Definition && !Invalid) 17342 return nullptr; 17343 if (EnumUnderlying) { 17344 EnumDecl *ED = cast<EnumDecl>(New); 17345 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 17346 ED->setIntegerTypeSourceInfo(TI); 17347 else 17348 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 17349 QualType EnumTy = ED->getIntegerType(); 17350 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy) 17351 ? Context.getPromotedIntegerType(EnumTy) 17352 : EnumTy); 17353 } 17354 } else { // struct/union 17355 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 17356 nullptr); 17357 } 17358 17359 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 17360 // Add alignment attributes if necessary; these attributes are checked 17361 // when the ASTContext lays out the structure. 17362 // 17363 // It is important for implementing the correct semantics that this 17364 // happen here (in ActOnTag). The #pragma pack stack is 17365 // maintained as a result of parser callbacks which can occur at 17366 // many points during the parsing of a struct declaration (because 17367 // the #pragma tokens are effectively skipped over during the 17368 // parsing of the struct). 17369 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 17370 AddAlignmentAttributesForRecord(RD); 17371 AddMsStructLayoutForRecord(RD); 17372 } 17373 } 17374 New->setLexicalDeclContext(CurContext); 17375 return New; 17376 }; 17377 17378 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 17379 if (Name && SS.isNotEmpty()) { 17380 // We have a nested-name tag ('struct foo::bar'). 17381 17382 // Check for invalid 'foo::'. 17383 if (SS.isInvalid()) { 17384 Name = nullptr; 17385 goto CreateNewDecl; 17386 } 17387 17388 // If this is a friend or a reference to a class in a dependent 17389 // context, don't try to make a decl for it. 17390 if (TUK == TUK_Friend || TUK == TUK_Reference) { 17391 DC = computeDeclContext(SS, false); 17392 if (!DC) { 17393 IsDependent = true; 17394 return true; 17395 } 17396 } else { 17397 DC = computeDeclContext(SS, true); 17398 if (!DC) { 17399 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 17400 << SS.getRange(); 17401 return true; 17402 } 17403 } 17404 17405 if (RequireCompleteDeclContext(SS, DC)) 17406 return true; 17407 17408 SearchDC = DC; 17409 // Look-up name inside 'foo::'. 17410 LookupQualifiedName(Previous, DC); 17411 17412 if (Previous.isAmbiguous()) 17413 return true; 17414 17415 if (Previous.empty()) { 17416 // Name lookup did not find anything. However, if the 17417 // nested-name-specifier refers to the current instantiation, 17418 // and that current instantiation has any dependent base 17419 // classes, we might find something at instantiation time: treat 17420 // this as a dependent elaborated-type-specifier. 17421 // But this only makes any sense for reference-like lookups. 17422 if (Previous.wasNotFoundInCurrentInstantiation() && 17423 (TUK == TUK_Reference || TUK == TUK_Friend)) { 17424 IsDependent = true; 17425 return true; 17426 } 17427 17428 // A tag 'foo::bar' must already exist. 17429 Diag(NameLoc, diag::err_not_tag_in_scope) 17430 << llvm::to_underlying(Kind) << Name << DC << SS.getRange(); 17431 Name = nullptr; 17432 Invalid = true; 17433 goto CreateNewDecl; 17434 } 17435 } else if (Name) { 17436 // C++14 [class.mem]p14: 17437 // If T is the name of a class, then each of the following shall have a 17438 // name different from T: 17439 // -- every member of class T that is itself a type 17440 if (TUK != TUK_Reference && TUK != TUK_Friend && 17441 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 17442 return true; 17443 17444 // If this is a named struct, check to see if there was a previous forward 17445 // declaration or definition. 17446 // FIXME: We're looking into outer scopes here, even when we 17447 // shouldn't be. Doing so can result in ambiguities that we 17448 // shouldn't be diagnosing. 17449 LookupName(Previous, S); 17450 17451 // When declaring or defining a tag, ignore ambiguities introduced 17452 // by types using'ed into this scope. 17453 if (Previous.isAmbiguous() && 17454 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 17455 LookupResult::Filter F = Previous.makeFilter(); 17456 while (F.hasNext()) { 17457 NamedDecl *ND = F.next(); 17458 if (!ND->getDeclContext()->getRedeclContext()->Equals( 17459 SearchDC->getRedeclContext())) 17460 F.erase(); 17461 } 17462 F.done(); 17463 } 17464 17465 // C++11 [namespace.memdef]p3: 17466 // If the name in a friend declaration is neither qualified nor 17467 // a template-id and the declaration is a function or an 17468 // elaborated-type-specifier, the lookup to determine whether 17469 // the entity has been previously declared shall not consider 17470 // any scopes outside the innermost enclosing namespace. 17471 // 17472 // MSVC doesn't implement the above rule for types, so a friend tag 17473 // declaration may be a redeclaration of a type declared in an enclosing 17474 // scope. They do implement this rule for friend functions. 17475 // 17476 // Does it matter that this should be by scope instead of by 17477 // semantic context? 17478 if (!Previous.empty() && TUK == TUK_Friend) { 17479 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 17480 LookupResult::Filter F = Previous.makeFilter(); 17481 bool FriendSawTagOutsideEnclosingNamespace = false; 17482 while (F.hasNext()) { 17483 NamedDecl *ND = F.next(); 17484 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 17485 if (DC->isFileContext() && 17486 !EnclosingNS->Encloses(ND->getDeclContext())) { 17487 if (getLangOpts().MSVCCompat) 17488 FriendSawTagOutsideEnclosingNamespace = true; 17489 else 17490 F.erase(); 17491 } 17492 } 17493 F.done(); 17494 17495 // Diagnose this MSVC extension in the easy case where lookup would have 17496 // unambiguously found something outside the enclosing namespace. 17497 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 17498 NamedDecl *ND = Previous.getFoundDecl(); 17499 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 17500 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 17501 } 17502 } 17503 17504 // Note: there used to be some attempt at recovery here. 17505 if (Previous.isAmbiguous()) 17506 return true; 17507 17508 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 17509 // FIXME: This makes sure that we ignore the contexts associated 17510 // with C structs, unions, and enums when looking for a matching 17511 // tag declaration or definition. See the similar lookup tweak 17512 // in Sema::LookupName; is there a better way to deal with this? 17513 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC)) 17514 SearchDC = SearchDC->getParent(); 17515 } else if (getLangOpts().CPlusPlus) { 17516 // Inside ObjCContainer want to keep it as a lexical decl context but go 17517 // past it (most often to TranslationUnit) to find the semantic decl 17518 // context. 17519 while (isa<ObjCContainerDecl>(SearchDC)) 17520 SearchDC = SearchDC->getParent(); 17521 } 17522 } else if (getLangOpts().CPlusPlus) { 17523 // Don't use ObjCContainerDecl as the semantic decl context for anonymous 17524 // TagDecl the same way as we skip it for named TagDecl. 17525 while (isa<ObjCContainerDecl>(SearchDC)) 17526 SearchDC = SearchDC->getParent(); 17527 } 17528 17529 if (Previous.isSingleResult() && 17530 Previous.getFoundDecl()->isTemplateParameter()) { 17531 // Maybe we will complain about the shadowed template parameter. 17532 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 17533 // Just pretend that we didn't see the previous declaration. 17534 Previous.clear(); 17535 } 17536 17537 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 17538 DC->Equals(getStdNamespace())) { 17539 if (Name->isStr("bad_alloc")) { 17540 // This is a declaration of or a reference to "std::bad_alloc". 17541 isStdBadAlloc = true; 17542 17543 // If std::bad_alloc has been implicitly declared (but made invisible to 17544 // name lookup), fill in this implicit declaration as the previous 17545 // declaration, so that the declarations get chained appropriately. 17546 if (Previous.empty() && StdBadAlloc) 17547 Previous.addDecl(getStdBadAlloc()); 17548 } else if (Name->isStr("align_val_t")) { 17549 isStdAlignValT = true; 17550 if (Previous.empty() && StdAlignValT) 17551 Previous.addDecl(getStdAlignValT()); 17552 } 17553 } 17554 17555 // If we didn't find a previous declaration, and this is a reference 17556 // (or friend reference), move to the correct scope. In C++, we 17557 // also need to do a redeclaration lookup there, just in case 17558 // there's a shadow friend decl. 17559 if (Name && Previous.empty() && 17560 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 17561 if (Invalid) goto CreateNewDecl; 17562 assert(SS.isEmpty()); 17563 17564 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 17565 // C++ [basic.scope.pdecl]p5: 17566 // -- for an elaborated-type-specifier of the form 17567 // 17568 // class-key identifier 17569 // 17570 // if the elaborated-type-specifier is used in the 17571 // decl-specifier-seq or parameter-declaration-clause of a 17572 // function defined in namespace scope, the identifier is 17573 // declared as a class-name in the namespace that contains 17574 // the declaration; otherwise, except as a friend 17575 // declaration, the identifier is declared in the smallest 17576 // non-class, non-function-prototype scope that contains the 17577 // declaration. 17578 // 17579 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 17580 // C structs and unions. 17581 // 17582 // It is an error in C++ to declare (rather than define) an enum 17583 // type, including via an elaborated type specifier. We'll 17584 // diagnose that later; for now, declare the enum in the same 17585 // scope as we would have picked for any other tag type. 17586 // 17587 // GNU C also supports this behavior as part of its incomplete 17588 // enum types extension, while GNU C++ does not. 17589 // 17590 // Find the context where we'll be declaring the tag. 17591 // FIXME: We would like to maintain the current DeclContext as the 17592 // lexical context, 17593 SearchDC = getTagInjectionContext(SearchDC); 17594 17595 // Find the scope where we'll be declaring the tag. 17596 S = getTagInjectionScope(S, getLangOpts()); 17597 } else { 17598 assert(TUK == TUK_Friend); 17599 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC); 17600 17601 // C++ [namespace.memdef]p3: 17602 // If a friend declaration in a non-local class first declares a 17603 // class or function, the friend class or function is a member of 17604 // the innermost enclosing namespace. 17605 SearchDC = RD->isLocalClass() ? RD->isLocalClass() 17606 : SearchDC->getEnclosingNamespaceContext(); 17607 } 17608 17609 // In C++, we need to do a redeclaration lookup to properly 17610 // diagnose some problems. 17611 // FIXME: redeclaration lookup is also used (with and without C++) to find a 17612 // hidden declaration so that we don't get ambiguity errors when using a 17613 // type declared by an elaborated-type-specifier. In C that is not correct 17614 // and we should instead merge compatible types found by lookup. 17615 if (getLangOpts().CPlusPlus) { 17616 // FIXME: This can perform qualified lookups into function contexts, 17617 // which are meaningless. 17618 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 17619 LookupQualifiedName(Previous, SearchDC); 17620 } else { 17621 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 17622 LookupName(Previous, S); 17623 } 17624 } 17625 17626 // If we have a known previous declaration to use, then use it. 17627 if (Previous.empty() && SkipBody && SkipBody->Previous) 17628 Previous.addDecl(SkipBody->Previous); 17629 17630 if (!Previous.empty()) { 17631 NamedDecl *PrevDecl = Previous.getFoundDecl(); 17632 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 17633 17634 // It's okay to have a tag decl in the same scope as a typedef 17635 // which hides a tag decl in the same scope. Finding this 17636 // with a redeclaration lookup can only actually happen in C++. 17637 // 17638 // This is also okay for elaborated-type-specifiers, which is 17639 // technically forbidden by the current standard but which is 17640 // okay according to the likely resolution of an open issue; 17641 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 17642 if (getLangOpts().CPlusPlus) { 17643 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 17644 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 17645 TagDecl *Tag = TT->getDecl(); 17646 if (Tag->getDeclName() == Name && 17647 Tag->getDeclContext()->getRedeclContext() 17648 ->Equals(TD->getDeclContext()->getRedeclContext())) { 17649 PrevDecl = Tag; 17650 Previous.clear(); 17651 Previous.addDecl(Tag); 17652 Previous.resolveKind(); 17653 } 17654 } 17655 } 17656 } 17657 17658 // If this is a redeclaration of a using shadow declaration, it must 17659 // declare a tag in the same context. In MSVC mode, we allow a 17660 // redefinition if either context is within the other. 17661 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 17662 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 17663 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 17664 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 17665 !(OldTag && isAcceptableTagRedeclContext( 17666 *this, OldTag->getDeclContext(), SearchDC))) { 17667 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 17668 Diag(Shadow->getTargetDecl()->getLocation(), 17669 diag::note_using_decl_target); 17670 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 17671 << 0; 17672 // Recover by ignoring the old declaration. 17673 Previous.clear(); 17674 goto CreateNewDecl; 17675 } 17676 } 17677 17678 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 17679 // If this is a use of a previous tag, or if the tag is already declared 17680 // in the same scope (so that the definition/declaration completes or 17681 // rementions the tag), reuse the decl. 17682 if (TUK == TUK_Reference || TUK == TUK_Friend || 17683 isDeclInScope(DirectPrevDecl, SearchDC, S, 17684 SS.isNotEmpty() || isMemberSpecialization)) { 17685 // Make sure that this wasn't declared as an enum and now used as a 17686 // struct or something similar. 17687 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 17688 TUK == TUK_Definition, KWLoc, 17689 Name)) { 17690 bool SafeToContinue = 17691 (PrevTagDecl->getTagKind() != TagTypeKind::Enum && 17692 Kind != TagTypeKind::Enum); 17693 if (SafeToContinue) 17694 Diag(KWLoc, diag::err_use_with_wrong_tag) 17695 << Name 17696 << FixItHint::CreateReplacement(SourceRange(KWLoc), 17697 PrevTagDecl->getKindName()); 17698 else 17699 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 17700 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 17701 17702 if (SafeToContinue) 17703 Kind = PrevTagDecl->getTagKind(); 17704 else { 17705 // Recover by making this an anonymous redefinition. 17706 Name = nullptr; 17707 Previous.clear(); 17708 Invalid = true; 17709 } 17710 } 17711 17712 if (Kind == TagTypeKind::Enum && 17713 PrevTagDecl->getTagKind() == TagTypeKind::Enum) { 17714 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 17715 if (TUK == TUK_Reference || TUK == TUK_Friend) 17716 return PrevTagDecl; 17717 17718 QualType EnumUnderlyingTy; 17719 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 17720 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 17721 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 17722 EnumUnderlyingTy = QualType(T, 0); 17723 17724 // All conflicts with previous declarations are recovered by 17725 // returning the previous declaration, unless this is a definition, 17726 // in which case we want the caller to bail out. 17727 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 17728 ScopedEnum, EnumUnderlyingTy, 17729 IsFixed, PrevEnum)) 17730 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 17731 } 17732 17733 // C++11 [class.mem]p1: 17734 // A member shall not be declared twice in the member-specification, 17735 // except that a nested class or member class template can be declared 17736 // and then later defined. 17737 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 17738 S->isDeclScope(PrevDecl)) { 17739 Diag(NameLoc, diag::ext_member_redeclared); 17740 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 17741 } 17742 17743 if (!Invalid) { 17744 // If this is a use, just return the declaration we found, unless 17745 // we have attributes. 17746 if (TUK == TUK_Reference || TUK == TUK_Friend) { 17747 if (!Attrs.empty()) { 17748 // FIXME: Diagnose these attributes. For now, we create a new 17749 // declaration to hold them. 17750 } else if (TUK == TUK_Reference && 17751 (PrevTagDecl->getFriendObjectKind() == 17752 Decl::FOK_Undeclared || 17753 PrevDecl->getOwningModule() != getCurrentModule()) && 17754 SS.isEmpty()) { 17755 // This declaration is a reference to an existing entity, but 17756 // has different visibility from that entity: it either makes 17757 // a friend visible or it makes a type visible in a new module. 17758 // In either case, create a new declaration. We only do this if 17759 // the declaration would have meant the same thing if no prior 17760 // declaration were found, that is, if it was found in the same 17761 // scope where we would have injected a declaration. 17762 if (!getTagInjectionContext(CurContext)->getRedeclContext() 17763 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 17764 return PrevTagDecl; 17765 // This is in the injected scope, create a new declaration in 17766 // that scope. 17767 S = getTagInjectionScope(S, getLangOpts()); 17768 } else { 17769 return PrevTagDecl; 17770 } 17771 } 17772 17773 // Diagnose attempts to redefine a tag. 17774 if (TUK == TUK_Definition) { 17775 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 17776 // If we're defining a specialization and the previous definition 17777 // is from an implicit instantiation, don't emit an error 17778 // here; we'll catch this in the general case below. 17779 bool IsExplicitSpecializationAfterInstantiation = false; 17780 if (isMemberSpecialization) { 17781 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 17782 IsExplicitSpecializationAfterInstantiation = 17783 RD->getTemplateSpecializationKind() != 17784 TSK_ExplicitSpecialization; 17785 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 17786 IsExplicitSpecializationAfterInstantiation = 17787 ED->getTemplateSpecializationKind() != 17788 TSK_ExplicitSpecialization; 17789 } 17790 17791 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 17792 // not keep more that one definition around (merge them). However, 17793 // ensure the decl passes the structural compatibility check in 17794 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 17795 NamedDecl *Hidden = nullptr; 17796 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 17797 // There is a definition of this tag, but it is not visible. We 17798 // explicitly make use of C++'s one definition rule here, and 17799 // assume that this definition is identical to the hidden one 17800 // we already have. Make the existing definition visible and 17801 // use it in place of this one. 17802 if (!getLangOpts().CPlusPlus) { 17803 // Postpone making the old definition visible until after we 17804 // complete parsing the new one and do the structural 17805 // comparison. 17806 SkipBody->CheckSameAsPrevious = true; 17807 SkipBody->New = createTagFromNewDecl(); 17808 SkipBody->Previous = Def; 17809 return Def; 17810 } else { 17811 SkipBody->ShouldSkip = true; 17812 SkipBody->Previous = Def; 17813 makeMergedDefinitionVisible(Hidden); 17814 // Carry on and handle it like a normal definition. We'll 17815 // skip starting the definitiion later. 17816 } 17817 } else if (!IsExplicitSpecializationAfterInstantiation) { 17818 // A redeclaration in function prototype scope in C isn't 17819 // visible elsewhere, so merely issue a warning. 17820 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 17821 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 17822 else 17823 Diag(NameLoc, diag::err_redefinition) << Name; 17824 notePreviousDefinition(Def, 17825 NameLoc.isValid() ? NameLoc : KWLoc); 17826 // If this is a redefinition, recover by making this 17827 // struct be anonymous, which will make any later 17828 // references get the previous definition. 17829 Name = nullptr; 17830 Previous.clear(); 17831 Invalid = true; 17832 } 17833 } else { 17834 // If the type is currently being defined, complain 17835 // about a nested redefinition. 17836 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 17837 if (TD->isBeingDefined()) { 17838 Diag(NameLoc, diag::err_nested_redefinition) << Name; 17839 Diag(PrevTagDecl->getLocation(), 17840 diag::note_previous_definition); 17841 Name = nullptr; 17842 Previous.clear(); 17843 Invalid = true; 17844 } 17845 } 17846 17847 // Okay, this is definition of a previously declared or referenced 17848 // tag. We're going to create a new Decl for it. 17849 } 17850 17851 // Okay, we're going to make a redeclaration. If this is some kind 17852 // of reference, make sure we build the redeclaration in the same DC 17853 // as the original, and ignore the current access specifier. 17854 if (TUK == TUK_Friend || TUK == TUK_Reference) { 17855 SearchDC = PrevTagDecl->getDeclContext(); 17856 AS = AS_none; 17857 } 17858 } 17859 // If we get here we have (another) forward declaration or we 17860 // have a definition. Just create a new decl. 17861 17862 } else { 17863 // If we get here, this is a definition of a new tag type in a nested 17864 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 17865 // new decl/type. We set PrevDecl to NULL so that the entities 17866 // have distinct types. 17867 Previous.clear(); 17868 } 17869 // If we get here, we're going to create a new Decl. If PrevDecl 17870 // is non-NULL, it's a definition of the tag declared by 17871 // PrevDecl. If it's NULL, we have a new definition. 17872 17873 // Otherwise, PrevDecl is not a tag, but was found with tag 17874 // lookup. This is only actually possible in C++, where a few 17875 // things like templates still live in the tag namespace. 17876 } else { 17877 // Use a better diagnostic if an elaborated-type-specifier 17878 // found the wrong kind of type on the first 17879 // (non-redeclaration) lookup. 17880 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 17881 !Previous.isForRedeclaration()) { 17882 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 17883 Diag(NameLoc, diag::err_tag_reference_non_tag) 17884 << PrevDecl << NTK << llvm::to_underlying(Kind); 17885 Diag(PrevDecl->getLocation(), diag::note_declared_at); 17886 Invalid = true; 17887 17888 // Otherwise, only diagnose if the declaration is in scope. 17889 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 17890 SS.isNotEmpty() || isMemberSpecialization)) { 17891 // do nothing 17892 17893 // Diagnose implicit declarations introduced by elaborated types. 17894 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 17895 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 17896 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 17897 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 17898 Invalid = true; 17899 17900 // Otherwise it's a declaration. Call out a particularly common 17901 // case here. 17902 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 17903 unsigned Kind = 0; 17904 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 17905 Diag(NameLoc, diag::err_tag_definition_of_typedef) 17906 << Name << Kind << TND->getUnderlyingType(); 17907 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 17908 Invalid = true; 17909 17910 // Otherwise, diagnose. 17911 } else { 17912 // The tag name clashes with something else in the target scope, 17913 // issue an error and recover by making this tag be anonymous. 17914 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 17915 notePreviousDefinition(PrevDecl, NameLoc); 17916 Name = nullptr; 17917 Invalid = true; 17918 } 17919 17920 // The existing declaration isn't relevant to us; we're in a 17921 // new scope, so clear out the previous declaration. 17922 Previous.clear(); 17923 } 17924 } 17925 17926 CreateNewDecl: 17927 17928 TagDecl *PrevDecl = nullptr; 17929 if (Previous.isSingleResult()) 17930 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 17931 17932 // If there is an identifier, use the location of the identifier as the 17933 // location of the decl, otherwise use the location of the struct/union 17934 // keyword. 17935 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 17936 17937 // Otherwise, create a new declaration. If there is a previous 17938 // declaration of the same entity, the two will be linked via 17939 // PrevDecl. 17940 TagDecl *New; 17941 17942 if (Kind == TagTypeKind::Enum) { 17943 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 17944 // enum X { A, B, C } D; D should chain to X. 17945 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 17946 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 17947 ScopedEnumUsesClassTag, IsFixed); 17948 17949 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 17950 StdAlignValT = cast<EnumDecl>(New); 17951 17952 // If this is an undefined enum, warn. 17953 if (TUK != TUK_Definition && !Invalid) { 17954 TagDecl *Def; 17955 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 17956 // C++0x: 7.2p2: opaque-enum-declaration. 17957 // Conflicts are diagnosed above. Do nothing. 17958 } 17959 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 17960 Diag(Loc, diag::ext_forward_ref_enum_def) 17961 << New; 17962 Diag(Def->getLocation(), diag::note_previous_definition); 17963 } else { 17964 unsigned DiagID = diag::ext_forward_ref_enum; 17965 if (getLangOpts().MSVCCompat) 17966 DiagID = diag::ext_ms_forward_ref_enum; 17967 else if (getLangOpts().CPlusPlus) 17968 DiagID = diag::err_forward_ref_enum; 17969 Diag(Loc, DiagID); 17970 } 17971 } 17972 17973 if (EnumUnderlying) { 17974 EnumDecl *ED = cast<EnumDecl>(New); 17975 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 17976 ED->setIntegerTypeSourceInfo(TI); 17977 else 17978 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 17979 QualType EnumTy = ED->getIntegerType(); 17980 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy) 17981 ? Context.getPromotedIntegerType(EnumTy) 17982 : EnumTy); 17983 assert(ED->isComplete() && "enum with type should be complete"); 17984 } 17985 } else { 17986 // struct/union/class 17987 17988 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 17989 // struct X { int A; } D; D should chain to X. 17990 if (getLangOpts().CPlusPlus) { 17991 // FIXME: Look for a way to use RecordDecl for simple structs. 17992 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 17993 cast_or_null<CXXRecordDecl>(PrevDecl)); 17994 17995 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 17996 StdBadAlloc = cast<CXXRecordDecl>(New); 17997 } else 17998 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 17999 cast_or_null<RecordDecl>(PrevDecl)); 18000 } 18001 18002 if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus) 18003 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof) 18004 << (OOK == OOK_Macro) << New->getSourceRange(); 18005 18006 // C++11 [dcl.type]p3: 18007 // A type-specifier-seq shall not define a class or enumeration [...]. 18008 if (!Invalid && getLangOpts().CPlusPlus && 18009 (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) { 18010 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 18011 << Context.getTagDeclType(New); 18012 Invalid = true; 18013 } 18014 18015 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 18016 DC->getDeclKind() == Decl::Enum) { 18017 Diag(New->getLocation(), diag::err_type_defined_in_enum) 18018 << Context.getTagDeclType(New); 18019 Invalid = true; 18020 } 18021 18022 // Maybe add qualifier info. 18023 if (SS.isNotEmpty()) { 18024 if (SS.isSet()) { 18025 // If this is either a declaration or a definition, check the 18026 // nested-name-specifier against the current context. 18027 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 18028 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 18029 isMemberSpecialization)) 18030 Invalid = true; 18031 18032 New->setQualifierInfo(SS.getWithLocInContext(Context)); 18033 if (TemplateParameterLists.size() > 0) { 18034 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 18035 } 18036 } 18037 else 18038 Invalid = true; 18039 } 18040 18041 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 18042 // Add alignment attributes if necessary; these attributes are checked when 18043 // the ASTContext lays out the structure. 18044 // 18045 // It is important for implementing the correct semantics that this 18046 // happen here (in ActOnTag). The #pragma pack stack is 18047 // maintained as a result of parser callbacks which can occur at 18048 // many points during the parsing of a struct declaration (because 18049 // the #pragma tokens are effectively skipped over during the 18050 // parsing of the struct). 18051 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 18052 AddAlignmentAttributesForRecord(RD); 18053 AddMsStructLayoutForRecord(RD); 18054 } 18055 } 18056 18057 if (ModulePrivateLoc.isValid()) { 18058 if (isMemberSpecialization) 18059 Diag(New->getLocation(), diag::err_module_private_specialization) 18060 << 2 18061 << FixItHint::CreateRemoval(ModulePrivateLoc); 18062 // __module_private__ does not apply to local classes. However, we only 18063 // diagnose this as an error when the declaration specifiers are 18064 // freestanding. Here, we just ignore the __module_private__. 18065 else if (!SearchDC->isFunctionOrMethod()) 18066 New->setModulePrivate(); 18067 } 18068 18069 // If this is a specialization of a member class (of a class template), 18070 // check the specialization. 18071 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 18072 Invalid = true; 18073 18074 // If we're declaring or defining a tag in function prototype scope in C, 18075 // note that this type can only be used within the function and add it to 18076 // the list of decls to inject into the function definition scope. 18077 if ((Name || Kind == TagTypeKind::Enum) && 18078 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 18079 if (getLangOpts().CPlusPlus) { 18080 // C++ [dcl.fct]p6: 18081 // Types shall not be defined in return or parameter types. 18082 if (TUK == TUK_Definition && !IsTypeSpecifier) { 18083 Diag(Loc, diag::err_type_defined_in_param_type) 18084 << Name; 18085 Invalid = true; 18086 } 18087 } else if (!PrevDecl) { 18088 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 18089 } 18090 } 18091 18092 if (Invalid) 18093 New->setInvalidDecl(); 18094 18095 // Set the lexical context. If the tag has a C++ scope specifier, the 18096 // lexical context will be different from the semantic context. 18097 New->setLexicalDeclContext(CurContext); 18098 18099 // Mark this as a friend decl if applicable. 18100 // In Microsoft mode, a friend declaration also acts as a forward 18101 // declaration so we always pass true to setObjectOfFriendDecl to make 18102 // the tag name visible. 18103 if (TUK == TUK_Friend) 18104 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 18105 18106 // Set the access specifier. 18107 if (!Invalid && SearchDC->isRecord()) 18108 SetMemberAccessSpecifier(New, PrevDecl, AS); 18109 18110 if (PrevDecl) 18111 CheckRedeclarationInModule(New, PrevDecl); 18112 18113 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 18114 New->startDefinition(); 18115 18116 ProcessDeclAttributeList(S, New, Attrs); 18117 AddPragmaAttributes(S, New); 18118 18119 // If this has an identifier, add it to the scope stack. 18120 if (TUK == TUK_Friend) { 18121 // We might be replacing an existing declaration in the lookup tables; 18122 // if so, borrow its access specifier. 18123 if (PrevDecl) 18124 New->setAccess(PrevDecl->getAccess()); 18125 18126 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 18127 DC->makeDeclVisibleInContext(New); 18128 if (Name) // can be null along some error paths 18129 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 18130 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 18131 } else if (Name) { 18132 S = getNonFieldDeclScope(S); 18133 PushOnScopeChains(New, S, true); 18134 } else { 18135 CurContext->addDecl(New); 18136 } 18137 18138 // If this is the C FILE type, notify the AST context. 18139 if (IdentifierInfo *II = New->getIdentifier()) 18140 if (!New->isInvalidDecl() && 18141 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 18142 II->isStr("FILE")) 18143 Context.setFILEDecl(New); 18144 18145 if (PrevDecl) 18146 mergeDeclAttributes(New, PrevDecl); 18147 18148 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 18149 inferGslOwnerPointerAttribute(CXXRD); 18150 18151 // If there's a #pragma GCC visibility in scope, set the visibility of this 18152 // record. 18153 AddPushedVisibilityAttribute(New); 18154 18155 if (isMemberSpecialization && !New->isInvalidDecl()) 18156 CompleteMemberSpecialization(New, Previous); 18157 18158 OwnedDecl = true; 18159 // In C++, don't return an invalid declaration. We can't recover well from 18160 // the cases where we make the type anonymous. 18161 if (Invalid && getLangOpts().CPlusPlus) { 18162 if (New->isBeingDefined()) 18163 if (auto RD = dyn_cast<RecordDecl>(New)) 18164 RD->completeDefinition(); 18165 return true; 18166 } else if (SkipBody && SkipBody->ShouldSkip) { 18167 return SkipBody->Previous; 18168 } else { 18169 return New; 18170 } 18171 } 18172 18173 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 18174 AdjustDeclIfTemplate(TagD); 18175 TagDecl *Tag = cast<TagDecl>(TagD); 18176 18177 // Enter the tag context. 18178 PushDeclContext(S, Tag); 18179 18180 ActOnDocumentableDecl(TagD); 18181 18182 // If there's a #pragma GCC visibility in scope, set the visibility of this 18183 // record. 18184 AddPushedVisibilityAttribute(Tag); 18185 } 18186 18187 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) { 18188 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 18189 return false; 18190 18191 // Make the previous decl visible. 18192 makeMergedDefinitionVisible(SkipBody.Previous); 18193 return true; 18194 } 18195 18196 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) { 18197 assert(IDecl->getLexicalParent() == CurContext && 18198 "The next DeclContext should be lexically contained in the current one."); 18199 CurContext = IDecl; 18200 } 18201 18202 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 18203 SourceLocation FinalLoc, 18204 bool IsFinalSpelledSealed, 18205 bool IsAbstract, 18206 SourceLocation LBraceLoc) { 18207 AdjustDeclIfTemplate(TagD); 18208 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 18209 18210 FieldCollector->StartClass(); 18211 18212 if (!Record->getIdentifier()) 18213 return; 18214 18215 if (IsAbstract) 18216 Record->markAbstract(); 18217 18218 if (FinalLoc.isValid()) { 18219 Record->addAttr(FinalAttr::Create(Context, FinalLoc, 18220 IsFinalSpelledSealed 18221 ? FinalAttr::Keyword_sealed 18222 : FinalAttr::Keyword_final)); 18223 } 18224 // C++ [class]p2: 18225 // [...] The class-name is also inserted into the scope of the 18226 // class itself; this is known as the injected-class-name. For 18227 // purposes of access checking, the injected-class-name is treated 18228 // as if it were a public member name. 18229 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 18230 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 18231 Record->getLocation(), Record->getIdentifier(), 18232 /*PrevDecl=*/nullptr, 18233 /*DelayTypeCreation=*/true); 18234 Context.getTypeDeclType(InjectedClassName, Record); 18235 InjectedClassName->setImplicit(); 18236 InjectedClassName->setAccess(AS_public); 18237 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 18238 InjectedClassName->setDescribedClassTemplate(Template); 18239 PushOnScopeChains(InjectedClassName, S); 18240 assert(InjectedClassName->isInjectedClassName() && 18241 "Broken injected-class-name"); 18242 } 18243 18244 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 18245 SourceRange BraceRange) { 18246 AdjustDeclIfTemplate(TagD); 18247 TagDecl *Tag = cast<TagDecl>(TagD); 18248 Tag->setBraceRange(BraceRange); 18249 18250 // Make sure we "complete" the definition even it is invalid. 18251 if (Tag->isBeingDefined()) { 18252 assert(Tag->isInvalidDecl() && "We should already have completed it"); 18253 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 18254 RD->completeDefinition(); 18255 } 18256 18257 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 18258 FieldCollector->FinishClass(); 18259 if (RD->hasAttr<SYCLSpecialClassAttr>()) { 18260 auto *Def = RD->getDefinition(); 18261 assert(Def && "The record is expected to have a completed definition"); 18262 unsigned NumInitMethods = 0; 18263 for (auto *Method : Def->methods()) { 18264 if (!Method->getIdentifier()) 18265 continue; 18266 if (Method->getName() == "__init") 18267 NumInitMethods++; 18268 } 18269 if (NumInitMethods > 1 || !Def->hasInitMethod()) 18270 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method); 18271 } 18272 } 18273 18274 // Exit this scope of this tag's definition. 18275 PopDeclContext(); 18276 18277 if (getCurLexicalContext()->isObjCContainer() && 18278 Tag->getDeclContext()->isFileContext()) 18279 Tag->setTopLevelDeclInObjCContainer(); 18280 18281 // Notify the consumer that we've defined a tag. 18282 if (!Tag->isInvalidDecl()) 18283 Consumer.HandleTagDeclDefinition(Tag); 18284 18285 // Clangs implementation of #pragma align(packed) differs in bitfield layout 18286 // from XLs and instead matches the XL #pragma pack(1) behavior. 18287 if (Context.getTargetInfo().getTriple().isOSAIX() && 18288 AlignPackStack.hasValue()) { 18289 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 18290 // Only diagnose #pragma align(packed). 18291 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 18292 return; 18293 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 18294 if (!RD) 18295 return; 18296 // Only warn if there is at least 1 bitfield member. 18297 if (llvm::any_of(RD->fields(), 18298 [](const FieldDecl *FD) { return FD->isBitField(); })) 18299 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 18300 } 18301 } 18302 18303 void Sema::ActOnObjCContainerFinishDefinition() { 18304 // Exit this scope of this interface definition. 18305 PopDeclContext(); 18306 } 18307 18308 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) { 18309 assert(ObjCCtx == CurContext && "Mismatch of container contexts"); 18310 OriginalLexicalContext = ObjCCtx; 18311 ActOnObjCContainerFinishDefinition(); 18312 } 18313 18314 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) { 18315 ActOnObjCContainerStartDefinition(ObjCCtx); 18316 OriginalLexicalContext = nullptr; 18317 } 18318 18319 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 18320 AdjustDeclIfTemplate(TagD); 18321 TagDecl *Tag = cast<TagDecl>(TagD); 18322 Tag->setInvalidDecl(); 18323 18324 // Make sure we "complete" the definition even it is invalid. 18325 if (Tag->isBeingDefined()) { 18326 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 18327 RD->completeDefinition(); 18328 } 18329 18330 // We're undoing ActOnTagStartDefinition here, not 18331 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 18332 // the FieldCollector. 18333 18334 PopDeclContext(); 18335 } 18336 18337 // Note that FieldName may be null for anonymous bitfields. 18338 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 18339 IdentifierInfo *FieldName, QualType FieldTy, 18340 bool IsMsStruct, Expr *BitWidth) { 18341 assert(BitWidth); 18342 if (BitWidth->containsErrors()) 18343 return ExprError(); 18344 18345 // C99 6.7.2.1p4 - verify the field type. 18346 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 18347 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 18348 // Handle incomplete and sizeless types with a specific error. 18349 if (RequireCompleteSizedType(FieldLoc, FieldTy, 18350 diag::err_field_incomplete_or_sizeless)) 18351 return ExprError(); 18352 if (FieldName) 18353 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 18354 << FieldName << FieldTy << BitWidth->getSourceRange(); 18355 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 18356 << FieldTy << BitWidth->getSourceRange(); 18357 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 18358 UPPC_BitFieldWidth)) 18359 return ExprError(); 18360 18361 // If the bit-width is type- or value-dependent, don't try to check 18362 // it now. 18363 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 18364 return BitWidth; 18365 18366 llvm::APSInt Value; 18367 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 18368 if (ICE.isInvalid()) 18369 return ICE; 18370 BitWidth = ICE.get(); 18371 18372 // Zero-width bitfield is ok for anonymous field. 18373 if (Value == 0 && FieldName) 18374 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) 18375 << FieldName << BitWidth->getSourceRange(); 18376 18377 if (Value.isSigned() && Value.isNegative()) { 18378 if (FieldName) 18379 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 18380 << FieldName << toString(Value, 10); 18381 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 18382 << toString(Value, 10); 18383 } 18384 18385 // The size of the bit-field must not exceed our maximum permitted object 18386 // size. 18387 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 18388 return Diag(FieldLoc, diag::err_bitfield_too_wide) 18389 << !FieldName << FieldName << toString(Value, 10); 18390 } 18391 18392 if (!FieldTy->isDependentType()) { 18393 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 18394 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 18395 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 18396 18397 // Over-wide bitfields are an error in C or when using the MSVC bitfield 18398 // ABI. 18399 bool CStdConstraintViolation = 18400 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 18401 bool MSBitfieldViolation = 18402 Value.ugt(TypeStorageSize) && 18403 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 18404 if (CStdConstraintViolation || MSBitfieldViolation) { 18405 unsigned DiagWidth = 18406 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 18407 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 18408 << (bool)FieldName << FieldName << toString(Value, 10) 18409 << !CStdConstraintViolation << DiagWidth; 18410 } 18411 18412 // Warn on types where the user might conceivably expect to get all 18413 // specified bits as value bits: that's all integral types other than 18414 // 'bool'. 18415 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 18416 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 18417 << FieldName << toString(Value, 10) 18418 << (unsigned)TypeWidth; 18419 } 18420 } 18421 18422 return BitWidth; 18423 } 18424 18425 /// ActOnField - Each field of a C struct/union is passed into this in order 18426 /// to create a FieldDecl object for it. 18427 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 18428 Declarator &D, Expr *BitfieldWidth) { 18429 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart, 18430 D, BitfieldWidth, 18431 /*InitStyle=*/ICIS_NoInit, AS_public); 18432 return Res; 18433 } 18434 18435 /// HandleField - Analyze a field of a C struct or a C++ data member. 18436 /// 18437 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 18438 SourceLocation DeclStart, 18439 Declarator &D, Expr *BitWidth, 18440 InClassInitStyle InitStyle, 18441 AccessSpecifier AS) { 18442 if (D.isDecompositionDeclarator()) { 18443 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 18444 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 18445 << Decomp.getSourceRange(); 18446 return nullptr; 18447 } 18448 18449 IdentifierInfo *II = D.getIdentifier(); 18450 SourceLocation Loc = DeclStart; 18451 if (II) Loc = D.getIdentifierLoc(); 18452 18453 TypeSourceInfo *TInfo = GetTypeForDeclarator(D); 18454 QualType T = TInfo->getType(); 18455 if (getLangOpts().CPlusPlus) { 18456 CheckExtraCXXDefaultArguments(D); 18457 18458 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 18459 UPPC_DataMemberType)) { 18460 D.setInvalidType(); 18461 T = Context.IntTy; 18462 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 18463 } 18464 } 18465 18466 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 18467 18468 if (D.getDeclSpec().isInlineSpecified()) 18469 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 18470 << getLangOpts().CPlusPlus17; 18471 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 18472 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 18473 diag::err_invalid_thread) 18474 << DeclSpec::getSpecifierName(TSCS); 18475 18476 // Check to see if this name was declared as a member previously 18477 NamedDecl *PrevDecl = nullptr; 18478 LookupResult Previous(*this, II, Loc, LookupMemberName, 18479 ForVisibleRedeclaration); 18480 LookupName(Previous, S); 18481 switch (Previous.getResultKind()) { 18482 case LookupResult::Found: 18483 case LookupResult::FoundUnresolvedValue: 18484 PrevDecl = Previous.getAsSingle<NamedDecl>(); 18485 break; 18486 18487 case LookupResult::FoundOverloaded: 18488 PrevDecl = Previous.getRepresentativeDecl(); 18489 break; 18490 18491 case LookupResult::NotFound: 18492 case LookupResult::NotFoundInCurrentInstantiation: 18493 case LookupResult::Ambiguous: 18494 break; 18495 } 18496 Previous.suppressDiagnostics(); 18497 18498 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18499 // Maybe we will complain about the shadowed template parameter. 18500 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 18501 // Just pretend that we didn't see the previous declaration. 18502 PrevDecl = nullptr; 18503 } 18504 18505 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 18506 PrevDecl = nullptr; 18507 18508 bool Mutable 18509 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 18510 SourceLocation TSSL = D.getBeginLoc(); 18511 FieldDecl *NewFD 18512 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 18513 TSSL, AS, PrevDecl, &D); 18514 18515 if (NewFD->isInvalidDecl()) 18516 Record->setInvalidDecl(); 18517 18518 if (D.getDeclSpec().isModulePrivateSpecified()) 18519 NewFD->setModulePrivate(); 18520 18521 if (NewFD->isInvalidDecl() && PrevDecl) { 18522 // Don't introduce NewFD into scope; there's already something 18523 // with the same name in the same scope. 18524 } else if (II) { 18525 PushOnScopeChains(NewFD, S); 18526 } else 18527 Record->addDecl(NewFD); 18528 18529 return NewFD; 18530 } 18531 18532 /// Build a new FieldDecl and check its well-formedness. 18533 /// 18534 /// This routine builds a new FieldDecl given the fields name, type, 18535 /// record, etc. \p PrevDecl should refer to any previous declaration 18536 /// with the same name and in the same scope as the field to be 18537 /// created. 18538 /// 18539 /// \returns a new FieldDecl. 18540 /// 18541 /// \todo The Declarator argument is a hack. It will be removed once 18542 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 18543 TypeSourceInfo *TInfo, 18544 RecordDecl *Record, SourceLocation Loc, 18545 bool Mutable, Expr *BitWidth, 18546 InClassInitStyle InitStyle, 18547 SourceLocation TSSL, 18548 AccessSpecifier AS, NamedDecl *PrevDecl, 18549 Declarator *D) { 18550 IdentifierInfo *II = Name.getAsIdentifierInfo(); 18551 bool InvalidDecl = false; 18552 if (D) InvalidDecl = D->isInvalidType(); 18553 18554 // If we receive a broken type, recover by assuming 'int' and 18555 // marking this declaration as invalid. 18556 if (T.isNull() || T->containsErrors()) { 18557 InvalidDecl = true; 18558 T = Context.IntTy; 18559 } 18560 18561 QualType EltTy = Context.getBaseElementType(T); 18562 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 18563 if (RequireCompleteSizedType(Loc, EltTy, 18564 diag::err_field_incomplete_or_sizeless)) { 18565 // Fields of incomplete type force their record to be invalid. 18566 Record->setInvalidDecl(); 18567 InvalidDecl = true; 18568 } else { 18569 NamedDecl *Def; 18570 EltTy->isIncompleteType(&Def); 18571 if (Def && Def->isInvalidDecl()) { 18572 Record->setInvalidDecl(); 18573 InvalidDecl = true; 18574 } 18575 } 18576 } 18577 18578 // TR 18037 does not allow fields to be declared with address space 18579 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 18580 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 18581 Diag(Loc, diag::err_field_with_address_space); 18582 Record->setInvalidDecl(); 18583 InvalidDecl = true; 18584 } 18585 18586 if (LangOpts.OpenCL) { 18587 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 18588 // used as structure or union field: image, sampler, event or block types. 18589 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 18590 T->isBlockPointerType()) { 18591 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 18592 Record->setInvalidDecl(); 18593 InvalidDecl = true; 18594 } 18595 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 18596 // is enabled. 18597 if (BitWidth && !getOpenCLOptions().isAvailableOption( 18598 "__cl_clang_bitfields", LangOpts)) { 18599 Diag(Loc, diag::err_opencl_bitfields); 18600 InvalidDecl = true; 18601 } 18602 } 18603 18604 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 18605 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 18606 T.hasQualifiers()) { 18607 InvalidDecl = true; 18608 Diag(Loc, diag::err_anon_bitfield_qualifiers); 18609 } 18610 18611 // C99 6.7.2.1p8: A member of a structure or union may have any type other 18612 // than a variably modified type. 18613 if (!InvalidDecl && T->isVariablyModifiedType()) { 18614 if (!tryToFixVariablyModifiedVarType( 18615 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 18616 InvalidDecl = true; 18617 } 18618 18619 // Fields can not have abstract class types 18620 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 18621 diag::err_abstract_type_in_decl, 18622 AbstractFieldType)) 18623 InvalidDecl = true; 18624 18625 if (InvalidDecl) 18626 BitWidth = nullptr; 18627 // If this is declared as a bit-field, check the bit-field. 18628 if (BitWidth) { 18629 BitWidth = 18630 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get(); 18631 if (!BitWidth) { 18632 InvalidDecl = true; 18633 BitWidth = nullptr; 18634 } 18635 } 18636 18637 // Check that 'mutable' is consistent with the type of the declaration. 18638 if (!InvalidDecl && Mutable) { 18639 unsigned DiagID = 0; 18640 if (T->isReferenceType()) 18641 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 18642 : diag::err_mutable_reference; 18643 else if (T.isConstQualified()) 18644 DiagID = diag::err_mutable_const; 18645 18646 if (DiagID) { 18647 SourceLocation ErrLoc = Loc; 18648 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 18649 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 18650 Diag(ErrLoc, DiagID); 18651 if (DiagID != diag::ext_mutable_reference) { 18652 Mutable = false; 18653 InvalidDecl = true; 18654 } 18655 } 18656 } 18657 18658 // C++11 [class.union]p8 (DR1460): 18659 // At most one variant member of a union may have a 18660 // brace-or-equal-initializer. 18661 if (InitStyle != ICIS_NoInit) 18662 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 18663 18664 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 18665 BitWidth, Mutable, InitStyle); 18666 if (InvalidDecl) 18667 NewFD->setInvalidDecl(); 18668 18669 if (PrevDecl && !isa<TagDecl>(PrevDecl) && 18670 !PrevDecl->isPlaceholderVar(getLangOpts())) { 18671 Diag(Loc, diag::err_duplicate_member) << II; 18672 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 18673 NewFD->setInvalidDecl(); 18674 } 18675 18676 if (!InvalidDecl && getLangOpts().CPlusPlus) { 18677 if (Record->isUnion()) { 18678 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 18679 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 18680 if (RDecl->getDefinition()) { 18681 // C++ [class.union]p1: An object of a class with a non-trivial 18682 // constructor, a non-trivial copy constructor, a non-trivial 18683 // destructor, or a non-trivial copy assignment operator 18684 // cannot be a member of a union, nor can an array of such 18685 // objects. 18686 if (CheckNontrivialField(NewFD)) 18687 NewFD->setInvalidDecl(); 18688 } 18689 } 18690 18691 // C++ [class.union]p1: If a union contains a member of reference type, 18692 // the program is ill-formed, except when compiling with MSVC extensions 18693 // enabled. 18694 if (EltTy->isReferenceType()) { 18695 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 18696 diag::ext_union_member_of_reference_type : 18697 diag::err_union_member_of_reference_type) 18698 << NewFD->getDeclName() << EltTy; 18699 if (!getLangOpts().MicrosoftExt) 18700 NewFD->setInvalidDecl(); 18701 } 18702 } 18703 } 18704 18705 // FIXME: We need to pass in the attributes given an AST 18706 // representation, not a parser representation. 18707 if (D) { 18708 // FIXME: The current scope is almost... but not entirely... correct here. 18709 ProcessDeclAttributes(getCurScope(), NewFD, *D); 18710 18711 if (NewFD->hasAttrs()) 18712 CheckAlignasUnderalignment(NewFD); 18713 } 18714 18715 // In auto-retain/release, infer strong retension for fields of 18716 // retainable type. 18717 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 18718 NewFD->setInvalidDecl(); 18719 18720 if (T.isObjCGCWeak()) 18721 Diag(Loc, diag::warn_attribute_weak_on_field); 18722 18723 // PPC MMA non-pointer types are not allowed as field types. 18724 if (Context.getTargetInfo().getTriple().isPPC64() && 18725 CheckPPCMMAType(T, NewFD->getLocation())) 18726 NewFD->setInvalidDecl(); 18727 18728 NewFD->setAccess(AS); 18729 return NewFD; 18730 } 18731 18732 bool Sema::CheckNontrivialField(FieldDecl *FD) { 18733 assert(FD); 18734 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 18735 18736 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 18737 return false; 18738 18739 QualType EltTy = Context.getBaseElementType(FD->getType()); 18740 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 18741 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 18742 if (RDecl->getDefinition()) { 18743 // We check for copy constructors before constructors 18744 // because otherwise we'll never get complaints about 18745 // copy constructors. 18746 18747 CXXSpecialMember member = CXXInvalid; 18748 // We're required to check for any non-trivial constructors. Since the 18749 // implicit default constructor is suppressed if there are any 18750 // user-declared constructors, we just need to check that there is a 18751 // trivial default constructor and a trivial copy constructor. (We don't 18752 // worry about move constructors here, since this is a C++98 check.) 18753 if (RDecl->hasNonTrivialCopyConstructor()) 18754 member = CXXCopyConstructor; 18755 else if (!RDecl->hasTrivialDefaultConstructor()) 18756 member = CXXDefaultConstructor; 18757 else if (RDecl->hasNonTrivialCopyAssignment()) 18758 member = CXXCopyAssignment; 18759 else if (RDecl->hasNonTrivialDestructor()) 18760 member = CXXDestructor; 18761 18762 if (member != CXXInvalid) { 18763 if (!getLangOpts().CPlusPlus11 && 18764 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 18765 // Objective-C++ ARC: it is an error to have a non-trivial field of 18766 // a union. However, system headers in Objective-C programs 18767 // occasionally have Objective-C lifetime objects within unions, 18768 // and rather than cause the program to fail, we make those 18769 // members unavailable. 18770 SourceLocation Loc = FD->getLocation(); 18771 if (getSourceManager().isInSystemHeader(Loc)) { 18772 if (!FD->hasAttr<UnavailableAttr>()) 18773 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 18774 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 18775 return false; 18776 } 18777 } 18778 18779 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 18780 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 18781 diag::err_illegal_union_or_anon_struct_member) 18782 << FD->getParent()->isUnion() << FD->getDeclName() << member; 18783 DiagnoseNontrivial(RDecl, member); 18784 return !getLangOpts().CPlusPlus11; 18785 } 18786 } 18787 } 18788 18789 return false; 18790 } 18791 18792 /// TranslateIvarVisibility - Translate visibility from a token ID to an 18793 /// AST enum value. 18794 static ObjCIvarDecl::AccessControl 18795 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 18796 switch (ivarVisibility) { 18797 default: llvm_unreachable("Unknown visitibility kind"); 18798 case tok::objc_private: return ObjCIvarDecl::Private; 18799 case tok::objc_public: return ObjCIvarDecl::Public; 18800 case tok::objc_protected: return ObjCIvarDecl::Protected; 18801 case tok::objc_package: return ObjCIvarDecl::Package; 18802 } 18803 } 18804 18805 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 18806 /// in order to create an IvarDecl object for it. 18807 Decl *Sema::ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, 18808 Expr *BitWidth, tok::ObjCKeywordKind Visibility) { 18809 18810 IdentifierInfo *II = D.getIdentifier(); 18811 SourceLocation Loc = DeclStart; 18812 if (II) Loc = D.getIdentifierLoc(); 18813 18814 // FIXME: Unnamed fields can be handled in various different ways, for 18815 // example, unnamed unions inject all members into the struct namespace! 18816 18817 TypeSourceInfo *TInfo = GetTypeForDeclarator(D); 18818 QualType T = TInfo->getType(); 18819 18820 if (BitWidth) { 18821 // 6.7.2.1p3, 6.7.2.1p4 18822 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 18823 if (!BitWidth) 18824 D.setInvalidType(); 18825 } else { 18826 // Not a bitfield. 18827 18828 // validate II. 18829 18830 } 18831 if (T->isReferenceType()) { 18832 Diag(Loc, diag::err_ivar_reference_type); 18833 D.setInvalidType(); 18834 } 18835 // C99 6.7.2.1p8: A member of a structure or union may have any type other 18836 // than a variably modified type. 18837 else if (T->isVariablyModifiedType()) { 18838 if (!tryToFixVariablyModifiedVarType( 18839 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 18840 D.setInvalidType(); 18841 } 18842 18843 // Get the visibility (access control) for this ivar. 18844 ObjCIvarDecl::AccessControl ac = 18845 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 18846 : ObjCIvarDecl::None; 18847 // Must set ivar's DeclContext to its enclosing interface. 18848 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 18849 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 18850 return nullptr; 18851 ObjCContainerDecl *EnclosingContext; 18852 if (ObjCImplementationDecl *IMPDecl = 18853 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 18854 if (LangOpts.ObjCRuntime.isFragile()) { 18855 // Case of ivar declared in an implementation. Context is that of its class. 18856 EnclosingContext = IMPDecl->getClassInterface(); 18857 assert(EnclosingContext && "Implementation has no class interface!"); 18858 } 18859 else 18860 EnclosingContext = EnclosingDecl; 18861 } else { 18862 if (ObjCCategoryDecl *CDecl = 18863 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 18864 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 18865 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 18866 return nullptr; 18867 } 18868 } 18869 EnclosingContext = EnclosingDecl; 18870 } 18871 18872 // Construct the decl. 18873 ObjCIvarDecl *NewID = ObjCIvarDecl::Create( 18874 Context, EnclosingContext, DeclStart, Loc, II, T, TInfo, ac, BitWidth); 18875 18876 if (T->containsErrors()) 18877 NewID->setInvalidDecl(); 18878 18879 if (II) { 18880 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 18881 ForVisibleRedeclaration); 18882 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 18883 && !isa<TagDecl>(PrevDecl)) { 18884 Diag(Loc, diag::err_duplicate_member) << II; 18885 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 18886 NewID->setInvalidDecl(); 18887 } 18888 } 18889 18890 // Process attributes attached to the ivar. 18891 ProcessDeclAttributes(S, NewID, D); 18892 18893 if (D.isInvalidType()) 18894 NewID->setInvalidDecl(); 18895 18896 // In ARC, infer 'retaining' for ivars of retainable type. 18897 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 18898 NewID->setInvalidDecl(); 18899 18900 if (D.getDeclSpec().isModulePrivateSpecified()) 18901 NewID->setModulePrivate(); 18902 18903 if (II) { 18904 // FIXME: When interfaces are DeclContexts, we'll need to add 18905 // these to the interface. 18906 S->AddDecl(NewID); 18907 IdResolver.AddDecl(NewID); 18908 } 18909 18910 if (LangOpts.ObjCRuntime.isNonFragile() && 18911 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 18912 Diag(Loc, diag::warn_ivars_in_interface); 18913 18914 return NewID; 18915 } 18916 18917 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 18918 /// class and class extensions. For every class \@interface and class 18919 /// extension \@interface, if the last ivar is a bitfield of any type, 18920 /// then add an implicit `char :0` ivar to the end of that interface. 18921 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 18922 SmallVectorImpl<Decl *> &AllIvarDecls) { 18923 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 18924 return; 18925 18926 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 18927 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 18928 18929 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 18930 return; 18931 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 18932 if (!ID) { 18933 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 18934 if (!CD->IsClassExtension()) 18935 return; 18936 } 18937 // No need to add this to end of @implementation. 18938 else 18939 return; 18940 } 18941 // All conditions are met. Add a new bitfield to the tail end of ivars. 18942 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 18943 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 18944 18945 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 18946 DeclLoc, DeclLoc, nullptr, 18947 Context.CharTy, 18948 Context.getTrivialTypeSourceInfo(Context.CharTy, 18949 DeclLoc), 18950 ObjCIvarDecl::Private, BW, 18951 true); 18952 AllIvarDecls.push_back(Ivar); 18953 } 18954 18955 /// [class.dtor]p4: 18956 /// At the end of the definition of a class, overload resolution is 18957 /// performed among the prospective destructors declared in that class with 18958 /// an empty argument list to select the destructor for the class, also 18959 /// known as the selected destructor. 18960 /// 18961 /// We do the overload resolution here, then mark the selected constructor in the AST. 18962 /// Later CXXRecordDecl::getDestructor() will return the selected constructor. 18963 static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) { 18964 if (!Record->hasUserDeclaredDestructor()) { 18965 return; 18966 } 18967 18968 SourceLocation Loc = Record->getLocation(); 18969 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal); 18970 18971 for (auto *Decl : Record->decls()) { 18972 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) { 18973 if (DD->isInvalidDecl()) 18974 continue; 18975 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {}, 18976 OCS); 18977 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected."); 18978 } 18979 } 18980 18981 if (OCS.empty()) { 18982 return; 18983 } 18984 OverloadCandidateSet::iterator Best; 18985 unsigned Msg = 0; 18986 OverloadCandidateDisplayKind DisplayKind; 18987 18988 switch (OCS.BestViableFunction(S, Loc, Best)) { 18989 case OR_Success: 18990 case OR_Deleted: 18991 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function)); 18992 break; 18993 18994 case OR_Ambiguous: 18995 Msg = diag::err_ambiguous_destructor; 18996 DisplayKind = OCD_AmbiguousCandidates; 18997 break; 18998 18999 case OR_No_Viable_Function: 19000 Msg = diag::err_no_viable_destructor; 19001 DisplayKind = OCD_AllCandidates; 19002 break; 19003 } 19004 19005 if (Msg) { 19006 // OpenCL have got their own thing going with destructors. It's slightly broken, 19007 // but we allow it. 19008 if (!S.LangOpts.OpenCL) { 19009 PartialDiagnostic Diag = S.PDiag(Msg) << Record; 19010 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {}); 19011 Record->setInvalidDecl(); 19012 } 19013 // It's a bit hacky: At this point we've raised an error but we want the 19014 // rest of the compiler to continue somehow working. However almost 19015 // everything we'll try to do with the class will depend on there being a 19016 // destructor. So let's pretend the first one is selected and hope for the 19017 // best. 19018 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function)); 19019 } 19020 } 19021 19022 /// [class.mem.special]p5 19023 /// Two special member functions are of the same kind if: 19024 /// - they are both default constructors, 19025 /// - they are both copy or move constructors with the same first parameter 19026 /// type, or 19027 /// - they are both copy or move assignment operators with the same first 19028 /// parameter type and the same cv-qualifiers and ref-qualifier, if any. 19029 static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, 19030 CXXMethodDecl *M1, 19031 CXXMethodDecl *M2, 19032 Sema::CXXSpecialMember CSM) { 19033 // We don't want to compare templates to non-templates: See 19034 // https://github.com/llvm/llvm-project/issues/59206 19035 if (CSM == Sema::CXXDefaultConstructor) 19036 return bool(M1->getDescribedFunctionTemplate()) == 19037 bool(M2->getDescribedFunctionTemplate()); 19038 // FIXME: better resolve CWG 19039 // https://cplusplus.github.io/CWG/issues/2787.html 19040 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(), 19041 M2->getNonObjectParameter(0)->getType())) 19042 return false; 19043 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(), 19044 M2->getFunctionObjectParameterReferenceType())) 19045 return false; 19046 19047 return true; 19048 } 19049 19050 /// [class.mem.special]p6: 19051 /// An eligible special member function is a special member function for which: 19052 /// - the function is not deleted, 19053 /// - the associated constraints, if any, are satisfied, and 19054 /// - no special member function of the same kind whose associated constraints 19055 /// [CWG2595], if any, are satisfied is more constrained. 19056 static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, 19057 ArrayRef<CXXMethodDecl *> Methods, 19058 Sema::CXXSpecialMember CSM) { 19059 SmallVector<bool, 4> SatisfactionStatus; 19060 19061 for (CXXMethodDecl *Method : Methods) { 19062 const Expr *Constraints = Method->getTrailingRequiresClause(); 19063 if (!Constraints) 19064 SatisfactionStatus.push_back(true); 19065 else { 19066 ConstraintSatisfaction Satisfaction; 19067 if (S.CheckFunctionConstraints(Method, Satisfaction)) 19068 SatisfactionStatus.push_back(false); 19069 else 19070 SatisfactionStatus.push_back(Satisfaction.IsSatisfied); 19071 } 19072 } 19073 19074 for (size_t i = 0; i < Methods.size(); i++) { 19075 if (!SatisfactionStatus[i]) 19076 continue; 19077 CXXMethodDecl *Method = Methods[i]; 19078 CXXMethodDecl *OrigMethod = Method; 19079 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction()) 19080 OrigMethod = cast<CXXMethodDecl>(MF); 19081 19082 const Expr *Constraints = OrigMethod->getTrailingRequiresClause(); 19083 bool AnotherMethodIsMoreConstrained = false; 19084 for (size_t j = 0; j < Methods.size(); j++) { 19085 if (i == j || !SatisfactionStatus[j]) 19086 continue; 19087 CXXMethodDecl *OtherMethod = Methods[j]; 19088 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction()) 19089 OtherMethod = cast<CXXMethodDecl>(MF); 19090 19091 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod, 19092 CSM)) 19093 continue; 19094 19095 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause(); 19096 if (!OtherConstraints) 19097 continue; 19098 if (!Constraints) { 19099 AnotherMethodIsMoreConstrained = true; 19100 break; 19101 } 19102 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod, 19103 {Constraints}, 19104 AnotherMethodIsMoreConstrained)) { 19105 // There was an error with the constraints comparison. Exit the loop 19106 // and don't consider this function eligible. 19107 AnotherMethodIsMoreConstrained = true; 19108 } 19109 if (AnotherMethodIsMoreConstrained) 19110 break; 19111 } 19112 // FIXME: Do not consider deleted methods as eligible after implementing 19113 // DR1734 and DR1496. 19114 if (!AnotherMethodIsMoreConstrained) { 19115 Method->setIneligibleOrNotSelected(false); 19116 Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM); 19117 } 19118 } 19119 } 19120 19121 static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, 19122 CXXRecordDecl *Record) { 19123 SmallVector<CXXMethodDecl *, 4> DefaultConstructors; 19124 SmallVector<CXXMethodDecl *, 4> CopyConstructors; 19125 SmallVector<CXXMethodDecl *, 4> MoveConstructors; 19126 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators; 19127 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators; 19128 19129 for (auto *Decl : Record->decls()) { 19130 auto *MD = dyn_cast<CXXMethodDecl>(Decl); 19131 if (!MD) { 19132 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl); 19133 if (FTD) 19134 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl()); 19135 } 19136 if (!MD) 19137 continue; 19138 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) { 19139 if (CD->isInvalidDecl()) 19140 continue; 19141 if (CD->isDefaultConstructor()) 19142 DefaultConstructors.push_back(MD); 19143 else if (CD->isCopyConstructor()) 19144 CopyConstructors.push_back(MD); 19145 else if (CD->isMoveConstructor()) 19146 MoveConstructors.push_back(MD); 19147 } else if (MD->isCopyAssignmentOperator()) { 19148 CopyAssignmentOperators.push_back(MD); 19149 } else if (MD->isMoveAssignmentOperator()) { 19150 MoveAssignmentOperators.push_back(MD); 19151 } 19152 } 19153 19154 SetEligibleMethods(S, Record, DefaultConstructors, 19155 Sema::CXXDefaultConstructor); 19156 SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor); 19157 SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor); 19158 SetEligibleMethods(S, Record, CopyAssignmentOperators, 19159 Sema::CXXCopyAssignment); 19160 SetEligibleMethods(S, Record, MoveAssignmentOperators, 19161 Sema::CXXMoveAssignment); 19162 } 19163 19164 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 19165 ArrayRef<Decl *> Fields, SourceLocation LBrac, 19166 SourceLocation RBrac, 19167 const ParsedAttributesView &Attrs) { 19168 assert(EnclosingDecl && "missing record or interface decl"); 19169 19170 // If this is an Objective-C @implementation or category and we have 19171 // new fields here we should reset the layout of the interface since 19172 // it will now change. 19173 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 19174 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 19175 switch (DC->getKind()) { 19176 default: break; 19177 case Decl::ObjCCategory: 19178 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 19179 break; 19180 case Decl::ObjCImplementation: 19181 Context. 19182 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 19183 break; 19184 } 19185 } 19186 19187 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 19188 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 19189 19190 // Start counting up the number of named members; make sure to include 19191 // members of anonymous structs and unions in the total. 19192 unsigned NumNamedMembers = 0; 19193 if (Record) { 19194 for (const auto *I : Record->decls()) { 19195 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 19196 if (IFD->getDeclName()) 19197 ++NumNamedMembers; 19198 } 19199 } 19200 19201 // Verify that all the fields are okay. 19202 SmallVector<FieldDecl*, 32> RecFields; 19203 19204 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 19205 i != end; ++i) { 19206 FieldDecl *FD = cast<FieldDecl>(*i); 19207 19208 // Get the type for the field. 19209 const Type *FDTy = FD->getType().getTypePtr(); 19210 19211 if (!FD->isAnonymousStructOrUnion()) { 19212 // Remember all fields written by the user. 19213 RecFields.push_back(FD); 19214 } 19215 19216 // If the field is already invalid for some reason, don't emit more 19217 // diagnostics about it. 19218 if (FD->isInvalidDecl()) { 19219 EnclosingDecl->setInvalidDecl(); 19220 continue; 19221 } 19222 19223 // C99 6.7.2.1p2: 19224 // A structure or union shall not contain a member with 19225 // incomplete or function type (hence, a structure shall not 19226 // contain an instance of itself, but may contain a pointer to 19227 // an instance of itself), except that the last member of a 19228 // structure with more than one named member may have incomplete 19229 // array type; such a structure (and any union containing, 19230 // possibly recursively, a member that is such a structure) 19231 // shall not be a member of a structure or an element of an 19232 // array. 19233 bool IsLastField = (i + 1 == Fields.end()); 19234 if (FDTy->isFunctionType()) { 19235 // Field declared as a function. 19236 Diag(FD->getLocation(), diag::err_field_declared_as_function) 19237 << FD->getDeclName(); 19238 FD->setInvalidDecl(); 19239 EnclosingDecl->setInvalidDecl(); 19240 continue; 19241 } else if (FDTy->isIncompleteArrayType() && 19242 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 19243 if (Record) { 19244 // Flexible array member. 19245 // Microsoft and g++ is more permissive regarding flexible array. 19246 // It will accept flexible array in union and also 19247 // as the sole element of a struct/class. 19248 unsigned DiagID = 0; 19249 if (!Record->isUnion() && !IsLastField) { 19250 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 19251 << FD->getDeclName() << FD->getType() 19252 << llvm::to_underlying(Record->getTagKind()); 19253 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 19254 FD->setInvalidDecl(); 19255 EnclosingDecl->setInvalidDecl(); 19256 continue; 19257 } else if (Record->isUnion()) 19258 DiagID = getLangOpts().MicrosoftExt 19259 ? diag::ext_flexible_array_union_ms 19260 : getLangOpts().CPlusPlus 19261 ? diag::ext_flexible_array_union_gnu 19262 : diag::err_flexible_array_union; 19263 else if (NumNamedMembers < 1) 19264 DiagID = getLangOpts().MicrosoftExt 19265 ? diag::ext_flexible_array_empty_aggregate_ms 19266 : getLangOpts().CPlusPlus 19267 ? diag::ext_flexible_array_empty_aggregate_gnu 19268 : diag::err_flexible_array_empty_aggregate; 19269 19270 if (DiagID) 19271 Diag(FD->getLocation(), DiagID) 19272 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind()); 19273 // While the layout of types that contain virtual bases is not specified 19274 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 19275 // virtual bases after the derived members. This would make a flexible 19276 // array member declared at the end of an object not adjacent to the end 19277 // of the type. 19278 if (CXXRecord && CXXRecord->getNumVBases() != 0) 19279 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 19280 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind()); 19281 if (!getLangOpts().C99) 19282 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 19283 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind()); 19284 19285 // If the element type has a non-trivial destructor, we would not 19286 // implicitly destroy the elements, so disallow it for now. 19287 // 19288 // FIXME: GCC allows this. We should probably either implicitly delete 19289 // the destructor of the containing class, or just allow this. 19290 QualType BaseElem = Context.getBaseElementType(FD->getType()); 19291 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 19292 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 19293 << FD->getDeclName() << FD->getType(); 19294 FD->setInvalidDecl(); 19295 EnclosingDecl->setInvalidDecl(); 19296 continue; 19297 } 19298 // Okay, we have a legal flexible array member at the end of the struct. 19299 Record->setHasFlexibleArrayMember(true); 19300 } else { 19301 // In ObjCContainerDecl ivars with incomplete array type are accepted, 19302 // unless they are followed by another ivar. That check is done 19303 // elsewhere, after synthesized ivars are known. 19304 } 19305 } else if (!FDTy->isDependentType() && 19306 RequireCompleteSizedType( 19307 FD->getLocation(), FD->getType(), 19308 diag::err_field_incomplete_or_sizeless)) { 19309 // Incomplete type 19310 FD->setInvalidDecl(); 19311 EnclosingDecl->setInvalidDecl(); 19312 continue; 19313 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 19314 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 19315 // A type which contains a flexible array member is considered to be a 19316 // flexible array member. 19317 Record->setHasFlexibleArrayMember(true); 19318 if (!Record->isUnion()) { 19319 // If this is a struct/class and this is not the last element, reject 19320 // it. Note that GCC supports variable sized arrays in the middle of 19321 // structures. 19322 if (!IsLastField) 19323 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 19324 << FD->getDeclName() << FD->getType(); 19325 else { 19326 // We support flexible arrays at the end of structs in 19327 // other structs as an extension. 19328 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 19329 << FD->getDeclName(); 19330 } 19331 } 19332 } 19333 if (isa<ObjCContainerDecl>(EnclosingDecl) && 19334 RequireNonAbstractType(FD->getLocation(), FD->getType(), 19335 diag::err_abstract_type_in_decl, 19336 AbstractIvarType)) { 19337 // Ivars can not have abstract class types 19338 FD->setInvalidDecl(); 19339 } 19340 if (Record && FDTTy->getDecl()->hasObjectMember()) 19341 Record->setHasObjectMember(true); 19342 if (Record && FDTTy->getDecl()->hasVolatileMember()) 19343 Record->setHasVolatileMember(true); 19344 } else if (FDTy->isObjCObjectType()) { 19345 /// A field cannot be an Objective-c object 19346 Diag(FD->getLocation(), diag::err_statically_allocated_object) 19347 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 19348 QualType T = Context.getObjCObjectPointerType(FD->getType()); 19349 FD->setType(T); 19350 } else if (Record && Record->isUnion() && 19351 FD->getType().hasNonTrivialObjCLifetime() && 19352 getSourceManager().isInSystemHeader(FD->getLocation()) && 19353 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 19354 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 19355 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 19356 // For backward compatibility, fields of C unions declared in system 19357 // headers that have non-trivial ObjC ownership qualifications are marked 19358 // as unavailable unless the qualifier is explicit and __strong. This can 19359 // break ABI compatibility between programs compiled with ARC and MRR, but 19360 // is a better option than rejecting programs using those unions under 19361 // ARC. 19362 FD->addAttr(UnavailableAttr::CreateImplicit( 19363 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 19364 FD->getLocation())); 19365 } else if (getLangOpts().ObjC && 19366 getLangOpts().getGC() != LangOptions::NonGC && Record && 19367 !Record->hasObjectMember()) { 19368 if (FD->getType()->isObjCObjectPointerType() || 19369 FD->getType().isObjCGCStrong()) 19370 Record->setHasObjectMember(true); 19371 else if (Context.getAsArrayType(FD->getType())) { 19372 QualType BaseType = Context.getBaseElementType(FD->getType()); 19373 if (BaseType->isRecordType() && 19374 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 19375 Record->setHasObjectMember(true); 19376 else if (BaseType->isObjCObjectPointerType() || 19377 BaseType.isObjCGCStrong()) 19378 Record->setHasObjectMember(true); 19379 } 19380 } 19381 19382 if (Record && !getLangOpts().CPlusPlus && 19383 !shouldIgnoreForRecordTriviality(FD)) { 19384 QualType FT = FD->getType(); 19385 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 19386 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 19387 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 19388 Record->isUnion()) 19389 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 19390 } 19391 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 19392 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 19393 Record->setNonTrivialToPrimitiveCopy(true); 19394 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 19395 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 19396 } 19397 if (FT.isDestructedType()) { 19398 Record->setNonTrivialToPrimitiveDestroy(true); 19399 Record->setParamDestroyedInCallee(true); 19400 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 19401 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 19402 } 19403 19404 if (const auto *RT = FT->getAs<RecordType>()) { 19405 if (RT->getDecl()->getArgPassingRestrictions() == 19406 RecordArgPassingKind::CanNeverPassInRegs) 19407 Record->setArgPassingRestrictions( 19408 RecordArgPassingKind::CanNeverPassInRegs); 19409 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 19410 Record->setArgPassingRestrictions( 19411 RecordArgPassingKind::CanNeverPassInRegs); 19412 } 19413 19414 if (Record && FD->getType().isVolatileQualified()) 19415 Record->setHasVolatileMember(true); 19416 // Keep track of the number of named members. 19417 if (FD->getIdentifier()) 19418 ++NumNamedMembers; 19419 } 19420 19421 // Okay, we successfully defined 'Record'. 19422 if (Record) { 19423 bool Completed = false; 19424 if (CXXRecord) { 19425 if (!CXXRecord->isInvalidDecl()) { 19426 // Set access bits correctly on the directly-declared conversions. 19427 for (CXXRecordDecl::conversion_iterator 19428 I = CXXRecord->conversion_begin(), 19429 E = CXXRecord->conversion_end(); I != E; ++I) 19430 I.setAccess((*I)->getAccess()); 19431 } 19432 19433 // Add any implicitly-declared members to this class. 19434 AddImplicitlyDeclaredMembersToClass(CXXRecord); 19435 19436 if (!CXXRecord->isDependentType()) { 19437 if (!CXXRecord->isInvalidDecl()) { 19438 // If we have virtual base classes, we may end up finding multiple 19439 // final overriders for a given virtual function. Check for this 19440 // problem now. 19441 if (CXXRecord->getNumVBases()) { 19442 CXXFinalOverriderMap FinalOverriders; 19443 CXXRecord->getFinalOverriders(FinalOverriders); 19444 19445 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 19446 MEnd = FinalOverriders.end(); 19447 M != MEnd; ++M) { 19448 for (OverridingMethods::iterator SO = M->second.begin(), 19449 SOEnd = M->second.end(); 19450 SO != SOEnd; ++SO) { 19451 assert(SO->second.size() > 0 && 19452 "Virtual function without overriding functions?"); 19453 if (SO->second.size() == 1) 19454 continue; 19455 19456 // C++ [class.virtual]p2: 19457 // In a derived class, if a virtual member function of a base 19458 // class subobject has more than one final overrider the 19459 // program is ill-formed. 19460 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 19461 << (const NamedDecl *)M->first << Record; 19462 Diag(M->first->getLocation(), 19463 diag::note_overridden_virtual_function); 19464 for (OverridingMethods::overriding_iterator 19465 OM = SO->second.begin(), 19466 OMEnd = SO->second.end(); 19467 OM != OMEnd; ++OM) 19468 Diag(OM->Method->getLocation(), diag::note_final_overrider) 19469 << (const NamedDecl *)M->first << OM->Method->getParent(); 19470 19471 Record->setInvalidDecl(); 19472 } 19473 } 19474 CXXRecord->completeDefinition(&FinalOverriders); 19475 Completed = true; 19476 } 19477 } 19478 ComputeSelectedDestructor(*this, CXXRecord); 19479 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord); 19480 } 19481 } 19482 19483 if (!Completed) 19484 Record->completeDefinition(); 19485 19486 // Handle attributes before checking the layout. 19487 ProcessDeclAttributeList(S, Record, Attrs); 19488 19489 // Check to see if a FieldDecl is a pointer to a function. 19490 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) { 19491 const FieldDecl *FD = dyn_cast<FieldDecl>(D); 19492 if (!FD) { 19493 // Check whether this is a forward declaration that was inserted by 19494 // Clang. This happens when a non-forward declared / defined type is 19495 // used, e.g.: 19496 // 19497 // struct foo { 19498 // struct bar *(*f)(); 19499 // struct bar *(*g)(); 19500 // }; 19501 // 19502 // "struct bar" shows up in the decl AST as a "RecordDecl" with an 19503 // incomplete definition. 19504 if (const auto *TD = dyn_cast<TagDecl>(D)) 19505 return !TD->isCompleteDefinition(); 19506 return false; 19507 } 19508 QualType FieldType = FD->getType().getDesugaredType(Context); 19509 if (isa<PointerType>(FieldType)) { 19510 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType(); 19511 return PointeeType.getDesugaredType(Context)->isFunctionType(); 19512 } 19513 return false; 19514 }; 19515 19516 // Maybe randomize the record's decls. We automatically randomize a record 19517 // of function pointers, unless it has the "no_randomize_layout" attribute. 19518 if (!getLangOpts().CPlusPlus && 19519 (Record->hasAttr<RandomizeLayoutAttr>() || 19520 (!Record->hasAttr<NoRandomizeLayoutAttr>() && 19521 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) && 19522 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() && 19523 !Record->isRandomized()) { 19524 SmallVector<Decl *, 32> NewDeclOrdering; 19525 if (randstruct::randomizeStructureLayout(Context, Record, 19526 NewDeclOrdering)) 19527 Record->reorderDecls(NewDeclOrdering); 19528 } 19529 19530 // We may have deferred checking for a deleted destructor. Check now. 19531 if (CXXRecord) { 19532 auto *Dtor = CXXRecord->getDestructor(); 19533 if (Dtor && Dtor->isImplicit() && 19534 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 19535 CXXRecord->setImplicitDestructorIsDeleted(); 19536 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 19537 } 19538 } 19539 19540 if (Record->hasAttrs()) { 19541 CheckAlignasUnderalignment(Record); 19542 19543 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 19544 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 19545 IA->getRange(), IA->getBestCase(), 19546 IA->getInheritanceModel()); 19547 } 19548 19549 // Check if the structure/union declaration is a type that can have zero 19550 // size in C. For C this is a language extension, for C++ it may cause 19551 // compatibility problems. 19552 bool CheckForZeroSize; 19553 if (!getLangOpts().CPlusPlus) { 19554 CheckForZeroSize = true; 19555 } else { 19556 // For C++ filter out types that cannot be referenced in C code. 19557 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 19558 CheckForZeroSize = 19559 CXXRecord->getLexicalDeclContext()->isExternCContext() && 19560 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 19561 CXXRecord->isCLike(); 19562 } 19563 if (CheckForZeroSize) { 19564 bool ZeroSize = true; 19565 bool IsEmpty = true; 19566 unsigned NonBitFields = 0; 19567 for (RecordDecl::field_iterator I = Record->field_begin(), 19568 E = Record->field_end(); 19569 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 19570 IsEmpty = false; 19571 if (I->isUnnamedBitfield()) { 19572 if (!I->isZeroLengthBitField(Context)) 19573 ZeroSize = false; 19574 } else { 19575 ++NonBitFields; 19576 QualType FieldType = I->getType(); 19577 if (FieldType->isIncompleteType() || 19578 !Context.getTypeSizeInChars(FieldType).isZero()) 19579 ZeroSize = false; 19580 } 19581 } 19582 19583 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 19584 // allowed in C++, but warn if its declaration is inside 19585 // extern "C" block. 19586 if (ZeroSize) { 19587 Diag(RecLoc, getLangOpts().CPlusPlus ? 19588 diag::warn_zero_size_struct_union_in_extern_c : 19589 diag::warn_zero_size_struct_union_compat) 19590 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 19591 } 19592 19593 // Structs without named members are extension in C (C99 6.7.2.1p7), 19594 // but are accepted by GCC. 19595 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 19596 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 19597 diag::ext_no_named_members_in_struct_union) 19598 << Record->isUnion(); 19599 } 19600 } 19601 } else { 19602 ObjCIvarDecl **ClsFields = 19603 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 19604 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 19605 ID->setEndOfDefinitionLoc(RBrac); 19606 // Add ivar's to class's DeclContext. 19607 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 19608 ClsFields[i]->setLexicalDeclContext(ID); 19609 ID->addDecl(ClsFields[i]); 19610 } 19611 // Must enforce the rule that ivars in the base classes may not be 19612 // duplicates. 19613 if (ID->getSuperClass()) 19614 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 19615 } else if (ObjCImplementationDecl *IMPDecl = 19616 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 19617 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 19618 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 19619 // Ivar declared in @implementation never belongs to the implementation. 19620 // Only it is in implementation's lexical context. 19621 ClsFields[I]->setLexicalDeclContext(IMPDecl); 19622 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 19623 IMPDecl->setIvarLBraceLoc(LBrac); 19624 IMPDecl->setIvarRBraceLoc(RBrac); 19625 } else if (ObjCCategoryDecl *CDecl = 19626 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 19627 // case of ivars in class extension; all other cases have been 19628 // reported as errors elsewhere. 19629 // FIXME. Class extension does not have a LocEnd field. 19630 // CDecl->setLocEnd(RBrac); 19631 // Add ivar's to class extension's DeclContext. 19632 // Diagnose redeclaration of private ivars. 19633 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 19634 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 19635 if (IDecl) { 19636 if (const ObjCIvarDecl *ClsIvar = 19637 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 19638 Diag(ClsFields[i]->getLocation(), 19639 diag::err_duplicate_ivar_declaration); 19640 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 19641 continue; 19642 } 19643 for (const auto *Ext : IDecl->known_extensions()) { 19644 if (const ObjCIvarDecl *ClsExtIvar 19645 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 19646 Diag(ClsFields[i]->getLocation(), 19647 diag::err_duplicate_ivar_declaration); 19648 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 19649 continue; 19650 } 19651 } 19652 } 19653 ClsFields[i]->setLexicalDeclContext(CDecl); 19654 CDecl->addDecl(ClsFields[i]); 19655 } 19656 CDecl->setIvarLBraceLoc(LBrac); 19657 CDecl->setIvarRBraceLoc(RBrac); 19658 } 19659 } 19660 } 19661 19662 /// Determine whether the given integral value is representable within 19663 /// the given type T. 19664 static bool isRepresentableIntegerValue(ASTContext &Context, 19665 llvm::APSInt &Value, 19666 QualType T) { 19667 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 19668 "Integral type required!"); 19669 unsigned BitWidth = Context.getIntWidth(T); 19670 19671 if (Value.isUnsigned() || Value.isNonNegative()) { 19672 if (T->isSignedIntegerOrEnumerationType()) 19673 --BitWidth; 19674 return Value.getActiveBits() <= BitWidth; 19675 } 19676 return Value.getSignificantBits() <= BitWidth; 19677 } 19678 19679 // Given an integral type, return the next larger integral type 19680 // (or a NULL type of no such type exists). 19681 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 19682 // FIXME: Int128/UInt128 support, which also needs to be introduced into 19683 // enum checking below. 19684 assert((T->isIntegralType(Context) || 19685 T->isEnumeralType()) && "Integral type required!"); 19686 const unsigned NumTypes = 4; 19687 QualType SignedIntegralTypes[NumTypes] = { 19688 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 19689 }; 19690 QualType UnsignedIntegralTypes[NumTypes] = { 19691 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 19692 Context.UnsignedLongLongTy 19693 }; 19694 19695 unsigned BitWidth = Context.getTypeSize(T); 19696 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 19697 : UnsignedIntegralTypes; 19698 for (unsigned I = 0; I != NumTypes; ++I) 19699 if (Context.getTypeSize(Types[I]) > BitWidth) 19700 return Types[I]; 19701 19702 return QualType(); 19703 } 19704 19705 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 19706 EnumConstantDecl *LastEnumConst, 19707 SourceLocation IdLoc, 19708 IdentifierInfo *Id, 19709 Expr *Val) { 19710 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 19711 llvm::APSInt EnumVal(IntWidth); 19712 QualType EltTy; 19713 19714 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 19715 Val = nullptr; 19716 19717 if (Val) 19718 Val = DefaultLvalueConversion(Val).get(); 19719 19720 if (Val) { 19721 if (Enum->isDependentType() || Val->isTypeDependent() || 19722 Val->containsErrors()) 19723 EltTy = Context.DependentTy; 19724 else { 19725 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 19726 // underlying type, but do allow it in all other contexts. 19727 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 19728 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 19729 // constant-expression in the enumerator-definition shall be a converted 19730 // constant expression of the underlying type. 19731 EltTy = Enum->getIntegerType(); 19732 ExprResult Converted = 19733 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 19734 CCEK_Enumerator); 19735 if (Converted.isInvalid()) 19736 Val = nullptr; 19737 else 19738 Val = Converted.get(); 19739 } else if (!Val->isValueDependent() && 19740 !(Val = 19741 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 19742 .get())) { 19743 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 19744 } else { 19745 if (Enum->isComplete()) { 19746 EltTy = Enum->getIntegerType(); 19747 19748 // In Obj-C and Microsoft mode, require the enumeration value to be 19749 // representable in the underlying type of the enumeration. In C++11, 19750 // we perform a non-narrowing conversion as part of converted constant 19751 // expression checking. 19752 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 19753 if (Context.getTargetInfo() 19754 .getTriple() 19755 .isWindowsMSVCEnvironment()) { 19756 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 19757 } else { 19758 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 19759 } 19760 } 19761 19762 // Cast to the underlying type. 19763 Val = ImpCastExprToType(Val, EltTy, 19764 EltTy->isBooleanType() ? CK_IntegralToBoolean 19765 : CK_IntegralCast) 19766 .get(); 19767 } else if (getLangOpts().CPlusPlus) { 19768 // C++11 [dcl.enum]p5: 19769 // If the underlying type is not fixed, the type of each enumerator 19770 // is the type of its initializing value: 19771 // - If an initializer is specified for an enumerator, the 19772 // initializing value has the same type as the expression. 19773 EltTy = Val->getType(); 19774 } else { 19775 // C99 6.7.2.2p2: 19776 // The expression that defines the value of an enumeration constant 19777 // shall be an integer constant expression that has a value 19778 // representable as an int. 19779 19780 // Complain if the value is not representable in an int. 19781 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 19782 Diag(IdLoc, diag::ext_enum_value_not_int) 19783 << toString(EnumVal, 10) << Val->getSourceRange() 19784 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 19785 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 19786 // Force the type of the expression to 'int'. 19787 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 19788 } 19789 EltTy = Val->getType(); 19790 } 19791 } 19792 } 19793 } 19794 19795 if (!Val) { 19796 if (Enum->isDependentType()) 19797 EltTy = Context.DependentTy; 19798 else if (!LastEnumConst) { 19799 // C++0x [dcl.enum]p5: 19800 // If the underlying type is not fixed, the type of each enumerator 19801 // is the type of its initializing value: 19802 // - If no initializer is specified for the first enumerator, the 19803 // initializing value has an unspecified integral type. 19804 // 19805 // GCC uses 'int' for its unspecified integral type, as does 19806 // C99 6.7.2.2p3. 19807 if (Enum->isFixed()) { 19808 EltTy = Enum->getIntegerType(); 19809 } 19810 else { 19811 EltTy = Context.IntTy; 19812 } 19813 } else { 19814 // Assign the last value + 1. 19815 EnumVal = LastEnumConst->getInitVal(); 19816 ++EnumVal; 19817 EltTy = LastEnumConst->getType(); 19818 19819 // Check for overflow on increment. 19820 if (EnumVal < LastEnumConst->getInitVal()) { 19821 // C++0x [dcl.enum]p5: 19822 // If the underlying type is not fixed, the type of each enumerator 19823 // is the type of its initializing value: 19824 // 19825 // - Otherwise the type of the initializing value is the same as 19826 // the type of the initializing value of the preceding enumerator 19827 // unless the incremented value is not representable in that type, 19828 // in which case the type is an unspecified integral type 19829 // sufficient to contain the incremented value. If no such type 19830 // exists, the program is ill-formed. 19831 QualType T = getNextLargerIntegralType(Context, EltTy); 19832 if (T.isNull() || Enum->isFixed()) { 19833 // There is no integral type larger enough to represent this 19834 // value. Complain, then allow the value to wrap around. 19835 EnumVal = LastEnumConst->getInitVal(); 19836 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 19837 ++EnumVal; 19838 if (Enum->isFixed()) 19839 // When the underlying type is fixed, this is ill-formed. 19840 Diag(IdLoc, diag::err_enumerator_wrapped) 19841 << toString(EnumVal, 10) 19842 << EltTy; 19843 else 19844 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 19845 << toString(EnumVal, 10); 19846 } else { 19847 EltTy = T; 19848 } 19849 19850 // Retrieve the last enumerator's value, extent that type to the 19851 // type that is supposed to be large enough to represent the incremented 19852 // value, then increment. 19853 EnumVal = LastEnumConst->getInitVal(); 19854 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 19855 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 19856 ++EnumVal; 19857 19858 // If we're not in C++, diagnose the overflow of enumerator values, 19859 // which in C99 means that the enumerator value is not representable in 19860 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 19861 // permits enumerator values that are representable in some larger 19862 // integral type. 19863 if (!getLangOpts().CPlusPlus && !T.isNull()) 19864 Diag(IdLoc, diag::warn_enum_value_overflow); 19865 } else if (!getLangOpts().CPlusPlus && 19866 !EltTy->isDependentType() && 19867 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 19868 // Enforce C99 6.7.2.2p2 even when we compute the next value. 19869 Diag(IdLoc, diag::ext_enum_value_not_int) 19870 << toString(EnumVal, 10) << 1; 19871 } 19872 } 19873 } 19874 19875 if (!EltTy->isDependentType()) { 19876 // Make the enumerator value match the signedness and size of the 19877 // enumerator's type. 19878 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 19879 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 19880 } 19881 19882 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 19883 Val, EnumVal); 19884 } 19885 19886 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 19887 SourceLocation IILoc) { 19888 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 19889 !getLangOpts().CPlusPlus) 19890 return SkipBodyInfo(); 19891 19892 // We have an anonymous enum definition. Look up the first enumerator to 19893 // determine if we should merge the definition with an existing one and 19894 // skip the body. 19895 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 19896 forRedeclarationInCurContext()); 19897 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 19898 if (!PrevECD) 19899 return SkipBodyInfo(); 19900 19901 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 19902 NamedDecl *Hidden; 19903 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 19904 SkipBodyInfo Skip; 19905 Skip.Previous = Hidden; 19906 return Skip; 19907 } 19908 19909 return SkipBodyInfo(); 19910 } 19911 19912 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 19913 SourceLocation IdLoc, IdentifierInfo *Id, 19914 const ParsedAttributesView &Attrs, 19915 SourceLocation EqualLoc, Expr *Val) { 19916 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 19917 EnumConstantDecl *LastEnumConst = 19918 cast_or_null<EnumConstantDecl>(lastEnumConst); 19919 19920 // The scope passed in may not be a decl scope. Zip up the scope tree until 19921 // we find one that is. 19922 S = getNonFieldDeclScope(S); 19923 19924 // Verify that there isn't already something declared with this name in this 19925 // scope. 19926 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 19927 LookupName(R, S); 19928 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 19929 19930 if (PrevDecl && PrevDecl->isTemplateParameter()) { 19931 // Maybe we will complain about the shadowed template parameter. 19932 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 19933 // Just pretend that we didn't see the previous declaration. 19934 PrevDecl = nullptr; 19935 } 19936 19937 // C++ [class.mem]p15: 19938 // If T is the name of a class, then each of the following shall have a name 19939 // different from T: 19940 // - every enumerator of every member of class T that is an unscoped 19941 // enumerated type 19942 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 19943 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 19944 DeclarationNameInfo(Id, IdLoc)); 19945 19946 EnumConstantDecl *New = 19947 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 19948 if (!New) 19949 return nullptr; 19950 19951 if (PrevDecl) { 19952 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 19953 // Check for other kinds of shadowing not already handled. 19954 CheckShadow(New, PrevDecl, R); 19955 } 19956 19957 // When in C++, we may get a TagDecl with the same name; in this case the 19958 // enum constant will 'hide' the tag. 19959 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 19960 "Received TagDecl when not in C++!"); 19961 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 19962 if (isa<EnumConstantDecl>(PrevDecl)) 19963 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 19964 else 19965 Diag(IdLoc, diag::err_redefinition) << Id; 19966 notePreviousDefinition(PrevDecl, IdLoc); 19967 return nullptr; 19968 } 19969 } 19970 19971 // Process attributes. 19972 ProcessDeclAttributeList(S, New, Attrs); 19973 AddPragmaAttributes(S, New); 19974 19975 // Register this decl in the current scope stack. 19976 New->setAccess(TheEnumDecl->getAccess()); 19977 PushOnScopeChains(New, S); 19978 19979 ActOnDocumentableDecl(New); 19980 19981 return New; 19982 } 19983 19984 // Returns true when the enum initial expression does not trigger the 19985 // duplicate enum warning. A few common cases are exempted as follows: 19986 // Element2 = Element1 19987 // Element2 = Element1 + 1 19988 // Element2 = Element1 - 1 19989 // Where Element2 and Element1 are from the same enum. 19990 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 19991 Expr *InitExpr = ECD->getInitExpr(); 19992 if (!InitExpr) 19993 return true; 19994 InitExpr = InitExpr->IgnoreImpCasts(); 19995 19996 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 19997 if (!BO->isAdditiveOp()) 19998 return true; 19999 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 20000 if (!IL) 20001 return true; 20002 if (IL->getValue() != 1) 20003 return true; 20004 20005 InitExpr = BO->getLHS(); 20006 } 20007 20008 // This checks if the elements are from the same enum. 20009 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 20010 if (!DRE) 20011 return true; 20012 20013 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 20014 if (!EnumConstant) 20015 return true; 20016 20017 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 20018 Enum) 20019 return true; 20020 20021 return false; 20022 } 20023 20024 // Emits a warning when an element is implicitly set a value that 20025 // a previous element has already been set to. 20026 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 20027 EnumDecl *Enum, QualType EnumType) { 20028 // Avoid anonymous enums 20029 if (!Enum->getIdentifier()) 20030 return; 20031 20032 // Only check for small enums. 20033 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 20034 return; 20035 20036 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 20037 return; 20038 20039 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 20040 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 20041 20042 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 20043 20044 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 20045 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 20046 20047 // Use int64_t as a key to avoid needing special handling for map keys. 20048 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 20049 llvm::APSInt Val = D->getInitVal(); 20050 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 20051 }; 20052 20053 DuplicatesVector DupVector; 20054 ValueToVectorMap EnumMap; 20055 20056 // Populate the EnumMap with all values represented by enum constants without 20057 // an initializer. 20058 for (auto *Element : Elements) { 20059 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 20060 20061 // Null EnumConstantDecl means a previous diagnostic has been emitted for 20062 // this constant. Skip this enum since it may be ill-formed. 20063 if (!ECD) { 20064 return; 20065 } 20066 20067 // Constants with initializers are handled in the next loop. 20068 if (ECD->getInitExpr()) 20069 continue; 20070 20071 // Duplicate values are handled in the next loop. 20072 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 20073 } 20074 20075 if (EnumMap.size() == 0) 20076 return; 20077 20078 // Create vectors for any values that has duplicates. 20079 for (auto *Element : Elements) { 20080 // The last loop returned if any constant was null. 20081 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 20082 if (!ValidDuplicateEnum(ECD, Enum)) 20083 continue; 20084 20085 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 20086 if (Iter == EnumMap.end()) 20087 continue; 20088 20089 DeclOrVector& Entry = Iter->second; 20090 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 20091 // Ensure constants are different. 20092 if (D == ECD) 20093 continue; 20094 20095 // Create new vector and push values onto it. 20096 auto Vec = std::make_unique<ECDVector>(); 20097 Vec->push_back(D); 20098 Vec->push_back(ECD); 20099 20100 // Update entry to point to the duplicates vector. 20101 Entry = Vec.get(); 20102 20103 // Store the vector somewhere we can consult later for quick emission of 20104 // diagnostics. 20105 DupVector.emplace_back(std::move(Vec)); 20106 continue; 20107 } 20108 20109 ECDVector *Vec = Entry.get<ECDVector*>(); 20110 // Make sure constants are not added more than once. 20111 if (*Vec->begin() == ECD) 20112 continue; 20113 20114 Vec->push_back(ECD); 20115 } 20116 20117 // Emit diagnostics. 20118 for (const auto &Vec : DupVector) { 20119 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 20120 20121 // Emit warning for one enum constant. 20122 auto *FirstECD = Vec->front(); 20123 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 20124 << FirstECD << toString(FirstECD->getInitVal(), 10) 20125 << FirstECD->getSourceRange(); 20126 20127 // Emit one note for each of the remaining enum constants with 20128 // the same value. 20129 for (auto *ECD : llvm::drop_begin(*Vec)) 20130 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 20131 << ECD << toString(ECD->getInitVal(), 10) 20132 << ECD->getSourceRange(); 20133 } 20134 } 20135 20136 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 20137 bool AllowMask) const { 20138 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 20139 assert(ED->isCompleteDefinition() && "expected enum definition"); 20140 20141 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 20142 llvm::APInt &FlagBits = R.first->second; 20143 20144 if (R.second) { 20145 for (auto *E : ED->enumerators()) { 20146 const auto &EVal = E->getInitVal(); 20147 // Only single-bit enumerators introduce new flag values. 20148 if (EVal.isPowerOf2()) 20149 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal; 20150 } 20151 } 20152 20153 // A value is in a flag enum if either its bits are a subset of the enum's 20154 // flag bits (the first condition) or we are allowing masks and the same is 20155 // true of its complement (the second condition). When masks are allowed, we 20156 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 20157 // 20158 // While it's true that any value could be used as a mask, the assumption is 20159 // that a mask will have all of the insignificant bits set. Anything else is 20160 // likely a logic error. 20161 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 20162 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 20163 } 20164 20165 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 20166 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 20167 const ParsedAttributesView &Attrs) { 20168 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 20169 QualType EnumType = Context.getTypeDeclType(Enum); 20170 20171 ProcessDeclAttributeList(S, Enum, Attrs); 20172 20173 if (Enum->isDependentType()) { 20174 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 20175 EnumConstantDecl *ECD = 20176 cast_or_null<EnumConstantDecl>(Elements[i]); 20177 if (!ECD) continue; 20178 20179 ECD->setType(EnumType); 20180 } 20181 20182 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 20183 return; 20184 } 20185 20186 // TODO: If the result value doesn't fit in an int, it must be a long or long 20187 // long value. ISO C does not support this, but GCC does as an extension, 20188 // emit a warning. 20189 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 20190 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 20191 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 20192 20193 // Verify that all the values are okay, compute the size of the values, and 20194 // reverse the list. 20195 unsigned NumNegativeBits = 0; 20196 unsigned NumPositiveBits = 0; 20197 20198 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 20199 EnumConstantDecl *ECD = 20200 cast_or_null<EnumConstantDecl>(Elements[i]); 20201 if (!ECD) continue; // Already issued a diagnostic. 20202 20203 const llvm::APSInt &InitVal = ECD->getInitVal(); 20204 20205 // Keep track of the size of positive and negative values. 20206 if (InitVal.isUnsigned() || InitVal.isNonNegative()) { 20207 // If the enumerator is zero that should still be counted as a positive 20208 // bit since we need a bit to store the value zero. 20209 unsigned ActiveBits = InitVal.getActiveBits(); 20210 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u}); 20211 } else { 20212 NumNegativeBits = 20213 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits()); 20214 } 20215 } 20216 20217 // If we have an empty set of enumerators we still need one bit. 20218 // From [dcl.enum]p8 20219 // If the enumerator-list is empty, the values of the enumeration are as if 20220 // the enumeration had a single enumerator with value 0 20221 if (!NumPositiveBits && !NumNegativeBits) 20222 NumPositiveBits = 1; 20223 20224 // Figure out the type that should be used for this enum. 20225 QualType BestType; 20226 unsigned BestWidth; 20227 20228 // C++0x N3000 [conv.prom]p3: 20229 // An rvalue of an unscoped enumeration type whose underlying 20230 // type is not fixed can be converted to an rvalue of the first 20231 // of the following types that can represent all the values of 20232 // the enumeration: int, unsigned int, long int, unsigned long 20233 // int, long long int, or unsigned long long int. 20234 // C99 6.4.4.3p2: 20235 // An identifier declared as an enumeration constant has type int. 20236 // The C99 rule is modified by a gcc extension 20237 QualType BestPromotionType; 20238 20239 bool Packed = Enum->hasAttr<PackedAttr>(); 20240 // -fshort-enums is the equivalent to specifying the packed attribute on all 20241 // enum definitions. 20242 if (LangOpts.ShortEnums) 20243 Packed = true; 20244 20245 // If the enum already has a type because it is fixed or dictated by the 20246 // target, promote that type instead of analyzing the enumerators. 20247 if (Enum->isComplete()) { 20248 BestType = Enum->getIntegerType(); 20249 if (Context.isPromotableIntegerType(BestType)) 20250 BestPromotionType = Context.getPromotedIntegerType(BestType); 20251 else 20252 BestPromotionType = BestType; 20253 20254 BestWidth = Context.getIntWidth(BestType); 20255 } 20256 else if (NumNegativeBits) { 20257 // If there is a negative value, figure out the smallest integer type (of 20258 // int/long/longlong) that fits. 20259 // If it's packed, check also if it fits a char or a short. 20260 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 20261 BestType = Context.SignedCharTy; 20262 BestWidth = CharWidth; 20263 } else if (Packed && NumNegativeBits <= ShortWidth && 20264 NumPositiveBits < ShortWidth) { 20265 BestType = Context.ShortTy; 20266 BestWidth = ShortWidth; 20267 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 20268 BestType = Context.IntTy; 20269 BestWidth = IntWidth; 20270 } else { 20271 BestWidth = Context.getTargetInfo().getLongWidth(); 20272 20273 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 20274 BestType = Context.LongTy; 20275 } else { 20276 BestWidth = Context.getTargetInfo().getLongLongWidth(); 20277 20278 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 20279 Diag(Enum->getLocation(), diag::ext_enum_too_large); 20280 BestType = Context.LongLongTy; 20281 } 20282 } 20283 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 20284 } else { 20285 // If there is no negative value, figure out the smallest type that fits 20286 // all of the enumerator values. 20287 // If it's packed, check also if it fits a char or a short. 20288 if (Packed && NumPositiveBits <= CharWidth) { 20289 BestType = Context.UnsignedCharTy; 20290 BestPromotionType = Context.IntTy; 20291 BestWidth = CharWidth; 20292 } else if (Packed && NumPositiveBits <= ShortWidth) { 20293 BestType = Context.UnsignedShortTy; 20294 BestPromotionType = Context.IntTy; 20295 BestWidth = ShortWidth; 20296 } else if (NumPositiveBits <= IntWidth) { 20297 BestType = Context.UnsignedIntTy; 20298 BestWidth = IntWidth; 20299 BestPromotionType 20300 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 20301 ? Context.UnsignedIntTy : Context.IntTy; 20302 } else if (NumPositiveBits <= 20303 (BestWidth = Context.getTargetInfo().getLongWidth())) { 20304 BestType = Context.UnsignedLongTy; 20305 BestPromotionType 20306 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 20307 ? Context.UnsignedLongTy : Context.LongTy; 20308 } else { 20309 BestWidth = Context.getTargetInfo().getLongLongWidth(); 20310 assert(NumPositiveBits <= BestWidth && 20311 "How could an initializer get larger than ULL?"); 20312 BestType = Context.UnsignedLongLongTy; 20313 BestPromotionType 20314 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 20315 ? Context.UnsignedLongLongTy : Context.LongLongTy; 20316 } 20317 } 20318 20319 // Loop over all of the enumerator constants, changing their types to match 20320 // the type of the enum if needed. 20321 for (auto *D : Elements) { 20322 auto *ECD = cast_or_null<EnumConstantDecl>(D); 20323 if (!ECD) continue; // Already issued a diagnostic. 20324 20325 // Standard C says the enumerators have int type, but we allow, as an 20326 // extension, the enumerators to be larger than int size. If each 20327 // enumerator value fits in an int, type it as an int, otherwise type it the 20328 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 20329 // that X has type 'int', not 'unsigned'. 20330 20331 // Determine whether the value fits into an int. 20332 llvm::APSInt InitVal = ECD->getInitVal(); 20333 20334 // If it fits into an integer type, force it. Otherwise force it to match 20335 // the enum decl type. 20336 QualType NewTy; 20337 unsigned NewWidth; 20338 bool NewSign; 20339 if (!getLangOpts().CPlusPlus && 20340 !Enum->isFixed() && 20341 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 20342 NewTy = Context.IntTy; 20343 NewWidth = IntWidth; 20344 NewSign = true; 20345 } else if (ECD->getType() == BestType) { 20346 // Already the right type! 20347 if (getLangOpts().CPlusPlus) 20348 // C++ [dcl.enum]p4: Following the closing brace of an 20349 // enum-specifier, each enumerator has the type of its 20350 // enumeration. 20351 ECD->setType(EnumType); 20352 continue; 20353 } else { 20354 NewTy = BestType; 20355 NewWidth = BestWidth; 20356 NewSign = BestType->isSignedIntegerOrEnumerationType(); 20357 } 20358 20359 // Adjust the APSInt value. 20360 InitVal = InitVal.extOrTrunc(NewWidth); 20361 InitVal.setIsSigned(NewSign); 20362 ECD->setInitVal(Context, InitVal); 20363 20364 // Adjust the Expr initializer and type. 20365 if (ECD->getInitExpr() && 20366 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 20367 ECD->setInitExpr(ImplicitCastExpr::Create( 20368 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 20369 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 20370 if (getLangOpts().CPlusPlus) 20371 // C++ [dcl.enum]p4: Following the closing brace of an 20372 // enum-specifier, each enumerator has the type of its 20373 // enumeration. 20374 ECD->setType(EnumType); 20375 else 20376 ECD->setType(NewTy); 20377 } 20378 20379 Enum->completeDefinition(BestType, BestPromotionType, 20380 NumPositiveBits, NumNegativeBits); 20381 20382 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 20383 20384 if (Enum->isClosedFlag()) { 20385 for (Decl *D : Elements) { 20386 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 20387 if (!ECD) continue; // Already issued a diagnostic. 20388 20389 llvm::APSInt InitVal = ECD->getInitVal(); 20390 if (InitVal != 0 && !InitVal.isPowerOf2() && 20391 !IsValueInFlagEnum(Enum, InitVal, true)) 20392 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 20393 << ECD << Enum; 20394 } 20395 } 20396 20397 // Now that the enum type is defined, ensure it's not been underaligned. 20398 if (Enum->hasAttrs()) 20399 CheckAlignasUnderalignment(Enum); 20400 } 20401 20402 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 20403 SourceLocation StartLoc, 20404 SourceLocation EndLoc) { 20405 StringLiteral *AsmString = cast<StringLiteral>(expr); 20406 20407 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 20408 AsmString, StartLoc, 20409 EndLoc); 20410 CurContext->addDecl(New); 20411 return New; 20412 } 20413 20414 Decl *Sema::ActOnTopLevelStmtDecl(Stmt *Statement) { 20415 auto *New = TopLevelStmtDecl::Create(Context, Statement); 20416 Context.getTranslationUnitDecl()->addDecl(New); 20417 return New; 20418 } 20419 20420 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 20421 IdentifierInfo* AliasName, 20422 SourceLocation PragmaLoc, 20423 SourceLocation NameLoc, 20424 SourceLocation AliasNameLoc) { 20425 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 20426 LookupOrdinaryName); 20427 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 20428 AttributeCommonInfo::Form::Pragma()); 20429 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 20430 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info); 20431 20432 // If a declaration that: 20433 // 1) declares a function or a variable 20434 // 2) has external linkage 20435 // already exists, add a label attribute to it. 20436 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 20437 if (isDeclExternC(PrevDecl)) 20438 PrevDecl->addAttr(Attr); 20439 else 20440 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 20441 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 20442 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers. 20443 } else 20444 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 20445 } 20446 20447 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 20448 SourceLocation PragmaLoc, 20449 SourceLocation NameLoc) { 20450 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 20451 20452 if (PrevDecl) { 20453 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 20454 } else { 20455 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc)); 20456 } 20457 } 20458 20459 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 20460 IdentifierInfo* AliasName, 20461 SourceLocation PragmaLoc, 20462 SourceLocation NameLoc, 20463 SourceLocation AliasNameLoc) { 20464 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 20465 LookupOrdinaryName); 20466 WeakInfo W = WeakInfo(Name, NameLoc); 20467 20468 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 20469 if (!PrevDecl->hasAttr<AliasAttr>()) 20470 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 20471 DeclApplyPragmaWeak(TUScope, ND, W); 20472 } else { 20473 (void)WeakUndeclaredIdentifiers[AliasName].insert(W); 20474 } 20475 } 20476 20477 ObjCContainerDecl *Sema::getObjCDeclContext() const { 20478 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 20479 } 20480 20481 Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD, 20482 bool Final) { 20483 assert(FD && "Expected non-null FunctionDecl"); 20484 20485 // SYCL functions can be template, so we check if they have appropriate 20486 // attribute prior to checking if it is a template. 20487 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 20488 return FunctionEmissionStatus::Emitted; 20489 20490 // Templates are emitted when they're instantiated. 20491 if (FD->isDependentContext()) 20492 return FunctionEmissionStatus::TemplateDiscarded; 20493 20494 // Check whether this function is an externally visible definition. 20495 auto IsEmittedForExternalSymbol = [this, FD]() { 20496 // We have to check the GVA linkage of the function's *definition* -- if we 20497 // only have a declaration, we don't know whether or not the function will 20498 // be emitted, because (say) the definition could include "inline". 20499 const FunctionDecl *Def = FD->getDefinition(); 20500 20501 return Def && !isDiscardableGVALinkage( 20502 getASTContext().GetGVALinkageForFunction(Def)); 20503 }; 20504 20505 if (LangOpts.OpenMPIsTargetDevice) { 20506 // In OpenMP device mode we will not emit host only functions, or functions 20507 // we don't need due to their linkage. 20508 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 20509 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 20510 // DevTy may be changed later by 20511 // #pragma omp declare target to(*) device_type(*). 20512 // Therefore DevTy having no value does not imply host. The emission status 20513 // will be checked again at the end of compilation unit with Final = true. 20514 if (DevTy) 20515 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 20516 return FunctionEmissionStatus::OMPDiscarded; 20517 // If we have an explicit value for the device type, or we are in a target 20518 // declare context, we need to emit all extern and used symbols. 20519 if (isInOpenMPDeclareTargetContext() || DevTy) 20520 if (IsEmittedForExternalSymbol()) 20521 return FunctionEmissionStatus::Emitted; 20522 // Device mode only emits what it must, if it wasn't tagged yet and needed, 20523 // we'll omit it. 20524 if (Final) 20525 return FunctionEmissionStatus::OMPDiscarded; 20526 } else if (LangOpts.OpenMP > 45) { 20527 // In OpenMP host compilation prior to 5.0 everything was an emitted host 20528 // function. In 5.0, no_host was introduced which might cause a function to 20529 // be ommitted. 20530 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 20531 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 20532 if (DevTy) 20533 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 20534 return FunctionEmissionStatus::OMPDiscarded; 20535 } 20536 20537 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 20538 return FunctionEmissionStatus::Emitted; 20539 20540 if (LangOpts.CUDA) { 20541 // When compiling for device, host functions are never emitted. Similarly, 20542 // when compiling for host, device and global functions are never emitted. 20543 // (Technically, we do emit a host-side stub for global functions, but this 20544 // doesn't count for our purposes here.) 20545 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 20546 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 20547 return FunctionEmissionStatus::CUDADiscarded; 20548 if (!LangOpts.CUDAIsDevice && 20549 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 20550 return FunctionEmissionStatus::CUDADiscarded; 20551 20552 if (IsEmittedForExternalSymbol()) 20553 return FunctionEmissionStatus::Emitted; 20554 } 20555 20556 // Otherwise, the function is known-emitted if it's in our set of 20557 // known-emitted functions. 20558 return FunctionEmissionStatus::Unknown; 20559 } 20560 20561 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 20562 // Host-side references to a __global__ function refer to the stub, so the 20563 // function itself is never emitted and therefore should not be marked. 20564 // If we have host fn calls kernel fn calls host+device, the HD function 20565 // does not get instantiated on the host. We model this by omitting at the 20566 // call to the kernel from the callgraph. This ensures that, when compiling 20567 // for host, only HD functions actually called from the host get marked as 20568 // known-emitted. 20569 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 20570 IdentifyCUDATarget(Callee) == CFT_Global; 20571 } 20572