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/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/StmtCXX.h" 26 #include "clang/Basic/Builtins.h" 27 #include "clang/Basic/PartialDiagnostic.h" 28 #include "clang/Basic/SourceManager.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 32 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 34 #include "clang/Sema/CXXFieldCollector.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Initialization.h" 38 #include "clang/Sema/Lookup.h" 39 #include "clang/Sema/ParsedTemplate.h" 40 #include "clang/Sema/Scope.h" 41 #include "clang/Sema/ScopeInfo.h" 42 #include "clang/Sema/SemaInternal.h" 43 #include "clang/Sema/Template.h" 44 #include "llvm/ADT/SmallString.h" 45 #include "llvm/ADT/Triple.h" 46 #include <algorithm> 47 #include <cstring> 48 #include <functional> 49 50 using namespace clang; 51 using namespace sema; 52 53 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 54 if (OwnedType) { 55 Decl *Group[2] = { OwnedType, Ptr }; 56 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 57 } 58 59 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 60 } 61 62 namespace { 63 64 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 65 public: 66 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 67 bool AllowTemplates = false, 68 bool AllowNonTemplates = true) 69 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 70 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 71 WantExpressionKeywords = false; 72 WantCXXNamedCasts = false; 73 WantRemainingKeywords = false; 74 } 75 76 bool ValidateCandidate(const TypoCorrection &candidate) override { 77 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 78 if (!AllowInvalidDecl && ND->isInvalidDecl()) 79 return false; 80 81 if (getAsTypeTemplateDecl(ND)) 82 return AllowTemplates; 83 84 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 85 if (!IsType) 86 return false; 87 88 if (AllowNonTemplates) 89 return true; 90 91 // An injected-class-name of a class template (specialization) is valid 92 // as a template or as a non-template. 93 if (AllowTemplates) { 94 auto *RD = dyn_cast<CXXRecordDecl>(ND); 95 if (!RD || !RD->isInjectedClassName()) 96 return false; 97 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 98 return RD->getDescribedClassTemplate() || 99 isa<ClassTemplateSpecializationDecl>(RD); 100 } 101 102 return false; 103 } 104 105 return !WantClassName && candidate.isKeyword(); 106 } 107 108 std::unique_ptr<CorrectionCandidateCallback> clone() override { 109 return std::make_unique<TypeNameValidatorCCC>(*this); 110 } 111 112 private: 113 bool AllowInvalidDecl; 114 bool WantClassName; 115 bool AllowTemplates; 116 bool AllowNonTemplates; 117 }; 118 119 } // end anonymous namespace 120 121 /// Determine whether the token kind starts a simple-type-specifier. 122 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 123 switch (Kind) { 124 // FIXME: Take into account the current language when deciding whether a 125 // token kind is a valid type specifier 126 case tok::kw_short: 127 case tok::kw_long: 128 case tok::kw___int64: 129 case tok::kw___int128: 130 case tok::kw_signed: 131 case tok::kw_unsigned: 132 case tok::kw_void: 133 case tok::kw_char: 134 case tok::kw_int: 135 case tok::kw_half: 136 case tok::kw_float: 137 case tok::kw_double: 138 case tok::kw__Float16: 139 case tok::kw___float128: 140 case tok::kw_wchar_t: 141 case tok::kw_bool: 142 case tok::kw___underlying_type: 143 case tok::kw___auto_type: 144 return true; 145 146 case tok::annot_typename: 147 case tok::kw_char16_t: 148 case tok::kw_char32_t: 149 case tok::kw_typeof: 150 case tok::annot_decltype: 151 case tok::kw_decltype: 152 return getLangOpts().CPlusPlus; 153 154 case tok::kw_char8_t: 155 return getLangOpts().Char8; 156 157 default: 158 break; 159 } 160 161 return false; 162 } 163 164 namespace { 165 enum class UnqualifiedTypeNameLookupResult { 166 NotFound, 167 FoundNonType, 168 FoundType 169 }; 170 } // end anonymous namespace 171 172 /// Tries to perform unqualified lookup of the type decls in bases for 173 /// dependent class. 174 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 175 /// type decl, \a FoundType if only type decls are found. 176 static UnqualifiedTypeNameLookupResult 177 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 178 SourceLocation NameLoc, 179 const CXXRecordDecl *RD) { 180 if (!RD->hasDefinition()) 181 return UnqualifiedTypeNameLookupResult::NotFound; 182 // Look for type decls in base classes. 183 UnqualifiedTypeNameLookupResult FoundTypeDecl = 184 UnqualifiedTypeNameLookupResult::NotFound; 185 for (const auto &Base : RD->bases()) { 186 const CXXRecordDecl *BaseRD = nullptr; 187 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 188 BaseRD = BaseTT->getAsCXXRecordDecl(); 189 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 190 // Look for type decls in dependent base classes that have known primary 191 // templates. 192 if (!TST || !TST->isDependentType()) 193 continue; 194 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 195 if (!TD) 196 continue; 197 if (auto *BasePrimaryTemplate = 198 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 199 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 200 BaseRD = BasePrimaryTemplate; 201 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 202 if (const ClassTemplatePartialSpecializationDecl *PS = 203 CTD->findPartialSpecialization(Base.getType())) 204 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 205 BaseRD = PS; 206 } 207 } 208 } 209 if (BaseRD) { 210 for (NamedDecl *ND : BaseRD->lookup(&II)) { 211 if (!isa<TypeDecl>(ND)) 212 return UnqualifiedTypeNameLookupResult::FoundNonType; 213 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 214 } 215 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 216 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 217 case UnqualifiedTypeNameLookupResult::FoundNonType: 218 return UnqualifiedTypeNameLookupResult::FoundNonType; 219 case UnqualifiedTypeNameLookupResult::FoundType: 220 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 221 break; 222 case UnqualifiedTypeNameLookupResult::NotFound: 223 break; 224 } 225 } 226 } 227 } 228 229 return FoundTypeDecl; 230 } 231 232 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 233 const IdentifierInfo &II, 234 SourceLocation NameLoc) { 235 // Lookup in the parent class template context, if any. 236 const CXXRecordDecl *RD = nullptr; 237 UnqualifiedTypeNameLookupResult FoundTypeDecl = 238 UnqualifiedTypeNameLookupResult::NotFound; 239 for (DeclContext *DC = S.CurContext; 240 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 241 DC = DC->getParent()) { 242 // Look for type decls in dependent base classes that have known primary 243 // templates. 244 RD = dyn_cast<CXXRecordDecl>(DC); 245 if (RD && RD->getDescribedClassTemplate()) 246 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 247 } 248 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 249 return nullptr; 250 251 // We found some types in dependent base classes. Recover as if the user 252 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 253 // lookup during template instantiation. 254 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 255 256 ASTContext &Context = S.Context; 257 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 258 cast<Type>(Context.getRecordType(RD))); 259 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 260 261 CXXScopeSpec SS; 262 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 263 264 TypeLocBuilder Builder; 265 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 266 DepTL.setNameLoc(NameLoc); 267 DepTL.setElaboratedKeywordLoc(SourceLocation()); 268 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 269 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 270 } 271 272 /// If the identifier refers to a type name within this scope, 273 /// return the declaration of that type. 274 /// 275 /// This routine performs ordinary name lookup of the identifier II 276 /// within the given scope, with optional C++ scope specifier SS, to 277 /// determine whether the name refers to a type. If so, returns an 278 /// opaque pointer (actually a QualType) corresponding to that 279 /// type. Otherwise, returns NULL. 280 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 281 Scope *S, CXXScopeSpec *SS, 282 bool isClassName, bool HasTrailingDot, 283 ParsedType ObjectTypePtr, 284 bool IsCtorOrDtorName, 285 bool WantNontrivialTypeSourceInfo, 286 bool IsClassTemplateDeductionContext, 287 IdentifierInfo **CorrectedII) { 288 // FIXME: Consider allowing this outside C++1z mode as an extension. 289 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 290 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 291 !isClassName && !HasTrailingDot; 292 293 // Determine where we will perform name lookup. 294 DeclContext *LookupCtx = nullptr; 295 if (ObjectTypePtr) { 296 QualType ObjectType = ObjectTypePtr.get(); 297 if (ObjectType->isRecordType()) 298 LookupCtx = computeDeclContext(ObjectType); 299 } else if (SS && SS->isNotEmpty()) { 300 LookupCtx = computeDeclContext(*SS, false); 301 302 if (!LookupCtx) { 303 if (isDependentScopeSpecifier(*SS)) { 304 // C++ [temp.res]p3: 305 // A qualified-id that refers to a type and in which the 306 // nested-name-specifier depends on a template-parameter (14.6.2) 307 // shall be prefixed by the keyword typename to indicate that the 308 // qualified-id denotes a type, forming an 309 // elaborated-type-specifier (7.1.5.3). 310 // 311 // We therefore do not perform any name lookup if the result would 312 // refer to a member of an unknown specialization. 313 if (!isClassName && !IsCtorOrDtorName) 314 return nullptr; 315 316 // We know from the grammar that this name refers to a type, 317 // so build a dependent node to describe the type. 318 if (WantNontrivialTypeSourceInfo) 319 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 320 321 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 322 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 323 II, NameLoc); 324 return ParsedType::make(T); 325 } 326 327 return nullptr; 328 } 329 330 if (!LookupCtx->isDependentContext() && 331 RequireCompleteDeclContext(*SS, LookupCtx)) 332 return nullptr; 333 } 334 335 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 336 // lookup for class-names. 337 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 338 LookupOrdinaryName; 339 LookupResult Result(*this, &II, NameLoc, Kind); 340 if (LookupCtx) { 341 // Perform "qualified" name lookup into the declaration context we 342 // computed, which is either the type of the base of a member access 343 // expression or the declaration context associated with a prior 344 // nested-name-specifier. 345 LookupQualifiedName(Result, LookupCtx); 346 347 if (ObjectTypePtr && Result.empty()) { 348 // C++ [basic.lookup.classref]p3: 349 // If the unqualified-id is ~type-name, the type-name is looked up 350 // in the context of the entire postfix-expression. If the type T of 351 // the object expression is of a class type C, the type-name is also 352 // looked up in the scope of class C. At least one of the lookups shall 353 // find a name that refers to (possibly cv-qualified) T. 354 LookupName(Result, S); 355 } 356 } else { 357 // Perform unqualified name lookup. 358 LookupName(Result, S); 359 360 // For unqualified lookup in a class template in MSVC mode, look into 361 // dependent base classes where the primary class template is known. 362 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 363 if (ParsedType TypeInBase = 364 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 365 return TypeInBase; 366 } 367 } 368 369 NamedDecl *IIDecl = nullptr; 370 switch (Result.getResultKind()) { 371 case LookupResult::NotFound: 372 case LookupResult::NotFoundInCurrentInstantiation: 373 if (CorrectedII) { 374 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 375 AllowDeducedTemplate); 376 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 377 S, SS, CCC, CTK_ErrorRecovery); 378 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 379 TemplateTy Template; 380 bool MemberOfUnknownSpecialization; 381 UnqualifiedId TemplateName; 382 TemplateName.setIdentifier(NewII, NameLoc); 383 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 384 CXXScopeSpec NewSS, *NewSSPtr = SS; 385 if (SS && NNS) { 386 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 387 NewSSPtr = &NewSS; 388 } 389 if (Correction && (NNS || NewII != &II) && 390 // Ignore a correction to a template type as the to-be-corrected 391 // identifier is not a template (typo correction for template names 392 // is handled elsewhere). 393 !(getLangOpts().CPlusPlus && NewSSPtr && 394 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 395 Template, MemberOfUnknownSpecialization))) { 396 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 397 isClassName, HasTrailingDot, ObjectTypePtr, 398 IsCtorOrDtorName, 399 WantNontrivialTypeSourceInfo, 400 IsClassTemplateDeductionContext); 401 if (Ty) { 402 diagnoseTypo(Correction, 403 PDiag(diag::err_unknown_type_or_class_name_suggest) 404 << Result.getLookupName() << isClassName); 405 if (SS && NNS) 406 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 407 *CorrectedII = NewII; 408 return Ty; 409 } 410 } 411 } 412 // If typo correction failed or was not performed, fall through 413 LLVM_FALLTHROUGH; 414 case LookupResult::FoundOverloaded: 415 case LookupResult::FoundUnresolvedValue: 416 Result.suppressDiagnostics(); 417 return nullptr; 418 419 case LookupResult::Ambiguous: 420 // Recover from type-hiding ambiguities by hiding the type. We'll 421 // do the lookup again when looking for an object, and we can 422 // diagnose the error then. If we don't do this, then the error 423 // about hiding the type will be immediately followed by an error 424 // that only makes sense if the identifier was treated like a type. 425 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 426 Result.suppressDiagnostics(); 427 return nullptr; 428 } 429 430 // Look to see if we have a type anywhere in the list of results. 431 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 432 Res != ResEnd; ++Res) { 433 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 434 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 435 if (!IIDecl || 436 (*Res)->getLocation().getRawEncoding() < 437 IIDecl->getLocation().getRawEncoding()) 438 IIDecl = *Res; 439 } 440 } 441 442 if (!IIDecl) { 443 // None of the entities we found is a type, so there is no way 444 // to even assume that the result is a type. In this case, don't 445 // complain about the ambiguity. The parser will either try to 446 // perform this lookup again (e.g., as an object name), which 447 // will produce the ambiguity, or will complain that it expected 448 // a type name. 449 Result.suppressDiagnostics(); 450 return nullptr; 451 } 452 453 // We found a type within the ambiguous lookup; diagnose the 454 // ambiguity and then return that type. This might be the right 455 // answer, or it might not be, but it suppresses any attempt to 456 // perform the name lookup again. 457 break; 458 459 case LookupResult::Found: 460 IIDecl = Result.getFoundDecl(); 461 break; 462 } 463 464 assert(IIDecl && "Didn't find decl"); 465 466 QualType T; 467 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 468 // C++ [class.qual]p2: A lookup that would find the injected-class-name 469 // instead names the constructors of the class, except when naming a class. 470 // This is ill-formed when we're not actually forming a ctor or dtor name. 471 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 472 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 473 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 474 FoundRD->isInjectedClassName() && 475 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 476 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 477 << &II << /*Type*/1; 478 479 DiagnoseUseOfDecl(IIDecl, NameLoc); 480 481 T = Context.getTypeDeclType(TD); 482 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 483 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 484 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 485 if (!HasTrailingDot) 486 T = Context.getObjCInterfaceType(IDecl); 487 } else if (AllowDeducedTemplate) { 488 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 489 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 490 QualType(), false); 491 } 492 493 if (T.isNull()) { 494 // If it's not plausibly a type, suppress diagnostics. 495 Result.suppressDiagnostics(); 496 return nullptr; 497 } 498 499 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 500 // constructor or destructor name (in such a case, the scope specifier 501 // will be attached to the enclosing Expr or Decl node). 502 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 503 !isa<ObjCInterfaceDecl>(IIDecl)) { 504 if (WantNontrivialTypeSourceInfo) { 505 // Construct a type with type-source information. 506 TypeLocBuilder Builder; 507 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 508 509 T = getElaboratedType(ETK_None, *SS, T); 510 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 511 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 512 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 513 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 514 } else { 515 T = getElaboratedType(ETK_None, *SS, T); 516 } 517 } 518 519 return ParsedType::make(T); 520 } 521 522 // Builds a fake NNS for the given decl context. 523 static NestedNameSpecifier * 524 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 525 for (;; DC = DC->getLookupParent()) { 526 DC = DC->getPrimaryContext(); 527 auto *ND = dyn_cast<NamespaceDecl>(DC); 528 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 529 return NestedNameSpecifier::Create(Context, nullptr, ND); 530 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 531 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 532 RD->getTypeForDecl()); 533 else if (isa<TranslationUnitDecl>(DC)) 534 return NestedNameSpecifier::GlobalSpecifier(Context); 535 } 536 llvm_unreachable("something isn't in TU scope?"); 537 } 538 539 /// Find the parent class with dependent bases of the innermost enclosing method 540 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 541 /// up allowing unqualified dependent type names at class-level, which MSVC 542 /// correctly rejects. 543 static const CXXRecordDecl * 544 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 545 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 546 DC = DC->getPrimaryContext(); 547 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 548 if (MD->getParent()->hasAnyDependentBases()) 549 return MD->getParent(); 550 } 551 return nullptr; 552 } 553 554 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 555 SourceLocation NameLoc, 556 bool IsTemplateTypeArg) { 557 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 558 559 NestedNameSpecifier *NNS = nullptr; 560 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 561 // If we weren't able to parse a default template argument, delay lookup 562 // until instantiation time by making a non-dependent DependentTypeName. We 563 // pretend we saw a NestedNameSpecifier referring to the current scope, and 564 // lookup is retried. 565 // FIXME: This hurts our diagnostic quality, since we get errors like "no 566 // type named 'Foo' in 'current_namespace'" when the user didn't write any 567 // name specifiers. 568 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 569 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 570 } else if (const CXXRecordDecl *RD = 571 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 572 // Build a DependentNameType that will perform lookup into RD at 573 // instantiation time. 574 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 575 RD->getTypeForDecl()); 576 577 // Diagnose that this identifier was undeclared, and retry the lookup during 578 // template instantiation. 579 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 580 << RD; 581 } else { 582 // This is not a situation that we should recover from. 583 return ParsedType(); 584 } 585 586 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 587 588 // Build type location information. We synthesized the qualifier, so we have 589 // to build a fake NestedNameSpecifierLoc. 590 NestedNameSpecifierLocBuilder NNSLocBuilder; 591 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 592 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 593 594 TypeLocBuilder Builder; 595 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 596 DepTL.setNameLoc(NameLoc); 597 DepTL.setElaboratedKeywordLoc(SourceLocation()); 598 DepTL.setQualifierLoc(QualifierLoc); 599 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 600 } 601 602 /// isTagName() - This method is called *for error recovery purposes only* 603 /// to determine if the specified name is a valid tag name ("struct foo"). If 604 /// so, this returns the TST for the tag corresponding to it (TST_enum, 605 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 606 /// cases in C where the user forgot to specify the tag. 607 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 608 // Do a tag name lookup in this scope. 609 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 610 LookupName(R, S, false); 611 R.suppressDiagnostics(); 612 if (R.getResultKind() == LookupResult::Found) 613 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 614 switch (TD->getTagKind()) { 615 case TTK_Struct: return DeclSpec::TST_struct; 616 case TTK_Interface: return DeclSpec::TST_interface; 617 case TTK_Union: return DeclSpec::TST_union; 618 case TTK_Class: return DeclSpec::TST_class; 619 case TTK_Enum: return DeclSpec::TST_enum; 620 } 621 } 622 623 return DeclSpec::TST_unspecified; 624 } 625 626 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 627 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 628 /// then downgrade the missing typename error to a warning. 629 /// This is needed for MSVC compatibility; Example: 630 /// @code 631 /// template<class T> class A { 632 /// public: 633 /// typedef int TYPE; 634 /// }; 635 /// template<class T> class B : public A<T> { 636 /// public: 637 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 638 /// }; 639 /// @endcode 640 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 641 if (CurContext->isRecord()) { 642 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 643 return true; 644 645 const Type *Ty = SS->getScopeRep()->getAsType(); 646 647 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 648 for (const auto &Base : RD->bases()) 649 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 650 return true; 651 return S->isFunctionPrototypeScope(); 652 } 653 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 654 } 655 656 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 657 SourceLocation IILoc, 658 Scope *S, 659 CXXScopeSpec *SS, 660 ParsedType &SuggestedType, 661 bool IsTemplateName) { 662 // Don't report typename errors for editor placeholders. 663 if (II->isEditorPlaceholder()) 664 return; 665 // We don't have anything to suggest (yet). 666 SuggestedType = nullptr; 667 668 // There may have been a typo in the name of the type. Look up typo 669 // results, in case we have something that we can suggest. 670 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 671 /*AllowTemplates=*/IsTemplateName, 672 /*AllowNonTemplates=*/!IsTemplateName); 673 if (TypoCorrection Corrected = 674 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 675 CCC, CTK_ErrorRecovery)) { 676 // FIXME: Support error recovery for the template-name case. 677 bool CanRecover = !IsTemplateName; 678 if (Corrected.isKeyword()) { 679 // We corrected to a keyword. 680 diagnoseTypo(Corrected, 681 PDiag(IsTemplateName ? diag::err_no_template_suggest 682 : diag::err_unknown_typename_suggest) 683 << II); 684 II = Corrected.getCorrectionAsIdentifierInfo(); 685 } else { 686 // We found a similarly-named type or interface; suggest that. 687 if (!SS || !SS->isSet()) { 688 diagnoseTypo(Corrected, 689 PDiag(IsTemplateName ? diag::err_no_template_suggest 690 : diag::err_unknown_typename_suggest) 691 << II, CanRecover); 692 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 693 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 694 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 695 II->getName().equals(CorrectedStr); 696 diagnoseTypo(Corrected, 697 PDiag(IsTemplateName 698 ? diag::err_no_member_template_suggest 699 : diag::err_unknown_nested_typename_suggest) 700 << II << DC << DroppedSpecifier << SS->getRange(), 701 CanRecover); 702 } else { 703 llvm_unreachable("could not have corrected a typo here"); 704 } 705 706 if (!CanRecover) 707 return; 708 709 CXXScopeSpec tmpSS; 710 if (Corrected.getCorrectionSpecifier()) 711 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 712 SourceRange(IILoc)); 713 // FIXME: Support class template argument deduction here. 714 SuggestedType = 715 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 716 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 717 /*IsCtorOrDtorName=*/false, 718 /*WantNontrivialTypeSourceInfo=*/true); 719 } 720 return; 721 } 722 723 if (getLangOpts().CPlusPlus && !IsTemplateName) { 724 // See if II is a class template that the user forgot to pass arguments to. 725 UnqualifiedId Name; 726 Name.setIdentifier(II, IILoc); 727 CXXScopeSpec EmptySS; 728 TemplateTy TemplateResult; 729 bool MemberOfUnknownSpecialization; 730 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 731 Name, nullptr, true, TemplateResult, 732 MemberOfUnknownSpecialization) == TNK_Type_template) { 733 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 734 return; 735 } 736 } 737 738 // FIXME: Should we move the logic that tries to recover from a missing tag 739 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 740 741 if (!SS || (!SS->isSet() && !SS->isInvalid())) 742 Diag(IILoc, IsTemplateName ? diag::err_no_template 743 : diag::err_unknown_typename) 744 << II; 745 else if (DeclContext *DC = computeDeclContext(*SS, false)) 746 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 747 : diag::err_typename_nested_not_found) 748 << II << DC << SS->getRange(); 749 else if (isDependentScopeSpecifier(*SS)) { 750 unsigned DiagID = diag::err_typename_missing; 751 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 752 DiagID = diag::ext_typename_missing; 753 754 Diag(SS->getRange().getBegin(), DiagID) 755 << SS->getScopeRep() << II->getName() 756 << SourceRange(SS->getRange().getBegin(), IILoc) 757 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 758 SuggestedType = ActOnTypenameType(S, SourceLocation(), 759 *SS, *II, IILoc).get(); 760 } else { 761 assert(SS && SS->isInvalid() && 762 "Invalid scope specifier has already been diagnosed"); 763 } 764 } 765 766 /// Determine whether the given result set contains either a type name 767 /// or 768 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 769 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 770 NextToken.is(tok::less); 771 772 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 773 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 774 return true; 775 776 if (CheckTemplate && isa<TemplateDecl>(*I)) 777 return true; 778 } 779 780 return false; 781 } 782 783 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 784 Scope *S, CXXScopeSpec &SS, 785 IdentifierInfo *&Name, 786 SourceLocation NameLoc) { 787 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 788 SemaRef.LookupParsedName(R, S, &SS); 789 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 790 StringRef FixItTagName; 791 switch (Tag->getTagKind()) { 792 case TTK_Class: 793 FixItTagName = "class "; 794 break; 795 796 case TTK_Enum: 797 FixItTagName = "enum "; 798 break; 799 800 case TTK_Struct: 801 FixItTagName = "struct "; 802 break; 803 804 case TTK_Interface: 805 FixItTagName = "__interface "; 806 break; 807 808 case TTK_Union: 809 FixItTagName = "union "; 810 break; 811 } 812 813 StringRef TagName = FixItTagName.drop_back(); 814 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 815 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 816 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 817 818 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 819 I != IEnd; ++I) 820 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 821 << Name << TagName; 822 823 // Replace lookup results with just the tag decl. 824 Result.clear(Sema::LookupTagName); 825 SemaRef.LookupParsedName(Result, S, &SS); 826 return true; 827 } 828 829 return false; 830 } 831 832 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 833 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 834 QualType T, SourceLocation NameLoc) { 835 ASTContext &Context = S.Context; 836 837 TypeLocBuilder Builder; 838 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 839 840 T = S.getElaboratedType(ETK_None, SS, T); 841 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 842 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 843 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 844 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 845 } 846 847 Sema::NameClassification 848 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 849 SourceLocation NameLoc, const Token &NextToken, 850 bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) { 851 DeclarationNameInfo NameInfo(Name, NameLoc); 852 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 853 854 if (NextToken.is(tok::coloncolon)) { 855 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 856 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 857 } else if (getLangOpts().CPlusPlus && SS.isSet() && 858 isCurrentClassName(*Name, S, &SS)) { 859 // Per [class.qual]p2, this names the constructors of SS, not the 860 // injected-class-name. We don't have a classification for that. 861 // There's not much point caching this result, since the parser 862 // will reject it later. 863 return NameClassification::Unknown(); 864 } 865 866 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 867 LookupParsedName(Result, S, &SS, !CurMethod); 868 869 // For unqualified lookup in a class template in MSVC mode, look into 870 // dependent base classes where the primary class template is known. 871 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 872 if (ParsedType TypeInBase = 873 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 874 return TypeInBase; 875 } 876 877 // Perform lookup for Objective-C instance variables (including automatically 878 // synthesized instance variables), if we're in an Objective-C method. 879 // FIXME: This lookup really, really needs to be folded in to the normal 880 // unqualified lookup mechanism. 881 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 882 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 883 if (E.get() || E.isInvalid()) 884 return E; 885 } 886 887 bool SecondTry = false; 888 bool IsFilteredTemplateName = false; 889 890 Corrected: 891 switch (Result.getResultKind()) { 892 case LookupResult::NotFound: 893 // If an unqualified-id is followed by a '(', then we have a function 894 // call. 895 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 896 // In C++, this is an ADL-only call. 897 // FIXME: Reference? 898 if (getLangOpts().CPlusPlus) 899 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 900 901 // C90 6.3.2.2: 902 // If the expression that precedes the parenthesized argument list in a 903 // function call consists solely of an identifier, and if no 904 // declaration is visible for this identifier, the identifier is 905 // implicitly declared exactly as if, in the innermost block containing 906 // the function call, the declaration 907 // 908 // extern int identifier (); 909 // 910 // appeared. 911 // 912 // We also allow this in C99 as an extension. 913 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 914 Result.addDecl(D); 915 Result.resolveKind(); 916 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 917 } 918 } 919 920 if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) { 921 // In C++20 onwards, this could be an ADL-only call to a function 922 // template, and we're required to assume that this is a template name. 923 // 924 // FIXME: Find a way to still do typo correction in this case. 925 TemplateName Template = 926 Context.getAssumedTemplateName(NameInfo.getName()); 927 return NameClassification::UndeclaredTemplate(Template); 928 } 929 930 // In C, we first see whether there is a tag type by the same name, in 931 // which case it's likely that the user just forgot to write "enum", 932 // "struct", or "union". 933 if (!getLangOpts().CPlusPlus && !SecondTry && 934 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 935 break; 936 } 937 938 // Perform typo correction to determine if there is another name that is 939 // close to this name. 940 if (!SecondTry && CCC) { 941 SecondTry = true; 942 if (TypoCorrection Corrected = 943 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 944 &SS, *CCC, CTK_ErrorRecovery)) { 945 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 946 unsigned QualifiedDiag = diag::err_no_member_suggest; 947 948 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 949 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 950 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 951 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 952 UnqualifiedDiag = diag::err_no_template_suggest; 953 QualifiedDiag = diag::err_no_member_template_suggest; 954 } else if (UnderlyingFirstDecl && 955 (isa<TypeDecl>(UnderlyingFirstDecl) || 956 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 957 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 958 UnqualifiedDiag = diag::err_unknown_typename_suggest; 959 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 960 } 961 962 if (SS.isEmpty()) { 963 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 964 } else {// FIXME: is this even reachable? Test it. 965 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 966 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 967 Name->getName().equals(CorrectedStr); 968 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 969 << Name << computeDeclContext(SS, false) 970 << DroppedSpecifier << SS.getRange()); 971 } 972 973 // Update the name, so that the caller has the new name. 974 Name = Corrected.getCorrectionAsIdentifierInfo(); 975 976 // Typo correction corrected to a keyword. 977 if (Corrected.isKeyword()) 978 return Name; 979 980 // Also update the LookupResult... 981 // FIXME: This should probably go away at some point 982 Result.clear(); 983 Result.setLookupName(Corrected.getCorrection()); 984 if (FirstDecl) 985 Result.addDecl(FirstDecl); 986 987 // If we found an Objective-C instance variable, let 988 // LookupInObjCMethod build the appropriate expression to 989 // reference the ivar. 990 // FIXME: This is a gross hack. 991 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 992 Result.clear(); 993 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 994 return E; 995 } 996 997 goto Corrected; 998 } 999 } 1000 1001 // We failed to correct; just fall through and let the parser deal with it. 1002 Result.suppressDiagnostics(); 1003 return NameClassification::Unknown(); 1004 1005 case LookupResult::NotFoundInCurrentInstantiation: { 1006 // We performed name lookup into the current instantiation, and there were 1007 // dependent bases, so we treat this result the same way as any other 1008 // dependent nested-name-specifier. 1009 1010 // C++ [temp.res]p2: 1011 // A name used in a template declaration or definition and that is 1012 // dependent on a template-parameter is assumed not to name a type 1013 // unless the applicable name lookup finds a type name or the name is 1014 // qualified by the keyword typename. 1015 // 1016 // FIXME: If the next token is '<', we might want to ask the parser to 1017 // perform some heroics to see if we actually have a 1018 // template-argument-list, which would indicate a missing 'template' 1019 // keyword here. 1020 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1021 NameInfo, IsAddressOfOperand, 1022 /*TemplateArgs=*/nullptr); 1023 } 1024 1025 case LookupResult::Found: 1026 case LookupResult::FoundOverloaded: 1027 case LookupResult::FoundUnresolvedValue: 1028 break; 1029 1030 case LookupResult::Ambiguous: 1031 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1032 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1033 /*AllowDependent=*/false)) { 1034 // C++ [temp.local]p3: 1035 // A lookup that finds an injected-class-name (10.2) can result in an 1036 // ambiguity in certain cases (for example, if it is found in more than 1037 // one base class). If all of the injected-class-names that are found 1038 // refer to specializations of the same class template, and if the name 1039 // is followed by a template-argument-list, the reference refers to the 1040 // class template itself and not a specialization thereof, and is not 1041 // ambiguous. 1042 // 1043 // This filtering can make an ambiguous result into an unambiguous one, 1044 // so try again after filtering out template names. 1045 FilterAcceptableTemplateNames(Result); 1046 if (!Result.isAmbiguous()) { 1047 IsFilteredTemplateName = true; 1048 break; 1049 } 1050 } 1051 1052 // Diagnose the ambiguity and return an error. 1053 return NameClassification::Error(); 1054 } 1055 1056 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1057 (IsFilteredTemplateName || 1058 hasAnyAcceptableTemplateNames( 1059 Result, /*AllowFunctionTemplates=*/true, 1060 /*AllowDependent=*/false, 1061 /*AllowNonTemplateFunctions*/ !SS.isSet() && 1062 getLangOpts().CPlusPlus2a))) { 1063 // C++ [temp.names]p3: 1064 // After name lookup (3.4) finds that a name is a template-name or that 1065 // an operator-function-id or a literal- operator-id refers to a set of 1066 // overloaded functions any member of which is a function template if 1067 // this is followed by a <, the < is always taken as the delimiter of a 1068 // template-argument-list and never as the less-than operator. 1069 // C++2a [temp.names]p2: 1070 // A name is also considered to refer to a template if it is an 1071 // unqualified-id followed by a < and name lookup finds either one 1072 // or more functions or finds nothing. 1073 if (!IsFilteredTemplateName) 1074 FilterAcceptableTemplateNames(Result); 1075 1076 bool IsFunctionTemplate; 1077 bool IsVarTemplate; 1078 TemplateName Template; 1079 if (Result.end() - Result.begin() > 1) { 1080 IsFunctionTemplate = true; 1081 Template = Context.getOverloadedTemplateName(Result.begin(), 1082 Result.end()); 1083 } else if (!Result.empty()) { 1084 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1085 *Result.begin(), /*AllowFunctionTemplates=*/true, 1086 /*AllowDependent=*/false)); 1087 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1088 IsVarTemplate = isa<VarTemplateDecl>(TD); 1089 1090 if (SS.isSet() && !SS.isInvalid()) 1091 Template = 1092 Context.getQualifiedTemplateName(SS.getScopeRep(), 1093 /*TemplateKeyword=*/false, TD); 1094 else 1095 Template = TemplateName(TD); 1096 } else { 1097 // All results were non-template functions. This is a function template 1098 // name. 1099 IsFunctionTemplate = true; 1100 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1101 } 1102 1103 if (IsFunctionTemplate) { 1104 // Function templates always go through overload resolution, at which 1105 // point we'll perform the various checks (e.g., accessibility) we need 1106 // to based on which function we selected. 1107 Result.suppressDiagnostics(); 1108 1109 return NameClassification::FunctionTemplate(Template); 1110 } 1111 1112 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1113 : NameClassification::TypeTemplate(Template); 1114 } 1115 1116 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1117 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1118 DiagnoseUseOfDecl(Type, NameLoc); 1119 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1120 QualType T = Context.getTypeDeclType(Type); 1121 if (SS.isNotEmpty()) 1122 return buildNestedType(*this, SS, T, NameLoc); 1123 return ParsedType::make(T); 1124 } 1125 1126 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1127 if (!Class) { 1128 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1129 if (ObjCCompatibleAliasDecl *Alias = 1130 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1131 Class = Alias->getClassInterface(); 1132 } 1133 1134 if (Class) { 1135 DiagnoseUseOfDecl(Class, NameLoc); 1136 1137 if (NextToken.is(tok::period)) { 1138 // Interface. <something> is parsed as a property reference expression. 1139 // Just return "unknown" as a fall-through for now. 1140 Result.suppressDiagnostics(); 1141 return NameClassification::Unknown(); 1142 } 1143 1144 QualType T = Context.getObjCInterfaceType(Class); 1145 return ParsedType::make(T); 1146 } 1147 1148 // We can have a type template here if we're classifying a template argument. 1149 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1150 !isa<VarTemplateDecl>(FirstDecl)) 1151 return NameClassification::TypeTemplate( 1152 TemplateName(cast<TemplateDecl>(FirstDecl))); 1153 1154 // Check for a tag type hidden by a non-type decl in a few cases where it 1155 // seems likely a type is wanted instead of the non-type that was found. 1156 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1157 if ((NextToken.is(tok::identifier) || 1158 (NextIsOp && 1159 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1160 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1161 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1162 DiagnoseUseOfDecl(Type, NameLoc); 1163 QualType T = Context.getTypeDeclType(Type); 1164 if (SS.isNotEmpty()) 1165 return buildNestedType(*this, SS, T, NameLoc); 1166 return ParsedType::make(T); 1167 } 1168 1169 if (FirstDecl->isCXXClassMember()) 1170 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1171 nullptr, S); 1172 1173 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1174 return BuildDeclarationNameExpr(SS, Result, ADL); 1175 } 1176 1177 Sema::TemplateNameKindForDiagnostics 1178 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1179 auto *TD = Name.getAsTemplateDecl(); 1180 if (!TD) 1181 return TemplateNameKindForDiagnostics::DependentTemplate; 1182 if (isa<ClassTemplateDecl>(TD)) 1183 return TemplateNameKindForDiagnostics::ClassTemplate; 1184 if (isa<FunctionTemplateDecl>(TD)) 1185 return TemplateNameKindForDiagnostics::FunctionTemplate; 1186 if (isa<VarTemplateDecl>(TD)) 1187 return TemplateNameKindForDiagnostics::VarTemplate; 1188 if (isa<TypeAliasTemplateDecl>(TD)) 1189 return TemplateNameKindForDiagnostics::AliasTemplate; 1190 if (isa<TemplateTemplateParmDecl>(TD)) 1191 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1192 if (isa<ConceptDecl>(TD)) 1193 return TemplateNameKindForDiagnostics::Concept; 1194 return TemplateNameKindForDiagnostics::DependentTemplate; 1195 } 1196 1197 // Determines the context to return to after temporarily entering a 1198 // context. This depends in an unnecessarily complicated way on the 1199 // exact ordering of callbacks from the parser. 1200 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1201 1202 // Functions defined inline within classes aren't parsed until we've 1203 // finished parsing the top-level class, so the top-level class is 1204 // the context we'll need to return to. 1205 // A Lambda call operator whose parent is a class must not be treated 1206 // as an inline member function. A Lambda can be used legally 1207 // either as an in-class member initializer or a default argument. These 1208 // are parsed once the class has been marked complete and so the containing 1209 // context would be the nested class (when the lambda is defined in one); 1210 // If the class is not complete, then the lambda is being used in an 1211 // ill-formed fashion (such as to specify the width of a bit-field, or 1212 // in an array-bound) - in which case we still want to return the 1213 // lexically containing DC (which could be a nested class). 1214 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1215 DC = DC->getLexicalParent(); 1216 1217 // A function not defined within a class will always return to its 1218 // lexical context. 1219 if (!isa<CXXRecordDecl>(DC)) 1220 return DC; 1221 1222 // A C++ inline method/friend is parsed *after* the topmost class 1223 // it was declared in is fully parsed ("complete"); the topmost 1224 // class is the context we need to return to. 1225 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1226 DC = RD; 1227 1228 // Return the declaration context of the topmost class the inline method is 1229 // declared in. 1230 return DC; 1231 } 1232 1233 return DC->getLexicalParent(); 1234 } 1235 1236 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1237 assert(getContainingDC(DC) == CurContext && 1238 "The next DeclContext should be lexically contained in the current one."); 1239 CurContext = DC; 1240 S->setEntity(DC); 1241 } 1242 1243 void Sema::PopDeclContext() { 1244 assert(CurContext && "DeclContext imbalance!"); 1245 1246 CurContext = getContainingDC(CurContext); 1247 assert(CurContext && "Popped translation unit!"); 1248 } 1249 1250 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1251 Decl *D) { 1252 // Unlike PushDeclContext, the context to which we return is not necessarily 1253 // the containing DC of TD, because the new context will be some pre-existing 1254 // TagDecl definition instead of a fresh one. 1255 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1256 CurContext = cast<TagDecl>(D)->getDefinition(); 1257 assert(CurContext && "skipping definition of undefined tag"); 1258 // Start lookups from the parent of the current context; we don't want to look 1259 // into the pre-existing complete definition. 1260 S->setEntity(CurContext->getLookupParent()); 1261 return Result; 1262 } 1263 1264 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1265 CurContext = static_cast<decltype(CurContext)>(Context); 1266 } 1267 1268 /// EnterDeclaratorContext - Used when we must lookup names in the context 1269 /// of a declarator's nested name specifier. 1270 /// 1271 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1272 // C++0x [basic.lookup.unqual]p13: 1273 // A name used in the definition of a static data member of class 1274 // X (after the qualified-id of the static member) is looked up as 1275 // if the name was used in a member function of X. 1276 // C++0x [basic.lookup.unqual]p14: 1277 // If a variable member of a namespace is defined outside of the 1278 // scope of its namespace then any name used in the definition of 1279 // the variable member (after the declarator-id) is looked up as 1280 // if the definition of the variable member occurred in its 1281 // namespace. 1282 // Both of these imply that we should push a scope whose context 1283 // is the semantic context of the declaration. We can't use 1284 // PushDeclContext here because that context is not necessarily 1285 // lexically contained in the current context. Fortunately, 1286 // the containing scope should have the appropriate information. 1287 1288 assert(!S->getEntity() && "scope already has entity"); 1289 1290 #ifndef NDEBUG 1291 Scope *Ancestor = S->getParent(); 1292 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1293 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1294 #endif 1295 1296 CurContext = DC; 1297 S->setEntity(DC); 1298 } 1299 1300 void Sema::ExitDeclaratorContext(Scope *S) { 1301 assert(S->getEntity() == CurContext && "Context imbalance!"); 1302 1303 // Switch back to the lexical context. The safety of this is 1304 // enforced by an assert in EnterDeclaratorContext. 1305 Scope *Ancestor = S->getParent(); 1306 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1307 CurContext = Ancestor->getEntity(); 1308 1309 // We don't need to do anything with the scope, which is going to 1310 // disappear. 1311 } 1312 1313 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1314 // We assume that the caller has already called 1315 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1316 FunctionDecl *FD = D->getAsFunction(); 1317 if (!FD) 1318 return; 1319 1320 // Same implementation as PushDeclContext, but enters the context 1321 // from the lexical parent, rather than the top-level class. 1322 assert(CurContext == FD->getLexicalParent() && 1323 "The next DeclContext should be lexically contained in the current one."); 1324 CurContext = FD; 1325 S->setEntity(CurContext); 1326 1327 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1328 ParmVarDecl *Param = FD->getParamDecl(P); 1329 // If the parameter has an identifier, then add it to the scope 1330 if (Param->getIdentifier()) { 1331 S->AddDecl(Param); 1332 IdResolver.AddDecl(Param); 1333 } 1334 } 1335 } 1336 1337 void Sema::ActOnExitFunctionContext() { 1338 // Same implementation as PopDeclContext, but returns to the lexical parent, 1339 // rather than the top-level class. 1340 assert(CurContext && "DeclContext imbalance!"); 1341 CurContext = CurContext->getLexicalParent(); 1342 assert(CurContext && "Popped translation unit!"); 1343 } 1344 1345 /// Determine whether we allow overloading of the function 1346 /// PrevDecl with another declaration. 1347 /// 1348 /// This routine determines whether overloading is possible, not 1349 /// whether some new function is actually an overload. It will return 1350 /// true in C++ (where we can always provide overloads) or, as an 1351 /// extension, in C when the previous function is already an 1352 /// overloaded function declaration or has the "overloadable" 1353 /// attribute. 1354 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1355 ASTContext &Context, 1356 const FunctionDecl *New) { 1357 if (Context.getLangOpts().CPlusPlus) 1358 return true; 1359 1360 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1361 return true; 1362 1363 return Previous.getResultKind() == LookupResult::Found && 1364 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1365 New->hasAttr<OverloadableAttr>()); 1366 } 1367 1368 /// Add this decl to the scope shadowed decl chains. 1369 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1370 // Move up the scope chain until we find the nearest enclosing 1371 // non-transparent context. The declaration will be introduced into this 1372 // scope. 1373 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1374 S = S->getParent(); 1375 1376 // Add scoped declarations into their context, so that they can be 1377 // found later. Declarations without a context won't be inserted 1378 // into any context. 1379 if (AddToContext) 1380 CurContext->addDecl(D); 1381 1382 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1383 // are function-local declarations. 1384 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1385 !D->getDeclContext()->getRedeclContext()->Equals( 1386 D->getLexicalDeclContext()->getRedeclContext()) && 1387 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1388 return; 1389 1390 // Template instantiations should also not be pushed into scope. 1391 if (isa<FunctionDecl>(D) && 1392 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1393 return; 1394 1395 // If this replaces anything in the current scope, 1396 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1397 IEnd = IdResolver.end(); 1398 for (; I != IEnd; ++I) { 1399 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1400 S->RemoveDecl(*I); 1401 IdResolver.RemoveDecl(*I); 1402 1403 // Should only need to replace one decl. 1404 break; 1405 } 1406 } 1407 1408 S->AddDecl(D); 1409 1410 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1411 // Implicitly-generated labels may end up getting generated in an order that 1412 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1413 // the label at the appropriate place in the identifier chain. 1414 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1415 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1416 if (IDC == CurContext) { 1417 if (!S->isDeclScope(*I)) 1418 continue; 1419 } else if (IDC->Encloses(CurContext)) 1420 break; 1421 } 1422 1423 IdResolver.InsertDeclAfter(I, D); 1424 } else { 1425 IdResolver.AddDecl(D); 1426 } 1427 } 1428 1429 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1430 bool AllowInlineNamespace) { 1431 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1432 } 1433 1434 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1435 DeclContext *TargetDC = DC->getPrimaryContext(); 1436 do { 1437 if (DeclContext *ScopeDC = S->getEntity()) 1438 if (ScopeDC->getPrimaryContext() == TargetDC) 1439 return S; 1440 } while ((S = S->getParent())); 1441 1442 return nullptr; 1443 } 1444 1445 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1446 DeclContext*, 1447 ASTContext&); 1448 1449 /// Filters out lookup results that don't fall within the given scope 1450 /// as determined by isDeclInScope. 1451 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1452 bool ConsiderLinkage, 1453 bool AllowInlineNamespace) { 1454 LookupResult::Filter F = R.makeFilter(); 1455 while (F.hasNext()) { 1456 NamedDecl *D = F.next(); 1457 1458 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1459 continue; 1460 1461 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1462 continue; 1463 1464 F.erase(); 1465 } 1466 1467 F.done(); 1468 } 1469 1470 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1471 /// have compatible owning modules. 1472 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1473 // FIXME: The Modules TS is not clear about how friend declarations are 1474 // to be treated. It's not meaningful to have different owning modules for 1475 // linkage in redeclarations of the same entity, so for now allow the 1476 // redeclaration and change the owning modules to match. 1477 if (New->getFriendObjectKind() && 1478 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1479 New->setLocalOwningModule(Old->getOwningModule()); 1480 makeMergedDefinitionVisible(New); 1481 return false; 1482 } 1483 1484 Module *NewM = New->getOwningModule(); 1485 Module *OldM = Old->getOwningModule(); 1486 1487 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1488 NewM = NewM->Parent; 1489 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1490 OldM = OldM->Parent; 1491 1492 if (NewM == OldM) 1493 return false; 1494 1495 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1496 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1497 if (NewIsModuleInterface || OldIsModuleInterface) { 1498 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1499 // if a declaration of D [...] appears in the purview of a module, all 1500 // other such declarations shall appear in the purview of the same module 1501 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1502 << New 1503 << NewIsModuleInterface 1504 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1505 << OldIsModuleInterface 1506 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1507 Diag(Old->getLocation(), diag::note_previous_declaration); 1508 New->setInvalidDecl(); 1509 return true; 1510 } 1511 1512 return false; 1513 } 1514 1515 static bool isUsingDecl(NamedDecl *D) { 1516 return isa<UsingShadowDecl>(D) || 1517 isa<UnresolvedUsingTypenameDecl>(D) || 1518 isa<UnresolvedUsingValueDecl>(D); 1519 } 1520 1521 /// Removes using shadow declarations from the lookup results. 1522 static void RemoveUsingDecls(LookupResult &R) { 1523 LookupResult::Filter F = R.makeFilter(); 1524 while (F.hasNext()) 1525 if (isUsingDecl(F.next())) 1526 F.erase(); 1527 1528 F.done(); 1529 } 1530 1531 /// Check for this common pattern: 1532 /// @code 1533 /// class S { 1534 /// S(const S&); // DO NOT IMPLEMENT 1535 /// void operator=(const S&); // DO NOT IMPLEMENT 1536 /// }; 1537 /// @endcode 1538 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1539 // FIXME: Should check for private access too but access is set after we get 1540 // the decl here. 1541 if (D->doesThisDeclarationHaveABody()) 1542 return false; 1543 1544 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1545 return CD->isCopyConstructor(); 1546 return D->isCopyAssignmentOperator(); 1547 } 1548 1549 // We need this to handle 1550 // 1551 // typedef struct { 1552 // void *foo() { return 0; } 1553 // } A; 1554 // 1555 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1556 // for example. If 'A', foo will have external linkage. If we have '*A', 1557 // foo will have no linkage. Since we can't know until we get to the end 1558 // of the typedef, this function finds out if D might have non-external linkage. 1559 // Callers should verify at the end of the TU if it D has external linkage or 1560 // not. 1561 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1562 const DeclContext *DC = D->getDeclContext(); 1563 while (!DC->isTranslationUnit()) { 1564 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1565 if (!RD->hasNameForLinkage()) 1566 return true; 1567 } 1568 DC = DC->getParent(); 1569 } 1570 1571 return !D->isExternallyVisible(); 1572 } 1573 1574 // FIXME: This needs to be refactored; some other isInMainFile users want 1575 // these semantics. 1576 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1577 if (S.TUKind != TU_Complete) 1578 return false; 1579 return S.SourceMgr.isInMainFile(Loc); 1580 } 1581 1582 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1583 assert(D); 1584 1585 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1586 return false; 1587 1588 // Ignore all entities declared within templates, and out-of-line definitions 1589 // of members of class templates. 1590 if (D->getDeclContext()->isDependentContext() || 1591 D->getLexicalDeclContext()->isDependentContext()) 1592 return false; 1593 1594 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1595 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1596 return false; 1597 // A non-out-of-line declaration of a member specialization was implicitly 1598 // instantiated; it's the out-of-line declaration that we're interested in. 1599 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1600 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1601 return false; 1602 1603 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1604 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1605 return false; 1606 } else { 1607 // 'static inline' functions are defined in headers; don't warn. 1608 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1609 return false; 1610 } 1611 1612 if (FD->doesThisDeclarationHaveABody() && 1613 Context.DeclMustBeEmitted(FD)) 1614 return false; 1615 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1616 // Constants and utility variables are defined in headers with internal 1617 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1618 // like "inline".) 1619 if (!isMainFileLoc(*this, VD->getLocation())) 1620 return false; 1621 1622 if (Context.DeclMustBeEmitted(VD)) 1623 return false; 1624 1625 if (VD->isStaticDataMember() && 1626 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1627 return false; 1628 if (VD->isStaticDataMember() && 1629 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1630 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1631 return false; 1632 1633 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1634 return false; 1635 } else { 1636 return false; 1637 } 1638 1639 // Only warn for unused decls internal to the translation unit. 1640 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1641 // for inline functions defined in the main source file, for instance. 1642 return mightHaveNonExternalLinkage(D); 1643 } 1644 1645 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1646 if (!D) 1647 return; 1648 1649 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1650 const FunctionDecl *First = FD->getFirstDecl(); 1651 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1652 return; // First should already be in the vector. 1653 } 1654 1655 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1656 const VarDecl *First = VD->getFirstDecl(); 1657 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1658 return; // First should already be in the vector. 1659 } 1660 1661 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1662 UnusedFileScopedDecls.push_back(D); 1663 } 1664 1665 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1666 if (D->isInvalidDecl()) 1667 return false; 1668 1669 bool Referenced = false; 1670 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1671 // For a decomposition declaration, warn if none of the bindings are 1672 // referenced, instead of if the variable itself is referenced (which 1673 // it is, by the bindings' expressions). 1674 for (auto *BD : DD->bindings()) { 1675 if (BD->isReferenced()) { 1676 Referenced = true; 1677 break; 1678 } 1679 } 1680 } else if (!D->getDeclName()) { 1681 return false; 1682 } else if (D->isReferenced() || D->isUsed()) { 1683 Referenced = true; 1684 } 1685 1686 if (Referenced || D->hasAttr<UnusedAttr>() || 1687 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1688 return false; 1689 1690 if (isa<LabelDecl>(D)) 1691 return true; 1692 1693 // Except for labels, we only care about unused decls that are local to 1694 // functions. 1695 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1696 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1697 // For dependent types, the diagnostic is deferred. 1698 WithinFunction = 1699 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1700 if (!WithinFunction) 1701 return false; 1702 1703 if (isa<TypedefNameDecl>(D)) 1704 return true; 1705 1706 // White-list anything that isn't a local variable. 1707 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1708 return false; 1709 1710 // Types of valid local variables should be complete, so this should succeed. 1711 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1712 1713 // White-list anything with an __attribute__((unused)) type. 1714 const auto *Ty = VD->getType().getTypePtr(); 1715 1716 // Only look at the outermost level of typedef. 1717 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1718 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1719 return false; 1720 } 1721 1722 // If we failed to complete the type for some reason, or if the type is 1723 // dependent, don't diagnose the variable. 1724 if (Ty->isIncompleteType() || Ty->isDependentType()) 1725 return false; 1726 1727 // Look at the element type to ensure that the warning behaviour is 1728 // consistent for both scalars and arrays. 1729 Ty = Ty->getBaseElementTypeUnsafe(); 1730 1731 if (const TagType *TT = Ty->getAs<TagType>()) { 1732 const TagDecl *Tag = TT->getDecl(); 1733 if (Tag->hasAttr<UnusedAttr>()) 1734 return false; 1735 1736 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1737 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1738 return false; 1739 1740 if (const Expr *Init = VD->getInit()) { 1741 if (const ExprWithCleanups *Cleanups = 1742 dyn_cast<ExprWithCleanups>(Init)) 1743 Init = Cleanups->getSubExpr(); 1744 const CXXConstructExpr *Construct = 1745 dyn_cast<CXXConstructExpr>(Init); 1746 if (Construct && !Construct->isElidable()) { 1747 CXXConstructorDecl *CD = Construct->getConstructor(); 1748 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1749 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1750 return false; 1751 } 1752 } 1753 } 1754 } 1755 1756 // TODO: __attribute__((unused)) templates? 1757 } 1758 1759 return true; 1760 } 1761 1762 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1763 FixItHint &Hint) { 1764 if (isa<LabelDecl>(D)) { 1765 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1766 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1767 true); 1768 if (AfterColon.isInvalid()) 1769 return; 1770 Hint = FixItHint::CreateRemoval( 1771 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1772 } 1773 } 1774 1775 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1776 if (D->getTypeForDecl()->isDependentType()) 1777 return; 1778 1779 for (auto *TmpD : D->decls()) { 1780 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1781 DiagnoseUnusedDecl(T); 1782 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1783 DiagnoseUnusedNestedTypedefs(R); 1784 } 1785 } 1786 1787 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1788 /// unless they are marked attr(unused). 1789 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1790 if (!ShouldDiagnoseUnusedDecl(D)) 1791 return; 1792 1793 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1794 // typedefs can be referenced later on, so the diagnostics are emitted 1795 // at end-of-translation-unit. 1796 UnusedLocalTypedefNameCandidates.insert(TD); 1797 return; 1798 } 1799 1800 FixItHint Hint; 1801 GenerateFixForUnusedDecl(D, Context, Hint); 1802 1803 unsigned DiagID; 1804 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1805 DiagID = diag::warn_unused_exception_param; 1806 else if (isa<LabelDecl>(D)) 1807 DiagID = diag::warn_unused_label; 1808 else 1809 DiagID = diag::warn_unused_variable; 1810 1811 Diag(D->getLocation(), DiagID) << D << Hint; 1812 } 1813 1814 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1815 // Verify that we have no forward references left. If so, there was a goto 1816 // or address of a label taken, but no definition of it. Label fwd 1817 // definitions are indicated with a null substmt which is also not a resolved 1818 // MS inline assembly label name. 1819 bool Diagnose = false; 1820 if (L->isMSAsmLabel()) 1821 Diagnose = !L->isResolvedMSAsmLabel(); 1822 else 1823 Diagnose = L->getStmt() == nullptr; 1824 if (Diagnose) 1825 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1826 } 1827 1828 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1829 S->mergeNRVOIntoParent(); 1830 1831 if (S->decl_empty()) return; 1832 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1833 "Scope shouldn't contain decls!"); 1834 1835 for (auto *TmpD : S->decls()) { 1836 assert(TmpD && "This decl didn't get pushed??"); 1837 1838 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1839 NamedDecl *D = cast<NamedDecl>(TmpD); 1840 1841 // Diagnose unused variables in this scope. 1842 if (!S->hasUnrecoverableErrorOccurred()) { 1843 DiagnoseUnusedDecl(D); 1844 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1845 DiagnoseUnusedNestedTypedefs(RD); 1846 } 1847 1848 if (!D->getDeclName()) continue; 1849 1850 // If this was a forward reference to a label, verify it was defined. 1851 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1852 CheckPoppedLabel(LD, *this); 1853 1854 // Remove this name from our lexical scope, and warn on it if we haven't 1855 // already. 1856 IdResolver.RemoveDecl(D); 1857 auto ShadowI = ShadowingDecls.find(D); 1858 if (ShadowI != ShadowingDecls.end()) { 1859 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1860 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1861 << D << FD << FD->getParent(); 1862 Diag(FD->getLocation(), diag::note_previous_declaration); 1863 } 1864 ShadowingDecls.erase(ShadowI); 1865 } 1866 } 1867 } 1868 1869 /// Look for an Objective-C class in the translation unit. 1870 /// 1871 /// \param Id The name of the Objective-C class we're looking for. If 1872 /// typo-correction fixes this name, the Id will be updated 1873 /// to the fixed name. 1874 /// 1875 /// \param IdLoc The location of the name in the translation unit. 1876 /// 1877 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1878 /// if there is no class with the given name. 1879 /// 1880 /// \returns The declaration of the named Objective-C class, or NULL if the 1881 /// class could not be found. 1882 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1883 SourceLocation IdLoc, 1884 bool DoTypoCorrection) { 1885 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1886 // creation from this context. 1887 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1888 1889 if (!IDecl && DoTypoCorrection) { 1890 // Perform typo correction at the given location, but only if we 1891 // find an Objective-C class name. 1892 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1893 if (TypoCorrection C = 1894 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1895 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1896 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1897 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1898 Id = IDecl->getIdentifier(); 1899 } 1900 } 1901 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1902 // This routine must always return a class definition, if any. 1903 if (Def && Def->getDefinition()) 1904 Def = Def->getDefinition(); 1905 return Def; 1906 } 1907 1908 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1909 /// from S, where a non-field would be declared. This routine copes 1910 /// with the difference between C and C++ scoping rules in structs and 1911 /// unions. For example, the following code is well-formed in C but 1912 /// ill-formed in C++: 1913 /// @code 1914 /// struct S6 { 1915 /// enum { BAR } e; 1916 /// }; 1917 /// 1918 /// void test_S6() { 1919 /// struct S6 a; 1920 /// a.e = BAR; 1921 /// } 1922 /// @endcode 1923 /// For the declaration of BAR, this routine will return a different 1924 /// scope. The scope S will be the scope of the unnamed enumeration 1925 /// within S6. In C++, this routine will return the scope associated 1926 /// with S6, because the enumeration's scope is a transparent 1927 /// context but structures can contain non-field names. In C, this 1928 /// routine will return the translation unit scope, since the 1929 /// enumeration's scope is a transparent context and structures cannot 1930 /// contain non-field names. 1931 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1932 while (((S->getFlags() & Scope::DeclScope) == 0) || 1933 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1934 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1935 S = S->getParent(); 1936 return S; 1937 } 1938 1939 /// Looks up the declaration of "struct objc_super" and 1940 /// saves it for later use in building builtin declaration of 1941 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1942 /// pre-existing declaration exists no action takes place. 1943 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1944 IdentifierInfo *II) { 1945 if (!II->isStr("objc_msgSendSuper")) 1946 return; 1947 ASTContext &Context = ThisSema.Context; 1948 1949 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1950 SourceLocation(), Sema::LookupTagName); 1951 ThisSema.LookupName(Result, S); 1952 if (Result.getResultKind() == LookupResult::Found) 1953 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1954 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1955 } 1956 1957 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 1958 ASTContext::GetBuiltinTypeError Error) { 1959 switch (Error) { 1960 case ASTContext::GE_None: 1961 return ""; 1962 case ASTContext::GE_Missing_type: 1963 return BuiltinInfo.getHeaderName(ID); 1964 case ASTContext::GE_Missing_stdio: 1965 return "stdio.h"; 1966 case ASTContext::GE_Missing_setjmp: 1967 return "setjmp.h"; 1968 case ASTContext::GE_Missing_ucontext: 1969 return "ucontext.h"; 1970 } 1971 llvm_unreachable("unhandled error kind"); 1972 } 1973 1974 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1975 /// file scope. lazily create a decl for it. ForRedeclaration is true 1976 /// if we're creating this built-in in anticipation of redeclaring the 1977 /// built-in. 1978 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1979 Scope *S, bool ForRedeclaration, 1980 SourceLocation Loc) { 1981 LookupPredefedObjCSuperType(*this, S, II); 1982 1983 ASTContext::GetBuiltinTypeError Error; 1984 QualType R = Context.GetBuiltinType(ID, Error); 1985 if (Error) { 1986 if (!ForRedeclaration) 1987 return nullptr; 1988 1989 // If we have a builtin without an associated type we should not emit a 1990 // warning when we were not able to find a type for it. 1991 if (Error == ASTContext::GE_Missing_type) 1992 return nullptr; 1993 1994 // If we could not find a type for setjmp it is because the jmp_buf type was 1995 // not defined prior to the setjmp declaration. 1996 if (Error == ASTContext::GE_Missing_setjmp) { 1997 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 1998 << Context.BuiltinInfo.getName(ID); 1999 return nullptr; 2000 } 2001 2002 // Generally, we emit a warning that the declaration requires the 2003 // appropriate header. 2004 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2005 << getHeaderName(Context.BuiltinInfo, ID, Error) 2006 << Context.BuiltinInfo.getName(ID); 2007 return nullptr; 2008 } 2009 2010 if (!ForRedeclaration && 2011 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2012 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2013 Diag(Loc, diag::ext_implicit_lib_function_decl) 2014 << Context.BuiltinInfo.getName(ID) << R; 2015 if (Context.BuiltinInfo.getHeaderName(ID) && 2016 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 2017 Diag(Loc, diag::note_include_header_or_declare) 2018 << Context.BuiltinInfo.getHeaderName(ID) 2019 << Context.BuiltinInfo.getName(ID); 2020 } 2021 2022 if (R.isNull()) 2023 return nullptr; 2024 2025 DeclContext *Parent = Context.getTranslationUnitDecl(); 2026 if (getLangOpts().CPlusPlus) { 2027 LinkageSpecDecl *CLinkageDecl = 2028 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 2029 LinkageSpecDecl::lang_c, false); 2030 CLinkageDecl->setImplicit(); 2031 Parent->addDecl(CLinkageDecl); 2032 Parent = CLinkageDecl; 2033 } 2034 2035 FunctionDecl *New = FunctionDecl::Create(Context, 2036 Parent, 2037 Loc, Loc, II, R, /*TInfo=*/nullptr, 2038 SC_Extern, 2039 false, 2040 R->isFunctionProtoType()); 2041 New->setImplicit(); 2042 2043 // Create Decl objects for each parameter, adding them to the 2044 // FunctionDecl. 2045 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2046 SmallVector<ParmVarDecl*, 16> Params; 2047 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2048 ParmVarDecl *parm = 2049 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2050 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2051 SC_None, nullptr); 2052 parm->setScopeInfo(0, i); 2053 Params.push_back(parm); 2054 } 2055 New->setParams(Params); 2056 } 2057 2058 AddKnownFunctionAttributes(New); 2059 RegisterLocallyScopedExternCDecl(New, S); 2060 2061 // TUScope is the translation-unit scope to insert this function into. 2062 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2063 // relate Scopes to DeclContexts, and probably eliminate CurContext 2064 // entirely, but we're not there yet. 2065 DeclContext *SavedContext = CurContext; 2066 CurContext = Parent; 2067 PushOnScopeChains(New, TUScope); 2068 CurContext = SavedContext; 2069 return New; 2070 } 2071 2072 /// Typedef declarations don't have linkage, but they still denote the same 2073 /// entity if their types are the same. 2074 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2075 /// isSameEntity. 2076 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2077 TypedefNameDecl *Decl, 2078 LookupResult &Previous) { 2079 // This is only interesting when modules are enabled. 2080 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2081 return; 2082 2083 // Empty sets are uninteresting. 2084 if (Previous.empty()) 2085 return; 2086 2087 LookupResult::Filter Filter = Previous.makeFilter(); 2088 while (Filter.hasNext()) { 2089 NamedDecl *Old = Filter.next(); 2090 2091 // Non-hidden declarations are never ignored. 2092 if (S.isVisible(Old)) 2093 continue; 2094 2095 // Declarations of the same entity are not ignored, even if they have 2096 // different linkages. 2097 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2098 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2099 Decl->getUnderlyingType())) 2100 continue; 2101 2102 // If both declarations give a tag declaration a typedef name for linkage 2103 // purposes, then they declare the same entity. 2104 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2105 Decl->getAnonDeclWithTypedefName()) 2106 continue; 2107 } 2108 2109 Filter.erase(); 2110 } 2111 2112 Filter.done(); 2113 } 2114 2115 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2116 QualType OldType; 2117 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2118 OldType = OldTypedef->getUnderlyingType(); 2119 else 2120 OldType = Context.getTypeDeclType(Old); 2121 QualType NewType = New->getUnderlyingType(); 2122 2123 if (NewType->isVariablyModifiedType()) { 2124 // Must not redefine a typedef with a variably-modified type. 2125 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2126 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2127 << Kind << NewType; 2128 if (Old->getLocation().isValid()) 2129 notePreviousDefinition(Old, New->getLocation()); 2130 New->setInvalidDecl(); 2131 return true; 2132 } 2133 2134 if (OldType != NewType && 2135 !OldType->isDependentType() && 2136 !NewType->isDependentType() && 2137 !Context.hasSameType(OldType, NewType)) { 2138 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2139 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2140 << Kind << NewType << OldType; 2141 if (Old->getLocation().isValid()) 2142 notePreviousDefinition(Old, New->getLocation()); 2143 New->setInvalidDecl(); 2144 return true; 2145 } 2146 return false; 2147 } 2148 2149 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2150 /// same name and scope as a previous declaration 'Old'. Figure out 2151 /// how to resolve this situation, merging decls or emitting 2152 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2153 /// 2154 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2155 LookupResult &OldDecls) { 2156 // If the new decl is known invalid already, don't bother doing any 2157 // merging checks. 2158 if (New->isInvalidDecl()) return; 2159 2160 // Allow multiple definitions for ObjC built-in typedefs. 2161 // FIXME: Verify the underlying types are equivalent! 2162 if (getLangOpts().ObjC) { 2163 const IdentifierInfo *TypeID = New->getIdentifier(); 2164 switch (TypeID->getLength()) { 2165 default: break; 2166 case 2: 2167 { 2168 if (!TypeID->isStr("id")) 2169 break; 2170 QualType T = New->getUnderlyingType(); 2171 if (!T->isPointerType()) 2172 break; 2173 if (!T->isVoidPointerType()) { 2174 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2175 if (!PT->isStructureType()) 2176 break; 2177 } 2178 Context.setObjCIdRedefinitionType(T); 2179 // Install the built-in type for 'id', ignoring the current definition. 2180 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2181 return; 2182 } 2183 case 5: 2184 if (!TypeID->isStr("Class")) 2185 break; 2186 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2187 // Install the built-in type for 'Class', ignoring the current definition. 2188 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2189 return; 2190 case 3: 2191 if (!TypeID->isStr("SEL")) 2192 break; 2193 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2194 // Install the built-in type for 'SEL', ignoring the current definition. 2195 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2196 return; 2197 } 2198 // Fall through - the typedef name was not a builtin type. 2199 } 2200 2201 // Verify the old decl was also a type. 2202 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2203 if (!Old) { 2204 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2205 << New->getDeclName(); 2206 2207 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2208 if (OldD->getLocation().isValid()) 2209 notePreviousDefinition(OldD, New->getLocation()); 2210 2211 return New->setInvalidDecl(); 2212 } 2213 2214 // If the old declaration is invalid, just give up here. 2215 if (Old->isInvalidDecl()) 2216 return New->setInvalidDecl(); 2217 2218 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2219 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2220 auto *NewTag = New->getAnonDeclWithTypedefName(); 2221 NamedDecl *Hidden = nullptr; 2222 if (OldTag && NewTag && 2223 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2224 !hasVisibleDefinition(OldTag, &Hidden)) { 2225 // There is a definition of this tag, but it is not visible. Use it 2226 // instead of our tag. 2227 New->setTypeForDecl(OldTD->getTypeForDecl()); 2228 if (OldTD->isModed()) 2229 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2230 OldTD->getUnderlyingType()); 2231 else 2232 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2233 2234 // Make the old tag definition visible. 2235 makeMergedDefinitionVisible(Hidden); 2236 2237 // If this was an unscoped enumeration, yank all of its enumerators 2238 // out of the scope. 2239 if (isa<EnumDecl>(NewTag)) { 2240 Scope *EnumScope = getNonFieldDeclScope(S); 2241 for (auto *D : NewTag->decls()) { 2242 auto *ED = cast<EnumConstantDecl>(D); 2243 assert(EnumScope->isDeclScope(ED)); 2244 EnumScope->RemoveDecl(ED); 2245 IdResolver.RemoveDecl(ED); 2246 ED->getLexicalDeclContext()->removeDecl(ED); 2247 } 2248 } 2249 } 2250 } 2251 2252 // If the typedef types are not identical, reject them in all languages and 2253 // with any extensions enabled. 2254 if (isIncompatibleTypedef(Old, New)) 2255 return; 2256 2257 // The types match. Link up the redeclaration chain and merge attributes if 2258 // the old declaration was a typedef. 2259 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2260 New->setPreviousDecl(Typedef); 2261 mergeDeclAttributes(New, Old); 2262 } 2263 2264 if (getLangOpts().MicrosoftExt) 2265 return; 2266 2267 if (getLangOpts().CPlusPlus) { 2268 // C++ [dcl.typedef]p2: 2269 // In a given non-class scope, a typedef specifier can be used to 2270 // redefine the name of any type declared in that scope to refer 2271 // to the type to which it already refers. 2272 if (!isa<CXXRecordDecl>(CurContext)) 2273 return; 2274 2275 // C++0x [dcl.typedef]p4: 2276 // In a given class scope, a typedef specifier can be used to redefine 2277 // any class-name declared in that scope that is not also a typedef-name 2278 // to refer to the type to which it already refers. 2279 // 2280 // This wording came in via DR424, which was a correction to the 2281 // wording in DR56, which accidentally banned code like: 2282 // 2283 // struct S { 2284 // typedef struct A { } A; 2285 // }; 2286 // 2287 // in the C++03 standard. We implement the C++0x semantics, which 2288 // allow the above but disallow 2289 // 2290 // struct S { 2291 // typedef int I; 2292 // typedef int I; 2293 // }; 2294 // 2295 // since that was the intent of DR56. 2296 if (!isa<TypedefNameDecl>(Old)) 2297 return; 2298 2299 Diag(New->getLocation(), diag::err_redefinition) 2300 << New->getDeclName(); 2301 notePreviousDefinition(Old, New->getLocation()); 2302 return New->setInvalidDecl(); 2303 } 2304 2305 // Modules always permit redefinition of typedefs, as does C11. 2306 if (getLangOpts().Modules || getLangOpts().C11) 2307 return; 2308 2309 // If we have a redefinition of a typedef in C, emit a warning. This warning 2310 // is normally mapped to an error, but can be controlled with 2311 // -Wtypedef-redefinition. If either the original or the redefinition is 2312 // in a system header, don't emit this for compatibility with GCC. 2313 if (getDiagnostics().getSuppressSystemWarnings() && 2314 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2315 (Old->isImplicit() || 2316 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2317 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2318 return; 2319 2320 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2321 << New->getDeclName(); 2322 notePreviousDefinition(Old, New->getLocation()); 2323 } 2324 2325 /// DeclhasAttr - returns true if decl Declaration already has the target 2326 /// attribute. 2327 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2328 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2329 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2330 for (const auto *i : D->attrs()) 2331 if (i->getKind() == A->getKind()) { 2332 if (Ann) { 2333 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2334 return true; 2335 continue; 2336 } 2337 // FIXME: Don't hardcode this check 2338 if (OA && isa<OwnershipAttr>(i)) 2339 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2340 return true; 2341 } 2342 2343 return false; 2344 } 2345 2346 static bool isAttributeTargetADefinition(Decl *D) { 2347 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2348 return VD->isThisDeclarationADefinition(); 2349 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2350 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2351 return true; 2352 } 2353 2354 /// Merge alignment attributes from \p Old to \p New, taking into account the 2355 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2356 /// 2357 /// \return \c true if any attributes were added to \p New. 2358 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2359 // Look for alignas attributes on Old, and pick out whichever attribute 2360 // specifies the strictest alignment requirement. 2361 AlignedAttr *OldAlignasAttr = nullptr; 2362 AlignedAttr *OldStrictestAlignAttr = nullptr; 2363 unsigned OldAlign = 0; 2364 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2365 // FIXME: We have no way of representing inherited dependent alignments 2366 // in a case like: 2367 // template<int A, int B> struct alignas(A) X; 2368 // template<int A, int B> struct alignas(B) X {}; 2369 // For now, we just ignore any alignas attributes which are not on the 2370 // definition in such a case. 2371 if (I->isAlignmentDependent()) 2372 return false; 2373 2374 if (I->isAlignas()) 2375 OldAlignasAttr = I; 2376 2377 unsigned Align = I->getAlignment(S.Context); 2378 if (Align > OldAlign) { 2379 OldAlign = Align; 2380 OldStrictestAlignAttr = I; 2381 } 2382 } 2383 2384 // Look for alignas attributes on New. 2385 AlignedAttr *NewAlignasAttr = nullptr; 2386 unsigned NewAlign = 0; 2387 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2388 if (I->isAlignmentDependent()) 2389 return false; 2390 2391 if (I->isAlignas()) 2392 NewAlignasAttr = I; 2393 2394 unsigned Align = I->getAlignment(S.Context); 2395 if (Align > NewAlign) 2396 NewAlign = Align; 2397 } 2398 2399 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2400 // Both declarations have 'alignas' attributes. We require them to match. 2401 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2402 // fall short. (If two declarations both have alignas, they must both match 2403 // every definition, and so must match each other if there is a definition.) 2404 2405 // If either declaration only contains 'alignas(0)' specifiers, then it 2406 // specifies the natural alignment for the type. 2407 if (OldAlign == 0 || NewAlign == 0) { 2408 QualType Ty; 2409 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2410 Ty = VD->getType(); 2411 else 2412 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2413 2414 if (OldAlign == 0) 2415 OldAlign = S.Context.getTypeAlign(Ty); 2416 if (NewAlign == 0) 2417 NewAlign = S.Context.getTypeAlign(Ty); 2418 } 2419 2420 if (OldAlign != NewAlign) { 2421 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2422 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2423 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2424 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2425 } 2426 } 2427 2428 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2429 // C++11 [dcl.align]p6: 2430 // if any declaration of an entity has an alignment-specifier, 2431 // every defining declaration of that entity shall specify an 2432 // equivalent alignment. 2433 // C11 6.7.5/7: 2434 // If the definition of an object does not have an alignment 2435 // specifier, any other declaration of that object shall also 2436 // have no alignment specifier. 2437 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2438 << OldAlignasAttr; 2439 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2440 << OldAlignasAttr; 2441 } 2442 2443 bool AnyAdded = false; 2444 2445 // Ensure we have an attribute representing the strictest alignment. 2446 if (OldAlign > NewAlign) { 2447 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2448 Clone->setInherited(true); 2449 New->addAttr(Clone); 2450 AnyAdded = true; 2451 } 2452 2453 // Ensure we have an alignas attribute if the old declaration had one. 2454 if (OldAlignasAttr && !NewAlignasAttr && 2455 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2456 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2457 Clone->setInherited(true); 2458 New->addAttr(Clone); 2459 AnyAdded = true; 2460 } 2461 2462 return AnyAdded; 2463 } 2464 2465 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2466 const InheritableAttr *Attr, 2467 Sema::AvailabilityMergeKind AMK) { 2468 // This function copies an attribute Attr from a previous declaration to the 2469 // new declaration D if the new declaration doesn't itself have that attribute 2470 // yet or if that attribute allows duplicates. 2471 // If you're adding a new attribute that requires logic different from 2472 // "use explicit attribute on decl if present, else use attribute from 2473 // previous decl", for example if the attribute needs to be consistent 2474 // between redeclarations, you need to call a custom merge function here. 2475 InheritableAttr *NewAttr = nullptr; 2476 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2477 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2478 NewAttr = S.mergeAvailabilityAttr( 2479 D, AA->getRange(), AA->getPlatform(), AA->isImplicit(), 2480 AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(), 2481 AA->getUnavailable(), AA->getMessage(), AA->getStrict(), 2482 AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex); 2483 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2484 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2485 AttrSpellingListIndex); 2486 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2487 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2488 AttrSpellingListIndex); 2489 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2490 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2491 AttrSpellingListIndex); 2492 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2493 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2494 AttrSpellingListIndex); 2495 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2496 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2497 FA->getFormatIdx(), FA->getFirstArg(), 2498 AttrSpellingListIndex); 2499 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2500 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2501 AttrSpellingListIndex); 2502 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2503 NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(), 2504 AttrSpellingListIndex); 2505 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2506 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2507 AttrSpellingListIndex, 2508 IA->getSemanticSpelling()); 2509 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2510 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2511 &S.Context.Idents.get(AA->getSpelling()), 2512 AttrSpellingListIndex); 2513 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2514 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2515 isa<CUDAGlobalAttr>(Attr))) { 2516 // CUDA target attributes are part of function signature for 2517 // overloading purposes and must not be merged. 2518 return false; 2519 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2520 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2521 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2522 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2523 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2524 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2525 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2526 NewAttr = S.mergeCommonAttr(D, *CommonA); 2527 else if (isa<AlignedAttr>(Attr)) 2528 // AlignedAttrs are handled separately, because we need to handle all 2529 // such attributes on a declaration at the same time. 2530 NewAttr = nullptr; 2531 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2532 (AMK == Sema::AMK_Override || 2533 AMK == Sema::AMK_ProtocolImplementation)) 2534 NewAttr = nullptr; 2535 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2536 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2537 UA->getGuid()); 2538 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2539 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2540 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2541 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2542 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2543 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2544 2545 if (NewAttr) { 2546 NewAttr->setInherited(true); 2547 D->addAttr(NewAttr); 2548 if (isa<MSInheritanceAttr>(NewAttr)) 2549 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2550 return true; 2551 } 2552 2553 return false; 2554 } 2555 2556 static const NamedDecl *getDefinition(const Decl *D) { 2557 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2558 return TD->getDefinition(); 2559 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2560 const VarDecl *Def = VD->getDefinition(); 2561 if (Def) 2562 return Def; 2563 return VD->getActingDefinition(); 2564 } 2565 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2566 return FD->getDefinition(); 2567 return nullptr; 2568 } 2569 2570 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2571 for (const auto *Attribute : D->attrs()) 2572 if (Attribute->getKind() == Kind) 2573 return true; 2574 return false; 2575 } 2576 2577 /// checkNewAttributesAfterDef - If we already have a definition, check that 2578 /// there are no new attributes in this declaration. 2579 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2580 if (!New->hasAttrs()) 2581 return; 2582 2583 const NamedDecl *Def = getDefinition(Old); 2584 if (!Def || Def == New) 2585 return; 2586 2587 AttrVec &NewAttributes = New->getAttrs(); 2588 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2589 const Attr *NewAttribute = NewAttributes[I]; 2590 2591 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2592 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2593 Sema::SkipBodyInfo SkipBody; 2594 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2595 2596 // If we're skipping this definition, drop the "alias" attribute. 2597 if (SkipBody.ShouldSkip) { 2598 NewAttributes.erase(NewAttributes.begin() + I); 2599 --E; 2600 continue; 2601 } 2602 } else { 2603 VarDecl *VD = cast<VarDecl>(New); 2604 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2605 VarDecl::TentativeDefinition 2606 ? diag::err_alias_after_tentative 2607 : diag::err_redefinition; 2608 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2609 if (Diag == diag::err_redefinition) 2610 S.notePreviousDefinition(Def, VD->getLocation()); 2611 else 2612 S.Diag(Def->getLocation(), diag::note_previous_definition); 2613 VD->setInvalidDecl(); 2614 } 2615 ++I; 2616 continue; 2617 } 2618 2619 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2620 // Tentative definitions are only interesting for the alias check above. 2621 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2622 ++I; 2623 continue; 2624 } 2625 } 2626 2627 if (hasAttribute(Def, NewAttribute->getKind())) { 2628 ++I; 2629 continue; // regular attr merging will take care of validating this. 2630 } 2631 2632 if (isa<C11NoReturnAttr>(NewAttribute)) { 2633 // C's _Noreturn is allowed to be added to a function after it is defined. 2634 ++I; 2635 continue; 2636 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2637 if (AA->isAlignas()) { 2638 // C++11 [dcl.align]p6: 2639 // if any declaration of an entity has an alignment-specifier, 2640 // every defining declaration of that entity shall specify an 2641 // equivalent alignment. 2642 // C11 6.7.5/7: 2643 // If the definition of an object does not have an alignment 2644 // specifier, any other declaration of that object shall also 2645 // have no alignment specifier. 2646 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2647 << AA; 2648 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2649 << AA; 2650 NewAttributes.erase(NewAttributes.begin() + I); 2651 --E; 2652 continue; 2653 } 2654 } 2655 2656 S.Diag(NewAttribute->getLocation(), 2657 diag::warn_attribute_precede_definition); 2658 S.Diag(Def->getLocation(), diag::note_previous_definition); 2659 NewAttributes.erase(NewAttributes.begin() + I); 2660 --E; 2661 } 2662 } 2663 2664 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2665 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2666 AvailabilityMergeKind AMK) { 2667 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2668 UsedAttr *NewAttr = OldAttr->clone(Context); 2669 NewAttr->setInherited(true); 2670 New->addAttr(NewAttr); 2671 } 2672 2673 if (!Old->hasAttrs() && !New->hasAttrs()) 2674 return; 2675 2676 // Attributes declared post-definition are currently ignored. 2677 checkNewAttributesAfterDef(*this, New, Old); 2678 2679 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2680 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2681 if (OldA->getLabel() != NewA->getLabel()) { 2682 // This redeclaration changes __asm__ label. 2683 Diag(New->getLocation(), diag::err_different_asm_label); 2684 Diag(OldA->getLocation(), diag::note_previous_declaration); 2685 } 2686 } else if (Old->isUsed()) { 2687 // This redeclaration adds an __asm__ label to a declaration that has 2688 // already been ODR-used. 2689 Diag(New->getLocation(), diag::err_late_asm_label_name) 2690 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2691 } 2692 } 2693 2694 // Re-declaration cannot add abi_tag's. 2695 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2696 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2697 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2698 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2699 NewTag) == OldAbiTagAttr->tags_end()) { 2700 Diag(NewAbiTagAttr->getLocation(), 2701 diag::err_new_abi_tag_on_redeclaration) 2702 << NewTag; 2703 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2704 } 2705 } 2706 } else { 2707 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2708 Diag(Old->getLocation(), diag::note_previous_declaration); 2709 } 2710 } 2711 2712 // This redeclaration adds a section attribute. 2713 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2714 if (auto *VD = dyn_cast<VarDecl>(New)) { 2715 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2716 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2717 Diag(Old->getLocation(), diag::note_previous_declaration); 2718 } 2719 } 2720 } 2721 2722 // Redeclaration adds code-seg attribute. 2723 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2724 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2725 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2726 Diag(New->getLocation(), diag::warn_mismatched_section) 2727 << 0 /*codeseg*/; 2728 Diag(Old->getLocation(), diag::note_previous_declaration); 2729 } 2730 2731 if (!Old->hasAttrs()) 2732 return; 2733 2734 bool foundAny = New->hasAttrs(); 2735 2736 // Ensure that any moving of objects within the allocated map is done before 2737 // we process them. 2738 if (!foundAny) New->setAttrs(AttrVec()); 2739 2740 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2741 // Ignore deprecated/unavailable/availability attributes if requested. 2742 AvailabilityMergeKind LocalAMK = AMK_None; 2743 if (isa<DeprecatedAttr>(I) || 2744 isa<UnavailableAttr>(I) || 2745 isa<AvailabilityAttr>(I)) { 2746 switch (AMK) { 2747 case AMK_None: 2748 continue; 2749 2750 case AMK_Redeclaration: 2751 case AMK_Override: 2752 case AMK_ProtocolImplementation: 2753 LocalAMK = AMK; 2754 break; 2755 } 2756 } 2757 2758 // Already handled. 2759 if (isa<UsedAttr>(I)) 2760 continue; 2761 2762 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2763 foundAny = true; 2764 } 2765 2766 if (mergeAlignedAttrs(*this, New, Old)) 2767 foundAny = true; 2768 2769 if (!foundAny) New->dropAttrs(); 2770 } 2771 2772 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2773 /// to the new one. 2774 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2775 const ParmVarDecl *oldDecl, 2776 Sema &S) { 2777 // C++11 [dcl.attr.depend]p2: 2778 // The first declaration of a function shall specify the 2779 // carries_dependency attribute for its declarator-id if any declaration 2780 // of the function specifies the carries_dependency attribute. 2781 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2782 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2783 S.Diag(CDA->getLocation(), 2784 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2785 // Find the first declaration of the parameter. 2786 // FIXME: Should we build redeclaration chains for function parameters? 2787 const FunctionDecl *FirstFD = 2788 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2789 const ParmVarDecl *FirstVD = 2790 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2791 S.Diag(FirstVD->getLocation(), 2792 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2793 } 2794 2795 if (!oldDecl->hasAttrs()) 2796 return; 2797 2798 bool foundAny = newDecl->hasAttrs(); 2799 2800 // Ensure that any moving of objects within the allocated map is 2801 // done before we process them. 2802 if (!foundAny) newDecl->setAttrs(AttrVec()); 2803 2804 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2805 if (!DeclHasAttr(newDecl, I)) { 2806 InheritableAttr *newAttr = 2807 cast<InheritableParamAttr>(I->clone(S.Context)); 2808 newAttr->setInherited(true); 2809 newDecl->addAttr(newAttr); 2810 foundAny = true; 2811 } 2812 } 2813 2814 if (!foundAny) newDecl->dropAttrs(); 2815 } 2816 2817 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2818 const ParmVarDecl *OldParam, 2819 Sema &S) { 2820 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2821 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2822 if (*Oldnullability != *Newnullability) { 2823 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2824 << DiagNullabilityKind( 2825 *Newnullability, 2826 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2827 != 0)) 2828 << DiagNullabilityKind( 2829 *Oldnullability, 2830 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2831 != 0)); 2832 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2833 } 2834 } else { 2835 QualType NewT = NewParam->getType(); 2836 NewT = S.Context.getAttributedType( 2837 AttributedType::getNullabilityAttrKind(*Oldnullability), 2838 NewT, NewT); 2839 NewParam->setType(NewT); 2840 } 2841 } 2842 } 2843 2844 namespace { 2845 2846 /// Used in MergeFunctionDecl to keep track of function parameters in 2847 /// C. 2848 struct GNUCompatibleParamWarning { 2849 ParmVarDecl *OldParm; 2850 ParmVarDecl *NewParm; 2851 QualType PromotedType; 2852 }; 2853 2854 } // end anonymous namespace 2855 2856 /// getSpecialMember - get the special member enum for a method. 2857 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2858 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2859 if (Ctor->isDefaultConstructor()) 2860 return Sema::CXXDefaultConstructor; 2861 2862 if (Ctor->isCopyConstructor()) 2863 return Sema::CXXCopyConstructor; 2864 2865 if (Ctor->isMoveConstructor()) 2866 return Sema::CXXMoveConstructor; 2867 } else if (isa<CXXDestructorDecl>(MD)) { 2868 return Sema::CXXDestructor; 2869 } else if (MD->isCopyAssignmentOperator()) { 2870 return Sema::CXXCopyAssignment; 2871 } else if (MD->isMoveAssignmentOperator()) { 2872 return Sema::CXXMoveAssignment; 2873 } 2874 2875 return Sema::CXXInvalid; 2876 } 2877 2878 // Determine whether the previous declaration was a definition, implicit 2879 // declaration, or a declaration. 2880 template <typename T> 2881 static std::pair<diag::kind, SourceLocation> 2882 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2883 diag::kind PrevDiag; 2884 SourceLocation OldLocation = Old->getLocation(); 2885 if (Old->isThisDeclarationADefinition()) 2886 PrevDiag = diag::note_previous_definition; 2887 else if (Old->isImplicit()) { 2888 PrevDiag = diag::note_previous_implicit_declaration; 2889 if (OldLocation.isInvalid()) 2890 OldLocation = New->getLocation(); 2891 } else 2892 PrevDiag = diag::note_previous_declaration; 2893 return std::make_pair(PrevDiag, OldLocation); 2894 } 2895 2896 /// canRedefineFunction - checks if a function can be redefined. Currently, 2897 /// only extern inline functions can be redefined, and even then only in 2898 /// GNU89 mode. 2899 static bool canRedefineFunction(const FunctionDecl *FD, 2900 const LangOptions& LangOpts) { 2901 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2902 !LangOpts.CPlusPlus && 2903 FD->isInlineSpecified() && 2904 FD->getStorageClass() == SC_Extern); 2905 } 2906 2907 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2908 const AttributedType *AT = T->getAs<AttributedType>(); 2909 while (AT && !AT->isCallingConv()) 2910 AT = AT->getModifiedType()->getAs<AttributedType>(); 2911 return AT; 2912 } 2913 2914 template <typename T> 2915 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2916 const DeclContext *DC = Old->getDeclContext(); 2917 if (DC->isRecord()) 2918 return false; 2919 2920 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2921 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2922 return true; 2923 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2924 return true; 2925 return false; 2926 } 2927 2928 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2929 static bool isExternC(VarTemplateDecl *) { return false; } 2930 2931 /// Check whether a redeclaration of an entity introduced by a 2932 /// using-declaration is valid, given that we know it's not an overload 2933 /// (nor a hidden tag declaration). 2934 template<typename ExpectedDecl> 2935 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2936 ExpectedDecl *New) { 2937 // C++11 [basic.scope.declarative]p4: 2938 // Given a set of declarations in a single declarative region, each of 2939 // which specifies the same unqualified name, 2940 // -- they shall all refer to the same entity, or all refer to functions 2941 // and function templates; or 2942 // -- exactly one declaration shall declare a class name or enumeration 2943 // name that is not a typedef name and the other declarations shall all 2944 // refer to the same variable or enumerator, or all refer to functions 2945 // and function templates; in this case the class name or enumeration 2946 // name is hidden (3.3.10). 2947 2948 // C++11 [namespace.udecl]p14: 2949 // If a function declaration in namespace scope or block scope has the 2950 // same name and the same parameter-type-list as a function introduced 2951 // by a using-declaration, and the declarations do not declare the same 2952 // function, the program is ill-formed. 2953 2954 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2955 if (Old && 2956 !Old->getDeclContext()->getRedeclContext()->Equals( 2957 New->getDeclContext()->getRedeclContext()) && 2958 !(isExternC(Old) && isExternC(New))) 2959 Old = nullptr; 2960 2961 if (!Old) { 2962 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2963 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2964 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2965 return true; 2966 } 2967 return false; 2968 } 2969 2970 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2971 const FunctionDecl *B) { 2972 assert(A->getNumParams() == B->getNumParams()); 2973 2974 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2975 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2976 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2977 if (AttrA == AttrB) 2978 return true; 2979 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 2980 AttrA->isDynamic() == AttrB->isDynamic(); 2981 }; 2982 2983 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2984 } 2985 2986 /// If necessary, adjust the semantic declaration context for a qualified 2987 /// declaration to name the correct inline namespace within the qualifier. 2988 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 2989 DeclaratorDecl *OldD) { 2990 // The only case where we need to update the DeclContext is when 2991 // redeclaration lookup for a qualified name finds a declaration 2992 // in an inline namespace within the context named by the qualifier: 2993 // 2994 // inline namespace N { int f(); } 2995 // int ::f(); // Sema DC needs adjusting from :: to N::. 2996 // 2997 // For unqualified declarations, the semantic context *can* change 2998 // along the redeclaration chain (for local extern declarations, 2999 // extern "C" declarations, and friend declarations in particular). 3000 if (!NewD->getQualifier()) 3001 return; 3002 3003 // NewD is probably already in the right context. 3004 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3005 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3006 if (NamedDC->Equals(SemaDC)) 3007 return; 3008 3009 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3010 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3011 "unexpected context for redeclaration"); 3012 3013 auto *LexDC = NewD->getLexicalDeclContext(); 3014 auto FixSemaDC = [=](NamedDecl *D) { 3015 if (!D) 3016 return; 3017 D->setDeclContext(SemaDC); 3018 D->setLexicalDeclContext(LexDC); 3019 }; 3020 3021 FixSemaDC(NewD); 3022 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3023 FixSemaDC(FD->getDescribedFunctionTemplate()); 3024 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3025 FixSemaDC(VD->getDescribedVarTemplate()); 3026 } 3027 3028 /// MergeFunctionDecl - We just parsed a function 'New' from 3029 /// declarator D which has the same name and scope as a previous 3030 /// declaration 'Old'. Figure out how to resolve this situation, 3031 /// merging decls or emitting diagnostics as appropriate. 3032 /// 3033 /// In C++, New and Old must be declarations that are not 3034 /// overloaded. Use IsOverload to determine whether New and Old are 3035 /// overloaded, and to select the Old declaration that New should be 3036 /// merged with. 3037 /// 3038 /// Returns true if there was an error, false otherwise. 3039 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3040 Scope *S, bool MergeTypeWithOld) { 3041 // Verify the old decl was also a function. 3042 FunctionDecl *Old = OldD->getAsFunction(); 3043 if (!Old) { 3044 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3045 if (New->getFriendObjectKind()) { 3046 Diag(New->getLocation(), diag::err_using_decl_friend); 3047 Diag(Shadow->getTargetDecl()->getLocation(), 3048 diag::note_using_decl_target); 3049 Diag(Shadow->getUsingDecl()->getLocation(), 3050 diag::note_using_decl) << 0; 3051 return true; 3052 } 3053 3054 // Check whether the two declarations might declare the same function. 3055 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3056 return true; 3057 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3058 } else { 3059 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3060 << New->getDeclName(); 3061 notePreviousDefinition(OldD, New->getLocation()); 3062 return true; 3063 } 3064 } 3065 3066 // If the old declaration is invalid, just give up here. 3067 if (Old->isInvalidDecl()) 3068 return true; 3069 3070 // Disallow redeclaration of some builtins. 3071 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3072 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3073 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3074 << Old << Old->getType(); 3075 return true; 3076 } 3077 3078 diag::kind PrevDiag; 3079 SourceLocation OldLocation; 3080 std::tie(PrevDiag, OldLocation) = 3081 getNoteDiagForInvalidRedeclaration(Old, New); 3082 3083 // Don't complain about this if we're in GNU89 mode and the old function 3084 // is an extern inline function. 3085 // Don't complain about specializations. They are not supposed to have 3086 // storage classes. 3087 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3088 New->getStorageClass() == SC_Static && 3089 Old->hasExternalFormalLinkage() && 3090 !New->getTemplateSpecializationInfo() && 3091 !canRedefineFunction(Old, getLangOpts())) { 3092 if (getLangOpts().MicrosoftExt) { 3093 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3094 Diag(OldLocation, PrevDiag); 3095 } else { 3096 Diag(New->getLocation(), diag::err_static_non_static) << New; 3097 Diag(OldLocation, PrevDiag); 3098 return true; 3099 } 3100 } 3101 3102 if (New->hasAttr<InternalLinkageAttr>() && 3103 !Old->hasAttr<InternalLinkageAttr>()) { 3104 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3105 << New->getDeclName(); 3106 notePreviousDefinition(Old, New->getLocation()); 3107 New->dropAttr<InternalLinkageAttr>(); 3108 } 3109 3110 if (CheckRedeclarationModuleOwnership(New, Old)) 3111 return true; 3112 3113 if (!getLangOpts().CPlusPlus) { 3114 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3115 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3116 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3117 << New << OldOvl; 3118 3119 // Try our best to find a decl that actually has the overloadable 3120 // attribute for the note. In most cases (e.g. programs with only one 3121 // broken declaration/definition), this won't matter. 3122 // 3123 // FIXME: We could do this if we juggled some extra state in 3124 // OverloadableAttr, rather than just removing it. 3125 const Decl *DiagOld = Old; 3126 if (OldOvl) { 3127 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3128 const auto *A = D->getAttr<OverloadableAttr>(); 3129 return A && !A->isImplicit(); 3130 }); 3131 // If we've implicitly added *all* of the overloadable attrs to this 3132 // chain, emitting a "previous redecl" note is pointless. 3133 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3134 } 3135 3136 if (DiagOld) 3137 Diag(DiagOld->getLocation(), 3138 diag::note_attribute_overloadable_prev_overload) 3139 << OldOvl; 3140 3141 if (OldOvl) 3142 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3143 else 3144 New->dropAttr<OverloadableAttr>(); 3145 } 3146 } 3147 3148 // If a function is first declared with a calling convention, but is later 3149 // declared or defined without one, all following decls assume the calling 3150 // convention of the first. 3151 // 3152 // It's OK if a function is first declared without a calling convention, 3153 // but is later declared or defined with the default calling convention. 3154 // 3155 // To test if either decl has an explicit calling convention, we look for 3156 // AttributedType sugar nodes on the type as written. If they are missing or 3157 // were canonicalized away, we assume the calling convention was implicit. 3158 // 3159 // Note also that we DO NOT return at this point, because we still have 3160 // other tests to run. 3161 QualType OldQType = Context.getCanonicalType(Old->getType()); 3162 QualType NewQType = Context.getCanonicalType(New->getType()); 3163 const FunctionType *OldType = cast<FunctionType>(OldQType); 3164 const FunctionType *NewType = cast<FunctionType>(NewQType); 3165 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3166 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3167 bool RequiresAdjustment = false; 3168 3169 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3170 FunctionDecl *First = Old->getFirstDecl(); 3171 const FunctionType *FT = 3172 First->getType().getCanonicalType()->castAs<FunctionType>(); 3173 FunctionType::ExtInfo FI = FT->getExtInfo(); 3174 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3175 if (!NewCCExplicit) { 3176 // Inherit the CC from the previous declaration if it was specified 3177 // there but not here. 3178 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3179 RequiresAdjustment = true; 3180 } else if (New->getBuiltinID()) { 3181 // Calling Conventions on a Builtin aren't really useful and setting a 3182 // default calling convention and cdecl'ing some builtin redeclarations is 3183 // common, so warn and ignore the calling convention on the redeclaration. 3184 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3185 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3186 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3187 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3188 RequiresAdjustment = true; 3189 } else { 3190 // Calling conventions aren't compatible, so complain. 3191 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3192 Diag(New->getLocation(), diag::err_cconv_change) 3193 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3194 << !FirstCCExplicit 3195 << (!FirstCCExplicit ? "" : 3196 FunctionType::getNameForCallConv(FI.getCC())); 3197 3198 // Put the note on the first decl, since it is the one that matters. 3199 Diag(First->getLocation(), diag::note_previous_declaration); 3200 return true; 3201 } 3202 } 3203 3204 // FIXME: diagnose the other way around? 3205 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3206 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3207 RequiresAdjustment = true; 3208 } 3209 3210 // Merge regparm attribute. 3211 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3212 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3213 if (NewTypeInfo.getHasRegParm()) { 3214 Diag(New->getLocation(), diag::err_regparm_mismatch) 3215 << NewType->getRegParmType() 3216 << OldType->getRegParmType(); 3217 Diag(OldLocation, diag::note_previous_declaration); 3218 return true; 3219 } 3220 3221 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3222 RequiresAdjustment = true; 3223 } 3224 3225 // Merge ns_returns_retained attribute. 3226 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3227 if (NewTypeInfo.getProducesResult()) { 3228 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3229 << "'ns_returns_retained'"; 3230 Diag(OldLocation, diag::note_previous_declaration); 3231 return true; 3232 } 3233 3234 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3235 RequiresAdjustment = true; 3236 } 3237 3238 if (OldTypeInfo.getNoCallerSavedRegs() != 3239 NewTypeInfo.getNoCallerSavedRegs()) { 3240 if (NewTypeInfo.getNoCallerSavedRegs()) { 3241 AnyX86NoCallerSavedRegistersAttr *Attr = 3242 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3243 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3244 Diag(OldLocation, diag::note_previous_declaration); 3245 return true; 3246 } 3247 3248 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3249 RequiresAdjustment = true; 3250 } 3251 3252 if (RequiresAdjustment) { 3253 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3254 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3255 New->setType(QualType(AdjustedType, 0)); 3256 NewQType = Context.getCanonicalType(New->getType()); 3257 } 3258 3259 // If this redeclaration makes the function inline, we may need to add it to 3260 // UndefinedButUsed. 3261 if (!Old->isInlined() && New->isInlined() && 3262 !New->hasAttr<GNUInlineAttr>() && 3263 !getLangOpts().GNUInline && 3264 Old->isUsed(false) && 3265 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3266 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3267 SourceLocation())); 3268 3269 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3270 // about it. 3271 if (New->hasAttr<GNUInlineAttr>() && 3272 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3273 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3274 } 3275 3276 // If pass_object_size params don't match up perfectly, this isn't a valid 3277 // redeclaration. 3278 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3279 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3280 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3281 << New->getDeclName(); 3282 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3283 return true; 3284 } 3285 3286 if (getLangOpts().CPlusPlus) { 3287 // C++1z [over.load]p2 3288 // Certain function declarations cannot be overloaded: 3289 // -- Function declarations that differ only in the return type, 3290 // the exception specification, or both cannot be overloaded. 3291 3292 // Check the exception specifications match. This may recompute the type of 3293 // both Old and New if it resolved exception specifications, so grab the 3294 // types again after this. Because this updates the type, we do this before 3295 // any of the other checks below, which may update the "de facto" NewQType 3296 // but do not necessarily update the type of New. 3297 if (CheckEquivalentExceptionSpec(Old, New)) 3298 return true; 3299 OldQType = Context.getCanonicalType(Old->getType()); 3300 NewQType = Context.getCanonicalType(New->getType()); 3301 3302 // Go back to the type source info to compare the declared return types, 3303 // per C++1y [dcl.type.auto]p13: 3304 // Redeclarations or specializations of a function or function template 3305 // with a declared return type that uses a placeholder type shall also 3306 // use that placeholder, not a deduced type. 3307 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3308 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3309 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3310 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3311 OldDeclaredReturnType)) { 3312 QualType ResQT; 3313 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3314 OldDeclaredReturnType->isObjCObjectPointerType()) 3315 // FIXME: This does the wrong thing for a deduced return type. 3316 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3317 if (ResQT.isNull()) { 3318 if (New->isCXXClassMember() && New->isOutOfLine()) 3319 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3320 << New << New->getReturnTypeSourceRange(); 3321 else 3322 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3323 << New->getReturnTypeSourceRange(); 3324 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3325 << Old->getReturnTypeSourceRange(); 3326 return true; 3327 } 3328 else 3329 NewQType = ResQT; 3330 } 3331 3332 QualType OldReturnType = OldType->getReturnType(); 3333 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3334 if (OldReturnType != NewReturnType) { 3335 // If this function has a deduced return type and has already been 3336 // defined, copy the deduced value from the old declaration. 3337 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3338 if (OldAT && OldAT->isDeduced()) { 3339 New->setType( 3340 SubstAutoType(New->getType(), 3341 OldAT->isDependentType() ? Context.DependentTy 3342 : OldAT->getDeducedType())); 3343 NewQType = Context.getCanonicalType( 3344 SubstAutoType(NewQType, 3345 OldAT->isDependentType() ? Context.DependentTy 3346 : OldAT->getDeducedType())); 3347 } 3348 } 3349 3350 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3351 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3352 if (OldMethod && NewMethod) { 3353 // Preserve triviality. 3354 NewMethod->setTrivial(OldMethod->isTrivial()); 3355 3356 // MSVC allows explicit template specialization at class scope: 3357 // 2 CXXMethodDecls referring to the same function will be injected. 3358 // We don't want a redeclaration error. 3359 bool IsClassScopeExplicitSpecialization = 3360 OldMethod->isFunctionTemplateSpecialization() && 3361 NewMethod->isFunctionTemplateSpecialization(); 3362 bool isFriend = NewMethod->getFriendObjectKind(); 3363 3364 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3365 !IsClassScopeExplicitSpecialization) { 3366 // -- Member function declarations with the same name and the 3367 // same parameter types cannot be overloaded if any of them 3368 // is a static member function declaration. 3369 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3370 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3371 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3372 return true; 3373 } 3374 3375 // C++ [class.mem]p1: 3376 // [...] A member shall not be declared twice in the 3377 // member-specification, except that a nested class or member 3378 // class template can be declared and then later defined. 3379 if (!inTemplateInstantiation()) { 3380 unsigned NewDiag; 3381 if (isa<CXXConstructorDecl>(OldMethod)) 3382 NewDiag = diag::err_constructor_redeclared; 3383 else if (isa<CXXDestructorDecl>(NewMethod)) 3384 NewDiag = diag::err_destructor_redeclared; 3385 else if (isa<CXXConversionDecl>(NewMethod)) 3386 NewDiag = diag::err_conv_function_redeclared; 3387 else 3388 NewDiag = diag::err_member_redeclared; 3389 3390 Diag(New->getLocation(), NewDiag); 3391 } else { 3392 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3393 << New << New->getType(); 3394 } 3395 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3396 return true; 3397 3398 // Complain if this is an explicit declaration of a special 3399 // member that was initially declared implicitly. 3400 // 3401 // As an exception, it's okay to befriend such methods in order 3402 // to permit the implicit constructor/destructor/operator calls. 3403 } else if (OldMethod->isImplicit()) { 3404 if (isFriend) { 3405 NewMethod->setImplicit(); 3406 } else { 3407 Diag(NewMethod->getLocation(), 3408 diag::err_definition_of_implicitly_declared_member) 3409 << New << getSpecialMember(OldMethod); 3410 return true; 3411 } 3412 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3413 Diag(NewMethod->getLocation(), 3414 diag::err_definition_of_explicitly_defaulted_member) 3415 << getSpecialMember(OldMethod); 3416 return true; 3417 } 3418 } 3419 3420 // C++11 [dcl.attr.noreturn]p1: 3421 // The first declaration of a function shall specify the noreturn 3422 // attribute if any declaration of that function specifies the noreturn 3423 // attribute. 3424 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3425 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3426 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3427 Diag(Old->getFirstDecl()->getLocation(), 3428 diag::note_noreturn_missing_first_decl); 3429 } 3430 3431 // C++11 [dcl.attr.depend]p2: 3432 // The first declaration of a function shall specify the 3433 // carries_dependency attribute for its declarator-id if any declaration 3434 // of the function specifies the carries_dependency attribute. 3435 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3436 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3437 Diag(CDA->getLocation(), 3438 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3439 Diag(Old->getFirstDecl()->getLocation(), 3440 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3441 } 3442 3443 // (C++98 8.3.5p3): 3444 // All declarations for a function shall agree exactly in both the 3445 // return type and the parameter-type-list. 3446 // We also want to respect all the extended bits except noreturn. 3447 3448 // noreturn should now match unless the old type info didn't have it. 3449 QualType OldQTypeForComparison = OldQType; 3450 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3451 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3452 const FunctionType *OldTypeForComparison 3453 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3454 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3455 assert(OldQTypeForComparison.isCanonical()); 3456 } 3457 3458 if (haveIncompatibleLanguageLinkages(Old, New)) { 3459 // As a special case, retain the language linkage from previous 3460 // declarations of a friend function as an extension. 3461 // 3462 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3463 // and is useful because there's otherwise no way to specify language 3464 // linkage within class scope. 3465 // 3466 // Check cautiously as the friend object kind isn't yet complete. 3467 if (New->getFriendObjectKind() != Decl::FOK_None) { 3468 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3469 Diag(OldLocation, PrevDiag); 3470 } else { 3471 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3472 Diag(OldLocation, PrevDiag); 3473 return true; 3474 } 3475 } 3476 3477 if (OldQTypeForComparison == NewQType) 3478 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3479 3480 // If the types are imprecise (due to dependent constructs in friends or 3481 // local extern declarations), it's OK if they differ. We'll check again 3482 // during instantiation. 3483 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3484 return false; 3485 3486 // Fall through for conflicting redeclarations and redefinitions. 3487 } 3488 3489 // C: Function types need to be compatible, not identical. This handles 3490 // duplicate function decls like "void f(int); void f(enum X);" properly. 3491 if (!getLangOpts().CPlusPlus && 3492 Context.typesAreCompatible(OldQType, NewQType)) { 3493 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3494 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3495 const FunctionProtoType *OldProto = nullptr; 3496 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3497 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3498 // The old declaration provided a function prototype, but the 3499 // new declaration does not. Merge in the prototype. 3500 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3501 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3502 NewQType = 3503 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3504 OldProto->getExtProtoInfo()); 3505 New->setType(NewQType); 3506 New->setHasInheritedPrototype(); 3507 3508 // Synthesize parameters with the same types. 3509 SmallVector<ParmVarDecl*, 16> Params; 3510 for (const auto &ParamType : OldProto->param_types()) { 3511 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3512 SourceLocation(), nullptr, 3513 ParamType, /*TInfo=*/nullptr, 3514 SC_None, nullptr); 3515 Param->setScopeInfo(0, Params.size()); 3516 Param->setImplicit(); 3517 Params.push_back(Param); 3518 } 3519 3520 New->setParams(Params); 3521 } 3522 3523 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3524 } 3525 3526 // GNU C permits a K&R definition to follow a prototype declaration 3527 // if the declared types of the parameters in the K&R definition 3528 // match the types in the prototype declaration, even when the 3529 // promoted types of the parameters from the K&R definition differ 3530 // from the types in the prototype. GCC then keeps the types from 3531 // the prototype. 3532 // 3533 // If a variadic prototype is followed by a non-variadic K&R definition, 3534 // the K&R definition becomes variadic. This is sort of an edge case, but 3535 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3536 // C99 6.9.1p8. 3537 if (!getLangOpts().CPlusPlus && 3538 Old->hasPrototype() && !New->hasPrototype() && 3539 New->getType()->getAs<FunctionProtoType>() && 3540 Old->getNumParams() == New->getNumParams()) { 3541 SmallVector<QualType, 16> ArgTypes; 3542 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3543 const FunctionProtoType *OldProto 3544 = Old->getType()->getAs<FunctionProtoType>(); 3545 const FunctionProtoType *NewProto 3546 = New->getType()->getAs<FunctionProtoType>(); 3547 3548 // Determine whether this is the GNU C extension. 3549 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3550 NewProto->getReturnType()); 3551 bool LooseCompatible = !MergedReturn.isNull(); 3552 for (unsigned Idx = 0, End = Old->getNumParams(); 3553 LooseCompatible && Idx != End; ++Idx) { 3554 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3555 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3556 if (Context.typesAreCompatible(OldParm->getType(), 3557 NewProto->getParamType(Idx))) { 3558 ArgTypes.push_back(NewParm->getType()); 3559 } else if (Context.typesAreCompatible(OldParm->getType(), 3560 NewParm->getType(), 3561 /*CompareUnqualified=*/true)) { 3562 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3563 NewProto->getParamType(Idx) }; 3564 Warnings.push_back(Warn); 3565 ArgTypes.push_back(NewParm->getType()); 3566 } else 3567 LooseCompatible = false; 3568 } 3569 3570 if (LooseCompatible) { 3571 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3572 Diag(Warnings[Warn].NewParm->getLocation(), 3573 diag::ext_param_promoted_not_compatible_with_prototype) 3574 << Warnings[Warn].PromotedType 3575 << Warnings[Warn].OldParm->getType(); 3576 if (Warnings[Warn].OldParm->getLocation().isValid()) 3577 Diag(Warnings[Warn].OldParm->getLocation(), 3578 diag::note_previous_declaration); 3579 } 3580 3581 if (MergeTypeWithOld) 3582 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3583 OldProto->getExtProtoInfo())); 3584 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3585 } 3586 3587 // Fall through to diagnose conflicting types. 3588 } 3589 3590 // A function that has already been declared has been redeclared or 3591 // defined with a different type; show an appropriate diagnostic. 3592 3593 // If the previous declaration was an implicitly-generated builtin 3594 // declaration, then at the very least we should use a specialized note. 3595 unsigned BuiltinID; 3596 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3597 // If it's actually a library-defined builtin function like 'malloc' 3598 // or 'printf', just warn about the incompatible redeclaration. 3599 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3600 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3601 Diag(OldLocation, diag::note_previous_builtin_declaration) 3602 << Old << Old->getType(); 3603 3604 // If this is a global redeclaration, just forget hereafter 3605 // about the "builtin-ness" of the function. 3606 // 3607 // Doing this for local extern declarations is problematic. If 3608 // the builtin declaration remains visible, a second invalid 3609 // local declaration will produce a hard error; if it doesn't 3610 // remain visible, a single bogus local redeclaration (which is 3611 // actually only a warning) could break all the downstream code. 3612 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3613 New->getIdentifier()->revertBuiltin(); 3614 3615 return false; 3616 } 3617 3618 PrevDiag = diag::note_previous_builtin_declaration; 3619 } 3620 3621 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3622 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3623 return true; 3624 } 3625 3626 /// Completes the merge of two function declarations that are 3627 /// known to be compatible. 3628 /// 3629 /// This routine handles the merging of attributes and other 3630 /// properties of function declarations from the old declaration to 3631 /// the new declaration, once we know that New is in fact a 3632 /// redeclaration of Old. 3633 /// 3634 /// \returns false 3635 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3636 Scope *S, bool MergeTypeWithOld) { 3637 // Merge the attributes 3638 mergeDeclAttributes(New, Old); 3639 3640 // Merge "pure" flag. 3641 if (Old->isPure()) 3642 New->setPure(); 3643 3644 // Merge "used" flag. 3645 if (Old->getMostRecentDecl()->isUsed(false)) 3646 New->setIsUsed(); 3647 3648 // Merge attributes from the parameters. These can mismatch with K&R 3649 // declarations. 3650 if (New->getNumParams() == Old->getNumParams()) 3651 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3652 ParmVarDecl *NewParam = New->getParamDecl(i); 3653 ParmVarDecl *OldParam = Old->getParamDecl(i); 3654 mergeParamDeclAttributes(NewParam, OldParam, *this); 3655 mergeParamDeclTypes(NewParam, OldParam, *this); 3656 } 3657 3658 if (getLangOpts().CPlusPlus) 3659 return MergeCXXFunctionDecl(New, Old, S); 3660 3661 // Merge the function types so the we get the composite types for the return 3662 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3663 // was visible. 3664 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3665 if (!Merged.isNull() && MergeTypeWithOld) 3666 New->setType(Merged); 3667 3668 return false; 3669 } 3670 3671 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3672 ObjCMethodDecl *oldMethod) { 3673 // Merge the attributes, including deprecated/unavailable 3674 AvailabilityMergeKind MergeKind = 3675 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3676 ? AMK_ProtocolImplementation 3677 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3678 : AMK_Override; 3679 3680 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3681 3682 // Merge attributes from the parameters. 3683 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3684 oe = oldMethod->param_end(); 3685 for (ObjCMethodDecl::param_iterator 3686 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3687 ni != ne && oi != oe; ++ni, ++oi) 3688 mergeParamDeclAttributes(*ni, *oi, *this); 3689 3690 CheckObjCMethodOverride(newMethod, oldMethod); 3691 } 3692 3693 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3694 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3695 3696 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3697 ? diag::err_redefinition_different_type 3698 : diag::err_redeclaration_different_type) 3699 << New->getDeclName() << New->getType() << Old->getType(); 3700 3701 diag::kind PrevDiag; 3702 SourceLocation OldLocation; 3703 std::tie(PrevDiag, OldLocation) 3704 = getNoteDiagForInvalidRedeclaration(Old, New); 3705 S.Diag(OldLocation, PrevDiag); 3706 New->setInvalidDecl(); 3707 } 3708 3709 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3710 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3711 /// emitting diagnostics as appropriate. 3712 /// 3713 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3714 /// to here in AddInitializerToDecl. We can't check them before the initializer 3715 /// is attached. 3716 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3717 bool MergeTypeWithOld) { 3718 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3719 return; 3720 3721 QualType MergedT; 3722 if (getLangOpts().CPlusPlus) { 3723 if (New->getType()->isUndeducedType()) { 3724 // We don't know what the new type is until the initializer is attached. 3725 return; 3726 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3727 // These could still be something that needs exception specs checked. 3728 return MergeVarDeclExceptionSpecs(New, Old); 3729 } 3730 // C++ [basic.link]p10: 3731 // [...] the types specified by all declarations referring to a given 3732 // object or function shall be identical, except that declarations for an 3733 // array object can specify array types that differ by the presence or 3734 // absence of a major array bound (8.3.4). 3735 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3736 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3737 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3738 3739 // We are merging a variable declaration New into Old. If it has an array 3740 // bound, and that bound differs from Old's bound, we should diagnose the 3741 // mismatch. 3742 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3743 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3744 PrevVD = PrevVD->getPreviousDecl()) { 3745 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3746 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3747 continue; 3748 3749 if (!Context.hasSameType(NewArray, PrevVDTy)) 3750 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3751 } 3752 } 3753 3754 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3755 if (Context.hasSameType(OldArray->getElementType(), 3756 NewArray->getElementType())) 3757 MergedT = New->getType(); 3758 } 3759 // FIXME: Check visibility. New is hidden but has a complete type. If New 3760 // has no array bound, it should not inherit one from Old, if Old is not 3761 // visible. 3762 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3763 if (Context.hasSameType(OldArray->getElementType(), 3764 NewArray->getElementType())) 3765 MergedT = Old->getType(); 3766 } 3767 } 3768 else if (New->getType()->isObjCObjectPointerType() && 3769 Old->getType()->isObjCObjectPointerType()) { 3770 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3771 Old->getType()); 3772 } 3773 } else { 3774 // C 6.2.7p2: 3775 // All declarations that refer to the same object or function shall have 3776 // compatible type. 3777 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3778 } 3779 if (MergedT.isNull()) { 3780 // It's OK if we couldn't merge types if either type is dependent, for a 3781 // block-scope variable. In other cases (static data members of class 3782 // templates, variable templates, ...), we require the types to be 3783 // equivalent. 3784 // FIXME: The C++ standard doesn't say anything about this. 3785 if ((New->getType()->isDependentType() || 3786 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3787 // If the old type was dependent, we can't merge with it, so the new type 3788 // becomes dependent for now. We'll reproduce the original type when we 3789 // instantiate the TypeSourceInfo for the variable. 3790 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3791 New->setType(Context.DependentTy); 3792 return; 3793 } 3794 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3795 } 3796 3797 // Don't actually update the type on the new declaration if the old 3798 // declaration was an extern declaration in a different scope. 3799 if (MergeTypeWithOld) 3800 New->setType(MergedT); 3801 } 3802 3803 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3804 LookupResult &Previous) { 3805 // C11 6.2.7p4: 3806 // For an identifier with internal or external linkage declared 3807 // in a scope in which a prior declaration of that identifier is 3808 // visible, if the prior declaration specifies internal or 3809 // external linkage, the type of the identifier at the later 3810 // declaration becomes the composite type. 3811 // 3812 // If the variable isn't visible, we do not merge with its type. 3813 if (Previous.isShadowed()) 3814 return false; 3815 3816 if (S.getLangOpts().CPlusPlus) { 3817 // C++11 [dcl.array]p3: 3818 // If there is a preceding declaration of the entity in the same 3819 // scope in which the bound was specified, an omitted array bound 3820 // is taken to be the same as in that earlier declaration. 3821 return NewVD->isPreviousDeclInSameBlockScope() || 3822 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3823 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3824 } else { 3825 // If the old declaration was function-local, don't merge with its 3826 // type unless we're in the same function. 3827 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3828 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3829 } 3830 } 3831 3832 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3833 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3834 /// situation, merging decls or emitting diagnostics as appropriate. 3835 /// 3836 /// Tentative definition rules (C99 6.9.2p2) are checked by 3837 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3838 /// definitions here, since the initializer hasn't been attached. 3839 /// 3840 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3841 // If the new decl is already invalid, don't do any other checking. 3842 if (New->isInvalidDecl()) 3843 return; 3844 3845 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3846 return; 3847 3848 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3849 3850 // Verify the old decl was also a variable or variable template. 3851 VarDecl *Old = nullptr; 3852 VarTemplateDecl *OldTemplate = nullptr; 3853 if (Previous.isSingleResult()) { 3854 if (NewTemplate) { 3855 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3856 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3857 3858 if (auto *Shadow = 3859 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3860 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3861 return New->setInvalidDecl(); 3862 } else { 3863 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3864 3865 if (auto *Shadow = 3866 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3867 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3868 return New->setInvalidDecl(); 3869 } 3870 } 3871 if (!Old) { 3872 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3873 << New->getDeclName(); 3874 notePreviousDefinition(Previous.getRepresentativeDecl(), 3875 New->getLocation()); 3876 return New->setInvalidDecl(); 3877 } 3878 3879 // Ensure the template parameters are compatible. 3880 if (NewTemplate && 3881 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3882 OldTemplate->getTemplateParameters(), 3883 /*Complain=*/true, TPL_TemplateMatch)) 3884 return New->setInvalidDecl(); 3885 3886 // C++ [class.mem]p1: 3887 // A member shall not be declared twice in the member-specification [...] 3888 // 3889 // Here, we need only consider static data members. 3890 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3891 Diag(New->getLocation(), diag::err_duplicate_member) 3892 << New->getIdentifier(); 3893 Diag(Old->getLocation(), diag::note_previous_declaration); 3894 New->setInvalidDecl(); 3895 } 3896 3897 mergeDeclAttributes(New, Old); 3898 // Warn if an already-declared variable is made a weak_import in a subsequent 3899 // declaration 3900 if (New->hasAttr<WeakImportAttr>() && 3901 Old->getStorageClass() == SC_None && 3902 !Old->hasAttr<WeakImportAttr>()) { 3903 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3904 notePreviousDefinition(Old, New->getLocation()); 3905 // Remove weak_import attribute on new declaration. 3906 New->dropAttr<WeakImportAttr>(); 3907 } 3908 3909 if (New->hasAttr<InternalLinkageAttr>() && 3910 !Old->hasAttr<InternalLinkageAttr>()) { 3911 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3912 << New->getDeclName(); 3913 notePreviousDefinition(Old, New->getLocation()); 3914 New->dropAttr<InternalLinkageAttr>(); 3915 } 3916 3917 // Merge the types. 3918 VarDecl *MostRecent = Old->getMostRecentDecl(); 3919 if (MostRecent != Old) { 3920 MergeVarDeclTypes(New, MostRecent, 3921 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3922 if (New->isInvalidDecl()) 3923 return; 3924 } 3925 3926 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3927 if (New->isInvalidDecl()) 3928 return; 3929 3930 diag::kind PrevDiag; 3931 SourceLocation OldLocation; 3932 std::tie(PrevDiag, OldLocation) = 3933 getNoteDiagForInvalidRedeclaration(Old, New); 3934 3935 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3936 if (New->getStorageClass() == SC_Static && 3937 !New->isStaticDataMember() && 3938 Old->hasExternalFormalLinkage()) { 3939 if (getLangOpts().MicrosoftExt) { 3940 Diag(New->getLocation(), diag::ext_static_non_static) 3941 << New->getDeclName(); 3942 Diag(OldLocation, PrevDiag); 3943 } else { 3944 Diag(New->getLocation(), diag::err_static_non_static) 3945 << New->getDeclName(); 3946 Diag(OldLocation, PrevDiag); 3947 return New->setInvalidDecl(); 3948 } 3949 } 3950 // C99 6.2.2p4: 3951 // For an identifier declared with the storage-class specifier 3952 // extern in a scope in which a prior declaration of that 3953 // identifier is visible,23) if the prior declaration specifies 3954 // internal or external linkage, the linkage of the identifier at 3955 // the later declaration is the same as the linkage specified at 3956 // the prior declaration. If no prior declaration is visible, or 3957 // if the prior declaration specifies no linkage, then the 3958 // identifier has external linkage. 3959 if (New->hasExternalStorage() && Old->hasLinkage()) 3960 /* Okay */; 3961 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3962 !New->isStaticDataMember() && 3963 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3964 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3965 Diag(OldLocation, PrevDiag); 3966 return New->setInvalidDecl(); 3967 } 3968 3969 // Check if extern is followed by non-extern and vice-versa. 3970 if (New->hasExternalStorage() && 3971 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3972 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3973 Diag(OldLocation, PrevDiag); 3974 return New->setInvalidDecl(); 3975 } 3976 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3977 !New->hasExternalStorage()) { 3978 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3979 Diag(OldLocation, PrevDiag); 3980 return New->setInvalidDecl(); 3981 } 3982 3983 if (CheckRedeclarationModuleOwnership(New, Old)) 3984 return; 3985 3986 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3987 3988 // FIXME: The test for external storage here seems wrong? We still 3989 // need to check for mismatches. 3990 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3991 // Don't complain about out-of-line definitions of static members. 3992 !(Old->getLexicalDeclContext()->isRecord() && 3993 !New->getLexicalDeclContext()->isRecord())) { 3994 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3995 Diag(OldLocation, PrevDiag); 3996 return New->setInvalidDecl(); 3997 } 3998 3999 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4000 if (VarDecl *Def = Old->getDefinition()) { 4001 // C++1z [dcl.fcn.spec]p4: 4002 // If the definition of a variable appears in a translation unit before 4003 // its first declaration as inline, the program is ill-formed. 4004 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4005 Diag(Def->getLocation(), diag::note_previous_definition); 4006 } 4007 } 4008 4009 // If this redeclaration makes the variable inline, we may need to add it to 4010 // UndefinedButUsed. 4011 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4012 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4013 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4014 SourceLocation())); 4015 4016 if (New->getTLSKind() != Old->getTLSKind()) { 4017 if (!Old->getTLSKind()) { 4018 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4019 Diag(OldLocation, PrevDiag); 4020 } else if (!New->getTLSKind()) { 4021 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4022 Diag(OldLocation, PrevDiag); 4023 } else { 4024 // Do not allow redeclaration to change the variable between requiring 4025 // static and dynamic initialization. 4026 // FIXME: GCC allows this, but uses the TLS keyword on the first 4027 // declaration to determine the kind. Do we need to be compatible here? 4028 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4029 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4030 Diag(OldLocation, PrevDiag); 4031 } 4032 } 4033 4034 // C++ doesn't have tentative definitions, so go right ahead and check here. 4035 if (getLangOpts().CPlusPlus && 4036 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4037 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4038 Old->getCanonicalDecl()->isConstexpr()) { 4039 // This definition won't be a definition any more once it's been merged. 4040 Diag(New->getLocation(), 4041 diag::warn_deprecated_redundant_constexpr_static_def); 4042 } else if (VarDecl *Def = Old->getDefinition()) { 4043 if (checkVarDeclRedefinition(Def, New)) 4044 return; 4045 } 4046 } 4047 4048 if (haveIncompatibleLanguageLinkages(Old, New)) { 4049 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4050 Diag(OldLocation, PrevDiag); 4051 New->setInvalidDecl(); 4052 return; 4053 } 4054 4055 // Merge "used" flag. 4056 if (Old->getMostRecentDecl()->isUsed(false)) 4057 New->setIsUsed(); 4058 4059 // Keep a chain of previous declarations. 4060 New->setPreviousDecl(Old); 4061 if (NewTemplate) 4062 NewTemplate->setPreviousDecl(OldTemplate); 4063 adjustDeclContextForDeclaratorDecl(New, Old); 4064 4065 // Inherit access appropriately. 4066 New->setAccess(Old->getAccess()); 4067 if (NewTemplate) 4068 NewTemplate->setAccess(New->getAccess()); 4069 4070 if (Old->isInline()) 4071 New->setImplicitlyInline(); 4072 } 4073 4074 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4075 SourceManager &SrcMgr = getSourceManager(); 4076 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4077 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4078 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4079 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4080 auto &HSI = PP.getHeaderSearchInfo(); 4081 StringRef HdrFilename = 4082 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4083 4084 auto noteFromModuleOrInclude = [&](Module *Mod, 4085 SourceLocation IncLoc) -> bool { 4086 // Redefinition errors with modules are common with non modular mapped 4087 // headers, example: a non-modular header H in module A that also gets 4088 // included directly in a TU. Pointing twice to the same header/definition 4089 // is confusing, try to get better diagnostics when modules is on. 4090 if (IncLoc.isValid()) { 4091 if (Mod) { 4092 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4093 << HdrFilename.str() << Mod->getFullModuleName(); 4094 if (!Mod->DefinitionLoc.isInvalid()) 4095 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4096 << Mod->getFullModuleName(); 4097 } else { 4098 Diag(IncLoc, diag::note_redefinition_include_same_file) 4099 << HdrFilename.str(); 4100 } 4101 return true; 4102 } 4103 4104 return false; 4105 }; 4106 4107 // Is it the same file and same offset? Provide more information on why 4108 // this leads to a redefinition error. 4109 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4110 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4111 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4112 bool EmittedDiag = 4113 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4114 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4115 4116 // If the header has no guards, emit a note suggesting one. 4117 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4118 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4119 4120 if (EmittedDiag) 4121 return; 4122 } 4123 4124 // Redefinition coming from different files or couldn't do better above. 4125 if (Old->getLocation().isValid()) 4126 Diag(Old->getLocation(), diag::note_previous_definition); 4127 } 4128 4129 /// We've just determined that \p Old and \p New both appear to be definitions 4130 /// of the same variable. Either diagnose or fix the problem. 4131 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4132 if (!hasVisibleDefinition(Old) && 4133 (New->getFormalLinkage() == InternalLinkage || 4134 New->isInline() || 4135 New->getDescribedVarTemplate() || 4136 New->getNumTemplateParameterLists() || 4137 New->getDeclContext()->isDependentContext())) { 4138 // The previous definition is hidden, and multiple definitions are 4139 // permitted (in separate TUs). Demote this to a declaration. 4140 New->demoteThisDefinitionToDeclaration(); 4141 4142 // Make the canonical definition visible. 4143 if (auto *OldTD = Old->getDescribedVarTemplate()) 4144 makeMergedDefinitionVisible(OldTD); 4145 makeMergedDefinitionVisible(Old); 4146 return false; 4147 } else { 4148 Diag(New->getLocation(), diag::err_redefinition) << New; 4149 notePreviousDefinition(Old, New->getLocation()); 4150 New->setInvalidDecl(); 4151 return true; 4152 } 4153 } 4154 4155 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4156 /// no declarator (e.g. "struct foo;") is parsed. 4157 Decl * 4158 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4159 RecordDecl *&AnonRecord) { 4160 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4161 AnonRecord); 4162 } 4163 4164 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4165 // disambiguate entities defined in different scopes. 4166 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4167 // compatibility. 4168 // We will pick our mangling number depending on which version of MSVC is being 4169 // targeted. 4170 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4171 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4172 ? S->getMSCurManglingNumber() 4173 : S->getMSLastManglingNumber(); 4174 } 4175 4176 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4177 if (!Context.getLangOpts().CPlusPlus) 4178 return; 4179 4180 if (isa<CXXRecordDecl>(Tag->getParent())) { 4181 // If this tag is the direct child of a class, number it if 4182 // it is anonymous. 4183 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4184 return; 4185 MangleNumberingContext &MCtx = 4186 Context.getManglingNumberContext(Tag->getParent()); 4187 Context.setManglingNumber( 4188 Tag, MCtx.getManglingNumber( 4189 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4190 return; 4191 } 4192 4193 // If this tag isn't a direct child of a class, number it if it is local. 4194 Decl *ManglingContextDecl; 4195 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4196 Tag->getDeclContext(), ManglingContextDecl)) { 4197 Context.setManglingNumber( 4198 Tag, MCtx->getManglingNumber( 4199 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4200 } 4201 } 4202 4203 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4204 TypedefNameDecl *NewTD) { 4205 if (TagFromDeclSpec->isInvalidDecl()) 4206 return; 4207 4208 // Do nothing if the tag already has a name for linkage purposes. 4209 if (TagFromDeclSpec->hasNameForLinkage()) 4210 return; 4211 4212 // A well-formed anonymous tag must always be a TUK_Definition. 4213 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4214 4215 // The type must match the tag exactly; no qualifiers allowed. 4216 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4217 Context.getTagDeclType(TagFromDeclSpec))) { 4218 if (getLangOpts().CPlusPlus) 4219 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4220 return; 4221 } 4222 4223 // If we've already computed linkage for the anonymous tag, then 4224 // adding a typedef name for the anonymous decl can change that 4225 // linkage, which might be a serious problem. Diagnose this as 4226 // unsupported and ignore the typedef name. TODO: we should 4227 // pursue this as a language defect and establish a formal rule 4228 // for how to handle it. 4229 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4230 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4231 4232 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4233 tagLoc = getLocForEndOfToken(tagLoc); 4234 4235 llvm::SmallString<40> textToInsert; 4236 textToInsert += ' '; 4237 textToInsert += NewTD->getIdentifier()->getName(); 4238 Diag(tagLoc, diag::note_typedef_changes_linkage) 4239 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4240 return; 4241 } 4242 4243 // Otherwise, set this is the anon-decl typedef for the tag. 4244 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4245 } 4246 4247 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4248 switch (T) { 4249 case DeclSpec::TST_class: 4250 return 0; 4251 case DeclSpec::TST_struct: 4252 return 1; 4253 case DeclSpec::TST_interface: 4254 return 2; 4255 case DeclSpec::TST_union: 4256 return 3; 4257 case DeclSpec::TST_enum: 4258 return 4; 4259 default: 4260 llvm_unreachable("unexpected type specifier"); 4261 } 4262 } 4263 4264 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4265 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4266 /// parameters to cope with template friend declarations. 4267 Decl * 4268 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4269 MultiTemplateParamsArg TemplateParams, 4270 bool IsExplicitInstantiation, 4271 RecordDecl *&AnonRecord) { 4272 Decl *TagD = nullptr; 4273 TagDecl *Tag = nullptr; 4274 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4275 DS.getTypeSpecType() == DeclSpec::TST_struct || 4276 DS.getTypeSpecType() == DeclSpec::TST_interface || 4277 DS.getTypeSpecType() == DeclSpec::TST_union || 4278 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4279 TagD = DS.getRepAsDecl(); 4280 4281 if (!TagD) // We probably had an error 4282 return nullptr; 4283 4284 // Note that the above type specs guarantee that the 4285 // type rep is a Decl, whereas in many of the others 4286 // it's a Type. 4287 if (isa<TagDecl>(TagD)) 4288 Tag = cast<TagDecl>(TagD); 4289 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4290 Tag = CTD->getTemplatedDecl(); 4291 } 4292 4293 if (Tag) { 4294 handleTagNumbering(Tag, S); 4295 Tag->setFreeStanding(); 4296 if (Tag->isInvalidDecl()) 4297 return Tag; 4298 } 4299 4300 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4301 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4302 // or incomplete types shall not be restrict-qualified." 4303 if (TypeQuals & DeclSpec::TQ_restrict) 4304 Diag(DS.getRestrictSpecLoc(), 4305 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4306 << DS.getSourceRange(); 4307 } 4308 4309 if (DS.isInlineSpecified()) 4310 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4311 << getLangOpts().CPlusPlus17; 4312 4313 if (DS.hasConstexprSpecifier()) { 4314 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4315 // and definitions of functions and variables. 4316 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4317 // the declaration of a function or function template 4318 bool IsConsteval = DS.getConstexprSpecifier() == CSK_consteval; 4319 if (Tag) 4320 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4321 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << IsConsteval; 4322 else 4323 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4324 << IsConsteval; 4325 // Don't emit warnings after this error. 4326 return TagD; 4327 } 4328 4329 DiagnoseFunctionSpecifiers(DS); 4330 4331 if (DS.isFriendSpecified()) { 4332 // If we're dealing with a decl but not a TagDecl, assume that 4333 // whatever routines created it handled the friendship aspect. 4334 if (TagD && !Tag) 4335 return nullptr; 4336 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4337 } 4338 4339 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4340 bool IsExplicitSpecialization = 4341 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4342 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4343 !IsExplicitInstantiation && !IsExplicitSpecialization && 4344 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4345 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4346 // nested-name-specifier unless it is an explicit instantiation 4347 // or an explicit specialization. 4348 // 4349 // FIXME: We allow class template partial specializations here too, per the 4350 // obvious intent of DR1819. 4351 // 4352 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4353 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4354 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4355 return nullptr; 4356 } 4357 4358 // Track whether this decl-specifier declares anything. 4359 bool DeclaresAnything = true; 4360 4361 // Handle anonymous struct definitions. 4362 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4363 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4364 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4365 if (getLangOpts().CPlusPlus || 4366 Record->getDeclContext()->isRecord()) { 4367 // If CurContext is a DeclContext that can contain statements, 4368 // RecursiveASTVisitor won't visit the decls that 4369 // BuildAnonymousStructOrUnion() will put into CurContext. 4370 // Also store them here so that they can be part of the 4371 // DeclStmt that gets created in this case. 4372 // FIXME: Also return the IndirectFieldDecls created by 4373 // BuildAnonymousStructOr union, for the same reason? 4374 if (CurContext->isFunctionOrMethod()) 4375 AnonRecord = Record; 4376 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4377 Context.getPrintingPolicy()); 4378 } 4379 4380 DeclaresAnything = false; 4381 } 4382 } 4383 4384 // C11 6.7.2.1p2: 4385 // A struct-declaration that does not declare an anonymous structure or 4386 // anonymous union shall contain a struct-declarator-list. 4387 // 4388 // This rule also existed in C89 and C99; the grammar for struct-declaration 4389 // did not permit a struct-declaration without a struct-declarator-list. 4390 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4391 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4392 // Check for Microsoft C extension: anonymous struct/union member. 4393 // Handle 2 kinds of anonymous struct/union: 4394 // struct STRUCT; 4395 // union UNION; 4396 // and 4397 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4398 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4399 if ((Tag && Tag->getDeclName()) || 4400 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4401 RecordDecl *Record = nullptr; 4402 if (Tag) 4403 Record = dyn_cast<RecordDecl>(Tag); 4404 else if (const RecordType *RT = 4405 DS.getRepAsType().get()->getAsStructureType()) 4406 Record = RT->getDecl(); 4407 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4408 Record = UT->getDecl(); 4409 4410 if (Record && getLangOpts().MicrosoftExt) { 4411 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4412 << Record->isUnion() << DS.getSourceRange(); 4413 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4414 } 4415 4416 DeclaresAnything = false; 4417 } 4418 } 4419 4420 // Skip all the checks below if we have a type error. 4421 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4422 (TagD && TagD->isInvalidDecl())) 4423 return TagD; 4424 4425 if (getLangOpts().CPlusPlus && 4426 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4427 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4428 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4429 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4430 DeclaresAnything = false; 4431 4432 if (!DS.isMissingDeclaratorOk()) { 4433 // Customize diagnostic for a typedef missing a name. 4434 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4435 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4436 << DS.getSourceRange(); 4437 else 4438 DeclaresAnything = false; 4439 } 4440 4441 if (DS.isModulePrivateSpecified() && 4442 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4443 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4444 << Tag->getTagKind() 4445 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4446 4447 ActOnDocumentableDecl(TagD); 4448 4449 // C 6.7/2: 4450 // A declaration [...] shall declare at least a declarator [...], a tag, 4451 // or the members of an enumeration. 4452 // C++ [dcl.dcl]p3: 4453 // [If there are no declarators], and except for the declaration of an 4454 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4455 // names into the program, or shall redeclare a name introduced by a 4456 // previous declaration. 4457 if (!DeclaresAnything) { 4458 // In C, we allow this as a (popular) extension / bug. Don't bother 4459 // producing further diagnostics for redundant qualifiers after this. 4460 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4461 return TagD; 4462 } 4463 4464 // C++ [dcl.stc]p1: 4465 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4466 // init-declarator-list of the declaration shall not be empty. 4467 // C++ [dcl.fct.spec]p1: 4468 // If a cv-qualifier appears in a decl-specifier-seq, the 4469 // init-declarator-list of the declaration shall not be empty. 4470 // 4471 // Spurious qualifiers here appear to be valid in C. 4472 unsigned DiagID = diag::warn_standalone_specifier; 4473 if (getLangOpts().CPlusPlus) 4474 DiagID = diag::ext_standalone_specifier; 4475 4476 // Note that a linkage-specification sets a storage class, but 4477 // 'extern "C" struct foo;' is actually valid and not theoretically 4478 // useless. 4479 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4480 if (SCS == DeclSpec::SCS_mutable) 4481 // Since mutable is not a viable storage class specifier in C, there is 4482 // no reason to treat it as an extension. Instead, diagnose as an error. 4483 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4484 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4485 Diag(DS.getStorageClassSpecLoc(), DiagID) 4486 << DeclSpec::getSpecifierName(SCS); 4487 } 4488 4489 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4490 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4491 << DeclSpec::getSpecifierName(TSCS); 4492 if (DS.getTypeQualifiers()) { 4493 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4494 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4495 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4496 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4497 // Restrict is covered above. 4498 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4499 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4500 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4501 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4502 } 4503 4504 // Warn about ignored type attributes, for example: 4505 // __attribute__((aligned)) struct A; 4506 // Attributes should be placed after tag to apply to type declaration. 4507 if (!DS.getAttributes().empty()) { 4508 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4509 if (TypeSpecType == DeclSpec::TST_class || 4510 TypeSpecType == DeclSpec::TST_struct || 4511 TypeSpecType == DeclSpec::TST_interface || 4512 TypeSpecType == DeclSpec::TST_union || 4513 TypeSpecType == DeclSpec::TST_enum) { 4514 for (const ParsedAttr &AL : DS.getAttributes()) 4515 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4516 << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4517 } 4518 } 4519 4520 return TagD; 4521 } 4522 4523 /// We are trying to inject an anonymous member into the given scope; 4524 /// check if there's an existing declaration that can't be overloaded. 4525 /// 4526 /// \return true if this is a forbidden redeclaration 4527 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4528 Scope *S, 4529 DeclContext *Owner, 4530 DeclarationName Name, 4531 SourceLocation NameLoc, 4532 bool IsUnion) { 4533 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4534 Sema::ForVisibleRedeclaration); 4535 if (!SemaRef.LookupName(R, S)) return false; 4536 4537 // Pick a representative declaration. 4538 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4539 assert(PrevDecl && "Expected a non-null Decl"); 4540 4541 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4542 return false; 4543 4544 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4545 << IsUnion << Name; 4546 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4547 4548 return true; 4549 } 4550 4551 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4552 /// anonymous struct or union AnonRecord into the owning context Owner 4553 /// and scope S. This routine will be invoked just after we realize 4554 /// that an unnamed union or struct is actually an anonymous union or 4555 /// struct, e.g., 4556 /// 4557 /// @code 4558 /// union { 4559 /// int i; 4560 /// float f; 4561 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4562 /// // f into the surrounding scope.x 4563 /// @endcode 4564 /// 4565 /// This routine is recursive, injecting the names of nested anonymous 4566 /// structs/unions into the owning context and scope as well. 4567 static bool 4568 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4569 RecordDecl *AnonRecord, AccessSpecifier AS, 4570 SmallVectorImpl<NamedDecl *> &Chaining) { 4571 bool Invalid = false; 4572 4573 // Look every FieldDecl and IndirectFieldDecl with a name. 4574 for (auto *D : AnonRecord->decls()) { 4575 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4576 cast<NamedDecl>(D)->getDeclName()) { 4577 ValueDecl *VD = cast<ValueDecl>(D); 4578 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4579 VD->getLocation(), 4580 AnonRecord->isUnion())) { 4581 // C++ [class.union]p2: 4582 // The names of the members of an anonymous union shall be 4583 // distinct from the names of any other entity in the 4584 // scope in which the anonymous union is declared. 4585 Invalid = true; 4586 } else { 4587 // C++ [class.union]p2: 4588 // For the purpose of name lookup, after the anonymous union 4589 // definition, the members of the anonymous union are 4590 // considered to have been defined in the scope in which the 4591 // anonymous union is declared. 4592 unsigned OldChainingSize = Chaining.size(); 4593 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4594 Chaining.append(IF->chain_begin(), IF->chain_end()); 4595 else 4596 Chaining.push_back(VD); 4597 4598 assert(Chaining.size() >= 2); 4599 NamedDecl **NamedChain = 4600 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4601 for (unsigned i = 0; i < Chaining.size(); i++) 4602 NamedChain[i] = Chaining[i]; 4603 4604 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4605 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4606 VD->getType(), {NamedChain, Chaining.size()}); 4607 4608 for (const auto *Attr : VD->attrs()) 4609 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4610 4611 IndirectField->setAccess(AS); 4612 IndirectField->setImplicit(); 4613 SemaRef.PushOnScopeChains(IndirectField, S); 4614 4615 // That includes picking up the appropriate access specifier. 4616 if (AS != AS_none) IndirectField->setAccess(AS); 4617 4618 Chaining.resize(OldChainingSize); 4619 } 4620 } 4621 } 4622 4623 return Invalid; 4624 } 4625 4626 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4627 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4628 /// illegal input values are mapped to SC_None. 4629 static StorageClass 4630 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4631 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4632 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4633 "Parser allowed 'typedef' as storage class VarDecl."); 4634 switch (StorageClassSpec) { 4635 case DeclSpec::SCS_unspecified: return SC_None; 4636 case DeclSpec::SCS_extern: 4637 if (DS.isExternInLinkageSpec()) 4638 return SC_None; 4639 return SC_Extern; 4640 case DeclSpec::SCS_static: return SC_Static; 4641 case DeclSpec::SCS_auto: return SC_Auto; 4642 case DeclSpec::SCS_register: return SC_Register; 4643 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4644 // Illegal SCSs map to None: error reporting is up to the caller. 4645 case DeclSpec::SCS_mutable: // Fall through. 4646 case DeclSpec::SCS_typedef: return SC_None; 4647 } 4648 llvm_unreachable("unknown storage class specifier"); 4649 } 4650 4651 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4652 assert(Record->hasInClassInitializer()); 4653 4654 for (const auto *I : Record->decls()) { 4655 const auto *FD = dyn_cast<FieldDecl>(I); 4656 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4657 FD = IFD->getAnonField(); 4658 if (FD && FD->hasInClassInitializer()) 4659 return FD->getLocation(); 4660 } 4661 4662 llvm_unreachable("couldn't find in-class initializer"); 4663 } 4664 4665 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4666 SourceLocation DefaultInitLoc) { 4667 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4668 return; 4669 4670 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4671 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4672 } 4673 4674 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4675 CXXRecordDecl *AnonUnion) { 4676 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4677 return; 4678 4679 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4680 } 4681 4682 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4683 /// anonymous structure or union. Anonymous unions are a C++ feature 4684 /// (C++ [class.union]) and a C11 feature; anonymous structures 4685 /// are a C11 feature and GNU C++ extension. 4686 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4687 AccessSpecifier AS, 4688 RecordDecl *Record, 4689 const PrintingPolicy &Policy) { 4690 DeclContext *Owner = Record->getDeclContext(); 4691 4692 // Diagnose whether this anonymous struct/union is an extension. 4693 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4694 Diag(Record->getLocation(), diag::ext_anonymous_union); 4695 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4696 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4697 else if (!Record->isUnion() && !getLangOpts().C11) 4698 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4699 4700 // C and C++ require different kinds of checks for anonymous 4701 // structs/unions. 4702 bool Invalid = false; 4703 if (getLangOpts().CPlusPlus) { 4704 const char *PrevSpec = nullptr; 4705 if (Record->isUnion()) { 4706 // C++ [class.union]p6: 4707 // C++17 [class.union.anon]p2: 4708 // Anonymous unions declared in a named namespace or in the 4709 // global namespace shall be declared static. 4710 unsigned DiagID; 4711 DeclContext *OwnerScope = Owner->getRedeclContext(); 4712 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4713 (OwnerScope->isTranslationUnit() || 4714 (OwnerScope->isNamespace() && 4715 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4716 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4717 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4718 4719 // Recover by adding 'static'. 4720 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4721 PrevSpec, DiagID, Policy); 4722 } 4723 // C++ [class.union]p6: 4724 // A storage class is not allowed in a declaration of an 4725 // anonymous union in a class scope. 4726 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4727 isa<RecordDecl>(Owner)) { 4728 Diag(DS.getStorageClassSpecLoc(), 4729 diag::err_anonymous_union_with_storage_spec) 4730 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4731 4732 // Recover by removing the storage specifier. 4733 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4734 SourceLocation(), 4735 PrevSpec, DiagID, Context.getPrintingPolicy()); 4736 } 4737 } 4738 4739 // Ignore const/volatile/restrict qualifiers. 4740 if (DS.getTypeQualifiers()) { 4741 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4742 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4743 << Record->isUnion() << "const" 4744 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4745 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4746 Diag(DS.getVolatileSpecLoc(), 4747 diag::ext_anonymous_struct_union_qualified) 4748 << Record->isUnion() << "volatile" 4749 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4750 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4751 Diag(DS.getRestrictSpecLoc(), 4752 diag::ext_anonymous_struct_union_qualified) 4753 << Record->isUnion() << "restrict" 4754 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4755 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4756 Diag(DS.getAtomicSpecLoc(), 4757 diag::ext_anonymous_struct_union_qualified) 4758 << Record->isUnion() << "_Atomic" 4759 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4760 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4761 Diag(DS.getUnalignedSpecLoc(), 4762 diag::ext_anonymous_struct_union_qualified) 4763 << Record->isUnion() << "__unaligned" 4764 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4765 4766 DS.ClearTypeQualifiers(); 4767 } 4768 4769 // C++ [class.union]p2: 4770 // The member-specification of an anonymous union shall only 4771 // define non-static data members. [Note: nested types and 4772 // functions cannot be declared within an anonymous union. ] 4773 for (auto *Mem : Record->decls()) { 4774 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4775 // C++ [class.union]p3: 4776 // An anonymous union shall not have private or protected 4777 // members (clause 11). 4778 assert(FD->getAccess() != AS_none); 4779 if (FD->getAccess() != AS_public) { 4780 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4781 << Record->isUnion() << (FD->getAccess() == AS_protected); 4782 Invalid = true; 4783 } 4784 4785 // C++ [class.union]p1 4786 // An object of a class with a non-trivial constructor, a non-trivial 4787 // copy constructor, a non-trivial destructor, or a non-trivial copy 4788 // assignment operator cannot be a member of a union, nor can an 4789 // array of such objects. 4790 if (CheckNontrivialField(FD)) 4791 Invalid = true; 4792 } else if (Mem->isImplicit()) { 4793 // Any implicit members are fine. 4794 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4795 // This is a type that showed up in an 4796 // elaborated-type-specifier inside the anonymous struct or 4797 // union, but which actually declares a type outside of the 4798 // anonymous struct or union. It's okay. 4799 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4800 if (!MemRecord->isAnonymousStructOrUnion() && 4801 MemRecord->getDeclName()) { 4802 // Visual C++ allows type definition in anonymous struct or union. 4803 if (getLangOpts().MicrosoftExt) 4804 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4805 << Record->isUnion(); 4806 else { 4807 // This is a nested type declaration. 4808 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4809 << Record->isUnion(); 4810 Invalid = true; 4811 } 4812 } else { 4813 // This is an anonymous type definition within another anonymous type. 4814 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4815 // not part of standard C++. 4816 Diag(MemRecord->getLocation(), 4817 diag::ext_anonymous_record_with_anonymous_type) 4818 << Record->isUnion(); 4819 } 4820 } else if (isa<AccessSpecDecl>(Mem)) { 4821 // Any access specifier is fine. 4822 } else if (isa<StaticAssertDecl>(Mem)) { 4823 // In C++1z, static_assert declarations are also fine. 4824 } else { 4825 // We have something that isn't a non-static data 4826 // member. Complain about it. 4827 unsigned DK = diag::err_anonymous_record_bad_member; 4828 if (isa<TypeDecl>(Mem)) 4829 DK = diag::err_anonymous_record_with_type; 4830 else if (isa<FunctionDecl>(Mem)) 4831 DK = diag::err_anonymous_record_with_function; 4832 else if (isa<VarDecl>(Mem)) 4833 DK = diag::err_anonymous_record_with_static; 4834 4835 // Visual C++ allows type definition in anonymous struct or union. 4836 if (getLangOpts().MicrosoftExt && 4837 DK == diag::err_anonymous_record_with_type) 4838 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4839 << Record->isUnion(); 4840 else { 4841 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4842 Invalid = true; 4843 } 4844 } 4845 } 4846 4847 // C++11 [class.union]p8 (DR1460): 4848 // At most one variant member of a union may have a 4849 // brace-or-equal-initializer. 4850 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4851 Owner->isRecord()) 4852 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4853 cast<CXXRecordDecl>(Record)); 4854 } 4855 4856 if (!Record->isUnion() && !Owner->isRecord()) { 4857 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4858 << getLangOpts().CPlusPlus; 4859 Invalid = true; 4860 } 4861 4862 // C++ [dcl.dcl]p3: 4863 // [If there are no declarators], and except for the declaration of an 4864 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4865 // names into the program 4866 // C++ [class.mem]p2: 4867 // each such member-declaration shall either declare at least one member 4868 // name of the class or declare at least one unnamed bit-field 4869 // 4870 // For C this is an error even for a named struct, and is diagnosed elsewhere. 4871 if (getLangOpts().CPlusPlus && Record->field_empty()) 4872 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4873 4874 // Mock up a declarator. 4875 Declarator Dc(DS, DeclaratorContext::MemberContext); 4876 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4877 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4878 4879 // Create a declaration for this anonymous struct/union. 4880 NamedDecl *Anon = nullptr; 4881 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4882 Anon = FieldDecl::Create( 4883 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 4884 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 4885 /*BitWidth=*/nullptr, /*Mutable=*/false, 4886 /*InitStyle=*/ICIS_NoInit); 4887 Anon->setAccess(AS); 4888 if (getLangOpts().CPlusPlus) 4889 FieldCollector->Add(cast<FieldDecl>(Anon)); 4890 } else { 4891 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4892 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4893 if (SCSpec == DeclSpec::SCS_mutable) { 4894 // mutable can only appear on non-static class members, so it's always 4895 // an error here 4896 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4897 Invalid = true; 4898 SC = SC_None; 4899 } 4900 4901 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 4902 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4903 Context.getTypeDeclType(Record), TInfo, SC); 4904 4905 // Default-initialize the implicit variable. This initialization will be 4906 // trivial in almost all cases, except if a union member has an in-class 4907 // initializer: 4908 // union { int n = 0; }; 4909 ActOnUninitializedDecl(Anon); 4910 } 4911 Anon->setImplicit(); 4912 4913 // Mark this as an anonymous struct/union type. 4914 Record->setAnonymousStructOrUnion(true); 4915 4916 // Add the anonymous struct/union object to the current 4917 // context. We'll be referencing this object when we refer to one of 4918 // its members. 4919 Owner->addDecl(Anon); 4920 4921 // Inject the members of the anonymous struct/union into the owning 4922 // context and into the identifier resolver chain for name lookup 4923 // purposes. 4924 SmallVector<NamedDecl*, 2> Chain; 4925 Chain.push_back(Anon); 4926 4927 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4928 Invalid = true; 4929 4930 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4931 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4932 Decl *ManglingContextDecl; 4933 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4934 NewVD->getDeclContext(), ManglingContextDecl)) { 4935 Context.setManglingNumber( 4936 NewVD, MCtx->getManglingNumber( 4937 NewVD, getMSManglingNumber(getLangOpts(), S))); 4938 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4939 } 4940 } 4941 } 4942 4943 if (Invalid) 4944 Anon->setInvalidDecl(); 4945 4946 return Anon; 4947 } 4948 4949 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4950 /// Microsoft C anonymous structure. 4951 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4952 /// Example: 4953 /// 4954 /// struct A { int a; }; 4955 /// struct B { struct A; int b; }; 4956 /// 4957 /// void foo() { 4958 /// B var; 4959 /// var.a = 3; 4960 /// } 4961 /// 4962 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4963 RecordDecl *Record) { 4964 assert(Record && "expected a record!"); 4965 4966 // Mock up a declarator. 4967 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 4968 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4969 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4970 4971 auto *ParentDecl = cast<RecordDecl>(CurContext); 4972 QualType RecTy = Context.getTypeDeclType(Record); 4973 4974 // Create a declaration for this anonymous struct. 4975 NamedDecl *Anon = 4976 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 4977 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 4978 /*BitWidth=*/nullptr, /*Mutable=*/false, 4979 /*InitStyle=*/ICIS_NoInit); 4980 Anon->setImplicit(); 4981 4982 // Add the anonymous struct object to the current context. 4983 CurContext->addDecl(Anon); 4984 4985 // Inject the members of the anonymous struct into the current 4986 // context and into the identifier resolver chain for name lookup 4987 // purposes. 4988 SmallVector<NamedDecl*, 2> Chain; 4989 Chain.push_back(Anon); 4990 4991 RecordDecl *RecordDef = Record->getDefinition(); 4992 if (RequireCompleteType(Anon->getLocation(), RecTy, 4993 diag::err_field_incomplete) || 4994 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4995 AS_none, Chain)) { 4996 Anon->setInvalidDecl(); 4997 ParentDecl->setInvalidDecl(); 4998 } 4999 5000 return Anon; 5001 } 5002 5003 /// GetNameForDeclarator - Determine the full declaration name for the 5004 /// given Declarator. 5005 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5006 return GetNameFromUnqualifiedId(D.getName()); 5007 } 5008 5009 /// Retrieves the declaration name from a parsed unqualified-id. 5010 DeclarationNameInfo 5011 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5012 DeclarationNameInfo NameInfo; 5013 NameInfo.setLoc(Name.StartLocation); 5014 5015 switch (Name.getKind()) { 5016 5017 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5018 case UnqualifiedIdKind::IK_Identifier: 5019 NameInfo.setName(Name.Identifier); 5020 return NameInfo; 5021 5022 case UnqualifiedIdKind::IK_DeductionGuideName: { 5023 // C++ [temp.deduct.guide]p3: 5024 // The simple-template-id shall name a class template specialization. 5025 // The template-name shall be the same identifier as the template-name 5026 // of the simple-template-id. 5027 // These together intend to imply that the template-name shall name a 5028 // class template. 5029 // FIXME: template<typename T> struct X {}; 5030 // template<typename T> using Y = X<T>; 5031 // Y(int) -> Y<int>; 5032 // satisfies these rules but does not name a class template. 5033 TemplateName TN = Name.TemplateName.get().get(); 5034 auto *Template = TN.getAsTemplateDecl(); 5035 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5036 Diag(Name.StartLocation, 5037 diag::err_deduction_guide_name_not_class_template) 5038 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5039 if (Template) 5040 Diag(Template->getLocation(), diag::note_template_decl_here); 5041 return DeclarationNameInfo(); 5042 } 5043 5044 NameInfo.setName( 5045 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5046 return NameInfo; 5047 } 5048 5049 case UnqualifiedIdKind::IK_OperatorFunctionId: 5050 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5051 Name.OperatorFunctionId.Operator)); 5052 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5053 = Name.OperatorFunctionId.SymbolLocations[0]; 5054 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5055 = Name.EndLocation.getRawEncoding(); 5056 return NameInfo; 5057 5058 case UnqualifiedIdKind::IK_LiteralOperatorId: 5059 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5060 Name.Identifier)); 5061 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5062 return NameInfo; 5063 5064 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5065 TypeSourceInfo *TInfo; 5066 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5067 if (Ty.isNull()) 5068 return DeclarationNameInfo(); 5069 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5070 Context.getCanonicalType(Ty))); 5071 NameInfo.setNamedTypeInfo(TInfo); 5072 return NameInfo; 5073 } 5074 5075 case UnqualifiedIdKind::IK_ConstructorName: { 5076 TypeSourceInfo *TInfo; 5077 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5078 if (Ty.isNull()) 5079 return DeclarationNameInfo(); 5080 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5081 Context.getCanonicalType(Ty))); 5082 NameInfo.setNamedTypeInfo(TInfo); 5083 return NameInfo; 5084 } 5085 5086 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5087 // In well-formed code, we can only have a constructor 5088 // template-id that refers to the current context, so go there 5089 // to find the actual type being constructed. 5090 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5091 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5092 return DeclarationNameInfo(); 5093 5094 // Determine the type of the class being constructed. 5095 QualType CurClassType = Context.getTypeDeclType(CurClass); 5096 5097 // FIXME: Check two things: that the template-id names the same type as 5098 // CurClassType, and that the template-id does not occur when the name 5099 // was qualified. 5100 5101 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5102 Context.getCanonicalType(CurClassType))); 5103 // FIXME: should we retrieve TypeSourceInfo? 5104 NameInfo.setNamedTypeInfo(nullptr); 5105 return NameInfo; 5106 } 5107 5108 case UnqualifiedIdKind::IK_DestructorName: { 5109 TypeSourceInfo *TInfo; 5110 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5111 if (Ty.isNull()) 5112 return DeclarationNameInfo(); 5113 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5114 Context.getCanonicalType(Ty))); 5115 NameInfo.setNamedTypeInfo(TInfo); 5116 return NameInfo; 5117 } 5118 5119 case UnqualifiedIdKind::IK_TemplateId: { 5120 TemplateName TName = Name.TemplateId->Template.get(); 5121 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5122 return Context.getNameForTemplate(TName, TNameLoc); 5123 } 5124 5125 } // switch (Name.getKind()) 5126 5127 llvm_unreachable("Unknown name kind"); 5128 } 5129 5130 static QualType getCoreType(QualType Ty) { 5131 do { 5132 if (Ty->isPointerType() || Ty->isReferenceType()) 5133 Ty = Ty->getPointeeType(); 5134 else if (Ty->isArrayType()) 5135 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5136 else 5137 return Ty.withoutLocalFastQualifiers(); 5138 } while (true); 5139 } 5140 5141 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5142 /// and Definition have "nearly" matching parameters. This heuristic is 5143 /// used to improve diagnostics in the case where an out-of-line function 5144 /// definition doesn't match any declaration within the class or namespace. 5145 /// Also sets Params to the list of indices to the parameters that differ 5146 /// between the declaration and the definition. If hasSimilarParameters 5147 /// returns true and Params is empty, then all of the parameters match. 5148 static bool hasSimilarParameters(ASTContext &Context, 5149 FunctionDecl *Declaration, 5150 FunctionDecl *Definition, 5151 SmallVectorImpl<unsigned> &Params) { 5152 Params.clear(); 5153 if (Declaration->param_size() != Definition->param_size()) 5154 return false; 5155 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5156 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5157 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5158 5159 // The parameter types are identical 5160 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5161 continue; 5162 5163 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5164 QualType DefParamBaseTy = getCoreType(DefParamTy); 5165 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5166 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5167 5168 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5169 (DeclTyName && DeclTyName == DefTyName)) 5170 Params.push_back(Idx); 5171 else // The two parameters aren't even close 5172 return false; 5173 } 5174 5175 return true; 5176 } 5177 5178 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5179 /// declarator needs to be rebuilt in the current instantiation. 5180 /// Any bits of declarator which appear before the name are valid for 5181 /// consideration here. That's specifically the type in the decl spec 5182 /// and the base type in any member-pointer chunks. 5183 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5184 DeclarationName Name) { 5185 // The types we specifically need to rebuild are: 5186 // - typenames, typeofs, and decltypes 5187 // - types which will become injected class names 5188 // Of course, we also need to rebuild any type referencing such a 5189 // type. It's safest to just say "dependent", but we call out a 5190 // few cases here. 5191 5192 DeclSpec &DS = D.getMutableDeclSpec(); 5193 switch (DS.getTypeSpecType()) { 5194 case DeclSpec::TST_typename: 5195 case DeclSpec::TST_typeofType: 5196 case DeclSpec::TST_underlyingType: 5197 case DeclSpec::TST_atomic: { 5198 // Grab the type from the parser. 5199 TypeSourceInfo *TSI = nullptr; 5200 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5201 if (T.isNull() || !T->isDependentType()) break; 5202 5203 // Make sure there's a type source info. This isn't really much 5204 // of a waste; most dependent types should have type source info 5205 // attached already. 5206 if (!TSI) 5207 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5208 5209 // Rebuild the type in the current instantiation. 5210 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5211 if (!TSI) return true; 5212 5213 // Store the new type back in the decl spec. 5214 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5215 DS.UpdateTypeRep(LocType); 5216 break; 5217 } 5218 5219 case DeclSpec::TST_decltype: 5220 case DeclSpec::TST_typeofExpr: { 5221 Expr *E = DS.getRepAsExpr(); 5222 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5223 if (Result.isInvalid()) return true; 5224 DS.UpdateExprRep(Result.get()); 5225 break; 5226 } 5227 5228 default: 5229 // Nothing to do for these decl specs. 5230 break; 5231 } 5232 5233 // It doesn't matter what order we do this in. 5234 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5235 DeclaratorChunk &Chunk = D.getTypeObject(I); 5236 5237 // The only type information in the declarator which can come 5238 // before the declaration name is the base type of a member 5239 // pointer. 5240 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5241 continue; 5242 5243 // Rebuild the scope specifier in-place. 5244 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5245 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5246 return true; 5247 } 5248 5249 return false; 5250 } 5251 5252 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5253 D.setFunctionDefinitionKind(FDK_Declaration); 5254 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5255 5256 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5257 Dcl && Dcl->getDeclContext()->isFileContext()) 5258 Dcl->setTopLevelDeclInObjCContainer(); 5259 5260 if (getLangOpts().OpenCL) 5261 setCurrentOpenCLExtensionForDecl(Dcl); 5262 5263 return Dcl; 5264 } 5265 5266 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5267 /// If T is the name of a class, then each of the following shall have a 5268 /// name different from T: 5269 /// - every static data member of class T; 5270 /// - every member function of class T 5271 /// - every member of class T that is itself a type; 5272 /// \returns true if the declaration name violates these rules. 5273 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5274 DeclarationNameInfo NameInfo) { 5275 DeclarationName Name = NameInfo.getName(); 5276 5277 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5278 while (Record && Record->isAnonymousStructOrUnion()) 5279 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5280 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5281 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5282 return true; 5283 } 5284 5285 return false; 5286 } 5287 5288 /// Diagnose a declaration whose declarator-id has the given 5289 /// nested-name-specifier. 5290 /// 5291 /// \param SS The nested-name-specifier of the declarator-id. 5292 /// 5293 /// \param DC The declaration context to which the nested-name-specifier 5294 /// resolves. 5295 /// 5296 /// \param Name The name of the entity being declared. 5297 /// 5298 /// \param Loc The location of the name of the entity being declared. 5299 /// 5300 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5301 /// we're declaring an explicit / partial specialization / instantiation. 5302 /// 5303 /// \returns true if we cannot safely recover from this error, false otherwise. 5304 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5305 DeclarationName Name, 5306 SourceLocation Loc, bool IsTemplateId) { 5307 DeclContext *Cur = CurContext; 5308 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5309 Cur = Cur->getParent(); 5310 5311 // If the user provided a superfluous scope specifier that refers back to the 5312 // class in which the entity is already declared, diagnose and ignore it. 5313 // 5314 // class X { 5315 // void X::f(); 5316 // }; 5317 // 5318 // Note, it was once ill-formed to give redundant qualification in all 5319 // contexts, but that rule was removed by DR482. 5320 if (Cur->Equals(DC)) { 5321 if (Cur->isRecord()) { 5322 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5323 : diag::err_member_extra_qualification) 5324 << Name << FixItHint::CreateRemoval(SS.getRange()); 5325 SS.clear(); 5326 } else { 5327 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5328 } 5329 return false; 5330 } 5331 5332 // Check whether the qualifying scope encloses the scope of the original 5333 // declaration. For a template-id, we perform the checks in 5334 // CheckTemplateSpecializationScope. 5335 if (!Cur->Encloses(DC) && !IsTemplateId) { 5336 if (Cur->isRecord()) 5337 Diag(Loc, diag::err_member_qualification) 5338 << Name << SS.getRange(); 5339 else if (isa<TranslationUnitDecl>(DC)) 5340 Diag(Loc, diag::err_invalid_declarator_global_scope) 5341 << Name << SS.getRange(); 5342 else if (isa<FunctionDecl>(Cur)) 5343 Diag(Loc, diag::err_invalid_declarator_in_function) 5344 << Name << SS.getRange(); 5345 else if (isa<BlockDecl>(Cur)) 5346 Diag(Loc, diag::err_invalid_declarator_in_block) 5347 << Name << SS.getRange(); 5348 else 5349 Diag(Loc, diag::err_invalid_declarator_scope) 5350 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5351 5352 return true; 5353 } 5354 5355 if (Cur->isRecord()) { 5356 // Cannot qualify members within a class. 5357 Diag(Loc, diag::err_member_qualification) 5358 << Name << SS.getRange(); 5359 SS.clear(); 5360 5361 // C++ constructors and destructors with incorrect scopes can break 5362 // our AST invariants by having the wrong underlying types. If 5363 // that's the case, then drop this declaration entirely. 5364 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5365 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5366 !Context.hasSameType(Name.getCXXNameType(), 5367 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5368 return true; 5369 5370 return false; 5371 } 5372 5373 // C++11 [dcl.meaning]p1: 5374 // [...] "The nested-name-specifier of the qualified declarator-id shall 5375 // not begin with a decltype-specifer" 5376 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5377 while (SpecLoc.getPrefix()) 5378 SpecLoc = SpecLoc.getPrefix(); 5379 if (dyn_cast_or_null<DecltypeType>( 5380 SpecLoc.getNestedNameSpecifier()->getAsType())) 5381 Diag(Loc, diag::err_decltype_in_declarator) 5382 << SpecLoc.getTypeLoc().getSourceRange(); 5383 5384 return false; 5385 } 5386 5387 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5388 MultiTemplateParamsArg TemplateParamLists) { 5389 // TODO: consider using NameInfo for diagnostic. 5390 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5391 DeclarationName Name = NameInfo.getName(); 5392 5393 // All of these full declarators require an identifier. If it doesn't have 5394 // one, the ParsedFreeStandingDeclSpec action should be used. 5395 if (D.isDecompositionDeclarator()) { 5396 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5397 } else if (!Name) { 5398 if (!D.isInvalidType()) // Reject this if we think it is valid. 5399 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5400 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5401 return nullptr; 5402 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5403 return nullptr; 5404 5405 // The scope passed in may not be a decl scope. Zip up the scope tree until 5406 // we find one that is. 5407 while ((S->getFlags() & Scope::DeclScope) == 0 || 5408 (S->getFlags() & Scope::TemplateParamScope) != 0) 5409 S = S->getParent(); 5410 5411 DeclContext *DC = CurContext; 5412 if (D.getCXXScopeSpec().isInvalid()) 5413 D.setInvalidType(); 5414 else if (D.getCXXScopeSpec().isSet()) { 5415 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5416 UPPC_DeclarationQualifier)) 5417 return nullptr; 5418 5419 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5420 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5421 if (!DC || isa<EnumDecl>(DC)) { 5422 // If we could not compute the declaration context, it's because the 5423 // declaration context is dependent but does not refer to a class, 5424 // class template, or class template partial specialization. Complain 5425 // and return early, to avoid the coming semantic disaster. 5426 Diag(D.getIdentifierLoc(), 5427 diag::err_template_qualified_declarator_no_match) 5428 << D.getCXXScopeSpec().getScopeRep() 5429 << D.getCXXScopeSpec().getRange(); 5430 return nullptr; 5431 } 5432 bool IsDependentContext = DC->isDependentContext(); 5433 5434 if (!IsDependentContext && 5435 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5436 return nullptr; 5437 5438 // If a class is incomplete, do not parse entities inside it. 5439 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5440 Diag(D.getIdentifierLoc(), 5441 diag::err_member_def_undefined_record) 5442 << Name << DC << D.getCXXScopeSpec().getRange(); 5443 return nullptr; 5444 } 5445 if (!D.getDeclSpec().isFriendSpecified()) { 5446 if (diagnoseQualifiedDeclaration( 5447 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5448 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5449 if (DC->isRecord()) 5450 return nullptr; 5451 5452 D.setInvalidType(); 5453 } 5454 } 5455 5456 // Check whether we need to rebuild the type of the given 5457 // declaration in the current instantiation. 5458 if (EnteringContext && IsDependentContext && 5459 TemplateParamLists.size() != 0) { 5460 ContextRAII SavedContext(*this, DC); 5461 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5462 D.setInvalidType(); 5463 } 5464 } 5465 5466 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5467 QualType R = TInfo->getType(); 5468 5469 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5470 UPPC_DeclarationType)) 5471 D.setInvalidType(); 5472 5473 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5474 forRedeclarationInCurContext()); 5475 5476 // See if this is a redefinition of a variable in the same scope. 5477 if (!D.getCXXScopeSpec().isSet()) { 5478 bool IsLinkageLookup = false; 5479 bool CreateBuiltins = false; 5480 5481 // If the declaration we're planning to build will be a function 5482 // or object with linkage, then look for another declaration with 5483 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5484 // 5485 // If the declaration we're planning to build will be declared with 5486 // external linkage in the translation unit, create any builtin with 5487 // the same name. 5488 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5489 /* Do nothing*/; 5490 else if (CurContext->isFunctionOrMethod() && 5491 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5492 R->isFunctionType())) { 5493 IsLinkageLookup = true; 5494 CreateBuiltins = 5495 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5496 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5497 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5498 CreateBuiltins = true; 5499 5500 if (IsLinkageLookup) { 5501 Previous.clear(LookupRedeclarationWithLinkage); 5502 Previous.setRedeclarationKind(ForExternalRedeclaration); 5503 } 5504 5505 LookupName(Previous, S, CreateBuiltins); 5506 } else { // Something like "int foo::x;" 5507 LookupQualifiedName(Previous, DC); 5508 5509 // C++ [dcl.meaning]p1: 5510 // When the declarator-id is qualified, the declaration shall refer to a 5511 // previously declared member of the class or namespace to which the 5512 // qualifier refers (or, in the case of a namespace, of an element of the 5513 // inline namespace set of that namespace (7.3.1)) or to a specialization 5514 // thereof; [...] 5515 // 5516 // Note that we already checked the context above, and that we do not have 5517 // enough information to make sure that Previous contains the declaration 5518 // we want to match. For example, given: 5519 // 5520 // class X { 5521 // void f(); 5522 // void f(float); 5523 // }; 5524 // 5525 // void X::f(int) { } // ill-formed 5526 // 5527 // In this case, Previous will point to the overload set 5528 // containing the two f's declared in X, but neither of them 5529 // matches. 5530 5531 // C++ [dcl.meaning]p1: 5532 // [...] the member shall not merely have been introduced by a 5533 // using-declaration in the scope of the class or namespace nominated by 5534 // the nested-name-specifier of the declarator-id. 5535 RemoveUsingDecls(Previous); 5536 } 5537 5538 if (Previous.isSingleResult() && 5539 Previous.getFoundDecl()->isTemplateParameter()) { 5540 // Maybe we will complain about the shadowed template parameter. 5541 if (!D.isInvalidType()) 5542 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5543 Previous.getFoundDecl()); 5544 5545 // Just pretend that we didn't see the previous declaration. 5546 Previous.clear(); 5547 } 5548 5549 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5550 // Forget that the previous declaration is the injected-class-name. 5551 Previous.clear(); 5552 5553 // In C++, the previous declaration we find might be a tag type 5554 // (class or enum). In this case, the new declaration will hide the 5555 // tag type. Note that this applies to functions, function templates, and 5556 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5557 if (Previous.isSingleTagDecl() && 5558 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5559 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5560 Previous.clear(); 5561 5562 // Check that there are no default arguments other than in the parameters 5563 // of a function declaration (C++ only). 5564 if (getLangOpts().CPlusPlus) 5565 CheckExtraCXXDefaultArguments(D); 5566 5567 NamedDecl *New; 5568 5569 bool AddToScope = true; 5570 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5571 if (TemplateParamLists.size()) { 5572 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5573 return nullptr; 5574 } 5575 5576 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5577 } else if (R->isFunctionType()) { 5578 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5579 TemplateParamLists, 5580 AddToScope); 5581 } else { 5582 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5583 AddToScope); 5584 } 5585 5586 if (!New) 5587 return nullptr; 5588 5589 // If this has an identifier and is not a function template specialization, 5590 // add it to the scope stack. 5591 if (New->getDeclName() && AddToScope) 5592 PushOnScopeChains(New, S); 5593 5594 if (isInOpenMPDeclareTargetContext()) 5595 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5596 5597 return New; 5598 } 5599 5600 /// Helper method to turn variable array types into constant array 5601 /// types in certain situations which would otherwise be errors (for 5602 /// GCC compatibility). 5603 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5604 ASTContext &Context, 5605 bool &SizeIsNegative, 5606 llvm::APSInt &Oversized) { 5607 // This method tries to turn a variable array into a constant 5608 // array even when the size isn't an ICE. This is necessary 5609 // for compatibility with code that depends on gcc's buggy 5610 // constant expression folding, like struct {char x[(int)(char*)2];} 5611 SizeIsNegative = false; 5612 Oversized = 0; 5613 5614 if (T->isDependentType()) 5615 return QualType(); 5616 5617 QualifierCollector Qs; 5618 const Type *Ty = Qs.strip(T); 5619 5620 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5621 QualType Pointee = PTy->getPointeeType(); 5622 QualType FixedType = 5623 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5624 Oversized); 5625 if (FixedType.isNull()) return FixedType; 5626 FixedType = Context.getPointerType(FixedType); 5627 return Qs.apply(Context, FixedType); 5628 } 5629 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5630 QualType Inner = PTy->getInnerType(); 5631 QualType FixedType = 5632 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5633 Oversized); 5634 if (FixedType.isNull()) return FixedType; 5635 FixedType = Context.getParenType(FixedType); 5636 return Qs.apply(Context, FixedType); 5637 } 5638 5639 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5640 if (!VLATy) 5641 return QualType(); 5642 // FIXME: We should probably handle this case 5643 if (VLATy->getElementType()->isVariablyModifiedType()) 5644 return QualType(); 5645 5646 Expr::EvalResult Result; 5647 if (!VLATy->getSizeExpr() || 5648 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5649 return QualType(); 5650 5651 llvm::APSInt Res = Result.Val.getInt(); 5652 5653 // Check whether the array size is negative. 5654 if (Res.isSigned() && Res.isNegative()) { 5655 SizeIsNegative = true; 5656 return QualType(); 5657 } 5658 5659 // Check whether the array is too large to be addressed. 5660 unsigned ActiveSizeBits 5661 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5662 Res); 5663 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5664 Oversized = Res; 5665 return QualType(); 5666 } 5667 5668 return Context.getConstantArrayType(VLATy->getElementType(), 5669 Res, ArrayType::Normal, 0); 5670 } 5671 5672 static void 5673 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5674 SrcTL = SrcTL.getUnqualifiedLoc(); 5675 DstTL = DstTL.getUnqualifiedLoc(); 5676 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5677 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5678 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5679 DstPTL.getPointeeLoc()); 5680 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5681 return; 5682 } 5683 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5684 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5685 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5686 DstPTL.getInnerLoc()); 5687 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5688 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5689 return; 5690 } 5691 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5692 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5693 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5694 TypeLoc DstElemTL = DstATL.getElementLoc(); 5695 DstElemTL.initializeFullCopy(SrcElemTL); 5696 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5697 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5698 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5699 } 5700 5701 /// Helper method to turn variable array types into constant array 5702 /// types in certain situations which would otherwise be errors (for 5703 /// GCC compatibility). 5704 static TypeSourceInfo* 5705 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5706 ASTContext &Context, 5707 bool &SizeIsNegative, 5708 llvm::APSInt &Oversized) { 5709 QualType FixedTy 5710 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5711 SizeIsNegative, Oversized); 5712 if (FixedTy.isNull()) 5713 return nullptr; 5714 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5715 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5716 FixedTInfo->getTypeLoc()); 5717 return FixedTInfo; 5718 } 5719 5720 /// Register the given locally-scoped extern "C" declaration so 5721 /// that it can be found later for redeclarations. We include any extern "C" 5722 /// declaration that is not visible in the translation unit here, not just 5723 /// function-scope declarations. 5724 void 5725 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5726 if (!getLangOpts().CPlusPlus && 5727 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5728 // Don't need to track declarations in the TU in C. 5729 return; 5730 5731 // Note that we have a locally-scoped external with this name. 5732 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5733 } 5734 5735 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5736 // FIXME: We can have multiple results via __attribute__((overloadable)). 5737 auto Result = Context.getExternCContextDecl()->lookup(Name); 5738 return Result.empty() ? nullptr : *Result.begin(); 5739 } 5740 5741 /// Diagnose function specifiers on a declaration of an identifier that 5742 /// does not identify a function. 5743 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5744 // FIXME: We should probably indicate the identifier in question to avoid 5745 // confusion for constructs like "virtual int a(), b;" 5746 if (DS.isVirtualSpecified()) 5747 Diag(DS.getVirtualSpecLoc(), 5748 diag::err_virtual_non_function); 5749 5750 if (DS.hasExplicitSpecifier()) 5751 Diag(DS.getExplicitSpecLoc(), 5752 diag::err_explicit_non_function); 5753 5754 if (DS.isNoreturnSpecified()) 5755 Diag(DS.getNoreturnSpecLoc(), 5756 diag::err_noreturn_non_function); 5757 } 5758 5759 NamedDecl* 5760 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5761 TypeSourceInfo *TInfo, LookupResult &Previous) { 5762 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5763 if (D.getCXXScopeSpec().isSet()) { 5764 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5765 << D.getCXXScopeSpec().getRange(); 5766 D.setInvalidType(); 5767 // Pretend we didn't see the scope specifier. 5768 DC = CurContext; 5769 Previous.clear(); 5770 } 5771 5772 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5773 5774 if (D.getDeclSpec().isInlineSpecified()) 5775 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5776 << getLangOpts().CPlusPlus17; 5777 if (D.getDeclSpec().hasConstexprSpecifier()) 5778 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5779 << 1 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval); 5780 5781 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 5782 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 5783 Diag(D.getName().StartLocation, 5784 diag::err_deduction_guide_invalid_specifier) 5785 << "typedef"; 5786 else 5787 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5788 << D.getName().getSourceRange(); 5789 return nullptr; 5790 } 5791 5792 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5793 if (!NewTD) return nullptr; 5794 5795 // Handle attributes prior to checking for duplicates in MergeVarDecl 5796 ProcessDeclAttributes(S, NewTD, D); 5797 5798 CheckTypedefForVariablyModifiedType(S, NewTD); 5799 5800 bool Redeclaration = D.isRedeclaration(); 5801 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5802 D.setRedeclaration(Redeclaration); 5803 return ND; 5804 } 5805 5806 void 5807 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5808 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5809 // then it shall have block scope. 5810 // Note that variably modified types must be fixed before merging the decl so 5811 // that redeclarations will match. 5812 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5813 QualType T = TInfo->getType(); 5814 if (T->isVariablyModifiedType()) { 5815 setFunctionHasBranchProtectedScope(); 5816 5817 if (S->getFnParent() == nullptr) { 5818 bool SizeIsNegative; 5819 llvm::APSInt Oversized; 5820 TypeSourceInfo *FixedTInfo = 5821 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5822 SizeIsNegative, 5823 Oversized); 5824 if (FixedTInfo) { 5825 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5826 NewTD->setTypeSourceInfo(FixedTInfo); 5827 } else { 5828 if (SizeIsNegative) 5829 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5830 else if (T->isVariableArrayType()) 5831 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5832 else if (Oversized.getBoolValue()) 5833 Diag(NewTD->getLocation(), diag::err_array_too_large) 5834 << Oversized.toString(10); 5835 else 5836 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5837 NewTD->setInvalidDecl(); 5838 } 5839 } 5840 } 5841 } 5842 5843 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5844 /// declares a typedef-name, either using the 'typedef' type specifier or via 5845 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5846 NamedDecl* 5847 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5848 LookupResult &Previous, bool &Redeclaration) { 5849 5850 // Find the shadowed declaration before filtering for scope. 5851 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5852 5853 // Merge the decl with the existing one if appropriate. If the decl is 5854 // in an outer scope, it isn't the same thing. 5855 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5856 /*AllowInlineNamespace*/false); 5857 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5858 if (!Previous.empty()) { 5859 Redeclaration = true; 5860 MergeTypedefNameDecl(S, NewTD, Previous); 5861 } else { 5862 inferGslPointerAttribute(NewTD); 5863 } 5864 5865 if (ShadowedDecl && !Redeclaration) 5866 CheckShadow(NewTD, ShadowedDecl, Previous); 5867 5868 // If this is the C FILE type, notify the AST context. 5869 if (IdentifierInfo *II = NewTD->getIdentifier()) 5870 if (!NewTD->isInvalidDecl() && 5871 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5872 if (II->isStr("FILE")) 5873 Context.setFILEDecl(NewTD); 5874 else if (II->isStr("jmp_buf")) 5875 Context.setjmp_bufDecl(NewTD); 5876 else if (II->isStr("sigjmp_buf")) 5877 Context.setsigjmp_bufDecl(NewTD); 5878 else if (II->isStr("ucontext_t")) 5879 Context.setucontext_tDecl(NewTD); 5880 } 5881 5882 return NewTD; 5883 } 5884 5885 /// Determines whether the given declaration is an out-of-scope 5886 /// previous declaration. 5887 /// 5888 /// This routine should be invoked when name lookup has found a 5889 /// previous declaration (PrevDecl) that is not in the scope where a 5890 /// new declaration by the same name is being introduced. If the new 5891 /// declaration occurs in a local scope, previous declarations with 5892 /// linkage may still be considered previous declarations (C99 5893 /// 6.2.2p4-5, C++ [basic.link]p6). 5894 /// 5895 /// \param PrevDecl the previous declaration found by name 5896 /// lookup 5897 /// 5898 /// \param DC the context in which the new declaration is being 5899 /// declared. 5900 /// 5901 /// \returns true if PrevDecl is an out-of-scope previous declaration 5902 /// for a new delcaration with the same name. 5903 static bool 5904 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5905 ASTContext &Context) { 5906 if (!PrevDecl) 5907 return false; 5908 5909 if (!PrevDecl->hasLinkage()) 5910 return false; 5911 5912 if (Context.getLangOpts().CPlusPlus) { 5913 // C++ [basic.link]p6: 5914 // If there is a visible declaration of an entity with linkage 5915 // having the same name and type, ignoring entities declared 5916 // outside the innermost enclosing namespace scope, the block 5917 // scope declaration declares that same entity and receives the 5918 // linkage of the previous declaration. 5919 DeclContext *OuterContext = DC->getRedeclContext(); 5920 if (!OuterContext->isFunctionOrMethod()) 5921 // This rule only applies to block-scope declarations. 5922 return false; 5923 5924 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5925 if (PrevOuterContext->isRecord()) 5926 // We found a member function: ignore it. 5927 return false; 5928 5929 // Find the innermost enclosing namespace for the new and 5930 // previous declarations. 5931 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5932 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5933 5934 // The previous declaration is in a different namespace, so it 5935 // isn't the same function. 5936 if (!OuterContext->Equals(PrevOuterContext)) 5937 return false; 5938 } 5939 5940 return true; 5941 } 5942 5943 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 5944 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5945 if (!SS.isSet()) return; 5946 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 5947 } 5948 5949 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5950 QualType type = decl->getType(); 5951 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5952 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5953 // Various kinds of declaration aren't allowed to be __autoreleasing. 5954 unsigned kind = -1U; 5955 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5956 if (var->hasAttr<BlocksAttr>()) 5957 kind = 0; // __block 5958 else if (!var->hasLocalStorage()) 5959 kind = 1; // global 5960 } else if (isa<ObjCIvarDecl>(decl)) { 5961 kind = 3; // ivar 5962 } else if (isa<FieldDecl>(decl)) { 5963 kind = 2; // field 5964 } 5965 5966 if (kind != -1U) { 5967 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5968 << kind; 5969 } 5970 } else if (lifetime == Qualifiers::OCL_None) { 5971 // Try to infer lifetime. 5972 if (!type->isObjCLifetimeType()) 5973 return false; 5974 5975 lifetime = type->getObjCARCImplicitLifetime(); 5976 type = Context.getLifetimeQualifiedType(type, lifetime); 5977 decl->setType(type); 5978 } 5979 5980 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5981 // Thread-local variables cannot have lifetime. 5982 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5983 var->getTLSKind()) { 5984 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5985 << var->getType(); 5986 return true; 5987 } 5988 } 5989 5990 return false; 5991 } 5992 5993 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5994 // Ensure that an auto decl is deduced otherwise the checks below might cache 5995 // the wrong linkage. 5996 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5997 5998 // 'weak' only applies to declarations with external linkage. 5999 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6000 if (!ND.isExternallyVisible()) { 6001 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6002 ND.dropAttr<WeakAttr>(); 6003 } 6004 } 6005 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6006 if (ND.isExternallyVisible()) { 6007 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6008 ND.dropAttr<WeakRefAttr>(); 6009 ND.dropAttr<AliasAttr>(); 6010 } 6011 } 6012 6013 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6014 if (VD->hasInit()) { 6015 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6016 assert(VD->isThisDeclarationADefinition() && 6017 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6018 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6019 VD->dropAttr<AliasAttr>(); 6020 } 6021 } 6022 } 6023 6024 // 'selectany' only applies to externally visible variable declarations. 6025 // It does not apply to functions. 6026 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6027 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6028 S.Diag(Attr->getLocation(), 6029 diag::err_attribute_selectany_non_extern_data); 6030 ND.dropAttr<SelectAnyAttr>(); 6031 } 6032 } 6033 6034 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6035 auto *VD = dyn_cast<VarDecl>(&ND); 6036 bool IsAnonymousNS = false; 6037 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6038 if (VD) { 6039 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6040 while (NS && !IsAnonymousNS) { 6041 IsAnonymousNS = NS->isAnonymousNamespace(); 6042 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6043 } 6044 } 6045 // dll attributes require external linkage. Static locals may have external 6046 // linkage but still cannot be explicitly imported or exported. 6047 // In Microsoft mode, a variable defined in anonymous namespace must have 6048 // external linkage in order to be exported. 6049 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6050 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6051 (!AnonNSInMicrosoftMode && 6052 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6053 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6054 << &ND << Attr; 6055 ND.setInvalidDecl(); 6056 } 6057 } 6058 6059 // Virtual functions cannot be marked as 'notail'. 6060 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6061 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6062 if (MD->isVirtual()) { 6063 S.Diag(ND.getLocation(), 6064 diag::err_invalid_attribute_on_virtual_function) 6065 << Attr; 6066 ND.dropAttr<NotTailCalledAttr>(); 6067 } 6068 6069 // Check the attributes on the function type, if any. 6070 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6071 // Don't declare this variable in the second operand of the for-statement; 6072 // GCC miscompiles that by ending its lifetime before evaluating the 6073 // third operand. See gcc.gnu.org/PR86769. 6074 AttributedTypeLoc ATL; 6075 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6076 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6077 TL = ATL.getModifiedLoc()) { 6078 // The [[lifetimebound]] attribute can be applied to the implicit object 6079 // parameter of a non-static member function (other than a ctor or dtor) 6080 // by applying it to the function type. 6081 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6082 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6083 if (!MD || MD->isStatic()) { 6084 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6085 << !MD << A->getRange(); 6086 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6087 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6088 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6089 } 6090 } 6091 } 6092 } 6093 } 6094 6095 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6096 NamedDecl *NewDecl, 6097 bool IsSpecialization, 6098 bool IsDefinition) { 6099 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6100 return; 6101 6102 bool IsTemplate = false; 6103 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6104 OldDecl = OldTD->getTemplatedDecl(); 6105 IsTemplate = true; 6106 if (!IsSpecialization) 6107 IsDefinition = false; 6108 } 6109 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6110 NewDecl = NewTD->getTemplatedDecl(); 6111 IsTemplate = true; 6112 } 6113 6114 if (!OldDecl || !NewDecl) 6115 return; 6116 6117 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6118 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6119 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6120 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6121 6122 // dllimport and dllexport are inheritable attributes so we have to exclude 6123 // inherited attribute instances. 6124 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6125 (NewExportAttr && !NewExportAttr->isInherited()); 6126 6127 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6128 // the only exception being explicit specializations. 6129 // Implicitly generated declarations are also excluded for now because there 6130 // is no other way to switch these to use dllimport or dllexport. 6131 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6132 6133 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6134 // Allow with a warning for free functions and global variables. 6135 bool JustWarn = false; 6136 if (!OldDecl->isCXXClassMember()) { 6137 auto *VD = dyn_cast<VarDecl>(OldDecl); 6138 if (VD && !VD->getDescribedVarTemplate()) 6139 JustWarn = true; 6140 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6141 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6142 JustWarn = true; 6143 } 6144 6145 // We cannot change a declaration that's been used because IR has already 6146 // been emitted. Dllimported functions will still work though (modulo 6147 // address equality) as they can use the thunk. 6148 if (OldDecl->isUsed()) 6149 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6150 JustWarn = false; 6151 6152 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6153 : diag::err_attribute_dll_redeclaration; 6154 S.Diag(NewDecl->getLocation(), DiagID) 6155 << NewDecl 6156 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6157 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6158 if (!JustWarn) { 6159 NewDecl->setInvalidDecl(); 6160 return; 6161 } 6162 } 6163 6164 // A redeclaration is not allowed to drop a dllimport attribute, the only 6165 // exceptions being inline function definitions (except for function 6166 // templates), local extern declarations, qualified friend declarations or 6167 // special MSVC extension: in the last case, the declaration is treated as if 6168 // it were marked dllexport. 6169 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6170 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6171 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6172 // Ignore static data because out-of-line definitions are diagnosed 6173 // separately. 6174 IsStaticDataMember = VD->isStaticDataMember(); 6175 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6176 VarDecl::DeclarationOnly; 6177 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6178 IsInline = FD->isInlined(); 6179 IsQualifiedFriend = FD->getQualifier() && 6180 FD->getFriendObjectKind() == Decl::FOK_Declared; 6181 } 6182 6183 if (OldImportAttr && !HasNewAttr && 6184 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6185 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6186 if (IsMicrosoft && IsDefinition) { 6187 S.Diag(NewDecl->getLocation(), 6188 diag::warn_redeclaration_without_import_attribute) 6189 << NewDecl; 6190 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6191 NewDecl->dropAttr<DLLImportAttr>(); 6192 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 6193 NewImportAttr->getRange(), S.Context, 6194 NewImportAttr->getSpellingListIndex())); 6195 } else { 6196 S.Diag(NewDecl->getLocation(), 6197 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6198 << NewDecl << OldImportAttr; 6199 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6200 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6201 OldDecl->dropAttr<DLLImportAttr>(); 6202 NewDecl->dropAttr<DLLImportAttr>(); 6203 } 6204 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6205 // In MinGW, seeing a function declared inline drops the dllimport 6206 // attribute. 6207 OldDecl->dropAttr<DLLImportAttr>(); 6208 NewDecl->dropAttr<DLLImportAttr>(); 6209 S.Diag(NewDecl->getLocation(), 6210 diag::warn_dllimport_dropped_from_inline_function) 6211 << NewDecl << OldImportAttr; 6212 } 6213 6214 // A specialization of a class template member function is processed here 6215 // since it's a redeclaration. If the parent class is dllexport, the 6216 // specialization inherits that attribute. This doesn't happen automatically 6217 // since the parent class isn't instantiated until later. 6218 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6219 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6220 !NewImportAttr && !NewExportAttr) { 6221 if (const DLLExportAttr *ParentExportAttr = 6222 MD->getParent()->getAttr<DLLExportAttr>()) { 6223 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6224 NewAttr->setInherited(true); 6225 NewDecl->addAttr(NewAttr); 6226 } 6227 } 6228 } 6229 } 6230 6231 /// Given that we are within the definition of the given function, 6232 /// will that definition behave like C99's 'inline', where the 6233 /// definition is discarded except for optimization purposes? 6234 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6235 // Try to avoid calling GetGVALinkageForFunction. 6236 6237 // All cases of this require the 'inline' keyword. 6238 if (!FD->isInlined()) return false; 6239 6240 // This is only possible in C++ with the gnu_inline attribute. 6241 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6242 return false; 6243 6244 // Okay, go ahead and call the relatively-more-expensive function. 6245 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6246 } 6247 6248 /// Determine whether a variable is extern "C" prior to attaching 6249 /// an initializer. We can't just call isExternC() here, because that 6250 /// will also compute and cache whether the declaration is externally 6251 /// visible, which might change when we attach the initializer. 6252 /// 6253 /// This can only be used if the declaration is known to not be a 6254 /// redeclaration of an internal linkage declaration. 6255 /// 6256 /// For instance: 6257 /// 6258 /// auto x = []{}; 6259 /// 6260 /// Attaching the initializer here makes this declaration not externally 6261 /// visible, because its type has internal linkage. 6262 /// 6263 /// FIXME: This is a hack. 6264 template<typename T> 6265 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6266 if (S.getLangOpts().CPlusPlus) { 6267 // In C++, the overloadable attribute negates the effects of extern "C". 6268 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6269 return false; 6270 6271 // So do CUDA's host/device attributes. 6272 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6273 D->template hasAttr<CUDAHostAttr>())) 6274 return false; 6275 } 6276 return D->isExternC(); 6277 } 6278 6279 static bool shouldConsiderLinkage(const VarDecl *VD) { 6280 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6281 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6282 isa<OMPDeclareMapperDecl>(DC)) 6283 return VD->hasExternalStorage(); 6284 if (DC->isFileContext()) 6285 return true; 6286 if (DC->isRecord()) 6287 return false; 6288 llvm_unreachable("Unexpected context"); 6289 } 6290 6291 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6292 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6293 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6294 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6295 return true; 6296 if (DC->isRecord()) 6297 return false; 6298 llvm_unreachable("Unexpected context"); 6299 } 6300 6301 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6302 ParsedAttr::Kind Kind) { 6303 // Check decl attributes on the DeclSpec. 6304 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6305 return true; 6306 6307 // Walk the declarator structure, checking decl attributes that were in a type 6308 // position to the decl itself. 6309 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6310 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6311 return true; 6312 } 6313 6314 // Finally, check attributes on the decl itself. 6315 return PD.getAttributes().hasAttribute(Kind); 6316 } 6317 6318 /// Adjust the \c DeclContext for a function or variable that might be a 6319 /// function-local external declaration. 6320 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6321 if (!DC->isFunctionOrMethod()) 6322 return false; 6323 6324 // If this is a local extern function or variable declared within a function 6325 // template, don't add it into the enclosing namespace scope until it is 6326 // instantiated; it might have a dependent type right now. 6327 if (DC->isDependentContext()) 6328 return true; 6329 6330 // C++11 [basic.link]p7: 6331 // When a block scope declaration of an entity with linkage is not found to 6332 // refer to some other declaration, then that entity is a member of the 6333 // innermost enclosing namespace. 6334 // 6335 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6336 // semantically-enclosing namespace, not a lexically-enclosing one. 6337 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6338 DC = DC->getParent(); 6339 return true; 6340 } 6341 6342 /// Returns true if given declaration has external C language linkage. 6343 static bool isDeclExternC(const Decl *D) { 6344 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6345 return FD->isExternC(); 6346 if (const auto *VD = dyn_cast<VarDecl>(D)) 6347 return VD->isExternC(); 6348 6349 llvm_unreachable("Unknown type of decl!"); 6350 } 6351 6352 NamedDecl *Sema::ActOnVariableDeclarator( 6353 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6354 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6355 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6356 QualType R = TInfo->getType(); 6357 DeclarationName Name = GetNameForDeclarator(D).getName(); 6358 6359 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6360 6361 if (D.isDecompositionDeclarator()) { 6362 // Take the name of the first declarator as our name for diagnostic 6363 // purposes. 6364 auto &Decomp = D.getDecompositionDeclarator(); 6365 if (!Decomp.bindings().empty()) { 6366 II = Decomp.bindings()[0].Name; 6367 Name = II; 6368 } 6369 } else if (!II) { 6370 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6371 return nullptr; 6372 } 6373 6374 if (getLangOpts().OpenCL) { 6375 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6376 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6377 // argument. 6378 if (R->isImageType() || R->isPipeType()) { 6379 Diag(D.getIdentifierLoc(), 6380 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6381 << R; 6382 D.setInvalidType(); 6383 return nullptr; 6384 } 6385 6386 // OpenCL v1.2 s6.9.r: 6387 // The event type cannot be used to declare a program scope variable. 6388 // OpenCL v2.0 s6.9.q: 6389 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6390 if (NULL == S->getParent()) { 6391 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6392 Diag(D.getIdentifierLoc(), 6393 diag::err_invalid_type_for_program_scope_var) << R; 6394 D.setInvalidType(); 6395 return nullptr; 6396 } 6397 } 6398 6399 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6400 QualType NR = R; 6401 while (NR->isPointerType()) { 6402 if (NR->isFunctionPointerType()) { 6403 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6404 D.setInvalidType(); 6405 break; 6406 } 6407 NR = NR->getPointeeType(); 6408 } 6409 6410 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6411 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6412 // half array type (unless the cl_khr_fp16 extension is enabled). 6413 if (Context.getBaseElementType(R)->isHalfType()) { 6414 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6415 D.setInvalidType(); 6416 } 6417 } 6418 6419 if (R->isSamplerT()) { 6420 // OpenCL v1.2 s6.9.b p4: 6421 // The sampler type cannot be used with the __local and __global address 6422 // space qualifiers. 6423 if (R.getAddressSpace() == LangAS::opencl_local || 6424 R.getAddressSpace() == LangAS::opencl_global) { 6425 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6426 } 6427 6428 // OpenCL v1.2 s6.12.14.1: 6429 // A global sampler must be declared with either the constant address 6430 // space qualifier or with the const qualifier. 6431 if (DC->isTranslationUnit() && 6432 !(R.getAddressSpace() == LangAS::opencl_constant || 6433 R.isConstQualified())) { 6434 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6435 D.setInvalidType(); 6436 } 6437 } 6438 6439 // OpenCL v1.2 s6.9.r: 6440 // The event type cannot be used with the __local, __constant and __global 6441 // address space qualifiers. 6442 if (R->isEventT()) { 6443 if (R.getAddressSpace() != LangAS::opencl_private) { 6444 Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6445 D.setInvalidType(); 6446 } 6447 } 6448 6449 // C++ for OpenCL does not allow the thread_local storage qualifier. 6450 // OpenCL C does not support thread_local either, and 6451 // also reject all other thread storage class specifiers. 6452 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6453 if (TSC != TSCS_unspecified) { 6454 bool IsCXX = getLangOpts().OpenCLCPlusPlus; 6455 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6456 diag::err_opencl_unknown_type_specifier) 6457 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() 6458 << DeclSpec::getSpecifierName(TSC) << 1; 6459 D.setInvalidType(); 6460 return nullptr; 6461 } 6462 } 6463 6464 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6465 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6466 6467 // dllimport globals without explicit storage class are treated as extern. We 6468 // have to change the storage class this early to get the right DeclContext. 6469 if (SC == SC_None && !DC->isRecord() && 6470 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6471 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6472 SC = SC_Extern; 6473 6474 DeclContext *OriginalDC = DC; 6475 bool IsLocalExternDecl = SC == SC_Extern && 6476 adjustContextForLocalExternDecl(DC); 6477 6478 if (SCSpec == DeclSpec::SCS_mutable) { 6479 // mutable can only appear on non-static class members, so it's always 6480 // an error here 6481 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6482 D.setInvalidType(); 6483 SC = SC_None; 6484 } 6485 6486 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6487 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6488 D.getDeclSpec().getStorageClassSpecLoc())) { 6489 // In C++11, the 'register' storage class specifier is deprecated. 6490 // Suppress the warning in system macros, it's used in macros in some 6491 // popular C system headers, such as in glibc's htonl() macro. 6492 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6493 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6494 : diag::warn_deprecated_register) 6495 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6496 } 6497 6498 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6499 6500 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6501 // C99 6.9p2: The storage-class specifiers auto and register shall not 6502 // appear in the declaration specifiers in an external declaration. 6503 // Global Register+Asm is a GNU extension we support. 6504 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6505 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6506 D.setInvalidType(); 6507 } 6508 } 6509 6510 bool IsMemberSpecialization = false; 6511 bool IsVariableTemplateSpecialization = false; 6512 bool IsPartialSpecialization = false; 6513 bool IsVariableTemplate = false; 6514 VarDecl *NewVD = nullptr; 6515 VarTemplateDecl *NewTemplate = nullptr; 6516 TemplateParameterList *TemplateParams = nullptr; 6517 if (!getLangOpts().CPlusPlus) { 6518 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6519 II, R, TInfo, SC); 6520 6521 if (R->getContainedDeducedType()) 6522 ParsingInitForAutoVars.insert(NewVD); 6523 6524 if (D.isInvalidType()) 6525 NewVD->setInvalidDecl(); 6526 } else { 6527 bool Invalid = false; 6528 6529 if (DC->isRecord() && !CurContext->isRecord()) { 6530 // This is an out-of-line definition of a static data member. 6531 switch (SC) { 6532 case SC_None: 6533 break; 6534 case SC_Static: 6535 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6536 diag::err_static_out_of_line) 6537 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6538 break; 6539 case SC_Auto: 6540 case SC_Register: 6541 case SC_Extern: 6542 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6543 // to names of variables declared in a block or to function parameters. 6544 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6545 // of class members 6546 6547 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6548 diag::err_storage_class_for_static_member) 6549 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6550 break; 6551 case SC_PrivateExtern: 6552 llvm_unreachable("C storage class in c++!"); 6553 } 6554 } 6555 6556 if (SC == SC_Static && CurContext->isRecord()) { 6557 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6558 if (RD->isLocalClass()) 6559 Diag(D.getIdentifierLoc(), 6560 diag::err_static_data_member_not_allowed_in_local_class) 6561 << Name << RD->getDeclName(); 6562 6563 // C++98 [class.union]p1: If a union contains a static data member, 6564 // the program is ill-formed. C++11 drops this restriction. 6565 if (RD->isUnion()) 6566 Diag(D.getIdentifierLoc(), 6567 getLangOpts().CPlusPlus11 6568 ? diag::warn_cxx98_compat_static_data_member_in_union 6569 : diag::ext_static_data_member_in_union) << Name; 6570 // We conservatively disallow static data members in anonymous structs. 6571 else if (!RD->getDeclName()) 6572 Diag(D.getIdentifierLoc(), 6573 diag::err_static_data_member_not_allowed_in_anon_struct) 6574 << Name << RD->isUnion(); 6575 } 6576 } 6577 6578 // Match up the template parameter lists with the scope specifier, then 6579 // determine whether we have a template or a template specialization. 6580 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6581 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6582 D.getCXXScopeSpec(), 6583 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6584 ? D.getName().TemplateId 6585 : nullptr, 6586 TemplateParamLists, 6587 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6588 6589 if (TemplateParams) { 6590 if (!TemplateParams->size() && 6591 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6592 // There is an extraneous 'template<>' for this variable. Complain 6593 // about it, but allow the declaration of the variable. 6594 Diag(TemplateParams->getTemplateLoc(), 6595 diag::err_template_variable_noparams) 6596 << II 6597 << SourceRange(TemplateParams->getTemplateLoc(), 6598 TemplateParams->getRAngleLoc()); 6599 TemplateParams = nullptr; 6600 } else { 6601 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6602 // This is an explicit specialization or a partial specialization. 6603 // FIXME: Check that we can declare a specialization here. 6604 IsVariableTemplateSpecialization = true; 6605 IsPartialSpecialization = TemplateParams->size() > 0; 6606 } else { // if (TemplateParams->size() > 0) 6607 // This is a template declaration. 6608 IsVariableTemplate = true; 6609 6610 // Check that we can declare a template here. 6611 if (CheckTemplateDeclScope(S, TemplateParams)) 6612 return nullptr; 6613 6614 // Only C++1y supports variable templates (N3651). 6615 Diag(D.getIdentifierLoc(), 6616 getLangOpts().CPlusPlus14 6617 ? diag::warn_cxx11_compat_variable_template 6618 : diag::ext_variable_template); 6619 } 6620 } 6621 } else { 6622 assert((Invalid || 6623 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6624 "should have a 'template<>' for this decl"); 6625 } 6626 6627 if (IsVariableTemplateSpecialization) { 6628 SourceLocation TemplateKWLoc = 6629 TemplateParamLists.size() > 0 6630 ? TemplateParamLists[0]->getTemplateLoc() 6631 : SourceLocation(); 6632 DeclResult Res = ActOnVarTemplateSpecialization( 6633 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6634 IsPartialSpecialization); 6635 if (Res.isInvalid()) 6636 return nullptr; 6637 NewVD = cast<VarDecl>(Res.get()); 6638 AddToScope = false; 6639 } else if (D.isDecompositionDeclarator()) { 6640 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 6641 D.getIdentifierLoc(), R, TInfo, SC, 6642 Bindings); 6643 } else 6644 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 6645 D.getIdentifierLoc(), II, R, TInfo, SC); 6646 6647 // If this is supposed to be a variable template, create it as such. 6648 if (IsVariableTemplate) { 6649 NewTemplate = 6650 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6651 TemplateParams, NewVD); 6652 NewVD->setDescribedVarTemplate(NewTemplate); 6653 } 6654 6655 // If this decl has an auto type in need of deduction, make a note of the 6656 // Decl so we can diagnose uses of it in its own initializer. 6657 if (R->getContainedDeducedType()) 6658 ParsingInitForAutoVars.insert(NewVD); 6659 6660 if (D.isInvalidType() || Invalid) { 6661 NewVD->setInvalidDecl(); 6662 if (NewTemplate) 6663 NewTemplate->setInvalidDecl(); 6664 } 6665 6666 SetNestedNameSpecifier(*this, NewVD, D); 6667 6668 // If we have any template parameter lists that don't directly belong to 6669 // the variable (matching the scope specifier), store them. 6670 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6671 if (TemplateParamLists.size() > VDTemplateParamLists) 6672 NewVD->setTemplateParameterListsInfo( 6673 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6674 6675 if (D.getDeclSpec().hasConstexprSpecifier()) { 6676 NewVD->setConstexpr(true); 6677 // C++1z [dcl.spec.constexpr]p1: 6678 // A static data member declared with the constexpr specifier is 6679 // implicitly an inline variable. 6680 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17) 6681 NewVD->setImplicitlyInline(); 6682 if (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval) 6683 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6684 diag::err_constexpr_wrong_decl_kind) 6685 << /*consteval*/ 1; 6686 } 6687 } 6688 6689 if (D.getDeclSpec().isInlineSpecified()) { 6690 if (!getLangOpts().CPlusPlus) { 6691 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6692 << 0; 6693 } else if (CurContext->isFunctionOrMethod()) { 6694 // 'inline' is not allowed on block scope variable declaration. 6695 Diag(D.getDeclSpec().getInlineSpecLoc(), 6696 diag::err_inline_declaration_block_scope) << Name 6697 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6698 } else { 6699 Diag(D.getDeclSpec().getInlineSpecLoc(), 6700 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 6701 : diag::ext_inline_variable); 6702 NewVD->setInlineSpecified(); 6703 } 6704 } 6705 6706 // Set the lexical context. If the declarator has a C++ scope specifier, the 6707 // lexical context will be different from the semantic context. 6708 NewVD->setLexicalDeclContext(CurContext); 6709 if (NewTemplate) 6710 NewTemplate->setLexicalDeclContext(CurContext); 6711 6712 if (IsLocalExternDecl) { 6713 if (D.isDecompositionDeclarator()) 6714 for (auto *B : Bindings) 6715 B->setLocalExternDecl(); 6716 else 6717 NewVD->setLocalExternDecl(); 6718 } 6719 6720 bool EmitTLSUnsupportedError = false; 6721 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6722 // C++11 [dcl.stc]p4: 6723 // When thread_local is applied to a variable of block scope the 6724 // storage-class-specifier static is implied if it does not appear 6725 // explicitly. 6726 // Core issue: 'static' is not implied if the variable is declared 6727 // 'extern'. 6728 if (NewVD->hasLocalStorage() && 6729 (SCSpec != DeclSpec::SCS_unspecified || 6730 TSCS != DeclSpec::TSCS_thread_local || 6731 !DC->isFunctionOrMethod())) 6732 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6733 diag::err_thread_non_global) 6734 << DeclSpec::getSpecifierName(TSCS); 6735 else if (!Context.getTargetInfo().isTLSSupported()) { 6736 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6737 // Postpone error emission until we've collected attributes required to 6738 // figure out whether it's a host or device variable and whether the 6739 // error should be ignored. 6740 EmitTLSUnsupportedError = true; 6741 // We still need to mark the variable as TLS so it shows up in AST with 6742 // proper storage class for other tools to use even if we're not going 6743 // to emit any code for it. 6744 NewVD->setTSCSpec(TSCS); 6745 } else 6746 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6747 diag::err_thread_unsupported); 6748 } else 6749 NewVD->setTSCSpec(TSCS); 6750 } 6751 6752 // C99 6.7.4p3 6753 // An inline definition of a function with external linkage shall 6754 // not contain a definition of a modifiable object with static or 6755 // thread storage duration... 6756 // We only apply this when the function is required to be defined 6757 // elsewhere, i.e. when the function is not 'extern inline'. Note 6758 // that a local variable with thread storage duration still has to 6759 // be marked 'static'. Also note that it's possible to get these 6760 // semantics in C++ using __attribute__((gnu_inline)). 6761 if (SC == SC_Static && S->getFnParent() != nullptr && 6762 !NewVD->getType().isConstQualified()) { 6763 FunctionDecl *CurFD = getCurFunctionDecl(); 6764 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6765 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6766 diag::warn_static_local_in_extern_inline); 6767 MaybeSuggestAddingStaticToDecl(CurFD); 6768 } 6769 } 6770 6771 if (D.getDeclSpec().isModulePrivateSpecified()) { 6772 if (IsVariableTemplateSpecialization) 6773 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6774 << (IsPartialSpecialization ? 1 : 0) 6775 << FixItHint::CreateRemoval( 6776 D.getDeclSpec().getModulePrivateSpecLoc()); 6777 else if (IsMemberSpecialization) 6778 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6779 << 2 6780 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6781 else if (NewVD->hasLocalStorage()) 6782 Diag(NewVD->getLocation(), diag::err_module_private_local) 6783 << 0 << NewVD->getDeclName() 6784 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6785 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6786 else { 6787 NewVD->setModulePrivate(); 6788 if (NewTemplate) 6789 NewTemplate->setModulePrivate(); 6790 for (auto *B : Bindings) 6791 B->setModulePrivate(); 6792 } 6793 } 6794 6795 // Handle attributes prior to checking for duplicates in MergeVarDecl 6796 ProcessDeclAttributes(S, NewVD, D); 6797 6798 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6799 if (EmitTLSUnsupportedError && 6800 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6801 (getLangOpts().OpenMPIsDevice && 6802 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6803 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6804 diag::err_thread_unsupported); 6805 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6806 // storage [duration]." 6807 if (SC == SC_None && S->getFnParent() != nullptr && 6808 (NewVD->hasAttr<CUDASharedAttr>() || 6809 NewVD->hasAttr<CUDAConstantAttr>())) { 6810 NewVD->setStorageClass(SC_Static); 6811 } 6812 } 6813 6814 // Ensure that dllimport globals without explicit storage class are treated as 6815 // extern. The storage class is set above using parsed attributes. Now we can 6816 // check the VarDecl itself. 6817 assert(!NewVD->hasAttr<DLLImportAttr>() || 6818 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6819 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6820 6821 // In auto-retain/release, infer strong retension for variables of 6822 // retainable type. 6823 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6824 NewVD->setInvalidDecl(); 6825 6826 // Handle GNU asm-label extension (encoded as an attribute). 6827 if (Expr *E = (Expr*)D.getAsmLabel()) { 6828 // The parser guarantees this is a string. 6829 StringLiteral *SE = cast<StringLiteral>(E); 6830 StringRef Label = SE->getString(); 6831 if (S->getFnParent() != nullptr) { 6832 switch (SC) { 6833 case SC_None: 6834 case SC_Auto: 6835 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6836 break; 6837 case SC_Register: 6838 // Local Named register 6839 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6840 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6841 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6842 break; 6843 case SC_Static: 6844 case SC_Extern: 6845 case SC_PrivateExtern: 6846 break; 6847 } 6848 } else if (SC == SC_Register) { 6849 // Global Named register 6850 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6851 const auto &TI = Context.getTargetInfo(); 6852 bool HasSizeMismatch; 6853 6854 if (!TI.isValidGCCRegisterName(Label)) 6855 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6856 else if (!TI.validateGlobalRegisterVariable(Label, 6857 Context.getTypeSize(R), 6858 HasSizeMismatch)) 6859 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6860 else if (HasSizeMismatch) 6861 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6862 } 6863 6864 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6865 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 6866 NewVD->setInvalidDecl(true); 6867 } 6868 } 6869 6870 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6871 Context, Label, 0)); 6872 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6873 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6874 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6875 if (I != ExtnameUndeclaredIdentifiers.end()) { 6876 if (isDeclExternC(NewVD)) { 6877 NewVD->addAttr(I->second); 6878 ExtnameUndeclaredIdentifiers.erase(I); 6879 } else 6880 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6881 << /*Variable*/1 << NewVD; 6882 } 6883 } 6884 6885 // Find the shadowed declaration before filtering for scope. 6886 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6887 ? getShadowedDeclaration(NewVD, Previous) 6888 : nullptr; 6889 6890 // Don't consider existing declarations that are in a different 6891 // scope and are out-of-semantic-context declarations (if the new 6892 // declaration has linkage). 6893 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6894 D.getCXXScopeSpec().isNotEmpty() || 6895 IsMemberSpecialization || 6896 IsVariableTemplateSpecialization); 6897 6898 // Check whether the previous declaration is in the same block scope. This 6899 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6900 if (getLangOpts().CPlusPlus && 6901 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6902 NewVD->setPreviousDeclInSameBlockScope( 6903 Previous.isSingleResult() && !Previous.isShadowed() && 6904 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6905 6906 if (!getLangOpts().CPlusPlus) { 6907 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6908 } else { 6909 // If this is an explicit specialization of a static data member, check it. 6910 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6911 CheckMemberSpecialization(NewVD, Previous)) 6912 NewVD->setInvalidDecl(); 6913 6914 // Merge the decl with the existing one if appropriate. 6915 if (!Previous.empty()) { 6916 if (Previous.isSingleResult() && 6917 isa<FieldDecl>(Previous.getFoundDecl()) && 6918 D.getCXXScopeSpec().isSet()) { 6919 // The user tried to define a non-static data member 6920 // out-of-line (C++ [dcl.meaning]p1). 6921 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6922 << D.getCXXScopeSpec().getRange(); 6923 Previous.clear(); 6924 NewVD->setInvalidDecl(); 6925 } 6926 } else if (D.getCXXScopeSpec().isSet()) { 6927 // No previous declaration in the qualifying scope. 6928 Diag(D.getIdentifierLoc(), diag::err_no_member) 6929 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6930 << D.getCXXScopeSpec().getRange(); 6931 NewVD->setInvalidDecl(); 6932 } 6933 6934 if (!IsVariableTemplateSpecialization) 6935 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6936 6937 if (NewTemplate) { 6938 VarTemplateDecl *PrevVarTemplate = 6939 NewVD->getPreviousDecl() 6940 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6941 : nullptr; 6942 6943 // Check the template parameter list of this declaration, possibly 6944 // merging in the template parameter list from the previous variable 6945 // template declaration. 6946 if (CheckTemplateParameterList( 6947 TemplateParams, 6948 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6949 : nullptr, 6950 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6951 DC->isDependentContext()) 6952 ? TPC_ClassTemplateMember 6953 : TPC_VarTemplate)) 6954 NewVD->setInvalidDecl(); 6955 6956 // If we are providing an explicit specialization of a static variable 6957 // template, make a note of that. 6958 if (PrevVarTemplate && 6959 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6960 PrevVarTemplate->setMemberSpecialization(); 6961 } 6962 } 6963 6964 // Diagnose shadowed variables iff this isn't a redeclaration. 6965 if (ShadowedDecl && !D.isRedeclaration()) 6966 CheckShadow(NewVD, ShadowedDecl, Previous); 6967 6968 ProcessPragmaWeak(S, NewVD); 6969 6970 // If this is the first declaration of an extern C variable, update 6971 // the map of such variables. 6972 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6973 isIncompleteDeclExternC(*this, NewVD)) 6974 RegisterLocallyScopedExternCDecl(NewVD, S); 6975 6976 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6977 Decl *ManglingContextDecl; 6978 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6979 NewVD->getDeclContext(), ManglingContextDecl)) { 6980 Context.setManglingNumber( 6981 NewVD, MCtx->getManglingNumber( 6982 NewVD, getMSManglingNumber(getLangOpts(), S))); 6983 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6984 } 6985 } 6986 6987 // Special handling of variable named 'main'. 6988 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6989 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6990 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6991 6992 // C++ [basic.start.main]p3 6993 // A program that declares a variable main at global scope is ill-formed. 6994 if (getLangOpts().CPlusPlus) 6995 Diag(D.getBeginLoc(), diag::err_main_global_variable); 6996 6997 // In C, and external-linkage variable named main results in undefined 6998 // behavior. 6999 else if (NewVD->hasExternalFormalLinkage()) 7000 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7001 } 7002 7003 if (D.isRedeclaration() && !Previous.empty()) { 7004 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7005 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7006 D.isFunctionDefinition()); 7007 } 7008 7009 if (NewTemplate) { 7010 if (NewVD->isInvalidDecl()) 7011 NewTemplate->setInvalidDecl(); 7012 ActOnDocumentableDecl(NewTemplate); 7013 return NewTemplate; 7014 } 7015 7016 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7017 CompleteMemberSpecialization(NewVD, Previous); 7018 7019 return NewVD; 7020 } 7021 7022 /// Enum describing the %select options in diag::warn_decl_shadow. 7023 enum ShadowedDeclKind { 7024 SDK_Local, 7025 SDK_Global, 7026 SDK_StaticMember, 7027 SDK_Field, 7028 SDK_Typedef, 7029 SDK_Using 7030 }; 7031 7032 /// Determine what kind of declaration we're shadowing. 7033 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7034 const DeclContext *OldDC) { 7035 if (isa<TypeAliasDecl>(ShadowedDecl)) 7036 return SDK_Using; 7037 else if (isa<TypedefDecl>(ShadowedDecl)) 7038 return SDK_Typedef; 7039 else if (isa<RecordDecl>(OldDC)) 7040 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7041 7042 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7043 } 7044 7045 /// Return the location of the capture if the given lambda captures the given 7046 /// variable \p VD, or an invalid source location otherwise. 7047 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7048 const VarDecl *VD) { 7049 for (const Capture &Capture : LSI->Captures) { 7050 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7051 return Capture.getLocation(); 7052 } 7053 return SourceLocation(); 7054 } 7055 7056 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7057 const LookupResult &R) { 7058 // Only diagnose if we're shadowing an unambiguous field or variable. 7059 if (R.getResultKind() != LookupResult::Found) 7060 return false; 7061 7062 // Return false if warning is ignored. 7063 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7064 } 7065 7066 /// Return the declaration shadowed by the given variable \p D, or null 7067 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7068 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7069 const LookupResult &R) { 7070 if (!shouldWarnIfShadowedDecl(Diags, R)) 7071 return nullptr; 7072 7073 // Don't diagnose declarations at file scope. 7074 if (D->hasGlobalStorage()) 7075 return nullptr; 7076 7077 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7078 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7079 ? ShadowedDecl 7080 : nullptr; 7081 } 7082 7083 /// Return the declaration shadowed by the given typedef \p D, or null 7084 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7085 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7086 const LookupResult &R) { 7087 // Don't warn if typedef declaration is part of a class 7088 if (D->getDeclContext()->isRecord()) 7089 return nullptr; 7090 7091 if (!shouldWarnIfShadowedDecl(Diags, R)) 7092 return nullptr; 7093 7094 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7095 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7096 } 7097 7098 /// Diagnose variable or built-in function shadowing. Implements 7099 /// -Wshadow. 7100 /// 7101 /// This method is called whenever a VarDecl is added to a "useful" 7102 /// scope. 7103 /// 7104 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7105 /// \param R the lookup of the name 7106 /// 7107 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7108 const LookupResult &R) { 7109 DeclContext *NewDC = D->getDeclContext(); 7110 7111 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7112 // Fields are not shadowed by variables in C++ static methods. 7113 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7114 if (MD->isStatic()) 7115 return; 7116 7117 // Fields shadowed by constructor parameters are a special case. Usually 7118 // the constructor initializes the field with the parameter. 7119 if (isa<CXXConstructorDecl>(NewDC)) 7120 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7121 // Remember that this was shadowed so we can either warn about its 7122 // modification or its existence depending on warning settings. 7123 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7124 return; 7125 } 7126 } 7127 7128 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7129 if (shadowedVar->isExternC()) { 7130 // For shadowing external vars, make sure that we point to the global 7131 // declaration, not a locally scoped extern declaration. 7132 for (auto I : shadowedVar->redecls()) 7133 if (I->isFileVarDecl()) { 7134 ShadowedDecl = I; 7135 break; 7136 } 7137 } 7138 7139 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7140 7141 unsigned WarningDiag = diag::warn_decl_shadow; 7142 SourceLocation CaptureLoc; 7143 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7144 isa<CXXMethodDecl>(NewDC)) { 7145 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7146 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7147 if (RD->getLambdaCaptureDefault() == LCD_None) { 7148 // Try to avoid warnings for lambdas with an explicit capture list. 7149 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7150 // Warn only when the lambda captures the shadowed decl explicitly. 7151 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7152 if (CaptureLoc.isInvalid()) 7153 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7154 } else { 7155 // Remember that this was shadowed so we can avoid the warning if the 7156 // shadowed decl isn't captured and the warning settings allow it. 7157 cast<LambdaScopeInfo>(getCurFunction()) 7158 ->ShadowingDecls.push_back( 7159 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7160 return; 7161 } 7162 } 7163 7164 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7165 // A variable can't shadow a local variable in an enclosing scope, if 7166 // they are separated by a non-capturing declaration context. 7167 for (DeclContext *ParentDC = NewDC; 7168 ParentDC && !ParentDC->Equals(OldDC); 7169 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7170 // Only block literals, captured statements, and lambda expressions 7171 // can capture; other scopes don't. 7172 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7173 !isLambdaCallOperator(ParentDC)) { 7174 return; 7175 } 7176 } 7177 } 7178 } 7179 } 7180 7181 // Only warn about certain kinds of shadowing for class members. 7182 if (NewDC && NewDC->isRecord()) { 7183 // In particular, don't warn about shadowing non-class members. 7184 if (!OldDC->isRecord()) 7185 return; 7186 7187 // TODO: should we warn about static data members shadowing 7188 // static data members from base classes? 7189 7190 // TODO: don't diagnose for inaccessible shadowed members. 7191 // This is hard to do perfectly because we might friend the 7192 // shadowing context, but that's just a false negative. 7193 } 7194 7195 7196 DeclarationName Name = R.getLookupName(); 7197 7198 // Emit warning and note. 7199 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7200 return; 7201 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7202 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7203 if (!CaptureLoc.isInvalid()) 7204 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7205 << Name << /*explicitly*/ 1; 7206 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7207 } 7208 7209 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7210 /// when these variables are captured by the lambda. 7211 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7212 for (const auto &Shadow : LSI->ShadowingDecls) { 7213 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7214 // Try to avoid the warning when the shadowed decl isn't captured. 7215 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7216 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7217 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7218 ? diag::warn_decl_shadow_uncaptured_local 7219 : diag::warn_decl_shadow) 7220 << Shadow.VD->getDeclName() 7221 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7222 if (!CaptureLoc.isInvalid()) 7223 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7224 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7225 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7226 } 7227 } 7228 7229 /// Check -Wshadow without the advantage of a previous lookup. 7230 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7231 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7232 return; 7233 7234 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7235 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7236 LookupName(R, S); 7237 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7238 CheckShadow(D, ShadowedDecl, R); 7239 } 7240 7241 /// Check if 'E', which is an expression that is about to be modified, refers 7242 /// to a constructor parameter that shadows a field. 7243 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7244 // Quickly ignore expressions that can't be shadowing ctor parameters. 7245 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7246 return; 7247 E = E->IgnoreParenImpCasts(); 7248 auto *DRE = dyn_cast<DeclRefExpr>(E); 7249 if (!DRE) 7250 return; 7251 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7252 auto I = ShadowingDecls.find(D); 7253 if (I == ShadowingDecls.end()) 7254 return; 7255 const NamedDecl *ShadowedDecl = I->second; 7256 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7257 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7258 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7259 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7260 7261 // Avoid issuing multiple warnings about the same decl. 7262 ShadowingDecls.erase(I); 7263 } 7264 7265 /// Check for conflict between this global or extern "C" declaration and 7266 /// previous global or extern "C" declarations. This is only used in C++. 7267 template<typename T> 7268 static bool checkGlobalOrExternCConflict( 7269 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7270 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7271 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7272 7273 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7274 // The common case: this global doesn't conflict with any extern "C" 7275 // declaration. 7276 return false; 7277 } 7278 7279 if (Prev) { 7280 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7281 // Both the old and new declarations have C language linkage. This is a 7282 // redeclaration. 7283 Previous.clear(); 7284 Previous.addDecl(Prev); 7285 return true; 7286 } 7287 7288 // This is a global, non-extern "C" declaration, and there is a previous 7289 // non-global extern "C" declaration. Diagnose if this is a variable 7290 // declaration. 7291 if (!isa<VarDecl>(ND)) 7292 return false; 7293 } else { 7294 // The declaration is extern "C". Check for any declaration in the 7295 // translation unit which might conflict. 7296 if (IsGlobal) { 7297 // We have already performed the lookup into the translation unit. 7298 IsGlobal = false; 7299 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7300 I != E; ++I) { 7301 if (isa<VarDecl>(*I)) { 7302 Prev = *I; 7303 break; 7304 } 7305 } 7306 } else { 7307 DeclContext::lookup_result R = 7308 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7309 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7310 I != E; ++I) { 7311 if (isa<VarDecl>(*I)) { 7312 Prev = *I; 7313 break; 7314 } 7315 // FIXME: If we have any other entity with this name in global scope, 7316 // the declaration is ill-formed, but that is a defect: it breaks the 7317 // 'stat' hack, for instance. Only variables can have mangled name 7318 // clashes with extern "C" declarations, so only they deserve a 7319 // diagnostic. 7320 } 7321 } 7322 7323 if (!Prev) 7324 return false; 7325 } 7326 7327 // Use the first declaration's location to ensure we point at something which 7328 // is lexically inside an extern "C" linkage-spec. 7329 assert(Prev && "should have found a previous declaration to diagnose"); 7330 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7331 Prev = FD->getFirstDecl(); 7332 else 7333 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7334 7335 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7336 << IsGlobal << ND; 7337 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7338 << IsGlobal; 7339 return false; 7340 } 7341 7342 /// Apply special rules for handling extern "C" declarations. Returns \c true 7343 /// if we have found that this is a redeclaration of some prior entity. 7344 /// 7345 /// Per C++ [dcl.link]p6: 7346 /// Two declarations [for a function or variable] with C language linkage 7347 /// with the same name that appear in different scopes refer to the same 7348 /// [entity]. An entity with C language linkage shall not be declared with 7349 /// the same name as an entity in global scope. 7350 template<typename T> 7351 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7352 LookupResult &Previous) { 7353 if (!S.getLangOpts().CPlusPlus) { 7354 // In C, when declaring a global variable, look for a corresponding 'extern' 7355 // variable declared in function scope. We don't need this in C++, because 7356 // we find local extern decls in the surrounding file-scope DeclContext. 7357 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7358 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7359 Previous.clear(); 7360 Previous.addDecl(Prev); 7361 return true; 7362 } 7363 } 7364 return false; 7365 } 7366 7367 // A declaration in the translation unit can conflict with an extern "C" 7368 // declaration. 7369 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7370 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7371 7372 // An extern "C" declaration can conflict with a declaration in the 7373 // translation unit or can be a redeclaration of an extern "C" declaration 7374 // in another scope. 7375 if (isIncompleteDeclExternC(S,ND)) 7376 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7377 7378 // Neither global nor extern "C": nothing to do. 7379 return false; 7380 } 7381 7382 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7383 // If the decl is already known invalid, don't check it. 7384 if (NewVD->isInvalidDecl()) 7385 return; 7386 7387 QualType T = NewVD->getType(); 7388 7389 // Defer checking an 'auto' type until its initializer is attached. 7390 if (T->isUndeducedType()) 7391 return; 7392 7393 if (NewVD->hasAttrs()) 7394 CheckAlignasUnderalignment(NewVD); 7395 7396 if (T->isObjCObjectType()) { 7397 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7398 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7399 T = Context.getObjCObjectPointerType(T); 7400 NewVD->setType(T); 7401 } 7402 7403 // Emit an error if an address space was applied to decl with local storage. 7404 // This includes arrays of objects with address space qualifiers, but not 7405 // automatic variables that point to other address spaces. 7406 // ISO/IEC TR 18037 S5.1.2 7407 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7408 T.getAddressSpace() != LangAS::Default) { 7409 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7410 NewVD->setInvalidDecl(); 7411 return; 7412 } 7413 7414 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7415 // scope. 7416 if (getLangOpts().OpenCLVersion == 120 && 7417 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7418 NewVD->isStaticLocal()) { 7419 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7420 NewVD->setInvalidDecl(); 7421 return; 7422 } 7423 7424 if (getLangOpts().OpenCL) { 7425 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7426 if (NewVD->hasAttr<BlocksAttr>()) { 7427 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7428 return; 7429 } 7430 7431 if (T->isBlockPointerType()) { 7432 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7433 // can't use 'extern' storage class. 7434 if (!T.isConstQualified()) { 7435 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7436 << 0 /*const*/; 7437 NewVD->setInvalidDecl(); 7438 return; 7439 } 7440 if (NewVD->hasExternalStorage()) { 7441 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7442 NewVD->setInvalidDecl(); 7443 return; 7444 } 7445 } 7446 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7447 // __constant address space. 7448 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7449 // variables inside a function can also be declared in the global 7450 // address space. 7451 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7452 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7453 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7454 NewVD->hasExternalStorage()) { 7455 if (!T->isSamplerT() && 7456 !(T.getAddressSpace() == LangAS::opencl_constant || 7457 (T.getAddressSpace() == LangAS::opencl_global && 7458 (getLangOpts().OpenCLVersion == 200 || 7459 getLangOpts().OpenCLCPlusPlus)))) { 7460 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7461 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7462 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7463 << Scope << "global or constant"; 7464 else 7465 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7466 << Scope << "constant"; 7467 NewVD->setInvalidDecl(); 7468 return; 7469 } 7470 } else { 7471 if (T.getAddressSpace() == LangAS::opencl_global) { 7472 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7473 << 1 /*is any function*/ << "global"; 7474 NewVD->setInvalidDecl(); 7475 return; 7476 } 7477 if (T.getAddressSpace() == LangAS::opencl_constant || 7478 T.getAddressSpace() == LangAS::opencl_local) { 7479 FunctionDecl *FD = getCurFunctionDecl(); 7480 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7481 // in functions. 7482 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7483 if (T.getAddressSpace() == LangAS::opencl_constant) 7484 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7485 << 0 /*non-kernel only*/ << "constant"; 7486 else 7487 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7488 << 0 /*non-kernel only*/ << "local"; 7489 NewVD->setInvalidDecl(); 7490 return; 7491 } 7492 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7493 // in the outermost scope of a kernel function. 7494 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7495 if (!getCurScope()->isFunctionScope()) { 7496 if (T.getAddressSpace() == LangAS::opencl_constant) 7497 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7498 << "constant"; 7499 else 7500 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7501 << "local"; 7502 NewVD->setInvalidDecl(); 7503 return; 7504 } 7505 } 7506 } else if (T.getAddressSpace() != LangAS::opencl_private && 7507 // If we are parsing a template we didn't deduce an addr 7508 // space yet. 7509 T.getAddressSpace() != LangAS::Default) { 7510 // Do not allow other address spaces on automatic variable. 7511 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7512 NewVD->setInvalidDecl(); 7513 return; 7514 } 7515 } 7516 } 7517 7518 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7519 && !NewVD->hasAttr<BlocksAttr>()) { 7520 if (getLangOpts().getGC() != LangOptions::NonGC) 7521 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7522 else { 7523 assert(!getLangOpts().ObjCAutoRefCount); 7524 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7525 } 7526 } 7527 7528 bool isVM = T->isVariablyModifiedType(); 7529 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7530 NewVD->hasAttr<BlocksAttr>()) 7531 setFunctionHasBranchProtectedScope(); 7532 7533 if ((isVM && NewVD->hasLinkage()) || 7534 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7535 bool SizeIsNegative; 7536 llvm::APSInt Oversized; 7537 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7538 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7539 QualType FixedT; 7540 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7541 FixedT = FixedTInfo->getType(); 7542 else if (FixedTInfo) { 7543 // Type and type-as-written are canonically different. We need to fix up 7544 // both types separately. 7545 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7546 Oversized); 7547 } 7548 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7549 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7550 // FIXME: This won't give the correct result for 7551 // int a[10][n]; 7552 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7553 7554 if (NewVD->isFileVarDecl()) 7555 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7556 << SizeRange; 7557 else if (NewVD->isStaticLocal()) 7558 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7559 << SizeRange; 7560 else 7561 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7562 << SizeRange; 7563 NewVD->setInvalidDecl(); 7564 return; 7565 } 7566 7567 if (!FixedTInfo) { 7568 if (NewVD->isFileVarDecl()) 7569 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7570 else 7571 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7572 NewVD->setInvalidDecl(); 7573 return; 7574 } 7575 7576 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7577 NewVD->setType(FixedT); 7578 NewVD->setTypeSourceInfo(FixedTInfo); 7579 } 7580 7581 if (T->isVoidType()) { 7582 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7583 // of objects and functions. 7584 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7585 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7586 << T; 7587 NewVD->setInvalidDecl(); 7588 return; 7589 } 7590 } 7591 7592 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7593 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7594 NewVD->setInvalidDecl(); 7595 return; 7596 } 7597 7598 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7599 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7600 NewVD->setInvalidDecl(); 7601 return; 7602 } 7603 7604 if (NewVD->isConstexpr() && !T->isDependentType() && 7605 RequireLiteralType(NewVD->getLocation(), T, 7606 diag::err_constexpr_var_non_literal)) { 7607 NewVD->setInvalidDecl(); 7608 return; 7609 } 7610 } 7611 7612 /// Perform semantic checking on a newly-created variable 7613 /// declaration. 7614 /// 7615 /// This routine performs all of the type-checking required for a 7616 /// variable declaration once it has been built. It is used both to 7617 /// check variables after they have been parsed and their declarators 7618 /// have been translated into a declaration, and to check variables 7619 /// that have been instantiated from a template. 7620 /// 7621 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7622 /// 7623 /// Returns true if the variable declaration is a redeclaration. 7624 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7625 CheckVariableDeclarationType(NewVD); 7626 7627 // If the decl is already known invalid, don't check it. 7628 if (NewVD->isInvalidDecl()) 7629 return false; 7630 7631 // If we did not find anything by this name, look for a non-visible 7632 // extern "C" declaration with the same name. 7633 if (Previous.empty() && 7634 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7635 Previous.setShadowed(); 7636 7637 if (!Previous.empty()) { 7638 MergeVarDecl(NewVD, Previous); 7639 return true; 7640 } 7641 return false; 7642 } 7643 7644 namespace { 7645 struct FindOverriddenMethod { 7646 Sema *S; 7647 CXXMethodDecl *Method; 7648 7649 /// Member lookup function that determines whether a given C++ 7650 /// method overrides a method in a base class, to be used with 7651 /// CXXRecordDecl::lookupInBases(). 7652 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7653 RecordDecl *BaseRecord = 7654 Specifier->getType()->getAs<RecordType>()->getDecl(); 7655 7656 DeclarationName Name = Method->getDeclName(); 7657 7658 // FIXME: Do we care about other names here too? 7659 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7660 // We really want to find the base class destructor here. 7661 QualType T = S->Context.getTypeDeclType(BaseRecord); 7662 CanQualType CT = S->Context.getCanonicalType(T); 7663 7664 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7665 } 7666 7667 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7668 Path.Decls = Path.Decls.slice(1)) { 7669 NamedDecl *D = Path.Decls.front(); 7670 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7671 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7672 return true; 7673 } 7674 } 7675 7676 return false; 7677 } 7678 }; 7679 7680 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7681 } // end anonymous namespace 7682 7683 /// Report an error regarding overriding, along with any relevant 7684 /// overridden methods. 7685 /// 7686 /// \param DiagID the primary error to report. 7687 /// \param MD the overriding method. 7688 /// \param OEK which overrides to include as notes. 7689 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7690 OverrideErrorKind OEK = OEK_All) { 7691 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7692 for (const CXXMethodDecl *O : MD->overridden_methods()) { 7693 // This check (& the OEK parameter) could be replaced by a predicate, but 7694 // without lambdas that would be overkill. This is still nicer than writing 7695 // out the diag loop 3 times. 7696 if ((OEK == OEK_All) || 7697 (OEK == OEK_NonDeleted && !O->isDeleted()) || 7698 (OEK == OEK_Deleted && O->isDeleted())) 7699 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 7700 } 7701 } 7702 7703 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7704 /// and if so, check that it's a valid override and remember it. 7705 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7706 // Look for methods in base classes that this method might override. 7707 CXXBasePaths Paths; 7708 FindOverriddenMethod FOM; 7709 FOM.Method = MD; 7710 FOM.S = this; 7711 bool hasDeletedOverridenMethods = false; 7712 bool hasNonDeletedOverridenMethods = false; 7713 bool AddedAny = false; 7714 if (DC->lookupInBases(FOM, Paths)) { 7715 for (auto *I : Paths.found_decls()) { 7716 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7717 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7718 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7719 !CheckOverridingFunctionAttributes(MD, OldMD) && 7720 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7721 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7722 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7723 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7724 AddedAny = true; 7725 } 7726 } 7727 } 7728 } 7729 7730 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7731 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7732 } 7733 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7734 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7735 } 7736 7737 return AddedAny; 7738 } 7739 7740 namespace { 7741 // Struct for holding all of the extra arguments needed by 7742 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7743 struct ActOnFDArgs { 7744 Scope *S; 7745 Declarator &D; 7746 MultiTemplateParamsArg TemplateParamLists; 7747 bool AddToScope; 7748 }; 7749 } // end anonymous namespace 7750 7751 namespace { 7752 7753 // Callback to only accept typo corrections that have a non-zero edit distance. 7754 // Also only accept corrections that have the same parent decl. 7755 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 7756 public: 7757 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7758 CXXRecordDecl *Parent) 7759 : Context(Context), OriginalFD(TypoFD), 7760 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7761 7762 bool ValidateCandidate(const TypoCorrection &candidate) override { 7763 if (candidate.getEditDistance() == 0) 7764 return false; 7765 7766 SmallVector<unsigned, 1> MismatchedParams; 7767 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7768 CDeclEnd = candidate.end(); 7769 CDecl != CDeclEnd; ++CDecl) { 7770 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7771 7772 if (FD && !FD->hasBody() && 7773 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7774 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7775 CXXRecordDecl *Parent = MD->getParent(); 7776 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7777 return true; 7778 } else if (!ExpectedParent) { 7779 return true; 7780 } 7781 } 7782 } 7783 7784 return false; 7785 } 7786 7787 std::unique_ptr<CorrectionCandidateCallback> clone() override { 7788 return std::make_unique<DifferentNameValidatorCCC>(*this); 7789 } 7790 7791 private: 7792 ASTContext &Context; 7793 FunctionDecl *OriginalFD; 7794 CXXRecordDecl *ExpectedParent; 7795 }; 7796 7797 } // end anonymous namespace 7798 7799 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7800 TypoCorrectedFunctionDefinitions.insert(F); 7801 } 7802 7803 /// Generate diagnostics for an invalid function redeclaration. 7804 /// 7805 /// This routine handles generating the diagnostic messages for an invalid 7806 /// function redeclaration, including finding possible similar declarations 7807 /// or performing typo correction if there are no previous declarations with 7808 /// the same name. 7809 /// 7810 /// Returns a NamedDecl iff typo correction was performed and substituting in 7811 /// the new declaration name does not cause new errors. 7812 static NamedDecl *DiagnoseInvalidRedeclaration( 7813 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7814 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7815 DeclarationName Name = NewFD->getDeclName(); 7816 DeclContext *NewDC = NewFD->getDeclContext(); 7817 SmallVector<unsigned, 1> MismatchedParams; 7818 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7819 TypoCorrection Correction; 7820 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7821 unsigned DiagMsg = 7822 IsLocalFriend ? diag::err_no_matching_local_friend : 7823 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 7824 diag::err_member_decl_does_not_match; 7825 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7826 IsLocalFriend ? Sema::LookupLocalFriendName 7827 : Sema::LookupOrdinaryName, 7828 Sema::ForVisibleRedeclaration); 7829 7830 NewFD->setInvalidDecl(); 7831 if (IsLocalFriend) 7832 SemaRef.LookupName(Prev, S); 7833 else 7834 SemaRef.LookupQualifiedName(Prev, NewDC); 7835 assert(!Prev.isAmbiguous() && 7836 "Cannot have an ambiguity in previous-declaration lookup"); 7837 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7838 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 7839 MD ? MD->getParent() : nullptr); 7840 if (!Prev.empty()) { 7841 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7842 Func != FuncEnd; ++Func) { 7843 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7844 if (FD && 7845 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7846 // Add 1 to the index so that 0 can mean the mismatch didn't 7847 // involve a parameter 7848 unsigned ParamNum = 7849 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7850 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7851 } 7852 } 7853 // If the qualified name lookup yielded nothing, try typo correction 7854 } else if ((Correction = SemaRef.CorrectTypo( 7855 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7856 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 7857 IsLocalFriend ? nullptr : NewDC))) { 7858 // Set up everything for the call to ActOnFunctionDeclarator 7859 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7860 ExtraArgs.D.getIdentifierLoc()); 7861 Previous.clear(); 7862 Previous.setLookupName(Correction.getCorrection()); 7863 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7864 CDeclEnd = Correction.end(); 7865 CDecl != CDeclEnd; ++CDecl) { 7866 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7867 if (FD && !FD->hasBody() && 7868 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7869 Previous.addDecl(FD); 7870 } 7871 } 7872 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7873 7874 NamedDecl *Result; 7875 // Retry building the function declaration with the new previous 7876 // declarations, and with errors suppressed. 7877 { 7878 // Trap errors. 7879 Sema::SFINAETrap Trap(SemaRef); 7880 7881 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7882 // pieces need to verify the typo-corrected C++ declaration and hopefully 7883 // eliminate the need for the parameter pack ExtraArgs. 7884 Result = SemaRef.ActOnFunctionDeclarator( 7885 ExtraArgs.S, ExtraArgs.D, 7886 Correction.getCorrectionDecl()->getDeclContext(), 7887 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7888 ExtraArgs.AddToScope); 7889 7890 if (Trap.hasErrorOccurred()) 7891 Result = nullptr; 7892 } 7893 7894 if (Result) { 7895 // Determine which correction we picked. 7896 Decl *Canonical = Result->getCanonicalDecl(); 7897 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7898 I != E; ++I) 7899 if ((*I)->getCanonicalDecl() == Canonical) 7900 Correction.setCorrectionDecl(*I); 7901 7902 // Let Sema know about the correction. 7903 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7904 SemaRef.diagnoseTypo( 7905 Correction, 7906 SemaRef.PDiag(IsLocalFriend 7907 ? diag::err_no_matching_local_friend_suggest 7908 : diag::err_member_decl_does_not_match_suggest) 7909 << Name << NewDC << IsDefinition); 7910 return Result; 7911 } 7912 7913 // Pretend the typo correction never occurred 7914 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7915 ExtraArgs.D.getIdentifierLoc()); 7916 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7917 Previous.clear(); 7918 Previous.setLookupName(Name); 7919 } 7920 7921 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7922 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7923 7924 bool NewFDisConst = false; 7925 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7926 NewFDisConst = NewMD->isConst(); 7927 7928 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7929 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7930 NearMatch != NearMatchEnd; ++NearMatch) { 7931 FunctionDecl *FD = NearMatch->first; 7932 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7933 bool FDisConst = MD && MD->isConst(); 7934 bool IsMember = MD || !IsLocalFriend; 7935 7936 // FIXME: These notes are poorly worded for the local friend case. 7937 if (unsigned Idx = NearMatch->second) { 7938 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7939 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7940 if (Loc.isInvalid()) Loc = FD->getLocation(); 7941 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7942 : diag::note_local_decl_close_param_match) 7943 << Idx << FDParam->getType() 7944 << NewFD->getParamDecl(Idx - 1)->getType(); 7945 } else if (FDisConst != NewFDisConst) { 7946 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7947 << NewFDisConst << FD->getSourceRange().getEnd(); 7948 } else 7949 SemaRef.Diag(FD->getLocation(), 7950 IsMember ? diag::note_member_def_close_match 7951 : diag::note_local_decl_close_match); 7952 } 7953 return nullptr; 7954 } 7955 7956 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7957 switch (D.getDeclSpec().getStorageClassSpec()) { 7958 default: llvm_unreachable("Unknown storage class!"); 7959 case DeclSpec::SCS_auto: 7960 case DeclSpec::SCS_register: 7961 case DeclSpec::SCS_mutable: 7962 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7963 diag::err_typecheck_sclass_func); 7964 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7965 D.setInvalidType(); 7966 break; 7967 case DeclSpec::SCS_unspecified: break; 7968 case DeclSpec::SCS_extern: 7969 if (D.getDeclSpec().isExternInLinkageSpec()) 7970 return SC_None; 7971 return SC_Extern; 7972 case DeclSpec::SCS_static: { 7973 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7974 // C99 6.7.1p5: 7975 // The declaration of an identifier for a function that has 7976 // block scope shall have no explicit storage-class specifier 7977 // other than extern 7978 // See also (C++ [dcl.stc]p4). 7979 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7980 diag::err_static_block_func); 7981 break; 7982 } else 7983 return SC_Static; 7984 } 7985 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7986 } 7987 7988 // No explicit storage class has already been returned 7989 return SC_None; 7990 } 7991 7992 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7993 DeclContext *DC, QualType &R, 7994 TypeSourceInfo *TInfo, 7995 StorageClass SC, 7996 bool &IsVirtualOkay) { 7997 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7998 DeclarationName Name = NameInfo.getName(); 7999 8000 FunctionDecl *NewFD = nullptr; 8001 bool isInline = D.getDeclSpec().isInlineSpecified(); 8002 8003 if (!SemaRef.getLangOpts().CPlusPlus) { 8004 // Determine whether the function was written with a 8005 // prototype. This true when: 8006 // - there is a prototype in the declarator, or 8007 // - the type R of the function is some kind of typedef or other non- 8008 // attributed reference to a type name (which eventually refers to a 8009 // function type). 8010 bool HasPrototype = 8011 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8012 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8013 8014 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8015 R, TInfo, SC, isInline, HasPrototype, 8016 CSK_unspecified); 8017 if (D.isInvalidType()) 8018 NewFD->setInvalidDecl(); 8019 8020 return NewFD; 8021 } 8022 8023 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8024 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8025 // Check that the return type is not an abstract class type. 8026 // For record types, this is done by the AbstractClassUsageDiagnoser once 8027 // the class has been completely parsed. 8028 if (!DC->isRecord() && 8029 SemaRef.RequireNonAbstractType( 8030 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 8031 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8032 D.setInvalidType(); 8033 8034 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8035 // This is a C++ constructor declaration. 8036 assert(DC->isRecord() && 8037 "Constructors can only be declared in a member context"); 8038 8039 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8040 return CXXConstructorDecl::Create( 8041 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8042 TInfo, ExplicitSpecifier, isInline, 8043 /*isImplicitlyDeclared=*/false, ConstexprKind); 8044 8045 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8046 // This is a C++ destructor declaration. 8047 if (DC->isRecord()) { 8048 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8049 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8050 CXXDestructorDecl *NewDD = 8051 CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(), 8052 NameInfo, R, TInfo, isInline, 8053 /*isImplicitlyDeclared=*/false); 8054 8055 // If the destructor needs an implicit exception specification, set it 8056 // now. FIXME: It'd be nice to be able to create the right type to start 8057 // with, but the type needs to reference the destructor declaration. 8058 if (SemaRef.getLangOpts().CPlusPlus11) 8059 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8060 8061 IsVirtualOkay = true; 8062 return NewDD; 8063 8064 } else { 8065 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8066 D.setInvalidType(); 8067 8068 // Create a FunctionDecl to satisfy the function definition parsing 8069 // code path. 8070 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8071 D.getIdentifierLoc(), Name, R, TInfo, SC, 8072 isInline, 8073 /*hasPrototype=*/true, ConstexprKind); 8074 } 8075 8076 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8077 if (!DC->isRecord()) { 8078 SemaRef.Diag(D.getIdentifierLoc(), 8079 diag::err_conv_function_not_member); 8080 return nullptr; 8081 } 8082 8083 SemaRef.CheckConversionDeclarator(D, R, SC); 8084 IsVirtualOkay = true; 8085 return CXXConversionDecl::Create( 8086 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8087 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation()); 8088 8089 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8090 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8091 8092 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8093 ExplicitSpecifier, NameInfo, R, TInfo, 8094 D.getEndLoc()); 8095 } else if (DC->isRecord()) { 8096 // If the name of the function is the same as the name of the record, 8097 // then this must be an invalid constructor that has a return type. 8098 // (The parser checks for a return type and makes the declarator a 8099 // constructor if it has no return type). 8100 if (Name.getAsIdentifierInfo() && 8101 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8102 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8103 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8104 << SourceRange(D.getIdentifierLoc()); 8105 return nullptr; 8106 } 8107 8108 // This is a C++ method declaration. 8109 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8110 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8111 TInfo, SC, isInline, ConstexprKind, SourceLocation()); 8112 IsVirtualOkay = !Ret->isStatic(); 8113 return Ret; 8114 } else { 8115 bool isFriend = 8116 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8117 if (!isFriend && SemaRef.CurContext->isRecord()) 8118 return nullptr; 8119 8120 // Determine whether the function was written with a 8121 // prototype. This true when: 8122 // - we're in C++ (where every function has a prototype), 8123 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8124 R, TInfo, SC, isInline, true /*HasPrototype*/, 8125 ConstexprKind); 8126 } 8127 } 8128 8129 enum OpenCLParamType { 8130 ValidKernelParam, 8131 PtrPtrKernelParam, 8132 PtrKernelParam, 8133 InvalidAddrSpacePtrKernelParam, 8134 InvalidKernelParam, 8135 RecordKernelParam 8136 }; 8137 8138 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8139 // Size dependent types are just typedefs to normal integer types 8140 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8141 // integers other than by their names. 8142 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8143 8144 // Remove typedefs one by one until we reach a typedef 8145 // for a size dependent type. 8146 QualType DesugaredTy = Ty; 8147 do { 8148 ArrayRef<StringRef> Names(SizeTypeNames); 8149 auto Match = llvm::find(Names, DesugaredTy.getAsString()); 8150 if (Names.end() != Match) 8151 return true; 8152 8153 Ty = DesugaredTy; 8154 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8155 } while (DesugaredTy != Ty); 8156 8157 return false; 8158 } 8159 8160 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8161 if (PT->isPointerType()) { 8162 QualType PointeeType = PT->getPointeeType(); 8163 if (PointeeType->isPointerType()) 8164 return PtrPtrKernelParam; 8165 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8166 PointeeType.getAddressSpace() == LangAS::opencl_private || 8167 PointeeType.getAddressSpace() == LangAS::Default) 8168 return InvalidAddrSpacePtrKernelParam; 8169 return PtrKernelParam; 8170 } 8171 8172 // OpenCL v1.2 s6.9.k: 8173 // Arguments to kernel functions in a program cannot be declared with the 8174 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8175 // uintptr_t or a struct and/or union that contain fields declared to be one 8176 // of these built-in scalar types. 8177 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8178 return InvalidKernelParam; 8179 8180 if (PT->isImageType()) 8181 return PtrKernelParam; 8182 8183 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8184 return InvalidKernelParam; 8185 8186 // OpenCL extension spec v1.2 s9.5: 8187 // This extension adds support for half scalar and vector types as built-in 8188 // types that can be used for arithmetic operations, conversions etc. 8189 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8190 return InvalidKernelParam; 8191 8192 if (PT->isRecordType()) 8193 return RecordKernelParam; 8194 8195 // Look into an array argument to check if it has a forbidden type. 8196 if (PT->isArrayType()) { 8197 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8198 // Call ourself to check an underlying type of an array. Since the 8199 // getPointeeOrArrayElementType returns an innermost type which is not an 8200 // array, this recursive call only happens once. 8201 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8202 } 8203 8204 return ValidKernelParam; 8205 } 8206 8207 static void checkIsValidOpenCLKernelParameter( 8208 Sema &S, 8209 Declarator &D, 8210 ParmVarDecl *Param, 8211 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8212 QualType PT = Param->getType(); 8213 8214 // Cache the valid types we encounter to avoid rechecking structs that are 8215 // used again 8216 if (ValidTypes.count(PT.getTypePtr())) 8217 return; 8218 8219 switch (getOpenCLKernelParameterType(S, PT)) { 8220 case PtrPtrKernelParam: 8221 // OpenCL v1.2 s6.9.a: 8222 // A kernel function argument cannot be declared as a 8223 // pointer to a pointer type. 8224 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8225 D.setInvalidType(); 8226 return; 8227 8228 case InvalidAddrSpacePtrKernelParam: 8229 // OpenCL v1.0 s6.5: 8230 // __kernel function arguments declared to be a pointer of a type can point 8231 // to one of the following address spaces only : __global, __local or 8232 // __constant. 8233 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8234 D.setInvalidType(); 8235 return; 8236 8237 // OpenCL v1.2 s6.9.k: 8238 // Arguments to kernel functions in a program cannot be declared with the 8239 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8240 // uintptr_t or a struct and/or union that contain fields declared to be 8241 // one of these built-in scalar types. 8242 8243 case InvalidKernelParam: 8244 // OpenCL v1.2 s6.8 n: 8245 // A kernel function argument cannot be declared 8246 // of event_t type. 8247 // Do not diagnose half type since it is diagnosed as invalid argument 8248 // type for any function elsewhere. 8249 if (!PT->isHalfType()) { 8250 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8251 8252 // Explain what typedefs are involved. 8253 const TypedefType *Typedef = nullptr; 8254 while ((Typedef = PT->getAs<TypedefType>())) { 8255 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8256 // SourceLocation may be invalid for a built-in type. 8257 if (Loc.isValid()) 8258 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8259 PT = Typedef->desugar(); 8260 } 8261 } 8262 8263 D.setInvalidType(); 8264 return; 8265 8266 case PtrKernelParam: 8267 case ValidKernelParam: 8268 ValidTypes.insert(PT.getTypePtr()); 8269 return; 8270 8271 case RecordKernelParam: 8272 break; 8273 } 8274 8275 // Track nested structs we will inspect 8276 SmallVector<const Decl *, 4> VisitStack; 8277 8278 // Track where we are in the nested structs. Items will migrate from 8279 // VisitStack to HistoryStack as we do the DFS for bad field. 8280 SmallVector<const FieldDecl *, 4> HistoryStack; 8281 HistoryStack.push_back(nullptr); 8282 8283 // At this point we already handled everything except of a RecordType or 8284 // an ArrayType of a RecordType. 8285 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8286 const RecordType *RecTy = 8287 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8288 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8289 8290 VisitStack.push_back(RecTy->getDecl()); 8291 assert(VisitStack.back() && "First decl null?"); 8292 8293 do { 8294 const Decl *Next = VisitStack.pop_back_val(); 8295 if (!Next) { 8296 assert(!HistoryStack.empty()); 8297 // Found a marker, we have gone up a level 8298 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8299 ValidTypes.insert(Hist->getType().getTypePtr()); 8300 8301 continue; 8302 } 8303 8304 // Adds everything except the original parameter declaration (which is not a 8305 // field itself) to the history stack. 8306 const RecordDecl *RD; 8307 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8308 HistoryStack.push_back(Field); 8309 8310 QualType FieldTy = Field->getType(); 8311 // Other field types (known to be valid or invalid) are handled while we 8312 // walk around RecordDecl::fields(). 8313 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8314 "Unexpected type."); 8315 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8316 8317 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8318 } else { 8319 RD = cast<RecordDecl>(Next); 8320 } 8321 8322 // Add a null marker so we know when we've gone back up a level 8323 VisitStack.push_back(nullptr); 8324 8325 for (const auto *FD : RD->fields()) { 8326 QualType QT = FD->getType(); 8327 8328 if (ValidTypes.count(QT.getTypePtr())) 8329 continue; 8330 8331 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8332 if (ParamType == ValidKernelParam) 8333 continue; 8334 8335 if (ParamType == RecordKernelParam) { 8336 VisitStack.push_back(FD); 8337 continue; 8338 } 8339 8340 // OpenCL v1.2 s6.9.p: 8341 // Arguments to kernel functions that are declared to be a struct or union 8342 // do not allow OpenCL objects to be passed as elements of the struct or 8343 // union. 8344 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8345 ParamType == InvalidAddrSpacePtrKernelParam) { 8346 S.Diag(Param->getLocation(), 8347 diag::err_record_with_pointers_kernel_param) 8348 << PT->isUnionType() 8349 << PT; 8350 } else { 8351 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8352 } 8353 8354 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8355 << OrigRecDecl->getDeclName(); 8356 8357 // We have an error, now let's go back up through history and show where 8358 // the offending field came from 8359 for (ArrayRef<const FieldDecl *>::const_iterator 8360 I = HistoryStack.begin() + 1, 8361 E = HistoryStack.end(); 8362 I != E; ++I) { 8363 const FieldDecl *OuterField = *I; 8364 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8365 << OuterField->getType(); 8366 } 8367 8368 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8369 << QT->isPointerType() 8370 << QT; 8371 D.setInvalidType(); 8372 return; 8373 } 8374 } while (!VisitStack.empty()); 8375 } 8376 8377 /// Find the DeclContext in which a tag is implicitly declared if we see an 8378 /// elaborated type specifier in the specified context, and lookup finds 8379 /// nothing. 8380 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8381 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8382 DC = DC->getParent(); 8383 return DC; 8384 } 8385 8386 /// Find the Scope in which a tag is implicitly declared if we see an 8387 /// elaborated type specifier in the specified context, and lookup finds 8388 /// nothing. 8389 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8390 while (S->isClassScope() || 8391 (LangOpts.CPlusPlus && 8392 S->isFunctionPrototypeScope()) || 8393 ((S->getFlags() & Scope::DeclScope) == 0) || 8394 (S->getEntity() && S->getEntity()->isTransparentContext())) 8395 S = S->getParent(); 8396 return S; 8397 } 8398 8399 NamedDecl* 8400 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8401 TypeSourceInfo *TInfo, LookupResult &Previous, 8402 MultiTemplateParamsArg TemplateParamLists, 8403 bool &AddToScope) { 8404 QualType R = TInfo->getType(); 8405 8406 assert(R->isFunctionType()); 8407 8408 // TODO: consider using NameInfo for diagnostic. 8409 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8410 DeclarationName Name = NameInfo.getName(); 8411 StorageClass SC = getFunctionStorageClass(*this, D); 8412 8413 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8414 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8415 diag::err_invalid_thread) 8416 << DeclSpec::getSpecifierName(TSCS); 8417 8418 if (D.isFirstDeclarationOfMember()) 8419 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8420 D.getIdentifierLoc()); 8421 8422 bool isFriend = false; 8423 FunctionTemplateDecl *FunctionTemplate = nullptr; 8424 bool isMemberSpecialization = false; 8425 bool isFunctionTemplateSpecialization = false; 8426 8427 bool isDependentClassScopeExplicitSpecialization = false; 8428 bool HasExplicitTemplateArgs = false; 8429 TemplateArgumentListInfo TemplateArgs; 8430 8431 bool isVirtualOkay = false; 8432 8433 DeclContext *OriginalDC = DC; 8434 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8435 8436 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8437 isVirtualOkay); 8438 if (!NewFD) return nullptr; 8439 8440 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8441 NewFD->setTopLevelDeclInObjCContainer(); 8442 8443 // Set the lexical context. If this is a function-scope declaration, or has a 8444 // C++ scope specifier, or is the object of a friend declaration, the lexical 8445 // context will be different from the semantic context. 8446 NewFD->setLexicalDeclContext(CurContext); 8447 8448 if (IsLocalExternDecl) 8449 NewFD->setLocalExternDecl(); 8450 8451 if (getLangOpts().CPlusPlus) { 8452 bool isInline = D.getDeclSpec().isInlineSpecified(); 8453 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8454 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8455 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8456 isFriend = D.getDeclSpec().isFriendSpecified(); 8457 if (isFriend && !isInline && D.isFunctionDefinition()) { 8458 // C++ [class.friend]p5 8459 // A function can be defined in a friend declaration of a 8460 // class . . . . Such a function is implicitly inline. 8461 NewFD->setImplicitlyInline(); 8462 } 8463 8464 // If this is a method defined in an __interface, and is not a constructor 8465 // or an overloaded operator, then set the pure flag (isVirtual will already 8466 // return true). 8467 if (const CXXRecordDecl *Parent = 8468 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8469 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8470 NewFD->setPure(true); 8471 8472 // C++ [class.union]p2 8473 // A union can have member functions, but not virtual functions. 8474 if (isVirtual && Parent->isUnion()) 8475 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8476 } 8477 8478 SetNestedNameSpecifier(*this, NewFD, D); 8479 isMemberSpecialization = false; 8480 isFunctionTemplateSpecialization = false; 8481 if (D.isInvalidType()) 8482 NewFD->setInvalidDecl(); 8483 8484 // Match up the template parameter lists with the scope specifier, then 8485 // determine whether we have a template or a template specialization. 8486 bool Invalid = false; 8487 if (TemplateParameterList *TemplateParams = 8488 MatchTemplateParametersToScopeSpecifier( 8489 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8490 D.getCXXScopeSpec(), 8491 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8492 ? D.getName().TemplateId 8493 : nullptr, 8494 TemplateParamLists, isFriend, isMemberSpecialization, 8495 Invalid)) { 8496 if (TemplateParams->size() > 0) { 8497 // This is a function template 8498 8499 // Check that we can declare a template here. 8500 if (CheckTemplateDeclScope(S, TemplateParams)) 8501 NewFD->setInvalidDecl(); 8502 8503 // A destructor cannot be a template. 8504 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8505 Diag(NewFD->getLocation(), diag::err_destructor_template); 8506 NewFD->setInvalidDecl(); 8507 } 8508 8509 // If we're adding a template to a dependent context, we may need to 8510 // rebuilding some of the types used within the template parameter list, 8511 // now that we know what the current instantiation is. 8512 if (DC->isDependentContext()) { 8513 ContextRAII SavedContext(*this, DC); 8514 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8515 Invalid = true; 8516 } 8517 8518 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8519 NewFD->getLocation(), 8520 Name, TemplateParams, 8521 NewFD); 8522 FunctionTemplate->setLexicalDeclContext(CurContext); 8523 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8524 8525 // For source fidelity, store the other template param lists. 8526 if (TemplateParamLists.size() > 1) { 8527 NewFD->setTemplateParameterListsInfo(Context, 8528 TemplateParamLists.drop_back(1)); 8529 } 8530 } else { 8531 // This is a function template specialization. 8532 isFunctionTemplateSpecialization = true; 8533 // For source fidelity, store all the template param lists. 8534 if (TemplateParamLists.size() > 0) 8535 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8536 8537 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8538 if (isFriend) { 8539 // We want to remove the "template<>", found here. 8540 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8541 8542 // If we remove the template<> and the name is not a 8543 // template-id, we're actually silently creating a problem: 8544 // the friend declaration will refer to an untemplated decl, 8545 // and clearly the user wants a template specialization. So 8546 // we need to insert '<>' after the name. 8547 SourceLocation InsertLoc; 8548 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8549 InsertLoc = D.getName().getSourceRange().getEnd(); 8550 InsertLoc = getLocForEndOfToken(InsertLoc); 8551 } 8552 8553 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8554 << Name << RemoveRange 8555 << FixItHint::CreateRemoval(RemoveRange) 8556 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8557 } 8558 } 8559 } else { 8560 // All template param lists were matched against the scope specifier: 8561 // this is NOT (an explicit specialization of) a template. 8562 if (TemplateParamLists.size() > 0) 8563 // For source fidelity, store all the template param lists. 8564 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8565 } 8566 8567 if (Invalid) { 8568 NewFD->setInvalidDecl(); 8569 if (FunctionTemplate) 8570 FunctionTemplate->setInvalidDecl(); 8571 } 8572 8573 // C++ [dcl.fct.spec]p5: 8574 // The virtual specifier shall only be used in declarations of 8575 // nonstatic class member functions that appear within a 8576 // member-specification of a class declaration; see 10.3. 8577 // 8578 if (isVirtual && !NewFD->isInvalidDecl()) { 8579 if (!isVirtualOkay) { 8580 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8581 diag::err_virtual_non_function); 8582 } else if (!CurContext->isRecord()) { 8583 // 'virtual' was specified outside of the class. 8584 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8585 diag::err_virtual_out_of_class) 8586 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8587 } else if (NewFD->getDescribedFunctionTemplate()) { 8588 // C++ [temp.mem]p3: 8589 // A member function template shall not be virtual. 8590 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8591 diag::err_virtual_member_function_template) 8592 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8593 } else { 8594 // Okay: Add virtual to the method. 8595 NewFD->setVirtualAsWritten(true); 8596 } 8597 8598 if (getLangOpts().CPlusPlus14 && 8599 NewFD->getReturnType()->isUndeducedType()) 8600 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8601 } 8602 8603 if (getLangOpts().CPlusPlus14 && 8604 (NewFD->isDependentContext() || 8605 (isFriend && CurContext->isDependentContext())) && 8606 NewFD->getReturnType()->isUndeducedType()) { 8607 // If the function template is referenced directly (for instance, as a 8608 // member of the current instantiation), pretend it has a dependent type. 8609 // This is not really justified by the standard, but is the only sane 8610 // thing to do. 8611 // FIXME: For a friend function, we have not marked the function as being 8612 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8613 const FunctionProtoType *FPT = 8614 NewFD->getType()->castAs<FunctionProtoType>(); 8615 QualType Result = 8616 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8617 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8618 FPT->getExtProtoInfo())); 8619 } 8620 8621 // C++ [dcl.fct.spec]p3: 8622 // The inline specifier shall not appear on a block scope function 8623 // declaration. 8624 if (isInline && !NewFD->isInvalidDecl()) { 8625 if (CurContext->isFunctionOrMethod()) { 8626 // 'inline' is not allowed on block scope function declaration. 8627 Diag(D.getDeclSpec().getInlineSpecLoc(), 8628 diag::err_inline_declaration_block_scope) << Name 8629 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8630 } 8631 } 8632 8633 // C++ [dcl.fct.spec]p6: 8634 // The explicit specifier shall be used only in the declaration of a 8635 // constructor or conversion function within its class definition; 8636 // see 12.3.1 and 12.3.2. 8637 if (hasExplicit && !NewFD->isInvalidDecl() && 8638 !isa<CXXDeductionGuideDecl>(NewFD)) { 8639 if (!CurContext->isRecord()) { 8640 // 'explicit' was specified outside of the class. 8641 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8642 diag::err_explicit_out_of_class) 8643 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 8644 } else if (!isa<CXXConstructorDecl>(NewFD) && 8645 !isa<CXXConversionDecl>(NewFD)) { 8646 // 'explicit' was specified on a function that wasn't a constructor 8647 // or conversion function. 8648 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8649 diag::err_explicit_non_ctor_or_conv_function) 8650 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 8651 } 8652 } 8653 8654 if (ConstexprKind != CSK_unspecified) { 8655 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8656 // are implicitly inline. 8657 NewFD->setImplicitlyInline(); 8658 8659 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8660 // be either constructors or to return a literal type. Therefore, 8661 // destructors cannot be declared constexpr. 8662 if (isa<CXXDestructorDecl>(NewFD)) 8663 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 8664 << (ConstexprKind == CSK_consteval); 8665 } 8666 8667 // If __module_private__ was specified, mark the function accordingly. 8668 if (D.getDeclSpec().isModulePrivateSpecified()) { 8669 if (isFunctionTemplateSpecialization) { 8670 SourceLocation ModulePrivateLoc 8671 = D.getDeclSpec().getModulePrivateSpecLoc(); 8672 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8673 << 0 8674 << FixItHint::CreateRemoval(ModulePrivateLoc); 8675 } else { 8676 NewFD->setModulePrivate(); 8677 if (FunctionTemplate) 8678 FunctionTemplate->setModulePrivate(); 8679 } 8680 } 8681 8682 if (isFriend) { 8683 if (FunctionTemplate) { 8684 FunctionTemplate->setObjectOfFriendDecl(); 8685 FunctionTemplate->setAccess(AS_public); 8686 } 8687 NewFD->setObjectOfFriendDecl(); 8688 NewFD->setAccess(AS_public); 8689 } 8690 8691 // If a function is defined as defaulted or deleted, mark it as such now. 8692 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8693 // definition kind to FDK_Definition. 8694 switch (D.getFunctionDefinitionKind()) { 8695 case FDK_Declaration: 8696 case FDK_Definition: 8697 break; 8698 8699 case FDK_Defaulted: 8700 NewFD->setDefaulted(); 8701 break; 8702 8703 case FDK_Deleted: 8704 NewFD->setDeletedAsWritten(); 8705 break; 8706 } 8707 8708 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8709 D.isFunctionDefinition()) { 8710 // C++ [class.mfct]p2: 8711 // A member function may be defined (8.4) in its class definition, in 8712 // which case it is an inline member function (7.1.2) 8713 NewFD->setImplicitlyInline(); 8714 } 8715 8716 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8717 !CurContext->isRecord()) { 8718 // C++ [class.static]p1: 8719 // A data or function member of a class may be declared static 8720 // in a class definition, in which case it is a static member of 8721 // the class. 8722 8723 // Complain about the 'static' specifier if it's on an out-of-line 8724 // member function definition. 8725 8726 // MSVC permits the use of a 'static' storage specifier on an out-of-line 8727 // member function template declaration and class member template 8728 // declaration (MSVC versions before 2015), warn about this. 8729 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8730 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 8731 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 8732 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 8733 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 8734 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8735 } 8736 8737 // C++11 [except.spec]p15: 8738 // A deallocation function with no exception-specification is treated 8739 // as if it were specified with noexcept(true). 8740 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8741 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8742 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8743 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8744 NewFD->setType(Context.getFunctionType( 8745 FPT->getReturnType(), FPT->getParamTypes(), 8746 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8747 } 8748 8749 // Filter out previous declarations that don't match the scope. 8750 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8751 D.getCXXScopeSpec().isNotEmpty() || 8752 isMemberSpecialization || 8753 isFunctionTemplateSpecialization); 8754 8755 // Handle GNU asm-label extension (encoded as an attribute). 8756 if (Expr *E = (Expr*) D.getAsmLabel()) { 8757 // The parser guarantees this is a string. 8758 StringLiteral *SE = cast<StringLiteral>(E); 8759 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8760 SE->getString(), 0)); 8761 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8762 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8763 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8764 if (I != ExtnameUndeclaredIdentifiers.end()) { 8765 if (isDeclExternC(NewFD)) { 8766 NewFD->addAttr(I->second); 8767 ExtnameUndeclaredIdentifiers.erase(I); 8768 } else 8769 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8770 << /*Variable*/0 << NewFD; 8771 } 8772 } 8773 8774 // Copy the parameter declarations from the declarator D to the function 8775 // declaration NewFD, if they are available. First scavenge them into Params. 8776 SmallVector<ParmVarDecl*, 16> Params; 8777 unsigned FTIIdx; 8778 if (D.isFunctionDeclarator(FTIIdx)) { 8779 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8780 8781 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8782 // function that takes no arguments, not a function that takes a 8783 // single void argument. 8784 // We let through "const void" here because Sema::GetTypeForDeclarator 8785 // already checks for that case. 8786 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8787 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8788 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8789 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8790 Param->setDeclContext(NewFD); 8791 Params.push_back(Param); 8792 8793 if (Param->isInvalidDecl()) 8794 NewFD->setInvalidDecl(); 8795 } 8796 } 8797 8798 if (!getLangOpts().CPlusPlus) { 8799 // In C, find all the tag declarations from the prototype and move them 8800 // into the function DeclContext. Remove them from the surrounding tag 8801 // injection context of the function, which is typically but not always 8802 // the TU. 8803 DeclContext *PrototypeTagContext = 8804 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8805 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8806 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8807 8808 // We don't want to reparent enumerators. Look at their parent enum 8809 // instead. 8810 if (!TD) { 8811 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8812 TD = cast<EnumDecl>(ECD->getDeclContext()); 8813 } 8814 if (!TD) 8815 continue; 8816 DeclContext *TagDC = TD->getLexicalDeclContext(); 8817 if (!TagDC->containsDecl(TD)) 8818 continue; 8819 TagDC->removeDecl(TD); 8820 TD->setDeclContext(NewFD); 8821 NewFD->addDecl(TD); 8822 8823 // Preserve the lexical DeclContext if it is not the surrounding tag 8824 // injection context of the FD. In this example, the semantic context of 8825 // E will be f and the lexical context will be S, while both the 8826 // semantic and lexical contexts of S will be f: 8827 // void f(struct S { enum E { a } f; } s); 8828 if (TagDC != PrototypeTagContext) 8829 TD->setLexicalDeclContext(TagDC); 8830 } 8831 } 8832 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8833 // When we're declaring a function with a typedef, typeof, etc as in the 8834 // following example, we'll need to synthesize (unnamed) 8835 // parameters for use in the declaration. 8836 // 8837 // @code 8838 // typedef void fn(int); 8839 // fn f; 8840 // @endcode 8841 8842 // Synthesize a parameter for each argument type. 8843 for (const auto &AI : FT->param_types()) { 8844 ParmVarDecl *Param = 8845 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8846 Param->setScopeInfo(0, Params.size()); 8847 Params.push_back(Param); 8848 } 8849 } else { 8850 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8851 "Should not need args for typedef of non-prototype fn"); 8852 } 8853 8854 // Finally, we know we have the right number of parameters, install them. 8855 NewFD->setParams(Params); 8856 8857 if (D.getDeclSpec().isNoreturnSpecified()) 8858 NewFD->addAttr( 8859 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8860 Context, 0)); 8861 8862 // Functions returning a variably modified type violate C99 6.7.5.2p2 8863 // because all functions have linkage. 8864 if (!NewFD->isInvalidDecl() && 8865 NewFD->getReturnType()->isVariablyModifiedType()) { 8866 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8867 NewFD->setInvalidDecl(); 8868 } 8869 8870 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8871 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8872 !NewFD->hasAttr<SectionAttr>()) { 8873 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8874 PragmaClangTextSection.SectionName, 8875 PragmaClangTextSection.PragmaLocation)); 8876 } 8877 8878 // Apply an implicit SectionAttr if #pragma code_seg is active. 8879 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8880 !NewFD->hasAttr<SectionAttr>()) { 8881 NewFD->addAttr( 8882 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8883 CodeSegStack.CurrentValue->getString(), 8884 CodeSegStack.CurrentPragmaLocation)); 8885 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8886 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8887 ASTContext::PSF_Read, 8888 NewFD)) 8889 NewFD->dropAttr<SectionAttr>(); 8890 } 8891 8892 // Apply an implicit CodeSegAttr from class declspec or 8893 // apply an implicit SectionAttr from #pragma code_seg if active. 8894 if (!NewFD->hasAttr<CodeSegAttr>()) { 8895 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 8896 D.isFunctionDefinition())) { 8897 NewFD->addAttr(SAttr); 8898 } 8899 } 8900 8901 // Handle attributes. 8902 ProcessDeclAttributes(S, NewFD, D); 8903 8904 if (getLangOpts().OpenCL) { 8905 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8906 // type declaration will generate a compilation error. 8907 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 8908 if (AddressSpace != LangAS::Default) { 8909 Diag(NewFD->getLocation(), 8910 diag::err_opencl_return_value_with_address_space); 8911 NewFD->setInvalidDecl(); 8912 } 8913 } 8914 8915 if (!getLangOpts().CPlusPlus) { 8916 // Perform semantic checking on the function declaration. 8917 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8918 CheckMain(NewFD, D.getDeclSpec()); 8919 8920 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8921 CheckMSVCRTEntryPoint(NewFD); 8922 8923 if (!NewFD->isInvalidDecl()) 8924 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8925 isMemberSpecialization)); 8926 else if (!Previous.empty()) 8927 // Recover gracefully from an invalid redeclaration. 8928 D.setRedeclaration(true); 8929 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8930 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8931 "previous declaration set still overloaded"); 8932 8933 // Diagnose no-prototype function declarations with calling conventions that 8934 // don't support variadic calls. Only do this in C and do it after merging 8935 // possibly prototyped redeclarations. 8936 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8937 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8938 CallingConv CC = FT->getExtInfo().getCC(); 8939 if (!supportsVariadicCall(CC)) { 8940 // Windows system headers sometimes accidentally use stdcall without 8941 // (void) parameters, so we relax this to a warning. 8942 int DiagID = 8943 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8944 Diag(NewFD->getLocation(), DiagID) 8945 << FunctionType::getNameForCallConv(CC); 8946 } 8947 } 8948 } else { 8949 // C++11 [replacement.functions]p3: 8950 // The program's definitions shall not be specified as inline. 8951 // 8952 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8953 // 8954 // Suppress the diagnostic if the function is __attribute__((used)), since 8955 // that forces an external definition to be emitted. 8956 if (D.getDeclSpec().isInlineSpecified() && 8957 NewFD->isReplaceableGlobalAllocationFunction() && 8958 !NewFD->hasAttr<UsedAttr>()) 8959 Diag(D.getDeclSpec().getInlineSpecLoc(), 8960 diag::ext_operator_new_delete_declared_inline) 8961 << NewFD->getDeclName(); 8962 8963 // If the declarator is a template-id, translate the parser's template 8964 // argument list into our AST format. 8965 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 8966 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8967 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8968 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8969 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8970 TemplateId->NumArgs); 8971 translateTemplateArguments(TemplateArgsPtr, 8972 TemplateArgs); 8973 8974 HasExplicitTemplateArgs = true; 8975 8976 if (NewFD->isInvalidDecl()) { 8977 HasExplicitTemplateArgs = false; 8978 } else if (FunctionTemplate) { 8979 // Function template with explicit template arguments. 8980 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8981 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8982 8983 HasExplicitTemplateArgs = false; 8984 } else { 8985 assert((isFunctionTemplateSpecialization || 8986 D.getDeclSpec().isFriendSpecified()) && 8987 "should have a 'template<>' for this decl"); 8988 // "friend void foo<>(int);" is an implicit specialization decl. 8989 isFunctionTemplateSpecialization = true; 8990 } 8991 } else if (isFriend && isFunctionTemplateSpecialization) { 8992 // This combination is only possible in a recovery case; the user 8993 // wrote something like: 8994 // template <> friend void foo(int); 8995 // which we're recovering from as if the user had written: 8996 // friend void foo<>(int); 8997 // Go ahead and fake up a template id. 8998 HasExplicitTemplateArgs = true; 8999 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9000 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9001 } 9002 9003 // We do not add HD attributes to specializations here because 9004 // they may have different constexpr-ness compared to their 9005 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9006 // may end up with different effective targets. Instead, a 9007 // specialization inherits its target attributes from its template 9008 // in the CheckFunctionTemplateSpecialization() call below. 9009 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 9010 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9011 9012 // If it's a friend (and only if it's a friend), it's possible 9013 // that either the specialized function type or the specialized 9014 // template is dependent, and therefore matching will fail. In 9015 // this case, don't check the specialization yet. 9016 bool InstantiationDependent = false; 9017 if (isFunctionTemplateSpecialization && isFriend && 9018 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9019 TemplateSpecializationType::anyDependentTemplateArguments( 9020 TemplateArgs, 9021 InstantiationDependent))) { 9022 assert(HasExplicitTemplateArgs && 9023 "friend function specialization without template args"); 9024 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9025 Previous)) 9026 NewFD->setInvalidDecl(); 9027 } else if (isFunctionTemplateSpecialization) { 9028 if (CurContext->isDependentContext() && CurContext->isRecord() 9029 && !isFriend) { 9030 isDependentClassScopeExplicitSpecialization = true; 9031 } else if (!NewFD->isInvalidDecl() && 9032 CheckFunctionTemplateSpecialization( 9033 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9034 Previous)) 9035 NewFD->setInvalidDecl(); 9036 9037 // C++ [dcl.stc]p1: 9038 // A storage-class-specifier shall not be specified in an explicit 9039 // specialization (14.7.3) 9040 FunctionTemplateSpecializationInfo *Info = 9041 NewFD->getTemplateSpecializationInfo(); 9042 if (Info && SC != SC_None) { 9043 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9044 Diag(NewFD->getLocation(), 9045 diag::err_explicit_specialization_inconsistent_storage_class) 9046 << SC 9047 << FixItHint::CreateRemoval( 9048 D.getDeclSpec().getStorageClassSpecLoc()); 9049 9050 else 9051 Diag(NewFD->getLocation(), 9052 diag::ext_explicit_specialization_storage_class) 9053 << FixItHint::CreateRemoval( 9054 D.getDeclSpec().getStorageClassSpecLoc()); 9055 } 9056 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9057 if (CheckMemberSpecialization(NewFD, Previous)) 9058 NewFD->setInvalidDecl(); 9059 } 9060 9061 // Perform semantic checking on the function declaration. 9062 if (!isDependentClassScopeExplicitSpecialization) { 9063 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9064 CheckMain(NewFD, D.getDeclSpec()); 9065 9066 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9067 CheckMSVCRTEntryPoint(NewFD); 9068 9069 if (!NewFD->isInvalidDecl()) 9070 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9071 isMemberSpecialization)); 9072 else if (!Previous.empty()) 9073 // Recover gracefully from an invalid redeclaration. 9074 D.setRedeclaration(true); 9075 } 9076 9077 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9078 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9079 "previous declaration set still overloaded"); 9080 9081 NamedDecl *PrincipalDecl = (FunctionTemplate 9082 ? cast<NamedDecl>(FunctionTemplate) 9083 : NewFD); 9084 9085 if (isFriend && NewFD->getPreviousDecl()) { 9086 AccessSpecifier Access = AS_public; 9087 if (!NewFD->isInvalidDecl()) 9088 Access = NewFD->getPreviousDecl()->getAccess(); 9089 9090 NewFD->setAccess(Access); 9091 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9092 } 9093 9094 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9095 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9096 PrincipalDecl->setNonMemberOperator(); 9097 9098 // If we have a function template, check the template parameter 9099 // list. This will check and merge default template arguments. 9100 if (FunctionTemplate) { 9101 FunctionTemplateDecl *PrevTemplate = 9102 FunctionTemplate->getPreviousDecl(); 9103 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9104 PrevTemplate ? PrevTemplate->getTemplateParameters() 9105 : nullptr, 9106 D.getDeclSpec().isFriendSpecified() 9107 ? (D.isFunctionDefinition() 9108 ? TPC_FriendFunctionTemplateDefinition 9109 : TPC_FriendFunctionTemplate) 9110 : (D.getCXXScopeSpec().isSet() && 9111 DC && DC->isRecord() && 9112 DC->isDependentContext()) 9113 ? TPC_ClassTemplateMember 9114 : TPC_FunctionTemplate); 9115 } 9116 9117 if (NewFD->isInvalidDecl()) { 9118 // Ignore all the rest of this. 9119 } else if (!D.isRedeclaration()) { 9120 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9121 AddToScope }; 9122 // Fake up an access specifier if it's supposed to be a class member. 9123 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9124 NewFD->setAccess(AS_public); 9125 9126 // Qualified decls generally require a previous declaration. 9127 if (D.getCXXScopeSpec().isSet()) { 9128 // ...with the major exception of templated-scope or 9129 // dependent-scope friend declarations. 9130 9131 // TODO: we currently also suppress this check in dependent 9132 // contexts because (1) the parameter depth will be off when 9133 // matching friend templates and (2) we might actually be 9134 // selecting a friend based on a dependent factor. But there 9135 // are situations where these conditions don't apply and we 9136 // can actually do this check immediately. 9137 // 9138 // Unless the scope is dependent, it's always an error if qualified 9139 // redeclaration lookup found nothing at all. Diagnose that now; 9140 // nothing will diagnose that error later. 9141 if (isFriend && 9142 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9143 (!Previous.empty() && CurContext->isDependentContext()))) { 9144 // ignore these 9145 } else { 9146 // The user tried to provide an out-of-line definition for a 9147 // function that is a member of a class or namespace, but there 9148 // was no such member function declared (C++ [class.mfct]p2, 9149 // C++ [namespace.memdef]p2). For example: 9150 // 9151 // class X { 9152 // void f() const; 9153 // }; 9154 // 9155 // void X::f() { } // ill-formed 9156 // 9157 // Complain about this problem, and attempt to suggest close 9158 // matches (e.g., those that differ only in cv-qualifiers and 9159 // whether the parameter types are references). 9160 9161 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9162 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9163 AddToScope = ExtraArgs.AddToScope; 9164 return Result; 9165 } 9166 } 9167 9168 // Unqualified local friend declarations are required to resolve 9169 // to something. 9170 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9171 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9172 *this, Previous, NewFD, ExtraArgs, true, S)) { 9173 AddToScope = ExtraArgs.AddToScope; 9174 return Result; 9175 } 9176 } 9177 } else if (!D.isFunctionDefinition() && 9178 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9179 !isFriend && !isFunctionTemplateSpecialization && 9180 !isMemberSpecialization) { 9181 // An out-of-line member function declaration must also be a 9182 // definition (C++ [class.mfct]p2). 9183 // Note that this is not the case for explicit specializations of 9184 // function templates or member functions of class templates, per 9185 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9186 // extension for compatibility with old SWIG code which likes to 9187 // generate them. 9188 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9189 << D.getCXXScopeSpec().getRange(); 9190 } 9191 } 9192 9193 ProcessPragmaWeak(S, NewFD); 9194 checkAttributesAfterMerging(*this, *NewFD); 9195 9196 AddKnownFunctionAttributes(NewFD); 9197 9198 if (NewFD->hasAttr<OverloadableAttr>() && 9199 !NewFD->getType()->getAs<FunctionProtoType>()) { 9200 Diag(NewFD->getLocation(), 9201 diag::err_attribute_overloadable_no_prototype) 9202 << NewFD; 9203 9204 // Turn this into a variadic function with no parameters. 9205 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9206 FunctionProtoType::ExtProtoInfo EPI( 9207 Context.getDefaultCallingConvention(true, false)); 9208 EPI.Variadic = true; 9209 EPI.ExtInfo = FT->getExtInfo(); 9210 9211 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9212 NewFD->setType(R); 9213 } 9214 9215 // If there's a #pragma GCC visibility in scope, and this isn't a class 9216 // member, set the visibility of this function. 9217 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9218 AddPushedVisibilityAttribute(NewFD); 9219 9220 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9221 // marking the function. 9222 AddCFAuditedAttribute(NewFD); 9223 9224 // If this is a function definition, check if we have to apply optnone due to 9225 // a pragma. 9226 if(D.isFunctionDefinition()) 9227 AddRangeBasedOptnone(NewFD); 9228 9229 // If this is the first declaration of an extern C variable, update 9230 // the map of such variables. 9231 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9232 isIncompleteDeclExternC(*this, NewFD)) 9233 RegisterLocallyScopedExternCDecl(NewFD, S); 9234 9235 // Set this FunctionDecl's range up to the right paren. 9236 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9237 9238 if (D.isRedeclaration() && !Previous.empty()) { 9239 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9240 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9241 isMemberSpecialization || 9242 isFunctionTemplateSpecialization, 9243 D.isFunctionDefinition()); 9244 } 9245 9246 if (getLangOpts().CUDA) { 9247 IdentifierInfo *II = NewFD->getIdentifier(); 9248 if (II && II->isStr(getCudaConfigureFuncName()) && 9249 !NewFD->isInvalidDecl() && 9250 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9251 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9252 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9253 << getCudaConfigureFuncName(); 9254 Context.setcudaConfigureCallDecl(NewFD); 9255 } 9256 9257 // Variadic functions, other than a *declaration* of printf, are not allowed 9258 // in device-side CUDA code, unless someone passed 9259 // -fcuda-allow-variadic-functions. 9260 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9261 (NewFD->hasAttr<CUDADeviceAttr>() || 9262 NewFD->hasAttr<CUDAGlobalAttr>()) && 9263 !(II && II->isStr("printf") && NewFD->isExternC() && 9264 !D.isFunctionDefinition())) { 9265 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9266 } 9267 } 9268 9269 MarkUnusedFileScopedDecl(NewFD); 9270 9271 9272 9273 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9274 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9275 if ((getLangOpts().OpenCLVersion >= 120) 9276 && (SC == SC_Static)) { 9277 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9278 D.setInvalidType(); 9279 } 9280 9281 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9282 if (!NewFD->getReturnType()->isVoidType()) { 9283 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9284 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9285 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9286 : FixItHint()); 9287 D.setInvalidType(); 9288 } 9289 9290 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9291 for (auto Param : NewFD->parameters()) 9292 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9293 9294 if (getLangOpts().OpenCLCPlusPlus) { 9295 if (DC->isRecord()) { 9296 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9297 D.setInvalidType(); 9298 } 9299 if (FunctionTemplate) { 9300 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9301 D.setInvalidType(); 9302 } 9303 } 9304 } 9305 9306 if (getLangOpts().CPlusPlus) { 9307 if (FunctionTemplate) { 9308 if (NewFD->isInvalidDecl()) 9309 FunctionTemplate->setInvalidDecl(); 9310 return FunctionTemplate; 9311 } 9312 9313 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9314 CompleteMemberSpecialization(NewFD, Previous); 9315 } 9316 9317 for (const ParmVarDecl *Param : NewFD->parameters()) { 9318 QualType PT = Param->getType(); 9319 9320 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9321 // types. 9322 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9323 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9324 QualType ElemTy = PipeTy->getElementType(); 9325 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9326 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9327 D.setInvalidType(); 9328 } 9329 } 9330 } 9331 } 9332 9333 // Here we have an function template explicit specialization at class scope. 9334 // The actual specialization will be postponed to template instatiation 9335 // time via the ClassScopeFunctionSpecializationDecl node. 9336 if (isDependentClassScopeExplicitSpecialization) { 9337 ClassScopeFunctionSpecializationDecl *NewSpec = 9338 ClassScopeFunctionSpecializationDecl::Create( 9339 Context, CurContext, NewFD->getLocation(), 9340 cast<CXXMethodDecl>(NewFD), 9341 HasExplicitTemplateArgs, TemplateArgs); 9342 CurContext->addDecl(NewSpec); 9343 AddToScope = false; 9344 } 9345 9346 // Diagnose availability attributes. Availability cannot be used on functions 9347 // that are run during load/unload. 9348 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9349 if (NewFD->hasAttr<ConstructorAttr>()) { 9350 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9351 << 1; 9352 NewFD->dropAttr<AvailabilityAttr>(); 9353 } 9354 if (NewFD->hasAttr<DestructorAttr>()) { 9355 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9356 << 2; 9357 NewFD->dropAttr<AvailabilityAttr>(); 9358 } 9359 } 9360 9361 return NewFD; 9362 } 9363 9364 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9365 /// when __declspec(code_seg) "is applied to a class, all member functions of 9366 /// the class and nested classes -- this includes compiler-generated special 9367 /// member functions -- are put in the specified segment." 9368 /// The actual behavior is a little more complicated. The Microsoft compiler 9369 /// won't check outer classes if there is an active value from #pragma code_seg. 9370 /// The CodeSeg is always applied from the direct parent but only from outer 9371 /// classes when the #pragma code_seg stack is empty. See: 9372 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9373 /// available since MS has removed the page. 9374 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9375 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9376 if (!Method) 9377 return nullptr; 9378 const CXXRecordDecl *Parent = Method->getParent(); 9379 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9380 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9381 NewAttr->setImplicit(true); 9382 return NewAttr; 9383 } 9384 9385 // The Microsoft compiler won't check outer classes for the CodeSeg 9386 // when the #pragma code_seg stack is active. 9387 if (S.CodeSegStack.CurrentValue) 9388 return nullptr; 9389 9390 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9391 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9392 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9393 NewAttr->setImplicit(true); 9394 return NewAttr; 9395 } 9396 } 9397 return nullptr; 9398 } 9399 9400 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9401 /// containing class. Otherwise it will return implicit SectionAttr if the 9402 /// function is a definition and there is an active value on CodeSegStack 9403 /// (from the current #pragma code-seg value). 9404 /// 9405 /// \param FD Function being declared. 9406 /// \param IsDefinition Whether it is a definition or just a declarartion. 9407 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9408 /// nullptr if no attribute should be added. 9409 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9410 bool IsDefinition) { 9411 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9412 return A; 9413 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9414 CodeSegStack.CurrentValue) { 9415 return SectionAttr::CreateImplicit(getASTContext(), 9416 SectionAttr::Declspec_allocate, 9417 CodeSegStack.CurrentValue->getString(), 9418 CodeSegStack.CurrentPragmaLocation); 9419 } 9420 return nullptr; 9421 } 9422 9423 /// Determines if we can perform a correct type check for \p D as a 9424 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9425 /// best-effort check. 9426 /// 9427 /// \param NewD The new declaration. 9428 /// \param OldD The old declaration. 9429 /// \param NewT The portion of the type of the new declaration to check. 9430 /// \param OldT The portion of the type of the old declaration to check. 9431 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9432 QualType NewT, QualType OldT) { 9433 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9434 return true; 9435 9436 // For dependently-typed local extern declarations and friends, we can't 9437 // perform a correct type check in general until instantiation: 9438 // 9439 // int f(); 9440 // template<typename T> void g() { T f(); } 9441 // 9442 // (valid if g() is only instantiated with T = int). 9443 if (NewT->isDependentType() && 9444 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9445 return false; 9446 9447 // Similarly, if the previous declaration was a dependent local extern 9448 // declaration, we don't really know its type yet. 9449 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9450 return false; 9451 9452 return true; 9453 } 9454 9455 /// Checks if the new declaration declared in dependent context must be 9456 /// put in the same redeclaration chain as the specified declaration. 9457 /// 9458 /// \param D Declaration that is checked. 9459 /// \param PrevDecl Previous declaration found with proper lookup method for the 9460 /// same declaration name. 9461 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9462 /// belongs to. 9463 /// 9464 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9465 if (!D->getLexicalDeclContext()->isDependentContext()) 9466 return true; 9467 9468 // Don't chain dependent friend function definitions until instantiation, to 9469 // permit cases like 9470 // 9471 // void func(); 9472 // template<typename T> class C1 { friend void func() {} }; 9473 // template<typename T> class C2 { friend void func() {} }; 9474 // 9475 // ... which is valid if only one of C1 and C2 is ever instantiated. 9476 // 9477 // FIXME: This need only apply to function definitions. For now, we proxy 9478 // this by checking for a file-scope function. We do not want this to apply 9479 // to friend declarations nominating member functions, because that gets in 9480 // the way of access checks. 9481 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9482 return false; 9483 9484 auto *VD = dyn_cast<ValueDecl>(D); 9485 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9486 return !VD || !PrevVD || 9487 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9488 PrevVD->getType()); 9489 } 9490 9491 /// Check the target attribute of the function for MultiVersion 9492 /// validity. 9493 /// 9494 /// Returns true if there was an error, false otherwise. 9495 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9496 const auto *TA = FD->getAttr<TargetAttr>(); 9497 assert(TA && "MultiVersion Candidate requires a target attribute"); 9498 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); 9499 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9500 enum ErrType { Feature = 0, Architecture = 1 }; 9501 9502 if (!ParseInfo.Architecture.empty() && 9503 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9504 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9505 << Architecture << ParseInfo.Architecture; 9506 return true; 9507 } 9508 9509 for (const auto &Feat : ParseInfo.Features) { 9510 auto BareFeat = StringRef{Feat}.substr(1); 9511 if (Feat[0] == '-') { 9512 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9513 << Feature << ("no-" + BareFeat).str(); 9514 return true; 9515 } 9516 9517 if (!TargetInfo.validateCpuSupports(BareFeat) || 9518 !TargetInfo.isValidFeatureName(BareFeat)) { 9519 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9520 << Feature << BareFeat; 9521 return true; 9522 } 9523 } 9524 return false; 9525 } 9526 9527 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9528 MultiVersionKind MVType) { 9529 for (const Attr *A : FD->attrs()) { 9530 switch (A->getKind()) { 9531 case attr::CPUDispatch: 9532 case attr::CPUSpecific: 9533 if (MVType != MultiVersionKind::CPUDispatch && 9534 MVType != MultiVersionKind::CPUSpecific) 9535 return true; 9536 break; 9537 case attr::Target: 9538 if (MVType != MultiVersionKind::Target) 9539 return true; 9540 break; 9541 default: 9542 return true; 9543 } 9544 } 9545 return false; 9546 } 9547 9548 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 9549 const FunctionDecl *NewFD, 9550 bool CausesMV, 9551 MultiVersionKind MVType) { 9552 enum DoesntSupport { 9553 FuncTemplates = 0, 9554 VirtFuncs = 1, 9555 DeducedReturn = 2, 9556 Constructors = 3, 9557 Destructors = 4, 9558 DeletedFuncs = 5, 9559 DefaultedFuncs = 6, 9560 ConstexprFuncs = 7, 9561 ConstevalFuncs = 8, 9562 }; 9563 enum Different { 9564 CallingConv = 0, 9565 ReturnType = 1, 9566 ConstexprSpec = 2, 9567 InlineSpec = 3, 9568 StorageClass = 4, 9569 Linkage = 5 9570 }; 9571 9572 bool IsCPUSpecificCPUDispatchMVType = 9573 MVType == MultiVersionKind::CPUDispatch || 9574 MVType == MultiVersionKind::CPUSpecific; 9575 9576 if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) { 9577 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); 9578 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9579 return true; 9580 } 9581 9582 if (!NewFD->getType()->getAs<FunctionProtoType>()) 9583 return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 9584 9585 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9586 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9587 if (OldFD) 9588 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9589 return true; 9590 } 9591 9592 // For now, disallow all other attributes. These should be opt-in, but 9593 // an analysis of all of them is a future FIXME. 9594 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 9595 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 9596 << IsCPUSpecificCPUDispatchMVType; 9597 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9598 return true; 9599 } 9600 9601 if (HasNonMultiVersionAttributes(NewFD, MVType)) 9602 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 9603 << IsCPUSpecificCPUDispatchMVType; 9604 9605 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9606 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9607 << IsCPUSpecificCPUDispatchMVType << FuncTemplates; 9608 9609 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 9610 if (NewCXXFD->isVirtual()) 9611 return S.Diag(NewCXXFD->getLocation(), 9612 diag::err_multiversion_doesnt_support) 9613 << IsCPUSpecificCPUDispatchMVType << VirtFuncs; 9614 9615 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) 9616 return S.Diag(NewCXXCtor->getLocation(), 9617 diag::err_multiversion_doesnt_support) 9618 << IsCPUSpecificCPUDispatchMVType << Constructors; 9619 9620 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) 9621 return S.Diag(NewCXXDtor->getLocation(), 9622 diag::err_multiversion_doesnt_support) 9623 << IsCPUSpecificCPUDispatchMVType << Destructors; 9624 } 9625 9626 if (NewFD->isDeleted()) 9627 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9628 << IsCPUSpecificCPUDispatchMVType << DeletedFuncs; 9629 9630 if (NewFD->isDefaulted()) 9631 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9632 << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs; 9633 9634 if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch || 9635 MVType == MultiVersionKind::CPUSpecific)) 9636 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9637 << IsCPUSpecificCPUDispatchMVType 9638 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 9639 9640 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); 9641 const auto *NewType = cast<FunctionType>(NewQType); 9642 QualType NewReturnType = NewType->getReturnType(); 9643 9644 if (NewReturnType->isUndeducedType()) 9645 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9646 << IsCPUSpecificCPUDispatchMVType << DeducedReturn; 9647 9648 // Only allow transition to MultiVersion if it hasn't been used. 9649 if (OldFD && CausesMV && OldFD->isUsed(false)) 9650 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 9651 9652 // Ensure the return type is identical. 9653 if (OldFD) { 9654 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); 9655 const auto *OldType = cast<FunctionType>(OldQType); 9656 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 9657 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 9658 9659 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 9660 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9661 << CallingConv; 9662 9663 QualType OldReturnType = OldType->getReturnType(); 9664 9665 if (OldReturnType != NewReturnType) 9666 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9667 << ReturnType; 9668 9669 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 9670 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9671 << ConstexprSpec; 9672 9673 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 9674 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9675 << InlineSpec; 9676 9677 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 9678 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9679 << StorageClass; 9680 9681 if (OldFD->isExternC() != NewFD->isExternC()) 9682 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9683 << Linkage; 9684 9685 if (S.CheckEquivalentExceptionSpec( 9686 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 9687 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 9688 return true; 9689 } 9690 return false; 9691 } 9692 9693 /// Check the validity of a multiversion function declaration that is the 9694 /// first of its kind. Also sets the multiversion'ness' of the function itself. 9695 /// 9696 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9697 /// 9698 /// Returns true if there was an error, false otherwise. 9699 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 9700 MultiVersionKind MVType, 9701 const TargetAttr *TA) { 9702 assert(MVType != MultiVersionKind::None && 9703 "Function lacks multiversion attribute"); 9704 9705 // Target only causes MV if it is default, otherwise this is a normal 9706 // function. 9707 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 9708 return false; 9709 9710 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 9711 FD->setInvalidDecl(); 9712 return true; 9713 } 9714 9715 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 9716 FD->setInvalidDecl(); 9717 return true; 9718 } 9719 9720 FD->setIsMultiVersion(); 9721 return false; 9722 } 9723 9724 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 9725 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 9726 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 9727 return true; 9728 } 9729 9730 return false; 9731 } 9732 9733 static bool CheckTargetCausesMultiVersioning( 9734 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 9735 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 9736 LookupResult &Previous) { 9737 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 9738 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); 9739 // Sort order doesn't matter, it just needs to be consistent. 9740 llvm::sort(NewParsed.Features); 9741 9742 // If the old decl is NOT MultiVersioned yet, and we don't cause that 9743 // to change, this is a simple redeclaration. 9744 if (!NewTA->isDefaultVersion() && 9745 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 9746 return false; 9747 9748 // Otherwise, this decl causes MultiVersioning. 9749 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9750 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9751 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9752 NewFD->setInvalidDecl(); 9753 return true; 9754 } 9755 9756 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 9757 MultiVersionKind::Target)) { 9758 NewFD->setInvalidDecl(); 9759 return true; 9760 } 9761 9762 if (CheckMultiVersionValue(S, NewFD)) { 9763 NewFD->setInvalidDecl(); 9764 return true; 9765 } 9766 9767 // If this is 'default', permit the forward declaration. 9768 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 9769 Redeclaration = true; 9770 OldDecl = OldFD; 9771 OldFD->setIsMultiVersion(); 9772 NewFD->setIsMultiVersion(); 9773 return false; 9774 } 9775 9776 if (CheckMultiVersionValue(S, OldFD)) { 9777 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9778 NewFD->setInvalidDecl(); 9779 return true; 9780 } 9781 9782 TargetAttr::ParsedTargetAttr OldParsed = 9783 OldTA->parse(std::less<std::string>()); 9784 9785 if (OldParsed == NewParsed) { 9786 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9787 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9788 NewFD->setInvalidDecl(); 9789 return true; 9790 } 9791 9792 for (const auto *FD : OldFD->redecls()) { 9793 const auto *CurTA = FD->getAttr<TargetAttr>(); 9794 // We allow forward declarations before ANY multiversioning attributes, but 9795 // nothing after the fact. 9796 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 9797 (!CurTA || CurTA->isInherited())) { 9798 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 9799 << 0; 9800 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9801 NewFD->setInvalidDecl(); 9802 return true; 9803 } 9804 } 9805 9806 OldFD->setIsMultiVersion(); 9807 NewFD->setIsMultiVersion(); 9808 Redeclaration = false; 9809 MergeTypeWithPrevious = false; 9810 OldDecl = nullptr; 9811 Previous.clear(); 9812 return false; 9813 } 9814 9815 /// Check the validity of a new function declaration being added to an existing 9816 /// multiversioned declaration collection. 9817 static bool CheckMultiVersionAdditionalDecl( 9818 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 9819 MultiVersionKind NewMVType, const TargetAttr *NewTA, 9820 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 9821 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 9822 LookupResult &Previous) { 9823 9824 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 9825 // Disallow mixing of multiversioning types. 9826 if ((OldMVType == MultiVersionKind::Target && 9827 NewMVType != MultiVersionKind::Target) || 9828 (NewMVType == MultiVersionKind::Target && 9829 OldMVType != MultiVersionKind::Target)) { 9830 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 9831 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9832 NewFD->setInvalidDecl(); 9833 return true; 9834 } 9835 9836 TargetAttr::ParsedTargetAttr NewParsed; 9837 if (NewTA) { 9838 NewParsed = NewTA->parse(); 9839 llvm::sort(NewParsed.Features); 9840 } 9841 9842 bool UseMemberUsingDeclRules = 9843 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 9844 9845 // Next, check ALL non-overloads to see if this is a redeclaration of a 9846 // previous member of the MultiVersion set. 9847 for (NamedDecl *ND : Previous) { 9848 FunctionDecl *CurFD = ND->getAsFunction(); 9849 if (!CurFD) 9850 continue; 9851 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 9852 continue; 9853 9854 if (NewMVType == MultiVersionKind::Target) { 9855 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 9856 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 9857 NewFD->setIsMultiVersion(); 9858 Redeclaration = true; 9859 OldDecl = ND; 9860 return false; 9861 } 9862 9863 TargetAttr::ParsedTargetAttr CurParsed = 9864 CurTA->parse(std::less<std::string>()); 9865 if (CurParsed == NewParsed) { 9866 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9867 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9868 NewFD->setInvalidDecl(); 9869 return true; 9870 } 9871 } else { 9872 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 9873 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 9874 // Handle CPUDispatch/CPUSpecific versions. 9875 // Only 1 CPUDispatch function is allowed, this will make it go through 9876 // the redeclaration errors. 9877 if (NewMVType == MultiVersionKind::CPUDispatch && 9878 CurFD->hasAttr<CPUDispatchAttr>()) { 9879 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 9880 std::equal( 9881 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 9882 NewCPUDisp->cpus_begin(), 9883 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 9884 return Cur->getName() == New->getName(); 9885 })) { 9886 NewFD->setIsMultiVersion(); 9887 Redeclaration = true; 9888 OldDecl = ND; 9889 return false; 9890 } 9891 9892 // If the declarations don't match, this is an error condition. 9893 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 9894 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9895 NewFD->setInvalidDecl(); 9896 return true; 9897 } 9898 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 9899 9900 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 9901 std::equal( 9902 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 9903 NewCPUSpec->cpus_begin(), 9904 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 9905 return Cur->getName() == New->getName(); 9906 })) { 9907 NewFD->setIsMultiVersion(); 9908 Redeclaration = true; 9909 OldDecl = ND; 9910 return false; 9911 } 9912 9913 // Only 1 version of CPUSpecific is allowed for each CPU. 9914 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 9915 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 9916 if (CurII == NewII) { 9917 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 9918 << NewII; 9919 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9920 NewFD->setInvalidDecl(); 9921 return true; 9922 } 9923 } 9924 } 9925 } 9926 // If the two decls aren't the same MVType, there is no possible error 9927 // condition. 9928 } 9929 } 9930 9931 // Else, this is simply a non-redecl case. Checking the 'value' is only 9932 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 9933 // handled in the attribute adding step. 9934 if (NewMVType == MultiVersionKind::Target && 9935 CheckMultiVersionValue(S, NewFD)) { 9936 NewFD->setInvalidDecl(); 9937 return true; 9938 } 9939 9940 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 9941 !OldFD->isMultiVersion(), NewMVType)) { 9942 NewFD->setInvalidDecl(); 9943 return true; 9944 } 9945 9946 // Permit forward declarations in the case where these two are compatible. 9947 if (!OldFD->isMultiVersion()) { 9948 OldFD->setIsMultiVersion(); 9949 NewFD->setIsMultiVersion(); 9950 Redeclaration = true; 9951 OldDecl = OldFD; 9952 return false; 9953 } 9954 9955 NewFD->setIsMultiVersion(); 9956 Redeclaration = false; 9957 MergeTypeWithPrevious = false; 9958 OldDecl = nullptr; 9959 Previous.clear(); 9960 return false; 9961 } 9962 9963 9964 /// Check the validity of a mulitversion function declaration. 9965 /// Also sets the multiversion'ness' of the function itself. 9966 /// 9967 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9968 /// 9969 /// Returns true if there was an error, false otherwise. 9970 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 9971 bool &Redeclaration, NamedDecl *&OldDecl, 9972 bool &MergeTypeWithPrevious, 9973 LookupResult &Previous) { 9974 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 9975 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 9976 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 9977 9978 // Mixing Multiversioning types is prohibited. 9979 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 9980 (NewCPUDisp && NewCPUSpec)) { 9981 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 9982 NewFD->setInvalidDecl(); 9983 return true; 9984 } 9985 9986 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 9987 9988 // Main isn't allowed to become a multiversion function, however it IS 9989 // permitted to have 'main' be marked with the 'target' optimization hint. 9990 if (NewFD->isMain()) { 9991 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 9992 MVType == MultiVersionKind::CPUDispatch || 9993 MVType == MultiVersionKind::CPUSpecific) { 9994 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 9995 NewFD->setInvalidDecl(); 9996 return true; 9997 } 9998 return false; 9999 } 10000 10001 if (!OldDecl || !OldDecl->getAsFunction() || 10002 OldDecl->getDeclContext()->getRedeclContext() != 10003 NewFD->getDeclContext()->getRedeclContext()) { 10004 // If there's no previous declaration, AND this isn't attempting to cause 10005 // multiversioning, this isn't an error condition. 10006 if (MVType == MultiVersionKind::None) 10007 return false; 10008 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10009 } 10010 10011 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10012 10013 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10014 return false; 10015 10016 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10017 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10018 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10019 NewFD->setInvalidDecl(); 10020 return true; 10021 } 10022 10023 // Handle the target potentially causes multiversioning case. 10024 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10025 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10026 Redeclaration, OldDecl, 10027 MergeTypeWithPrevious, Previous); 10028 10029 // At this point, we have a multiversion function decl (in OldFD) AND an 10030 // appropriate attribute in the current function decl. Resolve that these are 10031 // still compatible with previous declarations. 10032 return CheckMultiVersionAdditionalDecl( 10033 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10034 OldDecl, MergeTypeWithPrevious, Previous); 10035 } 10036 10037 /// Perform semantic checking of a new function declaration. 10038 /// 10039 /// Performs semantic analysis of the new function declaration 10040 /// NewFD. This routine performs all semantic checking that does not 10041 /// require the actual declarator involved in the declaration, and is 10042 /// used both for the declaration of functions as they are parsed 10043 /// (called via ActOnDeclarator) and for the declaration of functions 10044 /// that have been instantiated via C++ template instantiation (called 10045 /// via InstantiateDecl). 10046 /// 10047 /// \param IsMemberSpecialization whether this new function declaration is 10048 /// a member specialization (that replaces any definition provided by the 10049 /// previous declaration). 10050 /// 10051 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10052 /// 10053 /// \returns true if the function declaration is a redeclaration. 10054 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10055 LookupResult &Previous, 10056 bool IsMemberSpecialization) { 10057 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10058 "Variably modified return types are not handled here"); 10059 10060 // Determine whether the type of this function should be merged with 10061 // a previous visible declaration. This never happens for functions in C++, 10062 // and always happens in C if the previous declaration was visible. 10063 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10064 !Previous.isShadowed(); 10065 10066 bool Redeclaration = false; 10067 NamedDecl *OldDecl = nullptr; 10068 bool MayNeedOverloadableChecks = false; 10069 10070 // Merge or overload the declaration with an existing declaration of 10071 // the same name, if appropriate. 10072 if (!Previous.empty()) { 10073 // Determine whether NewFD is an overload of PrevDecl or 10074 // a declaration that requires merging. If it's an overload, 10075 // there's no more work to do here; we'll just add the new 10076 // function to the scope. 10077 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10078 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10079 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10080 Redeclaration = true; 10081 OldDecl = Candidate; 10082 } 10083 } else { 10084 MayNeedOverloadableChecks = true; 10085 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10086 /*NewIsUsingDecl*/ false)) { 10087 case Ovl_Match: 10088 Redeclaration = true; 10089 break; 10090 10091 case Ovl_NonFunction: 10092 Redeclaration = true; 10093 break; 10094 10095 case Ovl_Overload: 10096 Redeclaration = false; 10097 break; 10098 } 10099 } 10100 } 10101 10102 // Check for a previous extern "C" declaration with this name. 10103 if (!Redeclaration && 10104 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10105 if (!Previous.empty()) { 10106 // This is an extern "C" declaration with the same name as a previous 10107 // declaration, and thus redeclares that entity... 10108 Redeclaration = true; 10109 OldDecl = Previous.getFoundDecl(); 10110 MergeTypeWithPrevious = false; 10111 10112 // ... except in the presence of __attribute__((overloadable)). 10113 if (OldDecl->hasAttr<OverloadableAttr>() || 10114 NewFD->hasAttr<OverloadableAttr>()) { 10115 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10116 MayNeedOverloadableChecks = true; 10117 Redeclaration = false; 10118 OldDecl = nullptr; 10119 } 10120 } 10121 } 10122 } 10123 10124 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10125 MergeTypeWithPrevious, Previous)) 10126 return Redeclaration; 10127 10128 // C++11 [dcl.constexpr]p8: 10129 // A constexpr specifier for a non-static member function that is not 10130 // a constructor declares that member function to be const. 10131 // 10132 // This needs to be delayed until we know whether this is an out-of-line 10133 // definition of a static member function. 10134 // 10135 // This rule is not present in C++1y, so we produce a backwards 10136 // compatibility warning whenever it happens in C++11. 10137 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10138 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10139 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10140 !MD->getMethodQualifiers().hasConst()) { 10141 CXXMethodDecl *OldMD = nullptr; 10142 if (OldDecl) 10143 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10144 if (!OldMD || !OldMD->isStatic()) { 10145 const FunctionProtoType *FPT = 10146 MD->getType()->castAs<FunctionProtoType>(); 10147 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10148 EPI.TypeQuals.addConst(); 10149 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10150 FPT->getParamTypes(), EPI)); 10151 10152 // Warn that we did this, if we're not performing template instantiation. 10153 // In that case, we'll have warned already when the template was defined. 10154 if (!inTemplateInstantiation()) { 10155 SourceLocation AddConstLoc; 10156 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10157 .IgnoreParens().getAs<FunctionTypeLoc>()) 10158 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10159 10160 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10161 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10162 } 10163 } 10164 } 10165 10166 if (Redeclaration) { 10167 // NewFD and OldDecl represent declarations that need to be 10168 // merged. 10169 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10170 NewFD->setInvalidDecl(); 10171 return Redeclaration; 10172 } 10173 10174 Previous.clear(); 10175 Previous.addDecl(OldDecl); 10176 10177 if (FunctionTemplateDecl *OldTemplateDecl = 10178 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10179 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10180 FunctionTemplateDecl *NewTemplateDecl 10181 = NewFD->getDescribedFunctionTemplate(); 10182 assert(NewTemplateDecl && "Template/non-template mismatch"); 10183 10184 // The call to MergeFunctionDecl above may have created some state in 10185 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10186 // can add it as a redeclaration. 10187 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10188 10189 NewFD->setPreviousDeclaration(OldFD); 10190 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10191 if (NewFD->isCXXClassMember()) { 10192 NewFD->setAccess(OldTemplateDecl->getAccess()); 10193 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10194 } 10195 10196 // If this is an explicit specialization of a member that is a function 10197 // template, mark it as a member specialization. 10198 if (IsMemberSpecialization && 10199 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10200 NewTemplateDecl->setMemberSpecialization(); 10201 assert(OldTemplateDecl->isMemberSpecialization()); 10202 // Explicit specializations of a member template do not inherit deleted 10203 // status from the parent member template that they are specializing. 10204 if (OldFD->isDeleted()) { 10205 // FIXME: This assert will not hold in the presence of modules. 10206 assert(OldFD->getCanonicalDecl() == OldFD); 10207 // FIXME: We need an update record for this AST mutation. 10208 OldFD->setDeletedAsWritten(false); 10209 } 10210 } 10211 10212 } else { 10213 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10214 auto *OldFD = cast<FunctionDecl>(OldDecl); 10215 // This needs to happen first so that 'inline' propagates. 10216 NewFD->setPreviousDeclaration(OldFD); 10217 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10218 if (NewFD->isCXXClassMember()) 10219 NewFD->setAccess(OldFD->getAccess()); 10220 } 10221 } 10222 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10223 !NewFD->getAttr<OverloadableAttr>()) { 10224 assert((Previous.empty() || 10225 llvm::any_of(Previous, 10226 [](const NamedDecl *ND) { 10227 return ND->hasAttr<OverloadableAttr>(); 10228 })) && 10229 "Non-redecls shouldn't happen without overloadable present"); 10230 10231 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10232 const auto *FD = dyn_cast<FunctionDecl>(ND); 10233 return FD && !FD->hasAttr<OverloadableAttr>(); 10234 }); 10235 10236 if (OtherUnmarkedIter != Previous.end()) { 10237 Diag(NewFD->getLocation(), 10238 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10239 Diag((*OtherUnmarkedIter)->getLocation(), 10240 diag::note_attribute_overloadable_prev_overload) 10241 << false; 10242 10243 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10244 } 10245 } 10246 10247 // Semantic checking for this function declaration (in isolation). 10248 10249 if (getLangOpts().CPlusPlus) { 10250 // C++-specific checks. 10251 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10252 CheckConstructor(Constructor); 10253 } else if (CXXDestructorDecl *Destructor = 10254 dyn_cast<CXXDestructorDecl>(NewFD)) { 10255 CXXRecordDecl *Record = Destructor->getParent(); 10256 QualType ClassType = Context.getTypeDeclType(Record); 10257 10258 // FIXME: Shouldn't we be able to perform this check even when the class 10259 // type is dependent? Both gcc and edg can handle that. 10260 if (!ClassType->isDependentType()) { 10261 DeclarationName Name 10262 = Context.DeclarationNames.getCXXDestructorName( 10263 Context.getCanonicalType(ClassType)); 10264 if (NewFD->getDeclName() != Name) { 10265 Diag(NewFD->getLocation(), diag::err_destructor_name); 10266 NewFD->setInvalidDecl(); 10267 return Redeclaration; 10268 } 10269 } 10270 } else if (CXXConversionDecl *Conversion 10271 = dyn_cast<CXXConversionDecl>(NewFD)) { 10272 ActOnConversionDeclarator(Conversion); 10273 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10274 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10275 CheckDeductionGuideTemplate(TD); 10276 10277 // A deduction guide is not on the list of entities that can be 10278 // explicitly specialized. 10279 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10280 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10281 << /*explicit specialization*/ 1; 10282 } 10283 10284 // Find any virtual functions that this function overrides. 10285 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10286 if (!Method->isFunctionTemplateSpecialization() && 10287 !Method->getDescribedFunctionTemplate() && 10288 Method->isCanonicalDecl()) { 10289 if (AddOverriddenMethods(Method->getParent(), Method)) { 10290 // If the function was marked as "static", we have a problem. 10291 if (NewFD->getStorageClass() == SC_Static) { 10292 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 10293 } 10294 } 10295 } 10296 10297 if (Method->isStatic()) 10298 checkThisInStaticMemberFunctionType(Method); 10299 } 10300 10301 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10302 if (NewFD->isOverloadedOperator() && 10303 CheckOverloadedOperatorDeclaration(NewFD)) { 10304 NewFD->setInvalidDecl(); 10305 return Redeclaration; 10306 } 10307 10308 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10309 if (NewFD->getLiteralIdentifier() && 10310 CheckLiteralOperatorDeclaration(NewFD)) { 10311 NewFD->setInvalidDecl(); 10312 return Redeclaration; 10313 } 10314 10315 // In C++, check default arguments now that we have merged decls. Unless 10316 // the lexical context is the class, because in this case this is done 10317 // during delayed parsing anyway. 10318 if (!CurContext->isRecord()) 10319 CheckCXXDefaultArguments(NewFD); 10320 10321 // If this function declares a builtin function, check the type of this 10322 // declaration against the expected type for the builtin. 10323 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10324 ASTContext::GetBuiltinTypeError Error; 10325 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10326 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10327 // If the type of the builtin differs only in its exception 10328 // specification, that's OK. 10329 // FIXME: If the types do differ in this way, it would be better to 10330 // retain the 'noexcept' form of the type. 10331 if (!T.isNull() && 10332 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10333 NewFD->getType())) 10334 // The type of this function differs from the type of the builtin, 10335 // so forget about the builtin entirely. 10336 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10337 } 10338 10339 // If this function is declared as being extern "C", then check to see if 10340 // the function returns a UDT (class, struct, or union type) that is not C 10341 // compatible, and if it does, warn the user. 10342 // But, issue any diagnostic on the first declaration only. 10343 if (Previous.empty() && NewFD->isExternC()) { 10344 QualType R = NewFD->getReturnType(); 10345 if (R->isIncompleteType() && !R->isVoidType()) 10346 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10347 << NewFD << R; 10348 else if (!R.isPODType(Context) && !R->isVoidType() && 10349 !R->isObjCObjectPointerType()) 10350 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10351 } 10352 10353 // C++1z [dcl.fct]p6: 10354 // [...] whether the function has a non-throwing exception-specification 10355 // [is] part of the function type 10356 // 10357 // This results in an ABI break between C++14 and C++17 for functions whose 10358 // declared type includes an exception-specification in a parameter or 10359 // return type. (Exception specifications on the function itself are OK in 10360 // most cases, and exception specifications are not permitted in most other 10361 // contexts where they could make it into a mangling.) 10362 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10363 auto HasNoexcept = [&](QualType T) -> bool { 10364 // Strip off declarator chunks that could be between us and a function 10365 // type. We don't need to look far, exception specifications are very 10366 // restricted prior to C++17. 10367 if (auto *RT = T->getAs<ReferenceType>()) 10368 T = RT->getPointeeType(); 10369 else if (T->isAnyPointerType()) 10370 T = T->getPointeeType(); 10371 else if (auto *MPT = T->getAs<MemberPointerType>()) 10372 T = MPT->getPointeeType(); 10373 if (auto *FPT = T->getAs<FunctionProtoType>()) 10374 if (FPT->isNothrow()) 10375 return true; 10376 return false; 10377 }; 10378 10379 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10380 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10381 for (QualType T : FPT->param_types()) 10382 AnyNoexcept |= HasNoexcept(T); 10383 if (AnyNoexcept) 10384 Diag(NewFD->getLocation(), 10385 diag::warn_cxx17_compat_exception_spec_in_signature) 10386 << NewFD; 10387 } 10388 10389 if (!Redeclaration && LangOpts.CUDA) 10390 checkCUDATargetOverload(NewFD, Previous); 10391 } 10392 return Redeclaration; 10393 } 10394 10395 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10396 // C++11 [basic.start.main]p3: 10397 // A program that [...] declares main to be inline, static or 10398 // constexpr is ill-formed. 10399 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10400 // appear in a declaration of main. 10401 // static main is not an error under C99, but we should warn about it. 10402 // We accept _Noreturn main as an extension. 10403 if (FD->getStorageClass() == SC_Static) 10404 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10405 ? diag::err_static_main : diag::warn_static_main) 10406 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10407 if (FD->isInlineSpecified()) 10408 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10409 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10410 if (DS.isNoreturnSpecified()) { 10411 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10412 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10413 Diag(NoreturnLoc, diag::ext_noreturn_main); 10414 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10415 << FixItHint::CreateRemoval(NoreturnRange); 10416 } 10417 if (FD->isConstexpr()) { 10418 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10419 << FD->isConsteval() 10420 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10421 FD->setConstexprKind(CSK_unspecified); 10422 } 10423 10424 if (getLangOpts().OpenCL) { 10425 Diag(FD->getLocation(), diag::err_opencl_no_main) 10426 << FD->hasAttr<OpenCLKernelAttr>(); 10427 FD->setInvalidDecl(); 10428 return; 10429 } 10430 10431 QualType T = FD->getType(); 10432 assert(T->isFunctionType() && "function decl is not of function type"); 10433 const FunctionType* FT = T->castAs<FunctionType>(); 10434 10435 // Set default calling convention for main() 10436 if (FT->getCallConv() != CC_C) { 10437 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10438 FD->setType(QualType(FT, 0)); 10439 T = Context.getCanonicalType(FD->getType()); 10440 } 10441 10442 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10443 // In C with GNU extensions we allow main() to have non-integer return 10444 // type, but we should warn about the extension, and we disable the 10445 // implicit-return-zero rule. 10446 10447 // GCC in C mode accepts qualified 'int'. 10448 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10449 FD->setHasImplicitReturnZero(true); 10450 else { 10451 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10452 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10453 if (RTRange.isValid()) 10454 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10455 << FixItHint::CreateReplacement(RTRange, "int"); 10456 } 10457 } else { 10458 // In C and C++, main magically returns 0 if you fall off the end; 10459 // set the flag which tells us that. 10460 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10461 10462 // All the standards say that main() should return 'int'. 10463 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10464 FD->setHasImplicitReturnZero(true); 10465 else { 10466 // Otherwise, this is just a flat-out error. 10467 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10468 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10469 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10470 : FixItHint()); 10471 FD->setInvalidDecl(true); 10472 } 10473 } 10474 10475 // Treat protoless main() as nullary. 10476 if (isa<FunctionNoProtoType>(FT)) return; 10477 10478 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10479 unsigned nparams = FTP->getNumParams(); 10480 assert(FD->getNumParams() == nparams); 10481 10482 bool HasExtraParameters = (nparams > 3); 10483 10484 if (FTP->isVariadic()) { 10485 Diag(FD->getLocation(), diag::ext_variadic_main); 10486 // FIXME: if we had information about the location of the ellipsis, we 10487 // could add a FixIt hint to remove it as a parameter. 10488 } 10489 10490 // Darwin passes an undocumented fourth argument of type char**. If 10491 // other platforms start sprouting these, the logic below will start 10492 // getting shifty. 10493 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10494 HasExtraParameters = false; 10495 10496 if (HasExtraParameters) { 10497 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10498 FD->setInvalidDecl(true); 10499 nparams = 3; 10500 } 10501 10502 // FIXME: a lot of the following diagnostics would be improved 10503 // if we had some location information about types. 10504 10505 QualType CharPP = 10506 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10507 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10508 10509 for (unsigned i = 0; i < nparams; ++i) { 10510 QualType AT = FTP->getParamType(i); 10511 10512 bool mismatch = true; 10513 10514 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10515 mismatch = false; 10516 else if (Expected[i] == CharPP) { 10517 // As an extension, the following forms are okay: 10518 // char const ** 10519 // char const * const * 10520 // char * const * 10521 10522 QualifierCollector qs; 10523 const PointerType* PT; 10524 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10525 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10526 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10527 Context.CharTy)) { 10528 qs.removeConst(); 10529 mismatch = !qs.empty(); 10530 } 10531 } 10532 10533 if (mismatch) { 10534 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10535 // TODO: suggest replacing given type with expected type 10536 FD->setInvalidDecl(true); 10537 } 10538 } 10539 10540 if (nparams == 1 && !FD->isInvalidDecl()) { 10541 Diag(FD->getLocation(), diag::warn_main_one_arg); 10542 } 10543 10544 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10545 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10546 FD->setInvalidDecl(); 10547 } 10548 } 10549 10550 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10551 QualType T = FD->getType(); 10552 assert(T->isFunctionType() && "function decl is not of function type"); 10553 const FunctionType *FT = T->castAs<FunctionType>(); 10554 10555 // Set an implicit return of 'zero' if the function can return some integral, 10556 // enumeration, pointer or nullptr type. 10557 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10558 FT->getReturnType()->isAnyPointerType() || 10559 FT->getReturnType()->isNullPtrType()) 10560 // DllMain is exempt because a return value of zero means it failed. 10561 if (FD->getName() != "DllMain") 10562 FD->setHasImplicitReturnZero(true); 10563 10564 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10565 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10566 FD->setInvalidDecl(); 10567 } 10568 } 10569 10570 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10571 // FIXME: Need strict checking. In C89, we need to check for 10572 // any assignment, increment, decrement, function-calls, or 10573 // commas outside of a sizeof. In C99, it's the same list, 10574 // except that the aforementioned are allowed in unevaluated 10575 // expressions. Everything else falls under the 10576 // "may accept other forms of constant expressions" exception. 10577 // (We never end up here for C++, so the constant expression 10578 // rules there don't matter.) 10579 const Expr *Culprit; 10580 if (Init->isConstantInitializer(Context, false, &Culprit)) 10581 return false; 10582 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 10583 << Culprit->getSourceRange(); 10584 return true; 10585 } 10586 10587 namespace { 10588 // Visits an initialization expression to see if OrigDecl is evaluated in 10589 // its own initialization and throws a warning if it does. 10590 class SelfReferenceChecker 10591 : public EvaluatedExprVisitor<SelfReferenceChecker> { 10592 Sema &S; 10593 Decl *OrigDecl; 10594 bool isRecordType; 10595 bool isPODType; 10596 bool isReferenceType; 10597 10598 bool isInitList; 10599 llvm::SmallVector<unsigned, 4> InitFieldIndex; 10600 10601 public: 10602 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 10603 10604 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 10605 S(S), OrigDecl(OrigDecl) { 10606 isPODType = false; 10607 isRecordType = false; 10608 isReferenceType = false; 10609 isInitList = false; 10610 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 10611 isPODType = VD->getType().isPODType(S.Context); 10612 isRecordType = VD->getType()->isRecordType(); 10613 isReferenceType = VD->getType()->isReferenceType(); 10614 } 10615 } 10616 10617 // For most expressions, just call the visitor. For initializer lists, 10618 // track the index of the field being initialized since fields are 10619 // initialized in order allowing use of previously initialized fields. 10620 void CheckExpr(Expr *E) { 10621 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 10622 if (!InitList) { 10623 Visit(E); 10624 return; 10625 } 10626 10627 // Track and increment the index here. 10628 isInitList = true; 10629 InitFieldIndex.push_back(0); 10630 for (auto Child : InitList->children()) { 10631 CheckExpr(cast<Expr>(Child)); 10632 ++InitFieldIndex.back(); 10633 } 10634 InitFieldIndex.pop_back(); 10635 } 10636 10637 // Returns true if MemberExpr is checked and no further checking is needed. 10638 // Returns false if additional checking is required. 10639 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 10640 llvm::SmallVector<FieldDecl*, 4> Fields; 10641 Expr *Base = E; 10642 bool ReferenceField = false; 10643 10644 // Get the field members used. 10645 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10646 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 10647 if (!FD) 10648 return false; 10649 Fields.push_back(FD); 10650 if (FD->getType()->isReferenceType()) 10651 ReferenceField = true; 10652 Base = ME->getBase()->IgnoreParenImpCasts(); 10653 } 10654 10655 // Keep checking only if the base Decl is the same. 10656 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 10657 if (!DRE || DRE->getDecl() != OrigDecl) 10658 return false; 10659 10660 // A reference field can be bound to an unininitialized field. 10661 if (CheckReference && !ReferenceField) 10662 return true; 10663 10664 // Convert FieldDecls to their index number. 10665 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 10666 for (const FieldDecl *I : llvm::reverse(Fields)) 10667 UsedFieldIndex.push_back(I->getFieldIndex()); 10668 10669 // See if a warning is needed by checking the first difference in index 10670 // numbers. If field being used has index less than the field being 10671 // initialized, then the use is safe. 10672 for (auto UsedIter = UsedFieldIndex.begin(), 10673 UsedEnd = UsedFieldIndex.end(), 10674 OrigIter = InitFieldIndex.begin(), 10675 OrigEnd = InitFieldIndex.end(); 10676 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 10677 if (*UsedIter < *OrigIter) 10678 return true; 10679 if (*UsedIter > *OrigIter) 10680 break; 10681 } 10682 10683 // TODO: Add a different warning which will print the field names. 10684 HandleDeclRefExpr(DRE); 10685 return true; 10686 } 10687 10688 // For most expressions, the cast is directly above the DeclRefExpr. 10689 // For conditional operators, the cast can be outside the conditional 10690 // operator if both expressions are DeclRefExpr's. 10691 void HandleValue(Expr *E) { 10692 E = E->IgnoreParens(); 10693 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 10694 HandleDeclRefExpr(DRE); 10695 return; 10696 } 10697 10698 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 10699 Visit(CO->getCond()); 10700 HandleValue(CO->getTrueExpr()); 10701 HandleValue(CO->getFalseExpr()); 10702 return; 10703 } 10704 10705 if (BinaryConditionalOperator *BCO = 10706 dyn_cast<BinaryConditionalOperator>(E)) { 10707 Visit(BCO->getCond()); 10708 HandleValue(BCO->getFalseExpr()); 10709 return; 10710 } 10711 10712 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 10713 HandleValue(OVE->getSourceExpr()); 10714 return; 10715 } 10716 10717 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10718 if (BO->getOpcode() == BO_Comma) { 10719 Visit(BO->getLHS()); 10720 HandleValue(BO->getRHS()); 10721 return; 10722 } 10723 } 10724 10725 if (isa<MemberExpr>(E)) { 10726 if (isInitList) { 10727 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 10728 false /*CheckReference*/)) 10729 return; 10730 } 10731 10732 Expr *Base = E->IgnoreParenImpCasts(); 10733 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10734 // Check for static member variables and don't warn on them. 10735 if (!isa<FieldDecl>(ME->getMemberDecl())) 10736 return; 10737 Base = ME->getBase()->IgnoreParenImpCasts(); 10738 } 10739 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 10740 HandleDeclRefExpr(DRE); 10741 return; 10742 } 10743 10744 Visit(E); 10745 } 10746 10747 // Reference types not handled in HandleValue are handled here since all 10748 // uses of references are bad, not just r-value uses. 10749 void VisitDeclRefExpr(DeclRefExpr *E) { 10750 if (isReferenceType) 10751 HandleDeclRefExpr(E); 10752 } 10753 10754 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10755 if (E->getCastKind() == CK_LValueToRValue) { 10756 HandleValue(E->getSubExpr()); 10757 return; 10758 } 10759 10760 Inherited::VisitImplicitCastExpr(E); 10761 } 10762 10763 void VisitMemberExpr(MemberExpr *E) { 10764 if (isInitList) { 10765 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 10766 return; 10767 } 10768 10769 // Don't warn on arrays since they can be treated as pointers. 10770 if (E->getType()->canDecayToPointerType()) return; 10771 10772 // Warn when a non-static method call is followed by non-static member 10773 // field accesses, which is followed by a DeclRefExpr. 10774 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10775 bool Warn = (MD && !MD->isStatic()); 10776 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10777 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10778 if (!isa<FieldDecl>(ME->getMemberDecl())) 10779 Warn = false; 10780 Base = ME->getBase()->IgnoreParenImpCasts(); 10781 } 10782 10783 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10784 if (Warn) 10785 HandleDeclRefExpr(DRE); 10786 return; 10787 } 10788 10789 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10790 // Visit that expression. 10791 Visit(Base); 10792 } 10793 10794 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10795 Expr *Callee = E->getCallee(); 10796 10797 if (isa<UnresolvedLookupExpr>(Callee)) 10798 return Inherited::VisitCXXOperatorCallExpr(E); 10799 10800 Visit(Callee); 10801 for (auto Arg: E->arguments()) 10802 HandleValue(Arg->IgnoreParenImpCasts()); 10803 } 10804 10805 void VisitUnaryOperator(UnaryOperator *E) { 10806 // For POD record types, addresses of its own members are well-defined. 10807 if (E->getOpcode() == UO_AddrOf && isRecordType && 10808 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 10809 if (!isPODType) 10810 HandleValue(E->getSubExpr()); 10811 return; 10812 } 10813 10814 if (E->isIncrementDecrementOp()) { 10815 HandleValue(E->getSubExpr()); 10816 return; 10817 } 10818 10819 Inherited::VisitUnaryOperator(E); 10820 } 10821 10822 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 10823 10824 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10825 if (E->getConstructor()->isCopyConstructor()) { 10826 Expr *ArgExpr = E->getArg(0); 10827 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 10828 if (ILE->getNumInits() == 1) 10829 ArgExpr = ILE->getInit(0); 10830 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 10831 if (ICE->getCastKind() == CK_NoOp) 10832 ArgExpr = ICE->getSubExpr(); 10833 HandleValue(ArgExpr); 10834 return; 10835 } 10836 Inherited::VisitCXXConstructExpr(E); 10837 } 10838 10839 void VisitCallExpr(CallExpr *E) { 10840 // Treat std::move as a use. 10841 if (E->isCallToStdMove()) { 10842 HandleValue(E->getArg(0)); 10843 return; 10844 } 10845 10846 Inherited::VisitCallExpr(E); 10847 } 10848 10849 void VisitBinaryOperator(BinaryOperator *E) { 10850 if (E->isCompoundAssignmentOp()) { 10851 HandleValue(E->getLHS()); 10852 Visit(E->getRHS()); 10853 return; 10854 } 10855 10856 Inherited::VisitBinaryOperator(E); 10857 } 10858 10859 // A custom visitor for BinaryConditionalOperator is needed because the 10860 // regular visitor would check the condition and true expression separately 10861 // but both point to the same place giving duplicate diagnostics. 10862 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10863 Visit(E->getCond()); 10864 Visit(E->getFalseExpr()); 10865 } 10866 10867 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10868 Decl* ReferenceDecl = DRE->getDecl(); 10869 if (OrigDecl != ReferenceDecl) return; 10870 unsigned diag; 10871 if (isReferenceType) { 10872 diag = diag::warn_uninit_self_reference_in_reference_init; 10873 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10874 diag = diag::warn_static_self_reference_in_init; 10875 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10876 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10877 DRE->getDecl()->getType()->isRecordType()) { 10878 diag = diag::warn_uninit_self_reference_in_init; 10879 } else { 10880 // Local variables will be handled by the CFG analysis. 10881 return; 10882 } 10883 10884 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 10885 S.PDiag(diag) 10886 << DRE->getDecl() << OrigDecl->getLocation() 10887 << DRE->getSourceRange()); 10888 } 10889 }; 10890 10891 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10892 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10893 bool DirectInit) { 10894 // Parameters arguments are occassionially constructed with itself, 10895 // for instance, in recursive functions. Skip them. 10896 if (isa<ParmVarDecl>(OrigDecl)) 10897 return; 10898 10899 E = E->IgnoreParens(); 10900 10901 // Skip checking T a = a where T is not a record or reference type. 10902 // Doing so is a way to silence uninitialized warnings. 10903 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10904 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10905 if (ICE->getCastKind() == CK_LValueToRValue) 10906 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10907 if (DRE->getDecl() == OrigDecl) 10908 return; 10909 10910 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10911 } 10912 } // end anonymous namespace 10913 10914 namespace { 10915 // Simple wrapper to add the name of a variable or (if no variable is 10916 // available) a DeclarationName into a diagnostic. 10917 struct VarDeclOrName { 10918 VarDecl *VDecl; 10919 DeclarationName Name; 10920 10921 friend const Sema::SemaDiagnosticBuilder & 10922 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10923 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10924 } 10925 }; 10926 } // end anonymous namespace 10927 10928 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10929 DeclarationName Name, QualType Type, 10930 TypeSourceInfo *TSI, 10931 SourceRange Range, bool DirectInit, 10932 Expr *Init) { 10933 bool IsInitCapture = !VDecl; 10934 assert((!VDecl || !VDecl->isInitCapture()) && 10935 "init captures are expected to be deduced prior to initialization"); 10936 10937 VarDeclOrName VN{VDecl, Name}; 10938 10939 DeducedType *Deduced = Type->getContainedDeducedType(); 10940 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10941 10942 // C++11 [dcl.spec.auto]p3 10943 if (!Init) { 10944 assert(VDecl && "no init for init capture deduction?"); 10945 10946 // Except for class argument deduction, and then for an initializing 10947 // declaration only, i.e. no static at class scope or extern. 10948 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 10949 VDecl->hasExternalStorage() || 10950 VDecl->isStaticDataMember()) { 10951 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10952 << VDecl->getDeclName() << Type; 10953 return QualType(); 10954 } 10955 } 10956 10957 ArrayRef<Expr*> DeduceInits; 10958 if (Init) 10959 DeduceInits = Init; 10960 10961 if (DirectInit) { 10962 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10963 DeduceInits = PL->exprs(); 10964 } 10965 10966 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10967 assert(VDecl && "non-auto type for init capture deduction?"); 10968 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10969 InitializationKind Kind = InitializationKind::CreateForInit( 10970 VDecl->getLocation(), DirectInit, Init); 10971 // FIXME: Initialization should not be taking a mutable list of inits. 10972 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10973 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10974 InitsCopy); 10975 } 10976 10977 if (DirectInit) { 10978 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10979 DeduceInits = IL->inits(); 10980 } 10981 10982 // Deduction only works if we have exactly one source expression. 10983 if (DeduceInits.empty()) { 10984 // It isn't possible to write this directly, but it is possible to 10985 // end up in this situation with "auto x(some_pack...);" 10986 Diag(Init->getBeginLoc(), IsInitCapture 10987 ? diag::err_init_capture_no_expression 10988 : diag::err_auto_var_init_no_expression) 10989 << VN << Type << Range; 10990 return QualType(); 10991 } 10992 10993 if (DeduceInits.size() > 1) { 10994 Diag(DeduceInits[1]->getBeginLoc(), 10995 IsInitCapture ? diag::err_init_capture_multiple_expressions 10996 : diag::err_auto_var_init_multiple_expressions) 10997 << VN << Type << Range; 10998 return QualType(); 10999 } 11000 11001 Expr *DeduceInit = DeduceInits[0]; 11002 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11003 Diag(Init->getBeginLoc(), IsInitCapture 11004 ? diag::err_init_capture_paren_braces 11005 : diag::err_auto_var_init_paren_braces) 11006 << isa<InitListExpr>(Init) << VN << Type << Range; 11007 return QualType(); 11008 } 11009 11010 // Expressions default to 'id' when we're in a debugger. 11011 bool DefaultedAnyToId = false; 11012 if (getLangOpts().DebuggerCastResultToId && 11013 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11014 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11015 if (Result.isInvalid()) { 11016 return QualType(); 11017 } 11018 Init = Result.get(); 11019 DefaultedAnyToId = true; 11020 } 11021 11022 // C++ [dcl.decomp]p1: 11023 // If the assignment-expression [...] has array type A and no ref-qualifier 11024 // is present, e has type cv A 11025 if (VDecl && isa<DecompositionDecl>(VDecl) && 11026 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11027 DeduceInit->getType()->isConstantArrayType()) 11028 return Context.getQualifiedType(DeduceInit->getType(), 11029 Type.getQualifiers()); 11030 11031 QualType DeducedType; 11032 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11033 if (!IsInitCapture) 11034 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11035 else if (isa<InitListExpr>(Init)) 11036 Diag(Range.getBegin(), 11037 diag::err_init_capture_deduction_failure_from_init_list) 11038 << VN 11039 << (DeduceInit->getType().isNull() ? TSI->getType() 11040 : DeduceInit->getType()) 11041 << DeduceInit->getSourceRange(); 11042 else 11043 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11044 << VN << TSI->getType() 11045 << (DeduceInit->getType().isNull() ? TSI->getType() 11046 : DeduceInit->getType()) 11047 << DeduceInit->getSourceRange(); 11048 } 11049 11050 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11051 // 'id' instead of a specific object type prevents most of our usual 11052 // checks. 11053 // We only want to warn outside of template instantiations, though: 11054 // inside a template, the 'id' could have come from a parameter. 11055 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11056 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11057 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11058 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11059 } 11060 11061 return DeducedType; 11062 } 11063 11064 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11065 Expr *Init) { 11066 QualType DeducedType = deduceVarTypeFromInitializer( 11067 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11068 VDecl->getSourceRange(), DirectInit, Init); 11069 if (DeducedType.isNull()) { 11070 VDecl->setInvalidDecl(); 11071 return true; 11072 } 11073 11074 VDecl->setType(DeducedType); 11075 assert(VDecl->isLinkageValid()); 11076 11077 // In ARC, infer lifetime. 11078 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11079 VDecl->setInvalidDecl(); 11080 11081 // If this is a redeclaration, check that the type we just deduced matches 11082 // the previously declared type. 11083 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11084 // We never need to merge the type, because we cannot form an incomplete 11085 // array of auto, nor deduce such a type. 11086 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11087 } 11088 11089 // Check the deduced type is valid for a variable declaration. 11090 CheckVariableDeclarationType(VDecl); 11091 return VDecl->isInvalidDecl(); 11092 } 11093 11094 /// AddInitializerToDecl - Adds the initializer Init to the 11095 /// declaration dcl. If DirectInit is true, this is C++ direct 11096 /// initialization rather than copy initialization. 11097 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11098 // If there is no declaration, there was an error parsing it. Just ignore 11099 // the initializer. 11100 if (!RealDecl || RealDecl->isInvalidDecl()) { 11101 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11102 return; 11103 } 11104 11105 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11106 // Pure-specifiers are handled in ActOnPureSpecifier. 11107 Diag(Method->getLocation(), diag::err_member_function_initialization) 11108 << Method->getDeclName() << Init->getSourceRange(); 11109 Method->setInvalidDecl(); 11110 return; 11111 } 11112 11113 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11114 if (!VDecl) { 11115 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11116 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11117 RealDecl->setInvalidDecl(); 11118 return; 11119 } 11120 11121 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11122 if (VDecl->getType()->isUndeducedType()) { 11123 // Attempt typo correction early so that the type of the init expression can 11124 // be deduced based on the chosen correction if the original init contains a 11125 // TypoExpr. 11126 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11127 if (!Res.isUsable()) { 11128 RealDecl->setInvalidDecl(); 11129 return; 11130 } 11131 Init = Res.get(); 11132 11133 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11134 return; 11135 } 11136 11137 // dllimport cannot be used on variable definitions. 11138 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11139 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11140 VDecl->setInvalidDecl(); 11141 return; 11142 } 11143 11144 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11145 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11146 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11147 VDecl->setInvalidDecl(); 11148 return; 11149 } 11150 11151 if (!VDecl->getType()->isDependentType()) { 11152 // A definition must end up with a complete type, which means it must be 11153 // complete with the restriction that an array type might be completed by 11154 // the initializer; note that later code assumes this restriction. 11155 QualType BaseDeclType = VDecl->getType(); 11156 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11157 BaseDeclType = Array->getElementType(); 11158 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11159 diag::err_typecheck_decl_incomplete_type)) { 11160 RealDecl->setInvalidDecl(); 11161 return; 11162 } 11163 11164 // The variable can not have an abstract class type. 11165 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11166 diag::err_abstract_type_in_decl, 11167 AbstractVariableType)) 11168 VDecl->setInvalidDecl(); 11169 } 11170 11171 // If adding the initializer will turn this declaration into a definition, 11172 // and we already have a definition for this variable, diagnose or otherwise 11173 // handle the situation. 11174 VarDecl *Def; 11175 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11176 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11177 !VDecl->isThisDeclarationADemotedDefinition() && 11178 checkVarDeclRedefinition(Def, VDecl)) 11179 return; 11180 11181 if (getLangOpts().CPlusPlus) { 11182 // C++ [class.static.data]p4 11183 // If a static data member is of const integral or const 11184 // enumeration type, its declaration in the class definition can 11185 // specify a constant-initializer which shall be an integral 11186 // constant expression (5.19). In that case, the member can appear 11187 // in integral constant expressions. The member shall still be 11188 // defined in a namespace scope if it is used in the program and the 11189 // namespace scope definition shall not contain an initializer. 11190 // 11191 // We already performed a redefinition check above, but for static 11192 // data members we also need to check whether there was an in-class 11193 // declaration with an initializer. 11194 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11195 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11196 << VDecl->getDeclName(); 11197 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11198 diag::note_previous_initializer) 11199 << 0; 11200 return; 11201 } 11202 11203 if (VDecl->hasLocalStorage()) 11204 setFunctionHasBranchProtectedScope(); 11205 11206 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11207 VDecl->setInvalidDecl(); 11208 return; 11209 } 11210 } 11211 11212 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11213 // a kernel function cannot be initialized." 11214 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11215 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11216 VDecl->setInvalidDecl(); 11217 return; 11218 } 11219 11220 // Get the decls type and save a reference for later, since 11221 // CheckInitializerTypes may change it. 11222 QualType DclT = VDecl->getType(), SavT = DclT; 11223 11224 // Expressions default to 'id' when we're in a debugger 11225 // and we are assigning it to a variable of Objective-C pointer type. 11226 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11227 Init->getType() == Context.UnknownAnyTy) { 11228 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11229 if (Result.isInvalid()) { 11230 VDecl->setInvalidDecl(); 11231 return; 11232 } 11233 Init = Result.get(); 11234 } 11235 11236 // Perform the initialization. 11237 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 11238 if (!VDecl->isInvalidDecl()) { 11239 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11240 InitializationKind Kind = InitializationKind::CreateForInit( 11241 VDecl->getLocation(), DirectInit, Init); 11242 11243 MultiExprArg Args = Init; 11244 if (CXXDirectInit) 11245 Args = MultiExprArg(CXXDirectInit->getExprs(), 11246 CXXDirectInit->getNumExprs()); 11247 11248 // Try to correct any TypoExprs in the initialization arguments. 11249 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 11250 ExprResult Res = CorrectDelayedTyposInExpr( 11251 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 11252 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 11253 return Init.Failed() ? ExprError() : E; 11254 }); 11255 if (Res.isInvalid()) { 11256 VDecl->setInvalidDecl(); 11257 } else if (Res.get() != Args[Idx]) { 11258 Args[Idx] = Res.get(); 11259 } 11260 } 11261 if (VDecl->isInvalidDecl()) 11262 return; 11263 11264 InitializationSequence InitSeq(*this, Entity, Kind, Args, 11265 /*TopLevelOfInitList=*/false, 11266 /*TreatUnavailableAsInvalid=*/false); 11267 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 11268 if (Result.isInvalid()) { 11269 VDecl->setInvalidDecl(); 11270 return; 11271 } 11272 11273 Init = Result.getAs<Expr>(); 11274 } 11275 11276 // Check for self-references within variable initializers. 11277 // Variables declared within a function/method body (except for references) 11278 // are handled by a dataflow analysis. 11279 // This is undefined behavior in C++, but valid in C. 11280 if (getLangOpts().CPlusPlus) { 11281 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 11282 VDecl->getType()->isReferenceType()) { 11283 CheckSelfReference(*this, RealDecl, Init, DirectInit); 11284 } 11285 } 11286 11287 // If the type changed, it means we had an incomplete type that was 11288 // completed by the initializer. For example: 11289 // int ary[] = { 1, 3, 5 }; 11290 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 11291 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 11292 VDecl->setType(DclT); 11293 11294 if (!VDecl->isInvalidDecl()) { 11295 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 11296 11297 if (VDecl->hasAttr<BlocksAttr>()) 11298 checkRetainCycles(VDecl, Init); 11299 11300 // It is safe to assign a weak reference into a strong variable. 11301 // Although this code can still have problems: 11302 // id x = self.weakProp; 11303 // id y = self.weakProp; 11304 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11305 // paths through the function. This should be revisited if 11306 // -Wrepeated-use-of-weak is made flow-sensitive. 11307 if (FunctionScopeInfo *FSI = getCurFunction()) 11308 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 11309 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 11310 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11311 Init->getBeginLoc())) 11312 FSI->markSafeWeakUse(Init); 11313 } 11314 11315 // The initialization is usually a full-expression. 11316 // 11317 // FIXME: If this is a braced initialization of an aggregate, it is not 11318 // an expression, and each individual field initializer is a separate 11319 // full-expression. For instance, in: 11320 // 11321 // struct Temp { ~Temp(); }; 11322 // struct S { S(Temp); }; 11323 // struct T { S a, b; } t = { Temp(), Temp() } 11324 // 11325 // we should destroy the first Temp before constructing the second. 11326 ExprResult Result = 11327 ActOnFinishFullExpr(Init, VDecl->getLocation(), 11328 /*DiscardedValue*/ false, VDecl->isConstexpr()); 11329 if (Result.isInvalid()) { 11330 VDecl->setInvalidDecl(); 11331 return; 11332 } 11333 Init = Result.get(); 11334 11335 // Attach the initializer to the decl. 11336 VDecl->setInit(Init); 11337 11338 if (VDecl->isLocalVarDecl()) { 11339 // Don't check the initializer if the declaration is malformed. 11340 if (VDecl->isInvalidDecl()) { 11341 // do nothing 11342 11343 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 11344 // This is true even in C++ for OpenCL. 11345 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 11346 CheckForConstantInitializer(Init, DclT); 11347 11348 // Otherwise, C++ does not restrict the initializer. 11349 } else if (getLangOpts().CPlusPlus) { 11350 // do nothing 11351 11352 // C99 6.7.8p4: All the expressions in an initializer for an object that has 11353 // static storage duration shall be constant expressions or string literals. 11354 } else if (VDecl->getStorageClass() == SC_Static) { 11355 CheckForConstantInitializer(Init, DclT); 11356 11357 // C89 is stricter than C99 for aggregate initializers. 11358 // C89 6.5.7p3: All the expressions [...] in an initializer list 11359 // for an object that has aggregate or union type shall be 11360 // constant expressions. 11361 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 11362 isa<InitListExpr>(Init)) { 11363 const Expr *Culprit; 11364 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 11365 Diag(Culprit->getExprLoc(), 11366 diag::ext_aggregate_init_not_constant) 11367 << Culprit->getSourceRange(); 11368 } 11369 } 11370 11371 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 11372 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 11373 if (VDecl->hasLocalStorage()) 11374 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 11375 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 11376 VDecl->getLexicalDeclContext()->isRecord()) { 11377 // This is an in-class initialization for a static data member, e.g., 11378 // 11379 // struct S { 11380 // static const int value = 17; 11381 // }; 11382 11383 // C++ [class.mem]p4: 11384 // A member-declarator can contain a constant-initializer only 11385 // if it declares a static member (9.4) of const integral or 11386 // const enumeration type, see 9.4.2. 11387 // 11388 // C++11 [class.static.data]p3: 11389 // If a non-volatile non-inline const static data member is of integral 11390 // or enumeration type, its declaration in the class definition can 11391 // specify a brace-or-equal-initializer in which every initializer-clause 11392 // that is an assignment-expression is a constant expression. A static 11393 // data member of literal type can be declared in the class definition 11394 // with the constexpr specifier; if so, its declaration shall specify a 11395 // brace-or-equal-initializer in which every initializer-clause that is 11396 // an assignment-expression is a constant expression. 11397 11398 // Do nothing on dependent types. 11399 if (DclT->isDependentType()) { 11400 11401 // Allow any 'static constexpr' members, whether or not they are of literal 11402 // type. We separately check that every constexpr variable is of literal 11403 // type. 11404 } else if (VDecl->isConstexpr()) { 11405 11406 // Require constness. 11407 } else if (!DclT.isConstQualified()) { 11408 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 11409 << Init->getSourceRange(); 11410 VDecl->setInvalidDecl(); 11411 11412 // We allow integer constant expressions in all cases. 11413 } else if (DclT->isIntegralOrEnumerationType()) { 11414 // Check whether the expression is a constant expression. 11415 SourceLocation Loc; 11416 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 11417 // In C++11, a non-constexpr const static data member with an 11418 // in-class initializer cannot be volatile. 11419 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 11420 else if (Init->isValueDependent()) 11421 ; // Nothing to check. 11422 else if (Init->isIntegerConstantExpr(Context, &Loc)) 11423 ; // Ok, it's an ICE! 11424 else if (Init->getType()->isScopedEnumeralType() && 11425 Init->isCXX11ConstantExpr(Context)) 11426 ; // Ok, it is a scoped-enum constant expression. 11427 else if (Init->isEvaluatable(Context)) { 11428 // If we can constant fold the initializer through heroics, accept it, 11429 // but report this as a use of an extension for -pedantic. 11430 Diag(Loc, diag::ext_in_class_initializer_non_constant) 11431 << Init->getSourceRange(); 11432 } else { 11433 // Otherwise, this is some crazy unknown case. Report the issue at the 11434 // location provided by the isIntegerConstantExpr failed check. 11435 Diag(Loc, diag::err_in_class_initializer_non_constant) 11436 << Init->getSourceRange(); 11437 VDecl->setInvalidDecl(); 11438 } 11439 11440 // We allow foldable floating-point constants as an extension. 11441 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 11442 // In C++98, this is a GNU extension. In C++11, it is not, but we support 11443 // it anyway and provide a fixit to add the 'constexpr'. 11444 if (getLangOpts().CPlusPlus11) { 11445 Diag(VDecl->getLocation(), 11446 diag::ext_in_class_initializer_float_type_cxx11) 11447 << DclT << Init->getSourceRange(); 11448 Diag(VDecl->getBeginLoc(), 11449 diag::note_in_class_initializer_float_type_cxx11) 11450 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 11451 } else { 11452 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 11453 << DclT << Init->getSourceRange(); 11454 11455 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 11456 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 11457 << Init->getSourceRange(); 11458 VDecl->setInvalidDecl(); 11459 } 11460 } 11461 11462 // Suggest adding 'constexpr' in C++11 for literal types. 11463 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 11464 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 11465 << DclT << Init->getSourceRange() 11466 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 11467 VDecl->setConstexpr(true); 11468 11469 } else { 11470 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 11471 << DclT << Init->getSourceRange(); 11472 VDecl->setInvalidDecl(); 11473 } 11474 } else if (VDecl->isFileVarDecl()) { 11475 // In C, extern is typically used to avoid tentative definitions when 11476 // declaring variables in headers, but adding an intializer makes it a 11477 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 11478 // In C++, extern is often used to give implictly static const variables 11479 // external linkage, so don't warn in that case. If selectany is present, 11480 // this might be header code intended for C and C++ inclusion, so apply the 11481 // C++ rules. 11482 if (VDecl->getStorageClass() == SC_Extern && 11483 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 11484 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 11485 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 11486 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 11487 Diag(VDecl->getLocation(), diag::warn_extern_init); 11488 11489 // In Microsoft C++ mode, a const variable defined in namespace scope has 11490 // external linkage by default if the variable is declared with 11491 // __declspec(dllexport). 11492 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 11493 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 11494 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 11495 VDecl->setStorageClass(SC_Extern); 11496 11497 // C99 6.7.8p4. All file scoped initializers need to be constant. 11498 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 11499 CheckForConstantInitializer(Init, DclT); 11500 } 11501 11502 // We will represent direct-initialization similarly to copy-initialization: 11503 // int x(1); -as-> int x = 1; 11504 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 11505 // 11506 // Clients that want to distinguish between the two forms, can check for 11507 // direct initializer using VarDecl::getInitStyle(). 11508 // A major benefit is that clients that don't particularly care about which 11509 // exactly form was it (like the CodeGen) can handle both cases without 11510 // special case code. 11511 11512 // C++ 8.5p11: 11513 // The form of initialization (using parentheses or '=') is generally 11514 // insignificant, but does matter when the entity being initialized has a 11515 // class type. 11516 if (CXXDirectInit) { 11517 assert(DirectInit && "Call-style initializer must be direct init."); 11518 VDecl->setInitStyle(VarDecl::CallInit); 11519 } else if (DirectInit) { 11520 // This must be list-initialization. No other way is direct-initialization. 11521 VDecl->setInitStyle(VarDecl::ListInit); 11522 } 11523 11524 CheckCompleteVariableDeclaration(VDecl); 11525 } 11526 11527 /// ActOnInitializerError - Given that there was an error parsing an 11528 /// initializer for the given declaration, try to return to some form 11529 /// of sanity. 11530 void Sema::ActOnInitializerError(Decl *D) { 11531 // Our main concern here is re-establishing invariants like "a 11532 // variable's type is either dependent or complete". 11533 if (!D || D->isInvalidDecl()) return; 11534 11535 VarDecl *VD = dyn_cast<VarDecl>(D); 11536 if (!VD) return; 11537 11538 // Bindings are not usable if we can't make sense of the initializer. 11539 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 11540 for (auto *BD : DD->bindings()) 11541 BD->setInvalidDecl(); 11542 11543 // Auto types are meaningless if we can't make sense of the initializer. 11544 if (ParsingInitForAutoVars.count(D)) { 11545 D->setInvalidDecl(); 11546 return; 11547 } 11548 11549 QualType Ty = VD->getType(); 11550 if (Ty->isDependentType()) return; 11551 11552 // Require a complete type. 11553 if (RequireCompleteType(VD->getLocation(), 11554 Context.getBaseElementType(Ty), 11555 diag::err_typecheck_decl_incomplete_type)) { 11556 VD->setInvalidDecl(); 11557 return; 11558 } 11559 11560 // Require a non-abstract type. 11561 if (RequireNonAbstractType(VD->getLocation(), Ty, 11562 diag::err_abstract_type_in_decl, 11563 AbstractVariableType)) { 11564 VD->setInvalidDecl(); 11565 return; 11566 } 11567 11568 // Don't bother complaining about constructors or destructors, 11569 // though. 11570 } 11571 11572 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 11573 // If there is no declaration, there was an error parsing it. Just ignore it. 11574 if (!RealDecl) 11575 return; 11576 11577 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 11578 QualType Type = Var->getType(); 11579 11580 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 11581 if (isa<DecompositionDecl>(RealDecl)) { 11582 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 11583 Var->setInvalidDecl(); 11584 return; 11585 } 11586 11587 if (Type->isUndeducedType() && 11588 DeduceVariableDeclarationType(Var, false, nullptr)) 11589 return; 11590 11591 // C++11 [class.static.data]p3: A static data member can be declared with 11592 // the constexpr specifier; if so, its declaration shall specify 11593 // a brace-or-equal-initializer. 11594 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 11595 // the definition of a variable [...] or the declaration of a static data 11596 // member. 11597 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 11598 !Var->isThisDeclarationADemotedDefinition()) { 11599 if (Var->isStaticDataMember()) { 11600 // C++1z removes the relevant rule; the in-class declaration is always 11601 // a definition there. 11602 if (!getLangOpts().CPlusPlus17) { 11603 Diag(Var->getLocation(), 11604 diag::err_constexpr_static_mem_var_requires_init) 11605 << Var->getDeclName(); 11606 Var->setInvalidDecl(); 11607 return; 11608 } 11609 } else { 11610 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 11611 Var->setInvalidDecl(); 11612 return; 11613 } 11614 } 11615 11616 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 11617 // be initialized. 11618 if (!Var->isInvalidDecl() && 11619 Var->getType().getAddressSpace() == LangAS::opencl_constant && 11620 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 11621 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 11622 Var->setInvalidDecl(); 11623 return; 11624 } 11625 11626 switch (Var->isThisDeclarationADefinition()) { 11627 case VarDecl::Definition: 11628 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 11629 break; 11630 11631 // We have an out-of-line definition of a static data member 11632 // that has an in-class initializer, so we type-check this like 11633 // a declaration. 11634 // 11635 LLVM_FALLTHROUGH; 11636 11637 case VarDecl::DeclarationOnly: 11638 // It's only a declaration. 11639 11640 // Block scope. C99 6.7p7: If an identifier for an object is 11641 // declared with no linkage (C99 6.2.2p6), the type for the 11642 // object shall be complete. 11643 if (!Type->isDependentType() && Var->isLocalVarDecl() && 11644 !Var->hasLinkage() && !Var->isInvalidDecl() && 11645 RequireCompleteType(Var->getLocation(), Type, 11646 diag::err_typecheck_decl_incomplete_type)) 11647 Var->setInvalidDecl(); 11648 11649 // Make sure that the type is not abstract. 11650 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11651 RequireNonAbstractType(Var->getLocation(), Type, 11652 diag::err_abstract_type_in_decl, 11653 AbstractVariableType)) 11654 Var->setInvalidDecl(); 11655 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11656 Var->getStorageClass() == SC_PrivateExtern) { 11657 Diag(Var->getLocation(), diag::warn_private_extern); 11658 Diag(Var->getLocation(), diag::note_private_extern); 11659 } 11660 11661 return; 11662 11663 case VarDecl::TentativeDefinition: 11664 // File scope. C99 6.9.2p2: A declaration of an identifier for an 11665 // object that has file scope without an initializer, and without a 11666 // storage-class specifier or with the storage-class specifier "static", 11667 // constitutes a tentative definition. Note: A tentative definition with 11668 // external linkage is valid (C99 6.2.2p5). 11669 if (!Var->isInvalidDecl()) { 11670 if (const IncompleteArrayType *ArrayT 11671 = Context.getAsIncompleteArrayType(Type)) { 11672 if (RequireCompleteType(Var->getLocation(), 11673 ArrayT->getElementType(), 11674 diag::err_illegal_decl_array_incomplete_type)) 11675 Var->setInvalidDecl(); 11676 } else if (Var->getStorageClass() == SC_Static) { 11677 // C99 6.9.2p3: If the declaration of an identifier for an object is 11678 // a tentative definition and has internal linkage (C99 6.2.2p3), the 11679 // declared type shall not be an incomplete type. 11680 // NOTE: code such as the following 11681 // static struct s; 11682 // struct s { int a; }; 11683 // is accepted by gcc. Hence here we issue a warning instead of 11684 // an error and we do not invalidate the static declaration. 11685 // NOTE: to avoid multiple warnings, only check the first declaration. 11686 if (Var->isFirstDecl()) 11687 RequireCompleteType(Var->getLocation(), Type, 11688 diag::ext_typecheck_decl_incomplete_type); 11689 } 11690 } 11691 11692 // Record the tentative definition; we're done. 11693 if (!Var->isInvalidDecl()) 11694 TentativeDefinitions.push_back(Var); 11695 return; 11696 } 11697 11698 // Provide a specific diagnostic for uninitialized variable 11699 // definitions with incomplete array type. 11700 if (Type->isIncompleteArrayType()) { 11701 Diag(Var->getLocation(), 11702 diag::err_typecheck_incomplete_array_needs_initializer); 11703 Var->setInvalidDecl(); 11704 return; 11705 } 11706 11707 // Provide a specific diagnostic for uninitialized variable 11708 // definitions with reference type. 11709 if (Type->isReferenceType()) { 11710 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 11711 << Var->getDeclName() 11712 << SourceRange(Var->getLocation(), Var->getLocation()); 11713 Var->setInvalidDecl(); 11714 return; 11715 } 11716 11717 // Do not attempt to type-check the default initializer for a 11718 // variable with dependent type. 11719 if (Type->isDependentType()) 11720 return; 11721 11722 if (Var->isInvalidDecl()) 11723 return; 11724 11725 if (!Var->hasAttr<AliasAttr>()) { 11726 if (RequireCompleteType(Var->getLocation(), 11727 Context.getBaseElementType(Type), 11728 diag::err_typecheck_decl_incomplete_type)) { 11729 Var->setInvalidDecl(); 11730 return; 11731 } 11732 } else { 11733 return; 11734 } 11735 11736 // The variable can not have an abstract class type. 11737 if (RequireNonAbstractType(Var->getLocation(), Type, 11738 diag::err_abstract_type_in_decl, 11739 AbstractVariableType)) { 11740 Var->setInvalidDecl(); 11741 return; 11742 } 11743 11744 // Check for jumps past the implicit initializer. C++0x 11745 // clarifies that this applies to a "variable with automatic 11746 // storage duration", not a "local variable". 11747 // C++11 [stmt.dcl]p3 11748 // A program that jumps from a point where a variable with automatic 11749 // storage duration is not in scope to a point where it is in scope is 11750 // ill-formed unless the variable has scalar type, class type with a 11751 // trivial default constructor and a trivial destructor, a cv-qualified 11752 // version of one of these types, or an array of one of the preceding 11753 // types and is declared without an initializer. 11754 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 11755 if (const RecordType *Record 11756 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 11757 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 11758 // Mark the function (if we're in one) for further checking even if the 11759 // looser rules of C++11 do not require such checks, so that we can 11760 // diagnose incompatibilities with C++98. 11761 if (!CXXRecord->isPOD()) 11762 setFunctionHasBranchProtectedScope(); 11763 } 11764 } 11765 // In OpenCL, we can't initialize objects in the __local address space, 11766 // even implicitly, so don't synthesize an implicit initializer. 11767 if (getLangOpts().OpenCL && 11768 Var->getType().getAddressSpace() == LangAS::opencl_local) 11769 return; 11770 // C++03 [dcl.init]p9: 11771 // If no initializer is specified for an object, and the 11772 // object is of (possibly cv-qualified) non-POD class type (or 11773 // array thereof), the object shall be default-initialized; if 11774 // the object is of const-qualified type, the underlying class 11775 // type shall have a user-declared default 11776 // constructor. Otherwise, if no initializer is specified for 11777 // a non- static object, the object and its subobjects, if 11778 // any, have an indeterminate initial value); if the object 11779 // or any of its subobjects are of const-qualified type, the 11780 // program is ill-formed. 11781 // C++0x [dcl.init]p11: 11782 // If no initializer is specified for an object, the object is 11783 // default-initialized; [...]. 11784 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 11785 InitializationKind Kind 11786 = InitializationKind::CreateDefault(Var->getLocation()); 11787 11788 InitializationSequence InitSeq(*this, Entity, Kind, None); 11789 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 11790 if (Init.isInvalid()) 11791 Var->setInvalidDecl(); 11792 else if (Init.get()) { 11793 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 11794 // This is important for template substitution. 11795 Var->setInitStyle(VarDecl::CallInit); 11796 } 11797 11798 CheckCompleteVariableDeclaration(Var); 11799 } 11800 } 11801 11802 void Sema::ActOnCXXForRangeDecl(Decl *D) { 11803 // If there is no declaration, there was an error parsing it. Ignore it. 11804 if (!D) 11805 return; 11806 11807 VarDecl *VD = dyn_cast<VarDecl>(D); 11808 if (!VD) { 11809 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 11810 D->setInvalidDecl(); 11811 return; 11812 } 11813 11814 VD->setCXXForRangeDecl(true); 11815 11816 // for-range-declaration cannot be given a storage class specifier. 11817 int Error = -1; 11818 switch (VD->getStorageClass()) { 11819 case SC_None: 11820 break; 11821 case SC_Extern: 11822 Error = 0; 11823 break; 11824 case SC_Static: 11825 Error = 1; 11826 break; 11827 case SC_PrivateExtern: 11828 Error = 2; 11829 break; 11830 case SC_Auto: 11831 Error = 3; 11832 break; 11833 case SC_Register: 11834 Error = 4; 11835 break; 11836 } 11837 if (Error != -1) { 11838 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 11839 << VD->getDeclName() << Error; 11840 D->setInvalidDecl(); 11841 } 11842 } 11843 11844 StmtResult 11845 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 11846 IdentifierInfo *Ident, 11847 ParsedAttributes &Attrs, 11848 SourceLocation AttrEnd) { 11849 // C++1y [stmt.iter]p1: 11850 // A range-based for statement of the form 11851 // for ( for-range-identifier : for-range-initializer ) statement 11852 // is equivalent to 11853 // for ( auto&& for-range-identifier : for-range-initializer ) statement 11854 DeclSpec DS(Attrs.getPool().getFactory()); 11855 11856 const char *PrevSpec; 11857 unsigned DiagID; 11858 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 11859 getPrintingPolicy()); 11860 11861 Declarator D(DS, DeclaratorContext::ForContext); 11862 D.SetIdentifier(Ident, IdentLoc); 11863 D.takeAttributes(Attrs, AttrEnd); 11864 11865 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 11866 IdentLoc); 11867 Decl *Var = ActOnDeclarator(S, D); 11868 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11869 FinalizeDeclaration(Var); 11870 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11871 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11872 } 11873 11874 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11875 if (var->isInvalidDecl()) return; 11876 11877 if (getLangOpts().OpenCL) { 11878 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11879 // initialiser 11880 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11881 !var->hasInit()) { 11882 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11883 << 1 /*Init*/; 11884 var->setInvalidDecl(); 11885 return; 11886 } 11887 } 11888 11889 // In Objective-C, don't allow jumps past the implicit initialization of a 11890 // local retaining variable. 11891 if (getLangOpts().ObjC && 11892 var->hasLocalStorage()) { 11893 switch (var->getType().getObjCLifetime()) { 11894 case Qualifiers::OCL_None: 11895 case Qualifiers::OCL_ExplicitNone: 11896 case Qualifiers::OCL_Autoreleasing: 11897 break; 11898 11899 case Qualifiers::OCL_Weak: 11900 case Qualifiers::OCL_Strong: 11901 setFunctionHasBranchProtectedScope(); 11902 break; 11903 } 11904 } 11905 11906 if (var->hasLocalStorage() && 11907 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 11908 setFunctionHasBranchProtectedScope(); 11909 11910 // Warn about externally-visible variables being defined without a 11911 // prior declaration. We only want to do this for global 11912 // declarations, but we also specifically need to avoid doing it for 11913 // class members because the linkage of an anonymous class can 11914 // change if it's later given a typedef name. 11915 if (var->isThisDeclarationADefinition() && 11916 var->getDeclContext()->getRedeclContext()->isFileContext() && 11917 var->isExternallyVisible() && var->hasLinkage() && 11918 !var->isInline() && !var->getDescribedVarTemplate() && 11919 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 11920 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11921 var->getLocation())) { 11922 // Find a previous declaration that's not a definition. 11923 VarDecl *prev = var->getPreviousDecl(); 11924 while (prev && prev->isThisDeclarationADefinition()) 11925 prev = prev->getPreviousDecl(); 11926 11927 if (!prev) { 11928 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11929 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 11930 << /* variable */ 0; 11931 } 11932 } 11933 11934 // Cache the result of checking for constant initialization. 11935 Optional<bool> CacheHasConstInit; 11936 const Expr *CacheCulprit = nullptr; 11937 auto checkConstInit = [&]() mutable { 11938 if (!CacheHasConstInit) 11939 CacheHasConstInit = var->getInit()->isConstantInitializer( 11940 Context, var->getType()->isReferenceType(), &CacheCulprit); 11941 return *CacheHasConstInit; 11942 }; 11943 11944 if (var->getTLSKind() == VarDecl::TLS_Static) { 11945 if (var->getType().isDestructedType()) { 11946 // GNU C++98 edits for __thread, [basic.start.term]p3: 11947 // The type of an object with thread storage duration shall not 11948 // have a non-trivial destructor. 11949 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11950 if (getLangOpts().CPlusPlus11) 11951 Diag(var->getLocation(), diag::note_use_thread_local); 11952 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11953 if (!checkConstInit()) { 11954 // GNU C++98 edits for __thread, [basic.start.init]p4: 11955 // An object of thread storage duration shall not require dynamic 11956 // initialization. 11957 // FIXME: Need strict checking here. 11958 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11959 << CacheCulprit->getSourceRange(); 11960 if (getLangOpts().CPlusPlus11) 11961 Diag(var->getLocation(), diag::note_use_thread_local); 11962 } 11963 } 11964 } 11965 11966 // Apply section attributes and pragmas to global variables. 11967 bool GlobalStorage = var->hasGlobalStorage(); 11968 if (GlobalStorage && var->isThisDeclarationADefinition() && 11969 !inTemplateInstantiation()) { 11970 PragmaStack<StringLiteral *> *Stack = nullptr; 11971 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11972 if (var->getType().isConstQualified()) 11973 Stack = &ConstSegStack; 11974 else if (!var->getInit()) { 11975 Stack = &BSSSegStack; 11976 SectionFlags |= ASTContext::PSF_Write; 11977 } else { 11978 Stack = &DataSegStack; 11979 SectionFlags |= ASTContext::PSF_Write; 11980 } 11981 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11982 var->addAttr(SectionAttr::CreateImplicit( 11983 Context, SectionAttr::Declspec_allocate, 11984 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11985 } 11986 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11987 if (UnifySection(SA->getName(), SectionFlags, var)) 11988 var->dropAttr<SectionAttr>(); 11989 11990 // Apply the init_seg attribute if this has an initializer. If the 11991 // initializer turns out to not be dynamic, we'll end up ignoring this 11992 // attribute. 11993 if (CurInitSeg && var->getInit()) 11994 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11995 CurInitSegLoc)); 11996 } 11997 11998 // All the following checks are C++ only. 11999 if (!getLangOpts().CPlusPlus) { 12000 // If this variable must be emitted, add it as an initializer for the 12001 // current module. 12002 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12003 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12004 return; 12005 } 12006 12007 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12008 CheckCompleteDecompositionDeclaration(DD); 12009 12010 QualType type = var->getType(); 12011 if (type->isDependentType()) return; 12012 12013 if (var->hasAttr<BlocksAttr>()) 12014 getCurFunction()->addByrefBlockVar(var); 12015 12016 Expr *Init = var->getInit(); 12017 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12018 QualType baseType = Context.getBaseElementType(type); 12019 12020 if (Init && !Init->isValueDependent()) { 12021 if (var->isConstexpr()) { 12022 SmallVector<PartialDiagnosticAt, 8> Notes; 12023 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12024 SourceLocation DiagLoc = var->getLocation(); 12025 // If the note doesn't add any useful information other than a source 12026 // location, fold it into the primary diagnostic. 12027 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12028 diag::note_invalid_subexpr_in_const_expr) { 12029 DiagLoc = Notes[0].first; 12030 Notes.clear(); 12031 } 12032 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12033 << var << Init->getSourceRange(); 12034 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12035 Diag(Notes[I].first, Notes[I].second); 12036 } 12037 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12038 // Check whether the initializer of a const variable of integral or 12039 // enumeration type is an ICE now, since we can't tell whether it was 12040 // initialized by a constant expression if we check later. 12041 var->checkInitIsICE(); 12042 } 12043 12044 // Don't emit further diagnostics about constexpr globals since they 12045 // were just diagnosed. 12046 if (!var->isConstexpr() && GlobalStorage && 12047 var->hasAttr<RequireConstantInitAttr>()) { 12048 // FIXME: Need strict checking in C++03 here. 12049 bool DiagErr = getLangOpts().CPlusPlus11 12050 ? !var->checkInitIsICE() : !checkConstInit(); 12051 if (DiagErr) { 12052 auto attr = var->getAttr<RequireConstantInitAttr>(); 12053 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12054 << Init->getSourceRange(); 12055 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 12056 << attr->getRange(); 12057 if (getLangOpts().CPlusPlus11) { 12058 APValue Value; 12059 SmallVector<PartialDiagnosticAt, 8> Notes; 12060 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12061 for (auto &it : Notes) 12062 Diag(it.first, it.second); 12063 } else { 12064 Diag(CacheCulprit->getExprLoc(), 12065 diag::note_invalid_subexpr_in_const_expr) 12066 << CacheCulprit->getSourceRange(); 12067 } 12068 } 12069 } 12070 else if (!var->isConstexpr() && IsGlobal && 12071 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12072 var->getLocation())) { 12073 // Warn about globals which don't have a constant initializer. Don't 12074 // warn about globals with a non-trivial destructor because we already 12075 // warned about them. 12076 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12077 if (!(RD && !RD->hasTrivialDestructor())) { 12078 if (!checkConstInit()) 12079 Diag(var->getLocation(), diag::warn_global_constructor) 12080 << Init->getSourceRange(); 12081 } 12082 } 12083 } 12084 12085 // Require the destructor. 12086 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12087 FinalizeVarWithDestructor(var, recordType); 12088 12089 // If this variable must be emitted, add it as an initializer for the current 12090 // module. 12091 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12092 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12093 } 12094 12095 /// Determines if a variable's alignment is dependent. 12096 static bool hasDependentAlignment(VarDecl *VD) { 12097 if (VD->getType()->isDependentType()) 12098 return true; 12099 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12100 if (I->isAlignmentDependent()) 12101 return true; 12102 return false; 12103 } 12104 12105 /// Check if VD needs to be dllexport/dllimport due to being in a 12106 /// dllexport/import function. 12107 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12108 assert(VD->isStaticLocal()); 12109 12110 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12111 12112 // Find outermost function when VD is in lambda function. 12113 while (FD && !getDLLAttr(FD) && 12114 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12115 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12116 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12117 } 12118 12119 if (!FD) 12120 return; 12121 12122 // Static locals inherit dll attributes from their function. 12123 if (Attr *A = getDLLAttr(FD)) { 12124 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12125 NewAttr->setInherited(true); 12126 VD->addAttr(NewAttr); 12127 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12128 auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(), 12129 getASTContext(), 12130 A->getSpellingListIndex()); 12131 NewAttr->setInherited(true); 12132 VD->addAttr(NewAttr); 12133 12134 // Export this function to enforce exporting this static variable even 12135 // if it is not used in this compilation unit. 12136 if (!FD->hasAttr<DLLExportAttr>()) 12137 FD->addAttr(NewAttr); 12138 12139 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12140 auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(), 12141 getASTContext(), 12142 A->getSpellingListIndex()); 12143 NewAttr->setInherited(true); 12144 VD->addAttr(NewAttr); 12145 } 12146 } 12147 12148 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12149 /// any semantic actions necessary after any initializer has been attached. 12150 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12151 // Note that we are no longer parsing the initializer for this declaration. 12152 ParsingInitForAutoVars.erase(ThisDecl); 12153 12154 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12155 if (!VD) 12156 return; 12157 12158 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12159 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12160 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12161 if (PragmaClangBSSSection.Valid) 12162 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 12163 PragmaClangBSSSection.SectionName, 12164 PragmaClangBSSSection.PragmaLocation)); 12165 if (PragmaClangDataSection.Valid) 12166 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 12167 PragmaClangDataSection.SectionName, 12168 PragmaClangDataSection.PragmaLocation)); 12169 if (PragmaClangRodataSection.Valid) 12170 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 12171 PragmaClangRodataSection.SectionName, 12172 PragmaClangRodataSection.PragmaLocation)); 12173 } 12174 12175 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 12176 for (auto *BD : DD->bindings()) { 12177 FinalizeDeclaration(BD); 12178 } 12179 } 12180 12181 checkAttributesAfterMerging(*this, *VD); 12182 12183 // Perform TLS alignment check here after attributes attached to the variable 12184 // which may affect the alignment have been processed. Only perform the check 12185 // if the target has a maximum TLS alignment (zero means no constraints). 12186 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 12187 // Protect the check so that it's not performed on dependent types and 12188 // dependent alignments (we can't determine the alignment in that case). 12189 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 12190 !VD->isInvalidDecl()) { 12191 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 12192 if (Context.getDeclAlign(VD) > MaxAlignChars) { 12193 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 12194 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 12195 << (unsigned)MaxAlignChars.getQuantity(); 12196 } 12197 } 12198 } 12199 12200 if (VD->isStaticLocal()) { 12201 CheckStaticLocalForDllExport(VD); 12202 12203 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 12204 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 12205 // function, only __shared__ variables or variables without any device 12206 // memory qualifiers may be declared with static storage class. 12207 // Note: It is unclear how a function-scope non-const static variable 12208 // without device memory qualifier is implemented, therefore only static 12209 // const variable without device memory qualifier is allowed. 12210 [&]() { 12211 if (!getLangOpts().CUDA) 12212 return; 12213 if (VD->hasAttr<CUDASharedAttr>()) 12214 return; 12215 if (VD->getType().isConstQualified() && 12216 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 12217 return; 12218 if (CUDADiagIfDeviceCode(VD->getLocation(), 12219 diag::err_device_static_local_var) 12220 << CurrentCUDATarget()) 12221 VD->setInvalidDecl(); 12222 }(); 12223 } 12224 } 12225 12226 // Perform check for initializers of device-side global variables. 12227 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 12228 // 7.5). We must also apply the same checks to all __shared__ 12229 // variables whether they are local or not. CUDA also allows 12230 // constant initializers for __constant__ and __device__ variables. 12231 if (getLangOpts().CUDA) 12232 checkAllowedCUDAInitializer(VD); 12233 12234 // Grab the dllimport or dllexport attribute off of the VarDecl. 12235 const InheritableAttr *DLLAttr = getDLLAttr(VD); 12236 12237 // Imported static data members cannot be defined out-of-line. 12238 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 12239 if (VD->isStaticDataMember() && VD->isOutOfLine() && 12240 VD->isThisDeclarationADefinition()) { 12241 // We allow definitions of dllimport class template static data members 12242 // with a warning. 12243 CXXRecordDecl *Context = 12244 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 12245 bool IsClassTemplateMember = 12246 isa<ClassTemplatePartialSpecializationDecl>(Context) || 12247 Context->getDescribedClassTemplate(); 12248 12249 Diag(VD->getLocation(), 12250 IsClassTemplateMember 12251 ? diag::warn_attribute_dllimport_static_field_definition 12252 : diag::err_attribute_dllimport_static_field_definition); 12253 Diag(IA->getLocation(), diag::note_attribute); 12254 if (!IsClassTemplateMember) 12255 VD->setInvalidDecl(); 12256 } 12257 } 12258 12259 // dllimport/dllexport variables cannot be thread local, their TLS index 12260 // isn't exported with the variable. 12261 if (DLLAttr && VD->getTLSKind()) { 12262 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12263 if (F && getDLLAttr(F)) { 12264 assert(VD->isStaticLocal()); 12265 // But if this is a static local in a dlimport/dllexport function, the 12266 // function will never be inlined, which means the var would never be 12267 // imported, so having it marked import/export is safe. 12268 } else { 12269 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 12270 << DLLAttr; 12271 VD->setInvalidDecl(); 12272 } 12273 } 12274 12275 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 12276 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 12277 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 12278 VD->dropAttr<UsedAttr>(); 12279 } 12280 } 12281 12282 const DeclContext *DC = VD->getDeclContext(); 12283 // If there's a #pragma GCC visibility in scope, and this isn't a class 12284 // member, set the visibility of this variable. 12285 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 12286 AddPushedVisibilityAttribute(VD); 12287 12288 // FIXME: Warn on unused var template partial specializations. 12289 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 12290 MarkUnusedFileScopedDecl(VD); 12291 12292 // Now we have parsed the initializer and can update the table of magic 12293 // tag values. 12294 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 12295 !VD->getType()->isIntegralOrEnumerationType()) 12296 return; 12297 12298 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 12299 const Expr *MagicValueExpr = VD->getInit(); 12300 if (!MagicValueExpr) { 12301 continue; 12302 } 12303 llvm::APSInt MagicValueInt; 12304 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 12305 Diag(I->getRange().getBegin(), 12306 diag::err_type_tag_for_datatype_not_ice) 12307 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 12308 continue; 12309 } 12310 if (MagicValueInt.getActiveBits() > 64) { 12311 Diag(I->getRange().getBegin(), 12312 diag::err_type_tag_for_datatype_too_large) 12313 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 12314 continue; 12315 } 12316 uint64_t MagicValue = MagicValueInt.getZExtValue(); 12317 RegisterTypeTagForDatatype(I->getArgumentKind(), 12318 MagicValue, 12319 I->getMatchingCType(), 12320 I->getLayoutCompatible(), 12321 I->getMustBeNull()); 12322 } 12323 } 12324 12325 static bool hasDeducedAuto(DeclaratorDecl *DD) { 12326 auto *VD = dyn_cast<VarDecl>(DD); 12327 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 12328 } 12329 12330 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 12331 ArrayRef<Decl *> Group) { 12332 SmallVector<Decl*, 8> Decls; 12333 12334 if (DS.isTypeSpecOwned()) 12335 Decls.push_back(DS.getRepAsDecl()); 12336 12337 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 12338 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 12339 bool DiagnosedMultipleDecomps = false; 12340 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 12341 bool DiagnosedNonDeducedAuto = false; 12342 12343 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 12344 if (Decl *D = Group[i]) { 12345 // For declarators, there are some additional syntactic-ish checks we need 12346 // to perform. 12347 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 12348 if (!FirstDeclaratorInGroup) 12349 FirstDeclaratorInGroup = DD; 12350 if (!FirstDecompDeclaratorInGroup) 12351 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 12352 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 12353 !hasDeducedAuto(DD)) 12354 FirstNonDeducedAutoInGroup = DD; 12355 12356 if (FirstDeclaratorInGroup != DD) { 12357 // A decomposition declaration cannot be combined with any other 12358 // declaration in the same group. 12359 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 12360 Diag(FirstDecompDeclaratorInGroup->getLocation(), 12361 diag::err_decomp_decl_not_alone) 12362 << FirstDeclaratorInGroup->getSourceRange() 12363 << DD->getSourceRange(); 12364 DiagnosedMultipleDecomps = true; 12365 } 12366 12367 // A declarator that uses 'auto' in any way other than to declare a 12368 // variable with a deduced type cannot be combined with any other 12369 // declarator in the same group. 12370 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 12371 Diag(FirstNonDeducedAutoInGroup->getLocation(), 12372 diag::err_auto_non_deduced_not_alone) 12373 << FirstNonDeducedAutoInGroup->getType() 12374 ->hasAutoForTrailingReturnType() 12375 << FirstDeclaratorInGroup->getSourceRange() 12376 << DD->getSourceRange(); 12377 DiagnosedNonDeducedAuto = true; 12378 } 12379 } 12380 } 12381 12382 Decls.push_back(D); 12383 } 12384 } 12385 12386 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 12387 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 12388 handleTagNumbering(Tag, S); 12389 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 12390 getLangOpts().CPlusPlus) 12391 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 12392 } 12393 } 12394 12395 return BuildDeclaratorGroup(Decls); 12396 } 12397 12398 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 12399 /// group, performing any necessary semantic checking. 12400 Sema::DeclGroupPtrTy 12401 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 12402 // C++14 [dcl.spec.auto]p7: (DR1347) 12403 // If the type that replaces the placeholder type is not the same in each 12404 // deduction, the program is ill-formed. 12405 if (Group.size() > 1) { 12406 QualType Deduced; 12407 VarDecl *DeducedDecl = nullptr; 12408 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 12409 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 12410 if (!D || D->isInvalidDecl()) 12411 break; 12412 DeducedType *DT = D->getType()->getContainedDeducedType(); 12413 if (!DT || DT->getDeducedType().isNull()) 12414 continue; 12415 if (Deduced.isNull()) { 12416 Deduced = DT->getDeducedType(); 12417 DeducedDecl = D; 12418 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 12419 auto *AT = dyn_cast<AutoType>(DT); 12420 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 12421 diag::err_auto_different_deductions) 12422 << (AT ? (unsigned)AT->getKeyword() : 3) 12423 << Deduced << DeducedDecl->getDeclName() 12424 << DT->getDeducedType() << D->getDeclName() 12425 << DeducedDecl->getInit()->getSourceRange() 12426 << D->getInit()->getSourceRange(); 12427 D->setInvalidDecl(); 12428 break; 12429 } 12430 } 12431 } 12432 12433 ActOnDocumentableDecls(Group); 12434 12435 return DeclGroupPtrTy::make( 12436 DeclGroupRef::Create(Context, Group.data(), Group.size())); 12437 } 12438 12439 void Sema::ActOnDocumentableDecl(Decl *D) { 12440 ActOnDocumentableDecls(D); 12441 } 12442 12443 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 12444 // Don't parse the comment if Doxygen diagnostics are ignored. 12445 if (Group.empty() || !Group[0]) 12446 return; 12447 12448 if (Diags.isIgnored(diag::warn_doc_param_not_found, 12449 Group[0]->getLocation()) && 12450 Diags.isIgnored(diag::warn_unknown_comment_command_name, 12451 Group[0]->getLocation())) 12452 return; 12453 12454 if (Group.size() >= 2) { 12455 // This is a decl group. Normally it will contain only declarations 12456 // produced from declarator list. But in case we have any definitions or 12457 // additional declaration references: 12458 // 'typedef struct S {} S;' 12459 // 'typedef struct S *S;' 12460 // 'struct S *pS;' 12461 // FinalizeDeclaratorGroup adds these as separate declarations. 12462 Decl *MaybeTagDecl = Group[0]; 12463 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 12464 Group = Group.slice(1); 12465 } 12466 } 12467 12468 // FIMXE: We assume every Decl in the group is in the same file. 12469 // This is false when preprocessor constructs the group from decls in 12470 // different files (e. g. macros or #include). 12471 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 12472 } 12473 12474 /// Common checks for a parameter-declaration that should apply to both function 12475 /// parameters and non-type template parameters. 12476 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 12477 // Check that there are no default arguments inside the type of this 12478 // parameter. 12479 if (getLangOpts().CPlusPlus) 12480 CheckExtraCXXDefaultArguments(D); 12481 12482 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 12483 if (D.getCXXScopeSpec().isSet()) { 12484 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 12485 << D.getCXXScopeSpec().getRange(); 12486 } 12487 12488 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 12489 // simple identifier except [...irrelevant cases...]. 12490 switch (D.getName().getKind()) { 12491 case UnqualifiedIdKind::IK_Identifier: 12492 break; 12493 12494 case UnqualifiedIdKind::IK_OperatorFunctionId: 12495 case UnqualifiedIdKind::IK_ConversionFunctionId: 12496 case UnqualifiedIdKind::IK_LiteralOperatorId: 12497 case UnqualifiedIdKind::IK_ConstructorName: 12498 case UnqualifiedIdKind::IK_DestructorName: 12499 case UnqualifiedIdKind::IK_ImplicitSelfParam: 12500 case UnqualifiedIdKind::IK_DeductionGuideName: 12501 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 12502 << GetNameForDeclarator(D).getName(); 12503 break; 12504 12505 case UnqualifiedIdKind::IK_TemplateId: 12506 case UnqualifiedIdKind::IK_ConstructorTemplateId: 12507 // GetNameForDeclarator would not produce a useful name in this case. 12508 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 12509 break; 12510 } 12511 } 12512 12513 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 12514 /// to introduce parameters into function prototype scope. 12515 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 12516 const DeclSpec &DS = D.getDeclSpec(); 12517 12518 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 12519 12520 // C++03 [dcl.stc]p2 also permits 'auto'. 12521 StorageClass SC = SC_None; 12522 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 12523 SC = SC_Register; 12524 // In C++11, the 'register' storage class specifier is deprecated. 12525 // In C++17, it is not allowed, but we tolerate it as an extension. 12526 if (getLangOpts().CPlusPlus11) { 12527 Diag(DS.getStorageClassSpecLoc(), 12528 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 12529 : diag::warn_deprecated_register) 12530 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 12531 } 12532 } else if (getLangOpts().CPlusPlus && 12533 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 12534 SC = SC_Auto; 12535 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 12536 Diag(DS.getStorageClassSpecLoc(), 12537 diag::err_invalid_storage_class_in_func_decl); 12538 D.getMutableDeclSpec().ClearStorageClassSpecs(); 12539 } 12540 12541 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 12542 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 12543 << DeclSpec::getSpecifierName(TSCS); 12544 if (DS.isInlineSpecified()) 12545 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 12546 << getLangOpts().CPlusPlus17; 12547 if (DS.hasConstexprSpecifier()) 12548 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 12549 << 0 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval); 12550 12551 DiagnoseFunctionSpecifiers(DS); 12552 12553 CheckFunctionOrTemplateParamDeclarator(S, D); 12554 12555 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12556 QualType parmDeclType = TInfo->getType(); 12557 12558 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 12559 IdentifierInfo *II = D.getIdentifier(); 12560 if (II) { 12561 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 12562 ForVisibleRedeclaration); 12563 LookupName(R, S); 12564 if (R.isSingleResult()) { 12565 NamedDecl *PrevDecl = R.getFoundDecl(); 12566 if (PrevDecl->isTemplateParameter()) { 12567 // Maybe we will complain about the shadowed template parameter. 12568 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12569 // Just pretend that we didn't see the previous declaration. 12570 PrevDecl = nullptr; 12571 } else if (S->isDeclScope(PrevDecl)) { 12572 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 12573 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12574 12575 // Recover by removing the name 12576 II = nullptr; 12577 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 12578 D.setInvalidType(true); 12579 } 12580 } 12581 } 12582 12583 // Temporarily put parameter variables in the translation unit, not 12584 // the enclosing context. This prevents them from accidentally 12585 // looking like class members in C++. 12586 ParmVarDecl *New = 12587 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 12588 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 12589 12590 if (D.isInvalidType()) 12591 New->setInvalidDecl(); 12592 12593 assert(S->isFunctionPrototypeScope()); 12594 assert(S->getFunctionPrototypeDepth() >= 1); 12595 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 12596 S->getNextFunctionPrototypeIndex()); 12597 12598 // Add the parameter declaration into this scope. 12599 S->AddDecl(New); 12600 if (II) 12601 IdResolver.AddDecl(New); 12602 12603 ProcessDeclAttributes(S, New, D); 12604 12605 if (D.getDeclSpec().isModulePrivateSpecified()) 12606 Diag(New->getLocation(), diag::err_module_private_local) 12607 << 1 << New->getDeclName() 12608 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12609 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12610 12611 if (New->hasAttr<BlocksAttr>()) { 12612 Diag(New->getLocation(), diag::err_block_on_nonlocal); 12613 } 12614 return New; 12615 } 12616 12617 /// Synthesizes a variable for a parameter arising from a 12618 /// typedef. 12619 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 12620 SourceLocation Loc, 12621 QualType T) { 12622 /* FIXME: setting StartLoc == Loc. 12623 Would it be worth to modify callers so as to provide proper source 12624 location for the unnamed parameters, embedding the parameter's type? */ 12625 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 12626 T, Context.getTrivialTypeSourceInfo(T, Loc), 12627 SC_None, nullptr); 12628 Param->setImplicit(); 12629 return Param; 12630 } 12631 12632 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 12633 // Don't diagnose unused-parameter errors in template instantiations; we 12634 // will already have done so in the template itself. 12635 if (inTemplateInstantiation()) 12636 return; 12637 12638 for (const ParmVarDecl *Parameter : Parameters) { 12639 if (!Parameter->isReferenced() && Parameter->getDeclName() && 12640 !Parameter->hasAttr<UnusedAttr>()) { 12641 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 12642 << Parameter->getDeclName(); 12643 } 12644 } 12645 } 12646 12647 void Sema::DiagnoseSizeOfParametersAndReturnValue( 12648 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 12649 if (LangOpts.NumLargeByValueCopy == 0) // No check. 12650 return; 12651 12652 // Warn if the return value is pass-by-value and larger than the specified 12653 // threshold. 12654 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 12655 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 12656 if (Size > LangOpts.NumLargeByValueCopy) 12657 Diag(D->getLocation(), diag::warn_return_value_size) 12658 << D->getDeclName() << Size; 12659 } 12660 12661 // Warn if any parameter is pass-by-value and larger than the specified 12662 // threshold. 12663 for (const ParmVarDecl *Parameter : Parameters) { 12664 QualType T = Parameter->getType(); 12665 if (T->isDependentType() || !T.isPODType(Context)) 12666 continue; 12667 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 12668 if (Size > LangOpts.NumLargeByValueCopy) 12669 Diag(Parameter->getLocation(), diag::warn_parameter_size) 12670 << Parameter->getDeclName() << Size; 12671 } 12672 } 12673 12674 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 12675 SourceLocation NameLoc, IdentifierInfo *Name, 12676 QualType T, TypeSourceInfo *TSInfo, 12677 StorageClass SC) { 12678 // In ARC, infer a lifetime qualifier for appropriate parameter types. 12679 if (getLangOpts().ObjCAutoRefCount && 12680 T.getObjCLifetime() == Qualifiers::OCL_None && 12681 T->isObjCLifetimeType()) { 12682 12683 Qualifiers::ObjCLifetime lifetime; 12684 12685 // Special cases for arrays: 12686 // - if it's const, use __unsafe_unretained 12687 // - otherwise, it's an error 12688 if (T->isArrayType()) { 12689 if (!T.isConstQualified()) { 12690 if (DelayedDiagnostics.shouldDelayDiagnostics()) 12691 DelayedDiagnostics.add( 12692 sema::DelayedDiagnostic::makeForbiddenType( 12693 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 12694 else 12695 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 12696 << TSInfo->getTypeLoc().getSourceRange(); 12697 } 12698 lifetime = Qualifiers::OCL_ExplicitNone; 12699 } else { 12700 lifetime = T->getObjCARCImplicitLifetime(); 12701 } 12702 T = Context.getLifetimeQualifiedType(T, lifetime); 12703 } 12704 12705 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 12706 Context.getAdjustedParameterType(T), 12707 TSInfo, SC, nullptr); 12708 12709 // Parameters can not be abstract class types. 12710 // For record types, this is done by the AbstractClassUsageDiagnoser once 12711 // the class has been completely parsed. 12712 if (!CurContext->isRecord() && 12713 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 12714 AbstractParamType)) 12715 New->setInvalidDecl(); 12716 12717 // Parameter declarators cannot be interface types. All ObjC objects are 12718 // passed by reference. 12719 if (T->isObjCObjectType()) { 12720 SourceLocation TypeEndLoc = 12721 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 12722 Diag(NameLoc, 12723 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 12724 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 12725 T = Context.getObjCObjectPointerType(T); 12726 New->setType(T); 12727 } 12728 12729 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 12730 // duration shall not be qualified by an address-space qualifier." 12731 // Since all parameters have automatic store duration, they can not have 12732 // an address space. 12733 if (T.getAddressSpace() != LangAS::Default && 12734 // OpenCL allows function arguments declared to be an array of a type 12735 // to be qualified with an address space. 12736 !(getLangOpts().OpenCL && 12737 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 12738 Diag(NameLoc, diag::err_arg_with_address_space); 12739 New->setInvalidDecl(); 12740 } 12741 12742 return New; 12743 } 12744 12745 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 12746 SourceLocation LocAfterDecls) { 12747 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 12748 12749 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 12750 // for a K&R function. 12751 if (!FTI.hasPrototype) { 12752 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 12753 --i; 12754 if (FTI.Params[i].Param == nullptr) { 12755 SmallString<256> Code; 12756 llvm::raw_svector_ostream(Code) 12757 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 12758 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 12759 << FTI.Params[i].Ident 12760 << FixItHint::CreateInsertion(LocAfterDecls, Code); 12761 12762 // Implicitly declare the argument as type 'int' for lack of a better 12763 // type. 12764 AttributeFactory attrs; 12765 DeclSpec DS(attrs); 12766 const char* PrevSpec; // unused 12767 unsigned DiagID; // unused 12768 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 12769 DiagID, Context.getPrintingPolicy()); 12770 // Use the identifier location for the type source range. 12771 DS.SetRangeStart(FTI.Params[i].IdentLoc); 12772 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 12773 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 12774 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 12775 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 12776 } 12777 } 12778 } 12779 } 12780 12781 Decl * 12782 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 12783 MultiTemplateParamsArg TemplateParameterLists, 12784 SkipBodyInfo *SkipBody) { 12785 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 12786 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 12787 Scope *ParentScope = FnBodyScope->getParent(); 12788 12789 D.setFunctionDefinitionKind(FDK_Definition); 12790 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 12791 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 12792 } 12793 12794 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 12795 Consumer.HandleInlineFunctionDefinition(D); 12796 } 12797 12798 static bool 12799 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 12800 const FunctionDecl *&PossiblePrototype) { 12801 // Don't warn about invalid declarations. 12802 if (FD->isInvalidDecl()) 12803 return false; 12804 12805 // Or declarations that aren't global. 12806 if (!FD->isGlobal()) 12807 return false; 12808 12809 // Don't warn about C++ member functions. 12810 if (isa<CXXMethodDecl>(FD)) 12811 return false; 12812 12813 // Don't warn about 'main'. 12814 if (FD->isMain()) 12815 return false; 12816 12817 // Don't warn about inline functions. 12818 if (FD->isInlined()) 12819 return false; 12820 12821 // Don't warn about function templates. 12822 if (FD->getDescribedFunctionTemplate()) 12823 return false; 12824 12825 // Don't warn about function template specializations. 12826 if (FD->isFunctionTemplateSpecialization()) 12827 return false; 12828 12829 // Don't warn for OpenCL kernels. 12830 if (FD->hasAttr<OpenCLKernelAttr>()) 12831 return false; 12832 12833 // Don't warn on explicitly deleted functions. 12834 if (FD->isDeleted()) 12835 return false; 12836 12837 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 12838 Prev; Prev = Prev->getPreviousDecl()) { 12839 // Ignore any declarations that occur in function or method 12840 // scope, because they aren't visible from the header. 12841 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 12842 continue; 12843 12844 PossiblePrototype = Prev; 12845 return Prev->getType()->isFunctionNoProtoType(); 12846 } 12847 12848 return true; 12849 } 12850 12851 void 12852 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 12853 const FunctionDecl *EffectiveDefinition, 12854 SkipBodyInfo *SkipBody) { 12855 const FunctionDecl *Definition = EffectiveDefinition; 12856 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 12857 // If this is a friend function defined in a class template, it does not 12858 // have a body until it is used, nevertheless it is a definition, see 12859 // [temp.inst]p2: 12860 // 12861 // ... for the purpose of determining whether an instantiated redeclaration 12862 // is valid according to [basic.def.odr] and [class.mem], a declaration that 12863 // corresponds to a definition in the template is considered to be a 12864 // definition. 12865 // 12866 // The following code must produce redefinition error: 12867 // 12868 // template<typename T> struct C20 { friend void func_20() {} }; 12869 // C20<int> c20i; 12870 // void func_20() {} 12871 // 12872 for (auto I : FD->redecls()) { 12873 if (I != FD && !I->isInvalidDecl() && 12874 I->getFriendObjectKind() != Decl::FOK_None) { 12875 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 12876 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 12877 // A merged copy of the same function, instantiated as a member of 12878 // the same class, is OK. 12879 if (declaresSameEntity(OrigFD, Original) && 12880 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 12881 cast<Decl>(FD->getLexicalDeclContext()))) 12882 continue; 12883 } 12884 12885 if (Original->isThisDeclarationADefinition()) { 12886 Definition = I; 12887 break; 12888 } 12889 } 12890 } 12891 } 12892 } 12893 12894 if (!Definition) 12895 // Similar to friend functions a friend function template may be a 12896 // definition and do not have a body if it is instantiated in a class 12897 // template. 12898 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 12899 for (auto I : FTD->redecls()) { 12900 auto D = cast<FunctionTemplateDecl>(I); 12901 if (D != FTD) { 12902 assert(!D->isThisDeclarationADefinition() && 12903 "More than one definition in redeclaration chain"); 12904 if (D->getFriendObjectKind() != Decl::FOK_None) 12905 if (FunctionTemplateDecl *FT = 12906 D->getInstantiatedFromMemberTemplate()) { 12907 if (FT->isThisDeclarationADefinition()) { 12908 Definition = D->getTemplatedDecl(); 12909 break; 12910 } 12911 } 12912 } 12913 } 12914 } 12915 12916 if (!Definition) 12917 return; 12918 12919 if (canRedefineFunction(Definition, getLangOpts())) 12920 return; 12921 12922 // Don't emit an error when this is redefinition of a typo-corrected 12923 // definition. 12924 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12925 return; 12926 12927 // If we don't have a visible definition of the function, and it's inline or 12928 // a template, skip the new definition. 12929 if (SkipBody && !hasVisibleDefinition(Definition) && 12930 (Definition->getFormalLinkage() == InternalLinkage || 12931 Definition->isInlined() || 12932 Definition->getDescribedFunctionTemplate() || 12933 Definition->getNumTemplateParameterLists())) { 12934 SkipBody->ShouldSkip = true; 12935 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 12936 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12937 makeMergedDefinitionVisible(TD); 12938 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12939 return; 12940 } 12941 12942 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12943 Definition->getStorageClass() == SC_Extern) 12944 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12945 << FD->getDeclName() << getLangOpts().CPlusPlus; 12946 else 12947 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12948 12949 Diag(Definition->getLocation(), diag::note_previous_definition); 12950 FD->setInvalidDecl(); 12951 } 12952 12953 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12954 Sema &S) { 12955 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12956 12957 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12958 LSI->CallOperator = CallOperator; 12959 LSI->Lambda = LambdaClass; 12960 LSI->ReturnType = CallOperator->getReturnType(); 12961 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12962 12963 if (LCD == LCD_None) 12964 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12965 else if (LCD == LCD_ByCopy) 12966 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12967 else if (LCD == LCD_ByRef) 12968 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12969 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12970 12971 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12972 LSI->Mutable = !CallOperator->isConst(); 12973 12974 // Add the captures to the LSI so they can be noted as already 12975 // captured within tryCaptureVar. 12976 auto I = LambdaClass->field_begin(); 12977 for (const auto &C : LambdaClass->captures()) { 12978 if (C.capturesVariable()) { 12979 VarDecl *VD = C.getCapturedVar(); 12980 if (VD->isInitCapture()) 12981 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12982 QualType CaptureType = VD->getType(); 12983 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12984 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12985 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12986 /*EllipsisLoc*/C.isPackExpansion() 12987 ? C.getEllipsisLoc() : SourceLocation(), 12988 CaptureType, /*Invalid*/false); 12989 12990 } else if (C.capturesThis()) { 12991 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 12992 C.getCaptureKind() == LCK_StarThis); 12993 } else { 12994 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 12995 I->getType()); 12996 } 12997 ++I; 12998 } 12999 } 13000 13001 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13002 SkipBodyInfo *SkipBody) { 13003 if (!D) { 13004 // Parsing the function declaration failed in some way. Push on a fake scope 13005 // anyway so we can try to parse the function body. 13006 PushFunctionScope(); 13007 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13008 return D; 13009 } 13010 13011 FunctionDecl *FD = nullptr; 13012 13013 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13014 FD = FunTmpl->getTemplatedDecl(); 13015 else 13016 FD = cast<FunctionDecl>(D); 13017 13018 // Do not push if it is a lambda because one is already pushed when building 13019 // the lambda in ActOnStartOfLambdaDefinition(). 13020 if (!isLambdaCallOperator(FD)) 13021 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13022 13023 // Check for defining attributes before the check for redefinition. 13024 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13025 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13026 FD->dropAttr<AliasAttr>(); 13027 FD->setInvalidDecl(); 13028 } 13029 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13030 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13031 FD->dropAttr<IFuncAttr>(); 13032 FD->setInvalidDecl(); 13033 } 13034 13035 // See if this is a redefinition. If 'will have body' is already set, then 13036 // these checks were already performed when it was set. 13037 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13038 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13039 13040 // If we're skipping the body, we're done. Don't enter the scope. 13041 if (SkipBody && SkipBody->ShouldSkip) 13042 return D; 13043 } 13044 13045 // Mark this function as "will have a body eventually". This lets users to 13046 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13047 // this function. 13048 FD->setWillHaveBody(); 13049 13050 // If we are instantiating a generic lambda call operator, push 13051 // a LambdaScopeInfo onto the function stack. But use the information 13052 // that's already been calculated (ActOnLambdaExpr) to prime the current 13053 // LambdaScopeInfo. 13054 // When the template operator is being specialized, the LambdaScopeInfo, 13055 // has to be properly restored so that tryCaptureVariable doesn't try 13056 // and capture any new variables. In addition when calculating potential 13057 // captures during transformation of nested lambdas, it is necessary to 13058 // have the LSI properly restored. 13059 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13060 assert(inTemplateInstantiation() && 13061 "There should be an active template instantiation on the stack " 13062 "when instantiating a generic lambda!"); 13063 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13064 } else { 13065 // Enter a new function scope 13066 PushFunctionScope(); 13067 } 13068 13069 // Builtin functions cannot be defined. 13070 if (unsigned BuiltinID = FD->getBuiltinID()) { 13071 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13072 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13073 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13074 FD->setInvalidDecl(); 13075 } 13076 } 13077 13078 // The return type of a function definition must be complete 13079 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13080 QualType ResultType = FD->getReturnType(); 13081 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13082 !FD->isInvalidDecl() && 13083 RequireCompleteType(FD->getLocation(), ResultType, 13084 diag::err_func_def_incomplete_result)) 13085 FD->setInvalidDecl(); 13086 13087 if (FnBodyScope) 13088 PushDeclContext(FnBodyScope, FD); 13089 13090 // Check the validity of our function parameters 13091 CheckParmsForFunctionDef(FD->parameters(), 13092 /*CheckParameterNames=*/true); 13093 13094 // Add non-parameter declarations already in the function to the current 13095 // scope. 13096 if (FnBodyScope) { 13097 for (Decl *NPD : FD->decls()) { 13098 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13099 if (!NonParmDecl) 13100 continue; 13101 assert(!isa<ParmVarDecl>(NonParmDecl) && 13102 "parameters should not be in newly created FD yet"); 13103 13104 // If the decl has a name, make it accessible in the current scope. 13105 if (NonParmDecl->getDeclName()) 13106 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13107 13108 // Similarly, dive into enums and fish their constants out, making them 13109 // accessible in this scope. 13110 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13111 for (auto *EI : ED->enumerators()) 13112 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13113 } 13114 } 13115 } 13116 13117 // Introduce our parameters into the function scope 13118 for (auto Param : FD->parameters()) { 13119 Param->setOwningFunction(FD); 13120 13121 // If this has an identifier, add it to the scope stack. 13122 if (Param->getIdentifier() && FnBodyScope) { 13123 CheckShadow(FnBodyScope, Param); 13124 13125 PushOnScopeChains(Param, FnBodyScope); 13126 } 13127 } 13128 13129 // Ensure that the function's exception specification is instantiated. 13130 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 13131 ResolveExceptionSpec(D->getLocation(), FPT); 13132 13133 // dllimport cannot be applied to non-inline function definitions. 13134 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 13135 !FD->isTemplateInstantiation()) { 13136 assert(!FD->hasAttr<DLLExportAttr>()); 13137 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 13138 FD->setInvalidDecl(); 13139 return D; 13140 } 13141 // We want to attach documentation to original Decl (which might be 13142 // a function template). 13143 ActOnDocumentableDecl(D); 13144 if (getCurLexicalContext()->isObjCContainer() && 13145 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 13146 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 13147 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 13148 13149 return D; 13150 } 13151 13152 /// Given the set of return statements within a function body, 13153 /// compute the variables that are subject to the named return value 13154 /// optimization. 13155 /// 13156 /// Each of the variables that is subject to the named return value 13157 /// optimization will be marked as NRVO variables in the AST, and any 13158 /// return statement that has a marked NRVO variable as its NRVO candidate can 13159 /// use the named return value optimization. 13160 /// 13161 /// This function applies a very simplistic algorithm for NRVO: if every return 13162 /// statement in the scope of a variable has the same NRVO candidate, that 13163 /// candidate is an NRVO variable. 13164 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 13165 ReturnStmt **Returns = Scope->Returns.data(); 13166 13167 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 13168 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 13169 if (!NRVOCandidate->isNRVOVariable()) 13170 Returns[I]->setNRVOCandidate(nullptr); 13171 } 13172 } 13173 } 13174 13175 bool Sema::canDelayFunctionBody(const Declarator &D) { 13176 // We can't delay parsing the body of a constexpr function template (yet). 13177 if (D.getDeclSpec().hasConstexprSpecifier()) 13178 return false; 13179 13180 // We can't delay parsing the body of a function template with a deduced 13181 // return type (yet). 13182 if (D.getDeclSpec().hasAutoTypeSpec()) { 13183 // If the placeholder introduces a non-deduced trailing return type, 13184 // we can still delay parsing it. 13185 if (D.getNumTypeObjects()) { 13186 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 13187 if (Outer.Kind == DeclaratorChunk::Function && 13188 Outer.Fun.hasTrailingReturnType()) { 13189 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 13190 return Ty.isNull() || !Ty->isUndeducedType(); 13191 } 13192 } 13193 return false; 13194 } 13195 13196 return true; 13197 } 13198 13199 bool Sema::canSkipFunctionBody(Decl *D) { 13200 // We cannot skip the body of a function (or function template) which is 13201 // constexpr, since we may need to evaluate its body in order to parse the 13202 // rest of the file. 13203 // We cannot skip the body of a function with an undeduced return type, 13204 // because any callers of that function need to know the type. 13205 if (const FunctionDecl *FD = D->getAsFunction()) { 13206 if (FD->isConstexpr()) 13207 return false; 13208 // We can't simply call Type::isUndeducedType here, because inside template 13209 // auto can be deduced to a dependent type, which is not considered 13210 // "undeduced". 13211 if (FD->getReturnType()->getContainedDeducedType()) 13212 return false; 13213 } 13214 return Consumer.shouldSkipFunctionBody(D); 13215 } 13216 13217 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 13218 if (!Decl) 13219 return nullptr; 13220 if (FunctionDecl *FD = Decl->getAsFunction()) 13221 FD->setHasSkippedBody(); 13222 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 13223 MD->setHasSkippedBody(); 13224 return Decl; 13225 } 13226 13227 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 13228 return ActOnFinishFunctionBody(D, BodyArg, false); 13229 } 13230 13231 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 13232 /// body. 13233 class ExitFunctionBodyRAII { 13234 public: 13235 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 13236 ~ExitFunctionBodyRAII() { 13237 if (!IsLambda) 13238 S.PopExpressionEvaluationContext(); 13239 } 13240 13241 private: 13242 Sema &S; 13243 bool IsLambda = false; 13244 }; 13245 13246 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 13247 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 13248 13249 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 13250 if (EscapeInfo.count(BD)) 13251 return EscapeInfo[BD]; 13252 13253 bool R = false; 13254 const BlockDecl *CurBD = BD; 13255 13256 do { 13257 R = !CurBD->doesNotEscape(); 13258 if (R) 13259 break; 13260 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 13261 } while (CurBD); 13262 13263 return EscapeInfo[BD] = R; 13264 }; 13265 13266 // If the location where 'self' is implicitly retained is inside a escaping 13267 // block, emit a diagnostic. 13268 for (const std::pair<SourceLocation, const BlockDecl *> &P : 13269 S.ImplicitlyRetainedSelfLocs) 13270 if (IsOrNestedInEscapingBlock(P.second)) 13271 S.Diag(P.first, diag::warn_implicitly_retains_self) 13272 << FixItHint::CreateInsertion(P.first, "self->"); 13273 } 13274 13275 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 13276 bool IsInstantiation) { 13277 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 13278 13279 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13280 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 13281 13282 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 13283 CheckCompletedCoroutineBody(FD, Body); 13284 13285 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 13286 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 13287 // meant to pop the context added in ActOnStartOfFunctionDef(). 13288 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 13289 13290 if (FD) { 13291 FD->setBody(Body); 13292 FD->setWillHaveBody(false); 13293 13294 if (getLangOpts().CPlusPlus14) { 13295 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 13296 FD->getReturnType()->isUndeducedType()) { 13297 // If the function has a deduced result type but contains no 'return' 13298 // statements, the result type as written must be exactly 'auto', and 13299 // the deduced result type is 'void'. 13300 if (!FD->getReturnType()->getAs<AutoType>()) { 13301 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 13302 << FD->getReturnType(); 13303 FD->setInvalidDecl(); 13304 } else { 13305 // Substitute 'void' for the 'auto' in the type. 13306 TypeLoc ResultType = getReturnTypeLoc(FD); 13307 Context.adjustDeducedFunctionResultType( 13308 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 13309 } 13310 } 13311 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 13312 // In C++11, we don't use 'auto' deduction rules for lambda call 13313 // operators because we don't support return type deduction. 13314 auto *LSI = getCurLambda(); 13315 if (LSI->HasImplicitReturnType) { 13316 deduceClosureReturnType(*LSI); 13317 13318 // C++11 [expr.prim.lambda]p4: 13319 // [...] if there are no return statements in the compound-statement 13320 // [the deduced type is] the type void 13321 QualType RetType = 13322 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 13323 13324 // Update the return type to the deduced type. 13325 const FunctionProtoType *Proto = 13326 FD->getType()->getAs<FunctionProtoType>(); 13327 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 13328 Proto->getExtProtoInfo())); 13329 } 13330 } 13331 13332 // If the function implicitly returns zero (like 'main') or is naked, 13333 // don't complain about missing return statements. 13334 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 13335 WP.disableCheckFallThrough(); 13336 13337 // MSVC permits the use of pure specifier (=0) on function definition, 13338 // defined at class scope, warn about this non-standard construct. 13339 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 13340 Diag(FD->getLocation(), diag::ext_pure_function_definition); 13341 13342 if (!FD->isInvalidDecl()) { 13343 // Don't diagnose unused parameters of defaulted or deleted functions. 13344 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 13345 DiagnoseUnusedParameters(FD->parameters()); 13346 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 13347 FD->getReturnType(), FD); 13348 13349 // If this is a structor, we need a vtable. 13350 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 13351 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 13352 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 13353 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 13354 13355 // Try to apply the named return value optimization. We have to check 13356 // if we can do this here because lambdas keep return statements around 13357 // to deduce an implicit return type. 13358 if (FD->getReturnType()->isRecordType() && 13359 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 13360 computeNRVO(Body, getCurFunction()); 13361 } 13362 13363 // GNU warning -Wmissing-prototypes: 13364 // Warn if a global function is defined without a previous 13365 // prototype declaration. This warning is issued even if the 13366 // definition itself provides a prototype. The aim is to detect 13367 // global functions that fail to be declared in header files. 13368 const FunctionDecl *PossiblePrototype = nullptr; 13369 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 13370 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 13371 13372 if (PossiblePrototype) { 13373 // We found a declaration that is not a prototype, 13374 // but that could be a zero-parameter prototype 13375 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 13376 TypeLoc TL = TI->getTypeLoc(); 13377 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 13378 Diag(PossiblePrototype->getLocation(), 13379 diag::note_declaration_not_a_prototype) 13380 << (FD->getNumParams() != 0) 13381 << (FD->getNumParams() == 0 13382 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 13383 : FixItHint{}); 13384 } 13385 } else { 13386 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13387 << /* function */ 1 13388 << (FD->getStorageClass() == SC_None 13389 ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(), 13390 "static ") 13391 : FixItHint{}); 13392 } 13393 13394 // GNU warning -Wstrict-prototypes 13395 // Warn if K&R function is defined without a previous declaration. 13396 // This warning is issued only if the definition itself does not provide 13397 // a prototype. Only K&R definitions do not provide a prototype. 13398 // An empty list in a function declarator that is part of a definition 13399 // of that function specifies that the function has no parameters 13400 // (C99 6.7.5.3p14) 13401 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 13402 !LangOpts.CPlusPlus) { 13403 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 13404 TypeLoc TL = TI->getTypeLoc(); 13405 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 13406 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 13407 } 13408 } 13409 13410 // Warn on CPUDispatch with an actual body. 13411 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 13412 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 13413 if (!CmpndBody->body_empty()) 13414 Diag(CmpndBody->body_front()->getBeginLoc(), 13415 diag::warn_dispatch_body_ignored); 13416 13417 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 13418 const CXXMethodDecl *KeyFunction; 13419 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 13420 MD->isVirtual() && 13421 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 13422 MD == KeyFunction->getCanonicalDecl()) { 13423 // Update the key-function state if necessary for this ABI. 13424 if (FD->isInlined() && 13425 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 13426 Context.setNonKeyFunction(MD); 13427 13428 // If the newly-chosen key function is already defined, then we 13429 // need to mark the vtable as used retroactively. 13430 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 13431 const FunctionDecl *Definition; 13432 if (KeyFunction && KeyFunction->isDefined(Definition)) 13433 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 13434 } else { 13435 // We just defined they key function; mark the vtable as used. 13436 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 13437 } 13438 } 13439 } 13440 13441 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 13442 "Function parsing confused"); 13443 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 13444 assert(MD == getCurMethodDecl() && "Method parsing confused"); 13445 MD->setBody(Body); 13446 if (!MD->isInvalidDecl()) { 13447 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 13448 MD->getReturnType(), MD); 13449 13450 if (Body) 13451 computeNRVO(Body, getCurFunction()); 13452 } 13453 if (getCurFunction()->ObjCShouldCallSuper) { 13454 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 13455 << MD->getSelector().getAsString(); 13456 getCurFunction()->ObjCShouldCallSuper = false; 13457 } 13458 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 13459 const ObjCMethodDecl *InitMethod = nullptr; 13460 bool isDesignated = 13461 MD->isDesignatedInitializerForTheInterface(&InitMethod); 13462 assert(isDesignated && InitMethod); 13463 (void)isDesignated; 13464 13465 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 13466 auto IFace = MD->getClassInterface(); 13467 if (!IFace) 13468 return false; 13469 auto SuperD = IFace->getSuperClass(); 13470 if (!SuperD) 13471 return false; 13472 return SuperD->getIdentifier() == 13473 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 13474 }; 13475 // Don't issue this warning for unavailable inits or direct subclasses 13476 // of NSObject. 13477 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 13478 Diag(MD->getLocation(), 13479 diag::warn_objc_designated_init_missing_super_call); 13480 Diag(InitMethod->getLocation(), 13481 diag::note_objc_designated_init_marked_here); 13482 } 13483 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 13484 } 13485 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 13486 // Don't issue this warning for unavaialable inits. 13487 if (!MD->isUnavailable()) 13488 Diag(MD->getLocation(), 13489 diag::warn_objc_secondary_init_missing_init_call); 13490 getCurFunction()->ObjCWarnForNoInitDelegation = false; 13491 } 13492 13493 diagnoseImplicitlyRetainedSelf(*this); 13494 } else { 13495 // Parsing the function declaration failed in some way. Pop the fake scope 13496 // we pushed on. 13497 PopFunctionScopeInfo(ActivePolicy, dcl); 13498 return nullptr; 13499 } 13500 13501 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13502 DiagnoseUnguardedAvailabilityViolations(dcl); 13503 13504 assert(!getCurFunction()->ObjCShouldCallSuper && 13505 "This should only be set for ObjC methods, which should have been " 13506 "handled in the block above."); 13507 13508 // Verify and clean out per-function state. 13509 if (Body && (!FD || !FD->isDefaulted())) { 13510 // C++ constructors that have function-try-blocks can't have return 13511 // statements in the handlers of that block. (C++ [except.handle]p14) 13512 // Verify this. 13513 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 13514 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 13515 13516 // Verify that gotos and switch cases don't jump into scopes illegally. 13517 if (getCurFunction()->NeedsScopeChecking() && 13518 !PP.isCodeCompletionEnabled()) 13519 DiagnoseInvalidJumps(Body); 13520 13521 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 13522 if (!Destructor->getParent()->isDependentType()) 13523 CheckDestructor(Destructor); 13524 13525 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13526 Destructor->getParent()); 13527 } 13528 13529 // If any errors have occurred, clear out any temporaries that may have 13530 // been leftover. This ensures that these temporaries won't be picked up for 13531 // deletion in some later function. 13532 if (getDiagnostics().hasErrorOccurred() || 13533 getDiagnostics().getSuppressAllDiagnostics()) { 13534 DiscardCleanupsInEvaluationContext(); 13535 } 13536 if (!getDiagnostics().hasUncompilableErrorOccurred() && 13537 !isa<FunctionTemplateDecl>(dcl)) { 13538 // Since the body is valid, issue any analysis-based warnings that are 13539 // enabled. 13540 ActivePolicy = &WP; 13541 } 13542 13543 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 13544 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 13545 FD->setInvalidDecl(); 13546 13547 if (FD && FD->hasAttr<NakedAttr>()) { 13548 for (const Stmt *S : Body->children()) { 13549 // Allow local register variables without initializer as they don't 13550 // require prologue. 13551 bool RegisterVariables = false; 13552 if (auto *DS = dyn_cast<DeclStmt>(S)) { 13553 for (const auto *Decl : DS->decls()) { 13554 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 13555 RegisterVariables = 13556 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 13557 if (!RegisterVariables) 13558 break; 13559 } 13560 } 13561 } 13562 if (RegisterVariables) 13563 continue; 13564 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 13565 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 13566 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 13567 FD->setInvalidDecl(); 13568 break; 13569 } 13570 } 13571 } 13572 13573 assert(ExprCleanupObjects.size() == 13574 ExprEvalContexts.back().NumCleanupObjects && 13575 "Leftover temporaries in function"); 13576 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 13577 assert(MaybeODRUseExprs.empty() && 13578 "Leftover expressions for odr-use checking"); 13579 } 13580 13581 if (!IsInstantiation) 13582 PopDeclContext(); 13583 13584 PopFunctionScopeInfo(ActivePolicy, dcl); 13585 // If any errors have occurred, clear out any temporaries that may have 13586 // been leftover. This ensures that these temporaries won't be picked up for 13587 // deletion in some later function. 13588 if (getDiagnostics().hasErrorOccurred()) { 13589 DiscardCleanupsInEvaluationContext(); 13590 } 13591 13592 return dcl; 13593 } 13594 13595 /// When we finish delayed parsing of an attribute, we must attach it to the 13596 /// relevant Decl. 13597 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 13598 ParsedAttributes &Attrs) { 13599 // Always attach attributes to the underlying decl. 13600 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 13601 D = TD->getTemplatedDecl(); 13602 ProcessDeclAttributeList(S, D, Attrs); 13603 13604 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 13605 if (Method->isStatic()) 13606 checkThisInStaticMemberFunctionAttributes(Method); 13607 } 13608 13609 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 13610 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 13611 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 13612 IdentifierInfo &II, Scope *S) { 13613 // Find the scope in which the identifier is injected and the corresponding 13614 // DeclContext. 13615 // FIXME: C89 does not say what happens if there is no enclosing block scope. 13616 // In that case, we inject the declaration into the translation unit scope 13617 // instead. 13618 Scope *BlockScope = S; 13619 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 13620 BlockScope = BlockScope->getParent(); 13621 13622 Scope *ContextScope = BlockScope; 13623 while (!ContextScope->getEntity()) 13624 ContextScope = ContextScope->getParent(); 13625 ContextRAII SavedContext(*this, ContextScope->getEntity()); 13626 13627 // Before we produce a declaration for an implicitly defined 13628 // function, see whether there was a locally-scoped declaration of 13629 // this name as a function or variable. If so, use that 13630 // (non-visible) declaration, and complain about it. 13631 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 13632 if (ExternCPrev) { 13633 // We still need to inject the function into the enclosing block scope so 13634 // that later (non-call) uses can see it. 13635 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 13636 13637 // C89 footnote 38: 13638 // If in fact it is not defined as having type "function returning int", 13639 // the behavior is undefined. 13640 if (!isa<FunctionDecl>(ExternCPrev) || 13641 !Context.typesAreCompatible( 13642 cast<FunctionDecl>(ExternCPrev)->getType(), 13643 Context.getFunctionNoProtoType(Context.IntTy))) { 13644 Diag(Loc, diag::ext_use_out_of_scope_declaration) 13645 << ExternCPrev << !getLangOpts().C99; 13646 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 13647 return ExternCPrev; 13648 } 13649 } 13650 13651 // Extension in C99. Legal in C90, but warn about it. 13652 unsigned diag_id; 13653 if (II.getName().startswith("__builtin_")) 13654 diag_id = diag::warn_builtin_unknown; 13655 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 13656 else if (getLangOpts().OpenCL) 13657 diag_id = diag::err_opencl_implicit_function_decl; 13658 else if (getLangOpts().C99) 13659 diag_id = diag::ext_implicit_function_decl; 13660 else 13661 diag_id = diag::warn_implicit_function_decl; 13662 Diag(Loc, diag_id) << &II; 13663 13664 // If we found a prior declaration of this function, don't bother building 13665 // another one. We've already pushed that one into scope, so there's nothing 13666 // more to do. 13667 if (ExternCPrev) 13668 return ExternCPrev; 13669 13670 // Because typo correction is expensive, only do it if the implicit 13671 // function declaration is going to be treated as an error. 13672 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 13673 TypoCorrection Corrected; 13674 DeclFilterCCC<FunctionDecl> CCC{}; 13675 if (S && (Corrected = 13676 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 13677 S, nullptr, CCC, CTK_NonError))) 13678 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 13679 /*ErrorRecovery*/false); 13680 } 13681 13682 // Set a Declarator for the implicit definition: int foo(); 13683 const char *Dummy; 13684 AttributeFactory attrFactory; 13685 DeclSpec DS(attrFactory); 13686 unsigned DiagID; 13687 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 13688 Context.getPrintingPolicy()); 13689 (void)Error; // Silence warning. 13690 assert(!Error && "Error setting up implicit decl!"); 13691 SourceLocation NoLoc; 13692 Declarator D(DS, DeclaratorContext::BlockContext); 13693 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 13694 /*IsAmbiguous=*/false, 13695 /*LParenLoc=*/NoLoc, 13696 /*Params=*/nullptr, 13697 /*NumParams=*/0, 13698 /*EllipsisLoc=*/NoLoc, 13699 /*RParenLoc=*/NoLoc, 13700 /*RefQualifierIsLvalueRef=*/true, 13701 /*RefQualifierLoc=*/NoLoc, 13702 /*MutableLoc=*/NoLoc, EST_None, 13703 /*ESpecRange=*/SourceRange(), 13704 /*Exceptions=*/nullptr, 13705 /*ExceptionRanges=*/nullptr, 13706 /*NumExceptions=*/0, 13707 /*NoexceptExpr=*/nullptr, 13708 /*ExceptionSpecTokens=*/nullptr, 13709 /*DeclsInPrototype=*/None, Loc, 13710 Loc, D), 13711 std::move(DS.getAttributes()), SourceLocation()); 13712 D.SetIdentifier(&II, Loc); 13713 13714 // Insert this function into the enclosing block scope. 13715 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 13716 FD->setImplicit(); 13717 13718 AddKnownFunctionAttributes(FD); 13719 13720 return FD; 13721 } 13722 13723 /// Adds any function attributes that we know a priori based on 13724 /// the declaration of this function. 13725 /// 13726 /// These attributes can apply both to implicitly-declared builtins 13727 /// (like __builtin___printf_chk) or to library-declared functions 13728 /// like NSLog or printf. 13729 /// 13730 /// We need to check for duplicate attributes both here and where user-written 13731 /// attributes are applied to declarations. 13732 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 13733 if (FD->isInvalidDecl()) 13734 return; 13735 13736 // If this is a built-in function, map its builtin attributes to 13737 // actual attributes. 13738 if (unsigned BuiltinID = FD->getBuiltinID()) { 13739 // Handle printf-formatting attributes. 13740 unsigned FormatIdx; 13741 bool HasVAListArg; 13742 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 13743 if (!FD->hasAttr<FormatAttr>()) { 13744 const char *fmt = "printf"; 13745 unsigned int NumParams = FD->getNumParams(); 13746 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 13747 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 13748 fmt = "NSString"; 13749 FD->addAttr(FormatAttr::CreateImplicit(Context, 13750 &Context.Idents.get(fmt), 13751 FormatIdx+1, 13752 HasVAListArg ? 0 : FormatIdx+2, 13753 FD->getLocation())); 13754 } 13755 } 13756 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 13757 HasVAListArg)) { 13758 if (!FD->hasAttr<FormatAttr>()) 13759 FD->addAttr(FormatAttr::CreateImplicit(Context, 13760 &Context.Idents.get("scanf"), 13761 FormatIdx+1, 13762 HasVAListArg ? 0 : FormatIdx+2, 13763 FD->getLocation())); 13764 } 13765 13766 // Handle automatically recognized callbacks. 13767 SmallVector<int, 4> Encoding; 13768 if (!FD->hasAttr<CallbackAttr>() && 13769 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 13770 FD->addAttr(CallbackAttr::CreateImplicit( 13771 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 13772 13773 // Mark const if we don't care about errno and that is the only thing 13774 // preventing the function from being const. This allows IRgen to use LLVM 13775 // intrinsics for such functions. 13776 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 13777 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 13778 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13779 13780 // We make "fma" on some platforms const because we know it does not set 13781 // errno in those environments even though it could set errno based on the 13782 // C standard. 13783 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 13784 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 13785 !FD->hasAttr<ConstAttr>()) { 13786 switch (BuiltinID) { 13787 case Builtin::BI__builtin_fma: 13788 case Builtin::BI__builtin_fmaf: 13789 case Builtin::BI__builtin_fmal: 13790 case Builtin::BIfma: 13791 case Builtin::BIfmaf: 13792 case Builtin::BIfmal: 13793 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13794 break; 13795 default: 13796 break; 13797 } 13798 } 13799 13800 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 13801 !FD->hasAttr<ReturnsTwiceAttr>()) 13802 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 13803 FD->getLocation())); 13804 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 13805 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13806 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 13807 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 13808 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 13809 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13810 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 13811 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 13812 // Add the appropriate attribute, depending on the CUDA compilation mode 13813 // and which target the builtin belongs to. For example, during host 13814 // compilation, aux builtins are __device__, while the rest are __host__. 13815 if (getLangOpts().CUDAIsDevice != 13816 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 13817 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 13818 else 13819 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 13820 } 13821 } 13822 13823 // If C++ exceptions are enabled but we are told extern "C" functions cannot 13824 // throw, add an implicit nothrow attribute to any extern "C" function we come 13825 // across. 13826 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 13827 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 13828 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 13829 if (!FPT || FPT->getExceptionSpecType() == EST_None) 13830 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13831 } 13832 13833 IdentifierInfo *Name = FD->getIdentifier(); 13834 if (!Name) 13835 return; 13836 if ((!getLangOpts().CPlusPlus && 13837 FD->getDeclContext()->isTranslationUnit()) || 13838 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 13839 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 13840 LinkageSpecDecl::lang_c)) { 13841 // Okay: this could be a libc/libm/Objective-C function we know 13842 // about. 13843 } else 13844 return; 13845 13846 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 13847 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 13848 // target-specific builtins, perhaps? 13849 if (!FD->hasAttr<FormatAttr>()) 13850 FD->addAttr(FormatAttr::CreateImplicit(Context, 13851 &Context.Idents.get("printf"), 2, 13852 Name->isStr("vasprintf") ? 0 : 3, 13853 FD->getLocation())); 13854 } 13855 13856 if (Name->isStr("__CFStringMakeConstantString")) { 13857 // We already have a __builtin___CFStringMakeConstantString, 13858 // but builds that use -fno-constant-cfstrings don't go through that. 13859 if (!FD->hasAttr<FormatArgAttr>()) 13860 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 13861 FD->getLocation())); 13862 } 13863 } 13864 13865 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 13866 TypeSourceInfo *TInfo) { 13867 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 13868 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 13869 13870 if (!TInfo) { 13871 assert(D.isInvalidType() && "no declarator info for valid type"); 13872 TInfo = Context.getTrivialTypeSourceInfo(T); 13873 } 13874 13875 // Scope manipulation handled by caller. 13876 TypedefDecl *NewTD = 13877 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 13878 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 13879 13880 // Bail out immediately if we have an invalid declaration. 13881 if (D.isInvalidType()) { 13882 NewTD->setInvalidDecl(); 13883 return NewTD; 13884 } 13885 13886 if (D.getDeclSpec().isModulePrivateSpecified()) { 13887 if (CurContext->isFunctionOrMethod()) 13888 Diag(NewTD->getLocation(), diag::err_module_private_local) 13889 << 2 << NewTD->getDeclName() 13890 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13891 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13892 else 13893 NewTD->setModulePrivate(); 13894 } 13895 13896 // C++ [dcl.typedef]p8: 13897 // If the typedef declaration defines an unnamed class (or 13898 // enum), the first typedef-name declared by the declaration 13899 // to be that class type (or enum type) is used to denote the 13900 // class type (or enum type) for linkage purposes only. 13901 // We need to check whether the type was declared in the declaration. 13902 switch (D.getDeclSpec().getTypeSpecType()) { 13903 case TST_enum: 13904 case TST_struct: 13905 case TST_interface: 13906 case TST_union: 13907 case TST_class: { 13908 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 13909 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 13910 break; 13911 } 13912 13913 default: 13914 break; 13915 } 13916 13917 return NewTD; 13918 } 13919 13920 /// Check that this is a valid underlying type for an enum declaration. 13921 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 13922 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 13923 QualType T = TI->getType(); 13924 13925 if (T->isDependentType()) 13926 return false; 13927 13928 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 13929 if (BT->isInteger()) 13930 return false; 13931 13932 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 13933 return true; 13934 } 13935 13936 /// Check whether this is a valid redeclaration of a previous enumeration. 13937 /// \return true if the redeclaration was invalid. 13938 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 13939 QualType EnumUnderlyingTy, bool IsFixed, 13940 const EnumDecl *Prev) { 13941 if (IsScoped != Prev->isScoped()) { 13942 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 13943 << Prev->isScoped(); 13944 Diag(Prev->getLocation(), diag::note_previous_declaration); 13945 return true; 13946 } 13947 13948 if (IsFixed && Prev->isFixed()) { 13949 if (!EnumUnderlyingTy->isDependentType() && 13950 !Prev->getIntegerType()->isDependentType() && 13951 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 13952 Prev->getIntegerType())) { 13953 // TODO: Highlight the underlying type of the redeclaration. 13954 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 13955 << EnumUnderlyingTy << Prev->getIntegerType(); 13956 Diag(Prev->getLocation(), diag::note_previous_declaration) 13957 << Prev->getIntegerTypeRange(); 13958 return true; 13959 } 13960 } else if (IsFixed != Prev->isFixed()) { 13961 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 13962 << Prev->isFixed(); 13963 Diag(Prev->getLocation(), diag::note_previous_declaration); 13964 return true; 13965 } 13966 13967 return false; 13968 } 13969 13970 /// Get diagnostic %select index for tag kind for 13971 /// redeclaration diagnostic message. 13972 /// WARNING: Indexes apply to particular diagnostics only! 13973 /// 13974 /// \returns diagnostic %select index. 13975 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 13976 switch (Tag) { 13977 case TTK_Struct: return 0; 13978 case TTK_Interface: return 1; 13979 case TTK_Class: return 2; 13980 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 13981 } 13982 } 13983 13984 /// Determine if tag kind is a class-key compatible with 13985 /// class for redeclaration (class, struct, or __interface). 13986 /// 13987 /// \returns true iff the tag kind is compatible. 13988 static bool isClassCompatTagKind(TagTypeKind Tag) 13989 { 13990 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 13991 } 13992 13993 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 13994 TagTypeKind TTK) { 13995 if (isa<TypedefDecl>(PrevDecl)) 13996 return NTK_Typedef; 13997 else if (isa<TypeAliasDecl>(PrevDecl)) 13998 return NTK_TypeAlias; 13999 else if (isa<ClassTemplateDecl>(PrevDecl)) 14000 return NTK_Template; 14001 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 14002 return NTK_TypeAliasTemplate; 14003 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 14004 return NTK_TemplateTemplateArgument; 14005 switch (TTK) { 14006 case TTK_Struct: 14007 case TTK_Interface: 14008 case TTK_Class: 14009 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 14010 case TTK_Union: 14011 return NTK_NonUnion; 14012 case TTK_Enum: 14013 return NTK_NonEnum; 14014 } 14015 llvm_unreachable("invalid TTK"); 14016 } 14017 14018 /// Determine whether a tag with a given kind is acceptable 14019 /// as a redeclaration of the given tag declaration. 14020 /// 14021 /// \returns true if the new tag kind is acceptable, false otherwise. 14022 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 14023 TagTypeKind NewTag, bool isDefinition, 14024 SourceLocation NewTagLoc, 14025 const IdentifierInfo *Name) { 14026 // C++ [dcl.type.elab]p3: 14027 // The class-key or enum keyword present in the 14028 // elaborated-type-specifier shall agree in kind with the 14029 // declaration to which the name in the elaborated-type-specifier 14030 // refers. This rule also applies to the form of 14031 // elaborated-type-specifier that declares a class-name or 14032 // friend class since it can be construed as referring to the 14033 // definition of the class. Thus, in any 14034 // elaborated-type-specifier, the enum keyword shall be used to 14035 // refer to an enumeration (7.2), the union class-key shall be 14036 // used to refer to a union (clause 9), and either the class or 14037 // struct class-key shall be used to refer to a class (clause 9) 14038 // declared using the class or struct class-key. 14039 TagTypeKind OldTag = Previous->getTagKind(); 14040 if (OldTag != NewTag && 14041 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 14042 return false; 14043 14044 // Tags are compatible, but we might still want to warn on mismatched tags. 14045 // Non-class tags can't be mismatched at this point. 14046 if (!isClassCompatTagKind(NewTag)) 14047 return true; 14048 14049 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 14050 // by our warning analysis. We don't want to warn about mismatches with (eg) 14051 // declarations in system headers that are designed to be specialized, but if 14052 // a user asks us to warn, we should warn if their code contains mismatched 14053 // declarations. 14054 auto IsIgnoredLoc = [&](SourceLocation Loc) { 14055 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 14056 Loc); 14057 }; 14058 if (IsIgnoredLoc(NewTagLoc)) 14059 return true; 14060 14061 auto IsIgnored = [&](const TagDecl *Tag) { 14062 return IsIgnoredLoc(Tag->getLocation()); 14063 }; 14064 while (IsIgnored(Previous)) { 14065 Previous = Previous->getPreviousDecl(); 14066 if (!Previous) 14067 return true; 14068 OldTag = Previous->getTagKind(); 14069 } 14070 14071 bool isTemplate = false; 14072 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 14073 isTemplate = Record->getDescribedClassTemplate(); 14074 14075 if (inTemplateInstantiation()) { 14076 if (OldTag != NewTag) { 14077 // In a template instantiation, do not offer fix-its for tag mismatches 14078 // since they usually mess up the template instead of fixing the problem. 14079 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14080 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14081 << getRedeclDiagFromTagKind(OldTag); 14082 // FIXME: Note previous location? 14083 } 14084 return true; 14085 } 14086 14087 if (isDefinition) { 14088 // On definitions, check all previous tags and issue a fix-it for each 14089 // one that doesn't match the current tag. 14090 if (Previous->getDefinition()) { 14091 // Don't suggest fix-its for redefinitions. 14092 return true; 14093 } 14094 14095 bool previousMismatch = false; 14096 for (const TagDecl *I : Previous->redecls()) { 14097 if (I->getTagKind() != NewTag) { 14098 // Ignore previous declarations for which the warning was disabled. 14099 if (IsIgnored(I)) 14100 continue; 14101 14102 if (!previousMismatch) { 14103 previousMismatch = true; 14104 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 14105 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14106 << getRedeclDiagFromTagKind(I->getTagKind()); 14107 } 14108 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 14109 << getRedeclDiagFromTagKind(NewTag) 14110 << FixItHint::CreateReplacement(I->getInnerLocStart(), 14111 TypeWithKeyword::getTagTypeKindName(NewTag)); 14112 } 14113 } 14114 return true; 14115 } 14116 14117 // Identify the prevailing tag kind: this is the kind of the definition (if 14118 // there is a non-ignored definition), or otherwise the kind of the prior 14119 // (non-ignored) declaration. 14120 const TagDecl *PrevDef = Previous->getDefinition(); 14121 if (PrevDef && IsIgnored(PrevDef)) 14122 PrevDef = nullptr; 14123 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 14124 if (Redecl->getTagKind() != NewTag) { 14125 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14126 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14127 << getRedeclDiagFromTagKind(OldTag); 14128 Diag(Redecl->getLocation(), diag::note_previous_use); 14129 14130 // If there is a previous definition, suggest a fix-it. 14131 if (PrevDef) { 14132 Diag(NewTagLoc, diag::note_struct_class_suggestion) 14133 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 14134 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 14135 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 14136 } 14137 } 14138 14139 return true; 14140 } 14141 14142 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 14143 /// from an outer enclosing namespace or file scope inside a friend declaration. 14144 /// This should provide the commented out code in the following snippet: 14145 /// namespace N { 14146 /// struct X; 14147 /// namespace M { 14148 /// struct Y { friend struct /*N::*/ X; }; 14149 /// } 14150 /// } 14151 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 14152 SourceLocation NameLoc) { 14153 // While the decl is in a namespace, do repeated lookup of that name and see 14154 // if we get the same namespace back. If we do not, continue until 14155 // translation unit scope, at which point we have a fully qualified NNS. 14156 SmallVector<IdentifierInfo *, 4> Namespaces; 14157 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14158 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 14159 // This tag should be declared in a namespace, which can only be enclosed by 14160 // other namespaces. Bail if there's an anonymous namespace in the chain. 14161 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 14162 if (!Namespace || Namespace->isAnonymousNamespace()) 14163 return FixItHint(); 14164 IdentifierInfo *II = Namespace->getIdentifier(); 14165 Namespaces.push_back(II); 14166 NamedDecl *Lookup = SemaRef.LookupSingleName( 14167 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 14168 if (Lookup == Namespace) 14169 break; 14170 } 14171 14172 // Once we have all the namespaces, reverse them to go outermost first, and 14173 // build an NNS. 14174 SmallString<64> Insertion; 14175 llvm::raw_svector_ostream OS(Insertion); 14176 if (DC->isTranslationUnit()) 14177 OS << "::"; 14178 std::reverse(Namespaces.begin(), Namespaces.end()); 14179 for (auto *II : Namespaces) 14180 OS << II->getName() << "::"; 14181 return FixItHint::CreateInsertion(NameLoc, Insertion); 14182 } 14183 14184 /// Determine whether a tag originally declared in context \p OldDC can 14185 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 14186 /// found a declaration in \p OldDC as a previous decl, perhaps through a 14187 /// using-declaration). 14188 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 14189 DeclContext *NewDC) { 14190 OldDC = OldDC->getRedeclContext(); 14191 NewDC = NewDC->getRedeclContext(); 14192 14193 if (OldDC->Equals(NewDC)) 14194 return true; 14195 14196 // In MSVC mode, we allow a redeclaration if the contexts are related (either 14197 // encloses the other). 14198 if (S.getLangOpts().MSVCCompat && 14199 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 14200 return true; 14201 14202 return false; 14203 } 14204 14205 /// This is invoked when we see 'struct foo' or 'struct {'. In the 14206 /// former case, Name will be non-null. In the later case, Name will be null. 14207 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 14208 /// reference/declaration/definition of a tag. 14209 /// 14210 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 14211 /// trailing-type-specifier) other than one in an alias-declaration. 14212 /// 14213 /// \param SkipBody If non-null, will be set to indicate if the caller should 14214 /// skip the definition of this tag and treat it as if it were a declaration. 14215 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 14216 SourceLocation KWLoc, CXXScopeSpec &SS, 14217 IdentifierInfo *Name, SourceLocation NameLoc, 14218 const ParsedAttributesView &Attrs, AccessSpecifier AS, 14219 SourceLocation ModulePrivateLoc, 14220 MultiTemplateParamsArg TemplateParameterLists, 14221 bool &OwnedDecl, bool &IsDependent, 14222 SourceLocation ScopedEnumKWLoc, 14223 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 14224 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 14225 SkipBodyInfo *SkipBody) { 14226 // If this is not a definition, it must have a name. 14227 IdentifierInfo *OrigName = Name; 14228 assert((Name != nullptr || TUK == TUK_Definition) && 14229 "Nameless record must be a definition!"); 14230 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 14231 14232 OwnedDecl = false; 14233 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14234 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 14235 14236 // FIXME: Check member specializations more carefully. 14237 bool isMemberSpecialization = false; 14238 bool Invalid = false; 14239 14240 // We only need to do this matching if we have template parameters 14241 // or a scope specifier, which also conveniently avoids this work 14242 // for non-C++ cases. 14243 if (TemplateParameterLists.size() > 0 || 14244 (SS.isNotEmpty() && TUK != TUK_Reference)) { 14245 if (TemplateParameterList *TemplateParams = 14246 MatchTemplateParametersToScopeSpecifier( 14247 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 14248 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 14249 if (Kind == TTK_Enum) { 14250 Diag(KWLoc, diag::err_enum_template); 14251 return nullptr; 14252 } 14253 14254 if (TemplateParams->size() > 0) { 14255 // This is a declaration or definition of a class template (which may 14256 // be a member of another template). 14257 14258 if (Invalid) 14259 return nullptr; 14260 14261 OwnedDecl = false; 14262 DeclResult Result = CheckClassTemplate( 14263 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 14264 AS, ModulePrivateLoc, 14265 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 14266 TemplateParameterLists.data(), SkipBody); 14267 return Result.get(); 14268 } else { 14269 // The "template<>" header is extraneous. 14270 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14271 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14272 isMemberSpecialization = true; 14273 } 14274 } 14275 } 14276 14277 // Figure out the underlying type if this a enum declaration. We need to do 14278 // this early, because it's needed to detect if this is an incompatible 14279 // redeclaration. 14280 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 14281 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 14282 14283 if (Kind == TTK_Enum) { 14284 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 14285 // No underlying type explicitly specified, or we failed to parse the 14286 // type, default to int. 14287 EnumUnderlying = Context.IntTy.getTypePtr(); 14288 } else if (UnderlyingType.get()) { 14289 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 14290 // integral type; any cv-qualification is ignored. 14291 TypeSourceInfo *TI = nullptr; 14292 GetTypeFromParser(UnderlyingType.get(), &TI); 14293 EnumUnderlying = TI; 14294 14295 if (CheckEnumUnderlyingType(TI)) 14296 // Recover by falling back to int. 14297 EnumUnderlying = Context.IntTy.getTypePtr(); 14298 14299 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 14300 UPPC_FixedUnderlyingType)) 14301 EnumUnderlying = Context.IntTy.getTypePtr(); 14302 14303 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14304 // For MSVC ABI compatibility, unfixed enums must use an underlying type 14305 // of 'int'. However, if this is an unfixed forward declaration, don't set 14306 // the underlying type unless the user enables -fms-compatibility. This 14307 // makes unfixed forward declared enums incomplete and is more conforming. 14308 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 14309 EnumUnderlying = Context.IntTy.getTypePtr(); 14310 } 14311 } 14312 14313 DeclContext *SearchDC = CurContext; 14314 DeclContext *DC = CurContext; 14315 bool isStdBadAlloc = false; 14316 bool isStdAlignValT = false; 14317 14318 RedeclarationKind Redecl = forRedeclarationInCurContext(); 14319 if (TUK == TUK_Friend || TUK == TUK_Reference) 14320 Redecl = NotForRedeclaration; 14321 14322 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 14323 /// implemented asks for structural equivalence checking, the returned decl 14324 /// here is passed back to the parser, allowing the tag body to be parsed. 14325 auto createTagFromNewDecl = [&]() -> TagDecl * { 14326 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 14327 // If there is an identifier, use the location of the identifier as the 14328 // location of the decl, otherwise use the location of the struct/union 14329 // keyword. 14330 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14331 TagDecl *New = nullptr; 14332 14333 if (Kind == TTK_Enum) { 14334 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 14335 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 14336 // If this is an undefined enum, bail. 14337 if (TUK != TUK_Definition && !Invalid) 14338 return nullptr; 14339 if (EnumUnderlying) { 14340 EnumDecl *ED = cast<EnumDecl>(New); 14341 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 14342 ED->setIntegerTypeSourceInfo(TI); 14343 else 14344 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 14345 ED->setPromotionType(ED->getIntegerType()); 14346 } 14347 } else { // struct/union 14348 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14349 nullptr); 14350 } 14351 14352 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14353 // Add alignment attributes if necessary; these attributes are checked 14354 // when the ASTContext lays out the structure. 14355 // 14356 // It is important for implementing the correct semantics that this 14357 // happen here (in ActOnTag). The #pragma pack stack is 14358 // maintained as a result of parser callbacks which can occur at 14359 // many points during the parsing of a struct declaration (because 14360 // the #pragma tokens are effectively skipped over during the 14361 // parsing of the struct). 14362 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 14363 AddAlignmentAttributesForRecord(RD); 14364 AddMsStructLayoutForRecord(RD); 14365 } 14366 } 14367 New->setLexicalDeclContext(CurContext); 14368 return New; 14369 }; 14370 14371 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 14372 if (Name && SS.isNotEmpty()) { 14373 // We have a nested-name tag ('struct foo::bar'). 14374 14375 // Check for invalid 'foo::'. 14376 if (SS.isInvalid()) { 14377 Name = nullptr; 14378 goto CreateNewDecl; 14379 } 14380 14381 // If this is a friend or a reference to a class in a dependent 14382 // context, don't try to make a decl for it. 14383 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14384 DC = computeDeclContext(SS, false); 14385 if (!DC) { 14386 IsDependent = true; 14387 return nullptr; 14388 } 14389 } else { 14390 DC = computeDeclContext(SS, true); 14391 if (!DC) { 14392 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 14393 << SS.getRange(); 14394 return nullptr; 14395 } 14396 } 14397 14398 if (RequireCompleteDeclContext(SS, DC)) 14399 return nullptr; 14400 14401 SearchDC = DC; 14402 // Look-up name inside 'foo::'. 14403 LookupQualifiedName(Previous, DC); 14404 14405 if (Previous.isAmbiguous()) 14406 return nullptr; 14407 14408 if (Previous.empty()) { 14409 // Name lookup did not find anything. However, if the 14410 // nested-name-specifier refers to the current instantiation, 14411 // and that current instantiation has any dependent base 14412 // classes, we might find something at instantiation time: treat 14413 // this as a dependent elaborated-type-specifier. 14414 // But this only makes any sense for reference-like lookups. 14415 if (Previous.wasNotFoundInCurrentInstantiation() && 14416 (TUK == TUK_Reference || TUK == TUK_Friend)) { 14417 IsDependent = true; 14418 return nullptr; 14419 } 14420 14421 // A tag 'foo::bar' must already exist. 14422 Diag(NameLoc, diag::err_not_tag_in_scope) 14423 << Kind << Name << DC << SS.getRange(); 14424 Name = nullptr; 14425 Invalid = true; 14426 goto CreateNewDecl; 14427 } 14428 } else if (Name) { 14429 // C++14 [class.mem]p14: 14430 // If T is the name of a class, then each of the following shall have a 14431 // name different from T: 14432 // -- every member of class T that is itself a type 14433 if (TUK != TUK_Reference && TUK != TUK_Friend && 14434 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 14435 return nullptr; 14436 14437 // If this is a named struct, check to see if there was a previous forward 14438 // declaration or definition. 14439 // FIXME: We're looking into outer scopes here, even when we 14440 // shouldn't be. Doing so can result in ambiguities that we 14441 // shouldn't be diagnosing. 14442 LookupName(Previous, S); 14443 14444 // When declaring or defining a tag, ignore ambiguities introduced 14445 // by types using'ed into this scope. 14446 if (Previous.isAmbiguous() && 14447 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 14448 LookupResult::Filter F = Previous.makeFilter(); 14449 while (F.hasNext()) { 14450 NamedDecl *ND = F.next(); 14451 if (!ND->getDeclContext()->getRedeclContext()->Equals( 14452 SearchDC->getRedeclContext())) 14453 F.erase(); 14454 } 14455 F.done(); 14456 } 14457 14458 // C++11 [namespace.memdef]p3: 14459 // If the name in a friend declaration is neither qualified nor 14460 // a template-id and the declaration is a function or an 14461 // elaborated-type-specifier, the lookup to determine whether 14462 // the entity has been previously declared shall not consider 14463 // any scopes outside the innermost enclosing namespace. 14464 // 14465 // MSVC doesn't implement the above rule for types, so a friend tag 14466 // declaration may be a redeclaration of a type declared in an enclosing 14467 // scope. They do implement this rule for friend functions. 14468 // 14469 // Does it matter that this should be by scope instead of by 14470 // semantic context? 14471 if (!Previous.empty() && TUK == TUK_Friend) { 14472 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 14473 LookupResult::Filter F = Previous.makeFilter(); 14474 bool FriendSawTagOutsideEnclosingNamespace = false; 14475 while (F.hasNext()) { 14476 NamedDecl *ND = F.next(); 14477 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14478 if (DC->isFileContext() && 14479 !EnclosingNS->Encloses(ND->getDeclContext())) { 14480 if (getLangOpts().MSVCCompat) 14481 FriendSawTagOutsideEnclosingNamespace = true; 14482 else 14483 F.erase(); 14484 } 14485 } 14486 F.done(); 14487 14488 // Diagnose this MSVC extension in the easy case where lookup would have 14489 // unambiguously found something outside the enclosing namespace. 14490 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 14491 NamedDecl *ND = Previous.getFoundDecl(); 14492 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 14493 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 14494 } 14495 } 14496 14497 // Note: there used to be some attempt at recovery here. 14498 if (Previous.isAmbiguous()) 14499 return nullptr; 14500 14501 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 14502 // FIXME: This makes sure that we ignore the contexts associated 14503 // with C structs, unions, and enums when looking for a matching 14504 // tag declaration or definition. See the similar lookup tweak 14505 // in Sema::LookupName; is there a better way to deal with this? 14506 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 14507 SearchDC = SearchDC->getParent(); 14508 } 14509 } 14510 14511 if (Previous.isSingleResult() && 14512 Previous.getFoundDecl()->isTemplateParameter()) { 14513 // Maybe we will complain about the shadowed template parameter. 14514 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 14515 // Just pretend that we didn't see the previous declaration. 14516 Previous.clear(); 14517 } 14518 14519 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 14520 DC->Equals(getStdNamespace())) { 14521 if (Name->isStr("bad_alloc")) { 14522 // This is a declaration of or a reference to "std::bad_alloc". 14523 isStdBadAlloc = true; 14524 14525 // If std::bad_alloc has been implicitly declared (but made invisible to 14526 // name lookup), fill in this implicit declaration as the previous 14527 // declaration, so that the declarations get chained appropriately. 14528 if (Previous.empty() && StdBadAlloc) 14529 Previous.addDecl(getStdBadAlloc()); 14530 } else if (Name->isStr("align_val_t")) { 14531 isStdAlignValT = true; 14532 if (Previous.empty() && StdAlignValT) 14533 Previous.addDecl(getStdAlignValT()); 14534 } 14535 } 14536 14537 // If we didn't find a previous declaration, and this is a reference 14538 // (or friend reference), move to the correct scope. In C++, we 14539 // also need to do a redeclaration lookup there, just in case 14540 // there's a shadow friend decl. 14541 if (Name && Previous.empty() && 14542 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 14543 if (Invalid) goto CreateNewDecl; 14544 assert(SS.isEmpty()); 14545 14546 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 14547 // C++ [basic.scope.pdecl]p5: 14548 // -- for an elaborated-type-specifier of the form 14549 // 14550 // class-key identifier 14551 // 14552 // if the elaborated-type-specifier is used in the 14553 // decl-specifier-seq or parameter-declaration-clause of a 14554 // function defined in namespace scope, the identifier is 14555 // declared as a class-name in the namespace that contains 14556 // the declaration; otherwise, except as a friend 14557 // declaration, the identifier is declared in the smallest 14558 // non-class, non-function-prototype scope that contains the 14559 // declaration. 14560 // 14561 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 14562 // C structs and unions. 14563 // 14564 // It is an error in C++ to declare (rather than define) an enum 14565 // type, including via an elaborated type specifier. We'll 14566 // diagnose that later; for now, declare the enum in the same 14567 // scope as we would have picked for any other tag type. 14568 // 14569 // GNU C also supports this behavior as part of its incomplete 14570 // enum types extension, while GNU C++ does not. 14571 // 14572 // Find the context where we'll be declaring the tag. 14573 // FIXME: We would like to maintain the current DeclContext as the 14574 // lexical context, 14575 SearchDC = getTagInjectionContext(SearchDC); 14576 14577 // Find the scope where we'll be declaring the tag. 14578 S = getTagInjectionScope(S, getLangOpts()); 14579 } else { 14580 assert(TUK == TUK_Friend); 14581 // C++ [namespace.memdef]p3: 14582 // If a friend declaration in a non-local class first declares a 14583 // class or function, the friend class or function is a member of 14584 // the innermost enclosing namespace. 14585 SearchDC = SearchDC->getEnclosingNamespaceContext(); 14586 } 14587 14588 // In C++, we need to do a redeclaration lookup to properly 14589 // diagnose some problems. 14590 // FIXME: redeclaration lookup is also used (with and without C++) to find a 14591 // hidden declaration so that we don't get ambiguity errors when using a 14592 // type declared by an elaborated-type-specifier. In C that is not correct 14593 // and we should instead merge compatible types found by lookup. 14594 if (getLangOpts().CPlusPlus) { 14595 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 14596 LookupQualifiedName(Previous, SearchDC); 14597 } else { 14598 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 14599 LookupName(Previous, S); 14600 } 14601 } 14602 14603 // If we have a known previous declaration to use, then use it. 14604 if (Previous.empty() && SkipBody && SkipBody->Previous) 14605 Previous.addDecl(SkipBody->Previous); 14606 14607 if (!Previous.empty()) { 14608 NamedDecl *PrevDecl = Previous.getFoundDecl(); 14609 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 14610 14611 // It's okay to have a tag decl in the same scope as a typedef 14612 // which hides a tag decl in the same scope. Finding this 14613 // insanity with a redeclaration lookup can only actually happen 14614 // in C++. 14615 // 14616 // This is also okay for elaborated-type-specifiers, which is 14617 // technically forbidden by the current standard but which is 14618 // okay according to the likely resolution of an open issue; 14619 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 14620 if (getLangOpts().CPlusPlus) { 14621 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14622 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 14623 TagDecl *Tag = TT->getDecl(); 14624 if (Tag->getDeclName() == Name && 14625 Tag->getDeclContext()->getRedeclContext() 14626 ->Equals(TD->getDeclContext()->getRedeclContext())) { 14627 PrevDecl = Tag; 14628 Previous.clear(); 14629 Previous.addDecl(Tag); 14630 Previous.resolveKind(); 14631 } 14632 } 14633 } 14634 } 14635 14636 // If this is a redeclaration of a using shadow declaration, it must 14637 // declare a tag in the same context. In MSVC mode, we allow a 14638 // redefinition if either context is within the other. 14639 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 14640 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 14641 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 14642 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 14643 !(OldTag && isAcceptableTagRedeclContext( 14644 *this, OldTag->getDeclContext(), SearchDC))) { 14645 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 14646 Diag(Shadow->getTargetDecl()->getLocation(), 14647 diag::note_using_decl_target); 14648 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 14649 << 0; 14650 // Recover by ignoring the old declaration. 14651 Previous.clear(); 14652 goto CreateNewDecl; 14653 } 14654 } 14655 14656 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 14657 // If this is a use of a previous tag, or if the tag is already declared 14658 // in the same scope (so that the definition/declaration completes or 14659 // rementions the tag), reuse the decl. 14660 if (TUK == TUK_Reference || TUK == TUK_Friend || 14661 isDeclInScope(DirectPrevDecl, SearchDC, S, 14662 SS.isNotEmpty() || isMemberSpecialization)) { 14663 // Make sure that this wasn't declared as an enum and now used as a 14664 // struct or something similar. 14665 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 14666 TUK == TUK_Definition, KWLoc, 14667 Name)) { 14668 bool SafeToContinue 14669 = (PrevTagDecl->getTagKind() != TTK_Enum && 14670 Kind != TTK_Enum); 14671 if (SafeToContinue) 14672 Diag(KWLoc, diag::err_use_with_wrong_tag) 14673 << Name 14674 << FixItHint::CreateReplacement(SourceRange(KWLoc), 14675 PrevTagDecl->getKindName()); 14676 else 14677 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 14678 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 14679 14680 if (SafeToContinue) 14681 Kind = PrevTagDecl->getTagKind(); 14682 else { 14683 // Recover by making this an anonymous redefinition. 14684 Name = nullptr; 14685 Previous.clear(); 14686 Invalid = true; 14687 } 14688 } 14689 14690 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 14691 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 14692 14693 // If this is an elaborated-type-specifier for a scoped enumeration, 14694 // the 'class' keyword is not necessary and not permitted. 14695 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14696 if (ScopedEnum) 14697 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 14698 << PrevEnum->isScoped() 14699 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 14700 return PrevTagDecl; 14701 } 14702 14703 QualType EnumUnderlyingTy; 14704 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14705 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 14706 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 14707 EnumUnderlyingTy = QualType(T, 0); 14708 14709 // All conflicts with previous declarations are recovered by 14710 // returning the previous declaration, unless this is a definition, 14711 // in which case we want the caller to bail out. 14712 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 14713 ScopedEnum, EnumUnderlyingTy, 14714 IsFixed, PrevEnum)) 14715 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 14716 } 14717 14718 // C++11 [class.mem]p1: 14719 // A member shall not be declared twice in the member-specification, 14720 // except that a nested class or member class template can be declared 14721 // and then later defined. 14722 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 14723 S->isDeclScope(PrevDecl)) { 14724 Diag(NameLoc, diag::ext_member_redeclared); 14725 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 14726 } 14727 14728 if (!Invalid) { 14729 // If this is a use, just return the declaration we found, unless 14730 // we have attributes. 14731 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14732 if (!Attrs.empty()) { 14733 // FIXME: Diagnose these attributes. For now, we create a new 14734 // declaration to hold them. 14735 } else if (TUK == TUK_Reference && 14736 (PrevTagDecl->getFriendObjectKind() == 14737 Decl::FOK_Undeclared || 14738 PrevDecl->getOwningModule() != getCurrentModule()) && 14739 SS.isEmpty()) { 14740 // This declaration is a reference to an existing entity, but 14741 // has different visibility from that entity: it either makes 14742 // a friend visible or it makes a type visible in a new module. 14743 // In either case, create a new declaration. We only do this if 14744 // the declaration would have meant the same thing if no prior 14745 // declaration were found, that is, if it was found in the same 14746 // scope where we would have injected a declaration. 14747 if (!getTagInjectionContext(CurContext)->getRedeclContext() 14748 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 14749 return PrevTagDecl; 14750 // This is in the injected scope, create a new declaration in 14751 // that scope. 14752 S = getTagInjectionScope(S, getLangOpts()); 14753 } else { 14754 return PrevTagDecl; 14755 } 14756 } 14757 14758 // Diagnose attempts to redefine a tag. 14759 if (TUK == TUK_Definition) { 14760 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 14761 // If we're defining a specialization and the previous definition 14762 // is from an implicit instantiation, don't emit an error 14763 // here; we'll catch this in the general case below. 14764 bool IsExplicitSpecializationAfterInstantiation = false; 14765 if (isMemberSpecialization) { 14766 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 14767 IsExplicitSpecializationAfterInstantiation = 14768 RD->getTemplateSpecializationKind() != 14769 TSK_ExplicitSpecialization; 14770 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 14771 IsExplicitSpecializationAfterInstantiation = 14772 ED->getTemplateSpecializationKind() != 14773 TSK_ExplicitSpecialization; 14774 } 14775 14776 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 14777 // not keep more that one definition around (merge them). However, 14778 // ensure the decl passes the structural compatibility check in 14779 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 14780 NamedDecl *Hidden = nullptr; 14781 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 14782 // There is a definition of this tag, but it is not visible. We 14783 // explicitly make use of C++'s one definition rule here, and 14784 // assume that this definition is identical to the hidden one 14785 // we already have. Make the existing definition visible and 14786 // use it in place of this one. 14787 if (!getLangOpts().CPlusPlus) { 14788 // Postpone making the old definition visible until after we 14789 // complete parsing the new one and do the structural 14790 // comparison. 14791 SkipBody->CheckSameAsPrevious = true; 14792 SkipBody->New = createTagFromNewDecl(); 14793 SkipBody->Previous = Def; 14794 return Def; 14795 } else { 14796 SkipBody->ShouldSkip = true; 14797 SkipBody->Previous = Def; 14798 makeMergedDefinitionVisible(Hidden); 14799 // Carry on and handle it like a normal definition. We'll 14800 // skip starting the definitiion later. 14801 } 14802 } else if (!IsExplicitSpecializationAfterInstantiation) { 14803 // A redeclaration in function prototype scope in C isn't 14804 // visible elsewhere, so merely issue a warning. 14805 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 14806 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 14807 else 14808 Diag(NameLoc, diag::err_redefinition) << Name; 14809 notePreviousDefinition(Def, 14810 NameLoc.isValid() ? NameLoc : KWLoc); 14811 // If this is a redefinition, recover by making this 14812 // struct be anonymous, which will make any later 14813 // references get the previous definition. 14814 Name = nullptr; 14815 Previous.clear(); 14816 Invalid = true; 14817 } 14818 } else { 14819 // If the type is currently being defined, complain 14820 // about a nested redefinition. 14821 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 14822 if (TD->isBeingDefined()) { 14823 Diag(NameLoc, diag::err_nested_redefinition) << Name; 14824 Diag(PrevTagDecl->getLocation(), 14825 diag::note_previous_definition); 14826 Name = nullptr; 14827 Previous.clear(); 14828 Invalid = true; 14829 } 14830 } 14831 14832 // Okay, this is definition of a previously declared or referenced 14833 // tag. We're going to create a new Decl for it. 14834 } 14835 14836 // Okay, we're going to make a redeclaration. If this is some kind 14837 // of reference, make sure we build the redeclaration in the same DC 14838 // as the original, and ignore the current access specifier. 14839 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14840 SearchDC = PrevTagDecl->getDeclContext(); 14841 AS = AS_none; 14842 } 14843 } 14844 // If we get here we have (another) forward declaration or we 14845 // have a definition. Just create a new decl. 14846 14847 } else { 14848 // If we get here, this is a definition of a new tag type in a nested 14849 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 14850 // new decl/type. We set PrevDecl to NULL so that the entities 14851 // have distinct types. 14852 Previous.clear(); 14853 } 14854 // If we get here, we're going to create a new Decl. If PrevDecl 14855 // is non-NULL, it's a definition of the tag declared by 14856 // PrevDecl. If it's NULL, we have a new definition. 14857 14858 // Otherwise, PrevDecl is not a tag, but was found with tag 14859 // lookup. This is only actually possible in C++, where a few 14860 // things like templates still live in the tag namespace. 14861 } else { 14862 // Use a better diagnostic if an elaborated-type-specifier 14863 // found the wrong kind of type on the first 14864 // (non-redeclaration) lookup. 14865 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 14866 !Previous.isForRedeclaration()) { 14867 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14868 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 14869 << Kind; 14870 Diag(PrevDecl->getLocation(), diag::note_declared_at); 14871 Invalid = true; 14872 14873 // Otherwise, only diagnose if the declaration is in scope. 14874 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 14875 SS.isNotEmpty() || isMemberSpecialization)) { 14876 // do nothing 14877 14878 // Diagnose implicit declarations introduced by elaborated types. 14879 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 14880 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14881 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 14882 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14883 Invalid = true; 14884 14885 // Otherwise it's a declaration. Call out a particularly common 14886 // case here. 14887 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14888 unsigned Kind = 0; 14889 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 14890 Diag(NameLoc, diag::err_tag_definition_of_typedef) 14891 << Name << Kind << TND->getUnderlyingType(); 14892 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14893 Invalid = true; 14894 14895 // Otherwise, diagnose. 14896 } else { 14897 // The tag name clashes with something else in the target scope, 14898 // issue an error and recover by making this tag be anonymous. 14899 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 14900 notePreviousDefinition(PrevDecl, NameLoc); 14901 Name = nullptr; 14902 Invalid = true; 14903 } 14904 14905 // The existing declaration isn't relevant to us; we're in a 14906 // new scope, so clear out the previous declaration. 14907 Previous.clear(); 14908 } 14909 } 14910 14911 CreateNewDecl: 14912 14913 TagDecl *PrevDecl = nullptr; 14914 if (Previous.isSingleResult()) 14915 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 14916 14917 // If there is an identifier, use the location of the identifier as the 14918 // location of the decl, otherwise use the location of the struct/union 14919 // keyword. 14920 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14921 14922 // Otherwise, create a new declaration. If there is a previous 14923 // declaration of the same entity, the two will be linked via 14924 // PrevDecl. 14925 TagDecl *New; 14926 14927 if (Kind == TTK_Enum) { 14928 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14929 // enum X { A, B, C } D; D should chain to X. 14930 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 14931 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 14932 ScopedEnumUsesClassTag, IsFixed); 14933 14934 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 14935 StdAlignValT = cast<EnumDecl>(New); 14936 14937 // If this is an undefined enum, warn. 14938 if (TUK != TUK_Definition && !Invalid) { 14939 TagDecl *Def; 14940 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 14941 // C++0x: 7.2p2: opaque-enum-declaration. 14942 // Conflicts are diagnosed above. Do nothing. 14943 } 14944 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 14945 Diag(Loc, diag::ext_forward_ref_enum_def) 14946 << New; 14947 Diag(Def->getLocation(), diag::note_previous_definition); 14948 } else { 14949 unsigned DiagID = diag::ext_forward_ref_enum; 14950 if (getLangOpts().MSVCCompat) 14951 DiagID = diag::ext_ms_forward_ref_enum; 14952 else if (getLangOpts().CPlusPlus) 14953 DiagID = diag::err_forward_ref_enum; 14954 Diag(Loc, DiagID); 14955 } 14956 } 14957 14958 if (EnumUnderlying) { 14959 EnumDecl *ED = cast<EnumDecl>(New); 14960 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14961 ED->setIntegerTypeSourceInfo(TI); 14962 else 14963 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 14964 ED->setPromotionType(ED->getIntegerType()); 14965 assert(ED->isComplete() && "enum with type should be complete"); 14966 } 14967 } else { 14968 // struct/union/class 14969 14970 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14971 // struct X { int A; } D; D should chain to X. 14972 if (getLangOpts().CPlusPlus) { 14973 // FIXME: Look for a way to use RecordDecl for simple structs. 14974 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14975 cast_or_null<CXXRecordDecl>(PrevDecl)); 14976 14977 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 14978 StdBadAlloc = cast<CXXRecordDecl>(New); 14979 } else 14980 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14981 cast_or_null<RecordDecl>(PrevDecl)); 14982 } 14983 14984 // C++11 [dcl.type]p3: 14985 // A type-specifier-seq shall not define a class or enumeration [...]. 14986 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 14987 TUK == TUK_Definition) { 14988 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 14989 << Context.getTagDeclType(New); 14990 Invalid = true; 14991 } 14992 14993 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 14994 DC->getDeclKind() == Decl::Enum) { 14995 Diag(New->getLocation(), diag::err_type_defined_in_enum) 14996 << Context.getTagDeclType(New); 14997 Invalid = true; 14998 } 14999 15000 // Maybe add qualifier info. 15001 if (SS.isNotEmpty()) { 15002 if (SS.isSet()) { 15003 // If this is either a declaration or a definition, check the 15004 // nested-name-specifier against the current context. 15005 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 15006 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 15007 isMemberSpecialization)) 15008 Invalid = true; 15009 15010 New->setQualifierInfo(SS.getWithLocInContext(Context)); 15011 if (TemplateParameterLists.size() > 0) { 15012 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 15013 } 15014 } 15015 else 15016 Invalid = true; 15017 } 15018 15019 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15020 // Add alignment attributes if necessary; these attributes are checked when 15021 // the ASTContext lays out the structure. 15022 // 15023 // It is important for implementing the correct semantics that this 15024 // happen here (in ActOnTag). The #pragma pack stack is 15025 // maintained as a result of parser callbacks which can occur at 15026 // many points during the parsing of a struct declaration (because 15027 // the #pragma tokens are effectively skipped over during the 15028 // parsing of the struct). 15029 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15030 AddAlignmentAttributesForRecord(RD); 15031 AddMsStructLayoutForRecord(RD); 15032 } 15033 } 15034 15035 if (ModulePrivateLoc.isValid()) { 15036 if (isMemberSpecialization) 15037 Diag(New->getLocation(), diag::err_module_private_specialization) 15038 << 2 15039 << FixItHint::CreateRemoval(ModulePrivateLoc); 15040 // __module_private__ does not apply to local classes. However, we only 15041 // diagnose this as an error when the declaration specifiers are 15042 // freestanding. Here, we just ignore the __module_private__. 15043 else if (!SearchDC->isFunctionOrMethod()) 15044 New->setModulePrivate(); 15045 } 15046 15047 // If this is a specialization of a member class (of a class template), 15048 // check the specialization. 15049 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 15050 Invalid = true; 15051 15052 // If we're declaring or defining a tag in function prototype scope in C, 15053 // note that this type can only be used within the function and add it to 15054 // the list of decls to inject into the function definition scope. 15055 if ((Name || Kind == TTK_Enum) && 15056 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 15057 if (getLangOpts().CPlusPlus) { 15058 // C++ [dcl.fct]p6: 15059 // Types shall not be defined in return or parameter types. 15060 if (TUK == TUK_Definition && !IsTypeSpecifier) { 15061 Diag(Loc, diag::err_type_defined_in_param_type) 15062 << Name; 15063 Invalid = true; 15064 } 15065 } else if (!PrevDecl) { 15066 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 15067 } 15068 } 15069 15070 if (Invalid) 15071 New->setInvalidDecl(); 15072 15073 // Set the lexical context. If the tag has a C++ scope specifier, the 15074 // lexical context will be different from the semantic context. 15075 New->setLexicalDeclContext(CurContext); 15076 15077 // Mark this as a friend decl if applicable. 15078 // In Microsoft mode, a friend declaration also acts as a forward 15079 // declaration so we always pass true to setObjectOfFriendDecl to make 15080 // the tag name visible. 15081 if (TUK == TUK_Friend) 15082 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 15083 15084 // Set the access specifier. 15085 if (!Invalid && SearchDC->isRecord()) 15086 SetMemberAccessSpecifier(New, PrevDecl, AS); 15087 15088 if (PrevDecl) 15089 CheckRedeclarationModuleOwnership(New, PrevDecl); 15090 15091 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 15092 New->startDefinition(); 15093 15094 ProcessDeclAttributeList(S, New, Attrs); 15095 AddPragmaAttributes(S, New); 15096 15097 // If this has an identifier, add it to the scope stack. 15098 if (TUK == TUK_Friend) { 15099 // We might be replacing an existing declaration in the lookup tables; 15100 // if so, borrow its access specifier. 15101 if (PrevDecl) 15102 New->setAccess(PrevDecl->getAccess()); 15103 15104 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 15105 DC->makeDeclVisibleInContext(New); 15106 if (Name) // can be null along some error paths 15107 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 15108 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 15109 } else if (Name) { 15110 S = getNonFieldDeclScope(S); 15111 PushOnScopeChains(New, S, true); 15112 } else { 15113 CurContext->addDecl(New); 15114 } 15115 15116 // If this is the C FILE type, notify the AST context. 15117 if (IdentifierInfo *II = New->getIdentifier()) 15118 if (!New->isInvalidDecl() && 15119 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 15120 II->isStr("FILE")) 15121 Context.setFILEDecl(New); 15122 15123 if (PrevDecl) 15124 mergeDeclAttributes(New, PrevDecl); 15125 15126 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 15127 inferGslOwnerPointerAttribute(CXXRD); 15128 15129 // If there's a #pragma GCC visibility in scope, set the visibility of this 15130 // record. 15131 AddPushedVisibilityAttribute(New); 15132 15133 if (isMemberSpecialization && !New->isInvalidDecl()) 15134 CompleteMemberSpecialization(New, Previous); 15135 15136 OwnedDecl = true; 15137 // In C++, don't return an invalid declaration. We can't recover well from 15138 // the cases where we make the type anonymous. 15139 if (Invalid && getLangOpts().CPlusPlus) { 15140 if (New->isBeingDefined()) 15141 if (auto RD = dyn_cast<RecordDecl>(New)) 15142 RD->completeDefinition(); 15143 return nullptr; 15144 } else if (SkipBody && SkipBody->ShouldSkip) { 15145 return SkipBody->Previous; 15146 } else { 15147 return New; 15148 } 15149 } 15150 15151 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 15152 AdjustDeclIfTemplate(TagD); 15153 TagDecl *Tag = cast<TagDecl>(TagD); 15154 15155 // Enter the tag context. 15156 PushDeclContext(S, Tag); 15157 15158 ActOnDocumentableDecl(TagD); 15159 15160 // If there's a #pragma GCC visibility in scope, set the visibility of this 15161 // record. 15162 AddPushedVisibilityAttribute(Tag); 15163 } 15164 15165 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 15166 SkipBodyInfo &SkipBody) { 15167 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 15168 return false; 15169 15170 // Make the previous decl visible. 15171 makeMergedDefinitionVisible(SkipBody.Previous); 15172 return true; 15173 } 15174 15175 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 15176 assert(isa<ObjCContainerDecl>(IDecl) && 15177 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 15178 DeclContext *OCD = cast<DeclContext>(IDecl); 15179 assert(getContainingDC(OCD) == CurContext && 15180 "The next DeclContext should be lexically contained in the current one."); 15181 CurContext = OCD; 15182 return IDecl; 15183 } 15184 15185 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 15186 SourceLocation FinalLoc, 15187 bool IsFinalSpelledSealed, 15188 SourceLocation LBraceLoc) { 15189 AdjustDeclIfTemplate(TagD); 15190 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 15191 15192 FieldCollector->StartClass(); 15193 15194 if (!Record->getIdentifier()) 15195 return; 15196 15197 if (FinalLoc.isValid()) 15198 Record->addAttr(new (Context) 15199 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 15200 15201 // C++ [class]p2: 15202 // [...] The class-name is also inserted into the scope of the 15203 // class itself; this is known as the injected-class-name. For 15204 // purposes of access checking, the injected-class-name is treated 15205 // as if it were a public member name. 15206 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 15207 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 15208 Record->getLocation(), Record->getIdentifier(), 15209 /*PrevDecl=*/nullptr, 15210 /*DelayTypeCreation=*/true); 15211 Context.getTypeDeclType(InjectedClassName, Record); 15212 InjectedClassName->setImplicit(); 15213 InjectedClassName->setAccess(AS_public); 15214 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 15215 InjectedClassName->setDescribedClassTemplate(Template); 15216 PushOnScopeChains(InjectedClassName, S); 15217 assert(InjectedClassName->isInjectedClassName() && 15218 "Broken injected-class-name"); 15219 } 15220 15221 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 15222 SourceRange BraceRange) { 15223 AdjustDeclIfTemplate(TagD); 15224 TagDecl *Tag = cast<TagDecl>(TagD); 15225 Tag->setBraceRange(BraceRange); 15226 15227 // Make sure we "complete" the definition even it is invalid. 15228 if (Tag->isBeingDefined()) { 15229 assert(Tag->isInvalidDecl() && "We should already have completed it"); 15230 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15231 RD->completeDefinition(); 15232 } 15233 15234 if (isa<CXXRecordDecl>(Tag)) { 15235 FieldCollector->FinishClass(); 15236 } 15237 15238 // Exit this scope of this tag's definition. 15239 PopDeclContext(); 15240 15241 if (getCurLexicalContext()->isObjCContainer() && 15242 Tag->getDeclContext()->isFileContext()) 15243 Tag->setTopLevelDeclInObjCContainer(); 15244 15245 // Notify the consumer that we've defined a tag. 15246 if (!Tag->isInvalidDecl()) 15247 Consumer.HandleTagDeclDefinition(Tag); 15248 } 15249 15250 void Sema::ActOnObjCContainerFinishDefinition() { 15251 // Exit this scope of this interface definition. 15252 PopDeclContext(); 15253 } 15254 15255 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 15256 assert(DC == CurContext && "Mismatch of container contexts"); 15257 OriginalLexicalContext = DC; 15258 ActOnObjCContainerFinishDefinition(); 15259 } 15260 15261 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 15262 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 15263 OriginalLexicalContext = nullptr; 15264 } 15265 15266 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 15267 AdjustDeclIfTemplate(TagD); 15268 TagDecl *Tag = cast<TagDecl>(TagD); 15269 Tag->setInvalidDecl(); 15270 15271 // Make sure we "complete" the definition even it is invalid. 15272 if (Tag->isBeingDefined()) { 15273 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15274 RD->completeDefinition(); 15275 } 15276 15277 // We're undoing ActOnTagStartDefinition here, not 15278 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 15279 // the FieldCollector. 15280 15281 PopDeclContext(); 15282 } 15283 15284 // Note that FieldName may be null for anonymous bitfields. 15285 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 15286 IdentifierInfo *FieldName, 15287 QualType FieldTy, bool IsMsStruct, 15288 Expr *BitWidth, bool *ZeroWidth) { 15289 // Default to true; that shouldn't confuse checks for emptiness 15290 if (ZeroWidth) 15291 *ZeroWidth = true; 15292 15293 // C99 6.7.2.1p4 - verify the field type. 15294 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 15295 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 15296 // Handle incomplete types with specific error. 15297 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 15298 return ExprError(); 15299 if (FieldName) 15300 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 15301 << FieldName << FieldTy << BitWidth->getSourceRange(); 15302 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 15303 << FieldTy << BitWidth->getSourceRange(); 15304 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 15305 UPPC_BitFieldWidth)) 15306 return ExprError(); 15307 15308 // If the bit-width is type- or value-dependent, don't try to check 15309 // it now. 15310 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 15311 return BitWidth; 15312 15313 llvm::APSInt Value; 15314 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 15315 if (ICE.isInvalid()) 15316 return ICE; 15317 BitWidth = ICE.get(); 15318 15319 if (Value != 0 && ZeroWidth) 15320 *ZeroWidth = false; 15321 15322 // Zero-width bitfield is ok for anonymous field. 15323 if (Value == 0 && FieldName) 15324 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 15325 15326 if (Value.isSigned() && Value.isNegative()) { 15327 if (FieldName) 15328 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 15329 << FieldName << Value.toString(10); 15330 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 15331 << Value.toString(10); 15332 } 15333 15334 if (!FieldTy->isDependentType()) { 15335 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 15336 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 15337 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 15338 15339 // Over-wide bitfields are an error in C or when using the MSVC bitfield 15340 // ABI. 15341 bool CStdConstraintViolation = 15342 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 15343 bool MSBitfieldViolation = 15344 Value.ugt(TypeStorageSize) && 15345 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 15346 if (CStdConstraintViolation || MSBitfieldViolation) { 15347 unsigned DiagWidth = 15348 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 15349 if (FieldName) 15350 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 15351 << FieldName << (unsigned)Value.getZExtValue() 15352 << !CStdConstraintViolation << DiagWidth; 15353 15354 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 15355 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 15356 << DiagWidth; 15357 } 15358 15359 // Warn on types where the user might conceivably expect to get all 15360 // specified bits as value bits: that's all integral types other than 15361 // 'bool'. 15362 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 15363 if (FieldName) 15364 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 15365 << FieldName << (unsigned)Value.getZExtValue() 15366 << (unsigned)TypeWidth; 15367 else 15368 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 15369 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 15370 } 15371 } 15372 15373 return BitWidth; 15374 } 15375 15376 /// ActOnField - Each field of a C struct/union is passed into this in order 15377 /// to create a FieldDecl object for it. 15378 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 15379 Declarator &D, Expr *BitfieldWidth) { 15380 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 15381 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 15382 /*InitStyle=*/ICIS_NoInit, AS_public); 15383 return Res; 15384 } 15385 15386 /// HandleField - Analyze a field of a C struct or a C++ data member. 15387 /// 15388 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 15389 SourceLocation DeclStart, 15390 Declarator &D, Expr *BitWidth, 15391 InClassInitStyle InitStyle, 15392 AccessSpecifier AS) { 15393 if (D.isDecompositionDeclarator()) { 15394 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 15395 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 15396 << Decomp.getSourceRange(); 15397 return nullptr; 15398 } 15399 15400 IdentifierInfo *II = D.getIdentifier(); 15401 SourceLocation Loc = DeclStart; 15402 if (II) Loc = D.getIdentifierLoc(); 15403 15404 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15405 QualType T = TInfo->getType(); 15406 if (getLangOpts().CPlusPlus) { 15407 CheckExtraCXXDefaultArguments(D); 15408 15409 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15410 UPPC_DataMemberType)) { 15411 D.setInvalidType(); 15412 T = Context.IntTy; 15413 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15414 } 15415 } 15416 15417 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15418 15419 if (D.getDeclSpec().isInlineSpecified()) 15420 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15421 << getLangOpts().CPlusPlus17; 15422 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15423 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15424 diag::err_invalid_thread) 15425 << DeclSpec::getSpecifierName(TSCS); 15426 15427 // Check to see if this name was declared as a member previously 15428 NamedDecl *PrevDecl = nullptr; 15429 LookupResult Previous(*this, II, Loc, LookupMemberName, 15430 ForVisibleRedeclaration); 15431 LookupName(Previous, S); 15432 switch (Previous.getResultKind()) { 15433 case LookupResult::Found: 15434 case LookupResult::FoundUnresolvedValue: 15435 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15436 break; 15437 15438 case LookupResult::FoundOverloaded: 15439 PrevDecl = Previous.getRepresentativeDecl(); 15440 break; 15441 15442 case LookupResult::NotFound: 15443 case LookupResult::NotFoundInCurrentInstantiation: 15444 case LookupResult::Ambiguous: 15445 break; 15446 } 15447 Previous.suppressDiagnostics(); 15448 15449 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15450 // Maybe we will complain about the shadowed template parameter. 15451 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15452 // Just pretend that we didn't see the previous declaration. 15453 PrevDecl = nullptr; 15454 } 15455 15456 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15457 PrevDecl = nullptr; 15458 15459 bool Mutable 15460 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 15461 SourceLocation TSSL = D.getBeginLoc(); 15462 FieldDecl *NewFD 15463 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 15464 TSSL, AS, PrevDecl, &D); 15465 15466 if (NewFD->isInvalidDecl()) 15467 Record->setInvalidDecl(); 15468 15469 if (D.getDeclSpec().isModulePrivateSpecified()) 15470 NewFD->setModulePrivate(); 15471 15472 if (NewFD->isInvalidDecl() && PrevDecl) { 15473 // Don't introduce NewFD into scope; there's already something 15474 // with the same name in the same scope. 15475 } else if (II) { 15476 PushOnScopeChains(NewFD, S); 15477 } else 15478 Record->addDecl(NewFD); 15479 15480 return NewFD; 15481 } 15482 15483 /// Build a new FieldDecl and check its well-formedness. 15484 /// 15485 /// This routine builds a new FieldDecl given the fields name, type, 15486 /// record, etc. \p PrevDecl should refer to any previous declaration 15487 /// with the same name and in the same scope as the field to be 15488 /// created. 15489 /// 15490 /// \returns a new FieldDecl. 15491 /// 15492 /// \todo The Declarator argument is a hack. It will be removed once 15493 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 15494 TypeSourceInfo *TInfo, 15495 RecordDecl *Record, SourceLocation Loc, 15496 bool Mutable, Expr *BitWidth, 15497 InClassInitStyle InitStyle, 15498 SourceLocation TSSL, 15499 AccessSpecifier AS, NamedDecl *PrevDecl, 15500 Declarator *D) { 15501 IdentifierInfo *II = Name.getAsIdentifierInfo(); 15502 bool InvalidDecl = false; 15503 if (D) InvalidDecl = D->isInvalidType(); 15504 15505 // If we receive a broken type, recover by assuming 'int' and 15506 // marking this declaration as invalid. 15507 if (T.isNull()) { 15508 InvalidDecl = true; 15509 T = Context.IntTy; 15510 } 15511 15512 QualType EltTy = Context.getBaseElementType(T); 15513 if (!EltTy->isDependentType()) { 15514 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 15515 // Fields of incomplete type force their record to be invalid. 15516 Record->setInvalidDecl(); 15517 InvalidDecl = true; 15518 } else { 15519 NamedDecl *Def; 15520 EltTy->isIncompleteType(&Def); 15521 if (Def && Def->isInvalidDecl()) { 15522 Record->setInvalidDecl(); 15523 InvalidDecl = true; 15524 } 15525 } 15526 } 15527 15528 // TR 18037 does not allow fields to be declared with address space 15529 if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() || 15530 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 15531 Diag(Loc, diag::err_field_with_address_space); 15532 Record->setInvalidDecl(); 15533 InvalidDecl = true; 15534 } 15535 15536 if (LangOpts.OpenCL) { 15537 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 15538 // used as structure or union field: image, sampler, event or block types. 15539 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 15540 T->isBlockPointerType()) { 15541 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 15542 Record->setInvalidDecl(); 15543 InvalidDecl = true; 15544 } 15545 // OpenCL v1.2 s6.9.c: bitfields are not supported. 15546 if (BitWidth) { 15547 Diag(Loc, diag::err_opencl_bitfields); 15548 InvalidDecl = true; 15549 } 15550 } 15551 15552 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 15553 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 15554 T.hasQualifiers()) { 15555 InvalidDecl = true; 15556 Diag(Loc, diag::err_anon_bitfield_qualifiers); 15557 } 15558 15559 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15560 // than a variably modified type. 15561 if (!InvalidDecl && T->isVariablyModifiedType()) { 15562 bool SizeIsNegative; 15563 llvm::APSInt Oversized; 15564 15565 TypeSourceInfo *FixedTInfo = 15566 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 15567 SizeIsNegative, 15568 Oversized); 15569 if (FixedTInfo) { 15570 Diag(Loc, diag::warn_illegal_constant_array_size); 15571 TInfo = FixedTInfo; 15572 T = FixedTInfo->getType(); 15573 } else { 15574 if (SizeIsNegative) 15575 Diag(Loc, diag::err_typecheck_negative_array_size); 15576 else if (Oversized.getBoolValue()) 15577 Diag(Loc, diag::err_array_too_large) 15578 << Oversized.toString(10); 15579 else 15580 Diag(Loc, diag::err_typecheck_field_variable_size); 15581 InvalidDecl = true; 15582 } 15583 } 15584 15585 // Fields can not have abstract class types 15586 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 15587 diag::err_abstract_type_in_decl, 15588 AbstractFieldType)) 15589 InvalidDecl = true; 15590 15591 bool ZeroWidth = false; 15592 if (InvalidDecl) 15593 BitWidth = nullptr; 15594 // If this is declared as a bit-field, check the bit-field. 15595 if (BitWidth) { 15596 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 15597 &ZeroWidth).get(); 15598 if (!BitWidth) { 15599 InvalidDecl = true; 15600 BitWidth = nullptr; 15601 ZeroWidth = false; 15602 } 15603 } 15604 15605 // Check that 'mutable' is consistent with the type of the declaration. 15606 if (!InvalidDecl && Mutable) { 15607 unsigned DiagID = 0; 15608 if (T->isReferenceType()) 15609 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 15610 : diag::err_mutable_reference; 15611 else if (T.isConstQualified()) 15612 DiagID = diag::err_mutable_const; 15613 15614 if (DiagID) { 15615 SourceLocation ErrLoc = Loc; 15616 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 15617 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 15618 Diag(ErrLoc, DiagID); 15619 if (DiagID != diag::ext_mutable_reference) { 15620 Mutable = false; 15621 InvalidDecl = true; 15622 } 15623 } 15624 } 15625 15626 // C++11 [class.union]p8 (DR1460): 15627 // At most one variant member of a union may have a 15628 // brace-or-equal-initializer. 15629 if (InitStyle != ICIS_NoInit) 15630 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 15631 15632 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 15633 BitWidth, Mutable, InitStyle); 15634 if (InvalidDecl) 15635 NewFD->setInvalidDecl(); 15636 15637 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 15638 Diag(Loc, diag::err_duplicate_member) << II; 15639 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15640 NewFD->setInvalidDecl(); 15641 } 15642 15643 if (!InvalidDecl && getLangOpts().CPlusPlus) { 15644 if (Record->isUnion()) { 15645 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15646 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15647 if (RDecl->getDefinition()) { 15648 // C++ [class.union]p1: An object of a class with a non-trivial 15649 // constructor, a non-trivial copy constructor, a non-trivial 15650 // destructor, or a non-trivial copy assignment operator 15651 // cannot be a member of a union, nor can an array of such 15652 // objects. 15653 if (CheckNontrivialField(NewFD)) 15654 NewFD->setInvalidDecl(); 15655 } 15656 } 15657 15658 // C++ [class.union]p1: If a union contains a member of reference type, 15659 // the program is ill-formed, except when compiling with MSVC extensions 15660 // enabled. 15661 if (EltTy->isReferenceType()) { 15662 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 15663 diag::ext_union_member_of_reference_type : 15664 diag::err_union_member_of_reference_type) 15665 << NewFD->getDeclName() << EltTy; 15666 if (!getLangOpts().MicrosoftExt) 15667 NewFD->setInvalidDecl(); 15668 } 15669 } 15670 } 15671 15672 // FIXME: We need to pass in the attributes given an AST 15673 // representation, not a parser representation. 15674 if (D) { 15675 // FIXME: The current scope is almost... but not entirely... correct here. 15676 ProcessDeclAttributes(getCurScope(), NewFD, *D); 15677 15678 if (NewFD->hasAttrs()) 15679 CheckAlignasUnderalignment(NewFD); 15680 } 15681 15682 // In auto-retain/release, infer strong retension for fields of 15683 // retainable type. 15684 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 15685 NewFD->setInvalidDecl(); 15686 15687 if (T.isObjCGCWeak()) 15688 Diag(Loc, diag::warn_attribute_weak_on_field); 15689 15690 NewFD->setAccess(AS); 15691 return NewFD; 15692 } 15693 15694 bool Sema::CheckNontrivialField(FieldDecl *FD) { 15695 assert(FD); 15696 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 15697 15698 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 15699 return false; 15700 15701 QualType EltTy = Context.getBaseElementType(FD->getType()); 15702 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15703 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15704 if (RDecl->getDefinition()) { 15705 // We check for copy constructors before constructors 15706 // because otherwise we'll never get complaints about 15707 // copy constructors. 15708 15709 CXXSpecialMember member = CXXInvalid; 15710 // We're required to check for any non-trivial constructors. Since the 15711 // implicit default constructor is suppressed if there are any 15712 // user-declared constructors, we just need to check that there is a 15713 // trivial default constructor and a trivial copy constructor. (We don't 15714 // worry about move constructors here, since this is a C++98 check.) 15715 if (RDecl->hasNonTrivialCopyConstructor()) 15716 member = CXXCopyConstructor; 15717 else if (!RDecl->hasTrivialDefaultConstructor()) 15718 member = CXXDefaultConstructor; 15719 else if (RDecl->hasNonTrivialCopyAssignment()) 15720 member = CXXCopyAssignment; 15721 else if (RDecl->hasNonTrivialDestructor()) 15722 member = CXXDestructor; 15723 15724 if (member != CXXInvalid) { 15725 if (!getLangOpts().CPlusPlus11 && 15726 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 15727 // Objective-C++ ARC: it is an error to have a non-trivial field of 15728 // a union. However, system headers in Objective-C programs 15729 // occasionally have Objective-C lifetime objects within unions, 15730 // and rather than cause the program to fail, we make those 15731 // members unavailable. 15732 SourceLocation Loc = FD->getLocation(); 15733 if (getSourceManager().isInSystemHeader(Loc)) { 15734 if (!FD->hasAttr<UnavailableAttr>()) 15735 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15736 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 15737 return false; 15738 } 15739 } 15740 15741 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 15742 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 15743 diag::err_illegal_union_or_anon_struct_member) 15744 << FD->getParent()->isUnion() << FD->getDeclName() << member; 15745 DiagnoseNontrivial(RDecl, member); 15746 return !getLangOpts().CPlusPlus11; 15747 } 15748 } 15749 } 15750 15751 return false; 15752 } 15753 15754 /// TranslateIvarVisibility - Translate visibility from a token ID to an 15755 /// AST enum value. 15756 static ObjCIvarDecl::AccessControl 15757 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 15758 switch (ivarVisibility) { 15759 default: llvm_unreachable("Unknown visitibility kind"); 15760 case tok::objc_private: return ObjCIvarDecl::Private; 15761 case tok::objc_public: return ObjCIvarDecl::Public; 15762 case tok::objc_protected: return ObjCIvarDecl::Protected; 15763 case tok::objc_package: return ObjCIvarDecl::Package; 15764 } 15765 } 15766 15767 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 15768 /// in order to create an IvarDecl object for it. 15769 Decl *Sema::ActOnIvar(Scope *S, 15770 SourceLocation DeclStart, 15771 Declarator &D, Expr *BitfieldWidth, 15772 tok::ObjCKeywordKind Visibility) { 15773 15774 IdentifierInfo *II = D.getIdentifier(); 15775 Expr *BitWidth = (Expr*)BitfieldWidth; 15776 SourceLocation Loc = DeclStart; 15777 if (II) Loc = D.getIdentifierLoc(); 15778 15779 // FIXME: Unnamed fields can be handled in various different ways, for 15780 // example, unnamed unions inject all members into the struct namespace! 15781 15782 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15783 QualType T = TInfo->getType(); 15784 15785 if (BitWidth) { 15786 // 6.7.2.1p3, 6.7.2.1p4 15787 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 15788 if (!BitWidth) 15789 D.setInvalidType(); 15790 } else { 15791 // Not a bitfield. 15792 15793 // validate II. 15794 15795 } 15796 if (T->isReferenceType()) { 15797 Diag(Loc, diag::err_ivar_reference_type); 15798 D.setInvalidType(); 15799 } 15800 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15801 // than a variably modified type. 15802 else if (T->isVariablyModifiedType()) { 15803 Diag(Loc, diag::err_typecheck_ivar_variable_size); 15804 D.setInvalidType(); 15805 } 15806 15807 // Get the visibility (access control) for this ivar. 15808 ObjCIvarDecl::AccessControl ac = 15809 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 15810 : ObjCIvarDecl::None; 15811 // Must set ivar's DeclContext to its enclosing interface. 15812 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 15813 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 15814 return nullptr; 15815 ObjCContainerDecl *EnclosingContext; 15816 if (ObjCImplementationDecl *IMPDecl = 15817 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15818 if (LangOpts.ObjCRuntime.isFragile()) { 15819 // Case of ivar declared in an implementation. Context is that of its class. 15820 EnclosingContext = IMPDecl->getClassInterface(); 15821 assert(EnclosingContext && "Implementation has no class interface!"); 15822 } 15823 else 15824 EnclosingContext = EnclosingDecl; 15825 } else { 15826 if (ObjCCategoryDecl *CDecl = 15827 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15828 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 15829 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 15830 return nullptr; 15831 } 15832 } 15833 EnclosingContext = EnclosingDecl; 15834 } 15835 15836 // Construct the decl. 15837 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 15838 DeclStart, Loc, II, T, 15839 TInfo, ac, (Expr *)BitfieldWidth); 15840 15841 if (II) { 15842 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 15843 ForVisibleRedeclaration); 15844 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 15845 && !isa<TagDecl>(PrevDecl)) { 15846 Diag(Loc, diag::err_duplicate_member) << II; 15847 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15848 NewID->setInvalidDecl(); 15849 } 15850 } 15851 15852 // Process attributes attached to the ivar. 15853 ProcessDeclAttributes(S, NewID, D); 15854 15855 if (D.isInvalidType()) 15856 NewID->setInvalidDecl(); 15857 15858 // In ARC, infer 'retaining' for ivars of retainable type. 15859 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 15860 NewID->setInvalidDecl(); 15861 15862 if (D.getDeclSpec().isModulePrivateSpecified()) 15863 NewID->setModulePrivate(); 15864 15865 if (II) { 15866 // FIXME: When interfaces are DeclContexts, we'll need to add 15867 // these to the interface. 15868 S->AddDecl(NewID); 15869 IdResolver.AddDecl(NewID); 15870 } 15871 15872 if (LangOpts.ObjCRuntime.isNonFragile() && 15873 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 15874 Diag(Loc, diag::warn_ivars_in_interface); 15875 15876 return NewID; 15877 } 15878 15879 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 15880 /// class and class extensions. For every class \@interface and class 15881 /// extension \@interface, if the last ivar is a bitfield of any type, 15882 /// then add an implicit `char :0` ivar to the end of that interface. 15883 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 15884 SmallVectorImpl<Decl *> &AllIvarDecls) { 15885 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 15886 return; 15887 15888 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 15889 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 15890 15891 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 15892 return; 15893 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 15894 if (!ID) { 15895 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 15896 if (!CD->IsClassExtension()) 15897 return; 15898 } 15899 // No need to add this to end of @implementation. 15900 else 15901 return; 15902 } 15903 // All conditions are met. Add a new bitfield to the tail end of ivars. 15904 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 15905 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 15906 15907 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 15908 DeclLoc, DeclLoc, nullptr, 15909 Context.CharTy, 15910 Context.getTrivialTypeSourceInfo(Context.CharTy, 15911 DeclLoc), 15912 ObjCIvarDecl::Private, BW, 15913 true); 15914 AllIvarDecls.push_back(Ivar); 15915 } 15916 15917 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 15918 ArrayRef<Decl *> Fields, SourceLocation LBrac, 15919 SourceLocation RBrac, 15920 const ParsedAttributesView &Attrs) { 15921 assert(EnclosingDecl && "missing record or interface decl"); 15922 15923 // If this is an Objective-C @implementation or category and we have 15924 // new fields here we should reset the layout of the interface since 15925 // it will now change. 15926 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 15927 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 15928 switch (DC->getKind()) { 15929 default: break; 15930 case Decl::ObjCCategory: 15931 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 15932 break; 15933 case Decl::ObjCImplementation: 15934 Context. 15935 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 15936 break; 15937 } 15938 } 15939 15940 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 15941 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 15942 15943 // Start counting up the number of named members; make sure to include 15944 // members of anonymous structs and unions in the total. 15945 unsigned NumNamedMembers = 0; 15946 if (Record) { 15947 for (const auto *I : Record->decls()) { 15948 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 15949 if (IFD->getDeclName()) 15950 ++NumNamedMembers; 15951 } 15952 } 15953 15954 // Verify that all the fields are okay. 15955 SmallVector<FieldDecl*, 32> RecFields; 15956 15957 bool ObjCFieldLifetimeErrReported = false; 15958 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 15959 i != end; ++i) { 15960 FieldDecl *FD = cast<FieldDecl>(*i); 15961 15962 // Get the type for the field. 15963 const Type *FDTy = FD->getType().getTypePtr(); 15964 15965 if (!FD->isAnonymousStructOrUnion()) { 15966 // Remember all fields written by the user. 15967 RecFields.push_back(FD); 15968 } 15969 15970 // If the field is already invalid for some reason, don't emit more 15971 // diagnostics about it. 15972 if (FD->isInvalidDecl()) { 15973 EnclosingDecl->setInvalidDecl(); 15974 continue; 15975 } 15976 15977 // C99 6.7.2.1p2: 15978 // A structure or union shall not contain a member with 15979 // incomplete or function type (hence, a structure shall not 15980 // contain an instance of itself, but may contain a pointer to 15981 // an instance of itself), except that the last member of a 15982 // structure with more than one named member may have incomplete 15983 // array type; such a structure (and any union containing, 15984 // possibly recursively, a member that is such a structure) 15985 // shall not be a member of a structure or an element of an 15986 // array. 15987 bool IsLastField = (i + 1 == Fields.end()); 15988 if (FDTy->isFunctionType()) { 15989 // Field declared as a function. 15990 Diag(FD->getLocation(), diag::err_field_declared_as_function) 15991 << FD->getDeclName(); 15992 FD->setInvalidDecl(); 15993 EnclosingDecl->setInvalidDecl(); 15994 continue; 15995 } else if (FDTy->isIncompleteArrayType() && 15996 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 15997 if (Record) { 15998 // Flexible array member. 15999 // Microsoft and g++ is more permissive regarding flexible array. 16000 // It will accept flexible array in union and also 16001 // as the sole element of a struct/class. 16002 unsigned DiagID = 0; 16003 if (!Record->isUnion() && !IsLastField) { 16004 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 16005 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 16006 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 16007 FD->setInvalidDecl(); 16008 EnclosingDecl->setInvalidDecl(); 16009 continue; 16010 } else if (Record->isUnion()) 16011 DiagID = getLangOpts().MicrosoftExt 16012 ? diag::ext_flexible_array_union_ms 16013 : getLangOpts().CPlusPlus 16014 ? diag::ext_flexible_array_union_gnu 16015 : diag::err_flexible_array_union; 16016 else if (NumNamedMembers < 1) 16017 DiagID = getLangOpts().MicrosoftExt 16018 ? diag::ext_flexible_array_empty_aggregate_ms 16019 : getLangOpts().CPlusPlus 16020 ? diag::ext_flexible_array_empty_aggregate_gnu 16021 : diag::err_flexible_array_empty_aggregate; 16022 16023 if (DiagID) 16024 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 16025 << Record->getTagKind(); 16026 // While the layout of types that contain virtual bases is not specified 16027 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 16028 // virtual bases after the derived members. This would make a flexible 16029 // array member declared at the end of an object not adjacent to the end 16030 // of the type. 16031 if (CXXRecord && CXXRecord->getNumVBases() != 0) 16032 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 16033 << FD->getDeclName() << Record->getTagKind(); 16034 if (!getLangOpts().C99) 16035 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 16036 << FD->getDeclName() << Record->getTagKind(); 16037 16038 // If the element type has a non-trivial destructor, we would not 16039 // implicitly destroy the elements, so disallow it for now. 16040 // 16041 // FIXME: GCC allows this. We should probably either implicitly delete 16042 // the destructor of the containing class, or just allow this. 16043 QualType BaseElem = Context.getBaseElementType(FD->getType()); 16044 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 16045 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 16046 << FD->getDeclName() << FD->getType(); 16047 FD->setInvalidDecl(); 16048 EnclosingDecl->setInvalidDecl(); 16049 continue; 16050 } 16051 // Okay, we have a legal flexible array member at the end of the struct. 16052 Record->setHasFlexibleArrayMember(true); 16053 } else { 16054 // In ObjCContainerDecl ivars with incomplete array type are accepted, 16055 // unless they are followed by another ivar. That check is done 16056 // elsewhere, after synthesized ivars are known. 16057 } 16058 } else if (!FDTy->isDependentType() && 16059 RequireCompleteType(FD->getLocation(), FD->getType(), 16060 diag::err_field_incomplete)) { 16061 // Incomplete type 16062 FD->setInvalidDecl(); 16063 EnclosingDecl->setInvalidDecl(); 16064 continue; 16065 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 16066 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 16067 // A type which contains a flexible array member is considered to be a 16068 // flexible array member. 16069 Record->setHasFlexibleArrayMember(true); 16070 if (!Record->isUnion()) { 16071 // If this is a struct/class and this is not the last element, reject 16072 // it. Note that GCC supports variable sized arrays in the middle of 16073 // structures. 16074 if (!IsLastField) 16075 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 16076 << FD->getDeclName() << FD->getType(); 16077 else { 16078 // We support flexible arrays at the end of structs in 16079 // other structs as an extension. 16080 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 16081 << FD->getDeclName(); 16082 } 16083 } 16084 } 16085 if (isa<ObjCContainerDecl>(EnclosingDecl) && 16086 RequireNonAbstractType(FD->getLocation(), FD->getType(), 16087 diag::err_abstract_type_in_decl, 16088 AbstractIvarType)) { 16089 // Ivars can not have abstract class types 16090 FD->setInvalidDecl(); 16091 } 16092 if (Record && FDTTy->getDecl()->hasObjectMember()) 16093 Record->setHasObjectMember(true); 16094 if (Record && FDTTy->getDecl()->hasVolatileMember()) 16095 Record->setHasVolatileMember(true); 16096 if (Record && Record->isUnion() && 16097 FD->getType().isNonTrivialPrimitiveCType(Context)) 16098 Diag(FD->getLocation(), 16099 diag::err_nontrivial_primitive_type_in_union); 16100 } else if (FDTy->isObjCObjectType()) { 16101 /// A field cannot be an Objective-c object 16102 Diag(FD->getLocation(), diag::err_statically_allocated_object) 16103 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 16104 QualType T = Context.getObjCObjectPointerType(FD->getType()); 16105 FD->setType(T); 16106 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 16107 Record && !ObjCFieldLifetimeErrReported && Record->isUnion() && 16108 !getLangOpts().CPlusPlus) { 16109 // It's an error in ARC or Weak if a field has lifetime. 16110 // We don't want to report this in a system header, though, 16111 // so we just make the field unavailable. 16112 // FIXME: that's really not sufficient; we need to make the type 16113 // itself invalid to, say, initialize or copy. 16114 QualType T = FD->getType(); 16115 if (T.hasNonTrivialObjCLifetime()) { 16116 SourceLocation loc = FD->getLocation(); 16117 if (getSourceManager().isInSystemHeader(loc)) { 16118 if (!FD->hasAttr<UnavailableAttr>()) { 16119 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16120 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 16121 } 16122 } else { 16123 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 16124 << T->isBlockPointerType() << Record->getTagKind(); 16125 } 16126 ObjCFieldLifetimeErrReported = true; 16127 } 16128 } else if (getLangOpts().ObjC && 16129 getLangOpts().getGC() != LangOptions::NonGC && 16130 Record && !Record->hasObjectMember()) { 16131 if (FD->getType()->isObjCObjectPointerType() || 16132 FD->getType().isObjCGCStrong()) 16133 Record->setHasObjectMember(true); 16134 else if (Context.getAsArrayType(FD->getType())) { 16135 QualType BaseType = Context.getBaseElementType(FD->getType()); 16136 if (BaseType->isRecordType() && 16137 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 16138 Record->setHasObjectMember(true); 16139 else if (BaseType->isObjCObjectPointerType() || 16140 BaseType.isObjCGCStrong()) 16141 Record->setHasObjectMember(true); 16142 } 16143 } 16144 16145 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { 16146 QualType FT = FD->getType(); 16147 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) 16148 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 16149 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 16150 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) 16151 Record->setNonTrivialToPrimitiveCopy(true); 16152 if (FT.isDestructedType()) { 16153 Record->setNonTrivialToPrimitiveDestroy(true); 16154 Record->setParamDestroyedInCallee(true); 16155 } 16156 16157 if (const auto *RT = FT->getAs<RecordType>()) { 16158 if (RT->getDecl()->getArgPassingRestrictions() == 16159 RecordDecl::APK_CanNeverPassInRegs) 16160 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16161 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 16162 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16163 } 16164 16165 if (Record && FD->getType().isVolatileQualified()) 16166 Record->setHasVolatileMember(true); 16167 // Keep track of the number of named members. 16168 if (FD->getIdentifier()) 16169 ++NumNamedMembers; 16170 } 16171 16172 // Okay, we successfully defined 'Record'. 16173 if (Record) { 16174 bool Completed = false; 16175 if (CXXRecord) { 16176 if (!CXXRecord->isInvalidDecl()) { 16177 // Set access bits correctly on the directly-declared conversions. 16178 for (CXXRecordDecl::conversion_iterator 16179 I = CXXRecord->conversion_begin(), 16180 E = CXXRecord->conversion_end(); I != E; ++I) 16181 I.setAccess((*I)->getAccess()); 16182 } 16183 16184 if (!CXXRecord->isDependentType()) { 16185 // Add any implicitly-declared members to this class. 16186 AddImplicitlyDeclaredMembersToClass(CXXRecord); 16187 16188 if (!CXXRecord->isInvalidDecl()) { 16189 // If we have virtual base classes, we may end up finding multiple 16190 // final overriders for a given virtual function. Check for this 16191 // problem now. 16192 if (CXXRecord->getNumVBases()) { 16193 CXXFinalOverriderMap FinalOverriders; 16194 CXXRecord->getFinalOverriders(FinalOverriders); 16195 16196 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 16197 MEnd = FinalOverriders.end(); 16198 M != MEnd; ++M) { 16199 for (OverridingMethods::iterator SO = M->second.begin(), 16200 SOEnd = M->second.end(); 16201 SO != SOEnd; ++SO) { 16202 assert(SO->second.size() > 0 && 16203 "Virtual function without overriding functions?"); 16204 if (SO->second.size() == 1) 16205 continue; 16206 16207 // C++ [class.virtual]p2: 16208 // In a derived class, if a virtual member function of a base 16209 // class subobject has more than one final overrider the 16210 // program is ill-formed. 16211 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 16212 << (const NamedDecl *)M->first << Record; 16213 Diag(M->first->getLocation(), 16214 diag::note_overridden_virtual_function); 16215 for (OverridingMethods::overriding_iterator 16216 OM = SO->second.begin(), 16217 OMEnd = SO->second.end(); 16218 OM != OMEnd; ++OM) 16219 Diag(OM->Method->getLocation(), diag::note_final_overrider) 16220 << (const NamedDecl *)M->first << OM->Method->getParent(); 16221 16222 Record->setInvalidDecl(); 16223 } 16224 } 16225 CXXRecord->completeDefinition(&FinalOverriders); 16226 Completed = true; 16227 } 16228 } 16229 } 16230 } 16231 16232 if (!Completed) 16233 Record->completeDefinition(); 16234 16235 // Handle attributes before checking the layout. 16236 ProcessDeclAttributeList(S, Record, Attrs); 16237 16238 // We may have deferred checking for a deleted destructor. Check now. 16239 if (CXXRecord) { 16240 auto *Dtor = CXXRecord->getDestructor(); 16241 if (Dtor && Dtor->isImplicit() && 16242 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 16243 CXXRecord->setImplicitDestructorIsDeleted(); 16244 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 16245 } 16246 } 16247 16248 if (Record->hasAttrs()) { 16249 CheckAlignasUnderalignment(Record); 16250 16251 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 16252 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 16253 IA->getRange(), IA->getBestCase(), 16254 IA->getSemanticSpelling()); 16255 } 16256 16257 // Check if the structure/union declaration is a type that can have zero 16258 // size in C. For C this is a language extension, for C++ it may cause 16259 // compatibility problems. 16260 bool CheckForZeroSize; 16261 if (!getLangOpts().CPlusPlus) { 16262 CheckForZeroSize = true; 16263 } else { 16264 // For C++ filter out types that cannot be referenced in C code. 16265 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 16266 CheckForZeroSize = 16267 CXXRecord->getLexicalDeclContext()->isExternCContext() && 16268 !CXXRecord->isDependentType() && 16269 CXXRecord->isCLike(); 16270 } 16271 if (CheckForZeroSize) { 16272 bool ZeroSize = true; 16273 bool IsEmpty = true; 16274 unsigned NonBitFields = 0; 16275 for (RecordDecl::field_iterator I = Record->field_begin(), 16276 E = Record->field_end(); 16277 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 16278 IsEmpty = false; 16279 if (I->isUnnamedBitfield()) { 16280 if (!I->isZeroLengthBitField(Context)) 16281 ZeroSize = false; 16282 } else { 16283 ++NonBitFields; 16284 QualType FieldType = I->getType(); 16285 if (FieldType->isIncompleteType() || 16286 !Context.getTypeSizeInChars(FieldType).isZero()) 16287 ZeroSize = false; 16288 } 16289 } 16290 16291 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 16292 // allowed in C++, but warn if its declaration is inside 16293 // extern "C" block. 16294 if (ZeroSize) { 16295 Diag(RecLoc, getLangOpts().CPlusPlus ? 16296 diag::warn_zero_size_struct_union_in_extern_c : 16297 diag::warn_zero_size_struct_union_compat) 16298 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 16299 } 16300 16301 // Structs without named members are extension in C (C99 6.7.2.1p7), 16302 // but are accepted by GCC. 16303 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 16304 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 16305 diag::ext_no_named_members_in_struct_union) 16306 << Record->isUnion(); 16307 } 16308 } 16309 } else { 16310 ObjCIvarDecl **ClsFields = 16311 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 16312 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 16313 ID->setEndOfDefinitionLoc(RBrac); 16314 // Add ivar's to class's DeclContext. 16315 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 16316 ClsFields[i]->setLexicalDeclContext(ID); 16317 ID->addDecl(ClsFields[i]); 16318 } 16319 // Must enforce the rule that ivars in the base classes may not be 16320 // duplicates. 16321 if (ID->getSuperClass()) 16322 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 16323 } else if (ObjCImplementationDecl *IMPDecl = 16324 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16325 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 16326 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 16327 // Ivar declared in @implementation never belongs to the implementation. 16328 // Only it is in implementation's lexical context. 16329 ClsFields[I]->setLexicalDeclContext(IMPDecl); 16330 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 16331 IMPDecl->setIvarLBraceLoc(LBrac); 16332 IMPDecl->setIvarRBraceLoc(RBrac); 16333 } else if (ObjCCategoryDecl *CDecl = 16334 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16335 // case of ivars in class extension; all other cases have been 16336 // reported as errors elsewhere. 16337 // FIXME. Class extension does not have a LocEnd field. 16338 // CDecl->setLocEnd(RBrac); 16339 // Add ivar's to class extension's DeclContext. 16340 // Diagnose redeclaration of private ivars. 16341 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 16342 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 16343 if (IDecl) { 16344 if (const ObjCIvarDecl *ClsIvar = 16345 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 16346 Diag(ClsFields[i]->getLocation(), 16347 diag::err_duplicate_ivar_declaration); 16348 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 16349 continue; 16350 } 16351 for (const auto *Ext : IDecl->known_extensions()) { 16352 if (const ObjCIvarDecl *ClsExtIvar 16353 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 16354 Diag(ClsFields[i]->getLocation(), 16355 diag::err_duplicate_ivar_declaration); 16356 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 16357 continue; 16358 } 16359 } 16360 } 16361 ClsFields[i]->setLexicalDeclContext(CDecl); 16362 CDecl->addDecl(ClsFields[i]); 16363 } 16364 CDecl->setIvarLBraceLoc(LBrac); 16365 CDecl->setIvarRBraceLoc(RBrac); 16366 } 16367 } 16368 } 16369 16370 /// Determine whether the given integral value is representable within 16371 /// the given type T. 16372 static bool isRepresentableIntegerValue(ASTContext &Context, 16373 llvm::APSInt &Value, 16374 QualType T) { 16375 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 16376 "Integral type required!"); 16377 unsigned BitWidth = Context.getIntWidth(T); 16378 16379 if (Value.isUnsigned() || Value.isNonNegative()) { 16380 if (T->isSignedIntegerOrEnumerationType()) 16381 --BitWidth; 16382 return Value.getActiveBits() <= BitWidth; 16383 } 16384 return Value.getMinSignedBits() <= BitWidth; 16385 } 16386 16387 // Given an integral type, return the next larger integral type 16388 // (or a NULL type of no such type exists). 16389 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 16390 // FIXME: Int128/UInt128 support, which also needs to be introduced into 16391 // enum checking below. 16392 assert((T->isIntegralType(Context) || 16393 T->isEnumeralType()) && "Integral type required!"); 16394 const unsigned NumTypes = 4; 16395 QualType SignedIntegralTypes[NumTypes] = { 16396 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 16397 }; 16398 QualType UnsignedIntegralTypes[NumTypes] = { 16399 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 16400 Context.UnsignedLongLongTy 16401 }; 16402 16403 unsigned BitWidth = Context.getTypeSize(T); 16404 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 16405 : UnsignedIntegralTypes; 16406 for (unsigned I = 0; I != NumTypes; ++I) 16407 if (Context.getTypeSize(Types[I]) > BitWidth) 16408 return Types[I]; 16409 16410 return QualType(); 16411 } 16412 16413 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 16414 EnumConstantDecl *LastEnumConst, 16415 SourceLocation IdLoc, 16416 IdentifierInfo *Id, 16417 Expr *Val) { 16418 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16419 llvm::APSInt EnumVal(IntWidth); 16420 QualType EltTy; 16421 16422 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 16423 Val = nullptr; 16424 16425 if (Val) 16426 Val = DefaultLvalueConversion(Val).get(); 16427 16428 if (Val) { 16429 if (Enum->isDependentType() || Val->isTypeDependent()) 16430 EltTy = Context.DependentTy; 16431 else { 16432 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 16433 !getLangOpts().MSVCCompat) { 16434 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 16435 // constant-expression in the enumerator-definition shall be a converted 16436 // constant expression of the underlying type. 16437 EltTy = Enum->getIntegerType(); 16438 ExprResult Converted = 16439 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 16440 CCEK_Enumerator); 16441 if (Converted.isInvalid()) 16442 Val = nullptr; 16443 else 16444 Val = Converted.get(); 16445 } else if (!Val->isValueDependent() && 16446 !(Val = VerifyIntegerConstantExpression(Val, 16447 &EnumVal).get())) { 16448 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 16449 } else { 16450 if (Enum->isComplete()) { 16451 EltTy = Enum->getIntegerType(); 16452 16453 // In Obj-C and Microsoft mode, require the enumeration value to be 16454 // representable in the underlying type of the enumeration. In C++11, 16455 // we perform a non-narrowing conversion as part of converted constant 16456 // expression checking. 16457 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 16458 if (getLangOpts().MSVCCompat) { 16459 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 16460 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 16461 } else 16462 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 16463 } else 16464 Val = ImpCastExprToType(Val, EltTy, 16465 EltTy->isBooleanType() ? 16466 CK_IntegralToBoolean : CK_IntegralCast) 16467 .get(); 16468 } else if (getLangOpts().CPlusPlus) { 16469 // C++11 [dcl.enum]p5: 16470 // If the underlying type is not fixed, the type of each enumerator 16471 // is the type of its initializing value: 16472 // - If an initializer is specified for an enumerator, the 16473 // initializing value has the same type as the expression. 16474 EltTy = Val->getType(); 16475 } else { 16476 // C99 6.7.2.2p2: 16477 // The expression that defines the value of an enumeration constant 16478 // shall be an integer constant expression that has a value 16479 // representable as an int. 16480 16481 // Complain if the value is not representable in an int. 16482 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 16483 Diag(IdLoc, diag::ext_enum_value_not_int) 16484 << EnumVal.toString(10) << Val->getSourceRange() 16485 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 16486 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 16487 // Force the type of the expression to 'int'. 16488 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 16489 } 16490 EltTy = Val->getType(); 16491 } 16492 } 16493 } 16494 } 16495 16496 if (!Val) { 16497 if (Enum->isDependentType()) 16498 EltTy = Context.DependentTy; 16499 else if (!LastEnumConst) { 16500 // C++0x [dcl.enum]p5: 16501 // If the underlying type is not fixed, the type of each enumerator 16502 // is the type of its initializing value: 16503 // - If no initializer is specified for the first enumerator, the 16504 // initializing value has an unspecified integral type. 16505 // 16506 // GCC uses 'int' for its unspecified integral type, as does 16507 // C99 6.7.2.2p3. 16508 if (Enum->isFixed()) { 16509 EltTy = Enum->getIntegerType(); 16510 } 16511 else { 16512 EltTy = Context.IntTy; 16513 } 16514 } else { 16515 // Assign the last value + 1. 16516 EnumVal = LastEnumConst->getInitVal(); 16517 ++EnumVal; 16518 EltTy = LastEnumConst->getType(); 16519 16520 // Check for overflow on increment. 16521 if (EnumVal < LastEnumConst->getInitVal()) { 16522 // C++0x [dcl.enum]p5: 16523 // If the underlying type is not fixed, the type of each enumerator 16524 // is the type of its initializing value: 16525 // 16526 // - Otherwise the type of the initializing value is the same as 16527 // the type of the initializing value of the preceding enumerator 16528 // unless the incremented value is not representable in that type, 16529 // in which case the type is an unspecified integral type 16530 // sufficient to contain the incremented value. If no such type 16531 // exists, the program is ill-formed. 16532 QualType T = getNextLargerIntegralType(Context, EltTy); 16533 if (T.isNull() || Enum->isFixed()) { 16534 // There is no integral type larger enough to represent this 16535 // value. Complain, then allow the value to wrap around. 16536 EnumVal = LastEnumConst->getInitVal(); 16537 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 16538 ++EnumVal; 16539 if (Enum->isFixed()) 16540 // When the underlying type is fixed, this is ill-formed. 16541 Diag(IdLoc, diag::err_enumerator_wrapped) 16542 << EnumVal.toString(10) 16543 << EltTy; 16544 else 16545 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 16546 << EnumVal.toString(10); 16547 } else { 16548 EltTy = T; 16549 } 16550 16551 // Retrieve the last enumerator's value, extent that type to the 16552 // type that is supposed to be large enough to represent the incremented 16553 // value, then increment. 16554 EnumVal = LastEnumConst->getInitVal(); 16555 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 16556 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 16557 ++EnumVal; 16558 16559 // If we're not in C++, diagnose the overflow of enumerator values, 16560 // which in C99 means that the enumerator value is not representable in 16561 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 16562 // permits enumerator values that are representable in some larger 16563 // integral type. 16564 if (!getLangOpts().CPlusPlus && !T.isNull()) 16565 Diag(IdLoc, diag::warn_enum_value_overflow); 16566 } else if (!getLangOpts().CPlusPlus && 16567 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 16568 // Enforce C99 6.7.2.2p2 even when we compute the next value. 16569 Diag(IdLoc, diag::ext_enum_value_not_int) 16570 << EnumVal.toString(10) << 1; 16571 } 16572 } 16573 } 16574 16575 if (!EltTy->isDependentType()) { 16576 // Make the enumerator value match the signedness and size of the 16577 // enumerator's type. 16578 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 16579 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 16580 } 16581 16582 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 16583 Val, EnumVal); 16584 } 16585 16586 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 16587 SourceLocation IILoc) { 16588 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 16589 !getLangOpts().CPlusPlus) 16590 return SkipBodyInfo(); 16591 16592 // We have an anonymous enum definition. Look up the first enumerator to 16593 // determine if we should merge the definition with an existing one and 16594 // skip the body. 16595 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 16596 forRedeclarationInCurContext()); 16597 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 16598 if (!PrevECD) 16599 return SkipBodyInfo(); 16600 16601 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 16602 NamedDecl *Hidden; 16603 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 16604 SkipBodyInfo Skip; 16605 Skip.Previous = Hidden; 16606 return Skip; 16607 } 16608 16609 return SkipBodyInfo(); 16610 } 16611 16612 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 16613 SourceLocation IdLoc, IdentifierInfo *Id, 16614 const ParsedAttributesView &Attrs, 16615 SourceLocation EqualLoc, Expr *Val) { 16616 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 16617 EnumConstantDecl *LastEnumConst = 16618 cast_or_null<EnumConstantDecl>(lastEnumConst); 16619 16620 // The scope passed in may not be a decl scope. Zip up the scope tree until 16621 // we find one that is. 16622 S = getNonFieldDeclScope(S); 16623 16624 // Verify that there isn't already something declared with this name in this 16625 // scope. 16626 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 16627 LookupName(R, S); 16628 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 16629 16630 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16631 // Maybe we will complain about the shadowed template parameter. 16632 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 16633 // Just pretend that we didn't see the previous declaration. 16634 PrevDecl = nullptr; 16635 } 16636 16637 // C++ [class.mem]p15: 16638 // If T is the name of a class, then each of the following shall have a name 16639 // different from T: 16640 // - every enumerator of every member of class T that is an unscoped 16641 // enumerated type 16642 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 16643 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 16644 DeclarationNameInfo(Id, IdLoc)); 16645 16646 EnumConstantDecl *New = 16647 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 16648 if (!New) 16649 return nullptr; 16650 16651 if (PrevDecl) { 16652 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 16653 // Check for other kinds of shadowing not already handled. 16654 CheckShadow(New, PrevDecl, R); 16655 } 16656 16657 // When in C++, we may get a TagDecl with the same name; in this case the 16658 // enum constant will 'hide' the tag. 16659 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 16660 "Received TagDecl when not in C++!"); 16661 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 16662 if (isa<EnumConstantDecl>(PrevDecl)) 16663 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 16664 else 16665 Diag(IdLoc, diag::err_redefinition) << Id; 16666 notePreviousDefinition(PrevDecl, IdLoc); 16667 return nullptr; 16668 } 16669 } 16670 16671 // Process attributes. 16672 ProcessDeclAttributeList(S, New, Attrs); 16673 AddPragmaAttributes(S, New); 16674 16675 // Register this decl in the current scope stack. 16676 New->setAccess(TheEnumDecl->getAccess()); 16677 PushOnScopeChains(New, S); 16678 16679 ActOnDocumentableDecl(New); 16680 16681 return New; 16682 } 16683 16684 // Returns true when the enum initial expression does not trigger the 16685 // duplicate enum warning. A few common cases are exempted as follows: 16686 // Element2 = Element1 16687 // Element2 = Element1 + 1 16688 // Element2 = Element1 - 1 16689 // Where Element2 and Element1 are from the same enum. 16690 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 16691 Expr *InitExpr = ECD->getInitExpr(); 16692 if (!InitExpr) 16693 return true; 16694 InitExpr = InitExpr->IgnoreImpCasts(); 16695 16696 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 16697 if (!BO->isAdditiveOp()) 16698 return true; 16699 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 16700 if (!IL) 16701 return true; 16702 if (IL->getValue() != 1) 16703 return true; 16704 16705 InitExpr = BO->getLHS(); 16706 } 16707 16708 // This checks if the elements are from the same enum. 16709 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 16710 if (!DRE) 16711 return true; 16712 16713 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 16714 if (!EnumConstant) 16715 return true; 16716 16717 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 16718 Enum) 16719 return true; 16720 16721 return false; 16722 } 16723 16724 // Emits a warning when an element is implicitly set a value that 16725 // a previous element has already been set to. 16726 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 16727 EnumDecl *Enum, QualType EnumType) { 16728 // Avoid anonymous enums 16729 if (!Enum->getIdentifier()) 16730 return; 16731 16732 // Only check for small enums. 16733 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 16734 return; 16735 16736 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 16737 return; 16738 16739 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 16740 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 16741 16742 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 16743 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 16744 16745 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 16746 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 16747 llvm::APSInt Val = D->getInitVal(); 16748 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 16749 }; 16750 16751 DuplicatesVector DupVector; 16752 ValueToVectorMap EnumMap; 16753 16754 // Populate the EnumMap with all values represented by enum constants without 16755 // an initializer. 16756 for (auto *Element : Elements) { 16757 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 16758 16759 // Null EnumConstantDecl means a previous diagnostic has been emitted for 16760 // this constant. Skip this enum since it may be ill-formed. 16761 if (!ECD) { 16762 return; 16763 } 16764 16765 // Constants with initalizers are handled in the next loop. 16766 if (ECD->getInitExpr()) 16767 continue; 16768 16769 // Duplicate values are handled in the next loop. 16770 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 16771 } 16772 16773 if (EnumMap.size() == 0) 16774 return; 16775 16776 // Create vectors for any values that has duplicates. 16777 for (auto *Element : Elements) { 16778 // The last loop returned if any constant was null. 16779 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 16780 if (!ValidDuplicateEnum(ECD, Enum)) 16781 continue; 16782 16783 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 16784 if (Iter == EnumMap.end()) 16785 continue; 16786 16787 DeclOrVector& Entry = Iter->second; 16788 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 16789 // Ensure constants are different. 16790 if (D == ECD) 16791 continue; 16792 16793 // Create new vector and push values onto it. 16794 auto Vec = std::make_unique<ECDVector>(); 16795 Vec->push_back(D); 16796 Vec->push_back(ECD); 16797 16798 // Update entry to point to the duplicates vector. 16799 Entry = Vec.get(); 16800 16801 // Store the vector somewhere we can consult later for quick emission of 16802 // diagnostics. 16803 DupVector.emplace_back(std::move(Vec)); 16804 continue; 16805 } 16806 16807 ECDVector *Vec = Entry.get<ECDVector*>(); 16808 // Make sure constants are not added more than once. 16809 if (*Vec->begin() == ECD) 16810 continue; 16811 16812 Vec->push_back(ECD); 16813 } 16814 16815 // Emit diagnostics. 16816 for (const auto &Vec : DupVector) { 16817 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 16818 16819 // Emit warning for one enum constant. 16820 auto *FirstECD = Vec->front(); 16821 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 16822 << FirstECD << FirstECD->getInitVal().toString(10) 16823 << FirstECD->getSourceRange(); 16824 16825 // Emit one note for each of the remaining enum constants with 16826 // the same value. 16827 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 16828 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 16829 << ECD << ECD->getInitVal().toString(10) 16830 << ECD->getSourceRange(); 16831 } 16832 } 16833 16834 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 16835 bool AllowMask) const { 16836 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 16837 assert(ED->isCompleteDefinition() && "expected enum definition"); 16838 16839 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 16840 llvm::APInt &FlagBits = R.first->second; 16841 16842 if (R.second) { 16843 for (auto *E : ED->enumerators()) { 16844 const auto &EVal = E->getInitVal(); 16845 // Only single-bit enumerators introduce new flag values. 16846 if (EVal.isPowerOf2()) 16847 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 16848 } 16849 } 16850 16851 // A value is in a flag enum if either its bits are a subset of the enum's 16852 // flag bits (the first condition) or we are allowing masks and the same is 16853 // true of its complement (the second condition). When masks are allowed, we 16854 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 16855 // 16856 // While it's true that any value could be used as a mask, the assumption is 16857 // that a mask will have all of the insignificant bits set. Anything else is 16858 // likely a logic error. 16859 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 16860 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 16861 } 16862 16863 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 16864 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 16865 const ParsedAttributesView &Attrs) { 16866 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 16867 QualType EnumType = Context.getTypeDeclType(Enum); 16868 16869 ProcessDeclAttributeList(S, Enum, Attrs); 16870 16871 if (Enum->isDependentType()) { 16872 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16873 EnumConstantDecl *ECD = 16874 cast_or_null<EnumConstantDecl>(Elements[i]); 16875 if (!ECD) continue; 16876 16877 ECD->setType(EnumType); 16878 } 16879 16880 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 16881 return; 16882 } 16883 16884 // TODO: If the result value doesn't fit in an int, it must be a long or long 16885 // long value. ISO C does not support this, but GCC does as an extension, 16886 // emit a warning. 16887 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16888 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 16889 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 16890 16891 // Verify that all the values are okay, compute the size of the values, and 16892 // reverse the list. 16893 unsigned NumNegativeBits = 0; 16894 unsigned NumPositiveBits = 0; 16895 16896 // Keep track of whether all elements have type int. 16897 bool AllElementsInt = true; 16898 16899 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16900 EnumConstantDecl *ECD = 16901 cast_or_null<EnumConstantDecl>(Elements[i]); 16902 if (!ECD) continue; // Already issued a diagnostic. 16903 16904 const llvm::APSInt &InitVal = ECD->getInitVal(); 16905 16906 // Keep track of the size of positive and negative values. 16907 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 16908 NumPositiveBits = std::max(NumPositiveBits, 16909 (unsigned)InitVal.getActiveBits()); 16910 else 16911 NumNegativeBits = std::max(NumNegativeBits, 16912 (unsigned)InitVal.getMinSignedBits()); 16913 16914 // Keep track of whether every enum element has type int (very common). 16915 if (AllElementsInt) 16916 AllElementsInt = ECD->getType() == Context.IntTy; 16917 } 16918 16919 // Figure out the type that should be used for this enum. 16920 QualType BestType; 16921 unsigned BestWidth; 16922 16923 // C++0x N3000 [conv.prom]p3: 16924 // An rvalue of an unscoped enumeration type whose underlying 16925 // type is not fixed can be converted to an rvalue of the first 16926 // of the following types that can represent all the values of 16927 // the enumeration: int, unsigned int, long int, unsigned long 16928 // int, long long int, or unsigned long long int. 16929 // C99 6.4.4.3p2: 16930 // An identifier declared as an enumeration constant has type int. 16931 // The C99 rule is modified by a gcc extension 16932 QualType BestPromotionType; 16933 16934 bool Packed = Enum->hasAttr<PackedAttr>(); 16935 // -fshort-enums is the equivalent to specifying the packed attribute on all 16936 // enum definitions. 16937 if (LangOpts.ShortEnums) 16938 Packed = true; 16939 16940 // If the enum already has a type because it is fixed or dictated by the 16941 // target, promote that type instead of analyzing the enumerators. 16942 if (Enum->isComplete()) { 16943 BestType = Enum->getIntegerType(); 16944 if (BestType->isPromotableIntegerType()) 16945 BestPromotionType = Context.getPromotedIntegerType(BestType); 16946 else 16947 BestPromotionType = BestType; 16948 16949 BestWidth = Context.getIntWidth(BestType); 16950 } 16951 else if (NumNegativeBits) { 16952 // If there is a negative value, figure out the smallest integer type (of 16953 // int/long/longlong) that fits. 16954 // If it's packed, check also if it fits a char or a short. 16955 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 16956 BestType = Context.SignedCharTy; 16957 BestWidth = CharWidth; 16958 } else if (Packed && NumNegativeBits <= ShortWidth && 16959 NumPositiveBits < ShortWidth) { 16960 BestType = Context.ShortTy; 16961 BestWidth = ShortWidth; 16962 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 16963 BestType = Context.IntTy; 16964 BestWidth = IntWidth; 16965 } else { 16966 BestWidth = Context.getTargetInfo().getLongWidth(); 16967 16968 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 16969 BestType = Context.LongTy; 16970 } else { 16971 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16972 16973 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 16974 Diag(Enum->getLocation(), diag::ext_enum_too_large); 16975 BestType = Context.LongLongTy; 16976 } 16977 } 16978 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 16979 } else { 16980 // If there is no negative value, figure out the smallest type that fits 16981 // all of the enumerator values. 16982 // If it's packed, check also if it fits a char or a short. 16983 if (Packed && NumPositiveBits <= CharWidth) { 16984 BestType = Context.UnsignedCharTy; 16985 BestPromotionType = Context.IntTy; 16986 BestWidth = CharWidth; 16987 } else if (Packed && NumPositiveBits <= ShortWidth) { 16988 BestType = Context.UnsignedShortTy; 16989 BestPromotionType = Context.IntTy; 16990 BestWidth = ShortWidth; 16991 } else if (NumPositiveBits <= IntWidth) { 16992 BestType = Context.UnsignedIntTy; 16993 BestWidth = IntWidth; 16994 BestPromotionType 16995 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16996 ? Context.UnsignedIntTy : Context.IntTy; 16997 } else if (NumPositiveBits <= 16998 (BestWidth = Context.getTargetInfo().getLongWidth())) { 16999 BestType = Context.UnsignedLongTy; 17000 BestPromotionType 17001 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17002 ? Context.UnsignedLongTy : Context.LongTy; 17003 } else { 17004 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17005 assert(NumPositiveBits <= BestWidth && 17006 "How could an initializer get larger than ULL?"); 17007 BestType = Context.UnsignedLongLongTy; 17008 BestPromotionType 17009 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17010 ? Context.UnsignedLongLongTy : Context.LongLongTy; 17011 } 17012 } 17013 17014 // Loop over all of the enumerator constants, changing their types to match 17015 // the type of the enum if needed. 17016 for (auto *D : Elements) { 17017 auto *ECD = cast_or_null<EnumConstantDecl>(D); 17018 if (!ECD) continue; // Already issued a diagnostic. 17019 17020 // Standard C says the enumerators have int type, but we allow, as an 17021 // extension, the enumerators to be larger than int size. If each 17022 // enumerator value fits in an int, type it as an int, otherwise type it the 17023 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 17024 // that X has type 'int', not 'unsigned'. 17025 17026 // Determine whether the value fits into an int. 17027 llvm::APSInt InitVal = ECD->getInitVal(); 17028 17029 // If it fits into an integer type, force it. Otherwise force it to match 17030 // the enum decl type. 17031 QualType NewTy; 17032 unsigned NewWidth; 17033 bool NewSign; 17034 if (!getLangOpts().CPlusPlus && 17035 !Enum->isFixed() && 17036 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 17037 NewTy = Context.IntTy; 17038 NewWidth = IntWidth; 17039 NewSign = true; 17040 } else if (ECD->getType() == BestType) { 17041 // Already the right type! 17042 if (getLangOpts().CPlusPlus) 17043 // C++ [dcl.enum]p4: Following the closing brace of an 17044 // enum-specifier, each enumerator has the type of its 17045 // enumeration. 17046 ECD->setType(EnumType); 17047 continue; 17048 } else { 17049 NewTy = BestType; 17050 NewWidth = BestWidth; 17051 NewSign = BestType->isSignedIntegerOrEnumerationType(); 17052 } 17053 17054 // Adjust the APSInt value. 17055 InitVal = InitVal.extOrTrunc(NewWidth); 17056 InitVal.setIsSigned(NewSign); 17057 ECD->setInitVal(InitVal); 17058 17059 // Adjust the Expr initializer and type. 17060 if (ECD->getInitExpr() && 17061 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 17062 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 17063 CK_IntegralCast, 17064 ECD->getInitExpr(), 17065 /*base paths*/ nullptr, 17066 VK_RValue)); 17067 if (getLangOpts().CPlusPlus) 17068 // C++ [dcl.enum]p4: Following the closing brace of an 17069 // enum-specifier, each enumerator has the type of its 17070 // enumeration. 17071 ECD->setType(EnumType); 17072 else 17073 ECD->setType(NewTy); 17074 } 17075 17076 Enum->completeDefinition(BestType, BestPromotionType, 17077 NumPositiveBits, NumNegativeBits); 17078 17079 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 17080 17081 if (Enum->isClosedFlag()) { 17082 for (Decl *D : Elements) { 17083 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 17084 if (!ECD) continue; // Already issued a diagnostic. 17085 17086 llvm::APSInt InitVal = ECD->getInitVal(); 17087 if (InitVal != 0 && !InitVal.isPowerOf2() && 17088 !IsValueInFlagEnum(Enum, InitVal, true)) 17089 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 17090 << ECD << Enum; 17091 } 17092 } 17093 17094 // Now that the enum type is defined, ensure it's not been underaligned. 17095 if (Enum->hasAttrs()) 17096 CheckAlignasUnderalignment(Enum); 17097 } 17098 17099 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 17100 SourceLocation StartLoc, 17101 SourceLocation EndLoc) { 17102 StringLiteral *AsmString = cast<StringLiteral>(expr); 17103 17104 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 17105 AsmString, StartLoc, 17106 EndLoc); 17107 CurContext->addDecl(New); 17108 return New; 17109 } 17110 17111 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 17112 IdentifierInfo* AliasName, 17113 SourceLocation PragmaLoc, 17114 SourceLocation NameLoc, 17115 SourceLocation AliasNameLoc) { 17116 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 17117 LookupOrdinaryName); 17118 AsmLabelAttr *Attr = 17119 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 17120 17121 // If a declaration that: 17122 // 1) declares a function or a variable 17123 // 2) has external linkage 17124 // already exists, add a label attribute to it. 17125 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17126 if (isDeclExternC(PrevDecl)) 17127 PrevDecl->addAttr(Attr); 17128 else 17129 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 17130 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 17131 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 17132 } else 17133 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 17134 } 17135 17136 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 17137 SourceLocation PragmaLoc, 17138 SourceLocation NameLoc) { 17139 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 17140 17141 if (PrevDecl) { 17142 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 17143 } else { 17144 (void)WeakUndeclaredIdentifiers.insert( 17145 std::pair<IdentifierInfo*,WeakInfo> 17146 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 17147 } 17148 } 17149 17150 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 17151 IdentifierInfo* AliasName, 17152 SourceLocation PragmaLoc, 17153 SourceLocation NameLoc, 17154 SourceLocation AliasNameLoc) { 17155 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 17156 LookupOrdinaryName); 17157 WeakInfo W = WeakInfo(Name, NameLoc); 17158 17159 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17160 if (!PrevDecl->hasAttr<AliasAttr>()) 17161 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 17162 DeclApplyPragmaWeak(TUScope, ND, W); 17163 } else { 17164 (void)WeakUndeclaredIdentifiers.insert( 17165 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 17166 } 17167 } 17168 17169 Decl *Sema::getObjCDeclContext() const { 17170 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 17171 } 17172