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/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NonTrivialTypeVisitor.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Sema/CXXFieldCollector.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 #include <unordered_map> 52 53 using namespace clang; 54 using namespace sema; 55 56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 57 if (OwnedType) { 58 Decl *Group[2] = { OwnedType, Ptr }; 59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 60 } 61 62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 63 } 64 65 namespace { 66 67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 68 public: 69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 70 bool AllowTemplates = false, 71 bool AllowNonTemplates = true) 72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 74 WantExpressionKeywords = false; 75 WantCXXNamedCasts = false; 76 WantRemainingKeywords = false; 77 } 78 79 bool ValidateCandidate(const TypoCorrection &candidate) override { 80 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 81 if (!AllowInvalidDecl && ND->isInvalidDecl()) 82 return false; 83 84 if (getAsTypeTemplateDecl(ND)) 85 return AllowTemplates; 86 87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 88 if (!IsType) 89 return false; 90 91 if (AllowNonTemplates) 92 return true; 93 94 // An injected-class-name of a class template (specialization) is valid 95 // as a template or as a non-template. 96 if (AllowTemplates) { 97 auto *RD = dyn_cast<CXXRecordDecl>(ND); 98 if (!RD || !RD->isInjectedClassName()) 99 return false; 100 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 101 return RD->getDescribedClassTemplate() || 102 isa<ClassTemplateSpecializationDecl>(RD); 103 } 104 105 return false; 106 } 107 108 return !WantClassName && candidate.isKeyword(); 109 } 110 111 std::unique_ptr<CorrectionCandidateCallback> clone() override { 112 return std::make_unique<TypeNameValidatorCCC>(*this); 113 } 114 115 private: 116 bool AllowInvalidDecl; 117 bool WantClassName; 118 bool AllowTemplates; 119 bool AllowNonTemplates; 120 }; 121 122 } // end anonymous namespace 123 124 /// Determine whether the token kind starts a simple-type-specifier. 125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 126 switch (Kind) { 127 // FIXME: Take into account the current language when deciding whether a 128 // token kind is a valid type specifier 129 case tok::kw_short: 130 case tok::kw_long: 131 case tok::kw___int64: 132 case tok::kw___int128: 133 case tok::kw_signed: 134 case tok::kw_unsigned: 135 case tok::kw_void: 136 case tok::kw_char: 137 case tok::kw_int: 138 case tok::kw_half: 139 case tok::kw_float: 140 case tok::kw_double: 141 case tok::kw___bf16: 142 case tok::kw__Float16: 143 case tok::kw___float128: 144 case tok::kw___ibm128: 145 case tok::kw_wchar_t: 146 case tok::kw_bool: 147 case tok::kw___underlying_type: 148 case tok::kw___auto_type: 149 return true; 150 151 case tok::annot_typename: 152 case tok::kw_char16_t: 153 case tok::kw_char32_t: 154 case tok::kw_typeof: 155 case tok::annot_decltype: 156 case tok::kw_decltype: 157 return getLangOpts().CPlusPlus; 158 159 case tok::kw_char8_t: 160 return getLangOpts().Char8; 161 162 default: 163 break; 164 } 165 166 return false; 167 } 168 169 namespace { 170 enum class UnqualifiedTypeNameLookupResult { 171 NotFound, 172 FoundNonType, 173 FoundType 174 }; 175 } // end anonymous namespace 176 177 /// Tries to perform unqualified lookup of the type decls in bases for 178 /// dependent class. 179 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 180 /// type decl, \a FoundType if only type decls are found. 181 static UnqualifiedTypeNameLookupResult 182 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 183 SourceLocation NameLoc, 184 const CXXRecordDecl *RD) { 185 if (!RD->hasDefinition()) 186 return UnqualifiedTypeNameLookupResult::NotFound; 187 // Look for type decls in base classes. 188 UnqualifiedTypeNameLookupResult FoundTypeDecl = 189 UnqualifiedTypeNameLookupResult::NotFound; 190 for (const auto &Base : RD->bases()) { 191 const CXXRecordDecl *BaseRD = nullptr; 192 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 193 BaseRD = BaseTT->getAsCXXRecordDecl(); 194 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 195 // Look for type decls in dependent base classes that have known primary 196 // templates. 197 if (!TST || !TST->isDependentType()) 198 continue; 199 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 200 if (!TD) 201 continue; 202 if (auto *BasePrimaryTemplate = 203 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 204 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 205 BaseRD = BasePrimaryTemplate; 206 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 207 if (const ClassTemplatePartialSpecializationDecl *PS = 208 CTD->findPartialSpecialization(Base.getType())) 209 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 210 BaseRD = PS; 211 } 212 } 213 } 214 if (BaseRD) { 215 for (NamedDecl *ND : BaseRD->lookup(&II)) { 216 if (!isa<TypeDecl>(ND)) 217 return UnqualifiedTypeNameLookupResult::FoundNonType; 218 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 219 } 220 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 221 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 222 case UnqualifiedTypeNameLookupResult::FoundNonType: 223 return UnqualifiedTypeNameLookupResult::FoundNonType; 224 case UnqualifiedTypeNameLookupResult::FoundType: 225 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 226 break; 227 case UnqualifiedTypeNameLookupResult::NotFound: 228 break; 229 } 230 } 231 } 232 } 233 234 return FoundTypeDecl; 235 } 236 237 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 238 const IdentifierInfo &II, 239 SourceLocation NameLoc) { 240 // Lookup in the parent class template context, if any. 241 const CXXRecordDecl *RD = nullptr; 242 UnqualifiedTypeNameLookupResult FoundTypeDecl = 243 UnqualifiedTypeNameLookupResult::NotFound; 244 for (DeclContext *DC = S.CurContext; 245 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 246 DC = DC->getParent()) { 247 // Look for type decls in dependent base classes that have known primary 248 // templates. 249 RD = dyn_cast<CXXRecordDecl>(DC); 250 if (RD && RD->getDescribedClassTemplate()) 251 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 252 } 253 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 254 return nullptr; 255 256 // We found some types in dependent base classes. Recover as if the user 257 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 258 // lookup during template instantiation. 259 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 260 261 ASTContext &Context = S.Context; 262 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 263 cast<Type>(Context.getRecordType(RD))); 264 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 265 266 CXXScopeSpec SS; 267 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 268 269 TypeLocBuilder Builder; 270 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 271 DepTL.setNameLoc(NameLoc); 272 DepTL.setElaboratedKeywordLoc(SourceLocation()); 273 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 274 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 275 } 276 277 /// If the identifier refers to a type name within this scope, 278 /// return the declaration of that type. 279 /// 280 /// This routine performs ordinary name lookup of the identifier II 281 /// within the given scope, with optional C++ scope specifier SS, to 282 /// determine whether the name refers to a type. If so, returns an 283 /// opaque pointer (actually a QualType) corresponding to that 284 /// type. Otherwise, returns NULL. 285 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 286 Scope *S, CXXScopeSpec *SS, 287 bool isClassName, bool HasTrailingDot, 288 ParsedType ObjectTypePtr, 289 bool IsCtorOrDtorName, 290 bool WantNontrivialTypeSourceInfo, 291 bool IsClassTemplateDeductionContext, 292 IdentifierInfo **CorrectedII) { 293 // FIXME: Consider allowing this outside C++1z mode as an extension. 294 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 295 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 296 !isClassName && !HasTrailingDot; 297 298 // Determine where we will perform name lookup. 299 DeclContext *LookupCtx = nullptr; 300 if (ObjectTypePtr) { 301 QualType ObjectType = ObjectTypePtr.get(); 302 if (ObjectType->isRecordType()) 303 LookupCtx = computeDeclContext(ObjectType); 304 } else if (SS && SS->isNotEmpty()) { 305 LookupCtx = computeDeclContext(*SS, false); 306 307 if (!LookupCtx) { 308 if (isDependentScopeSpecifier(*SS)) { 309 // C++ [temp.res]p3: 310 // A qualified-id that refers to a type and in which the 311 // nested-name-specifier depends on a template-parameter (14.6.2) 312 // shall be prefixed by the keyword typename to indicate that the 313 // qualified-id denotes a type, forming an 314 // elaborated-type-specifier (7.1.5.3). 315 // 316 // We therefore do not perform any name lookup if the result would 317 // refer to a member of an unknown specialization. 318 if (!isClassName && !IsCtorOrDtorName) 319 return nullptr; 320 321 // We know from the grammar that this name refers to a type, 322 // so build a dependent node to describe the type. 323 if (WantNontrivialTypeSourceInfo) 324 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 325 326 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 327 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 328 II, NameLoc); 329 return ParsedType::make(T); 330 } 331 332 return nullptr; 333 } 334 335 if (!LookupCtx->isDependentContext() && 336 RequireCompleteDeclContext(*SS, LookupCtx)) 337 return nullptr; 338 } 339 340 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 341 // lookup for class-names. 342 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 343 LookupOrdinaryName; 344 LookupResult Result(*this, &II, NameLoc, Kind); 345 if (LookupCtx) { 346 // Perform "qualified" name lookup into the declaration context we 347 // computed, which is either the type of the base of a member access 348 // expression or the declaration context associated with a prior 349 // nested-name-specifier. 350 LookupQualifiedName(Result, LookupCtx); 351 352 if (ObjectTypePtr && Result.empty()) { 353 // C++ [basic.lookup.classref]p3: 354 // If the unqualified-id is ~type-name, the type-name is looked up 355 // in the context of the entire postfix-expression. If the type T of 356 // the object expression is of a class type C, the type-name is also 357 // looked up in the scope of class C. At least one of the lookups shall 358 // find a name that refers to (possibly cv-qualified) T. 359 LookupName(Result, S); 360 } 361 } else { 362 // Perform unqualified name lookup. 363 LookupName(Result, S); 364 365 // For unqualified lookup in a class template in MSVC mode, look into 366 // dependent base classes where the primary class template is known. 367 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 368 if (ParsedType TypeInBase = 369 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 370 return TypeInBase; 371 } 372 } 373 374 NamedDecl *IIDecl = nullptr; 375 UsingShadowDecl *FoundUsingShadow = nullptr; 376 switch (Result.getResultKind()) { 377 case LookupResult::NotFound: 378 case LookupResult::NotFoundInCurrentInstantiation: 379 if (CorrectedII) { 380 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 381 AllowDeducedTemplate); 382 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 383 S, SS, CCC, CTK_ErrorRecovery); 384 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 385 TemplateTy Template; 386 bool MemberOfUnknownSpecialization; 387 UnqualifiedId TemplateName; 388 TemplateName.setIdentifier(NewII, NameLoc); 389 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 390 CXXScopeSpec NewSS, *NewSSPtr = SS; 391 if (SS && NNS) { 392 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 393 NewSSPtr = &NewSS; 394 } 395 if (Correction && (NNS || NewII != &II) && 396 // Ignore a correction to a template type as the to-be-corrected 397 // identifier is not a template (typo correction for template names 398 // is handled elsewhere). 399 !(getLangOpts().CPlusPlus && NewSSPtr && 400 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 401 Template, MemberOfUnknownSpecialization))) { 402 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 403 isClassName, HasTrailingDot, ObjectTypePtr, 404 IsCtorOrDtorName, 405 WantNontrivialTypeSourceInfo, 406 IsClassTemplateDeductionContext); 407 if (Ty) { 408 diagnoseTypo(Correction, 409 PDiag(diag::err_unknown_type_or_class_name_suggest) 410 << Result.getLookupName() << isClassName); 411 if (SS && NNS) 412 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 413 *CorrectedII = NewII; 414 return Ty; 415 } 416 } 417 } 418 // If typo correction failed or was not performed, fall through 419 LLVM_FALLTHROUGH; 420 case LookupResult::FoundOverloaded: 421 case LookupResult::FoundUnresolvedValue: 422 Result.suppressDiagnostics(); 423 return nullptr; 424 425 case LookupResult::Ambiguous: 426 // Recover from type-hiding ambiguities by hiding the type. We'll 427 // do the lookup again when looking for an object, and we can 428 // diagnose the error then. If we don't do this, then the error 429 // about hiding the type will be immediately followed by an error 430 // that only makes sense if the identifier was treated like a type. 431 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 432 Result.suppressDiagnostics(); 433 return nullptr; 434 } 435 436 // Look to see if we have a type anywhere in the list of results. 437 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 438 Res != ResEnd; ++Res) { 439 NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); 440 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( 441 RealRes) || 442 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { 443 if (!IIDecl || 444 // Make the selection of the recovery decl deterministic. 445 RealRes->getLocation() < IIDecl->getLocation()) { 446 IIDecl = RealRes; 447 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res); 448 } 449 } 450 } 451 452 if (!IIDecl) { 453 // None of the entities we found is a type, so there is no way 454 // to even assume that the result is a type. In this case, don't 455 // complain about the ambiguity. The parser will either try to 456 // perform this lookup again (e.g., as an object name), which 457 // will produce the ambiguity, or will complain that it expected 458 // a type name. 459 Result.suppressDiagnostics(); 460 return nullptr; 461 } 462 463 // We found a type within the ambiguous lookup; diagnose the 464 // ambiguity and then return that type. This might be the right 465 // answer, or it might not be, but it suppresses any attempt to 466 // perform the name lookup again. 467 break; 468 469 case LookupResult::Found: 470 IIDecl = Result.getFoundDecl(); 471 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin()); 472 break; 473 } 474 475 assert(IIDecl && "Didn't find decl"); 476 477 QualType T; 478 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 479 // C++ [class.qual]p2: A lookup that would find the injected-class-name 480 // instead names the constructors of the class, except when naming a class. 481 // This is ill-formed when we're not actually forming a ctor or dtor name. 482 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 483 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 484 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 485 FoundRD->isInjectedClassName() && 486 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 487 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 488 << &II << /*Type*/1; 489 490 DiagnoseUseOfDecl(IIDecl, NameLoc); 491 492 T = Context.getTypeDeclType(TD); 493 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 494 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 495 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 496 if (!HasTrailingDot) 497 T = Context.getObjCInterfaceType(IDecl); 498 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl. 499 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { 500 (void)DiagnoseUseOfDecl(UD, NameLoc); 501 // Recover with 'int' 502 T = Context.IntTy; 503 FoundUsingShadow = nullptr; 504 } else if (AllowDeducedTemplate) { 505 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) { 506 // FIXME: TemplateName should include FoundUsingShadow sugar. 507 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 508 QualType(), false); 509 // Don't wrap in a further UsingType. 510 FoundUsingShadow = nullptr; 511 } 512 } 513 514 if (T.isNull()) { 515 // If it's not plausibly a type, suppress diagnostics. 516 Result.suppressDiagnostics(); 517 return nullptr; 518 } 519 520 if (FoundUsingShadow) 521 T = Context.getUsingType(FoundUsingShadow, T); 522 523 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 524 // constructor or destructor name (in such a case, the scope specifier 525 // will be attached to the enclosing Expr or Decl node). 526 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 527 !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) { 528 if (WantNontrivialTypeSourceInfo) { 529 // Construct a type with type-source information. 530 TypeLocBuilder Builder; 531 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 532 533 T = getElaboratedType(ETK_None, *SS, T); 534 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 535 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 536 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 537 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 538 } else { 539 T = getElaboratedType(ETK_None, *SS, T); 540 } 541 } 542 543 return ParsedType::make(T); 544 } 545 546 // Builds a fake NNS for the given decl context. 547 static NestedNameSpecifier * 548 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 549 for (;; DC = DC->getLookupParent()) { 550 DC = DC->getPrimaryContext(); 551 auto *ND = dyn_cast<NamespaceDecl>(DC); 552 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 553 return NestedNameSpecifier::Create(Context, nullptr, ND); 554 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 555 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 556 RD->getTypeForDecl()); 557 else if (isa<TranslationUnitDecl>(DC)) 558 return NestedNameSpecifier::GlobalSpecifier(Context); 559 } 560 llvm_unreachable("something isn't in TU scope?"); 561 } 562 563 /// Find the parent class with dependent bases of the innermost enclosing method 564 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 565 /// up allowing unqualified dependent type names at class-level, which MSVC 566 /// correctly rejects. 567 static const CXXRecordDecl * 568 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 569 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 570 DC = DC->getPrimaryContext(); 571 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 572 if (MD->getParent()->hasAnyDependentBases()) 573 return MD->getParent(); 574 } 575 return nullptr; 576 } 577 578 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 579 SourceLocation NameLoc, 580 bool IsTemplateTypeArg) { 581 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 582 583 NestedNameSpecifier *NNS = nullptr; 584 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 585 // If we weren't able to parse a default template argument, delay lookup 586 // until instantiation time by making a non-dependent DependentTypeName. We 587 // pretend we saw a NestedNameSpecifier referring to the current scope, and 588 // lookup is retried. 589 // FIXME: This hurts our diagnostic quality, since we get errors like "no 590 // type named 'Foo' in 'current_namespace'" when the user didn't write any 591 // name specifiers. 592 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 593 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 594 } else if (const CXXRecordDecl *RD = 595 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 596 // Build a DependentNameType that will perform lookup into RD at 597 // instantiation time. 598 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 599 RD->getTypeForDecl()); 600 601 // Diagnose that this identifier was undeclared, and retry the lookup during 602 // template instantiation. 603 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 604 << RD; 605 } else { 606 // This is not a situation that we should recover from. 607 return ParsedType(); 608 } 609 610 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 611 612 // Build type location information. We synthesized the qualifier, so we have 613 // to build a fake NestedNameSpecifierLoc. 614 NestedNameSpecifierLocBuilder NNSLocBuilder; 615 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 616 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 617 618 TypeLocBuilder Builder; 619 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 620 DepTL.setNameLoc(NameLoc); 621 DepTL.setElaboratedKeywordLoc(SourceLocation()); 622 DepTL.setQualifierLoc(QualifierLoc); 623 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 624 } 625 626 /// isTagName() - This method is called *for error recovery purposes only* 627 /// to determine if the specified name is a valid tag name ("struct foo"). If 628 /// so, this returns the TST for the tag corresponding to it (TST_enum, 629 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 630 /// cases in C where the user forgot to specify the tag. 631 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 632 // Do a tag name lookup in this scope. 633 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 634 LookupName(R, S, false); 635 R.suppressDiagnostics(); 636 if (R.getResultKind() == LookupResult::Found) 637 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 638 switch (TD->getTagKind()) { 639 case TTK_Struct: return DeclSpec::TST_struct; 640 case TTK_Interface: return DeclSpec::TST_interface; 641 case TTK_Union: return DeclSpec::TST_union; 642 case TTK_Class: return DeclSpec::TST_class; 643 case TTK_Enum: return DeclSpec::TST_enum; 644 } 645 } 646 647 return DeclSpec::TST_unspecified; 648 } 649 650 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 651 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 652 /// then downgrade the missing typename error to a warning. 653 /// This is needed for MSVC compatibility; Example: 654 /// @code 655 /// template<class T> class A { 656 /// public: 657 /// typedef int TYPE; 658 /// }; 659 /// template<class T> class B : public A<T> { 660 /// public: 661 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 662 /// }; 663 /// @endcode 664 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 665 if (CurContext->isRecord()) { 666 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 667 return true; 668 669 const Type *Ty = SS->getScopeRep()->getAsType(); 670 671 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 672 for (const auto &Base : RD->bases()) 673 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 674 return true; 675 return S->isFunctionPrototypeScope(); 676 } 677 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 678 } 679 680 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 681 SourceLocation IILoc, 682 Scope *S, 683 CXXScopeSpec *SS, 684 ParsedType &SuggestedType, 685 bool IsTemplateName) { 686 // Don't report typename errors for editor placeholders. 687 if (II->isEditorPlaceholder()) 688 return; 689 // We don't have anything to suggest (yet). 690 SuggestedType = nullptr; 691 692 // There may have been a typo in the name of the type. Look up typo 693 // results, in case we have something that we can suggest. 694 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 695 /*AllowTemplates=*/IsTemplateName, 696 /*AllowNonTemplates=*/!IsTemplateName); 697 if (TypoCorrection Corrected = 698 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 699 CCC, CTK_ErrorRecovery)) { 700 // FIXME: Support error recovery for the template-name case. 701 bool CanRecover = !IsTemplateName; 702 if (Corrected.isKeyword()) { 703 // We corrected to a keyword. 704 diagnoseTypo(Corrected, 705 PDiag(IsTemplateName ? diag::err_no_template_suggest 706 : diag::err_unknown_typename_suggest) 707 << II); 708 II = Corrected.getCorrectionAsIdentifierInfo(); 709 } else { 710 // We found a similarly-named type or interface; suggest that. 711 if (!SS || !SS->isSet()) { 712 diagnoseTypo(Corrected, 713 PDiag(IsTemplateName ? diag::err_no_template_suggest 714 : diag::err_unknown_typename_suggest) 715 << II, CanRecover); 716 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 717 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 718 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 719 II->getName().equals(CorrectedStr); 720 diagnoseTypo(Corrected, 721 PDiag(IsTemplateName 722 ? diag::err_no_member_template_suggest 723 : diag::err_unknown_nested_typename_suggest) 724 << II << DC << DroppedSpecifier << SS->getRange(), 725 CanRecover); 726 } else { 727 llvm_unreachable("could not have corrected a typo here"); 728 } 729 730 if (!CanRecover) 731 return; 732 733 CXXScopeSpec tmpSS; 734 if (Corrected.getCorrectionSpecifier()) 735 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 736 SourceRange(IILoc)); 737 // FIXME: Support class template argument deduction here. 738 SuggestedType = 739 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 740 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 741 /*IsCtorOrDtorName=*/false, 742 /*WantNontrivialTypeSourceInfo=*/true); 743 } 744 return; 745 } 746 747 if (getLangOpts().CPlusPlus && !IsTemplateName) { 748 // See if II is a class template that the user forgot to pass arguments to. 749 UnqualifiedId Name; 750 Name.setIdentifier(II, IILoc); 751 CXXScopeSpec EmptySS; 752 TemplateTy TemplateResult; 753 bool MemberOfUnknownSpecialization; 754 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 755 Name, nullptr, true, TemplateResult, 756 MemberOfUnknownSpecialization) == TNK_Type_template) { 757 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 758 return; 759 } 760 } 761 762 // FIXME: Should we move the logic that tries to recover from a missing tag 763 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 764 765 if (!SS || (!SS->isSet() && !SS->isInvalid())) 766 Diag(IILoc, IsTemplateName ? diag::err_no_template 767 : diag::err_unknown_typename) 768 << II; 769 else if (DeclContext *DC = computeDeclContext(*SS, false)) 770 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 771 : diag::err_typename_nested_not_found) 772 << II << DC << SS->getRange(); 773 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 774 SuggestedType = 775 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 776 } else if (isDependentScopeSpecifier(*SS)) { 777 unsigned DiagID = diag::err_typename_missing; 778 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 779 DiagID = diag::ext_typename_missing; 780 781 Diag(SS->getRange().getBegin(), DiagID) 782 << SS->getScopeRep() << II->getName() 783 << SourceRange(SS->getRange().getBegin(), IILoc) 784 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 785 SuggestedType = ActOnTypenameType(S, SourceLocation(), 786 *SS, *II, IILoc).get(); 787 } else { 788 assert(SS && SS->isInvalid() && 789 "Invalid scope specifier has already been diagnosed"); 790 } 791 } 792 793 /// Determine whether the given result set contains either a type name 794 /// or 795 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 796 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 797 NextToken.is(tok::less); 798 799 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 800 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 801 return true; 802 803 if (CheckTemplate && isa<TemplateDecl>(*I)) 804 return true; 805 } 806 807 return false; 808 } 809 810 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 811 Scope *S, CXXScopeSpec &SS, 812 IdentifierInfo *&Name, 813 SourceLocation NameLoc) { 814 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 815 SemaRef.LookupParsedName(R, S, &SS); 816 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 817 StringRef FixItTagName; 818 switch (Tag->getTagKind()) { 819 case TTK_Class: 820 FixItTagName = "class "; 821 break; 822 823 case TTK_Enum: 824 FixItTagName = "enum "; 825 break; 826 827 case TTK_Struct: 828 FixItTagName = "struct "; 829 break; 830 831 case TTK_Interface: 832 FixItTagName = "__interface "; 833 break; 834 835 case TTK_Union: 836 FixItTagName = "union "; 837 break; 838 } 839 840 StringRef TagName = FixItTagName.drop_back(); 841 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 842 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 843 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 844 845 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 846 I != IEnd; ++I) 847 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 848 << Name << TagName; 849 850 // Replace lookup results with just the tag decl. 851 Result.clear(Sema::LookupTagName); 852 SemaRef.LookupParsedName(Result, S, &SS); 853 return true; 854 } 855 856 return false; 857 } 858 859 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 860 IdentifierInfo *&Name, 861 SourceLocation NameLoc, 862 const Token &NextToken, 863 CorrectionCandidateCallback *CCC) { 864 DeclarationNameInfo NameInfo(Name, NameLoc); 865 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 866 867 assert(NextToken.isNot(tok::coloncolon) && 868 "parse nested name specifiers before calling ClassifyName"); 869 if (getLangOpts().CPlusPlus && SS.isSet() && 870 isCurrentClassName(*Name, S, &SS)) { 871 // Per [class.qual]p2, this names the constructors of SS, not the 872 // injected-class-name. We don't have a classification for that. 873 // There's not much point caching this result, since the parser 874 // will reject it later. 875 return NameClassification::Unknown(); 876 } 877 878 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 879 LookupParsedName(Result, S, &SS, !CurMethod); 880 881 if (SS.isInvalid()) 882 return NameClassification::Error(); 883 884 // For unqualified lookup in a class template in MSVC mode, look into 885 // dependent base classes where the primary class template is known. 886 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 887 if (ParsedType TypeInBase = 888 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 889 return TypeInBase; 890 } 891 892 // Perform lookup for Objective-C instance variables (including automatically 893 // synthesized instance variables), if we're in an Objective-C method. 894 // FIXME: This lookup really, really needs to be folded in to the normal 895 // unqualified lookup mechanism. 896 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 897 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 898 if (Ivar.isInvalid()) 899 return NameClassification::Error(); 900 if (Ivar.isUsable()) 901 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 902 903 // We defer builtin creation until after ivar lookup inside ObjC methods. 904 if (Result.empty()) 905 LookupBuiltin(Result); 906 } 907 908 bool SecondTry = false; 909 bool IsFilteredTemplateName = false; 910 911 Corrected: 912 switch (Result.getResultKind()) { 913 case LookupResult::NotFound: 914 // If an unqualified-id is followed by a '(', then we have a function 915 // call. 916 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 917 // In C++, this is an ADL-only call. 918 // FIXME: Reference? 919 if (getLangOpts().CPlusPlus) 920 return NameClassification::UndeclaredNonType(); 921 922 // C90 6.3.2.2: 923 // If the expression that precedes the parenthesized argument list in a 924 // function call consists solely of an identifier, and if no 925 // declaration is visible for this identifier, the identifier is 926 // implicitly declared exactly as if, in the innermost block containing 927 // the function call, the declaration 928 // 929 // extern int identifier (); 930 // 931 // appeared. 932 // 933 // We also allow this in C99 as an extension. 934 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 935 return NameClassification::NonType(D); 936 } 937 938 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 939 // In C++20 onwards, this could be an ADL-only call to a function 940 // template, and we're required to assume that this is a template name. 941 // 942 // FIXME: Find a way to still do typo correction in this case. 943 TemplateName Template = 944 Context.getAssumedTemplateName(NameInfo.getName()); 945 return NameClassification::UndeclaredTemplate(Template); 946 } 947 948 // In C, we first see whether there is a tag type by the same name, in 949 // which case it's likely that the user just forgot to write "enum", 950 // "struct", or "union". 951 if (!getLangOpts().CPlusPlus && !SecondTry && 952 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 953 break; 954 } 955 956 // Perform typo correction to determine if there is another name that is 957 // close to this name. 958 if (!SecondTry && CCC) { 959 SecondTry = true; 960 if (TypoCorrection Corrected = 961 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 962 &SS, *CCC, CTK_ErrorRecovery)) { 963 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 964 unsigned QualifiedDiag = diag::err_no_member_suggest; 965 966 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 967 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 968 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 969 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 970 UnqualifiedDiag = diag::err_no_template_suggest; 971 QualifiedDiag = diag::err_no_member_template_suggest; 972 } else if (UnderlyingFirstDecl && 973 (isa<TypeDecl>(UnderlyingFirstDecl) || 974 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 975 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 976 UnqualifiedDiag = diag::err_unknown_typename_suggest; 977 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 978 } 979 980 if (SS.isEmpty()) { 981 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 982 } else {// FIXME: is this even reachable? Test it. 983 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 984 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 985 Name->getName().equals(CorrectedStr); 986 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 987 << Name << computeDeclContext(SS, false) 988 << DroppedSpecifier << SS.getRange()); 989 } 990 991 // Update the name, so that the caller has the new name. 992 Name = Corrected.getCorrectionAsIdentifierInfo(); 993 994 // Typo correction corrected to a keyword. 995 if (Corrected.isKeyword()) 996 return Name; 997 998 // Also update the LookupResult... 999 // FIXME: This should probably go away at some point 1000 Result.clear(); 1001 Result.setLookupName(Corrected.getCorrection()); 1002 if (FirstDecl) 1003 Result.addDecl(FirstDecl); 1004 1005 // If we found an Objective-C instance variable, let 1006 // LookupInObjCMethod build the appropriate expression to 1007 // reference the ivar. 1008 // FIXME: This is a gross hack. 1009 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1010 DeclResult R = 1011 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1012 if (R.isInvalid()) 1013 return NameClassification::Error(); 1014 if (R.isUsable()) 1015 return NameClassification::NonType(Ivar); 1016 } 1017 1018 goto Corrected; 1019 } 1020 } 1021 1022 // We failed to correct; just fall through and let the parser deal with it. 1023 Result.suppressDiagnostics(); 1024 return NameClassification::Unknown(); 1025 1026 case LookupResult::NotFoundInCurrentInstantiation: { 1027 // We performed name lookup into the current instantiation, and there were 1028 // dependent bases, so we treat this result the same way as any other 1029 // dependent nested-name-specifier. 1030 1031 // C++ [temp.res]p2: 1032 // A name used in a template declaration or definition and that is 1033 // dependent on a template-parameter is assumed not to name a type 1034 // unless the applicable name lookup finds a type name or the name is 1035 // qualified by the keyword typename. 1036 // 1037 // FIXME: If the next token is '<', we might want to ask the parser to 1038 // perform some heroics to see if we actually have a 1039 // template-argument-list, which would indicate a missing 'template' 1040 // keyword here. 1041 return NameClassification::DependentNonType(); 1042 } 1043 1044 case LookupResult::Found: 1045 case LookupResult::FoundOverloaded: 1046 case LookupResult::FoundUnresolvedValue: 1047 break; 1048 1049 case LookupResult::Ambiguous: 1050 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1051 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1052 /*AllowDependent=*/false)) { 1053 // C++ [temp.local]p3: 1054 // A lookup that finds an injected-class-name (10.2) can result in an 1055 // ambiguity in certain cases (for example, if it is found in more than 1056 // one base class). If all of the injected-class-names that are found 1057 // refer to specializations of the same class template, and if the name 1058 // is followed by a template-argument-list, the reference refers to the 1059 // class template itself and not a specialization thereof, and is not 1060 // ambiguous. 1061 // 1062 // This filtering can make an ambiguous result into an unambiguous one, 1063 // so try again after filtering out template names. 1064 FilterAcceptableTemplateNames(Result); 1065 if (!Result.isAmbiguous()) { 1066 IsFilteredTemplateName = true; 1067 break; 1068 } 1069 } 1070 1071 // Diagnose the ambiguity and return an error. 1072 return NameClassification::Error(); 1073 } 1074 1075 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1076 (IsFilteredTemplateName || 1077 hasAnyAcceptableTemplateNames( 1078 Result, /*AllowFunctionTemplates=*/true, 1079 /*AllowDependent=*/false, 1080 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1081 getLangOpts().CPlusPlus20))) { 1082 // C++ [temp.names]p3: 1083 // After name lookup (3.4) finds that a name is a template-name or that 1084 // an operator-function-id or a literal- operator-id refers to a set of 1085 // overloaded functions any member of which is a function template if 1086 // this is followed by a <, the < is always taken as the delimiter of a 1087 // template-argument-list and never as the less-than operator. 1088 // C++2a [temp.names]p2: 1089 // A name is also considered to refer to a template if it is an 1090 // unqualified-id followed by a < and name lookup finds either one 1091 // or more functions or finds nothing. 1092 if (!IsFilteredTemplateName) 1093 FilterAcceptableTemplateNames(Result); 1094 1095 bool IsFunctionTemplate; 1096 bool IsVarTemplate; 1097 TemplateName Template; 1098 if (Result.end() - Result.begin() > 1) { 1099 IsFunctionTemplate = true; 1100 Template = Context.getOverloadedTemplateName(Result.begin(), 1101 Result.end()); 1102 } else if (!Result.empty()) { 1103 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1104 *Result.begin(), /*AllowFunctionTemplates=*/true, 1105 /*AllowDependent=*/false)); 1106 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1107 IsVarTemplate = isa<VarTemplateDecl>(TD); 1108 1109 if (SS.isNotEmpty()) 1110 Template = 1111 Context.getQualifiedTemplateName(SS.getScopeRep(), 1112 /*TemplateKeyword=*/false, TD); 1113 else 1114 Template = TemplateName(TD); 1115 } else { 1116 // All results were non-template functions. This is a function template 1117 // name. 1118 IsFunctionTemplate = true; 1119 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1120 } 1121 1122 if (IsFunctionTemplate) { 1123 // Function templates always go through overload resolution, at which 1124 // point we'll perform the various checks (e.g., accessibility) we need 1125 // to based on which function we selected. 1126 Result.suppressDiagnostics(); 1127 1128 return NameClassification::FunctionTemplate(Template); 1129 } 1130 1131 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1132 : NameClassification::TypeTemplate(Template); 1133 } 1134 1135 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) { 1136 QualType T = Context.getTypeDeclType(Type); 1137 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) 1138 T = Context.getUsingType(USD, T); 1139 1140 if (SS.isEmpty()) // No elaborated type, trivial location info 1141 return ParsedType::make(T); 1142 1143 TypeLocBuilder Builder; 1144 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 1145 T = getElaboratedType(ETK_None, SS, T); 1146 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 1147 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 1148 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 1149 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 1150 }; 1151 1152 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1153 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1154 DiagnoseUseOfDecl(Type, NameLoc); 1155 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1156 return BuildTypeFor(Type, *Result.begin()); 1157 } 1158 1159 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1160 if (!Class) { 1161 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1162 if (ObjCCompatibleAliasDecl *Alias = 1163 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1164 Class = Alias->getClassInterface(); 1165 } 1166 1167 if (Class) { 1168 DiagnoseUseOfDecl(Class, NameLoc); 1169 1170 if (NextToken.is(tok::period)) { 1171 // Interface. <something> is parsed as a property reference expression. 1172 // Just return "unknown" as a fall-through for now. 1173 Result.suppressDiagnostics(); 1174 return NameClassification::Unknown(); 1175 } 1176 1177 QualType T = Context.getObjCInterfaceType(Class); 1178 return ParsedType::make(T); 1179 } 1180 1181 if (isa<ConceptDecl>(FirstDecl)) 1182 return NameClassification::Concept( 1183 TemplateName(cast<TemplateDecl>(FirstDecl))); 1184 1185 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { 1186 (void)DiagnoseUseOfDecl(EmptyD, NameLoc); 1187 return NameClassification::Error(); 1188 } 1189 1190 // We can have a type template here if we're classifying a template argument. 1191 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1192 !isa<VarTemplateDecl>(FirstDecl)) 1193 return NameClassification::TypeTemplate( 1194 TemplateName(cast<TemplateDecl>(FirstDecl))); 1195 1196 // Check for a tag type hidden by a non-type decl in a few cases where it 1197 // seems likely a type is wanted instead of the non-type that was found. 1198 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1199 if ((NextToken.is(tok::identifier) || 1200 (NextIsOp && 1201 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1202 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1203 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1204 DiagnoseUseOfDecl(Type, NameLoc); 1205 return BuildTypeFor(Type, *Result.begin()); 1206 } 1207 1208 // If we already know which single declaration is referenced, just annotate 1209 // that declaration directly. Defer resolving even non-overloaded class 1210 // member accesses, as we need to defer certain access checks until we know 1211 // the context. 1212 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1213 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1214 return NameClassification::NonType(Result.getRepresentativeDecl()); 1215 1216 // Otherwise, this is an overload set that we will need to resolve later. 1217 Result.suppressDiagnostics(); 1218 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1219 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1220 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1221 Result.begin(), Result.end())); 1222 } 1223 1224 ExprResult 1225 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1226 SourceLocation NameLoc) { 1227 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1228 CXXScopeSpec SS; 1229 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1230 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1231 } 1232 1233 ExprResult 1234 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1235 IdentifierInfo *Name, 1236 SourceLocation NameLoc, 1237 bool IsAddressOfOperand) { 1238 DeclarationNameInfo NameInfo(Name, NameLoc); 1239 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1240 NameInfo, IsAddressOfOperand, 1241 /*TemplateArgs=*/nullptr); 1242 } 1243 1244 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1245 NamedDecl *Found, 1246 SourceLocation NameLoc, 1247 const Token &NextToken) { 1248 if (getCurMethodDecl() && SS.isEmpty()) 1249 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1250 return BuildIvarRefExpr(S, NameLoc, Ivar); 1251 1252 // Reconstruct the lookup result. 1253 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1254 Result.addDecl(Found); 1255 Result.resolveKind(); 1256 1257 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1258 return BuildDeclarationNameExpr(SS, Result, ADL); 1259 } 1260 1261 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1262 // For an implicit class member access, transform the result into a member 1263 // access expression if necessary. 1264 auto *ULE = cast<UnresolvedLookupExpr>(E); 1265 if ((*ULE->decls_begin())->isCXXClassMember()) { 1266 CXXScopeSpec SS; 1267 SS.Adopt(ULE->getQualifierLoc()); 1268 1269 // Reconstruct the lookup result. 1270 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1271 LookupOrdinaryName); 1272 Result.setNamingClass(ULE->getNamingClass()); 1273 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1274 Result.addDecl(*I, I.getAccess()); 1275 Result.resolveKind(); 1276 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1277 nullptr, S); 1278 } 1279 1280 // Otherwise, this is already in the form we needed, and no further checks 1281 // are necessary. 1282 return ULE; 1283 } 1284 1285 Sema::TemplateNameKindForDiagnostics 1286 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1287 auto *TD = Name.getAsTemplateDecl(); 1288 if (!TD) 1289 return TemplateNameKindForDiagnostics::DependentTemplate; 1290 if (isa<ClassTemplateDecl>(TD)) 1291 return TemplateNameKindForDiagnostics::ClassTemplate; 1292 if (isa<FunctionTemplateDecl>(TD)) 1293 return TemplateNameKindForDiagnostics::FunctionTemplate; 1294 if (isa<VarTemplateDecl>(TD)) 1295 return TemplateNameKindForDiagnostics::VarTemplate; 1296 if (isa<TypeAliasTemplateDecl>(TD)) 1297 return TemplateNameKindForDiagnostics::AliasTemplate; 1298 if (isa<TemplateTemplateParmDecl>(TD)) 1299 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1300 if (isa<ConceptDecl>(TD)) 1301 return TemplateNameKindForDiagnostics::Concept; 1302 return TemplateNameKindForDiagnostics::DependentTemplate; 1303 } 1304 1305 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1306 assert(DC->getLexicalParent() == CurContext && 1307 "The next DeclContext should be lexically contained in the current one."); 1308 CurContext = DC; 1309 S->setEntity(DC); 1310 } 1311 1312 void Sema::PopDeclContext() { 1313 assert(CurContext && "DeclContext imbalance!"); 1314 1315 CurContext = CurContext->getLexicalParent(); 1316 assert(CurContext && "Popped translation unit!"); 1317 } 1318 1319 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1320 Decl *D) { 1321 // Unlike PushDeclContext, the context to which we return is not necessarily 1322 // the containing DC of TD, because the new context will be some pre-existing 1323 // TagDecl definition instead of a fresh one. 1324 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1325 CurContext = cast<TagDecl>(D)->getDefinition(); 1326 assert(CurContext && "skipping definition of undefined tag"); 1327 // Start lookups from the parent of the current context; we don't want to look 1328 // into the pre-existing complete definition. 1329 S->setEntity(CurContext->getLookupParent()); 1330 return Result; 1331 } 1332 1333 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1334 CurContext = static_cast<decltype(CurContext)>(Context); 1335 } 1336 1337 /// EnterDeclaratorContext - Used when we must lookup names in the context 1338 /// of a declarator's nested name specifier. 1339 /// 1340 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1341 // C++0x [basic.lookup.unqual]p13: 1342 // A name used in the definition of a static data member of class 1343 // X (after the qualified-id of the static member) is looked up as 1344 // if the name was used in a member function of X. 1345 // C++0x [basic.lookup.unqual]p14: 1346 // If a variable member of a namespace is defined outside of the 1347 // scope of its namespace then any name used in the definition of 1348 // the variable member (after the declarator-id) is looked up as 1349 // if the definition of the variable member occurred in its 1350 // namespace. 1351 // Both of these imply that we should push a scope whose context 1352 // is the semantic context of the declaration. We can't use 1353 // PushDeclContext here because that context is not necessarily 1354 // lexically contained in the current context. Fortunately, 1355 // the containing scope should have the appropriate information. 1356 1357 assert(!S->getEntity() && "scope already has entity"); 1358 1359 #ifndef NDEBUG 1360 Scope *Ancestor = S->getParent(); 1361 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1362 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1363 #endif 1364 1365 CurContext = DC; 1366 S->setEntity(DC); 1367 1368 if (S->getParent()->isTemplateParamScope()) { 1369 // Also set the corresponding entities for all immediately-enclosing 1370 // template parameter scopes. 1371 EnterTemplatedContext(S->getParent(), DC); 1372 } 1373 } 1374 1375 void Sema::ExitDeclaratorContext(Scope *S) { 1376 assert(S->getEntity() == CurContext && "Context imbalance!"); 1377 1378 // Switch back to the lexical context. The safety of this is 1379 // enforced by an assert in EnterDeclaratorContext. 1380 Scope *Ancestor = S->getParent(); 1381 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1382 CurContext = Ancestor->getEntity(); 1383 1384 // We don't need to do anything with the scope, which is going to 1385 // disappear. 1386 } 1387 1388 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1389 assert(S->isTemplateParamScope() && 1390 "expected to be initializing a template parameter scope"); 1391 1392 // C++20 [temp.local]p7: 1393 // In the definition of a member of a class template that appears outside 1394 // of the class template definition, the name of a member of the class 1395 // template hides the name of a template-parameter of any enclosing class 1396 // templates (but not a template-parameter of the member if the member is a 1397 // class or function template). 1398 // C++20 [temp.local]p9: 1399 // In the definition of a class template or in the definition of a member 1400 // of such a template that appears outside of the template definition, for 1401 // each non-dependent base class (13.8.2.1), if the name of the base class 1402 // or the name of a member of the base class is the same as the name of a 1403 // template-parameter, the base class name or member name hides the 1404 // template-parameter name (6.4.10). 1405 // 1406 // This means that a template parameter scope should be searched immediately 1407 // after searching the DeclContext for which it is a template parameter 1408 // scope. For example, for 1409 // template<typename T> template<typename U> template<typename V> 1410 // void N::A<T>::B<U>::f(...) 1411 // we search V then B<U> (and base classes) then U then A<T> (and base 1412 // classes) then T then N then ::. 1413 unsigned ScopeDepth = getTemplateDepth(S); 1414 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1415 DeclContext *SearchDCAfterScope = DC; 1416 for (; DC; DC = DC->getLookupParent()) { 1417 if (const TemplateParameterList *TPL = 1418 cast<Decl>(DC)->getDescribedTemplateParams()) { 1419 unsigned DCDepth = TPL->getDepth() + 1; 1420 if (DCDepth > ScopeDepth) 1421 continue; 1422 if (ScopeDepth == DCDepth) 1423 SearchDCAfterScope = DC = DC->getLookupParent(); 1424 break; 1425 } 1426 } 1427 S->setLookupEntity(SearchDCAfterScope); 1428 } 1429 } 1430 1431 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1432 // We assume that the caller has already called 1433 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1434 FunctionDecl *FD = D->getAsFunction(); 1435 if (!FD) 1436 return; 1437 1438 // Same implementation as PushDeclContext, but enters the context 1439 // from the lexical parent, rather than the top-level class. 1440 assert(CurContext == FD->getLexicalParent() && 1441 "The next DeclContext should be lexically contained in the current one."); 1442 CurContext = FD; 1443 S->setEntity(CurContext); 1444 1445 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1446 ParmVarDecl *Param = FD->getParamDecl(P); 1447 // If the parameter has an identifier, then add it to the scope 1448 if (Param->getIdentifier()) { 1449 S->AddDecl(Param); 1450 IdResolver.AddDecl(Param); 1451 } 1452 } 1453 } 1454 1455 void Sema::ActOnExitFunctionContext() { 1456 // Same implementation as PopDeclContext, but returns to the lexical parent, 1457 // rather than the top-level class. 1458 assert(CurContext && "DeclContext imbalance!"); 1459 CurContext = CurContext->getLexicalParent(); 1460 assert(CurContext && "Popped translation unit!"); 1461 } 1462 1463 /// Determine whether we allow overloading of the function 1464 /// PrevDecl with another declaration. 1465 /// 1466 /// This routine determines whether overloading is possible, not 1467 /// whether some new function is actually an overload. It will return 1468 /// true in C++ (where we can always provide overloads) or, as an 1469 /// extension, in C when the previous function is already an 1470 /// overloaded function declaration or has the "overloadable" 1471 /// attribute. 1472 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1473 ASTContext &Context, 1474 const FunctionDecl *New) { 1475 if (Context.getLangOpts().CPlusPlus) 1476 return true; 1477 1478 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1479 return true; 1480 1481 return Previous.getResultKind() == LookupResult::Found && 1482 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1483 New->hasAttr<OverloadableAttr>()); 1484 } 1485 1486 /// Add this decl to the scope shadowed decl chains. 1487 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1488 // Move up the scope chain until we find the nearest enclosing 1489 // non-transparent context. The declaration will be introduced into this 1490 // scope. 1491 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1492 S = S->getParent(); 1493 1494 // Add scoped declarations into their context, so that they can be 1495 // found later. Declarations without a context won't be inserted 1496 // into any context. 1497 if (AddToContext) 1498 CurContext->addDecl(D); 1499 1500 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1501 // are function-local declarations. 1502 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1503 return; 1504 1505 // Template instantiations should also not be pushed into scope. 1506 if (isa<FunctionDecl>(D) && 1507 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1508 return; 1509 1510 // If this replaces anything in the current scope, 1511 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1512 IEnd = IdResolver.end(); 1513 for (; I != IEnd; ++I) { 1514 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1515 S->RemoveDecl(*I); 1516 IdResolver.RemoveDecl(*I); 1517 1518 // Should only need to replace one decl. 1519 break; 1520 } 1521 } 1522 1523 S->AddDecl(D); 1524 1525 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1526 // Implicitly-generated labels may end up getting generated in an order that 1527 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1528 // the label at the appropriate place in the identifier chain. 1529 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1530 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1531 if (IDC == CurContext) { 1532 if (!S->isDeclScope(*I)) 1533 continue; 1534 } else if (IDC->Encloses(CurContext)) 1535 break; 1536 } 1537 1538 IdResolver.InsertDeclAfter(I, D); 1539 } else { 1540 IdResolver.AddDecl(D); 1541 } 1542 warnOnReservedIdentifier(D); 1543 } 1544 1545 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1546 bool AllowInlineNamespace) { 1547 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1548 } 1549 1550 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1551 DeclContext *TargetDC = DC->getPrimaryContext(); 1552 do { 1553 if (DeclContext *ScopeDC = S->getEntity()) 1554 if (ScopeDC->getPrimaryContext() == TargetDC) 1555 return S; 1556 } while ((S = S->getParent())); 1557 1558 return nullptr; 1559 } 1560 1561 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1562 DeclContext*, 1563 ASTContext&); 1564 1565 /// Filters out lookup results that don't fall within the given scope 1566 /// as determined by isDeclInScope. 1567 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1568 bool ConsiderLinkage, 1569 bool AllowInlineNamespace) { 1570 LookupResult::Filter F = R.makeFilter(); 1571 while (F.hasNext()) { 1572 NamedDecl *D = F.next(); 1573 1574 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1575 continue; 1576 1577 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1578 continue; 1579 1580 F.erase(); 1581 } 1582 1583 F.done(); 1584 } 1585 1586 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1587 /// have compatible owning modules. 1588 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1589 // FIXME: The Modules TS is not clear about how friend declarations are 1590 // to be treated. It's not meaningful to have different owning modules for 1591 // linkage in redeclarations of the same entity, so for now allow the 1592 // redeclaration and change the owning modules to match. 1593 if (New->getFriendObjectKind() && 1594 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1595 New->setLocalOwningModule(Old->getOwningModule()); 1596 makeMergedDefinitionVisible(New); 1597 return false; 1598 } 1599 1600 Module *NewM = New->getOwningModule(); 1601 Module *OldM = Old->getOwningModule(); 1602 1603 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1604 NewM = NewM->Parent; 1605 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1606 OldM = OldM->Parent; 1607 1608 if (NewM == OldM) 1609 return false; 1610 1611 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1612 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1613 if (NewIsModuleInterface || OldIsModuleInterface) { 1614 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1615 // if a declaration of D [...] appears in the purview of a module, all 1616 // other such declarations shall appear in the purview of the same module 1617 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1618 << New 1619 << NewIsModuleInterface 1620 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1621 << OldIsModuleInterface 1622 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1623 Diag(Old->getLocation(), diag::note_previous_declaration); 1624 New->setInvalidDecl(); 1625 return true; 1626 } 1627 1628 return false; 1629 } 1630 1631 // [module.interface]p6: 1632 // A redeclaration of an entity X is implicitly exported if X was introduced by 1633 // an exported declaration; otherwise it shall not be exported. 1634 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) { 1635 bool IsNewExported = New->isInExportDeclContext(); 1636 bool IsOldExported = Old->isInExportDeclContext(); 1637 1638 // It should be irrevelant if both of them are not exported. 1639 if (!IsNewExported && !IsOldExported) 1640 return false; 1641 1642 if (IsOldExported) 1643 return false; 1644 1645 assert(IsNewExported); 1646 1647 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New; 1648 Diag(Old->getLocation(), diag::note_previous_declaration); 1649 return true; 1650 } 1651 1652 // A wrapper function for checking the semantic restrictions of 1653 // a redeclaration within a module. 1654 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) { 1655 if (CheckRedeclarationModuleOwnership(New, Old)) 1656 return true; 1657 1658 if (CheckRedeclarationExported(New, Old)) 1659 return true; 1660 1661 return false; 1662 } 1663 1664 static bool isUsingDecl(NamedDecl *D) { 1665 return isa<UsingShadowDecl>(D) || 1666 isa<UnresolvedUsingTypenameDecl>(D) || 1667 isa<UnresolvedUsingValueDecl>(D); 1668 } 1669 1670 /// Removes using shadow declarations from the lookup results. 1671 static void RemoveUsingDecls(LookupResult &R) { 1672 LookupResult::Filter F = R.makeFilter(); 1673 while (F.hasNext()) 1674 if (isUsingDecl(F.next())) 1675 F.erase(); 1676 1677 F.done(); 1678 } 1679 1680 /// Check for this common pattern: 1681 /// @code 1682 /// class S { 1683 /// S(const S&); // DO NOT IMPLEMENT 1684 /// void operator=(const S&); // DO NOT IMPLEMENT 1685 /// }; 1686 /// @endcode 1687 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1688 // FIXME: Should check for private access too but access is set after we get 1689 // the decl here. 1690 if (D->doesThisDeclarationHaveABody()) 1691 return false; 1692 1693 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1694 return CD->isCopyConstructor(); 1695 return D->isCopyAssignmentOperator(); 1696 } 1697 1698 // We need this to handle 1699 // 1700 // typedef struct { 1701 // void *foo() { return 0; } 1702 // } A; 1703 // 1704 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1705 // for example. If 'A', foo will have external linkage. If we have '*A', 1706 // foo will have no linkage. Since we can't know until we get to the end 1707 // of the typedef, this function finds out if D might have non-external linkage. 1708 // Callers should verify at the end of the TU if it D has external linkage or 1709 // not. 1710 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1711 const DeclContext *DC = D->getDeclContext(); 1712 while (!DC->isTranslationUnit()) { 1713 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1714 if (!RD->hasNameForLinkage()) 1715 return true; 1716 } 1717 DC = DC->getParent(); 1718 } 1719 1720 return !D->isExternallyVisible(); 1721 } 1722 1723 // FIXME: This needs to be refactored; some other isInMainFile users want 1724 // these semantics. 1725 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1726 if (S.TUKind != TU_Complete) 1727 return false; 1728 return S.SourceMgr.isInMainFile(Loc); 1729 } 1730 1731 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1732 assert(D); 1733 1734 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1735 return false; 1736 1737 // Ignore all entities declared within templates, and out-of-line definitions 1738 // of members of class templates. 1739 if (D->getDeclContext()->isDependentContext() || 1740 D->getLexicalDeclContext()->isDependentContext()) 1741 return false; 1742 1743 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1744 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1745 return false; 1746 // A non-out-of-line declaration of a member specialization was implicitly 1747 // instantiated; it's the out-of-line declaration that we're interested in. 1748 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1749 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1750 return false; 1751 1752 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1753 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1754 return false; 1755 } else { 1756 // 'static inline' functions are defined in headers; don't warn. 1757 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1758 return false; 1759 } 1760 1761 if (FD->doesThisDeclarationHaveABody() && 1762 Context.DeclMustBeEmitted(FD)) 1763 return false; 1764 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1765 // Constants and utility variables are defined in headers with internal 1766 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1767 // like "inline".) 1768 if (!isMainFileLoc(*this, VD->getLocation())) 1769 return false; 1770 1771 if (Context.DeclMustBeEmitted(VD)) 1772 return false; 1773 1774 if (VD->isStaticDataMember() && 1775 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1776 return false; 1777 if (VD->isStaticDataMember() && 1778 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1779 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1780 return false; 1781 1782 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1783 return false; 1784 } else { 1785 return false; 1786 } 1787 1788 // Only warn for unused decls internal to the translation unit. 1789 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1790 // for inline functions defined in the main source file, for instance. 1791 return mightHaveNonExternalLinkage(D); 1792 } 1793 1794 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1795 if (!D) 1796 return; 1797 1798 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1799 const FunctionDecl *First = FD->getFirstDecl(); 1800 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1801 return; // First should already be in the vector. 1802 } 1803 1804 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1805 const VarDecl *First = VD->getFirstDecl(); 1806 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1807 return; // First should already be in the vector. 1808 } 1809 1810 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1811 UnusedFileScopedDecls.push_back(D); 1812 } 1813 1814 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1815 if (D->isInvalidDecl()) 1816 return false; 1817 1818 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1819 // For a decomposition declaration, warn if none of the bindings are 1820 // referenced, instead of if the variable itself is referenced (which 1821 // it is, by the bindings' expressions). 1822 for (auto *BD : DD->bindings()) 1823 if (BD->isReferenced()) 1824 return false; 1825 } else if (!D->getDeclName()) { 1826 return false; 1827 } else if (D->isReferenced() || D->isUsed()) { 1828 return false; 1829 } 1830 1831 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1832 return false; 1833 1834 if (isa<LabelDecl>(D)) 1835 return true; 1836 1837 // Except for labels, we only care about unused decls that are local to 1838 // functions. 1839 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1840 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1841 // For dependent types, the diagnostic is deferred. 1842 WithinFunction = 1843 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1844 if (!WithinFunction) 1845 return false; 1846 1847 if (isa<TypedefNameDecl>(D)) 1848 return true; 1849 1850 // White-list anything that isn't a local variable. 1851 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1852 return false; 1853 1854 // Types of valid local variables should be complete, so this should succeed. 1855 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1856 1857 // White-list anything with an __attribute__((unused)) type. 1858 const auto *Ty = VD->getType().getTypePtr(); 1859 1860 // Only look at the outermost level of typedef. 1861 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1862 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1863 return false; 1864 } 1865 1866 // If we failed to complete the type for some reason, or if the type is 1867 // dependent, don't diagnose the variable. 1868 if (Ty->isIncompleteType() || Ty->isDependentType()) 1869 return false; 1870 1871 // Look at the element type to ensure that the warning behaviour is 1872 // consistent for both scalars and arrays. 1873 Ty = Ty->getBaseElementTypeUnsafe(); 1874 1875 if (const TagType *TT = Ty->getAs<TagType>()) { 1876 const TagDecl *Tag = TT->getDecl(); 1877 if (Tag->hasAttr<UnusedAttr>()) 1878 return false; 1879 1880 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1881 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1882 return false; 1883 1884 if (const Expr *Init = VD->getInit()) { 1885 if (const ExprWithCleanups *Cleanups = 1886 dyn_cast<ExprWithCleanups>(Init)) 1887 Init = Cleanups->getSubExpr(); 1888 const CXXConstructExpr *Construct = 1889 dyn_cast<CXXConstructExpr>(Init); 1890 if (Construct && !Construct->isElidable()) { 1891 CXXConstructorDecl *CD = Construct->getConstructor(); 1892 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1893 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1894 return false; 1895 } 1896 1897 // Suppress the warning if we don't know how this is constructed, and 1898 // it could possibly be non-trivial constructor. 1899 if (Init->isTypeDependent()) 1900 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1901 if (!Ctor->isTrivial()) 1902 return false; 1903 } 1904 } 1905 } 1906 1907 // TODO: __attribute__((unused)) templates? 1908 } 1909 1910 return true; 1911 } 1912 1913 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1914 FixItHint &Hint) { 1915 if (isa<LabelDecl>(D)) { 1916 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1917 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1918 true); 1919 if (AfterColon.isInvalid()) 1920 return; 1921 Hint = FixItHint::CreateRemoval( 1922 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1923 } 1924 } 1925 1926 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1927 if (D->getTypeForDecl()->isDependentType()) 1928 return; 1929 1930 for (auto *TmpD : D->decls()) { 1931 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1932 DiagnoseUnusedDecl(T); 1933 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1934 DiagnoseUnusedNestedTypedefs(R); 1935 } 1936 } 1937 1938 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1939 /// unless they are marked attr(unused). 1940 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1941 if (!ShouldDiagnoseUnusedDecl(D)) 1942 return; 1943 1944 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1945 // typedefs can be referenced later on, so the diagnostics are emitted 1946 // at end-of-translation-unit. 1947 UnusedLocalTypedefNameCandidates.insert(TD); 1948 return; 1949 } 1950 1951 FixItHint Hint; 1952 GenerateFixForUnusedDecl(D, Context, Hint); 1953 1954 unsigned DiagID; 1955 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1956 DiagID = diag::warn_unused_exception_param; 1957 else if (isa<LabelDecl>(D)) 1958 DiagID = diag::warn_unused_label; 1959 else 1960 DiagID = diag::warn_unused_variable; 1961 1962 Diag(D->getLocation(), DiagID) << D << Hint; 1963 } 1964 1965 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { 1966 // If it's not referenced, it can't be set. If it has the Cleanup attribute, 1967 // it's not really unused. 1968 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() || 1969 VD->hasAttr<CleanupAttr>()) 1970 return; 1971 1972 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 1973 1974 if (Ty->isReferenceType() || Ty->isDependentType()) 1975 return; 1976 1977 if (const TagType *TT = Ty->getAs<TagType>()) { 1978 const TagDecl *Tag = TT->getDecl(); 1979 if (Tag->hasAttr<UnusedAttr>()) 1980 return; 1981 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 1982 // mimic gcc's behavior. 1983 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1984 if (!RD->hasAttr<WarnUnusedAttr>()) 1985 return; 1986 } 1987 } 1988 1989 // Don't warn about __block Objective-C pointer variables, as they might 1990 // be assigned in the block but not used elsewhere for the purpose of lifetime 1991 // extension. 1992 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) 1993 return; 1994 1995 auto iter = RefsMinusAssignments.find(VD); 1996 if (iter == RefsMinusAssignments.end()) 1997 return; 1998 1999 assert(iter->getSecond() >= 0 && 2000 "Found a negative number of references to a VarDecl"); 2001 if (iter->getSecond() != 0) 2002 return; 2003 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 2004 : diag::warn_unused_but_set_variable; 2005 Diag(VD->getLocation(), DiagID) << VD; 2006 } 2007 2008 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 2009 // Verify that we have no forward references left. If so, there was a goto 2010 // or address of a label taken, but no definition of it. Label fwd 2011 // definitions are indicated with a null substmt which is also not a resolved 2012 // MS inline assembly label name. 2013 bool Diagnose = false; 2014 if (L->isMSAsmLabel()) 2015 Diagnose = !L->isResolvedMSAsmLabel(); 2016 else 2017 Diagnose = L->getStmt() == nullptr; 2018 if (Diagnose) 2019 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 2020 } 2021 2022 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 2023 S->mergeNRVOIntoParent(); 2024 2025 if (S->decl_empty()) return; 2026 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 2027 "Scope shouldn't contain decls!"); 2028 2029 for (auto *TmpD : S->decls()) { 2030 assert(TmpD && "This decl didn't get pushed??"); 2031 2032 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 2033 NamedDecl *D = cast<NamedDecl>(TmpD); 2034 2035 // Diagnose unused variables in this scope. 2036 if (!S->hasUnrecoverableErrorOccurred()) { 2037 DiagnoseUnusedDecl(D); 2038 if (const auto *RD = dyn_cast<RecordDecl>(D)) 2039 DiagnoseUnusedNestedTypedefs(RD); 2040 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2041 DiagnoseUnusedButSetDecl(VD); 2042 RefsMinusAssignments.erase(VD); 2043 } 2044 } 2045 2046 if (!D->getDeclName()) continue; 2047 2048 // If this was a forward reference to a label, verify it was defined. 2049 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 2050 CheckPoppedLabel(LD, *this); 2051 2052 // Remove this name from our lexical scope, and warn on it if we haven't 2053 // already. 2054 IdResolver.RemoveDecl(D); 2055 auto ShadowI = ShadowingDecls.find(D); 2056 if (ShadowI != ShadowingDecls.end()) { 2057 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2058 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 2059 << D << FD << FD->getParent(); 2060 Diag(FD->getLocation(), diag::note_previous_declaration); 2061 } 2062 ShadowingDecls.erase(ShadowI); 2063 } 2064 } 2065 } 2066 2067 /// Look for an Objective-C class in the translation unit. 2068 /// 2069 /// \param Id The name of the Objective-C class we're looking for. If 2070 /// typo-correction fixes this name, the Id will be updated 2071 /// to the fixed name. 2072 /// 2073 /// \param IdLoc The location of the name in the translation unit. 2074 /// 2075 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2076 /// if there is no class with the given name. 2077 /// 2078 /// \returns The declaration of the named Objective-C class, or NULL if the 2079 /// class could not be found. 2080 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2081 SourceLocation IdLoc, 2082 bool DoTypoCorrection) { 2083 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2084 // creation from this context. 2085 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2086 2087 if (!IDecl && DoTypoCorrection) { 2088 // Perform typo correction at the given location, but only if we 2089 // find an Objective-C class name. 2090 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2091 if (TypoCorrection C = 2092 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2093 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2094 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2095 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2096 Id = IDecl->getIdentifier(); 2097 } 2098 } 2099 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2100 // This routine must always return a class definition, if any. 2101 if (Def && Def->getDefinition()) 2102 Def = Def->getDefinition(); 2103 return Def; 2104 } 2105 2106 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2107 /// from S, where a non-field would be declared. This routine copes 2108 /// with the difference between C and C++ scoping rules in structs and 2109 /// unions. For example, the following code is well-formed in C but 2110 /// ill-formed in C++: 2111 /// @code 2112 /// struct S6 { 2113 /// enum { BAR } e; 2114 /// }; 2115 /// 2116 /// void test_S6() { 2117 /// struct S6 a; 2118 /// a.e = BAR; 2119 /// } 2120 /// @endcode 2121 /// For the declaration of BAR, this routine will return a different 2122 /// scope. The scope S will be the scope of the unnamed enumeration 2123 /// within S6. In C++, this routine will return the scope associated 2124 /// with S6, because the enumeration's scope is a transparent 2125 /// context but structures can contain non-field names. In C, this 2126 /// routine will return the translation unit scope, since the 2127 /// enumeration's scope is a transparent context and structures cannot 2128 /// contain non-field names. 2129 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2130 while (((S->getFlags() & Scope::DeclScope) == 0) || 2131 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2132 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2133 S = S->getParent(); 2134 return S; 2135 } 2136 2137 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2138 ASTContext::GetBuiltinTypeError Error) { 2139 switch (Error) { 2140 case ASTContext::GE_None: 2141 return ""; 2142 case ASTContext::GE_Missing_type: 2143 return BuiltinInfo.getHeaderName(ID); 2144 case ASTContext::GE_Missing_stdio: 2145 return "stdio.h"; 2146 case ASTContext::GE_Missing_setjmp: 2147 return "setjmp.h"; 2148 case ASTContext::GE_Missing_ucontext: 2149 return "ucontext.h"; 2150 } 2151 llvm_unreachable("unhandled error kind"); 2152 } 2153 2154 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2155 unsigned ID, SourceLocation Loc) { 2156 DeclContext *Parent = Context.getTranslationUnitDecl(); 2157 2158 if (getLangOpts().CPlusPlus) { 2159 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2160 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2161 CLinkageDecl->setImplicit(); 2162 Parent->addDecl(CLinkageDecl); 2163 Parent = CLinkageDecl; 2164 } 2165 2166 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2167 /*TInfo=*/nullptr, SC_Extern, 2168 getCurFPFeatures().isFPConstrained(), 2169 false, Type->isFunctionProtoType()); 2170 New->setImplicit(); 2171 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2172 2173 // Create Decl objects for each parameter, adding them to the 2174 // FunctionDecl. 2175 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2176 SmallVector<ParmVarDecl *, 16> Params; 2177 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2178 ParmVarDecl *parm = ParmVarDecl::Create( 2179 Context, New, SourceLocation(), SourceLocation(), nullptr, 2180 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2181 parm->setScopeInfo(0, i); 2182 Params.push_back(parm); 2183 } 2184 New->setParams(Params); 2185 } 2186 2187 AddKnownFunctionAttributes(New); 2188 return New; 2189 } 2190 2191 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2192 /// file scope. lazily create a decl for it. ForRedeclaration is true 2193 /// if we're creating this built-in in anticipation of redeclaring the 2194 /// built-in. 2195 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2196 Scope *S, bool ForRedeclaration, 2197 SourceLocation Loc) { 2198 LookupNecessaryTypesForBuiltin(S, ID); 2199 2200 ASTContext::GetBuiltinTypeError Error; 2201 QualType R = Context.GetBuiltinType(ID, Error); 2202 if (Error) { 2203 if (!ForRedeclaration) 2204 return nullptr; 2205 2206 // If we have a builtin without an associated type we should not emit a 2207 // warning when we were not able to find a type for it. 2208 if (Error == ASTContext::GE_Missing_type || 2209 Context.BuiltinInfo.allowTypeMismatch(ID)) 2210 return nullptr; 2211 2212 // If we could not find a type for setjmp it is because the jmp_buf type was 2213 // not defined prior to the setjmp declaration. 2214 if (Error == ASTContext::GE_Missing_setjmp) { 2215 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2216 << Context.BuiltinInfo.getName(ID); 2217 return nullptr; 2218 } 2219 2220 // Generally, we emit a warning that the declaration requires the 2221 // appropriate header. 2222 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2223 << getHeaderName(Context.BuiltinInfo, ID, Error) 2224 << Context.BuiltinInfo.getName(ID); 2225 return nullptr; 2226 } 2227 2228 if (!ForRedeclaration && 2229 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2230 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2231 Diag(Loc, diag::ext_implicit_lib_function_decl) 2232 << Context.BuiltinInfo.getName(ID) << R; 2233 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2234 Diag(Loc, diag::note_include_header_or_declare) 2235 << Header << Context.BuiltinInfo.getName(ID); 2236 } 2237 2238 if (R.isNull()) 2239 return nullptr; 2240 2241 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2242 RegisterLocallyScopedExternCDecl(New, S); 2243 2244 // TUScope is the translation-unit scope to insert this function into. 2245 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2246 // relate Scopes to DeclContexts, and probably eliminate CurContext 2247 // entirely, but we're not there yet. 2248 DeclContext *SavedContext = CurContext; 2249 CurContext = New->getDeclContext(); 2250 PushOnScopeChains(New, TUScope); 2251 CurContext = SavedContext; 2252 return New; 2253 } 2254 2255 /// Typedef declarations don't have linkage, but they still denote the same 2256 /// entity if their types are the same. 2257 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2258 /// isSameEntity. 2259 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2260 TypedefNameDecl *Decl, 2261 LookupResult &Previous) { 2262 // This is only interesting when modules are enabled. 2263 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2264 return; 2265 2266 // Empty sets are uninteresting. 2267 if (Previous.empty()) 2268 return; 2269 2270 LookupResult::Filter Filter = Previous.makeFilter(); 2271 while (Filter.hasNext()) { 2272 NamedDecl *Old = Filter.next(); 2273 2274 // Non-hidden declarations are never ignored. 2275 if (S.isVisible(Old)) 2276 continue; 2277 2278 // Declarations of the same entity are not ignored, even if they have 2279 // different linkages. 2280 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2281 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2282 Decl->getUnderlyingType())) 2283 continue; 2284 2285 // If both declarations give a tag declaration a typedef name for linkage 2286 // purposes, then they declare the same entity. 2287 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2288 Decl->getAnonDeclWithTypedefName()) 2289 continue; 2290 } 2291 2292 Filter.erase(); 2293 } 2294 2295 Filter.done(); 2296 } 2297 2298 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2299 QualType OldType; 2300 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2301 OldType = OldTypedef->getUnderlyingType(); 2302 else 2303 OldType = Context.getTypeDeclType(Old); 2304 QualType NewType = New->getUnderlyingType(); 2305 2306 if (NewType->isVariablyModifiedType()) { 2307 // Must not redefine a typedef with a variably-modified type. 2308 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2309 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2310 << Kind << NewType; 2311 if (Old->getLocation().isValid()) 2312 notePreviousDefinition(Old, New->getLocation()); 2313 New->setInvalidDecl(); 2314 return true; 2315 } 2316 2317 if (OldType != NewType && 2318 !OldType->isDependentType() && 2319 !NewType->isDependentType() && 2320 !Context.hasSameType(OldType, NewType)) { 2321 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2322 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2323 << Kind << NewType << OldType; 2324 if (Old->getLocation().isValid()) 2325 notePreviousDefinition(Old, New->getLocation()); 2326 New->setInvalidDecl(); 2327 return true; 2328 } 2329 return false; 2330 } 2331 2332 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2333 /// same name and scope as a previous declaration 'Old'. Figure out 2334 /// how to resolve this situation, merging decls or emitting 2335 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2336 /// 2337 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2338 LookupResult &OldDecls) { 2339 // If the new decl is known invalid already, don't bother doing any 2340 // merging checks. 2341 if (New->isInvalidDecl()) return; 2342 2343 // Allow multiple definitions for ObjC built-in typedefs. 2344 // FIXME: Verify the underlying types are equivalent! 2345 if (getLangOpts().ObjC) { 2346 const IdentifierInfo *TypeID = New->getIdentifier(); 2347 switch (TypeID->getLength()) { 2348 default: break; 2349 case 2: 2350 { 2351 if (!TypeID->isStr("id")) 2352 break; 2353 QualType T = New->getUnderlyingType(); 2354 if (!T->isPointerType()) 2355 break; 2356 if (!T->isVoidPointerType()) { 2357 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2358 if (!PT->isStructureType()) 2359 break; 2360 } 2361 Context.setObjCIdRedefinitionType(T); 2362 // Install the built-in type for 'id', ignoring the current definition. 2363 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2364 return; 2365 } 2366 case 5: 2367 if (!TypeID->isStr("Class")) 2368 break; 2369 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2370 // Install the built-in type for 'Class', ignoring the current definition. 2371 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2372 return; 2373 case 3: 2374 if (!TypeID->isStr("SEL")) 2375 break; 2376 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2377 // Install the built-in type for 'SEL', ignoring the current definition. 2378 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2379 return; 2380 } 2381 // Fall through - the typedef name was not a builtin type. 2382 } 2383 2384 // Verify the old decl was also a type. 2385 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2386 if (!Old) { 2387 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2388 << New->getDeclName(); 2389 2390 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2391 if (OldD->getLocation().isValid()) 2392 notePreviousDefinition(OldD, New->getLocation()); 2393 2394 return New->setInvalidDecl(); 2395 } 2396 2397 // If the old declaration is invalid, just give up here. 2398 if (Old->isInvalidDecl()) 2399 return New->setInvalidDecl(); 2400 2401 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2402 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2403 auto *NewTag = New->getAnonDeclWithTypedefName(); 2404 NamedDecl *Hidden = nullptr; 2405 if (OldTag && NewTag && 2406 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2407 !hasVisibleDefinition(OldTag, &Hidden)) { 2408 // There is a definition of this tag, but it is not visible. Use it 2409 // instead of our tag. 2410 New->setTypeForDecl(OldTD->getTypeForDecl()); 2411 if (OldTD->isModed()) 2412 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2413 OldTD->getUnderlyingType()); 2414 else 2415 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2416 2417 // Make the old tag definition visible. 2418 makeMergedDefinitionVisible(Hidden); 2419 2420 // If this was an unscoped enumeration, yank all of its enumerators 2421 // out of the scope. 2422 if (isa<EnumDecl>(NewTag)) { 2423 Scope *EnumScope = getNonFieldDeclScope(S); 2424 for (auto *D : NewTag->decls()) { 2425 auto *ED = cast<EnumConstantDecl>(D); 2426 assert(EnumScope->isDeclScope(ED)); 2427 EnumScope->RemoveDecl(ED); 2428 IdResolver.RemoveDecl(ED); 2429 ED->getLexicalDeclContext()->removeDecl(ED); 2430 } 2431 } 2432 } 2433 } 2434 2435 // If the typedef types are not identical, reject them in all languages and 2436 // with any extensions enabled. 2437 if (isIncompatibleTypedef(Old, New)) 2438 return; 2439 2440 // The types match. Link up the redeclaration chain and merge attributes if 2441 // the old declaration was a typedef. 2442 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2443 New->setPreviousDecl(Typedef); 2444 mergeDeclAttributes(New, Old); 2445 } 2446 2447 if (getLangOpts().MicrosoftExt) 2448 return; 2449 2450 if (getLangOpts().CPlusPlus) { 2451 // C++ [dcl.typedef]p2: 2452 // In a given non-class scope, a typedef specifier can be used to 2453 // redefine the name of any type declared in that scope to refer 2454 // to the type to which it already refers. 2455 if (!isa<CXXRecordDecl>(CurContext)) 2456 return; 2457 2458 // C++0x [dcl.typedef]p4: 2459 // In a given class scope, a typedef specifier can be used to redefine 2460 // any class-name declared in that scope that is not also a typedef-name 2461 // to refer to the type to which it already refers. 2462 // 2463 // This wording came in via DR424, which was a correction to the 2464 // wording in DR56, which accidentally banned code like: 2465 // 2466 // struct S { 2467 // typedef struct A { } A; 2468 // }; 2469 // 2470 // in the C++03 standard. We implement the C++0x semantics, which 2471 // allow the above but disallow 2472 // 2473 // struct S { 2474 // typedef int I; 2475 // typedef int I; 2476 // }; 2477 // 2478 // since that was the intent of DR56. 2479 if (!isa<TypedefNameDecl>(Old)) 2480 return; 2481 2482 Diag(New->getLocation(), diag::err_redefinition) 2483 << New->getDeclName(); 2484 notePreviousDefinition(Old, New->getLocation()); 2485 return New->setInvalidDecl(); 2486 } 2487 2488 // Modules always permit redefinition of typedefs, as does C11. 2489 if (getLangOpts().Modules || getLangOpts().C11) 2490 return; 2491 2492 // If we have a redefinition of a typedef in C, emit a warning. This warning 2493 // is normally mapped to an error, but can be controlled with 2494 // -Wtypedef-redefinition. If either the original or the redefinition is 2495 // in a system header, don't emit this for compatibility with GCC. 2496 if (getDiagnostics().getSuppressSystemWarnings() && 2497 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2498 (Old->isImplicit() || 2499 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2500 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2501 return; 2502 2503 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2504 << New->getDeclName(); 2505 notePreviousDefinition(Old, New->getLocation()); 2506 } 2507 2508 /// DeclhasAttr - returns true if decl Declaration already has the target 2509 /// attribute. 2510 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2511 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2512 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2513 for (const auto *i : D->attrs()) 2514 if (i->getKind() == A->getKind()) { 2515 if (Ann) { 2516 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2517 return true; 2518 continue; 2519 } 2520 // FIXME: Don't hardcode this check 2521 if (OA && isa<OwnershipAttr>(i)) 2522 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2523 return true; 2524 } 2525 2526 return false; 2527 } 2528 2529 static bool isAttributeTargetADefinition(Decl *D) { 2530 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2531 return VD->isThisDeclarationADefinition(); 2532 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2533 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2534 return true; 2535 } 2536 2537 /// Merge alignment attributes from \p Old to \p New, taking into account the 2538 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2539 /// 2540 /// \return \c true if any attributes were added to \p New. 2541 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2542 // Look for alignas attributes on Old, and pick out whichever attribute 2543 // specifies the strictest alignment requirement. 2544 AlignedAttr *OldAlignasAttr = nullptr; 2545 AlignedAttr *OldStrictestAlignAttr = nullptr; 2546 unsigned OldAlign = 0; 2547 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2548 // FIXME: We have no way of representing inherited dependent alignments 2549 // in a case like: 2550 // template<int A, int B> struct alignas(A) X; 2551 // template<int A, int B> struct alignas(B) X {}; 2552 // For now, we just ignore any alignas attributes which are not on the 2553 // definition in such a case. 2554 if (I->isAlignmentDependent()) 2555 return false; 2556 2557 if (I->isAlignas()) 2558 OldAlignasAttr = I; 2559 2560 unsigned Align = I->getAlignment(S.Context); 2561 if (Align > OldAlign) { 2562 OldAlign = Align; 2563 OldStrictestAlignAttr = I; 2564 } 2565 } 2566 2567 // Look for alignas attributes on New. 2568 AlignedAttr *NewAlignasAttr = nullptr; 2569 unsigned NewAlign = 0; 2570 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2571 if (I->isAlignmentDependent()) 2572 return false; 2573 2574 if (I->isAlignas()) 2575 NewAlignasAttr = I; 2576 2577 unsigned Align = I->getAlignment(S.Context); 2578 if (Align > NewAlign) 2579 NewAlign = Align; 2580 } 2581 2582 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2583 // Both declarations have 'alignas' attributes. We require them to match. 2584 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2585 // fall short. (If two declarations both have alignas, they must both match 2586 // every definition, and so must match each other if there is a definition.) 2587 2588 // If either declaration only contains 'alignas(0)' specifiers, then it 2589 // specifies the natural alignment for the type. 2590 if (OldAlign == 0 || NewAlign == 0) { 2591 QualType Ty; 2592 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2593 Ty = VD->getType(); 2594 else 2595 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2596 2597 if (OldAlign == 0) 2598 OldAlign = S.Context.getTypeAlign(Ty); 2599 if (NewAlign == 0) 2600 NewAlign = S.Context.getTypeAlign(Ty); 2601 } 2602 2603 if (OldAlign != NewAlign) { 2604 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2605 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2606 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2607 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2608 } 2609 } 2610 2611 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2612 // C++11 [dcl.align]p6: 2613 // if any declaration of an entity has an alignment-specifier, 2614 // every defining declaration of that entity shall specify an 2615 // equivalent alignment. 2616 // C11 6.7.5/7: 2617 // If the definition of an object does not have an alignment 2618 // specifier, any other declaration of that object shall also 2619 // have no alignment specifier. 2620 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2621 << OldAlignasAttr; 2622 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2623 << OldAlignasAttr; 2624 } 2625 2626 bool AnyAdded = false; 2627 2628 // Ensure we have an attribute representing the strictest alignment. 2629 if (OldAlign > NewAlign) { 2630 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2631 Clone->setInherited(true); 2632 New->addAttr(Clone); 2633 AnyAdded = true; 2634 } 2635 2636 // Ensure we have an alignas attribute if the old declaration had one. 2637 if (OldAlignasAttr && !NewAlignasAttr && 2638 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2639 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2640 Clone->setInherited(true); 2641 New->addAttr(Clone); 2642 AnyAdded = true; 2643 } 2644 2645 return AnyAdded; 2646 } 2647 2648 #define WANT_DECL_MERGE_LOGIC 2649 #include "clang/Sema/AttrParsedAttrImpl.inc" 2650 #undef WANT_DECL_MERGE_LOGIC 2651 2652 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2653 const InheritableAttr *Attr, 2654 Sema::AvailabilityMergeKind AMK) { 2655 // Diagnose any mutual exclusions between the attribute that we want to add 2656 // and attributes that already exist on the declaration. 2657 if (!DiagnoseMutualExclusions(S, D, Attr)) 2658 return false; 2659 2660 // This function copies an attribute Attr from a previous declaration to the 2661 // new declaration D if the new declaration doesn't itself have that attribute 2662 // yet or if that attribute allows duplicates. 2663 // If you're adding a new attribute that requires logic different from 2664 // "use explicit attribute on decl if present, else use attribute from 2665 // previous decl", for example if the attribute needs to be consistent 2666 // between redeclarations, you need to call a custom merge function here. 2667 InheritableAttr *NewAttr = nullptr; 2668 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2669 NewAttr = S.mergeAvailabilityAttr( 2670 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2671 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2672 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2673 AA->getPriority()); 2674 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2675 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2676 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2677 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2678 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2679 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2680 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2681 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2682 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2683 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2684 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2685 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2686 FA->getFirstArg()); 2687 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2688 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2689 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2690 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2691 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2692 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2693 IA->getInheritanceModel()); 2694 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2695 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2696 &S.Context.Idents.get(AA->getSpelling())); 2697 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2698 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2699 isa<CUDAGlobalAttr>(Attr))) { 2700 // CUDA target attributes are part of function signature for 2701 // overloading purposes and must not be merged. 2702 return false; 2703 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2704 NewAttr = S.mergeMinSizeAttr(D, *MA); 2705 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2706 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2707 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2708 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2709 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2710 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2711 else if (isa<AlignedAttr>(Attr)) 2712 // AlignedAttrs are handled separately, because we need to handle all 2713 // such attributes on a declaration at the same time. 2714 NewAttr = nullptr; 2715 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2716 (AMK == Sema::AMK_Override || 2717 AMK == Sema::AMK_ProtocolImplementation || 2718 AMK == Sema::AMK_OptionalProtocolImplementation)) 2719 NewAttr = nullptr; 2720 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2721 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2722 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2723 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2724 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2725 NewAttr = S.mergeImportNameAttr(D, *INA); 2726 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2727 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2728 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2729 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2730 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) 2731 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); 2732 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2733 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2734 2735 if (NewAttr) { 2736 NewAttr->setInherited(true); 2737 D->addAttr(NewAttr); 2738 if (isa<MSInheritanceAttr>(NewAttr)) 2739 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2740 return true; 2741 } 2742 2743 return false; 2744 } 2745 2746 static const NamedDecl *getDefinition(const Decl *D) { 2747 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2748 return TD->getDefinition(); 2749 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2750 const VarDecl *Def = VD->getDefinition(); 2751 if (Def) 2752 return Def; 2753 return VD->getActingDefinition(); 2754 } 2755 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2756 const FunctionDecl *Def = nullptr; 2757 if (FD->isDefined(Def, true)) 2758 return Def; 2759 } 2760 return nullptr; 2761 } 2762 2763 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2764 for (const auto *Attribute : D->attrs()) 2765 if (Attribute->getKind() == Kind) 2766 return true; 2767 return false; 2768 } 2769 2770 /// checkNewAttributesAfterDef - If we already have a definition, check that 2771 /// there are no new attributes in this declaration. 2772 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2773 if (!New->hasAttrs()) 2774 return; 2775 2776 const NamedDecl *Def = getDefinition(Old); 2777 if (!Def || Def == New) 2778 return; 2779 2780 AttrVec &NewAttributes = New->getAttrs(); 2781 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2782 const Attr *NewAttribute = NewAttributes[I]; 2783 2784 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2785 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2786 Sema::SkipBodyInfo SkipBody; 2787 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2788 2789 // If we're skipping this definition, drop the "alias" attribute. 2790 if (SkipBody.ShouldSkip) { 2791 NewAttributes.erase(NewAttributes.begin() + I); 2792 --E; 2793 continue; 2794 } 2795 } else { 2796 VarDecl *VD = cast<VarDecl>(New); 2797 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2798 VarDecl::TentativeDefinition 2799 ? diag::err_alias_after_tentative 2800 : diag::err_redefinition; 2801 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2802 if (Diag == diag::err_redefinition) 2803 S.notePreviousDefinition(Def, VD->getLocation()); 2804 else 2805 S.Diag(Def->getLocation(), diag::note_previous_definition); 2806 VD->setInvalidDecl(); 2807 } 2808 ++I; 2809 continue; 2810 } 2811 2812 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2813 // Tentative definitions are only interesting for the alias check above. 2814 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2815 ++I; 2816 continue; 2817 } 2818 } 2819 2820 if (hasAttribute(Def, NewAttribute->getKind())) { 2821 ++I; 2822 continue; // regular attr merging will take care of validating this. 2823 } 2824 2825 if (isa<C11NoReturnAttr>(NewAttribute)) { 2826 // C's _Noreturn is allowed to be added to a function after it is defined. 2827 ++I; 2828 continue; 2829 } else if (isa<UuidAttr>(NewAttribute)) { 2830 // msvc will allow a subsequent definition to add an uuid to a class 2831 ++I; 2832 continue; 2833 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2834 if (AA->isAlignas()) { 2835 // C++11 [dcl.align]p6: 2836 // if any declaration of an entity has an alignment-specifier, 2837 // every defining declaration of that entity shall specify an 2838 // equivalent alignment. 2839 // C11 6.7.5/7: 2840 // If the definition of an object does not have an alignment 2841 // specifier, any other declaration of that object shall also 2842 // have no alignment specifier. 2843 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2844 << AA; 2845 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2846 << AA; 2847 NewAttributes.erase(NewAttributes.begin() + I); 2848 --E; 2849 continue; 2850 } 2851 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2852 // If there is a C definition followed by a redeclaration with this 2853 // attribute then there are two different definitions. In C++, prefer the 2854 // standard diagnostics. 2855 if (!S.getLangOpts().CPlusPlus) { 2856 S.Diag(NewAttribute->getLocation(), 2857 diag::err_loader_uninitialized_redeclaration); 2858 S.Diag(Def->getLocation(), diag::note_previous_definition); 2859 NewAttributes.erase(NewAttributes.begin() + I); 2860 --E; 2861 continue; 2862 } 2863 } else if (isa<SelectAnyAttr>(NewAttribute) && 2864 cast<VarDecl>(New)->isInline() && 2865 !cast<VarDecl>(New)->isInlineSpecified()) { 2866 // Don't warn about applying selectany to implicitly inline variables. 2867 // Older compilers and language modes would require the use of selectany 2868 // to make such variables inline, and it would have no effect if we 2869 // honored it. 2870 ++I; 2871 continue; 2872 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2873 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2874 // declarations after defintions. 2875 ++I; 2876 continue; 2877 } 2878 2879 S.Diag(NewAttribute->getLocation(), 2880 diag::warn_attribute_precede_definition); 2881 S.Diag(Def->getLocation(), diag::note_previous_definition); 2882 NewAttributes.erase(NewAttributes.begin() + I); 2883 --E; 2884 } 2885 } 2886 2887 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2888 const ConstInitAttr *CIAttr, 2889 bool AttrBeforeInit) { 2890 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2891 2892 // Figure out a good way to write this specifier on the old declaration. 2893 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2894 // enough of the attribute list spelling information to extract that without 2895 // heroics. 2896 std::string SuitableSpelling; 2897 if (S.getLangOpts().CPlusPlus20) 2898 SuitableSpelling = std::string( 2899 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2900 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2901 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2902 InsertLoc, {tok::l_square, tok::l_square, 2903 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2904 S.PP.getIdentifierInfo("require_constant_initialization"), 2905 tok::r_square, tok::r_square})); 2906 if (SuitableSpelling.empty()) 2907 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2908 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2909 S.PP.getIdentifierInfo("require_constant_initialization"), 2910 tok::r_paren, tok::r_paren})); 2911 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2912 SuitableSpelling = "constinit"; 2913 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2914 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2915 if (SuitableSpelling.empty()) 2916 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2917 SuitableSpelling += " "; 2918 2919 if (AttrBeforeInit) { 2920 // extern constinit int a; 2921 // int a = 0; // error (missing 'constinit'), accepted as extension 2922 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2923 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2924 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2925 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2926 } else { 2927 // int a = 0; 2928 // constinit extern int a; // error (missing 'constinit') 2929 S.Diag(CIAttr->getLocation(), 2930 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2931 : diag::warn_require_const_init_added_too_late) 2932 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2933 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2934 << CIAttr->isConstinit() 2935 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2936 } 2937 } 2938 2939 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2940 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2941 AvailabilityMergeKind AMK) { 2942 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2943 UsedAttr *NewAttr = OldAttr->clone(Context); 2944 NewAttr->setInherited(true); 2945 New->addAttr(NewAttr); 2946 } 2947 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 2948 RetainAttr *NewAttr = OldAttr->clone(Context); 2949 NewAttr->setInherited(true); 2950 New->addAttr(NewAttr); 2951 } 2952 2953 if (!Old->hasAttrs() && !New->hasAttrs()) 2954 return; 2955 2956 // [dcl.constinit]p1: 2957 // If the [constinit] specifier is applied to any declaration of a 2958 // variable, it shall be applied to the initializing declaration. 2959 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2960 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2961 if (bool(OldConstInit) != bool(NewConstInit)) { 2962 const auto *OldVD = cast<VarDecl>(Old); 2963 auto *NewVD = cast<VarDecl>(New); 2964 2965 // Find the initializing declaration. Note that we might not have linked 2966 // the new declaration into the redeclaration chain yet. 2967 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2968 if (!InitDecl && 2969 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2970 InitDecl = NewVD; 2971 2972 if (InitDecl == NewVD) { 2973 // This is the initializing declaration. If it would inherit 'constinit', 2974 // that's ill-formed. (Note that we do not apply this to the attribute 2975 // form). 2976 if (OldConstInit && OldConstInit->isConstinit()) 2977 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2978 /*AttrBeforeInit=*/true); 2979 } else if (NewConstInit) { 2980 // This is the first time we've been told that this declaration should 2981 // have a constant initializer. If we already saw the initializing 2982 // declaration, this is too late. 2983 if (InitDecl && InitDecl != NewVD) { 2984 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2985 /*AttrBeforeInit=*/false); 2986 NewVD->dropAttr<ConstInitAttr>(); 2987 } 2988 } 2989 } 2990 2991 // Attributes declared post-definition are currently ignored. 2992 checkNewAttributesAfterDef(*this, New, Old); 2993 2994 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2995 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2996 if (!OldA->isEquivalent(NewA)) { 2997 // This redeclaration changes __asm__ label. 2998 Diag(New->getLocation(), diag::err_different_asm_label); 2999 Diag(OldA->getLocation(), diag::note_previous_declaration); 3000 } 3001 } else if (Old->isUsed()) { 3002 // This redeclaration adds an __asm__ label to a declaration that has 3003 // already been ODR-used. 3004 Diag(New->getLocation(), diag::err_late_asm_label_name) 3005 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 3006 } 3007 } 3008 3009 // Re-declaration cannot add abi_tag's. 3010 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 3011 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 3012 for (const auto &NewTag : NewAbiTagAttr->tags()) { 3013 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { 3014 Diag(NewAbiTagAttr->getLocation(), 3015 diag::err_new_abi_tag_on_redeclaration) 3016 << NewTag; 3017 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 3018 } 3019 } 3020 } else { 3021 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 3022 Diag(Old->getLocation(), diag::note_previous_declaration); 3023 } 3024 } 3025 3026 // This redeclaration adds a section attribute. 3027 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 3028 if (auto *VD = dyn_cast<VarDecl>(New)) { 3029 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 3030 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 3031 Diag(Old->getLocation(), diag::note_previous_declaration); 3032 } 3033 } 3034 } 3035 3036 // Redeclaration adds code-seg attribute. 3037 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 3038 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 3039 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 3040 Diag(New->getLocation(), diag::warn_mismatched_section) 3041 << 0 /*codeseg*/; 3042 Diag(Old->getLocation(), diag::note_previous_declaration); 3043 } 3044 3045 if (!Old->hasAttrs()) 3046 return; 3047 3048 bool foundAny = New->hasAttrs(); 3049 3050 // Ensure that any moving of objects within the allocated map is done before 3051 // we process them. 3052 if (!foundAny) New->setAttrs(AttrVec()); 3053 3054 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3055 // Ignore deprecated/unavailable/availability attributes if requested. 3056 AvailabilityMergeKind LocalAMK = AMK_None; 3057 if (isa<DeprecatedAttr>(I) || 3058 isa<UnavailableAttr>(I) || 3059 isa<AvailabilityAttr>(I)) { 3060 switch (AMK) { 3061 case AMK_None: 3062 continue; 3063 3064 case AMK_Redeclaration: 3065 case AMK_Override: 3066 case AMK_ProtocolImplementation: 3067 case AMK_OptionalProtocolImplementation: 3068 LocalAMK = AMK; 3069 break; 3070 } 3071 } 3072 3073 // Already handled. 3074 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3075 continue; 3076 3077 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3078 foundAny = true; 3079 } 3080 3081 if (mergeAlignedAttrs(*this, New, Old)) 3082 foundAny = true; 3083 3084 if (!foundAny) New->dropAttrs(); 3085 } 3086 3087 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3088 /// to the new one. 3089 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3090 const ParmVarDecl *oldDecl, 3091 Sema &S) { 3092 // C++11 [dcl.attr.depend]p2: 3093 // The first declaration of a function shall specify the 3094 // carries_dependency attribute for its declarator-id if any declaration 3095 // of the function specifies the carries_dependency attribute. 3096 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3097 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3098 S.Diag(CDA->getLocation(), 3099 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3100 // Find the first declaration of the parameter. 3101 // FIXME: Should we build redeclaration chains for function parameters? 3102 const FunctionDecl *FirstFD = 3103 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3104 const ParmVarDecl *FirstVD = 3105 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3106 S.Diag(FirstVD->getLocation(), 3107 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3108 } 3109 3110 if (!oldDecl->hasAttrs()) 3111 return; 3112 3113 bool foundAny = newDecl->hasAttrs(); 3114 3115 // Ensure that any moving of objects within the allocated map is 3116 // done before we process them. 3117 if (!foundAny) newDecl->setAttrs(AttrVec()); 3118 3119 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3120 if (!DeclHasAttr(newDecl, I)) { 3121 InheritableAttr *newAttr = 3122 cast<InheritableParamAttr>(I->clone(S.Context)); 3123 newAttr->setInherited(true); 3124 newDecl->addAttr(newAttr); 3125 foundAny = true; 3126 } 3127 } 3128 3129 if (!foundAny) newDecl->dropAttrs(); 3130 } 3131 3132 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3133 const ParmVarDecl *OldParam, 3134 Sema &S) { 3135 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3136 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3137 if (*Oldnullability != *Newnullability) { 3138 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3139 << DiagNullabilityKind( 3140 *Newnullability, 3141 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3142 != 0)) 3143 << DiagNullabilityKind( 3144 *Oldnullability, 3145 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3146 != 0)); 3147 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3148 } 3149 } else { 3150 QualType NewT = NewParam->getType(); 3151 NewT = S.Context.getAttributedType( 3152 AttributedType::getNullabilityAttrKind(*Oldnullability), 3153 NewT, NewT); 3154 NewParam->setType(NewT); 3155 } 3156 } 3157 } 3158 3159 namespace { 3160 3161 /// Used in MergeFunctionDecl to keep track of function parameters in 3162 /// C. 3163 struct GNUCompatibleParamWarning { 3164 ParmVarDecl *OldParm; 3165 ParmVarDecl *NewParm; 3166 QualType PromotedType; 3167 }; 3168 3169 } // end anonymous namespace 3170 3171 // Determine whether the previous declaration was a definition, implicit 3172 // declaration, or a declaration. 3173 template <typename T> 3174 static std::pair<diag::kind, SourceLocation> 3175 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3176 diag::kind PrevDiag; 3177 SourceLocation OldLocation = Old->getLocation(); 3178 if (Old->isThisDeclarationADefinition()) 3179 PrevDiag = diag::note_previous_definition; 3180 else if (Old->isImplicit()) { 3181 PrevDiag = diag::note_previous_implicit_declaration; 3182 if (OldLocation.isInvalid()) 3183 OldLocation = New->getLocation(); 3184 } else 3185 PrevDiag = diag::note_previous_declaration; 3186 return std::make_pair(PrevDiag, OldLocation); 3187 } 3188 3189 /// canRedefineFunction - checks if a function can be redefined. Currently, 3190 /// only extern inline functions can be redefined, and even then only in 3191 /// GNU89 mode. 3192 static bool canRedefineFunction(const FunctionDecl *FD, 3193 const LangOptions& LangOpts) { 3194 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3195 !LangOpts.CPlusPlus && 3196 FD->isInlineSpecified() && 3197 FD->getStorageClass() == SC_Extern); 3198 } 3199 3200 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3201 const AttributedType *AT = T->getAs<AttributedType>(); 3202 while (AT && !AT->isCallingConv()) 3203 AT = AT->getModifiedType()->getAs<AttributedType>(); 3204 return AT; 3205 } 3206 3207 template <typename T> 3208 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3209 const DeclContext *DC = Old->getDeclContext(); 3210 if (DC->isRecord()) 3211 return false; 3212 3213 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3214 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3215 return true; 3216 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3217 return true; 3218 return false; 3219 } 3220 3221 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3222 static bool isExternC(VarTemplateDecl *) { return false; } 3223 static bool isExternC(FunctionTemplateDecl *) { return false; } 3224 3225 /// Check whether a redeclaration of an entity introduced by a 3226 /// using-declaration is valid, given that we know it's not an overload 3227 /// (nor a hidden tag declaration). 3228 template<typename ExpectedDecl> 3229 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3230 ExpectedDecl *New) { 3231 // C++11 [basic.scope.declarative]p4: 3232 // Given a set of declarations in a single declarative region, each of 3233 // which specifies the same unqualified name, 3234 // -- they shall all refer to the same entity, or all refer to functions 3235 // and function templates; or 3236 // -- exactly one declaration shall declare a class name or enumeration 3237 // name that is not a typedef name and the other declarations shall all 3238 // refer to the same variable or enumerator, or all refer to functions 3239 // and function templates; in this case the class name or enumeration 3240 // name is hidden (3.3.10). 3241 3242 // C++11 [namespace.udecl]p14: 3243 // If a function declaration in namespace scope or block scope has the 3244 // same name and the same parameter-type-list as a function introduced 3245 // by a using-declaration, and the declarations do not declare the same 3246 // function, the program is ill-formed. 3247 3248 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3249 if (Old && 3250 !Old->getDeclContext()->getRedeclContext()->Equals( 3251 New->getDeclContext()->getRedeclContext()) && 3252 !(isExternC(Old) && isExternC(New))) 3253 Old = nullptr; 3254 3255 if (!Old) { 3256 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3257 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3258 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3259 return true; 3260 } 3261 return false; 3262 } 3263 3264 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3265 const FunctionDecl *B) { 3266 assert(A->getNumParams() == B->getNumParams()); 3267 3268 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3269 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3270 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3271 if (AttrA == AttrB) 3272 return true; 3273 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3274 AttrA->isDynamic() == AttrB->isDynamic(); 3275 }; 3276 3277 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3278 } 3279 3280 /// If necessary, adjust the semantic declaration context for a qualified 3281 /// declaration to name the correct inline namespace within the qualifier. 3282 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3283 DeclaratorDecl *OldD) { 3284 // The only case where we need to update the DeclContext is when 3285 // redeclaration lookup for a qualified name finds a declaration 3286 // in an inline namespace within the context named by the qualifier: 3287 // 3288 // inline namespace N { int f(); } 3289 // int ::f(); // Sema DC needs adjusting from :: to N::. 3290 // 3291 // For unqualified declarations, the semantic context *can* change 3292 // along the redeclaration chain (for local extern declarations, 3293 // extern "C" declarations, and friend declarations in particular). 3294 if (!NewD->getQualifier()) 3295 return; 3296 3297 // NewD is probably already in the right context. 3298 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3299 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3300 if (NamedDC->Equals(SemaDC)) 3301 return; 3302 3303 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3304 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3305 "unexpected context for redeclaration"); 3306 3307 auto *LexDC = NewD->getLexicalDeclContext(); 3308 auto FixSemaDC = [=](NamedDecl *D) { 3309 if (!D) 3310 return; 3311 D->setDeclContext(SemaDC); 3312 D->setLexicalDeclContext(LexDC); 3313 }; 3314 3315 FixSemaDC(NewD); 3316 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3317 FixSemaDC(FD->getDescribedFunctionTemplate()); 3318 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3319 FixSemaDC(VD->getDescribedVarTemplate()); 3320 } 3321 3322 /// MergeFunctionDecl - We just parsed a function 'New' from 3323 /// declarator D which has the same name and scope as a previous 3324 /// declaration 'Old'. Figure out how to resolve this situation, 3325 /// merging decls or emitting diagnostics as appropriate. 3326 /// 3327 /// In C++, New and Old must be declarations that are not 3328 /// overloaded. Use IsOverload to determine whether New and Old are 3329 /// overloaded, and to select the Old declaration that New should be 3330 /// merged with. 3331 /// 3332 /// Returns true if there was an error, false otherwise. 3333 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3334 Scope *S, bool MergeTypeWithOld) { 3335 // Verify the old decl was also a function. 3336 FunctionDecl *Old = OldD->getAsFunction(); 3337 if (!Old) { 3338 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3339 if (New->getFriendObjectKind()) { 3340 Diag(New->getLocation(), diag::err_using_decl_friend); 3341 Diag(Shadow->getTargetDecl()->getLocation(), 3342 diag::note_using_decl_target); 3343 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3344 << 0; 3345 return true; 3346 } 3347 3348 // Check whether the two declarations might declare the same function or 3349 // function template. 3350 if (FunctionTemplateDecl *NewTemplate = 3351 New->getDescribedFunctionTemplate()) { 3352 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3353 NewTemplate)) 3354 return true; 3355 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3356 ->getAsFunction(); 3357 } else { 3358 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3359 return true; 3360 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3361 } 3362 } else { 3363 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3364 << New->getDeclName(); 3365 notePreviousDefinition(OldD, New->getLocation()); 3366 return true; 3367 } 3368 } 3369 3370 // If the old declaration was found in an inline namespace and the new 3371 // declaration was qualified, update the DeclContext to match. 3372 adjustDeclContextForDeclaratorDecl(New, Old); 3373 3374 // If the old declaration is invalid, just give up here. 3375 if (Old->isInvalidDecl()) 3376 return true; 3377 3378 // Disallow redeclaration of some builtins. 3379 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3380 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3381 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3382 << Old << Old->getType(); 3383 return true; 3384 } 3385 3386 diag::kind PrevDiag; 3387 SourceLocation OldLocation; 3388 std::tie(PrevDiag, OldLocation) = 3389 getNoteDiagForInvalidRedeclaration(Old, New); 3390 3391 // Don't complain about this if we're in GNU89 mode and the old function 3392 // is an extern inline function. 3393 // Don't complain about specializations. They are not supposed to have 3394 // storage classes. 3395 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3396 New->getStorageClass() == SC_Static && 3397 Old->hasExternalFormalLinkage() && 3398 !New->getTemplateSpecializationInfo() && 3399 !canRedefineFunction(Old, getLangOpts())) { 3400 if (getLangOpts().MicrosoftExt) { 3401 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3402 Diag(OldLocation, PrevDiag); 3403 } else { 3404 Diag(New->getLocation(), diag::err_static_non_static) << New; 3405 Diag(OldLocation, PrevDiag); 3406 return true; 3407 } 3408 } 3409 3410 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3411 if (!Old->hasAttr<InternalLinkageAttr>()) { 3412 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3413 << ILA; 3414 Diag(Old->getLocation(), diag::note_previous_declaration); 3415 New->dropAttr<InternalLinkageAttr>(); 3416 } 3417 3418 if (auto *EA = New->getAttr<ErrorAttr>()) { 3419 if (!Old->hasAttr<ErrorAttr>()) { 3420 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3421 Diag(Old->getLocation(), diag::note_previous_declaration); 3422 New->dropAttr<ErrorAttr>(); 3423 } 3424 } 3425 3426 if (CheckRedeclarationInModule(New, Old)) 3427 return true; 3428 3429 if (!getLangOpts().CPlusPlus) { 3430 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3431 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3432 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3433 << New << OldOvl; 3434 3435 // Try our best to find a decl that actually has the overloadable 3436 // attribute for the note. In most cases (e.g. programs with only one 3437 // broken declaration/definition), this won't matter. 3438 // 3439 // FIXME: We could do this if we juggled some extra state in 3440 // OverloadableAttr, rather than just removing it. 3441 const Decl *DiagOld = Old; 3442 if (OldOvl) { 3443 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3444 const auto *A = D->getAttr<OverloadableAttr>(); 3445 return A && !A->isImplicit(); 3446 }); 3447 // If we've implicitly added *all* of the overloadable attrs to this 3448 // chain, emitting a "previous redecl" note is pointless. 3449 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3450 } 3451 3452 if (DiagOld) 3453 Diag(DiagOld->getLocation(), 3454 diag::note_attribute_overloadable_prev_overload) 3455 << OldOvl; 3456 3457 if (OldOvl) 3458 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3459 else 3460 New->dropAttr<OverloadableAttr>(); 3461 } 3462 } 3463 3464 // If a function is first declared with a calling convention, but is later 3465 // declared or defined without one, all following decls assume the calling 3466 // convention of the first. 3467 // 3468 // It's OK if a function is first declared without a calling convention, 3469 // but is later declared or defined with the default calling convention. 3470 // 3471 // To test if either decl has an explicit calling convention, we look for 3472 // AttributedType sugar nodes on the type as written. If they are missing or 3473 // were canonicalized away, we assume the calling convention was implicit. 3474 // 3475 // Note also that we DO NOT return at this point, because we still have 3476 // other tests to run. 3477 QualType OldQType = Context.getCanonicalType(Old->getType()); 3478 QualType NewQType = Context.getCanonicalType(New->getType()); 3479 const FunctionType *OldType = cast<FunctionType>(OldQType); 3480 const FunctionType *NewType = cast<FunctionType>(NewQType); 3481 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3482 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3483 bool RequiresAdjustment = false; 3484 3485 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3486 FunctionDecl *First = Old->getFirstDecl(); 3487 const FunctionType *FT = 3488 First->getType().getCanonicalType()->castAs<FunctionType>(); 3489 FunctionType::ExtInfo FI = FT->getExtInfo(); 3490 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3491 if (!NewCCExplicit) { 3492 // Inherit the CC from the previous declaration if it was specified 3493 // there but not here. 3494 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3495 RequiresAdjustment = true; 3496 } else if (Old->getBuiltinID()) { 3497 // Builtin attribute isn't propagated to the new one yet at this point, 3498 // so we check if the old one is a builtin. 3499 3500 // Calling Conventions on a Builtin aren't really useful and setting a 3501 // default calling convention and cdecl'ing some builtin redeclarations is 3502 // common, so warn and ignore the calling convention on the redeclaration. 3503 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3504 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3505 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3506 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3507 RequiresAdjustment = true; 3508 } else { 3509 // Calling conventions aren't compatible, so complain. 3510 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3511 Diag(New->getLocation(), diag::err_cconv_change) 3512 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3513 << !FirstCCExplicit 3514 << (!FirstCCExplicit ? "" : 3515 FunctionType::getNameForCallConv(FI.getCC())); 3516 3517 // Put the note on the first decl, since it is the one that matters. 3518 Diag(First->getLocation(), diag::note_previous_declaration); 3519 return true; 3520 } 3521 } 3522 3523 // FIXME: diagnose the other way around? 3524 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3525 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3526 RequiresAdjustment = true; 3527 } 3528 3529 // Merge regparm attribute. 3530 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3531 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3532 if (NewTypeInfo.getHasRegParm()) { 3533 Diag(New->getLocation(), diag::err_regparm_mismatch) 3534 << NewType->getRegParmType() 3535 << OldType->getRegParmType(); 3536 Diag(OldLocation, diag::note_previous_declaration); 3537 return true; 3538 } 3539 3540 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3541 RequiresAdjustment = true; 3542 } 3543 3544 // Merge ns_returns_retained attribute. 3545 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3546 if (NewTypeInfo.getProducesResult()) { 3547 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3548 << "'ns_returns_retained'"; 3549 Diag(OldLocation, diag::note_previous_declaration); 3550 return true; 3551 } 3552 3553 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3554 RequiresAdjustment = true; 3555 } 3556 3557 if (OldTypeInfo.getNoCallerSavedRegs() != 3558 NewTypeInfo.getNoCallerSavedRegs()) { 3559 if (NewTypeInfo.getNoCallerSavedRegs()) { 3560 AnyX86NoCallerSavedRegistersAttr *Attr = 3561 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3562 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3563 Diag(OldLocation, diag::note_previous_declaration); 3564 return true; 3565 } 3566 3567 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3568 RequiresAdjustment = true; 3569 } 3570 3571 if (RequiresAdjustment) { 3572 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3573 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3574 New->setType(QualType(AdjustedType, 0)); 3575 NewQType = Context.getCanonicalType(New->getType()); 3576 } 3577 3578 // If this redeclaration makes the function inline, we may need to add it to 3579 // UndefinedButUsed. 3580 if (!Old->isInlined() && New->isInlined() && 3581 !New->hasAttr<GNUInlineAttr>() && 3582 !getLangOpts().GNUInline && 3583 Old->isUsed(false) && 3584 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3585 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3586 SourceLocation())); 3587 3588 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3589 // about it. 3590 if (New->hasAttr<GNUInlineAttr>() && 3591 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3592 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3593 } 3594 3595 // If pass_object_size params don't match up perfectly, this isn't a valid 3596 // redeclaration. 3597 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3598 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3599 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3600 << New->getDeclName(); 3601 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3602 return true; 3603 } 3604 3605 if (getLangOpts().CPlusPlus) { 3606 // C++1z [over.load]p2 3607 // Certain function declarations cannot be overloaded: 3608 // -- Function declarations that differ only in the return type, 3609 // the exception specification, or both cannot be overloaded. 3610 3611 // Check the exception specifications match. This may recompute the type of 3612 // both Old and New if it resolved exception specifications, so grab the 3613 // types again after this. Because this updates the type, we do this before 3614 // any of the other checks below, which may update the "de facto" NewQType 3615 // but do not necessarily update the type of New. 3616 if (CheckEquivalentExceptionSpec(Old, New)) 3617 return true; 3618 OldQType = Context.getCanonicalType(Old->getType()); 3619 NewQType = Context.getCanonicalType(New->getType()); 3620 3621 // Go back to the type source info to compare the declared return types, 3622 // per C++1y [dcl.type.auto]p13: 3623 // Redeclarations or specializations of a function or function template 3624 // with a declared return type that uses a placeholder type shall also 3625 // use that placeholder, not a deduced type. 3626 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3627 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3628 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3629 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3630 OldDeclaredReturnType)) { 3631 QualType ResQT; 3632 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3633 OldDeclaredReturnType->isObjCObjectPointerType()) 3634 // FIXME: This does the wrong thing for a deduced return type. 3635 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3636 if (ResQT.isNull()) { 3637 if (New->isCXXClassMember() && New->isOutOfLine()) 3638 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3639 << New << New->getReturnTypeSourceRange(); 3640 else 3641 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3642 << New->getReturnTypeSourceRange(); 3643 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3644 << Old->getReturnTypeSourceRange(); 3645 return true; 3646 } 3647 else 3648 NewQType = ResQT; 3649 } 3650 3651 QualType OldReturnType = OldType->getReturnType(); 3652 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3653 if (OldReturnType != NewReturnType) { 3654 // If this function has a deduced return type and has already been 3655 // defined, copy the deduced value from the old declaration. 3656 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3657 if (OldAT && OldAT->isDeduced()) { 3658 QualType DT = OldAT->getDeducedType(); 3659 if (DT.isNull()) { 3660 New->setType(SubstAutoTypeDependent(New->getType())); 3661 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); 3662 } else { 3663 New->setType(SubstAutoType(New->getType(), DT)); 3664 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); 3665 } 3666 } 3667 } 3668 3669 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3670 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3671 if (OldMethod && NewMethod) { 3672 // Preserve triviality. 3673 NewMethod->setTrivial(OldMethod->isTrivial()); 3674 3675 // MSVC allows explicit template specialization at class scope: 3676 // 2 CXXMethodDecls referring to the same function will be injected. 3677 // We don't want a redeclaration error. 3678 bool IsClassScopeExplicitSpecialization = 3679 OldMethod->isFunctionTemplateSpecialization() && 3680 NewMethod->isFunctionTemplateSpecialization(); 3681 bool isFriend = NewMethod->getFriendObjectKind(); 3682 3683 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3684 !IsClassScopeExplicitSpecialization) { 3685 // -- Member function declarations with the same name and the 3686 // same parameter types cannot be overloaded if any of them 3687 // is a static member function declaration. 3688 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3689 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3690 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3691 return true; 3692 } 3693 3694 // C++ [class.mem]p1: 3695 // [...] A member shall not be declared twice in the 3696 // member-specification, except that a nested class or member 3697 // class template can be declared and then later defined. 3698 if (!inTemplateInstantiation()) { 3699 unsigned NewDiag; 3700 if (isa<CXXConstructorDecl>(OldMethod)) 3701 NewDiag = diag::err_constructor_redeclared; 3702 else if (isa<CXXDestructorDecl>(NewMethod)) 3703 NewDiag = diag::err_destructor_redeclared; 3704 else if (isa<CXXConversionDecl>(NewMethod)) 3705 NewDiag = diag::err_conv_function_redeclared; 3706 else 3707 NewDiag = diag::err_member_redeclared; 3708 3709 Diag(New->getLocation(), NewDiag); 3710 } else { 3711 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3712 << New << New->getType(); 3713 } 3714 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3715 return true; 3716 3717 // Complain if this is an explicit declaration of a special 3718 // member that was initially declared implicitly. 3719 // 3720 // As an exception, it's okay to befriend such methods in order 3721 // to permit the implicit constructor/destructor/operator calls. 3722 } else if (OldMethod->isImplicit()) { 3723 if (isFriend) { 3724 NewMethod->setImplicit(); 3725 } else { 3726 Diag(NewMethod->getLocation(), 3727 diag::err_definition_of_implicitly_declared_member) 3728 << New << getSpecialMember(OldMethod); 3729 return true; 3730 } 3731 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3732 Diag(NewMethod->getLocation(), 3733 diag::err_definition_of_explicitly_defaulted_member) 3734 << getSpecialMember(OldMethod); 3735 return true; 3736 } 3737 } 3738 3739 // C++11 [dcl.attr.noreturn]p1: 3740 // The first declaration of a function shall specify the noreturn 3741 // attribute if any declaration of that function specifies the noreturn 3742 // attribute. 3743 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 3744 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 3745 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 3746 << NRA; 3747 Diag(Old->getLocation(), diag::note_previous_declaration); 3748 } 3749 3750 // C++11 [dcl.attr.depend]p2: 3751 // The first declaration of a function shall specify the 3752 // carries_dependency attribute for its declarator-id if any declaration 3753 // of the function specifies the carries_dependency attribute. 3754 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3755 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3756 Diag(CDA->getLocation(), 3757 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3758 Diag(Old->getFirstDecl()->getLocation(), 3759 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3760 } 3761 3762 // (C++98 8.3.5p3): 3763 // All declarations for a function shall agree exactly in both the 3764 // return type and the parameter-type-list. 3765 // We also want to respect all the extended bits except noreturn. 3766 3767 // noreturn should now match unless the old type info didn't have it. 3768 QualType OldQTypeForComparison = OldQType; 3769 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3770 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3771 const FunctionType *OldTypeForComparison 3772 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3773 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3774 assert(OldQTypeForComparison.isCanonical()); 3775 } 3776 3777 if (haveIncompatibleLanguageLinkages(Old, New)) { 3778 // As a special case, retain the language linkage from previous 3779 // declarations of a friend function as an extension. 3780 // 3781 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3782 // and is useful because there's otherwise no way to specify language 3783 // linkage within class scope. 3784 // 3785 // Check cautiously as the friend object kind isn't yet complete. 3786 if (New->getFriendObjectKind() != Decl::FOK_None) { 3787 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3788 Diag(OldLocation, PrevDiag); 3789 } else { 3790 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3791 Diag(OldLocation, PrevDiag); 3792 return true; 3793 } 3794 } 3795 3796 // If the function types are compatible, merge the declarations. Ignore the 3797 // exception specifier because it was already checked above in 3798 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3799 // about incompatible types under -fms-compatibility. 3800 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3801 NewQType)) 3802 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3803 3804 // If the types are imprecise (due to dependent constructs in friends or 3805 // local extern declarations), it's OK if they differ. We'll check again 3806 // during instantiation. 3807 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3808 return false; 3809 3810 // Fall through for conflicting redeclarations and redefinitions. 3811 } 3812 3813 // C: Function types need to be compatible, not identical. This handles 3814 // duplicate function decls like "void f(int); void f(enum X);" properly. 3815 if (!getLangOpts().CPlusPlus && 3816 Context.typesAreCompatible(OldQType, NewQType)) { 3817 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3818 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3819 const FunctionProtoType *OldProto = nullptr; 3820 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3821 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3822 // The old declaration provided a function prototype, but the 3823 // new declaration does not. Merge in the prototype. 3824 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3825 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3826 NewQType = 3827 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3828 OldProto->getExtProtoInfo()); 3829 New->setType(NewQType); 3830 New->setHasInheritedPrototype(); 3831 3832 // Synthesize parameters with the same types. 3833 SmallVector<ParmVarDecl*, 16> Params; 3834 for (const auto &ParamType : OldProto->param_types()) { 3835 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3836 SourceLocation(), nullptr, 3837 ParamType, /*TInfo=*/nullptr, 3838 SC_None, nullptr); 3839 Param->setScopeInfo(0, Params.size()); 3840 Param->setImplicit(); 3841 Params.push_back(Param); 3842 } 3843 3844 New->setParams(Params); 3845 } 3846 3847 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3848 } 3849 3850 // Check if the function types are compatible when pointer size address 3851 // spaces are ignored. 3852 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3853 return false; 3854 3855 // GNU C permits a K&R definition to follow a prototype declaration 3856 // if the declared types of the parameters in the K&R definition 3857 // match the types in the prototype declaration, even when the 3858 // promoted types of the parameters from the K&R definition differ 3859 // from the types in the prototype. GCC then keeps the types from 3860 // the prototype. 3861 // 3862 // If a variadic prototype is followed by a non-variadic K&R definition, 3863 // the K&R definition becomes variadic. This is sort of an edge case, but 3864 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3865 // C99 6.9.1p8. 3866 if (!getLangOpts().CPlusPlus && 3867 Old->hasPrototype() && !New->hasPrototype() && 3868 New->getType()->getAs<FunctionProtoType>() && 3869 Old->getNumParams() == New->getNumParams()) { 3870 SmallVector<QualType, 16> ArgTypes; 3871 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3872 const FunctionProtoType *OldProto 3873 = Old->getType()->getAs<FunctionProtoType>(); 3874 const FunctionProtoType *NewProto 3875 = New->getType()->getAs<FunctionProtoType>(); 3876 3877 // Determine whether this is the GNU C extension. 3878 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3879 NewProto->getReturnType()); 3880 bool LooseCompatible = !MergedReturn.isNull(); 3881 for (unsigned Idx = 0, End = Old->getNumParams(); 3882 LooseCompatible && Idx != End; ++Idx) { 3883 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3884 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3885 if (Context.typesAreCompatible(OldParm->getType(), 3886 NewProto->getParamType(Idx))) { 3887 ArgTypes.push_back(NewParm->getType()); 3888 } else if (Context.typesAreCompatible(OldParm->getType(), 3889 NewParm->getType(), 3890 /*CompareUnqualified=*/true)) { 3891 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3892 NewProto->getParamType(Idx) }; 3893 Warnings.push_back(Warn); 3894 ArgTypes.push_back(NewParm->getType()); 3895 } else 3896 LooseCompatible = false; 3897 } 3898 3899 if (LooseCompatible) { 3900 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3901 Diag(Warnings[Warn].NewParm->getLocation(), 3902 diag::ext_param_promoted_not_compatible_with_prototype) 3903 << Warnings[Warn].PromotedType 3904 << Warnings[Warn].OldParm->getType(); 3905 if (Warnings[Warn].OldParm->getLocation().isValid()) 3906 Diag(Warnings[Warn].OldParm->getLocation(), 3907 diag::note_previous_declaration); 3908 } 3909 3910 if (MergeTypeWithOld) 3911 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3912 OldProto->getExtProtoInfo())); 3913 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3914 } 3915 3916 // Fall through to diagnose conflicting types. 3917 } 3918 3919 // A function that has already been declared has been redeclared or 3920 // defined with a different type; show an appropriate diagnostic. 3921 3922 // If the previous declaration was an implicitly-generated builtin 3923 // declaration, then at the very least we should use a specialized note. 3924 unsigned BuiltinID; 3925 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3926 // If it's actually a library-defined builtin function like 'malloc' 3927 // or 'printf', just warn about the incompatible redeclaration. 3928 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3929 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3930 Diag(OldLocation, diag::note_previous_builtin_declaration) 3931 << Old << Old->getType(); 3932 return false; 3933 } 3934 3935 PrevDiag = diag::note_previous_builtin_declaration; 3936 } 3937 3938 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3939 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3940 return true; 3941 } 3942 3943 /// Completes the merge of two function declarations that are 3944 /// known to be compatible. 3945 /// 3946 /// This routine handles the merging of attributes and other 3947 /// properties of function declarations from the old declaration to 3948 /// the new declaration, once we know that New is in fact a 3949 /// redeclaration of Old. 3950 /// 3951 /// \returns false 3952 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3953 Scope *S, bool MergeTypeWithOld) { 3954 // Merge the attributes 3955 mergeDeclAttributes(New, Old); 3956 3957 // Merge "pure" flag. 3958 if (Old->isPure()) 3959 New->setPure(); 3960 3961 // Merge "used" flag. 3962 if (Old->getMostRecentDecl()->isUsed(false)) 3963 New->setIsUsed(); 3964 3965 // Merge attributes from the parameters. These can mismatch with K&R 3966 // declarations. 3967 if (New->getNumParams() == Old->getNumParams()) 3968 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3969 ParmVarDecl *NewParam = New->getParamDecl(i); 3970 ParmVarDecl *OldParam = Old->getParamDecl(i); 3971 mergeParamDeclAttributes(NewParam, OldParam, *this); 3972 mergeParamDeclTypes(NewParam, OldParam, *this); 3973 } 3974 3975 if (getLangOpts().CPlusPlus) 3976 return MergeCXXFunctionDecl(New, Old, S); 3977 3978 // Merge the function types so the we get the composite types for the return 3979 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3980 // was visible. 3981 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3982 if (!Merged.isNull() && MergeTypeWithOld) 3983 New->setType(Merged); 3984 3985 return false; 3986 } 3987 3988 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3989 ObjCMethodDecl *oldMethod) { 3990 // Merge the attributes, including deprecated/unavailable 3991 AvailabilityMergeKind MergeKind = 3992 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3993 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 3994 : AMK_ProtocolImplementation) 3995 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3996 : AMK_Override; 3997 3998 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3999 4000 // Merge attributes from the parameters. 4001 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 4002 oe = oldMethod->param_end(); 4003 for (ObjCMethodDecl::param_iterator 4004 ni = newMethod->param_begin(), ne = newMethod->param_end(); 4005 ni != ne && oi != oe; ++ni, ++oi) 4006 mergeParamDeclAttributes(*ni, *oi, *this); 4007 4008 CheckObjCMethodOverride(newMethod, oldMethod); 4009 } 4010 4011 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 4012 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 4013 4014 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 4015 ? diag::err_redefinition_different_type 4016 : diag::err_redeclaration_different_type) 4017 << New->getDeclName() << New->getType() << Old->getType(); 4018 4019 diag::kind PrevDiag; 4020 SourceLocation OldLocation; 4021 std::tie(PrevDiag, OldLocation) 4022 = getNoteDiagForInvalidRedeclaration(Old, New); 4023 S.Diag(OldLocation, PrevDiag); 4024 New->setInvalidDecl(); 4025 } 4026 4027 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 4028 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 4029 /// emitting diagnostics as appropriate. 4030 /// 4031 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 4032 /// to here in AddInitializerToDecl. We can't check them before the initializer 4033 /// is attached. 4034 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 4035 bool MergeTypeWithOld) { 4036 if (New->isInvalidDecl() || Old->isInvalidDecl()) 4037 return; 4038 4039 QualType MergedT; 4040 if (getLangOpts().CPlusPlus) { 4041 if (New->getType()->isUndeducedType()) { 4042 // We don't know what the new type is until the initializer is attached. 4043 return; 4044 } else if (Context.hasSameType(New->getType(), Old->getType())) { 4045 // These could still be something that needs exception specs checked. 4046 return MergeVarDeclExceptionSpecs(New, Old); 4047 } 4048 // C++ [basic.link]p10: 4049 // [...] the types specified by all declarations referring to a given 4050 // object or function shall be identical, except that declarations for an 4051 // array object can specify array types that differ by the presence or 4052 // absence of a major array bound (8.3.4). 4053 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4054 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4055 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4056 4057 // We are merging a variable declaration New into Old. If it has an array 4058 // bound, and that bound differs from Old's bound, we should diagnose the 4059 // mismatch. 4060 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4061 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4062 PrevVD = PrevVD->getPreviousDecl()) { 4063 QualType PrevVDTy = PrevVD->getType(); 4064 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4065 continue; 4066 4067 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4068 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4069 } 4070 } 4071 4072 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4073 if (Context.hasSameType(OldArray->getElementType(), 4074 NewArray->getElementType())) 4075 MergedT = New->getType(); 4076 } 4077 // FIXME: Check visibility. New is hidden but has a complete type. If New 4078 // has no array bound, it should not inherit one from Old, if Old is not 4079 // visible. 4080 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4081 if (Context.hasSameType(OldArray->getElementType(), 4082 NewArray->getElementType())) 4083 MergedT = Old->getType(); 4084 } 4085 } 4086 else if (New->getType()->isObjCObjectPointerType() && 4087 Old->getType()->isObjCObjectPointerType()) { 4088 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4089 Old->getType()); 4090 } 4091 } else { 4092 // C 6.2.7p2: 4093 // All declarations that refer to the same object or function shall have 4094 // compatible type. 4095 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4096 } 4097 if (MergedT.isNull()) { 4098 // It's OK if we couldn't merge types if either type is dependent, for a 4099 // block-scope variable. In other cases (static data members of class 4100 // templates, variable templates, ...), we require the types to be 4101 // equivalent. 4102 // FIXME: The C++ standard doesn't say anything about this. 4103 if ((New->getType()->isDependentType() || 4104 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4105 // If the old type was dependent, we can't merge with it, so the new type 4106 // becomes dependent for now. We'll reproduce the original type when we 4107 // instantiate the TypeSourceInfo for the variable. 4108 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4109 New->setType(Context.DependentTy); 4110 return; 4111 } 4112 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4113 } 4114 4115 // Don't actually update the type on the new declaration if the old 4116 // declaration was an extern declaration in a different scope. 4117 if (MergeTypeWithOld) 4118 New->setType(MergedT); 4119 } 4120 4121 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4122 LookupResult &Previous) { 4123 // C11 6.2.7p4: 4124 // For an identifier with internal or external linkage declared 4125 // in a scope in which a prior declaration of that identifier is 4126 // visible, if the prior declaration specifies internal or 4127 // external linkage, the type of the identifier at the later 4128 // declaration becomes the composite type. 4129 // 4130 // If the variable isn't visible, we do not merge with its type. 4131 if (Previous.isShadowed()) 4132 return false; 4133 4134 if (S.getLangOpts().CPlusPlus) { 4135 // C++11 [dcl.array]p3: 4136 // If there is a preceding declaration of the entity in the same 4137 // scope in which the bound was specified, an omitted array bound 4138 // is taken to be the same as in that earlier declaration. 4139 return NewVD->isPreviousDeclInSameBlockScope() || 4140 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4141 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4142 } else { 4143 // If the old declaration was function-local, don't merge with its 4144 // type unless we're in the same function. 4145 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4146 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4147 } 4148 } 4149 4150 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4151 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4152 /// situation, merging decls or emitting diagnostics as appropriate. 4153 /// 4154 /// Tentative definition rules (C99 6.9.2p2) are checked by 4155 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4156 /// definitions here, since the initializer hasn't been attached. 4157 /// 4158 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4159 // If the new decl is already invalid, don't do any other checking. 4160 if (New->isInvalidDecl()) 4161 return; 4162 4163 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4164 return; 4165 4166 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4167 4168 // Verify the old decl was also a variable or variable template. 4169 VarDecl *Old = nullptr; 4170 VarTemplateDecl *OldTemplate = nullptr; 4171 if (Previous.isSingleResult()) { 4172 if (NewTemplate) { 4173 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4174 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4175 4176 if (auto *Shadow = 4177 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4178 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4179 return New->setInvalidDecl(); 4180 } else { 4181 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4182 4183 if (auto *Shadow = 4184 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4185 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4186 return New->setInvalidDecl(); 4187 } 4188 } 4189 if (!Old) { 4190 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4191 << New->getDeclName(); 4192 notePreviousDefinition(Previous.getRepresentativeDecl(), 4193 New->getLocation()); 4194 return New->setInvalidDecl(); 4195 } 4196 4197 // If the old declaration was found in an inline namespace and the new 4198 // declaration was qualified, update the DeclContext to match. 4199 adjustDeclContextForDeclaratorDecl(New, Old); 4200 4201 // Ensure the template parameters are compatible. 4202 if (NewTemplate && 4203 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4204 OldTemplate->getTemplateParameters(), 4205 /*Complain=*/true, TPL_TemplateMatch)) 4206 return New->setInvalidDecl(); 4207 4208 // C++ [class.mem]p1: 4209 // A member shall not be declared twice in the member-specification [...] 4210 // 4211 // Here, we need only consider static data members. 4212 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4213 Diag(New->getLocation(), diag::err_duplicate_member) 4214 << New->getIdentifier(); 4215 Diag(Old->getLocation(), diag::note_previous_declaration); 4216 New->setInvalidDecl(); 4217 } 4218 4219 mergeDeclAttributes(New, Old); 4220 // Warn if an already-declared variable is made a weak_import in a subsequent 4221 // declaration 4222 if (New->hasAttr<WeakImportAttr>() && 4223 Old->getStorageClass() == SC_None && 4224 !Old->hasAttr<WeakImportAttr>()) { 4225 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4226 Diag(Old->getLocation(), diag::note_previous_declaration); 4227 // Remove weak_import attribute on new declaration. 4228 New->dropAttr<WeakImportAttr>(); 4229 } 4230 4231 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4232 if (!Old->hasAttr<InternalLinkageAttr>()) { 4233 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4234 << ILA; 4235 Diag(Old->getLocation(), diag::note_previous_declaration); 4236 New->dropAttr<InternalLinkageAttr>(); 4237 } 4238 4239 // Merge the types. 4240 VarDecl *MostRecent = Old->getMostRecentDecl(); 4241 if (MostRecent != Old) { 4242 MergeVarDeclTypes(New, MostRecent, 4243 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4244 if (New->isInvalidDecl()) 4245 return; 4246 } 4247 4248 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4249 if (New->isInvalidDecl()) 4250 return; 4251 4252 diag::kind PrevDiag; 4253 SourceLocation OldLocation; 4254 std::tie(PrevDiag, OldLocation) = 4255 getNoteDiagForInvalidRedeclaration(Old, New); 4256 4257 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4258 if (New->getStorageClass() == SC_Static && 4259 !New->isStaticDataMember() && 4260 Old->hasExternalFormalLinkage()) { 4261 if (getLangOpts().MicrosoftExt) { 4262 Diag(New->getLocation(), diag::ext_static_non_static) 4263 << New->getDeclName(); 4264 Diag(OldLocation, PrevDiag); 4265 } else { 4266 Diag(New->getLocation(), diag::err_static_non_static) 4267 << New->getDeclName(); 4268 Diag(OldLocation, PrevDiag); 4269 return New->setInvalidDecl(); 4270 } 4271 } 4272 // C99 6.2.2p4: 4273 // For an identifier declared with the storage-class specifier 4274 // extern in a scope in which a prior declaration of that 4275 // identifier is visible,23) if the prior declaration specifies 4276 // internal or external linkage, the linkage of the identifier at 4277 // the later declaration is the same as the linkage specified at 4278 // the prior declaration. If no prior declaration is visible, or 4279 // if the prior declaration specifies no linkage, then the 4280 // identifier has external linkage. 4281 if (New->hasExternalStorage() && Old->hasLinkage()) 4282 /* Okay */; 4283 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4284 !New->isStaticDataMember() && 4285 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4286 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4287 Diag(OldLocation, PrevDiag); 4288 return New->setInvalidDecl(); 4289 } 4290 4291 // Check if extern is followed by non-extern and vice-versa. 4292 if (New->hasExternalStorage() && 4293 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4294 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4295 Diag(OldLocation, PrevDiag); 4296 return New->setInvalidDecl(); 4297 } 4298 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4299 !New->hasExternalStorage()) { 4300 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4301 Diag(OldLocation, PrevDiag); 4302 return New->setInvalidDecl(); 4303 } 4304 4305 if (CheckRedeclarationInModule(New, Old)) 4306 return; 4307 4308 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4309 4310 // FIXME: The test for external storage here seems wrong? We still 4311 // need to check for mismatches. 4312 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4313 // Don't complain about out-of-line definitions of static members. 4314 !(Old->getLexicalDeclContext()->isRecord() && 4315 !New->getLexicalDeclContext()->isRecord())) { 4316 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4317 Diag(OldLocation, PrevDiag); 4318 return New->setInvalidDecl(); 4319 } 4320 4321 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4322 if (VarDecl *Def = Old->getDefinition()) { 4323 // C++1z [dcl.fcn.spec]p4: 4324 // If the definition of a variable appears in a translation unit before 4325 // its first declaration as inline, the program is ill-formed. 4326 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4327 Diag(Def->getLocation(), diag::note_previous_definition); 4328 } 4329 } 4330 4331 // If this redeclaration makes the variable inline, we may need to add it to 4332 // UndefinedButUsed. 4333 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4334 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4335 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4336 SourceLocation())); 4337 4338 if (New->getTLSKind() != Old->getTLSKind()) { 4339 if (!Old->getTLSKind()) { 4340 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4341 Diag(OldLocation, PrevDiag); 4342 } else if (!New->getTLSKind()) { 4343 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4344 Diag(OldLocation, PrevDiag); 4345 } else { 4346 // Do not allow redeclaration to change the variable between requiring 4347 // static and dynamic initialization. 4348 // FIXME: GCC allows this, but uses the TLS keyword on the first 4349 // declaration to determine the kind. Do we need to be compatible here? 4350 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4351 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4352 Diag(OldLocation, PrevDiag); 4353 } 4354 } 4355 4356 // C++ doesn't have tentative definitions, so go right ahead and check here. 4357 if (getLangOpts().CPlusPlus && 4358 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4359 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4360 Old->getCanonicalDecl()->isConstexpr()) { 4361 // This definition won't be a definition any more once it's been merged. 4362 Diag(New->getLocation(), 4363 diag::warn_deprecated_redundant_constexpr_static_def); 4364 } else if (VarDecl *Def = Old->getDefinition()) { 4365 if (checkVarDeclRedefinition(Def, New)) 4366 return; 4367 } 4368 } 4369 4370 if (haveIncompatibleLanguageLinkages(Old, New)) { 4371 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4372 Diag(OldLocation, PrevDiag); 4373 New->setInvalidDecl(); 4374 return; 4375 } 4376 4377 // Merge "used" flag. 4378 if (Old->getMostRecentDecl()->isUsed(false)) 4379 New->setIsUsed(); 4380 4381 // Keep a chain of previous declarations. 4382 New->setPreviousDecl(Old); 4383 if (NewTemplate) 4384 NewTemplate->setPreviousDecl(OldTemplate); 4385 4386 // Inherit access appropriately. 4387 New->setAccess(Old->getAccess()); 4388 if (NewTemplate) 4389 NewTemplate->setAccess(New->getAccess()); 4390 4391 if (Old->isInline()) 4392 New->setImplicitlyInline(); 4393 } 4394 4395 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4396 SourceManager &SrcMgr = getSourceManager(); 4397 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4398 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4399 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4400 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4401 auto &HSI = PP.getHeaderSearchInfo(); 4402 StringRef HdrFilename = 4403 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4404 4405 auto noteFromModuleOrInclude = [&](Module *Mod, 4406 SourceLocation IncLoc) -> bool { 4407 // Redefinition errors with modules are common with non modular mapped 4408 // headers, example: a non-modular header H in module A that also gets 4409 // included directly in a TU. Pointing twice to the same header/definition 4410 // is confusing, try to get better diagnostics when modules is on. 4411 if (IncLoc.isValid()) { 4412 if (Mod) { 4413 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4414 << HdrFilename.str() << Mod->getFullModuleName(); 4415 if (!Mod->DefinitionLoc.isInvalid()) 4416 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4417 << Mod->getFullModuleName(); 4418 } else { 4419 Diag(IncLoc, diag::note_redefinition_include_same_file) 4420 << HdrFilename.str(); 4421 } 4422 return true; 4423 } 4424 4425 return false; 4426 }; 4427 4428 // Is it the same file and same offset? Provide more information on why 4429 // this leads to a redefinition error. 4430 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4431 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4432 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4433 bool EmittedDiag = 4434 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4435 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4436 4437 // If the header has no guards, emit a note suggesting one. 4438 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4439 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4440 4441 if (EmittedDiag) 4442 return; 4443 } 4444 4445 // Redefinition coming from different files or couldn't do better above. 4446 if (Old->getLocation().isValid()) 4447 Diag(Old->getLocation(), diag::note_previous_definition); 4448 } 4449 4450 /// We've just determined that \p Old and \p New both appear to be definitions 4451 /// of the same variable. Either diagnose or fix the problem. 4452 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4453 if (!hasVisibleDefinition(Old) && 4454 (New->getFormalLinkage() == InternalLinkage || 4455 New->isInline() || 4456 New->getDescribedVarTemplate() || 4457 New->getNumTemplateParameterLists() || 4458 New->getDeclContext()->isDependentContext())) { 4459 // The previous definition is hidden, and multiple definitions are 4460 // permitted (in separate TUs). Demote this to a declaration. 4461 New->demoteThisDefinitionToDeclaration(); 4462 4463 // Make the canonical definition visible. 4464 if (auto *OldTD = Old->getDescribedVarTemplate()) 4465 makeMergedDefinitionVisible(OldTD); 4466 makeMergedDefinitionVisible(Old); 4467 return false; 4468 } else { 4469 Diag(New->getLocation(), diag::err_redefinition) << New; 4470 notePreviousDefinition(Old, New->getLocation()); 4471 New->setInvalidDecl(); 4472 return true; 4473 } 4474 } 4475 4476 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4477 /// no declarator (e.g. "struct foo;") is parsed. 4478 Decl * 4479 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4480 RecordDecl *&AnonRecord) { 4481 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4482 AnonRecord); 4483 } 4484 4485 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4486 // disambiguate entities defined in different scopes. 4487 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4488 // compatibility. 4489 // We will pick our mangling number depending on which version of MSVC is being 4490 // targeted. 4491 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4492 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4493 ? S->getMSCurManglingNumber() 4494 : S->getMSLastManglingNumber(); 4495 } 4496 4497 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4498 if (!Context.getLangOpts().CPlusPlus) 4499 return; 4500 4501 if (isa<CXXRecordDecl>(Tag->getParent())) { 4502 // If this tag is the direct child of a class, number it if 4503 // it is anonymous. 4504 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4505 return; 4506 MangleNumberingContext &MCtx = 4507 Context.getManglingNumberContext(Tag->getParent()); 4508 Context.setManglingNumber( 4509 Tag, MCtx.getManglingNumber( 4510 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4511 return; 4512 } 4513 4514 // If this tag isn't a direct child of a class, number it if it is local. 4515 MangleNumberingContext *MCtx; 4516 Decl *ManglingContextDecl; 4517 std::tie(MCtx, ManglingContextDecl) = 4518 getCurrentMangleNumberContext(Tag->getDeclContext()); 4519 if (MCtx) { 4520 Context.setManglingNumber( 4521 Tag, MCtx->getManglingNumber( 4522 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4523 } 4524 } 4525 4526 namespace { 4527 struct NonCLikeKind { 4528 enum { 4529 None, 4530 BaseClass, 4531 DefaultMemberInit, 4532 Lambda, 4533 Friend, 4534 OtherMember, 4535 Invalid, 4536 } Kind = None; 4537 SourceRange Range; 4538 4539 explicit operator bool() { return Kind != None; } 4540 }; 4541 } 4542 4543 /// Determine whether a class is C-like, according to the rules of C++ 4544 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4545 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4546 if (RD->isInvalidDecl()) 4547 return {NonCLikeKind::Invalid, {}}; 4548 4549 // C++ [dcl.typedef]p9: [P1766R1] 4550 // An unnamed class with a typedef name for linkage purposes shall not 4551 // 4552 // -- have any base classes 4553 if (RD->getNumBases()) 4554 return {NonCLikeKind::BaseClass, 4555 SourceRange(RD->bases_begin()->getBeginLoc(), 4556 RD->bases_end()[-1].getEndLoc())}; 4557 bool Invalid = false; 4558 for (Decl *D : RD->decls()) { 4559 // Don't complain about things we already diagnosed. 4560 if (D->isInvalidDecl()) { 4561 Invalid = true; 4562 continue; 4563 } 4564 4565 // -- have any [...] default member initializers 4566 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4567 if (FD->hasInClassInitializer()) { 4568 auto *Init = FD->getInClassInitializer(); 4569 return {NonCLikeKind::DefaultMemberInit, 4570 Init ? Init->getSourceRange() : D->getSourceRange()}; 4571 } 4572 continue; 4573 } 4574 4575 // FIXME: We don't allow friend declarations. This violates the wording of 4576 // P1766, but not the intent. 4577 if (isa<FriendDecl>(D)) 4578 return {NonCLikeKind::Friend, D->getSourceRange()}; 4579 4580 // -- declare any members other than non-static data members, member 4581 // enumerations, or member classes, 4582 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4583 isa<EnumDecl>(D)) 4584 continue; 4585 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4586 if (!MemberRD) { 4587 if (D->isImplicit()) 4588 continue; 4589 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4590 } 4591 4592 // -- contain a lambda-expression, 4593 if (MemberRD->isLambda()) 4594 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4595 4596 // and all member classes shall also satisfy these requirements 4597 // (recursively). 4598 if (MemberRD->isThisDeclarationADefinition()) { 4599 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4600 return Kind; 4601 } 4602 } 4603 4604 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4605 } 4606 4607 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4608 TypedefNameDecl *NewTD) { 4609 if (TagFromDeclSpec->isInvalidDecl()) 4610 return; 4611 4612 // Do nothing if the tag already has a name for linkage purposes. 4613 if (TagFromDeclSpec->hasNameForLinkage()) 4614 return; 4615 4616 // A well-formed anonymous tag must always be a TUK_Definition. 4617 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4618 4619 // The type must match the tag exactly; no qualifiers allowed. 4620 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4621 Context.getTagDeclType(TagFromDeclSpec))) { 4622 if (getLangOpts().CPlusPlus) 4623 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4624 return; 4625 } 4626 4627 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4628 // An unnamed class with a typedef name for linkage purposes shall [be 4629 // C-like]. 4630 // 4631 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4632 // shouldn't happen, but there are constructs that the language rule doesn't 4633 // disallow for which we can't reasonably avoid computing linkage early. 4634 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4635 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4636 : NonCLikeKind(); 4637 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4638 if (NonCLike || ChangesLinkage) { 4639 if (NonCLike.Kind == NonCLikeKind::Invalid) 4640 return; 4641 4642 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4643 if (ChangesLinkage) { 4644 // If the linkage changes, we can't accept this as an extension. 4645 if (NonCLike.Kind == NonCLikeKind::None) 4646 DiagID = diag::err_typedef_changes_linkage; 4647 else 4648 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4649 } 4650 4651 SourceLocation FixitLoc = 4652 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4653 llvm::SmallString<40> TextToInsert; 4654 TextToInsert += ' '; 4655 TextToInsert += NewTD->getIdentifier()->getName(); 4656 4657 Diag(FixitLoc, DiagID) 4658 << isa<TypeAliasDecl>(NewTD) 4659 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4660 if (NonCLike.Kind != NonCLikeKind::None) { 4661 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4662 << NonCLike.Kind - 1 << NonCLike.Range; 4663 } 4664 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4665 << NewTD << isa<TypeAliasDecl>(NewTD); 4666 4667 if (ChangesLinkage) 4668 return; 4669 } 4670 4671 // Otherwise, set this as the anon-decl typedef for the tag. 4672 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4673 } 4674 4675 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4676 switch (T) { 4677 case DeclSpec::TST_class: 4678 return 0; 4679 case DeclSpec::TST_struct: 4680 return 1; 4681 case DeclSpec::TST_interface: 4682 return 2; 4683 case DeclSpec::TST_union: 4684 return 3; 4685 case DeclSpec::TST_enum: 4686 return 4; 4687 default: 4688 llvm_unreachable("unexpected type specifier"); 4689 } 4690 } 4691 4692 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4693 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4694 /// parameters to cope with template friend declarations. 4695 Decl * 4696 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4697 MultiTemplateParamsArg TemplateParams, 4698 bool IsExplicitInstantiation, 4699 RecordDecl *&AnonRecord) { 4700 Decl *TagD = nullptr; 4701 TagDecl *Tag = nullptr; 4702 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4703 DS.getTypeSpecType() == DeclSpec::TST_struct || 4704 DS.getTypeSpecType() == DeclSpec::TST_interface || 4705 DS.getTypeSpecType() == DeclSpec::TST_union || 4706 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4707 TagD = DS.getRepAsDecl(); 4708 4709 if (!TagD) // We probably had an error 4710 return nullptr; 4711 4712 // Note that the above type specs guarantee that the 4713 // type rep is a Decl, whereas in many of the others 4714 // it's a Type. 4715 if (isa<TagDecl>(TagD)) 4716 Tag = cast<TagDecl>(TagD); 4717 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4718 Tag = CTD->getTemplatedDecl(); 4719 } 4720 4721 if (Tag) { 4722 handleTagNumbering(Tag, S); 4723 Tag->setFreeStanding(); 4724 if (Tag->isInvalidDecl()) 4725 return Tag; 4726 } 4727 4728 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4729 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4730 // or incomplete types shall not be restrict-qualified." 4731 if (TypeQuals & DeclSpec::TQ_restrict) 4732 Diag(DS.getRestrictSpecLoc(), 4733 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4734 << DS.getSourceRange(); 4735 } 4736 4737 if (DS.isInlineSpecified()) 4738 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4739 << getLangOpts().CPlusPlus17; 4740 4741 if (DS.hasConstexprSpecifier()) { 4742 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4743 // and definitions of functions and variables. 4744 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4745 // the declaration of a function or function template 4746 if (Tag) 4747 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4748 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4749 << static_cast<int>(DS.getConstexprSpecifier()); 4750 else 4751 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4752 << static_cast<int>(DS.getConstexprSpecifier()); 4753 // Don't emit warnings after this error. 4754 return TagD; 4755 } 4756 4757 DiagnoseFunctionSpecifiers(DS); 4758 4759 if (DS.isFriendSpecified()) { 4760 // If we're dealing with a decl but not a TagDecl, assume that 4761 // whatever routines created it handled the friendship aspect. 4762 if (TagD && !Tag) 4763 return nullptr; 4764 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4765 } 4766 4767 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4768 bool IsExplicitSpecialization = 4769 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4770 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4771 !IsExplicitInstantiation && !IsExplicitSpecialization && 4772 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4773 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4774 // nested-name-specifier unless it is an explicit instantiation 4775 // or an explicit specialization. 4776 // 4777 // FIXME: We allow class template partial specializations here too, per the 4778 // obvious intent of DR1819. 4779 // 4780 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4781 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4782 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4783 return nullptr; 4784 } 4785 4786 // Track whether this decl-specifier declares anything. 4787 bool DeclaresAnything = true; 4788 4789 // Handle anonymous struct definitions. 4790 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4791 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4792 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4793 if (getLangOpts().CPlusPlus || 4794 Record->getDeclContext()->isRecord()) { 4795 // If CurContext is a DeclContext that can contain statements, 4796 // RecursiveASTVisitor won't visit the decls that 4797 // BuildAnonymousStructOrUnion() will put into CurContext. 4798 // Also store them here so that they can be part of the 4799 // DeclStmt that gets created in this case. 4800 // FIXME: Also return the IndirectFieldDecls created by 4801 // BuildAnonymousStructOr union, for the same reason? 4802 if (CurContext->isFunctionOrMethod()) 4803 AnonRecord = Record; 4804 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4805 Context.getPrintingPolicy()); 4806 } 4807 4808 DeclaresAnything = false; 4809 } 4810 } 4811 4812 // C11 6.7.2.1p2: 4813 // A struct-declaration that does not declare an anonymous structure or 4814 // anonymous union shall contain a struct-declarator-list. 4815 // 4816 // This rule also existed in C89 and C99; the grammar for struct-declaration 4817 // did not permit a struct-declaration without a struct-declarator-list. 4818 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4819 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4820 // Check for Microsoft C extension: anonymous struct/union member. 4821 // Handle 2 kinds of anonymous struct/union: 4822 // struct STRUCT; 4823 // union UNION; 4824 // and 4825 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4826 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4827 if ((Tag && Tag->getDeclName()) || 4828 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4829 RecordDecl *Record = nullptr; 4830 if (Tag) 4831 Record = dyn_cast<RecordDecl>(Tag); 4832 else if (const RecordType *RT = 4833 DS.getRepAsType().get()->getAsStructureType()) 4834 Record = RT->getDecl(); 4835 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4836 Record = UT->getDecl(); 4837 4838 if (Record && getLangOpts().MicrosoftExt) { 4839 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4840 << Record->isUnion() << DS.getSourceRange(); 4841 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4842 } 4843 4844 DeclaresAnything = false; 4845 } 4846 } 4847 4848 // Skip all the checks below if we have a type error. 4849 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4850 (TagD && TagD->isInvalidDecl())) 4851 return TagD; 4852 4853 if (getLangOpts().CPlusPlus && 4854 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4855 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4856 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4857 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4858 DeclaresAnything = false; 4859 4860 if (!DS.isMissingDeclaratorOk()) { 4861 // Customize diagnostic for a typedef missing a name. 4862 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4863 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4864 << DS.getSourceRange(); 4865 else 4866 DeclaresAnything = false; 4867 } 4868 4869 if (DS.isModulePrivateSpecified() && 4870 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4871 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4872 << Tag->getTagKind() 4873 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4874 4875 ActOnDocumentableDecl(TagD); 4876 4877 // C 6.7/2: 4878 // A declaration [...] shall declare at least a declarator [...], a tag, 4879 // or the members of an enumeration. 4880 // C++ [dcl.dcl]p3: 4881 // [If there are no declarators], and except for the declaration of an 4882 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4883 // names into the program, or shall redeclare a name introduced by a 4884 // previous declaration. 4885 if (!DeclaresAnything) { 4886 // In C, we allow this as a (popular) extension / bug. Don't bother 4887 // producing further diagnostics for redundant qualifiers after this. 4888 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4889 ? diag::err_no_declarators 4890 : diag::ext_no_declarators) 4891 << DS.getSourceRange(); 4892 return TagD; 4893 } 4894 4895 // C++ [dcl.stc]p1: 4896 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4897 // init-declarator-list of the declaration shall not be empty. 4898 // C++ [dcl.fct.spec]p1: 4899 // If a cv-qualifier appears in a decl-specifier-seq, the 4900 // init-declarator-list of the declaration shall not be empty. 4901 // 4902 // Spurious qualifiers here appear to be valid in C. 4903 unsigned DiagID = diag::warn_standalone_specifier; 4904 if (getLangOpts().CPlusPlus) 4905 DiagID = diag::ext_standalone_specifier; 4906 4907 // Note that a linkage-specification sets a storage class, but 4908 // 'extern "C" struct foo;' is actually valid and not theoretically 4909 // useless. 4910 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4911 if (SCS == DeclSpec::SCS_mutable) 4912 // Since mutable is not a viable storage class specifier in C, there is 4913 // no reason to treat it as an extension. Instead, diagnose as an error. 4914 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4915 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4916 Diag(DS.getStorageClassSpecLoc(), DiagID) 4917 << DeclSpec::getSpecifierName(SCS); 4918 } 4919 4920 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4921 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4922 << DeclSpec::getSpecifierName(TSCS); 4923 if (DS.getTypeQualifiers()) { 4924 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4925 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4926 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4927 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4928 // Restrict is covered above. 4929 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4930 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4931 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4932 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4933 } 4934 4935 // Warn about ignored type attributes, for example: 4936 // __attribute__((aligned)) struct A; 4937 // Attributes should be placed after tag to apply to type declaration. 4938 if (!DS.getAttributes().empty()) { 4939 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4940 if (TypeSpecType == DeclSpec::TST_class || 4941 TypeSpecType == DeclSpec::TST_struct || 4942 TypeSpecType == DeclSpec::TST_interface || 4943 TypeSpecType == DeclSpec::TST_union || 4944 TypeSpecType == DeclSpec::TST_enum) { 4945 for (const ParsedAttr &AL : DS.getAttributes()) 4946 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4947 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4948 } 4949 } 4950 4951 return TagD; 4952 } 4953 4954 /// We are trying to inject an anonymous member into the given scope; 4955 /// check if there's an existing declaration that can't be overloaded. 4956 /// 4957 /// \return true if this is a forbidden redeclaration 4958 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4959 Scope *S, 4960 DeclContext *Owner, 4961 DeclarationName Name, 4962 SourceLocation NameLoc, 4963 bool IsUnion) { 4964 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4965 Sema::ForVisibleRedeclaration); 4966 if (!SemaRef.LookupName(R, S)) return false; 4967 4968 // Pick a representative declaration. 4969 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4970 assert(PrevDecl && "Expected a non-null Decl"); 4971 4972 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4973 return false; 4974 4975 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4976 << IsUnion << Name; 4977 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4978 4979 return true; 4980 } 4981 4982 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4983 /// anonymous struct or union AnonRecord into the owning context Owner 4984 /// and scope S. This routine will be invoked just after we realize 4985 /// that an unnamed union or struct is actually an anonymous union or 4986 /// struct, e.g., 4987 /// 4988 /// @code 4989 /// union { 4990 /// int i; 4991 /// float f; 4992 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4993 /// // f into the surrounding scope.x 4994 /// @endcode 4995 /// 4996 /// This routine is recursive, injecting the names of nested anonymous 4997 /// structs/unions into the owning context and scope as well. 4998 static bool 4999 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 5000 RecordDecl *AnonRecord, AccessSpecifier AS, 5001 SmallVectorImpl<NamedDecl *> &Chaining) { 5002 bool Invalid = false; 5003 5004 // Look every FieldDecl and IndirectFieldDecl with a name. 5005 for (auto *D : AnonRecord->decls()) { 5006 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 5007 cast<NamedDecl>(D)->getDeclName()) { 5008 ValueDecl *VD = cast<ValueDecl>(D); 5009 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 5010 VD->getLocation(), 5011 AnonRecord->isUnion())) { 5012 // C++ [class.union]p2: 5013 // The names of the members of an anonymous union shall be 5014 // distinct from the names of any other entity in the 5015 // scope in which the anonymous union is declared. 5016 Invalid = true; 5017 } else { 5018 // C++ [class.union]p2: 5019 // For the purpose of name lookup, after the anonymous union 5020 // definition, the members of the anonymous union are 5021 // considered to have been defined in the scope in which the 5022 // anonymous union is declared. 5023 unsigned OldChainingSize = Chaining.size(); 5024 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 5025 Chaining.append(IF->chain_begin(), IF->chain_end()); 5026 else 5027 Chaining.push_back(VD); 5028 5029 assert(Chaining.size() >= 2); 5030 NamedDecl **NamedChain = 5031 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 5032 for (unsigned i = 0; i < Chaining.size(); i++) 5033 NamedChain[i] = Chaining[i]; 5034 5035 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 5036 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 5037 VD->getType(), {NamedChain, Chaining.size()}); 5038 5039 for (const auto *Attr : VD->attrs()) 5040 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 5041 5042 IndirectField->setAccess(AS); 5043 IndirectField->setImplicit(); 5044 SemaRef.PushOnScopeChains(IndirectField, S); 5045 5046 // That includes picking up the appropriate access specifier. 5047 if (AS != AS_none) IndirectField->setAccess(AS); 5048 5049 Chaining.resize(OldChainingSize); 5050 } 5051 } 5052 } 5053 5054 return Invalid; 5055 } 5056 5057 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5058 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5059 /// illegal input values are mapped to SC_None. 5060 static StorageClass 5061 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5062 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5063 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5064 "Parser allowed 'typedef' as storage class VarDecl."); 5065 switch (StorageClassSpec) { 5066 case DeclSpec::SCS_unspecified: return SC_None; 5067 case DeclSpec::SCS_extern: 5068 if (DS.isExternInLinkageSpec()) 5069 return SC_None; 5070 return SC_Extern; 5071 case DeclSpec::SCS_static: return SC_Static; 5072 case DeclSpec::SCS_auto: return SC_Auto; 5073 case DeclSpec::SCS_register: return SC_Register; 5074 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5075 // Illegal SCSs map to None: error reporting is up to the caller. 5076 case DeclSpec::SCS_mutable: // Fall through. 5077 case DeclSpec::SCS_typedef: return SC_None; 5078 } 5079 llvm_unreachable("unknown storage class specifier"); 5080 } 5081 5082 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5083 assert(Record->hasInClassInitializer()); 5084 5085 for (const auto *I : Record->decls()) { 5086 const auto *FD = dyn_cast<FieldDecl>(I); 5087 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5088 FD = IFD->getAnonField(); 5089 if (FD && FD->hasInClassInitializer()) 5090 return FD->getLocation(); 5091 } 5092 5093 llvm_unreachable("couldn't find in-class initializer"); 5094 } 5095 5096 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5097 SourceLocation DefaultInitLoc) { 5098 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5099 return; 5100 5101 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5102 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5103 } 5104 5105 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5106 CXXRecordDecl *AnonUnion) { 5107 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5108 return; 5109 5110 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5111 } 5112 5113 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5114 /// anonymous structure or union. Anonymous unions are a C++ feature 5115 /// (C++ [class.union]) and a C11 feature; anonymous structures 5116 /// are a C11 feature and GNU C++ extension. 5117 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5118 AccessSpecifier AS, 5119 RecordDecl *Record, 5120 const PrintingPolicy &Policy) { 5121 DeclContext *Owner = Record->getDeclContext(); 5122 5123 // Diagnose whether this anonymous struct/union is an extension. 5124 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5125 Diag(Record->getLocation(), diag::ext_anonymous_union); 5126 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5127 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5128 else if (!Record->isUnion() && !getLangOpts().C11) 5129 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5130 5131 // C and C++ require different kinds of checks for anonymous 5132 // structs/unions. 5133 bool Invalid = false; 5134 if (getLangOpts().CPlusPlus) { 5135 const char *PrevSpec = nullptr; 5136 if (Record->isUnion()) { 5137 // C++ [class.union]p6: 5138 // C++17 [class.union.anon]p2: 5139 // Anonymous unions declared in a named namespace or in the 5140 // global namespace shall be declared static. 5141 unsigned DiagID; 5142 DeclContext *OwnerScope = Owner->getRedeclContext(); 5143 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5144 (OwnerScope->isTranslationUnit() || 5145 (OwnerScope->isNamespace() && 5146 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5147 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5148 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5149 5150 // Recover by adding 'static'. 5151 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5152 PrevSpec, DiagID, Policy); 5153 } 5154 // C++ [class.union]p6: 5155 // A storage class is not allowed in a declaration of an 5156 // anonymous union in a class scope. 5157 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5158 isa<RecordDecl>(Owner)) { 5159 Diag(DS.getStorageClassSpecLoc(), 5160 diag::err_anonymous_union_with_storage_spec) 5161 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5162 5163 // Recover by removing the storage specifier. 5164 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5165 SourceLocation(), 5166 PrevSpec, DiagID, Context.getPrintingPolicy()); 5167 } 5168 } 5169 5170 // Ignore const/volatile/restrict qualifiers. 5171 if (DS.getTypeQualifiers()) { 5172 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5173 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5174 << Record->isUnion() << "const" 5175 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5176 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5177 Diag(DS.getVolatileSpecLoc(), 5178 diag::ext_anonymous_struct_union_qualified) 5179 << Record->isUnion() << "volatile" 5180 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5181 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5182 Diag(DS.getRestrictSpecLoc(), 5183 diag::ext_anonymous_struct_union_qualified) 5184 << Record->isUnion() << "restrict" 5185 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5186 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5187 Diag(DS.getAtomicSpecLoc(), 5188 diag::ext_anonymous_struct_union_qualified) 5189 << Record->isUnion() << "_Atomic" 5190 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5191 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5192 Diag(DS.getUnalignedSpecLoc(), 5193 diag::ext_anonymous_struct_union_qualified) 5194 << Record->isUnion() << "__unaligned" 5195 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5196 5197 DS.ClearTypeQualifiers(); 5198 } 5199 5200 // C++ [class.union]p2: 5201 // The member-specification of an anonymous union shall only 5202 // define non-static data members. [Note: nested types and 5203 // functions cannot be declared within an anonymous union. ] 5204 for (auto *Mem : Record->decls()) { 5205 // Ignore invalid declarations; we already diagnosed them. 5206 if (Mem->isInvalidDecl()) 5207 continue; 5208 5209 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5210 // C++ [class.union]p3: 5211 // An anonymous union shall not have private or protected 5212 // members (clause 11). 5213 assert(FD->getAccess() != AS_none); 5214 if (FD->getAccess() != AS_public) { 5215 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5216 << Record->isUnion() << (FD->getAccess() == AS_protected); 5217 Invalid = true; 5218 } 5219 5220 // C++ [class.union]p1 5221 // An object of a class with a non-trivial constructor, a non-trivial 5222 // copy constructor, a non-trivial destructor, or a non-trivial copy 5223 // assignment operator cannot be a member of a union, nor can an 5224 // array of such objects. 5225 if (CheckNontrivialField(FD)) 5226 Invalid = true; 5227 } else if (Mem->isImplicit()) { 5228 // Any implicit members are fine. 5229 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5230 // This is a type that showed up in an 5231 // elaborated-type-specifier inside the anonymous struct or 5232 // union, but which actually declares a type outside of the 5233 // anonymous struct or union. It's okay. 5234 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5235 if (!MemRecord->isAnonymousStructOrUnion() && 5236 MemRecord->getDeclName()) { 5237 // Visual C++ allows type definition in anonymous struct or union. 5238 if (getLangOpts().MicrosoftExt) 5239 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5240 << Record->isUnion(); 5241 else { 5242 // This is a nested type declaration. 5243 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5244 << Record->isUnion(); 5245 Invalid = true; 5246 } 5247 } else { 5248 // This is an anonymous type definition within another anonymous type. 5249 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5250 // not part of standard C++. 5251 Diag(MemRecord->getLocation(), 5252 diag::ext_anonymous_record_with_anonymous_type) 5253 << Record->isUnion(); 5254 } 5255 } else if (isa<AccessSpecDecl>(Mem)) { 5256 // Any access specifier is fine. 5257 } else if (isa<StaticAssertDecl>(Mem)) { 5258 // In C++1z, static_assert declarations are also fine. 5259 } else { 5260 // We have something that isn't a non-static data 5261 // member. Complain about it. 5262 unsigned DK = diag::err_anonymous_record_bad_member; 5263 if (isa<TypeDecl>(Mem)) 5264 DK = diag::err_anonymous_record_with_type; 5265 else if (isa<FunctionDecl>(Mem)) 5266 DK = diag::err_anonymous_record_with_function; 5267 else if (isa<VarDecl>(Mem)) 5268 DK = diag::err_anonymous_record_with_static; 5269 5270 // Visual C++ allows type definition in anonymous struct or union. 5271 if (getLangOpts().MicrosoftExt && 5272 DK == diag::err_anonymous_record_with_type) 5273 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5274 << Record->isUnion(); 5275 else { 5276 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5277 Invalid = true; 5278 } 5279 } 5280 } 5281 5282 // C++11 [class.union]p8 (DR1460): 5283 // At most one variant member of a union may have a 5284 // brace-or-equal-initializer. 5285 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5286 Owner->isRecord()) 5287 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5288 cast<CXXRecordDecl>(Record)); 5289 } 5290 5291 if (!Record->isUnion() && !Owner->isRecord()) { 5292 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5293 << getLangOpts().CPlusPlus; 5294 Invalid = true; 5295 } 5296 5297 // C++ [dcl.dcl]p3: 5298 // [If there are no declarators], and except for the declaration of an 5299 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5300 // names into the program 5301 // C++ [class.mem]p2: 5302 // each such member-declaration shall either declare at least one member 5303 // name of the class or declare at least one unnamed bit-field 5304 // 5305 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5306 if (getLangOpts().CPlusPlus && Record->field_empty()) 5307 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5308 5309 // Mock up a declarator. 5310 Declarator Dc(DS, DeclaratorContext::Member); 5311 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5312 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5313 5314 // Create a declaration for this anonymous struct/union. 5315 NamedDecl *Anon = nullptr; 5316 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5317 Anon = FieldDecl::Create( 5318 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5319 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5320 /*BitWidth=*/nullptr, /*Mutable=*/false, 5321 /*InitStyle=*/ICIS_NoInit); 5322 Anon->setAccess(AS); 5323 ProcessDeclAttributes(S, Anon, Dc); 5324 5325 if (getLangOpts().CPlusPlus) 5326 FieldCollector->Add(cast<FieldDecl>(Anon)); 5327 } else { 5328 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5329 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5330 if (SCSpec == DeclSpec::SCS_mutable) { 5331 // mutable can only appear on non-static class members, so it's always 5332 // an error here 5333 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5334 Invalid = true; 5335 SC = SC_None; 5336 } 5337 5338 assert(DS.getAttributes().empty() && "No attribute expected"); 5339 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5340 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5341 Context.getTypeDeclType(Record), TInfo, SC); 5342 5343 // Default-initialize the implicit variable. This initialization will be 5344 // trivial in almost all cases, except if a union member has an in-class 5345 // initializer: 5346 // union { int n = 0; }; 5347 ActOnUninitializedDecl(Anon); 5348 } 5349 Anon->setImplicit(); 5350 5351 // Mark this as an anonymous struct/union type. 5352 Record->setAnonymousStructOrUnion(true); 5353 5354 // Add the anonymous struct/union object to the current 5355 // context. We'll be referencing this object when we refer to one of 5356 // its members. 5357 Owner->addDecl(Anon); 5358 5359 // Inject the members of the anonymous struct/union into the owning 5360 // context and into the identifier resolver chain for name lookup 5361 // purposes. 5362 SmallVector<NamedDecl*, 2> Chain; 5363 Chain.push_back(Anon); 5364 5365 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5366 Invalid = true; 5367 5368 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5369 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5370 MangleNumberingContext *MCtx; 5371 Decl *ManglingContextDecl; 5372 std::tie(MCtx, ManglingContextDecl) = 5373 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5374 if (MCtx) { 5375 Context.setManglingNumber( 5376 NewVD, MCtx->getManglingNumber( 5377 NewVD, getMSManglingNumber(getLangOpts(), S))); 5378 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5379 } 5380 } 5381 } 5382 5383 if (Invalid) 5384 Anon->setInvalidDecl(); 5385 5386 return Anon; 5387 } 5388 5389 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5390 /// Microsoft C anonymous structure. 5391 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5392 /// Example: 5393 /// 5394 /// struct A { int a; }; 5395 /// struct B { struct A; int b; }; 5396 /// 5397 /// void foo() { 5398 /// B var; 5399 /// var.a = 3; 5400 /// } 5401 /// 5402 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5403 RecordDecl *Record) { 5404 assert(Record && "expected a record!"); 5405 5406 // Mock up a declarator. 5407 Declarator Dc(DS, DeclaratorContext::TypeName); 5408 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5409 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5410 5411 auto *ParentDecl = cast<RecordDecl>(CurContext); 5412 QualType RecTy = Context.getTypeDeclType(Record); 5413 5414 // Create a declaration for this anonymous struct. 5415 NamedDecl *Anon = 5416 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5417 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5418 /*BitWidth=*/nullptr, /*Mutable=*/false, 5419 /*InitStyle=*/ICIS_NoInit); 5420 Anon->setImplicit(); 5421 5422 // Add the anonymous struct object to the current context. 5423 CurContext->addDecl(Anon); 5424 5425 // Inject the members of the anonymous struct into the current 5426 // context and into the identifier resolver chain for name lookup 5427 // purposes. 5428 SmallVector<NamedDecl*, 2> Chain; 5429 Chain.push_back(Anon); 5430 5431 RecordDecl *RecordDef = Record->getDefinition(); 5432 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5433 diag::err_field_incomplete_or_sizeless) || 5434 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5435 AS_none, Chain)) { 5436 Anon->setInvalidDecl(); 5437 ParentDecl->setInvalidDecl(); 5438 } 5439 5440 return Anon; 5441 } 5442 5443 /// GetNameForDeclarator - Determine the full declaration name for the 5444 /// given Declarator. 5445 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5446 return GetNameFromUnqualifiedId(D.getName()); 5447 } 5448 5449 /// Retrieves the declaration name from a parsed unqualified-id. 5450 DeclarationNameInfo 5451 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5452 DeclarationNameInfo NameInfo; 5453 NameInfo.setLoc(Name.StartLocation); 5454 5455 switch (Name.getKind()) { 5456 5457 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5458 case UnqualifiedIdKind::IK_Identifier: 5459 NameInfo.setName(Name.Identifier); 5460 return NameInfo; 5461 5462 case UnqualifiedIdKind::IK_DeductionGuideName: { 5463 // C++ [temp.deduct.guide]p3: 5464 // The simple-template-id shall name a class template specialization. 5465 // The template-name shall be the same identifier as the template-name 5466 // of the simple-template-id. 5467 // These together intend to imply that the template-name shall name a 5468 // class template. 5469 // FIXME: template<typename T> struct X {}; 5470 // template<typename T> using Y = X<T>; 5471 // Y(int) -> Y<int>; 5472 // satisfies these rules but does not name a class template. 5473 TemplateName TN = Name.TemplateName.get().get(); 5474 auto *Template = TN.getAsTemplateDecl(); 5475 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5476 Diag(Name.StartLocation, 5477 diag::err_deduction_guide_name_not_class_template) 5478 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5479 if (Template) 5480 Diag(Template->getLocation(), diag::note_template_decl_here); 5481 return DeclarationNameInfo(); 5482 } 5483 5484 NameInfo.setName( 5485 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5486 return NameInfo; 5487 } 5488 5489 case UnqualifiedIdKind::IK_OperatorFunctionId: 5490 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5491 Name.OperatorFunctionId.Operator)); 5492 NameInfo.setCXXOperatorNameRange(SourceRange( 5493 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5494 return NameInfo; 5495 5496 case UnqualifiedIdKind::IK_LiteralOperatorId: 5497 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5498 Name.Identifier)); 5499 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5500 return NameInfo; 5501 5502 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5503 TypeSourceInfo *TInfo; 5504 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5505 if (Ty.isNull()) 5506 return DeclarationNameInfo(); 5507 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5508 Context.getCanonicalType(Ty))); 5509 NameInfo.setNamedTypeInfo(TInfo); 5510 return NameInfo; 5511 } 5512 5513 case UnqualifiedIdKind::IK_ConstructorName: { 5514 TypeSourceInfo *TInfo; 5515 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5516 if (Ty.isNull()) 5517 return DeclarationNameInfo(); 5518 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5519 Context.getCanonicalType(Ty))); 5520 NameInfo.setNamedTypeInfo(TInfo); 5521 return NameInfo; 5522 } 5523 5524 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5525 // In well-formed code, we can only have a constructor 5526 // template-id that refers to the current context, so go there 5527 // to find the actual type being constructed. 5528 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5529 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5530 return DeclarationNameInfo(); 5531 5532 // Determine the type of the class being constructed. 5533 QualType CurClassType = Context.getTypeDeclType(CurClass); 5534 5535 // FIXME: Check two things: that the template-id names the same type as 5536 // CurClassType, and that the template-id does not occur when the name 5537 // was qualified. 5538 5539 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5540 Context.getCanonicalType(CurClassType))); 5541 // FIXME: should we retrieve TypeSourceInfo? 5542 NameInfo.setNamedTypeInfo(nullptr); 5543 return NameInfo; 5544 } 5545 5546 case UnqualifiedIdKind::IK_DestructorName: { 5547 TypeSourceInfo *TInfo; 5548 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5549 if (Ty.isNull()) 5550 return DeclarationNameInfo(); 5551 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5552 Context.getCanonicalType(Ty))); 5553 NameInfo.setNamedTypeInfo(TInfo); 5554 return NameInfo; 5555 } 5556 5557 case UnqualifiedIdKind::IK_TemplateId: { 5558 TemplateName TName = Name.TemplateId->Template.get(); 5559 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5560 return Context.getNameForTemplate(TName, TNameLoc); 5561 } 5562 5563 } // switch (Name.getKind()) 5564 5565 llvm_unreachable("Unknown name kind"); 5566 } 5567 5568 static QualType getCoreType(QualType Ty) { 5569 do { 5570 if (Ty->isPointerType() || Ty->isReferenceType()) 5571 Ty = Ty->getPointeeType(); 5572 else if (Ty->isArrayType()) 5573 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5574 else 5575 return Ty.withoutLocalFastQualifiers(); 5576 } while (true); 5577 } 5578 5579 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5580 /// and Definition have "nearly" matching parameters. This heuristic is 5581 /// used to improve diagnostics in the case where an out-of-line function 5582 /// definition doesn't match any declaration within the class or namespace. 5583 /// Also sets Params to the list of indices to the parameters that differ 5584 /// between the declaration and the definition. If hasSimilarParameters 5585 /// returns true and Params is empty, then all of the parameters match. 5586 static bool hasSimilarParameters(ASTContext &Context, 5587 FunctionDecl *Declaration, 5588 FunctionDecl *Definition, 5589 SmallVectorImpl<unsigned> &Params) { 5590 Params.clear(); 5591 if (Declaration->param_size() != Definition->param_size()) 5592 return false; 5593 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5594 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5595 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5596 5597 // The parameter types are identical 5598 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5599 continue; 5600 5601 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5602 QualType DefParamBaseTy = getCoreType(DefParamTy); 5603 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5604 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5605 5606 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5607 (DeclTyName && DeclTyName == DefTyName)) 5608 Params.push_back(Idx); 5609 else // The two parameters aren't even close 5610 return false; 5611 } 5612 5613 return true; 5614 } 5615 5616 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5617 /// declarator needs to be rebuilt in the current instantiation. 5618 /// Any bits of declarator which appear before the name are valid for 5619 /// consideration here. That's specifically the type in the decl spec 5620 /// and the base type in any member-pointer chunks. 5621 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5622 DeclarationName Name) { 5623 // The types we specifically need to rebuild are: 5624 // - typenames, typeofs, and decltypes 5625 // - types which will become injected class names 5626 // Of course, we also need to rebuild any type referencing such a 5627 // type. It's safest to just say "dependent", but we call out a 5628 // few cases here. 5629 5630 DeclSpec &DS = D.getMutableDeclSpec(); 5631 switch (DS.getTypeSpecType()) { 5632 case DeclSpec::TST_typename: 5633 case DeclSpec::TST_typeofType: 5634 case DeclSpec::TST_underlyingType: 5635 case DeclSpec::TST_atomic: { 5636 // Grab the type from the parser. 5637 TypeSourceInfo *TSI = nullptr; 5638 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5639 if (T.isNull() || !T->isInstantiationDependentType()) break; 5640 5641 // Make sure there's a type source info. This isn't really much 5642 // of a waste; most dependent types should have type source info 5643 // attached already. 5644 if (!TSI) 5645 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5646 5647 // Rebuild the type in the current instantiation. 5648 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5649 if (!TSI) return true; 5650 5651 // Store the new type back in the decl spec. 5652 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5653 DS.UpdateTypeRep(LocType); 5654 break; 5655 } 5656 5657 case DeclSpec::TST_decltype: 5658 case DeclSpec::TST_typeofExpr: { 5659 Expr *E = DS.getRepAsExpr(); 5660 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5661 if (Result.isInvalid()) return true; 5662 DS.UpdateExprRep(Result.get()); 5663 break; 5664 } 5665 5666 default: 5667 // Nothing to do for these decl specs. 5668 break; 5669 } 5670 5671 // It doesn't matter what order we do this in. 5672 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5673 DeclaratorChunk &Chunk = D.getTypeObject(I); 5674 5675 // The only type information in the declarator which can come 5676 // before the declaration name is the base type of a member 5677 // pointer. 5678 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5679 continue; 5680 5681 // Rebuild the scope specifier in-place. 5682 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5683 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5684 return true; 5685 } 5686 5687 return false; 5688 } 5689 5690 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 5691 // Avoid warning twice on the same identifier, and don't warn on redeclaration 5692 // of system decl. 5693 if (D->getPreviousDecl() || D->isImplicit()) 5694 return; 5695 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 5696 if (Status != ReservedIdentifierStatus::NotReserved && 5697 !Context.getSourceManager().isInSystemHeader(D->getLocation())) 5698 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 5699 << D << static_cast<int>(Status); 5700 } 5701 5702 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5703 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5704 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5705 5706 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5707 Dcl && Dcl->getDeclContext()->isFileContext()) 5708 Dcl->setTopLevelDeclInObjCContainer(); 5709 5710 return Dcl; 5711 } 5712 5713 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5714 /// If T is the name of a class, then each of the following shall have a 5715 /// name different from T: 5716 /// - every static data member of class T; 5717 /// - every member function of class T 5718 /// - every member of class T that is itself a type; 5719 /// \returns true if the declaration name violates these rules. 5720 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5721 DeclarationNameInfo NameInfo) { 5722 DeclarationName Name = NameInfo.getName(); 5723 5724 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5725 while (Record && Record->isAnonymousStructOrUnion()) 5726 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5727 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5728 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5729 return true; 5730 } 5731 5732 return false; 5733 } 5734 5735 /// Diagnose a declaration whose declarator-id has the given 5736 /// nested-name-specifier. 5737 /// 5738 /// \param SS The nested-name-specifier of the declarator-id. 5739 /// 5740 /// \param DC The declaration context to which the nested-name-specifier 5741 /// resolves. 5742 /// 5743 /// \param Name The name of the entity being declared. 5744 /// 5745 /// \param Loc The location of the name of the entity being declared. 5746 /// 5747 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5748 /// we're declaring an explicit / partial specialization / instantiation. 5749 /// 5750 /// \returns true if we cannot safely recover from this error, false otherwise. 5751 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5752 DeclarationName Name, 5753 SourceLocation Loc, bool IsTemplateId) { 5754 DeclContext *Cur = CurContext; 5755 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5756 Cur = Cur->getParent(); 5757 5758 // If the user provided a superfluous scope specifier that refers back to the 5759 // class in which the entity is already declared, diagnose and ignore it. 5760 // 5761 // class X { 5762 // void X::f(); 5763 // }; 5764 // 5765 // Note, it was once ill-formed to give redundant qualification in all 5766 // contexts, but that rule was removed by DR482. 5767 if (Cur->Equals(DC)) { 5768 if (Cur->isRecord()) { 5769 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5770 : diag::err_member_extra_qualification) 5771 << Name << FixItHint::CreateRemoval(SS.getRange()); 5772 SS.clear(); 5773 } else { 5774 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5775 } 5776 return false; 5777 } 5778 5779 // Check whether the qualifying scope encloses the scope of the original 5780 // declaration. For a template-id, we perform the checks in 5781 // CheckTemplateSpecializationScope. 5782 if (!Cur->Encloses(DC) && !IsTemplateId) { 5783 if (Cur->isRecord()) 5784 Diag(Loc, diag::err_member_qualification) 5785 << Name << SS.getRange(); 5786 else if (isa<TranslationUnitDecl>(DC)) 5787 Diag(Loc, diag::err_invalid_declarator_global_scope) 5788 << Name << SS.getRange(); 5789 else if (isa<FunctionDecl>(Cur)) 5790 Diag(Loc, diag::err_invalid_declarator_in_function) 5791 << Name << SS.getRange(); 5792 else if (isa<BlockDecl>(Cur)) 5793 Diag(Loc, diag::err_invalid_declarator_in_block) 5794 << Name << SS.getRange(); 5795 else if (isa<ExportDecl>(Cur)) { 5796 if (!isa<NamespaceDecl>(DC)) 5797 Diag(Loc, diag::err_export_non_namespace_scope_name) 5798 << Name << SS.getRange(); 5799 else 5800 // The cases that DC is not NamespaceDecl should be handled in 5801 // CheckRedeclarationExported. 5802 return false; 5803 } else 5804 Diag(Loc, diag::err_invalid_declarator_scope) 5805 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5806 5807 return true; 5808 } 5809 5810 if (Cur->isRecord()) { 5811 // Cannot qualify members within a class. 5812 Diag(Loc, diag::err_member_qualification) 5813 << Name << SS.getRange(); 5814 SS.clear(); 5815 5816 // C++ constructors and destructors with incorrect scopes can break 5817 // our AST invariants by having the wrong underlying types. If 5818 // that's the case, then drop this declaration entirely. 5819 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5820 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5821 !Context.hasSameType(Name.getCXXNameType(), 5822 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5823 return true; 5824 5825 return false; 5826 } 5827 5828 // C++11 [dcl.meaning]p1: 5829 // [...] "The nested-name-specifier of the qualified declarator-id shall 5830 // not begin with a decltype-specifer" 5831 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5832 while (SpecLoc.getPrefix()) 5833 SpecLoc = SpecLoc.getPrefix(); 5834 if (isa_and_nonnull<DecltypeType>( 5835 SpecLoc.getNestedNameSpecifier()->getAsType())) 5836 Diag(Loc, diag::err_decltype_in_declarator) 5837 << SpecLoc.getTypeLoc().getSourceRange(); 5838 5839 return false; 5840 } 5841 5842 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5843 MultiTemplateParamsArg TemplateParamLists) { 5844 // TODO: consider using NameInfo for diagnostic. 5845 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5846 DeclarationName Name = NameInfo.getName(); 5847 5848 // All of these full declarators require an identifier. If it doesn't have 5849 // one, the ParsedFreeStandingDeclSpec action should be used. 5850 if (D.isDecompositionDeclarator()) { 5851 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5852 } else if (!Name) { 5853 if (!D.isInvalidType()) // Reject this if we think it is valid. 5854 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5855 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5856 return nullptr; 5857 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5858 return nullptr; 5859 5860 // The scope passed in may not be a decl scope. Zip up the scope tree until 5861 // we find one that is. 5862 while ((S->getFlags() & Scope::DeclScope) == 0 || 5863 (S->getFlags() & Scope::TemplateParamScope) != 0) 5864 S = S->getParent(); 5865 5866 DeclContext *DC = CurContext; 5867 if (D.getCXXScopeSpec().isInvalid()) 5868 D.setInvalidType(); 5869 else if (D.getCXXScopeSpec().isSet()) { 5870 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5871 UPPC_DeclarationQualifier)) 5872 return nullptr; 5873 5874 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5875 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5876 if (!DC || isa<EnumDecl>(DC)) { 5877 // If we could not compute the declaration context, it's because the 5878 // declaration context is dependent but does not refer to a class, 5879 // class template, or class template partial specialization. Complain 5880 // and return early, to avoid the coming semantic disaster. 5881 Diag(D.getIdentifierLoc(), 5882 diag::err_template_qualified_declarator_no_match) 5883 << D.getCXXScopeSpec().getScopeRep() 5884 << D.getCXXScopeSpec().getRange(); 5885 return nullptr; 5886 } 5887 bool IsDependentContext = DC->isDependentContext(); 5888 5889 if (!IsDependentContext && 5890 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5891 return nullptr; 5892 5893 // If a class is incomplete, do not parse entities inside it. 5894 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5895 Diag(D.getIdentifierLoc(), 5896 diag::err_member_def_undefined_record) 5897 << Name << DC << D.getCXXScopeSpec().getRange(); 5898 return nullptr; 5899 } 5900 if (!D.getDeclSpec().isFriendSpecified()) { 5901 if (diagnoseQualifiedDeclaration( 5902 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5903 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5904 if (DC->isRecord()) 5905 return nullptr; 5906 5907 D.setInvalidType(); 5908 } 5909 } 5910 5911 // Check whether we need to rebuild the type of the given 5912 // declaration in the current instantiation. 5913 if (EnteringContext && IsDependentContext && 5914 TemplateParamLists.size() != 0) { 5915 ContextRAII SavedContext(*this, DC); 5916 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5917 D.setInvalidType(); 5918 } 5919 } 5920 5921 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5922 QualType R = TInfo->getType(); 5923 5924 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5925 UPPC_DeclarationType)) 5926 D.setInvalidType(); 5927 5928 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5929 forRedeclarationInCurContext()); 5930 5931 // See if this is a redefinition of a variable in the same scope. 5932 if (!D.getCXXScopeSpec().isSet()) { 5933 bool IsLinkageLookup = false; 5934 bool CreateBuiltins = false; 5935 5936 // If the declaration we're planning to build will be a function 5937 // or object with linkage, then look for another declaration with 5938 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5939 // 5940 // If the declaration we're planning to build will be declared with 5941 // external linkage in the translation unit, create any builtin with 5942 // the same name. 5943 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5944 /* Do nothing*/; 5945 else if (CurContext->isFunctionOrMethod() && 5946 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5947 R->isFunctionType())) { 5948 IsLinkageLookup = true; 5949 CreateBuiltins = 5950 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5951 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5952 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5953 CreateBuiltins = true; 5954 5955 if (IsLinkageLookup) { 5956 Previous.clear(LookupRedeclarationWithLinkage); 5957 Previous.setRedeclarationKind(ForExternalRedeclaration); 5958 } 5959 5960 LookupName(Previous, S, CreateBuiltins); 5961 } else { // Something like "int foo::x;" 5962 LookupQualifiedName(Previous, DC); 5963 5964 // C++ [dcl.meaning]p1: 5965 // When the declarator-id is qualified, the declaration shall refer to a 5966 // previously declared member of the class or namespace to which the 5967 // qualifier refers (or, in the case of a namespace, of an element of the 5968 // inline namespace set of that namespace (7.3.1)) or to a specialization 5969 // thereof; [...] 5970 // 5971 // Note that we already checked the context above, and that we do not have 5972 // enough information to make sure that Previous contains the declaration 5973 // we want to match. For example, given: 5974 // 5975 // class X { 5976 // void f(); 5977 // void f(float); 5978 // }; 5979 // 5980 // void X::f(int) { } // ill-formed 5981 // 5982 // In this case, Previous will point to the overload set 5983 // containing the two f's declared in X, but neither of them 5984 // matches. 5985 5986 // C++ [dcl.meaning]p1: 5987 // [...] the member shall not merely have been introduced by a 5988 // using-declaration in the scope of the class or namespace nominated by 5989 // the nested-name-specifier of the declarator-id. 5990 RemoveUsingDecls(Previous); 5991 } 5992 5993 if (Previous.isSingleResult() && 5994 Previous.getFoundDecl()->isTemplateParameter()) { 5995 // Maybe we will complain about the shadowed template parameter. 5996 if (!D.isInvalidType()) 5997 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5998 Previous.getFoundDecl()); 5999 6000 // Just pretend that we didn't see the previous declaration. 6001 Previous.clear(); 6002 } 6003 6004 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 6005 // Forget that the previous declaration is the injected-class-name. 6006 Previous.clear(); 6007 6008 // In C++, the previous declaration we find might be a tag type 6009 // (class or enum). In this case, the new declaration will hide the 6010 // tag type. Note that this applies to functions, function templates, and 6011 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 6012 if (Previous.isSingleTagDecl() && 6013 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6014 (TemplateParamLists.size() == 0 || R->isFunctionType())) 6015 Previous.clear(); 6016 6017 // Check that there are no default arguments other than in the parameters 6018 // of a function declaration (C++ only). 6019 if (getLangOpts().CPlusPlus) 6020 CheckExtraCXXDefaultArguments(D); 6021 6022 NamedDecl *New; 6023 6024 bool AddToScope = true; 6025 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 6026 if (TemplateParamLists.size()) { 6027 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 6028 return nullptr; 6029 } 6030 6031 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 6032 } else if (R->isFunctionType()) { 6033 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 6034 TemplateParamLists, 6035 AddToScope); 6036 } else { 6037 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 6038 AddToScope); 6039 } 6040 6041 if (!New) 6042 return nullptr; 6043 6044 // If this has an identifier and is not a function template specialization, 6045 // add it to the scope stack. 6046 if (New->getDeclName() && AddToScope) 6047 PushOnScopeChains(New, S); 6048 6049 if (isInOpenMPDeclareTargetContext()) 6050 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 6051 6052 return New; 6053 } 6054 6055 /// Helper method to turn variable array types into constant array 6056 /// types in certain situations which would otherwise be errors (for 6057 /// GCC compatibility). 6058 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6059 ASTContext &Context, 6060 bool &SizeIsNegative, 6061 llvm::APSInt &Oversized) { 6062 // This method tries to turn a variable array into a constant 6063 // array even when the size isn't an ICE. This is necessary 6064 // for compatibility with code that depends on gcc's buggy 6065 // constant expression folding, like struct {char x[(int)(char*)2];} 6066 SizeIsNegative = false; 6067 Oversized = 0; 6068 6069 if (T->isDependentType()) 6070 return QualType(); 6071 6072 QualifierCollector Qs; 6073 const Type *Ty = Qs.strip(T); 6074 6075 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6076 QualType Pointee = PTy->getPointeeType(); 6077 QualType FixedType = 6078 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6079 Oversized); 6080 if (FixedType.isNull()) return FixedType; 6081 FixedType = Context.getPointerType(FixedType); 6082 return Qs.apply(Context, FixedType); 6083 } 6084 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6085 QualType Inner = PTy->getInnerType(); 6086 QualType FixedType = 6087 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6088 Oversized); 6089 if (FixedType.isNull()) return FixedType; 6090 FixedType = Context.getParenType(FixedType); 6091 return Qs.apply(Context, FixedType); 6092 } 6093 6094 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6095 if (!VLATy) 6096 return QualType(); 6097 6098 QualType ElemTy = VLATy->getElementType(); 6099 if (ElemTy->isVariablyModifiedType()) { 6100 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6101 SizeIsNegative, Oversized); 6102 if (ElemTy.isNull()) 6103 return QualType(); 6104 } 6105 6106 Expr::EvalResult Result; 6107 if (!VLATy->getSizeExpr() || 6108 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6109 return QualType(); 6110 6111 llvm::APSInt Res = Result.Val.getInt(); 6112 6113 // Check whether the array size is negative. 6114 if (Res.isSigned() && Res.isNegative()) { 6115 SizeIsNegative = true; 6116 return QualType(); 6117 } 6118 6119 // Check whether the array is too large to be addressed. 6120 unsigned ActiveSizeBits = 6121 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6122 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6123 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6124 : Res.getActiveBits(); 6125 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6126 Oversized = Res; 6127 return QualType(); 6128 } 6129 6130 QualType FoldedArrayType = Context.getConstantArrayType( 6131 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 6132 return Qs.apply(Context, FoldedArrayType); 6133 } 6134 6135 static void 6136 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6137 SrcTL = SrcTL.getUnqualifiedLoc(); 6138 DstTL = DstTL.getUnqualifiedLoc(); 6139 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6140 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6141 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6142 DstPTL.getPointeeLoc()); 6143 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6144 return; 6145 } 6146 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6147 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6148 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6149 DstPTL.getInnerLoc()); 6150 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6151 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6152 return; 6153 } 6154 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6155 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6156 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6157 TypeLoc DstElemTL = DstATL.getElementLoc(); 6158 if (VariableArrayTypeLoc SrcElemATL = 6159 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6160 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6161 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6162 } else { 6163 DstElemTL.initializeFullCopy(SrcElemTL); 6164 } 6165 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6166 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6167 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6168 } 6169 6170 /// Helper method to turn variable array types into constant array 6171 /// types in certain situations which would otherwise be errors (for 6172 /// GCC compatibility). 6173 static TypeSourceInfo* 6174 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6175 ASTContext &Context, 6176 bool &SizeIsNegative, 6177 llvm::APSInt &Oversized) { 6178 QualType FixedTy 6179 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6180 SizeIsNegative, Oversized); 6181 if (FixedTy.isNull()) 6182 return nullptr; 6183 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6184 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6185 FixedTInfo->getTypeLoc()); 6186 return FixedTInfo; 6187 } 6188 6189 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6190 /// true if we were successful. 6191 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6192 QualType &T, SourceLocation Loc, 6193 unsigned FailedFoldDiagID) { 6194 bool SizeIsNegative; 6195 llvm::APSInt Oversized; 6196 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6197 TInfo, Context, SizeIsNegative, Oversized); 6198 if (FixedTInfo) { 6199 Diag(Loc, diag::ext_vla_folded_to_constant); 6200 TInfo = FixedTInfo; 6201 T = FixedTInfo->getType(); 6202 return true; 6203 } 6204 6205 if (SizeIsNegative) 6206 Diag(Loc, diag::err_typecheck_negative_array_size); 6207 else if (Oversized.getBoolValue()) 6208 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6209 else if (FailedFoldDiagID) 6210 Diag(Loc, FailedFoldDiagID); 6211 return false; 6212 } 6213 6214 /// Register the given locally-scoped extern "C" declaration so 6215 /// that it can be found later for redeclarations. We include any extern "C" 6216 /// declaration that is not visible in the translation unit here, not just 6217 /// function-scope declarations. 6218 void 6219 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6220 if (!getLangOpts().CPlusPlus && 6221 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6222 // Don't need to track declarations in the TU in C. 6223 return; 6224 6225 // Note that we have a locally-scoped external with this name. 6226 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6227 } 6228 6229 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6230 // FIXME: We can have multiple results via __attribute__((overloadable)). 6231 auto Result = Context.getExternCContextDecl()->lookup(Name); 6232 return Result.empty() ? nullptr : *Result.begin(); 6233 } 6234 6235 /// Diagnose function specifiers on a declaration of an identifier that 6236 /// does not identify a function. 6237 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6238 // FIXME: We should probably indicate the identifier in question to avoid 6239 // confusion for constructs like "virtual int a(), b;" 6240 if (DS.isVirtualSpecified()) 6241 Diag(DS.getVirtualSpecLoc(), 6242 diag::err_virtual_non_function); 6243 6244 if (DS.hasExplicitSpecifier()) 6245 Diag(DS.getExplicitSpecLoc(), 6246 diag::err_explicit_non_function); 6247 6248 if (DS.isNoreturnSpecified()) 6249 Diag(DS.getNoreturnSpecLoc(), 6250 diag::err_noreturn_non_function); 6251 } 6252 6253 NamedDecl* 6254 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6255 TypeSourceInfo *TInfo, LookupResult &Previous) { 6256 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6257 if (D.getCXXScopeSpec().isSet()) { 6258 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6259 << D.getCXXScopeSpec().getRange(); 6260 D.setInvalidType(); 6261 // Pretend we didn't see the scope specifier. 6262 DC = CurContext; 6263 Previous.clear(); 6264 } 6265 6266 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6267 6268 if (D.getDeclSpec().isInlineSpecified()) 6269 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6270 << getLangOpts().CPlusPlus17; 6271 if (D.getDeclSpec().hasConstexprSpecifier()) 6272 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6273 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6274 6275 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6276 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6277 Diag(D.getName().StartLocation, 6278 diag::err_deduction_guide_invalid_specifier) 6279 << "typedef"; 6280 else 6281 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6282 << D.getName().getSourceRange(); 6283 return nullptr; 6284 } 6285 6286 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6287 if (!NewTD) return nullptr; 6288 6289 // Handle attributes prior to checking for duplicates in MergeVarDecl 6290 ProcessDeclAttributes(S, NewTD, D); 6291 6292 CheckTypedefForVariablyModifiedType(S, NewTD); 6293 6294 bool Redeclaration = D.isRedeclaration(); 6295 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6296 D.setRedeclaration(Redeclaration); 6297 return ND; 6298 } 6299 6300 void 6301 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6302 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6303 // then it shall have block scope. 6304 // Note that variably modified types must be fixed before merging the decl so 6305 // that redeclarations will match. 6306 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6307 QualType T = TInfo->getType(); 6308 if (T->isVariablyModifiedType()) { 6309 setFunctionHasBranchProtectedScope(); 6310 6311 if (S->getFnParent() == nullptr) { 6312 bool SizeIsNegative; 6313 llvm::APSInt Oversized; 6314 TypeSourceInfo *FixedTInfo = 6315 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6316 SizeIsNegative, 6317 Oversized); 6318 if (FixedTInfo) { 6319 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6320 NewTD->setTypeSourceInfo(FixedTInfo); 6321 } else { 6322 if (SizeIsNegative) 6323 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6324 else if (T->isVariableArrayType()) 6325 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6326 else if (Oversized.getBoolValue()) 6327 Diag(NewTD->getLocation(), diag::err_array_too_large) 6328 << toString(Oversized, 10); 6329 else 6330 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6331 NewTD->setInvalidDecl(); 6332 } 6333 } 6334 } 6335 } 6336 6337 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6338 /// declares a typedef-name, either using the 'typedef' type specifier or via 6339 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6340 NamedDecl* 6341 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6342 LookupResult &Previous, bool &Redeclaration) { 6343 6344 // Find the shadowed declaration before filtering for scope. 6345 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6346 6347 // Merge the decl with the existing one if appropriate. If the decl is 6348 // in an outer scope, it isn't the same thing. 6349 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6350 /*AllowInlineNamespace*/false); 6351 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6352 if (!Previous.empty()) { 6353 Redeclaration = true; 6354 MergeTypedefNameDecl(S, NewTD, Previous); 6355 } else { 6356 inferGslPointerAttribute(NewTD); 6357 } 6358 6359 if (ShadowedDecl && !Redeclaration) 6360 CheckShadow(NewTD, ShadowedDecl, Previous); 6361 6362 // If this is the C FILE type, notify the AST context. 6363 if (IdentifierInfo *II = NewTD->getIdentifier()) 6364 if (!NewTD->isInvalidDecl() && 6365 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6366 if (II->isStr("FILE")) 6367 Context.setFILEDecl(NewTD); 6368 else if (II->isStr("jmp_buf")) 6369 Context.setjmp_bufDecl(NewTD); 6370 else if (II->isStr("sigjmp_buf")) 6371 Context.setsigjmp_bufDecl(NewTD); 6372 else if (II->isStr("ucontext_t")) 6373 Context.setucontext_tDecl(NewTD); 6374 } 6375 6376 return NewTD; 6377 } 6378 6379 /// Determines whether the given declaration is an out-of-scope 6380 /// previous declaration. 6381 /// 6382 /// This routine should be invoked when name lookup has found a 6383 /// previous declaration (PrevDecl) that is not in the scope where a 6384 /// new declaration by the same name is being introduced. If the new 6385 /// declaration occurs in a local scope, previous declarations with 6386 /// linkage may still be considered previous declarations (C99 6387 /// 6.2.2p4-5, C++ [basic.link]p6). 6388 /// 6389 /// \param PrevDecl the previous declaration found by name 6390 /// lookup 6391 /// 6392 /// \param DC the context in which the new declaration is being 6393 /// declared. 6394 /// 6395 /// \returns true if PrevDecl is an out-of-scope previous declaration 6396 /// for a new delcaration with the same name. 6397 static bool 6398 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6399 ASTContext &Context) { 6400 if (!PrevDecl) 6401 return false; 6402 6403 if (!PrevDecl->hasLinkage()) 6404 return false; 6405 6406 if (Context.getLangOpts().CPlusPlus) { 6407 // C++ [basic.link]p6: 6408 // If there is a visible declaration of an entity with linkage 6409 // having the same name and type, ignoring entities declared 6410 // outside the innermost enclosing namespace scope, the block 6411 // scope declaration declares that same entity and receives the 6412 // linkage of the previous declaration. 6413 DeclContext *OuterContext = DC->getRedeclContext(); 6414 if (!OuterContext->isFunctionOrMethod()) 6415 // This rule only applies to block-scope declarations. 6416 return false; 6417 6418 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6419 if (PrevOuterContext->isRecord()) 6420 // We found a member function: ignore it. 6421 return false; 6422 6423 // Find the innermost enclosing namespace for the new and 6424 // previous declarations. 6425 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6426 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6427 6428 // The previous declaration is in a different namespace, so it 6429 // isn't the same function. 6430 if (!OuterContext->Equals(PrevOuterContext)) 6431 return false; 6432 } 6433 6434 return true; 6435 } 6436 6437 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6438 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6439 if (!SS.isSet()) return; 6440 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6441 } 6442 6443 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6444 QualType type = decl->getType(); 6445 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6446 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6447 // Various kinds of declaration aren't allowed to be __autoreleasing. 6448 unsigned kind = -1U; 6449 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6450 if (var->hasAttr<BlocksAttr>()) 6451 kind = 0; // __block 6452 else if (!var->hasLocalStorage()) 6453 kind = 1; // global 6454 } else if (isa<ObjCIvarDecl>(decl)) { 6455 kind = 3; // ivar 6456 } else if (isa<FieldDecl>(decl)) { 6457 kind = 2; // field 6458 } 6459 6460 if (kind != -1U) { 6461 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6462 << kind; 6463 } 6464 } else if (lifetime == Qualifiers::OCL_None) { 6465 // Try to infer lifetime. 6466 if (!type->isObjCLifetimeType()) 6467 return false; 6468 6469 lifetime = type->getObjCARCImplicitLifetime(); 6470 type = Context.getLifetimeQualifiedType(type, lifetime); 6471 decl->setType(type); 6472 } 6473 6474 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6475 // Thread-local variables cannot have lifetime. 6476 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6477 var->getTLSKind()) { 6478 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6479 << var->getType(); 6480 return true; 6481 } 6482 } 6483 6484 return false; 6485 } 6486 6487 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6488 if (Decl->getType().hasAddressSpace()) 6489 return; 6490 if (Decl->getType()->isDependentType()) 6491 return; 6492 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6493 QualType Type = Var->getType(); 6494 if (Type->isSamplerT() || Type->isVoidType()) 6495 return; 6496 LangAS ImplAS = LangAS::opencl_private; 6497 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 6498 // __opencl_c_program_scope_global_variables feature, the address space 6499 // for a variable at program scope or a static or extern variable inside 6500 // a function are inferred to be __global. 6501 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 6502 Var->hasGlobalStorage()) 6503 ImplAS = LangAS::opencl_global; 6504 // If the original type from a decayed type is an array type and that array 6505 // type has no address space yet, deduce it now. 6506 if (auto DT = dyn_cast<DecayedType>(Type)) { 6507 auto OrigTy = DT->getOriginalType(); 6508 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6509 // Add the address space to the original array type and then propagate 6510 // that to the element type through `getAsArrayType`. 6511 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6512 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6513 // Re-generate the decayed type. 6514 Type = Context.getDecayedType(OrigTy); 6515 } 6516 } 6517 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6518 // Apply any qualifiers (including address space) from the array type to 6519 // the element type. This implements C99 6.7.3p8: "If the specification of 6520 // an array type includes any type qualifiers, the element type is so 6521 // qualified, not the array type." 6522 if (Type->isArrayType()) 6523 Type = QualType(Context.getAsArrayType(Type), 0); 6524 Decl->setType(Type); 6525 } 6526 } 6527 6528 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6529 // Ensure that an auto decl is deduced otherwise the checks below might cache 6530 // the wrong linkage. 6531 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6532 6533 // 'weak' only applies to declarations with external linkage. 6534 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6535 if (!ND.isExternallyVisible()) { 6536 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6537 ND.dropAttr<WeakAttr>(); 6538 } 6539 } 6540 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6541 if (ND.isExternallyVisible()) { 6542 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6543 ND.dropAttr<WeakRefAttr>(); 6544 ND.dropAttr<AliasAttr>(); 6545 } 6546 } 6547 6548 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6549 if (VD->hasInit()) { 6550 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6551 assert(VD->isThisDeclarationADefinition() && 6552 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6553 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6554 VD->dropAttr<AliasAttr>(); 6555 } 6556 } 6557 } 6558 6559 // 'selectany' only applies to externally visible variable declarations. 6560 // It does not apply to functions. 6561 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6562 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6563 S.Diag(Attr->getLocation(), 6564 diag::err_attribute_selectany_non_extern_data); 6565 ND.dropAttr<SelectAnyAttr>(); 6566 } 6567 } 6568 6569 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6570 auto *VD = dyn_cast<VarDecl>(&ND); 6571 bool IsAnonymousNS = false; 6572 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6573 if (VD) { 6574 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6575 while (NS && !IsAnonymousNS) { 6576 IsAnonymousNS = NS->isAnonymousNamespace(); 6577 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6578 } 6579 } 6580 // dll attributes require external linkage. Static locals may have external 6581 // linkage but still cannot be explicitly imported or exported. 6582 // In Microsoft mode, a variable defined in anonymous namespace must have 6583 // external linkage in order to be exported. 6584 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6585 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6586 (!AnonNSInMicrosoftMode && 6587 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6588 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6589 << &ND << Attr; 6590 ND.setInvalidDecl(); 6591 } 6592 } 6593 6594 // Check the attributes on the function type, if any. 6595 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6596 // Don't declare this variable in the second operand of the for-statement; 6597 // GCC miscompiles that by ending its lifetime before evaluating the 6598 // third operand. See gcc.gnu.org/PR86769. 6599 AttributedTypeLoc ATL; 6600 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6601 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6602 TL = ATL.getModifiedLoc()) { 6603 // The [[lifetimebound]] attribute can be applied to the implicit object 6604 // parameter of a non-static member function (other than a ctor or dtor) 6605 // by applying it to the function type. 6606 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6607 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6608 if (!MD || MD->isStatic()) { 6609 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6610 << !MD << A->getRange(); 6611 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6612 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6613 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6614 } 6615 } 6616 } 6617 } 6618 } 6619 6620 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6621 NamedDecl *NewDecl, 6622 bool IsSpecialization, 6623 bool IsDefinition) { 6624 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6625 return; 6626 6627 bool IsTemplate = false; 6628 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6629 OldDecl = OldTD->getTemplatedDecl(); 6630 IsTemplate = true; 6631 if (!IsSpecialization) 6632 IsDefinition = false; 6633 } 6634 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6635 NewDecl = NewTD->getTemplatedDecl(); 6636 IsTemplate = true; 6637 } 6638 6639 if (!OldDecl || !NewDecl) 6640 return; 6641 6642 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6643 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6644 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6645 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6646 6647 // dllimport and dllexport are inheritable attributes so we have to exclude 6648 // inherited attribute instances. 6649 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6650 (NewExportAttr && !NewExportAttr->isInherited()); 6651 6652 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6653 // the only exception being explicit specializations. 6654 // Implicitly generated declarations are also excluded for now because there 6655 // is no other way to switch these to use dllimport or dllexport. 6656 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6657 6658 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6659 // Allow with a warning for free functions and global variables. 6660 bool JustWarn = false; 6661 if (!OldDecl->isCXXClassMember()) { 6662 auto *VD = dyn_cast<VarDecl>(OldDecl); 6663 if (VD && !VD->getDescribedVarTemplate()) 6664 JustWarn = true; 6665 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6666 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6667 JustWarn = true; 6668 } 6669 6670 // We cannot change a declaration that's been used because IR has already 6671 // been emitted. Dllimported functions will still work though (modulo 6672 // address equality) as they can use the thunk. 6673 if (OldDecl->isUsed()) 6674 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6675 JustWarn = false; 6676 6677 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6678 : diag::err_attribute_dll_redeclaration; 6679 S.Diag(NewDecl->getLocation(), DiagID) 6680 << NewDecl 6681 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6682 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6683 if (!JustWarn) { 6684 NewDecl->setInvalidDecl(); 6685 return; 6686 } 6687 } 6688 6689 // A redeclaration is not allowed to drop a dllimport attribute, the only 6690 // exceptions being inline function definitions (except for function 6691 // templates), local extern declarations, qualified friend declarations or 6692 // special MSVC extension: in the last case, the declaration is treated as if 6693 // it were marked dllexport. 6694 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6695 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6696 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6697 // Ignore static data because out-of-line definitions are diagnosed 6698 // separately. 6699 IsStaticDataMember = VD->isStaticDataMember(); 6700 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6701 VarDecl::DeclarationOnly; 6702 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6703 IsInline = FD->isInlined(); 6704 IsQualifiedFriend = FD->getQualifier() && 6705 FD->getFriendObjectKind() == Decl::FOK_Declared; 6706 } 6707 6708 if (OldImportAttr && !HasNewAttr && 6709 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6710 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6711 if (IsMicrosoftABI && IsDefinition) { 6712 S.Diag(NewDecl->getLocation(), 6713 diag::warn_redeclaration_without_import_attribute) 6714 << NewDecl; 6715 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6716 NewDecl->dropAttr<DLLImportAttr>(); 6717 NewDecl->addAttr( 6718 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6719 } else { 6720 S.Diag(NewDecl->getLocation(), 6721 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6722 << NewDecl << OldImportAttr; 6723 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6724 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6725 OldDecl->dropAttr<DLLImportAttr>(); 6726 NewDecl->dropAttr<DLLImportAttr>(); 6727 } 6728 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6729 // In MinGW, seeing a function declared inline drops the dllimport 6730 // attribute. 6731 OldDecl->dropAttr<DLLImportAttr>(); 6732 NewDecl->dropAttr<DLLImportAttr>(); 6733 S.Diag(NewDecl->getLocation(), 6734 diag::warn_dllimport_dropped_from_inline_function) 6735 << NewDecl << OldImportAttr; 6736 } 6737 6738 // A specialization of a class template member function is processed here 6739 // since it's a redeclaration. If the parent class is dllexport, the 6740 // specialization inherits that attribute. This doesn't happen automatically 6741 // since the parent class isn't instantiated until later. 6742 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6743 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6744 !NewImportAttr && !NewExportAttr) { 6745 if (const DLLExportAttr *ParentExportAttr = 6746 MD->getParent()->getAttr<DLLExportAttr>()) { 6747 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6748 NewAttr->setInherited(true); 6749 NewDecl->addAttr(NewAttr); 6750 } 6751 } 6752 } 6753 } 6754 6755 /// Given that we are within the definition of the given function, 6756 /// will that definition behave like C99's 'inline', where the 6757 /// definition is discarded except for optimization purposes? 6758 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6759 // Try to avoid calling GetGVALinkageForFunction. 6760 6761 // All cases of this require the 'inline' keyword. 6762 if (!FD->isInlined()) return false; 6763 6764 // This is only possible in C++ with the gnu_inline attribute. 6765 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6766 return false; 6767 6768 // Okay, go ahead and call the relatively-more-expensive function. 6769 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6770 } 6771 6772 /// Determine whether a variable is extern "C" prior to attaching 6773 /// an initializer. We can't just call isExternC() here, because that 6774 /// will also compute and cache whether the declaration is externally 6775 /// visible, which might change when we attach the initializer. 6776 /// 6777 /// This can only be used if the declaration is known to not be a 6778 /// redeclaration of an internal linkage declaration. 6779 /// 6780 /// For instance: 6781 /// 6782 /// auto x = []{}; 6783 /// 6784 /// Attaching the initializer here makes this declaration not externally 6785 /// visible, because its type has internal linkage. 6786 /// 6787 /// FIXME: This is a hack. 6788 template<typename T> 6789 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6790 if (S.getLangOpts().CPlusPlus) { 6791 // In C++, the overloadable attribute negates the effects of extern "C". 6792 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6793 return false; 6794 6795 // So do CUDA's host/device attributes. 6796 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6797 D->template hasAttr<CUDAHostAttr>())) 6798 return false; 6799 } 6800 return D->isExternC(); 6801 } 6802 6803 static bool shouldConsiderLinkage(const VarDecl *VD) { 6804 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6805 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6806 isa<OMPDeclareMapperDecl>(DC)) 6807 return VD->hasExternalStorage(); 6808 if (DC->isFileContext()) 6809 return true; 6810 if (DC->isRecord()) 6811 return false; 6812 if (isa<RequiresExprBodyDecl>(DC)) 6813 return false; 6814 llvm_unreachable("Unexpected context"); 6815 } 6816 6817 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6818 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6819 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6820 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6821 return true; 6822 if (DC->isRecord()) 6823 return false; 6824 llvm_unreachable("Unexpected context"); 6825 } 6826 6827 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6828 ParsedAttr::Kind Kind) { 6829 // Check decl attributes on the DeclSpec. 6830 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6831 return true; 6832 6833 // Walk the declarator structure, checking decl attributes that were in a type 6834 // position to the decl itself. 6835 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6836 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6837 return true; 6838 } 6839 6840 // Finally, check attributes on the decl itself. 6841 return PD.getAttributes().hasAttribute(Kind); 6842 } 6843 6844 /// Adjust the \c DeclContext for a function or variable that might be a 6845 /// function-local external declaration. 6846 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6847 if (!DC->isFunctionOrMethod()) 6848 return false; 6849 6850 // If this is a local extern function or variable declared within a function 6851 // template, don't add it into the enclosing namespace scope until it is 6852 // instantiated; it might have a dependent type right now. 6853 if (DC->isDependentContext()) 6854 return true; 6855 6856 // C++11 [basic.link]p7: 6857 // When a block scope declaration of an entity with linkage is not found to 6858 // refer to some other declaration, then that entity is a member of the 6859 // innermost enclosing namespace. 6860 // 6861 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6862 // semantically-enclosing namespace, not a lexically-enclosing one. 6863 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6864 DC = DC->getParent(); 6865 return true; 6866 } 6867 6868 /// Returns true if given declaration has external C language linkage. 6869 static bool isDeclExternC(const Decl *D) { 6870 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6871 return FD->isExternC(); 6872 if (const auto *VD = dyn_cast<VarDecl>(D)) 6873 return VD->isExternC(); 6874 6875 llvm_unreachable("Unknown type of decl!"); 6876 } 6877 6878 /// Returns true if there hasn't been any invalid type diagnosed. 6879 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 6880 DeclContext *DC = NewVD->getDeclContext(); 6881 QualType R = NewVD->getType(); 6882 6883 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6884 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6885 // argument. 6886 if (R->isImageType() || R->isPipeType()) { 6887 Se.Diag(NewVD->getLocation(), 6888 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6889 << R; 6890 NewVD->setInvalidDecl(); 6891 return false; 6892 } 6893 6894 // OpenCL v1.2 s6.9.r: 6895 // The event type cannot be used to declare a program scope variable. 6896 // OpenCL v2.0 s6.9.q: 6897 // The clk_event_t and reserve_id_t types cannot be declared in program 6898 // scope. 6899 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 6900 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6901 Se.Diag(NewVD->getLocation(), 6902 diag::err_invalid_type_for_program_scope_var) 6903 << R; 6904 NewVD->setInvalidDecl(); 6905 return false; 6906 } 6907 } 6908 6909 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6910 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 6911 Se.getLangOpts())) { 6912 QualType NR = R.getCanonicalType(); 6913 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 6914 NR->isReferenceType()) { 6915 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 6916 NR->isFunctionReferenceType()) { 6917 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 6918 << NR->isReferenceType(); 6919 NewVD->setInvalidDecl(); 6920 return false; 6921 } 6922 NR = NR->getPointeeType(); 6923 } 6924 } 6925 6926 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 6927 Se.getLangOpts())) { 6928 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6929 // half array type (unless the cl_khr_fp16 extension is enabled). 6930 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6931 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 6932 NewVD->setInvalidDecl(); 6933 return false; 6934 } 6935 } 6936 6937 // OpenCL v1.2 s6.9.r: 6938 // The event type cannot be used with the __local, __constant and __global 6939 // address space qualifiers. 6940 if (R->isEventT()) { 6941 if (R.getAddressSpace() != LangAS::opencl_private) { 6942 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 6943 NewVD->setInvalidDecl(); 6944 return false; 6945 } 6946 } 6947 6948 if (R->isSamplerT()) { 6949 // OpenCL v1.2 s6.9.b p4: 6950 // The sampler type cannot be used with the __local and __global address 6951 // space qualifiers. 6952 if (R.getAddressSpace() == LangAS::opencl_local || 6953 R.getAddressSpace() == LangAS::opencl_global) { 6954 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 6955 NewVD->setInvalidDecl(); 6956 } 6957 6958 // OpenCL v1.2 s6.12.14.1: 6959 // A global sampler must be declared with either the constant address 6960 // space qualifier or with the const qualifier. 6961 if (DC->isTranslationUnit() && 6962 !(R.getAddressSpace() == LangAS::opencl_constant || 6963 R.isConstQualified())) { 6964 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 6965 NewVD->setInvalidDecl(); 6966 } 6967 if (NewVD->isInvalidDecl()) 6968 return false; 6969 } 6970 6971 return true; 6972 } 6973 6974 template <typename AttrTy> 6975 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 6976 const TypedefNameDecl *TND = TT->getDecl(); 6977 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 6978 AttrTy *Clone = Attribute->clone(S.Context); 6979 Clone->setInherited(true); 6980 D->addAttr(Clone); 6981 } 6982 } 6983 6984 NamedDecl *Sema::ActOnVariableDeclarator( 6985 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6986 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6987 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6988 QualType R = TInfo->getType(); 6989 DeclarationName Name = GetNameForDeclarator(D).getName(); 6990 6991 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6992 6993 if (D.isDecompositionDeclarator()) { 6994 // Take the name of the first declarator as our name for diagnostic 6995 // purposes. 6996 auto &Decomp = D.getDecompositionDeclarator(); 6997 if (!Decomp.bindings().empty()) { 6998 II = Decomp.bindings()[0].Name; 6999 Name = II; 7000 } 7001 } else if (!II) { 7002 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 7003 return nullptr; 7004 } 7005 7006 7007 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 7008 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 7009 7010 // dllimport globals without explicit storage class are treated as extern. We 7011 // have to change the storage class this early to get the right DeclContext. 7012 if (SC == SC_None && !DC->isRecord() && 7013 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 7014 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 7015 SC = SC_Extern; 7016 7017 DeclContext *OriginalDC = DC; 7018 bool IsLocalExternDecl = SC == SC_Extern && 7019 adjustContextForLocalExternDecl(DC); 7020 7021 if (SCSpec == DeclSpec::SCS_mutable) { 7022 // mutable can only appear on non-static class members, so it's always 7023 // an error here 7024 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 7025 D.setInvalidType(); 7026 SC = SC_None; 7027 } 7028 7029 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 7030 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 7031 D.getDeclSpec().getStorageClassSpecLoc())) { 7032 // In C++11, the 'register' storage class specifier is deprecated. 7033 // Suppress the warning in system macros, it's used in macros in some 7034 // popular C system headers, such as in glibc's htonl() macro. 7035 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7036 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 7037 : diag::warn_deprecated_register) 7038 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7039 } 7040 7041 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 7042 7043 if (!DC->isRecord() && S->getFnParent() == nullptr) { 7044 // C99 6.9p2: The storage-class specifiers auto and register shall not 7045 // appear in the declaration specifiers in an external declaration. 7046 // Global Register+Asm is a GNU extension we support. 7047 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 7048 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 7049 D.setInvalidType(); 7050 } 7051 } 7052 7053 // If this variable has a VLA type and an initializer, try to 7054 // fold to a constant-sized type. This is otherwise invalid. 7055 if (D.hasInitializer() && R->isVariableArrayType()) 7056 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7057 /*DiagID=*/0); 7058 7059 bool IsMemberSpecialization = false; 7060 bool IsVariableTemplateSpecialization = false; 7061 bool IsPartialSpecialization = false; 7062 bool IsVariableTemplate = false; 7063 VarDecl *NewVD = nullptr; 7064 VarTemplateDecl *NewTemplate = nullptr; 7065 TemplateParameterList *TemplateParams = nullptr; 7066 if (!getLangOpts().CPlusPlus) { 7067 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7068 II, R, TInfo, SC); 7069 7070 if (R->getContainedDeducedType()) 7071 ParsingInitForAutoVars.insert(NewVD); 7072 7073 if (D.isInvalidType()) 7074 NewVD->setInvalidDecl(); 7075 7076 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7077 NewVD->hasLocalStorage()) 7078 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7079 NTCUC_AutoVar, NTCUK_Destruct); 7080 } else { 7081 bool Invalid = false; 7082 7083 if (DC->isRecord() && !CurContext->isRecord()) { 7084 // This is an out-of-line definition of a static data member. 7085 switch (SC) { 7086 case SC_None: 7087 break; 7088 case SC_Static: 7089 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7090 diag::err_static_out_of_line) 7091 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7092 break; 7093 case SC_Auto: 7094 case SC_Register: 7095 case SC_Extern: 7096 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7097 // to names of variables declared in a block or to function parameters. 7098 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7099 // of class members 7100 7101 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7102 diag::err_storage_class_for_static_member) 7103 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7104 break; 7105 case SC_PrivateExtern: 7106 llvm_unreachable("C storage class in c++!"); 7107 } 7108 } 7109 7110 if (SC == SC_Static && CurContext->isRecord()) { 7111 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7112 // Walk up the enclosing DeclContexts to check for any that are 7113 // incompatible with static data members. 7114 const DeclContext *FunctionOrMethod = nullptr; 7115 const CXXRecordDecl *AnonStruct = nullptr; 7116 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7117 if (Ctxt->isFunctionOrMethod()) { 7118 FunctionOrMethod = Ctxt; 7119 break; 7120 } 7121 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7122 if (ParentDecl && !ParentDecl->getDeclName()) { 7123 AnonStruct = ParentDecl; 7124 break; 7125 } 7126 } 7127 if (FunctionOrMethod) { 7128 // C++ [class.static.data]p5: A local class shall not have static data 7129 // members. 7130 Diag(D.getIdentifierLoc(), 7131 diag::err_static_data_member_not_allowed_in_local_class) 7132 << Name << RD->getDeclName() << RD->getTagKind(); 7133 } else if (AnonStruct) { 7134 // C++ [class.static.data]p4: Unnamed classes and classes contained 7135 // directly or indirectly within unnamed classes shall not contain 7136 // static data members. 7137 Diag(D.getIdentifierLoc(), 7138 diag::err_static_data_member_not_allowed_in_anon_struct) 7139 << Name << AnonStruct->getTagKind(); 7140 Invalid = true; 7141 } else if (RD->isUnion()) { 7142 // C++98 [class.union]p1: If a union contains a static data member, 7143 // the program is ill-formed. C++11 drops this restriction. 7144 Diag(D.getIdentifierLoc(), 7145 getLangOpts().CPlusPlus11 7146 ? diag::warn_cxx98_compat_static_data_member_in_union 7147 : diag::ext_static_data_member_in_union) << Name; 7148 } 7149 } 7150 } 7151 7152 // Match up the template parameter lists with the scope specifier, then 7153 // determine whether we have a template or a template specialization. 7154 bool InvalidScope = false; 7155 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7156 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7157 D.getCXXScopeSpec(), 7158 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7159 ? D.getName().TemplateId 7160 : nullptr, 7161 TemplateParamLists, 7162 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7163 Invalid |= InvalidScope; 7164 7165 if (TemplateParams) { 7166 if (!TemplateParams->size() && 7167 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7168 // There is an extraneous 'template<>' for this variable. Complain 7169 // about it, but allow the declaration of the variable. 7170 Diag(TemplateParams->getTemplateLoc(), 7171 diag::err_template_variable_noparams) 7172 << II 7173 << SourceRange(TemplateParams->getTemplateLoc(), 7174 TemplateParams->getRAngleLoc()); 7175 TemplateParams = nullptr; 7176 } else { 7177 // Check that we can declare a template here. 7178 if (CheckTemplateDeclScope(S, TemplateParams)) 7179 return nullptr; 7180 7181 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7182 // This is an explicit specialization or a partial specialization. 7183 IsVariableTemplateSpecialization = true; 7184 IsPartialSpecialization = TemplateParams->size() > 0; 7185 } else { // if (TemplateParams->size() > 0) 7186 // This is a template declaration. 7187 IsVariableTemplate = true; 7188 7189 // Only C++1y supports variable templates (N3651). 7190 Diag(D.getIdentifierLoc(), 7191 getLangOpts().CPlusPlus14 7192 ? diag::warn_cxx11_compat_variable_template 7193 : diag::ext_variable_template); 7194 } 7195 } 7196 } else { 7197 // Check that we can declare a member specialization here. 7198 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7199 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7200 return nullptr; 7201 assert((Invalid || 7202 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7203 "should have a 'template<>' for this decl"); 7204 } 7205 7206 if (IsVariableTemplateSpecialization) { 7207 SourceLocation TemplateKWLoc = 7208 TemplateParamLists.size() > 0 7209 ? TemplateParamLists[0]->getTemplateLoc() 7210 : SourceLocation(); 7211 DeclResult Res = ActOnVarTemplateSpecialization( 7212 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7213 IsPartialSpecialization); 7214 if (Res.isInvalid()) 7215 return nullptr; 7216 NewVD = cast<VarDecl>(Res.get()); 7217 AddToScope = false; 7218 } else if (D.isDecompositionDeclarator()) { 7219 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7220 D.getIdentifierLoc(), R, TInfo, SC, 7221 Bindings); 7222 } else 7223 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7224 D.getIdentifierLoc(), II, R, TInfo, SC); 7225 7226 // If this is supposed to be a variable template, create it as such. 7227 if (IsVariableTemplate) { 7228 NewTemplate = 7229 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7230 TemplateParams, NewVD); 7231 NewVD->setDescribedVarTemplate(NewTemplate); 7232 } 7233 7234 // If this decl has an auto type in need of deduction, make a note of the 7235 // Decl so we can diagnose uses of it in its own initializer. 7236 if (R->getContainedDeducedType()) 7237 ParsingInitForAutoVars.insert(NewVD); 7238 7239 if (D.isInvalidType() || Invalid) { 7240 NewVD->setInvalidDecl(); 7241 if (NewTemplate) 7242 NewTemplate->setInvalidDecl(); 7243 } 7244 7245 SetNestedNameSpecifier(*this, NewVD, D); 7246 7247 // If we have any template parameter lists that don't directly belong to 7248 // the variable (matching the scope specifier), store them. 7249 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7250 if (TemplateParamLists.size() > VDTemplateParamLists) 7251 NewVD->setTemplateParameterListsInfo( 7252 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7253 } 7254 7255 if (D.getDeclSpec().isInlineSpecified()) { 7256 if (!getLangOpts().CPlusPlus) { 7257 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7258 << 0; 7259 } else if (CurContext->isFunctionOrMethod()) { 7260 // 'inline' is not allowed on block scope variable declaration. 7261 Diag(D.getDeclSpec().getInlineSpecLoc(), 7262 diag::err_inline_declaration_block_scope) << Name 7263 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7264 } else { 7265 Diag(D.getDeclSpec().getInlineSpecLoc(), 7266 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7267 : diag::ext_inline_variable); 7268 NewVD->setInlineSpecified(); 7269 } 7270 } 7271 7272 // Set the lexical context. If the declarator has a C++ scope specifier, the 7273 // lexical context will be different from the semantic context. 7274 NewVD->setLexicalDeclContext(CurContext); 7275 if (NewTemplate) 7276 NewTemplate->setLexicalDeclContext(CurContext); 7277 7278 if (IsLocalExternDecl) { 7279 if (D.isDecompositionDeclarator()) 7280 for (auto *B : Bindings) 7281 B->setLocalExternDecl(); 7282 else 7283 NewVD->setLocalExternDecl(); 7284 } 7285 7286 bool EmitTLSUnsupportedError = false; 7287 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7288 // C++11 [dcl.stc]p4: 7289 // When thread_local is applied to a variable of block scope the 7290 // storage-class-specifier static is implied if it does not appear 7291 // explicitly. 7292 // Core issue: 'static' is not implied if the variable is declared 7293 // 'extern'. 7294 if (NewVD->hasLocalStorage() && 7295 (SCSpec != DeclSpec::SCS_unspecified || 7296 TSCS != DeclSpec::TSCS_thread_local || 7297 !DC->isFunctionOrMethod())) 7298 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7299 diag::err_thread_non_global) 7300 << DeclSpec::getSpecifierName(TSCS); 7301 else if (!Context.getTargetInfo().isTLSSupported()) { 7302 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7303 getLangOpts().SYCLIsDevice) { 7304 // Postpone error emission until we've collected attributes required to 7305 // figure out whether it's a host or device variable and whether the 7306 // error should be ignored. 7307 EmitTLSUnsupportedError = true; 7308 // We still need to mark the variable as TLS so it shows up in AST with 7309 // proper storage class for other tools to use even if we're not going 7310 // to emit any code for it. 7311 NewVD->setTSCSpec(TSCS); 7312 } else 7313 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7314 diag::err_thread_unsupported); 7315 } else 7316 NewVD->setTSCSpec(TSCS); 7317 } 7318 7319 switch (D.getDeclSpec().getConstexprSpecifier()) { 7320 case ConstexprSpecKind::Unspecified: 7321 break; 7322 7323 case ConstexprSpecKind::Consteval: 7324 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7325 diag::err_constexpr_wrong_decl_kind) 7326 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7327 LLVM_FALLTHROUGH; 7328 7329 case ConstexprSpecKind::Constexpr: 7330 NewVD->setConstexpr(true); 7331 // C++1z [dcl.spec.constexpr]p1: 7332 // A static data member declared with the constexpr specifier is 7333 // implicitly an inline variable. 7334 if (NewVD->isStaticDataMember() && 7335 (getLangOpts().CPlusPlus17 || 7336 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7337 NewVD->setImplicitlyInline(); 7338 break; 7339 7340 case ConstexprSpecKind::Constinit: 7341 if (!NewVD->hasGlobalStorage()) 7342 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7343 diag::err_constinit_local_variable); 7344 else 7345 NewVD->addAttr(ConstInitAttr::Create( 7346 Context, D.getDeclSpec().getConstexprSpecLoc(), 7347 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7348 break; 7349 } 7350 7351 // C99 6.7.4p3 7352 // An inline definition of a function with external linkage shall 7353 // not contain a definition of a modifiable object with static or 7354 // thread storage duration... 7355 // We only apply this when the function is required to be defined 7356 // elsewhere, i.e. when the function is not 'extern inline'. Note 7357 // that a local variable with thread storage duration still has to 7358 // be marked 'static'. Also note that it's possible to get these 7359 // semantics in C++ using __attribute__((gnu_inline)). 7360 if (SC == SC_Static && S->getFnParent() != nullptr && 7361 !NewVD->getType().isConstQualified()) { 7362 FunctionDecl *CurFD = getCurFunctionDecl(); 7363 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7364 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7365 diag::warn_static_local_in_extern_inline); 7366 MaybeSuggestAddingStaticToDecl(CurFD); 7367 } 7368 } 7369 7370 if (D.getDeclSpec().isModulePrivateSpecified()) { 7371 if (IsVariableTemplateSpecialization) 7372 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7373 << (IsPartialSpecialization ? 1 : 0) 7374 << FixItHint::CreateRemoval( 7375 D.getDeclSpec().getModulePrivateSpecLoc()); 7376 else if (IsMemberSpecialization) 7377 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7378 << 2 7379 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7380 else if (NewVD->hasLocalStorage()) 7381 Diag(NewVD->getLocation(), diag::err_module_private_local) 7382 << 0 << NewVD 7383 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7384 << FixItHint::CreateRemoval( 7385 D.getDeclSpec().getModulePrivateSpecLoc()); 7386 else { 7387 NewVD->setModulePrivate(); 7388 if (NewTemplate) 7389 NewTemplate->setModulePrivate(); 7390 for (auto *B : Bindings) 7391 B->setModulePrivate(); 7392 } 7393 } 7394 7395 if (getLangOpts().OpenCL) { 7396 deduceOpenCLAddressSpace(NewVD); 7397 7398 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7399 if (TSC != TSCS_unspecified) { 7400 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7401 diag::err_opencl_unknown_type_specifier) 7402 << getLangOpts().getOpenCLVersionString() 7403 << DeclSpec::getSpecifierName(TSC) << 1; 7404 NewVD->setInvalidDecl(); 7405 } 7406 } 7407 7408 // Handle attributes prior to checking for duplicates in MergeVarDecl 7409 ProcessDeclAttributes(S, NewVD, D); 7410 7411 // FIXME: This is probably the wrong location to be doing this and we should 7412 // probably be doing this for more attributes (especially for function 7413 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7414 // the code to copy attributes would be generated by TableGen. 7415 if (R->isFunctionPointerType()) 7416 if (const auto *TT = R->getAs<TypedefType>()) 7417 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7418 7419 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7420 getLangOpts().SYCLIsDevice) { 7421 if (EmitTLSUnsupportedError && 7422 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7423 (getLangOpts().OpenMPIsDevice && 7424 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7425 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7426 diag::err_thread_unsupported); 7427 7428 if (EmitTLSUnsupportedError && 7429 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7430 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7431 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7432 // storage [duration]." 7433 if (SC == SC_None && S->getFnParent() != nullptr && 7434 (NewVD->hasAttr<CUDASharedAttr>() || 7435 NewVD->hasAttr<CUDAConstantAttr>())) { 7436 NewVD->setStorageClass(SC_Static); 7437 } 7438 } 7439 7440 // Ensure that dllimport globals without explicit storage class are treated as 7441 // extern. The storage class is set above using parsed attributes. Now we can 7442 // check the VarDecl itself. 7443 assert(!NewVD->hasAttr<DLLImportAttr>() || 7444 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7445 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7446 7447 // In auto-retain/release, infer strong retension for variables of 7448 // retainable type. 7449 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7450 NewVD->setInvalidDecl(); 7451 7452 // Handle GNU asm-label extension (encoded as an attribute). 7453 if (Expr *E = (Expr*)D.getAsmLabel()) { 7454 // The parser guarantees this is a string. 7455 StringLiteral *SE = cast<StringLiteral>(E); 7456 StringRef Label = SE->getString(); 7457 if (S->getFnParent() != nullptr) { 7458 switch (SC) { 7459 case SC_None: 7460 case SC_Auto: 7461 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7462 break; 7463 case SC_Register: 7464 // Local Named register 7465 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7466 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7467 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7468 break; 7469 case SC_Static: 7470 case SC_Extern: 7471 case SC_PrivateExtern: 7472 break; 7473 } 7474 } else if (SC == SC_Register) { 7475 // Global Named register 7476 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7477 const auto &TI = Context.getTargetInfo(); 7478 bool HasSizeMismatch; 7479 7480 if (!TI.isValidGCCRegisterName(Label)) 7481 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7482 else if (!TI.validateGlobalRegisterVariable(Label, 7483 Context.getTypeSize(R), 7484 HasSizeMismatch)) 7485 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7486 else if (HasSizeMismatch) 7487 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7488 } 7489 7490 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7491 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7492 NewVD->setInvalidDecl(true); 7493 } 7494 } 7495 7496 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7497 /*IsLiteralLabel=*/true, 7498 SE->getStrTokenLoc(0))); 7499 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7500 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7501 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7502 if (I != ExtnameUndeclaredIdentifiers.end()) { 7503 if (isDeclExternC(NewVD)) { 7504 NewVD->addAttr(I->second); 7505 ExtnameUndeclaredIdentifiers.erase(I); 7506 } else 7507 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7508 << /*Variable*/1 << NewVD; 7509 } 7510 } 7511 7512 // Find the shadowed declaration before filtering for scope. 7513 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7514 ? getShadowedDeclaration(NewVD, Previous) 7515 : nullptr; 7516 7517 // Don't consider existing declarations that are in a different 7518 // scope and are out-of-semantic-context declarations (if the new 7519 // declaration has linkage). 7520 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7521 D.getCXXScopeSpec().isNotEmpty() || 7522 IsMemberSpecialization || 7523 IsVariableTemplateSpecialization); 7524 7525 // Check whether the previous declaration is in the same block scope. This 7526 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7527 if (getLangOpts().CPlusPlus && 7528 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7529 NewVD->setPreviousDeclInSameBlockScope( 7530 Previous.isSingleResult() && !Previous.isShadowed() && 7531 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7532 7533 if (!getLangOpts().CPlusPlus) { 7534 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7535 } else { 7536 // If this is an explicit specialization of a static data member, check it. 7537 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7538 CheckMemberSpecialization(NewVD, Previous)) 7539 NewVD->setInvalidDecl(); 7540 7541 // Merge the decl with the existing one if appropriate. 7542 if (!Previous.empty()) { 7543 if (Previous.isSingleResult() && 7544 isa<FieldDecl>(Previous.getFoundDecl()) && 7545 D.getCXXScopeSpec().isSet()) { 7546 // The user tried to define a non-static data member 7547 // out-of-line (C++ [dcl.meaning]p1). 7548 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7549 << D.getCXXScopeSpec().getRange(); 7550 Previous.clear(); 7551 NewVD->setInvalidDecl(); 7552 } 7553 } else if (D.getCXXScopeSpec().isSet()) { 7554 // No previous declaration in the qualifying scope. 7555 Diag(D.getIdentifierLoc(), diag::err_no_member) 7556 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7557 << D.getCXXScopeSpec().getRange(); 7558 NewVD->setInvalidDecl(); 7559 } 7560 7561 if (!IsVariableTemplateSpecialization) 7562 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7563 7564 if (NewTemplate) { 7565 VarTemplateDecl *PrevVarTemplate = 7566 NewVD->getPreviousDecl() 7567 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7568 : nullptr; 7569 7570 // Check the template parameter list of this declaration, possibly 7571 // merging in the template parameter list from the previous variable 7572 // template declaration. 7573 if (CheckTemplateParameterList( 7574 TemplateParams, 7575 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7576 : nullptr, 7577 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7578 DC->isDependentContext()) 7579 ? TPC_ClassTemplateMember 7580 : TPC_VarTemplate)) 7581 NewVD->setInvalidDecl(); 7582 7583 // If we are providing an explicit specialization of a static variable 7584 // template, make a note of that. 7585 if (PrevVarTemplate && 7586 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7587 PrevVarTemplate->setMemberSpecialization(); 7588 } 7589 } 7590 7591 // Diagnose shadowed variables iff this isn't a redeclaration. 7592 if (ShadowedDecl && !D.isRedeclaration()) 7593 CheckShadow(NewVD, ShadowedDecl, Previous); 7594 7595 ProcessPragmaWeak(S, NewVD); 7596 7597 // If this is the first declaration of an extern C variable, update 7598 // the map of such variables. 7599 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7600 isIncompleteDeclExternC(*this, NewVD)) 7601 RegisterLocallyScopedExternCDecl(NewVD, S); 7602 7603 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7604 MangleNumberingContext *MCtx; 7605 Decl *ManglingContextDecl; 7606 std::tie(MCtx, ManglingContextDecl) = 7607 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7608 if (MCtx) { 7609 Context.setManglingNumber( 7610 NewVD, MCtx->getManglingNumber( 7611 NewVD, getMSManglingNumber(getLangOpts(), S))); 7612 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7613 } 7614 } 7615 7616 // Special handling of variable named 'main'. 7617 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7618 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7619 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7620 7621 // C++ [basic.start.main]p3 7622 // A program that declares a variable main at global scope is ill-formed. 7623 if (getLangOpts().CPlusPlus) 7624 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7625 7626 // In C, and external-linkage variable named main results in undefined 7627 // behavior. 7628 else if (NewVD->hasExternalFormalLinkage()) 7629 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7630 } 7631 7632 if (D.isRedeclaration() && !Previous.empty()) { 7633 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7634 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7635 D.isFunctionDefinition()); 7636 } 7637 7638 if (NewTemplate) { 7639 if (NewVD->isInvalidDecl()) 7640 NewTemplate->setInvalidDecl(); 7641 ActOnDocumentableDecl(NewTemplate); 7642 return NewTemplate; 7643 } 7644 7645 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7646 CompleteMemberSpecialization(NewVD, Previous); 7647 7648 return NewVD; 7649 } 7650 7651 /// Enum describing the %select options in diag::warn_decl_shadow. 7652 enum ShadowedDeclKind { 7653 SDK_Local, 7654 SDK_Global, 7655 SDK_StaticMember, 7656 SDK_Field, 7657 SDK_Typedef, 7658 SDK_Using, 7659 SDK_StructuredBinding 7660 }; 7661 7662 /// Determine what kind of declaration we're shadowing. 7663 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7664 const DeclContext *OldDC) { 7665 if (isa<TypeAliasDecl>(ShadowedDecl)) 7666 return SDK_Using; 7667 else if (isa<TypedefDecl>(ShadowedDecl)) 7668 return SDK_Typedef; 7669 else if (isa<BindingDecl>(ShadowedDecl)) 7670 return SDK_StructuredBinding; 7671 else if (isa<RecordDecl>(OldDC)) 7672 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7673 7674 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7675 } 7676 7677 /// Return the location of the capture if the given lambda captures the given 7678 /// variable \p VD, or an invalid source location otherwise. 7679 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7680 const VarDecl *VD) { 7681 for (const Capture &Capture : LSI->Captures) { 7682 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7683 return Capture.getLocation(); 7684 } 7685 return SourceLocation(); 7686 } 7687 7688 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7689 const LookupResult &R) { 7690 // Only diagnose if we're shadowing an unambiguous field or variable. 7691 if (R.getResultKind() != LookupResult::Found) 7692 return false; 7693 7694 // Return false if warning is ignored. 7695 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7696 } 7697 7698 /// Return the declaration shadowed by the given variable \p D, or null 7699 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7700 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7701 const LookupResult &R) { 7702 if (!shouldWarnIfShadowedDecl(Diags, R)) 7703 return nullptr; 7704 7705 // Don't diagnose declarations at file scope. 7706 if (D->hasGlobalStorage()) 7707 return nullptr; 7708 7709 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7710 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7711 : nullptr; 7712 } 7713 7714 /// Return the declaration shadowed by the given typedef \p D, or null 7715 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7716 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7717 const LookupResult &R) { 7718 // Don't warn if typedef declaration is part of a class 7719 if (D->getDeclContext()->isRecord()) 7720 return nullptr; 7721 7722 if (!shouldWarnIfShadowedDecl(Diags, R)) 7723 return nullptr; 7724 7725 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7726 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7727 } 7728 7729 /// Return the declaration shadowed by the given variable \p D, or null 7730 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7731 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7732 const LookupResult &R) { 7733 if (!shouldWarnIfShadowedDecl(Diags, R)) 7734 return nullptr; 7735 7736 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7737 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7738 : nullptr; 7739 } 7740 7741 /// Diagnose variable or built-in function shadowing. Implements 7742 /// -Wshadow. 7743 /// 7744 /// This method is called whenever a VarDecl is added to a "useful" 7745 /// scope. 7746 /// 7747 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7748 /// \param R the lookup of the name 7749 /// 7750 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7751 const LookupResult &R) { 7752 DeclContext *NewDC = D->getDeclContext(); 7753 7754 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7755 // Fields are not shadowed by variables in C++ static methods. 7756 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7757 if (MD->isStatic()) 7758 return; 7759 7760 // Fields shadowed by constructor parameters are a special case. Usually 7761 // the constructor initializes the field with the parameter. 7762 if (isa<CXXConstructorDecl>(NewDC)) 7763 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7764 // Remember that this was shadowed so we can either warn about its 7765 // modification or its existence depending on warning settings. 7766 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7767 return; 7768 } 7769 } 7770 7771 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7772 if (shadowedVar->isExternC()) { 7773 // For shadowing external vars, make sure that we point to the global 7774 // declaration, not a locally scoped extern declaration. 7775 for (auto I : shadowedVar->redecls()) 7776 if (I->isFileVarDecl()) { 7777 ShadowedDecl = I; 7778 break; 7779 } 7780 } 7781 7782 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7783 7784 unsigned WarningDiag = diag::warn_decl_shadow; 7785 SourceLocation CaptureLoc; 7786 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7787 isa<CXXMethodDecl>(NewDC)) { 7788 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7789 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7790 if (RD->getLambdaCaptureDefault() == LCD_None) { 7791 // Try to avoid warnings for lambdas with an explicit capture list. 7792 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7793 // Warn only when the lambda captures the shadowed decl explicitly. 7794 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7795 if (CaptureLoc.isInvalid()) 7796 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7797 } else { 7798 // Remember that this was shadowed so we can avoid the warning if the 7799 // shadowed decl isn't captured and the warning settings allow it. 7800 cast<LambdaScopeInfo>(getCurFunction()) 7801 ->ShadowingDecls.push_back( 7802 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7803 return; 7804 } 7805 } 7806 7807 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7808 // A variable can't shadow a local variable in an enclosing scope, if 7809 // they are separated by a non-capturing declaration context. 7810 for (DeclContext *ParentDC = NewDC; 7811 ParentDC && !ParentDC->Equals(OldDC); 7812 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7813 // Only block literals, captured statements, and lambda expressions 7814 // can capture; other scopes don't. 7815 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7816 !isLambdaCallOperator(ParentDC)) { 7817 return; 7818 } 7819 } 7820 } 7821 } 7822 } 7823 7824 // Only warn about certain kinds of shadowing for class members. 7825 if (NewDC && NewDC->isRecord()) { 7826 // In particular, don't warn about shadowing non-class members. 7827 if (!OldDC->isRecord()) 7828 return; 7829 7830 // TODO: should we warn about static data members shadowing 7831 // static data members from base classes? 7832 7833 // TODO: don't diagnose for inaccessible shadowed members. 7834 // This is hard to do perfectly because we might friend the 7835 // shadowing context, but that's just a false negative. 7836 } 7837 7838 7839 DeclarationName Name = R.getLookupName(); 7840 7841 // Emit warning and note. 7842 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7843 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7844 if (!CaptureLoc.isInvalid()) 7845 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7846 << Name << /*explicitly*/ 1; 7847 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7848 } 7849 7850 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7851 /// when these variables are captured by the lambda. 7852 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7853 for (const auto &Shadow : LSI->ShadowingDecls) { 7854 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7855 // Try to avoid the warning when the shadowed decl isn't captured. 7856 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7857 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7858 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7859 ? diag::warn_decl_shadow_uncaptured_local 7860 : diag::warn_decl_shadow) 7861 << Shadow.VD->getDeclName() 7862 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7863 if (!CaptureLoc.isInvalid()) 7864 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7865 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7866 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7867 } 7868 } 7869 7870 /// Check -Wshadow without the advantage of a previous lookup. 7871 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7872 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7873 return; 7874 7875 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7876 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7877 LookupName(R, S); 7878 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7879 CheckShadow(D, ShadowedDecl, R); 7880 } 7881 7882 /// Check if 'E', which is an expression that is about to be modified, refers 7883 /// to a constructor parameter that shadows a field. 7884 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7885 // Quickly ignore expressions that can't be shadowing ctor parameters. 7886 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7887 return; 7888 E = E->IgnoreParenImpCasts(); 7889 auto *DRE = dyn_cast<DeclRefExpr>(E); 7890 if (!DRE) 7891 return; 7892 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7893 auto I = ShadowingDecls.find(D); 7894 if (I == ShadowingDecls.end()) 7895 return; 7896 const NamedDecl *ShadowedDecl = I->second; 7897 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7898 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7899 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7900 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7901 7902 // Avoid issuing multiple warnings about the same decl. 7903 ShadowingDecls.erase(I); 7904 } 7905 7906 /// Check for conflict between this global or extern "C" declaration and 7907 /// previous global or extern "C" declarations. This is only used in C++. 7908 template<typename T> 7909 static bool checkGlobalOrExternCConflict( 7910 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7911 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7912 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7913 7914 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7915 // The common case: this global doesn't conflict with any extern "C" 7916 // declaration. 7917 return false; 7918 } 7919 7920 if (Prev) { 7921 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7922 // Both the old and new declarations have C language linkage. This is a 7923 // redeclaration. 7924 Previous.clear(); 7925 Previous.addDecl(Prev); 7926 return true; 7927 } 7928 7929 // This is a global, non-extern "C" declaration, and there is a previous 7930 // non-global extern "C" declaration. Diagnose if this is a variable 7931 // declaration. 7932 if (!isa<VarDecl>(ND)) 7933 return false; 7934 } else { 7935 // The declaration is extern "C". Check for any declaration in the 7936 // translation unit which might conflict. 7937 if (IsGlobal) { 7938 // We have already performed the lookup into the translation unit. 7939 IsGlobal = false; 7940 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7941 I != E; ++I) { 7942 if (isa<VarDecl>(*I)) { 7943 Prev = *I; 7944 break; 7945 } 7946 } 7947 } else { 7948 DeclContext::lookup_result R = 7949 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7950 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7951 I != E; ++I) { 7952 if (isa<VarDecl>(*I)) { 7953 Prev = *I; 7954 break; 7955 } 7956 // FIXME: If we have any other entity with this name in global scope, 7957 // the declaration is ill-formed, but that is a defect: it breaks the 7958 // 'stat' hack, for instance. Only variables can have mangled name 7959 // clashes with extern "C" declarations, so only they deserve a 7960 // diagnostic. 7961 } 7962 } 7963 7964 if (!Prev) 7965 return false; 7966 } 7967 7968 // Use the first declaration's location to ensure we point at something which 7969 // is lexically inside an extern "C" linkage-spec. 7970 assert(Prev && "should have found a previous declaration to diagnose"); 7971 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7972 Prev = FD->getFirstDecl(); 7973 else 7974 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7975 7976 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7977 << IsGlobal << ND; 7978 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7979 << IsGlobal; 7980 return false; 7981 } 7982 7983 /// Apply special rules for handling extern "C" declarations. Returns \c true 7984 /// if we have found that this is a redeclaration of some prior entity. 7985 /// 7986 /// Per C++ [dcl.link]p6: 7987 /// Two declarations [for a function or variable] with C language linkage 7988 /// with the same name that appear in different scopes refer to the same 7989 /// [entity]. An entity with C language linkage shall not be declared with 7990 /// the same name as an entity in global scope. 7991 template<typename T> 7992 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7993 LookupResult &Previous) { 7994 if (!S.getLangOpts().CPlusPlus) { 7995 // In C, when declaring a global variable, look for a corresponding 'extern' 7996 // variable declared in function scope. We don't need this in C++, because 7997 // we find local extern decls in the surrounding file-scope DeclContext. 7998 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7999 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 8000 Previous.clear(); 8001 Previous.addDecl(Prev); 8002 return true; 8003 } 8004 } 8005 return false; 8006 } 8007 8008 // A declaration in the translation unit can conflict with an extern "C" 8009 // declaration. 8010 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 8011 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 8012 8013 // An extern "C" declaration can conflict with a declaration in the 8014 // translation unit or can be a redeclaration of an extern "C" declaration 8015 // in another scope. 8016 if (isIncompleteDeclExternC(S,ND)) 8017 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 8018 8019 // Neither global nor extern "C": nothing to do. 8020 return false; 8021 } 8022 8023 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 8024 // If the decl is already known invalid, don't check it. 8025 if (NewVD->isInvalidDecl()) 8026 return; 8027 8028 QualType T = NewVD->getType(); 8029 8030 // Defer checking an 'auto' type until its initializer is attached. 8031 if (T->isUndeducedType()) 8032 return; 8033 8034 if (NewVD->hasAttrs()) 8035 CheckAlignasUnderalignment(NewVD); 8036 8037 if (T->isObjCObjectType()) { 8038 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 8039 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 8040 T = Context.getObjCObjectPointerType(T); 8041 NewVD->setType(T); 8042 } 8043 8044 // Emit an error if an address space was applied to decl with local storage. 8045 // This includes arrays of objects with address space qualifiers, but not 8046 // automatic variables that point to other address spaces. 8047 // ISO/IEC TR 18037 S5.1.2 8048 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 8049 T.getAddressSpace() != LangAS::Default) { 8050 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 8051 NewVD->setInvalidDecl(); 8052 return; 8053 } 8054 8055 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8056 // scope. 8057 if (getLangOpts().OpenCLVersion == 120 && 8058 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8059 getLangOpts()) && 8060 NewVD->isStaticLocal()) { 8061 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8062 NewVD->setInvalidDecl(); 8063 return; 8064 } 8065 8066 if (getLangOpts().OpenCL) { 8067 if (!diagnoseOpenCLTypes(*this, NewVD)) 8068 return; 8069 8070 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8071 if (NewVD->hasAttr<BlocksAttr>()) { 8072 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8073 return; 8074 } 8075 8076 if (T->isBlockPointerType()) { 8077 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8078 // can't use 'extern' storage class. 8079 if (!T.isConstQualified()) { 8080 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8081 << 0 /*const*/; 8082 NewVD->setInvalidDecl(); 8083 return; 8084 } 8085 if (NewVD->hasExternalStorage()) { 8086 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8087 NewVD->setInvalidDecl(); 8088 return; 8089 } 8090 } 8091 8092 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8093 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8094 NewVD->hasExternalStorage()) { 8095 if (!T->isSamplerT() && !T->isDependentType() && 8096 !(T.getAddressSpace() == LangAS::opencl_constant || 8097 (T.getAddressSpace() == LangAS::opencl_global && 8098 getOpenCLOptions().areProgramScopeVariablesSupported( 8099 getLangOpts())))) { 8100 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8101 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8102 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8103 << Scope << "global or constant"; 8104 else 8105 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8106 << Scope << "constant"; 8107 NewVD->setInvalidDecl(); 8108 return; 8109 } 8110 } else { 8111 if (T.getAddressSpace() == LangAS::opencl_global) { 8112 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8113 << 1 /*is any function*/ << "global"; 8114 NewVD->setInvalidDecl(); 8115 return; 8116 } 8117 if (T.getAddressSpace() == LangAS::opencl_constant || 8118 T.getAddressSpace() == LangAS::opencl_local) { 8119 FunctionDecl *FD = getCurFunctionDecl(); 8120 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8121 // in functions. 8122 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8123 if (T.getAddressSpace() == LangAS::opencl_constant) 8124 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8125 << 0 /*non-kernel only*/ << "constant"; 8126 else 8127 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8128 << 0 /*non-kernel only*/ << "local"; 8129 NewVD->setInvalidDecl(); 8130 return; 8131 } 8132 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8133 // in the outermost scope of a kernel function. 8134 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8135 if (!getCurScope()->isFunctionScope()) { 8136 if (T.getAddressSpace() == LangAS::opencl_constant) 8137 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8138 << "constant"; 8139 else 8140 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8141 << "local"; 8142 NewVD->setInvalidDecl(); 8143 return; 8144 } 8145 } 8146 } else if (T.getAddressSpace() != LangAS::opencl_private && 8147 // If we are parsing a template we didn't deduce an addr 8148 // space yet. 8149 T.getAddressSpace() != LangAS::Default) { 8150 // Do not allow other address spaces on automatic variable. 8151 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8152 NewVD->setInvalidDecl(); 8153 return; 8154 } 8155 } 8156 } 8157 8158 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8159 && !NewVD->hasAttr<BlocksAttr>()) { 8160 if (getLangOpts().getGC() != LangOptions::NonGC) 8161 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8162 else { 8163 assert(!getLangOpts().ObjCAutoRefCount); 8164 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8165 } 8166 } 8167 8168 bool isVM = T->isVariablyModifiedType(); 8169 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8170 NewVD->hasAttr<BlocksAttr>()) 8171 setFunctionHasBranchProtectedScope(); 8172 8173 if ((isVM && NewVD->hasLinkage()) || 8174 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8175 bool SizeIsNegative; 8176 llvm::APSInt Oversized; 8177 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8178 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8179 QualType FixedT; 8180 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8181 FixedT = FixedTInfo->getType(); 8182 else if (FixedTInfo) { 8183 // Type and type-as-written are canonically different. We need to fix up 8184 // both types separately. 8185 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8186 Oversized); 8187 } 8188 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8189 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8190 // FIXME: This won't give the correct result for 8191 // int a[10][n]; 8192 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8193 8194 if (NewVD->isFileVarDecl()) 8195 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8196 << SizeRange; 8197 else if (NewVD->isStaticLocal()) 8198 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8199 << SizeRange; 8200 else 8201 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8202 << SizeRange; 8203 NewVD->setInvalidDecl(); 8204 return; 8205 } 8206 8207 if (!FixedTInfo) { 8208 if (NewVD->isFileVarDecl()) 8209 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8210 else 8211 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8212 NewVD->setInvalidDecl(); 8213 return; 8214 } 8215 8216 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8217 NewVD->setType(FixedT); 8218 NewVD->setTypeSourceInfo(FixedTInfo); 8219 } 8220 8221 if (T->isVoidType()) { 8222 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8223 // of objects and functions. 8224 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8225 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8226 << T; 8227 NewVD->setInvalidDecl(); 8228 return; 8229 } 8230 } 8231 8232 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8233 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8234 NewVD->setInvalidDecl(); 8235 return; 8236 } 8237 8238 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8239 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8240 NewVD->setInvalidDecl(); 8241 return; 8242 } 8243 8244 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8245 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8246 NewVD->setInvalidDecl(); 8247 return; 8248 } 8249 8250 if (NewVD->isConstexpr() && !T->isDependentType() && 8251 RequireLiteralType(NewVD->getLocation(), T, 8252 diag::err_constexpr_var_non_literal)) { 8253 NewVD->setInvalidDecl(); 8254 return; 8255 } 8256 8257 // PPC MMA non-pointer types are not allowed as non-local variable types. 8258 if (Context.getTargetInfo().getTriple().isPPC64() && 8259 !NewVD->isLocalVarDecl() && 8260 CheckPPCMMAType(T, NewVD->getLocation())) { 8261 NewVD->setInvalidDecl(); 8262 return; 8263 } 8264 } 8265 8266 /// Perform semantic checking on a newly-created variable 8267 /// declaration. 8268 /// 8269 /// This routine performs all of the type-checking required for a 8270 /// variable declaration once it has been built. It is used both to 8271 /// check variables after they have been parsed and their declarators 8272 /// have been translated into a declaration, and to check variables 8273 /// that have been instantiated from a template. 8274 /// 8275 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8276 /// 8277 /// Returns true if the variable declaration is a redeclaration. 8278 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8279 CheckVariableDeclarationType(NewVD); 8280 8281 // If the decl is already known invalid, don't check it. 8282 if (NewVD->isInvalidDecl()) 8283 return false; 8284 8285 // If we did not find anything by this name, look for a non-visible 8286 // extern "C" declaration with the same name. 8287 if (Previous.empty() && 8288 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8289 Previous.setShadowed(); 8290 8291 if (!Previous.empty()) { 8292 MergeVarDecl(NewVD, Previous); 8293 return true; 8294 } 8295 return false; 8296 } 8297 8298 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8299 /// and if so, check that it's a valid override and remember it. 8300 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8301 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8302 8303 // Look for methods in base classes that this method might override. 8304 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8305 /*DetectVirtual=*/false); 8306 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8307 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8308 DeclarationName Name = MD->getDeclName(); 8309 8310 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8311 // We really want to find the base class destructor here. 8312 QualType T = Context.getTypeDeclType(BaseRecord); 8313 CanQualType CT = Context.getCanonicalType(T); 8314 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8315 } 8316 8317 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8318 CXXMethodDecl *BaseMD = 8319 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8320 if (!BaseMD || !BaseMD->isVirtual() || 8321 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8322 /*ConsiderCudaAttrs=*/true, 8323 // C++2a [class.virtual]p2 does not consider requires 8324 // clauses when overriding. 8325 /*ConsiderRequiresClauses=*/false)) 8326 continue; 8327 8328 if (Overridden.insert(BaseMD).second) { 8329 MD->addOverriddenMethod(BaseMD); 8330 CheckOverridingFunctionReturnType(MD, BaseMD); 8331 CheckOverridingFunctionAttributes(MD, BaseMD); 8332 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8333 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8334 } 8335 8336 // A method can only override one function from each base class. We 8337 // don't track indirectly overridden methods from bases of bases. 8338 return true; 8339 } 8340 8341 return false; 8342 }; 8343 8344 DC->lookupInBases(VisitBase, Paths); 8345 return !Overridden.empty(); 8346 } 8347 8348 namespace { 8349 // Struct for holding all of the extra arguments needed by 8350 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8351 struct ActOnFDArgs { 8352 Scope *S; 8353 Declarator &D; 8354 MultiTemplateParamsArg TemplateParamLists; 8355 bool AddToScope; 8356 }; 8357 } // end anonymous namespace 8358 8359 namespace { 8360 8361 // Callback to only accept typo corrections that have a non-zero edit distance. 8362 // Also only accept corrections that have the same parent decl. 8363 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8364 public: 8365 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8366 CXXRecordDecl *Parent) 8367 : Context(Context), OriginalFD(TypoFD), 8368 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8369 8370 bool ValidateCandidate(const TypoCorrection &candidate) override { 8371 if (candidate.getEditDistance() == 0) 8372 return false; 8373 8374 SmallVector<unsigned, 1> MismatchedParams; 8375 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8376 CDeclEnd = candidate.end(); 8377 CDecl != CDeclEnd; ++CDecl) { 8378 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8379 8380 if (FD && !FD->hasBody() && 8381 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8382 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8383 CXXRecordDecl *Parent = MD->getParent(); 8384 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8385 return true; 8386 } else if (!ExpectedParent) { 8387 return true; 8388 } 8389 } 8390 } 8391 8392 return false; 8393 } 8394 8395 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8396 return std::make_unique<DifferentNameValidatorCCC>(*this); 8397 } 8398 8399 private: 8400 ASTContext &Context; 8401 FunctionDecl *OriginalFD; 8402 CXXRecordDecl *ExpectedParent; 8403 }; 8404 8405 } // end anonymous namespace 8406 8407 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8408 TypoCorrectedFunctionDefinitions.insert(F); 8409 } 8410 8411 /// Generate diagnostics for an invalid function redeclaration. 8412 /// 8413 /// This routine handles generating the diagnostic messages for an invalid 8414 /// function redeclaration, including finding possible similar declarations 8415 /// or performing typo correction if there are no previous declarations with 8416 /// the same name. 8417 /// 8418 /// Returns a NamedDecl iff typo correction was performed and substituting in 8419 /// the new declaration name does not cause new errors. 8420 static NamedDecl *DiagnoseInvalidRedeclaration( 8421 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8422 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8423 DeclarationName Name = NewFD->getDeclName(); 8424 DeclContext *NewDC = NewFD->getDeclContext(); 8425 SmallVector<unsigned, 1> MismatchedParams; 8426 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8427 TypoCorrection Correction; 8428 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8429 unsigned DiagMsg = 8430 IsLocalFriend ? diag::err_no_matching_local_friend : 8431 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8432 diag::err_member_decl_does_not_match; 8433 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8434 IsLocalFriend ? Sema::LookupLocalFriendName 8435 : Sema::LookupOrdinaryName, 8436 Sema::ForVisibleRedeclaration); 8437 8438 NewFD->setInvalidDecl(); 8439 if (IsLocalFriend) 8440 SemaRef.LookupName(Prev, S); 8441 else 8442 SemaRef.LookupQualifiedName(Prev, NewDC); 8443 assert(!Prev.isAmbiguous() && 8444 "Cannot have an ambiguity in previous-declaration lookup"); 8445 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8446 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8447 MD ? MD->getParent() : nullptr); 8448 if (!Prev.empty()) { 8449 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8450 Func != FuncEnd; ++Func) { 8451 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8452 if (FD && 8453 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8454 // Add 1 to the index so that 0 can mean the mismatch didn't 8455 // involve a parameter 8456 unsigned ParamNum = 8457 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8458 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8459 } 8460 } 8461 // If the qualified name lookup yielded nothing, try typo correction 8462 } else if ((Correction = SemaRef.CorrectTypo( 8463 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8464 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8465 IsLocalFriend ? nullptr : NewDC))) { 8466 // Set up everything for the call to ActOnFunctionDeclarator 8467 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8468 ExtraArgs.D.getIdentifierLoc()); 8469 Previous.clear(); 8470 Previous.setLookupName(Correction.getCorrection()); 8471 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8472 CDeclEnd = Correction.end(); 8473 CDecl != CDeclEnd; ++CDecl) { 8474 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8475 if (FD && !FD->hasBody() && 8476 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8477 Previous.addDecl(FD); 8478 } 8479 } 8480 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8481 8482 NamedDecl *Result; 8483 // Retry building the function declaration with the new previous 8484 // declarations, and with errors suppressed. 8485 { 8486 // Trap errors. 8487 Sema::SFINAETrap Trap(SemaRef); 8488 8489 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8490 // pieces need to verify the typo-corrected C++ declaration and hopefully 8491 // eliminate the need for the parameter pack ExtraArgs. 8492 Result = SemaRef.ActOnFunctionDeclarator( 8493 ExtraArgs.S, ExtraArgs.D, 8494 Correction.getCorrectionDecl()->getDeclContext(), 8495 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8496 ExtraArgs.AddToScope); 8497 8498 if (Trap.hasErrorOccurred()) 8499 Result = nullptr; 8500 } 8501 8502 if (Result) { 8503 // Determine which correction we picked. 8504 Decl *Canonical = Result->getCanonicalDecl(); 8505 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8506 I != E; ++I) 8507 if ((*I)->getCanonicalDecl() == Canonical) 8508 Correction.setCorrectionDecl(*I); 8509 8510 // Let Sema know about the correction. 8511 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8512 SemaRef.diagnoseTypo( 8513 Correction, 8514 SemaRef.PDiag(IsLocalFriend 8515 ? diag::err_no_matching_local_friend_suggest 8516 : diag::err_member_decl_does_not_match_suggest) 8517 << Name << NewDC << IsDefinition); 8518 return Result; 8519 } 8520 8521 // Pretend the typo correction never occurred 8522 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8523 ExtraArgs.D.getIdentifierLoc()); 8524 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8525 Previous.clear(); 8526 Previous.setLookupName(Name); 8527 } 8528 8529 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8530 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8531 8532 bool NewFDisConst = false; 8533 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8534 NewFDisConst = NewMD->isConst(); 8535 8536 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8537 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8538 NearMatch != NearMatchEnd; ++NearMatch) { 8539 FunctionDecl *FD = NearMatch->first; 8540 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8541 bool FDisConst = MD && MD->isConst(); 8542 bool IsMember = MD || !IsLocalFriend; 8543 8544 // FIXME: These notes are poorly worded for the local friend case. 8545 if (unsigned Idx = NearMatch->second) { 8546 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8547 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8548 if (Loc.isInvalid()) Loc = FD->getLocation(); 8549 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8550 : diag::note_local_decl_close_param_match) 8551 << Idx << FDParam->getType() 8552 << NewFD->getParamDecl(Idx - 1)->getType(); 8553 } else if (FDisConst != NewFDisConst) { 8554 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8555 << NewFDisConst << FD->getSourceRange().getEnd() 8556 << (NewFDisConst 8557 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo() 8558 .getConstQualifierLoc()) 8559 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo() 8560 .getRParenLoc() 8561 .getLocWithOffset(1), 8562 " const")); 8563 } else 8564 SemaRef.Diag(FD->getLocation(), 8565 IsMember ? diag::note_member_def_close_match 8566 : diag::note_local_decl_close_match); 8567 } 8568 return nullptr; 8569 } 8570 8571 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8572 switch (D.getDeclSpec().getStorageClassSpec()) { 8573 default: llvm_unreachable("Unknown storage class!"); 8574 case DeclSpec::SCS_auto: 8575 case DeclSpec::SCS_register: 8576 case DeclSpec::SCS_mutable: 8577 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8578 diag::err_typecheck_sclass_func); 8579 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8580 D.setInvalidType(); 8581 break; 8582 case DeclSpec::SCS_unspecified: break; 8583 case DeclSpec::SCS_extern: 8584 if (D.getDeclSpec().isExternInLinkageSpec()) 8585 return SC_None; 8586 return SC_Extern; 8587 case DeclSpec::SCS_static: { 8588 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8589 // C99 6.7.1p5: 8590 // The declaration of an identifier for a function that has 8591 // block scope shall have no explicit storage-class specifier 8592 // other than extern 8593 // See also (C++ [dcl.stc]p4). 8594 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8595 diag::err_static_block_func); 8596 break; 8597 } else 8598 return SC_Static; 8599 } 8600 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8601 } 8602 8603 // No explicit storage class has already been returned 8604 return SC_None; 8605 } 8606 8607 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8608 DeclContext *DC, QualType &R, 8609 TypeSourceInfo *TInfo, 8610 StorageClass SC, 8611 bool &IsVirtualOkay) { 8612 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8613 DeclarationName Name = NameInfo.getName(); 8614 8615 FunctionDecl *NewFD = nullptr; 8616 bool isInline = D.getDeclSpec().isInlineSpecified(); 8617 8618 if (!SemaRef.getLangOpts().CPlusPlus) { 8619 // Determine whether the function was written with a 8620 // prototype. This true when: 8621 // - there is a prototype in the declarator, or 8622 // - the type R of the function is some kind of typedef or other non- 8623 // attributed reference to a type name (which eventually refers to a 8624 // function type). 8625 bool HasPrototype = 8626 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8627 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8628 8629 NewFD = FunctionDecl::Create( 8630 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8631 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 8632 ConstexprSpecKind::Unspecified, 8633 /*TrailingRequiresClause=*/nullptr); 8634 if (D.isInvalidType()) 8635 NewFD->setInvalidDecl(); 8636 8637 return NewFD; 8638 } 8639 8640 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8641 8642 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8643 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8644 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8645 diag::err_constexpr_wrong_decl_kind) 8646 << static_cast<int>(ConstexprKind); 8647 ConstexprKind = ConstexprSpecKind::Unspecified; 8648 D.getMutableDeclSpec().ClearConstexprSpec(); 8649 } 8650 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8651 8652 // Check that the return type is not an abstract class type. 8653 // For record types, this is done by the AbstractClassUsageDiagnoser once 8654 // the class has been completely parsed. 8655 if (!DC->isRecord() && 8656 SemaRef.RequireNonAbstractType( 8657 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8658 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8659 D.setInvalidType(); 8660 8661 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8662 // This is a C++ constructor declaration. 8663 assert(DC->isRecord() && 8664 "Constructors can only be declared in a member context"); 8665 8666 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8667 return CXXConstructorDecl::Create( 8668 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8669 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 8670 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8671 InheritedConstructor(), TrailingRequiresClause); 8672 8673 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8674 // This is a C++ destructor declaration. 8675 if (DC->isRecord()) { 8676 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8677 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8678 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8679 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8680 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8681 /*isImplicitlyDeclared=*/false, ConstexprKind, 8682 TrailingRequiresClause); 8683 8684 // If the destructor needs an implicit exception specification, set it 8685 // now. FIXME: It'd be nice to be able to create the right type to start 8686 // with, but the type needs to reference the destructor declaration. 8687 if (SemaRef.getLangOpts().CPlusPlus11) 8688 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8689 8690 IsVirtualOkay = true; 8691 return NewDD; 8692 8693 } else { 8694 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8695 D.setInvalidType(); 8696 8697 // Create a FunctionDecl to satisfy the function definition parsing 8698 // code path. 8699 return FunctionDecl::Create( 8700 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 8701 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8702 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 8703 } 8704 8705 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8706 if (!DC->isRecord()) { 8707 SemaRef.Diag(D.getIdentifierLoc(), 8708 diag::err_conv_function_not_member); 8709 return nullptr; 8710 } 8711 8712 SemaRef.CheckConversionDeclarator(D, R, SC); 8713 if (D.isInvalidType()) 8714 return nullptr; 8715 8716 IsVirtualOkay = true; 8717 return CXXConversionDecl::Create( 8718 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8719 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8720 ExplicitSpecifier, ConstexprKind, SourceLocation(), 8721 TrailingRequiresClause); 8722 8723 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8724 if (TrailingRequiresClause) 8725 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8726 diag::err_trailing_requires_clause_on_deduction_guide) 8727 << TrailingRequiresClause->getSourceRange(); 8728 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8729 8730 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8731 ExplicitSpecifier, NameInfo, R, TInfo, 8732 D.getEndLoc()); 8733 } else if (DC->isRecord()) { 8734 // If the name of the function is the same as the name of the record, 8735 // then this must be an invalid constructor that has a return type. 8736 // (The parser checks for a return type and makes the declarator a 8737 // constructor if it has no return type). 8738 if (Name.getAsIdentifierInfo() && 8739 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8740 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8741 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8742 << SourceRange(D.getIdentifierLoc()); 8743 return nullptr; 8744 } 8745 8746 // This is a C++ method declaration. 8747 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8748 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8749 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8750 ConstexprKind, SourceLocation(), TrailingRequiresClause); 8751 IsVirtualOkay = !Ret->isStatic(); 8752 return Ret; 8753 } else { 8754 bool isFriend = 8755 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8756 if (!isFriend && SemaRef.CurContext->isRecord()) 8757 return nullptr; 8758 8759 // Determine whether the function was written with a 8760 // prototype. This true when: 8761 // - we're in C++ (where every function has a prototype), 8762 return FunctionDecl::Create( 8763 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8764 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8765 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 8766 } 8767 } 8768 8769 enum OpenCLParamType { 8770 ValidKernelParam, 8771 PtrPtrKernelParam, 8772 PtrKernelParam, 8773 InvalidAddrSpacePtrKernelParam, 8774 InvalidKernelParam, 8775 RecordKernelParam 8776 }; 8777 8778 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8779 // Size dependent types are just typedefs to normal integer types 8780 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8781 // integers other than by their names. 8782 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8783 8784 // Remove typedefs one by one until we reach a typedef 8785 // for a size dependent type. 8786 QualType DesugaredTy = Ty; 8787 do { 8788 ArrayRef<StringRef> Names(SizeTypeNames); 8789 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8790 if (Names.end() != Match) 8791 return true; 8792 8793 Ty = DesugaredTy; 8794 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8795 } while (DesugaredTy != Ty); 8796 8797 return false; 8798 } 8799 8800 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8801 if (PT->isDependentType()) 8802 return InvalidKernelParam; 8803 8804 if (PT->isPointerType() || PT->isReferenceType()) { 8805 QualType PointeeType = PT->getPointeeType(); 8806 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8807 PointeeType.getAddressSpace() == LangAS::opencl_private || 8808 PointeeType.getAddressSpace() == LangAS::Default) 8809 return InvalidAddrSpacePtrKernelParam; 8810 8811 if (PointeeType->isPointerType()) { 8812 // This is a pointer to pointer parameter. 8813 // Recursively check inner type. 8814 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8815 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8816 ParamKind == InvalidKernelParam) 8817 return ParamKind; 8818 8819 return PtrPtrKernelParam; 8820 } 8821 8822 // C++ for OpenCL v1.0 s2.4: 8823 // Moreover the types used in parameters of the kernel functions must be: 8824 // Standard layout types for pointer parameters. The same applies to 8825 // reference if an implementation supports them in kernel parameters. 8826 if (S.getLangOpts().OpenCLCPlusPlus && 8827 !S.getOpenCLOptions().isAvailableOption( 8828 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8829 !PointeeType->isAtomicType() && !PointeeType->isVoidType() && 8830 !PointeeType->isStandardLayoutType()) 8831 return InvalidKernelParam; 8832 8833 return PtrKernelParam; 8834 } 8835 8836 // OpenCL v1.2 s6.9.k: 8837 // Arguments to kernel functions in a program cannot be declared with the 8838 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8839 // uintptr_t or a struct and/or union that contain fields declared to be one 8840 // of these built-in scalar types. 8841 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8842 return InvalidKernelParam; 8843 8844 if (PT->isImageType()) 8845 return PtrKernelParam; 8846 8847 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8848 return InvalidKernelParam; 8849 8850 // OpenCL extension spec v1.2 s9.5: 8851 // This extension adds support for half scalar and vector types as built-in 8852 // types that can be used for arithmetic operations, conversions etc. 8853 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 8854 PT->isHalfType()) 8855 return InvalidKernelParam; 8856 8857 // Look into an array argument to check if it has a forbidden type. 8858 if (PT->isArrayType()) { 8859 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8860 // Call ourself to check an underlying type of an array. Since the 8861 // getPointeeOrArrayElementType returns an innermost type which is not an 8862 // array, this recursive call only happens once. 8863 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8864 } 8865 8866 // C++ for OpenCL v1.0 s2.4: 8867 // Moreover the types used in parameters of the kernel functions must be: 8868 // Trivial and standard-layout types C++17 [basic.types] (plain old data 8869 // types) for parameters passed by value; 8870 if (S.getLangOpts().OpenCLCPlusPlus && 8871 !S.getOpenCLOptions().isAvailableOption( 8872 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8873 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 8874 return InvalidKernelParam; 8875 8876 if (PT->isRecordType()) 8877 return RecordKernelParam; 8878 8879 return ValidKernelParam; 8880 } 8881 8882 static void checkIsValidOpenCLKernelParameter( 8883 Sema &S, 8884 Declarator &D, 8885 ParmVarDecl *Param, 8886 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8887 QualType PT = Param->getType(); 8888 8889 // Cache the valid types we encounter to avoid rechecking structs that are 8890 // used again 8891 if (ValidTypes.count(PT.getTypePtr())) 8892 return; 8893 8894 switch (getOpenCLKernelParameterType(S, PT)) { 8895 case PtrPtrKernelParam: 8896 // OpenCL v3.0 s6.11.a: 8897 // A kernel function argument cannot be declared as a pointer to a pointer 8898 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8899 if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) { 8900 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8901 D.setInvalidType(); 8902 return; 8903 } 8904 8905 ValidTypes.insert(PT.getTypePtr()); 8906 return; 8907 8908 case InvalidAddrSpacePtrKernelParam: 8909 // OpenCL v1.0 s6.5: 8910 // __kernel function arguments declared to be a pointer of a type can point 8911 // to one of the following address spaces only : __global, __local or 8912 // __constant. 8913 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8914 D.setInvalidType(); 8915 return; 8916 8917 // OpenCL v1.2 s6.9.k: 8918 // Arguments to kernel functions in a program cannot be declared with the 8919 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8920 // uintptr_t or a struct and/or union that contain fields declared to be 8921 // one of these built-in scalar types. 8922 8923 case InvalidKernelParam: 8924 // OpenCL v1.2 s6.8 n: 8925 // A kernel function argument cannot be declared 8926 // of event_t type. 8927 // Do not diagnose half type since it is diagnosed as invalid argument 8928 // type for any function elsewhere. 8929 if (!PT->isHalfType()) { 8930 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8931 8932 // Explain what typedefs are involved. 8933 const TypedefType *Typedef = nullptr; 8934 while ((Typedef = PT->getAs<TypedefType>())) { 8935 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8936 // SourceLocation may be invalid for a built-in type. 8937 if (Loc.isValid()) 8938 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8939 PT = Typedef->desugar(); 8940 } 8941 } 8942 8943 D.setInvalidType(); 8944 return; 8945 8946 case PtrKernelParam: 8947 case ValidKernelParam: 8948 ValidTypes.insert(PT.getTypePtr()); 8949 return; 8950 8951 case RecordKernelParam: 8952 break; 8953 } 8954 8955 // Track nested structs we will inspect 8956 SmallVector<const Decl *, 4> VisitStack; 8957 8958 // Track where we are in the nested structs. Items will migrate from 8959 // VisitStack to HistoryStack as we do the DFS for bad field. 8960 SmallVector<const FieldDecl *, 4> HistoryStack; 8961 HistoryStack.push_back(nullptr); 8962 8963 // At this point we already handled everything except of a RecordType or 8964 // an ArrayType of a RecordType. 8965 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8966 const RecordType *RecTy = 8967 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8968 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8969 8970 VisitStack.push_back(RecTy->getDecl()); 8971 assert(VisitStack.back() && "First decl null?"); 8972 8973 do { 8974 const Decl *Next = VisitStack.pop_back_val(); 8975 if (!Next) { 8976 assert(!HistoryStack.empty()); 8977 // Found a marker, we have gone up a level 8978 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8979 ValidTypes.insert(Hist->getType().getTypePtr()); 8980 8981 continue; 8982 } 8983 8984 // Adds everything except the original parameter declaration (which is not a 8985 // field itself) to the history stack. 8986 const RecordDecl *RD; 8987 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8988 HistoryStack.push_back(Field); 8989 8990 QualType FieldTy = Field->getType(); 8991 // Other field types (known to be valid or invalid) are handled while we 8992 // walk around RecordDecl::fields(). 8993 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8994 "Unexpected type."); 8995 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8996 8997 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8998 } else { 8999 RD = cast<RecordDecl>(Next); 9000 } 9001 9002 // Add a null marker so we know when we've gone back up a level 9003 VisitStack.push_back(nullptr); 9004 9005 for (const auto *FD : RD->fields()) { 9006 QualType QT = FD->getType(); 9007 9008 if (ValidTypes.count(QT.getTypePtr())) 9009 continue; 9010 9011 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 9012 if (ParamType == ValidKernelParam) 9013 continue; 9014 9015 if (ParamType == RecordKernelParam) { 9016 VisitStack.push_back(FD); 9017 continue; 9018 } 9019 9020 // OpenCL v1.2 s6.9.p: 9021 // Arguments to kernel functions that are declared to be a struct or union 9022 // do not allow OpenCL objects to be passed as elements of the struct or 9023 // union. 9024 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 9025 ParamType == InvalidAddrSpacePtrKernelParam) { 9026 S.Diag(Param->getLocation(), 9027 diag::err_record_with_pointers_kernel_param) 9028 << PT->isUnionType() 9029 << PT; 9030 } else { 9031 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9032 } 9033 9034 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 9035 << OrigRecDecl->getDeclName(); 9036 9037 // We have an error, now let's go back up through history and show where 9038 // the offending field came from 9039 for (ArrayRef<const FieldDecl *>::const_iterator 9040 I = HistoryStack.begin() + 1, 9041 E = HistoryStack.end(); 9042 I != E; ++I) { 9043 const FieldDecl *OuterField = *I; 9044 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 9045 << OuterField->getType(); 9046 } 9047 9048 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 9049 << QT->isPointerType() 9050 << QT; 9051 D.setInvalidType(); 9052 return; 9053 } 9054 } while (!VisitStack.empty()); 9055 } 9056 9057 /// Find the DeclContext in which a tag is implicitly declared if we see an 9058 /// elaborated type specifier in the specified context, and lookup finds 9059 /// nothing. 9060 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9061 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9062 DC = DC->getParent(); 9063 return DC; 9064 } 9065 9066 /// Find the Scope in which a tag is implicitly declared if we see an 9067 /// elaborated type specifier in the specified context, and lookup finds 9068 /// nothing. 9069 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9070 while (S->isClassScope() || 9071 (LangOpts.CPlusPlus && 9072 S->isFunctionPrototypeScope()) || 9073 ((S->getFlags() & Scope::DeclScope) == 0) || 9074 (S->getEntity() && S->getEntity()->isTransparentContext())) 9075 S = S->getParent(); 9076 return S; 9077 } 9078 9079 NamedDecl* 9080 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9081 TypeSourceInfo *TInfo, LookupResult &Previous, 9082 MultiTemplateParamsArg TemplateParamListsRef, 9083 bool &AddToScope) { 9084 QualType R = TInfo->getType(); 9085 9086 assert(R->isFunctionType()); 9087 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9088 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9089 9090 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9091 for (TemplateParameterList *TPL : TemplateParamListsRef) 9092 TemplateParamLists.push_back(TPL); 9093 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9094 if (!TemplateParamLists.empty() && 9095 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9096 TemplateParamLists.back() = Invented; 9097 else 9098 TemplateParamLists.push_back(Invented); 9099 } 9100 9101 // TODO: consider using NameInfo for diagnostic. 9102 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9103 DeclarationName Name = NameInfo.getName(); 9104 StorageClass SC = getFunctionStorageClass(*this, D); 9105 9106 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9107 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9108 diag::err_invalid_thread) 9109 << DeclSpec::getSpecifierName(TSCS); 9110 9111 if (D.isFirstDeclarationOfMember()) 9112 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 9113 D.getIdentifierLoc()); 9114 9115 bool isFriend = false; 9116 FunctionTemplateDecl *FunctionTemplate = nullptr; 9117 bool isMemberSpecialization = false; 9118 bool isFunctionTemplateSpecialization = false; 9119 9120 bool isDependentClassScopeExplicitSpecialization = false; 9121 bool HasExplicitTemplateArgs = false; 9122 TemplateArgumentListInfo TemplateArgs; 9123 9124 bool isVirtualOkay = false; 9125 9126 DeclContext *OriginalDC = DC; 9127 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9128 9129 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9130 isVirtualOkay); 9131 if (!NewFD) return nullptr; 9132 9133 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9134 NewFD->setTopLevelDeclInObjCContainer(); 9135 9136 // Set the lexical context. If this is a function-scope declaration, or has a 9137 // C++ scope specifier, or is the object of a friend declaration, the lexical 9138 // context will be different from the semantic context. 9139 NewFD->setLexicalDeclContext(CurContext); 9140 9141 if (IsLocalExternDecl) 9142 NewFD->setLocalExternDecl(); 9143 9144 if (getLangOpts().CPlusPlus) { 9145 bool isInline = D.getDeclSpec().isInlineSpecified(); 9146 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9147 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9148 isFriend = D.getDeclSpec().isFriendSpecified(); 9149 if (isFriend && !isInline && D.isFunctionDefinition()) { 9150 // C++ [class.friend]p5 9151 // A function can be defined in a friend declaration of a 9152 // class . . . . Such a function is implicitly inline. 9153 NewFD->setImplicitlyInline(); 9154 } 9155 9156 // If this is a method defined in an __interface, and is not a constructor 9157 // or an overloaded operator, then set the pure flag (isVirtual will already 9158 // return true). 9159 if (const CXXRecordDecl *Parent = 9160 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9161 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9162 NewFD->setPure(true); 9163 9164 // C++ [class.union]p2 9165 // A union can have member functions, but not virtual functions. 9166 if (isVirtual && Parent->isUnion()) { 9167 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9168 NewFD->setInvalidDecl(); 9169 } 9170 } 9171 9172 SetNestedNameSpecifier(*this, NewFD, D); 9173 isMemberSpecialization = false; 9174 isFunctionTemplateSpecialization = false; 9175 if (D.isInvalidType()) 9176 NewFD->setInvalidDecl(); 9177 9178 // Match up the template parameter lists with the scope specifier, then 9179 // determine whether we have a template or a template specialization. 9180 bool Invalid = false; 9181 TemplateParameterList *TemplateParams = 9182 MatchTemplateParametersToScopeSpecifier( 9183 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9184 D.getCXXScopeSpec(), 9185 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9186 ? D.getName().TemplateId 9187 : nullptr, 9188 TemplateParamLists, isFriend, isMemberSpecialization, 9189 Invalid); 9190 if (TemplateParams) { 9191 // Check that we can declare a template here. 9192 if (CheckTemplateDeclScope(S, TemplateParams)) 9193 NewFD->setInvalidDecl(); 9194 9195 if (TemplateParams->size() > 0) { 9196 // This is a function template 9197 9198 // A destructor cannot be a template. 9199 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9200 Diag(NewFD->getLocation(), diag::err_destructor_template); 9201 NewFD->setInvalidDecl(); 9202 } 9203 9204 // If we're adding a template to a dependent context, we may need to 9205 // rebuilding some of the types used within the template parameter list, 9206 // now that we know what the current instantiation is. 9207 if (DC->isDependentContext()) { 9208 ContextRAII SavedContext(*this, DC); 9209 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9210 Invalid = true; 9211 } 9212 9213 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9214 NewFD->getLocation(), 9215 Name, TemplateParams, 9216 NewFD); 9217 FunctionTemplate->setLexicalDeclContext(CurContext); 9218 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9219 9220 // For source fidelity, store the other template param lists. 9221 if (TemplateParamLists.size() > 1) { 9222 NewFD->setTemplateParameterListsInfo(Context, 9223 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9224 .drop_back(1)); 9225 } 9226 } else { 9227 // This is a function template specialization. 9228 isFunctionTemplateSpecialization = true; 9229 // For source fidelity, store all the template param lists. 9230 if (TemplateParamLists.size() > 0) 9231 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9232 9233 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9234 if (isFriend) { 9235 // We want to remove the "template<>", found here. 9236 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9237 9238 // If we remove the template<> and the name is not a 9239 // template-id, we're actually silently creating a problem: 9240 // the friend declaration will refer to an untemplated decl, 9241 // and clearly the user wants a template specialization. So 9242 // we need to insert '<>' after the name. 9243 SourceLocation InsertLoc; 9244 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9245 InsertLoc = D.getName().getSourceRange().getEnd(); 9246 InsertLoc = getLocForEndOfToken(InsertLoc); 9247 } 9248 9249 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9250 << Name << RemoveRange 9251 << FixItHint::CreateRemoval(RemoveRange) 9252 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9253 Invalid = true; 9254 } 9255 } 9256 } else { 9257 // Check that we can declare a template here. 9258 if (!TemplateParamLists.empty() && isMemberSpecialization && 9259 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9260 NewFD->setInvalidDecl(); 9261 9262 // All template param lists were matched against the scope specifier: 9263 // this is NOT (an explicit specialization of) a template. 9264 if (TemplateParamLists.size() > 0) 9265 // For source fidelity, store all the template param lists. 9266 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9267 } 9268 9269 if (Invalid) { 9270 NewFD->setInvalidDecl(); 9271 if (FunctionTemplate) 9272 FunctionTemplate->setInvalidDecl(); 9273 } 9274 9275 // C++ [dcl.fct.spec]p5: 9276 // The virtual specifier shall only be used in declarations of 9277 // nonstatic class member functions that appear within a 9278 // member-specification of a class declaration; see 10.3. 9279 // 9280 if (isVirtual && !NewFD->isInvalidDecl()) { 9281 if (!isVirtualOkay) { 9282 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9283 diag::err_virtual_non_function); 9284 } else if (!CurContext->isRecord()) { 9285 // 'virtual' was specified outside of the class. 9286 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9287 diag::err_virtual_out_of_class) 9288 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9289 } else if (NewFD->getDescribedFunctionTemplate()) { 9290 // C++ [temp.mem]p3: 9291 // A member function template shall not be virtual. 9292 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9293 diag::err_virtual_member_function_template) 9294 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9295 } else { 9296 // Okay: Add virtual to the method. 9297 NewFD->setVirtualAsWritten(true); 9298 } 9299 9300 if (getLangOpts().CPlusPlus14 && 9301 NewFD->getReturnType()->isUndeducedType()) 9302 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9303 } 9304 9305 if (getLangOpts().CPlusPlus14 && 9306 (NewFD->isDependentContext() || 9307 (isFriend && CurContext->isDependentContext())) && 9308 NewFD->getReturnType()->isUndeducedType()) { 9309 // If the function template is referenced directly (for instance, as a 9310 // member of the current instantiation), pretend it has a dependent type. 9311 // This is not really justified by the standard, but is the only sane 9312 // thing to do. 9313 // FIXME: For a friend function, we have not marked the function as being 9314 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9315 const FunctionProtoType *FPT = 9316 NewFD->getType()->castAs<FunctionProtoType>(); 9317 QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); 9318 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9319 FPT->getExtProtoInfo())); 9320 } 9321 9322 // C++ [dcl.fct.spec]p3: 9323 // The inline specifier shall not appear on a block scope function 9324 // declaration. 9325 if (isInline && !NewFD->isInvalidDecl()) { 9326 if (CurContext->isFunctionOrMethod()) { 9327 // 'inline' is not allowed on block scope function declaration. 9328 Diag(D.getDeclSpec().getInlineSpecLoc(), 9329 diag::err_inline_declaration_block_scope) << Name 9330 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9331 } 9332 } 9333 9334 // C++ [dcl.fct.spec]p6: 9335 // The explicit specifier shall be used only in the declaration of a 9336 // constructor or conversion function within its class definition; 9337 // see 12.3.1 and 12.3.2. 9338 if (hasExplicit && !NewFD->isInvalidDecl() && 9339 !isa<CXXDeductionGuideDecl>(NewFD)) { 9340 if (!CurContext->isRecord()) { 9341 // 'explicit' was specified outside of the class. 9342 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9343 diag::err_explicit_out_of_class) 9344 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9345 } else if (!isa<CXXConstructorDecl>(NewFD) && 9346 !isa<CXXConversionDecl>(NewFD)) { 9347 // 'explicit' was specified on a function that wasn't a constructor 9348 // or conversion function. 9349 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9350 diag::err_explicit_non_ctor_or_conv_function) 9351 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9352 } 9353 } 9354 9355 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9356 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9357 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9358 // are implicitly inline. 9359 NewFD->setImplicitlyInline(); 9360 9361 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9362 // be either constructors or to return a literal type. Therefore, 9363 // destructors cannot be declared constexpr. 9364 if (isa<CXXDestructorDecl>(NewFD) && 9365 (!getLangOpts().CPlusPlus20 || 9366 ConstexprKind == ConstexprSpecKind::Consteval)) { 9367 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9368 << static_cast<int>(ConstexprKind); 9369 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9370 ? ConstexprSpecKind::Unspecified 9371 : ConstexprSpecKind::Constexpr); 9372 } 9373 // C++20 [dcl.constexpr]p2: An allocation function, or a 9374 // deallocation function shall not be declared with the consteval 9375 // specifier. 9376 if (ConstexprKind == ConstexprSpecKind::Consteval && 9377 (NewFD->getOverloadedOperator() == OO_New || 9378 NewFD->getOverloadedOperator() == OO_Array_New || 9379 NewFD->getOverloadedOperator() == OO_Delete || 9380 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9381 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9382 diag::err_invalid_consteval_decl_kind) 9383 << NewFD; 9384 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9385 } 9386 } 9387 9388 // If __module_private__ was specified, mark the function accordingly. 9389 if (D.getDeclSpec().isModulePrivateSpecified()) { 9390 if (isFunctionTemplateSpecialization) { 9391 SourceLocation ModulePrivateLoc 9392 = D.getDeclSpec().getModulePrivateSpecLoc(); 9393 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9394 << 0 9395 << FixItHint::CreateRemoval(ModulePrivateLoc); 9396 } else { 9397 NewFD->setModulePrivate(); 9398 if (FunctionTemplate) 9399 FunctionTemplate->setModulePrivate(); 9400 } 9401 } 9402 9403 if (isFriend) { 9404 if (FunctionTemplate) { 9405 FunctionTemplate->setObjectOfFriendDecl(); 9406 FunctionTemplate->setAccess(AS_public); 9407 } 9408 NewFD->setObjectOfFriendDecl(); 9409 NewFD->setAccess(AS_public); 9410 } 9411 9412 // If a function is defined as defaulted or deleted, mark it as such now. 9413 // We'll do the relevant checks on defaulted / deleted functions later. 9414 switch (D.getFunctionDefinitionKind()) { 9415 case FunctionDefinitionKind::Declaration: 9416 case FunctionDefinitionKind::Definition: 9417 break; 9418 9419 case FunctionDefinitionKind::Defaulted: 9420 NewFD->setDefaulted(); 9421 break; 9422 9423 case FunctionDefinitionKind::Deleted: 9424 NewFD->setDeletedAsWritten(); 9425 break; 9426 } 9427 9428 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9429 D.isFunctionDefinition()) { 9430 // C++ [class.mfct]p2: 9431 // A member function may be defined (8.4) in its class definition, in 9432 // which case it is an inline member function (7.1.2) 9433 NewFD->setImplicitlyInline(); 9434 } 9435 9436 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9437 !CurContext->isRecord()) { 9438 // C++ [class.static]p1: 9439 // A data or function member of a class may be declared static 9440 // in a class definition, in which case it is a static member of 9441 // the class. 9442 9443 // Complain about the 'static' specifier if it's on an out-of-line 9444 // member function definition. 9445 9446 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9447 // member function template declaration and class member template 9448 // declaration (MSVC versions before 2015), warn about this. 9449 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9450 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9451 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9452 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9453 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9454 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9455 } 9456 9457 // C++11 [except.spec]p15: 9458 // A deallocation function with no exception-specification is treated 9459 // as if it were specified with noexcept(true). 9460 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9461 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9462 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9463 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9464 NewFD->setType(Context.getFunctionType( 9465 FPT->getReturnType(), FPT->getParamTypes(), 9466 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9467 } 9468 9469 // Filter out previous declarations that don't match the scope. 9470 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9471 D.getCXXScopeSpec().isNotEmpty() || 9472 isMemberSpecialization || 9473 isFunctionTemplateSpecialization); 9474 9475 // Handle GNU asm-label extension (encoded as an attribute). 9476 if (Expr *E = (Expr*) D.getAsmLabel()) { 9477 // The parser guarantees this is a string. 9478 StringLiteral *SE = cast<StringLiteral>(E); 9479 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9480 /*IsLiteralLabel=*/true, 9481 SE->getStrTokenLoc(0))); 9482 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9483 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9484 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9485 if (I != ExtnameUndeclaredIdentifiers.end()) { 9486 if (isDeclExternC(NewFD)) { 9487 NewFD->addAttr(I->second); 9488 ExtnameUndeclaredIdentifiers.erase(I); 9489 } else 9490 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9491 << /*Variable*/0 << NewFD; 9492 } 9493 } 9494 9495 // Copy the parameter declarations from the declarator D to the function 9496 // declaration NewFD, if they are available. First scavenge them into Params. 9497 SmallVector<ParmVarDecl*, 16> Params; 9498 unsigned FTIIdx; 9499 if (D.isFunctionDeclarator(FTIIdx)) { 9500 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9501 9502 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9503 // function that takes no arguments, not a function that takes a 9504 // single void argument. 9505 // We let through "const void" here because Sema::GetTypeForDeclarator 9506 // already checks for that case. 9507 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9508 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9509 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9510 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9511 Param->setDeclContext(NewFD); 9512 Params.push_back(Param); 9513 9514 if (Param->isInvalidDecl()) 9515 NewFD->setInvalidDecl(); 9516 } 9517 } 9518 9519 if (!getLangOpts().CPlusPlus) { 9520 // In C, find all the tag declarations from the prototype and move them 9521 // into the function DeclContext. Remove them from the surrounding tag 9522 // injection context of the function, which is typically but not always 9523 // the TU. 9524 DeclContext *PrototypeTagContext = 9525 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9526 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9527 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9528 9529 // We don't want to reparent enumerators. Look at their parent enum 9530 // instead. 9531 if (!TD) { 9532 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9533 TD = cast<EnumDecl>(ECD->getDeclContext()); 9534 } 9535 if (!TD) 9536 continue; 9537 DeclContext *TagDC = TD->getLexicalDeclContext(); 9538 if (!TagDC->containsDecl(TD)) 9539 continue; 9540 TagDC->removeDecl(TD); 9541 TD->setDeclContext(NewFD); 9542 NewFD->addDecl(TD); 9543 9544 // Preserve the lexical DeclContext if it is not the surrounding tag 9545 // injection context of the FD. In this example, the semantic context of 9546 // E will be f and the lexical context will be S, while both the 9547 // semantic and lexical contexts of S will be f: 9548 // void f(struct S { enum E { a } f; } s); 9549 if (TagDC != PrototypeTagContext) 9550 TD->setLexicalDeclContext(TagDC); 9551 } 9552 } 9553 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9554 // When we're declaring a function with a typedef, typeof, etc as in the 9555 // following example, we'll need to synthesize (unnamed) 9556 // parameters for use in the declaration. 9557 // 9558 // @code 9559 // typedef void fn(int); 9560 // fn f; 9561 // @endcode 9562 9563 // Synthesize a parameter for each argument type. 9564 for (const auto &AI : FT->param_types()) { 9565 ParmVarDecl *Param = 9566 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9567 Param->setScopeInfo(0, Params.size()); 9568 Params.push_back(Param); 9569 } 9570 } else { 9571 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9572 "Should not need args for typedef of non-prototype fn"); 9573 } 9574 9575 // Finally, we know we have the right number of parameters, install them. 9576 NewFD->setParams(Params); 9577 9578 if (D.getDeclSpec().isNoreturnSpecified()) 9579 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9580 D.getDeclSpec().getNoreturnSpecLoc(), 9581 AttributeCommonInfo::AS_Keyword)); 9582 9583 // Functions returning a variably modified type violate C99 6.7.5.2p2 9584 // because all functions have linkage. 9585 if (!NewFD->isInvalidDecl() && 9586 NewFD->getReturnType()->isVariablyModifiedType()) { 9587 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9588 NewFD->setInvalidDecl(); 9589 } 9590 9591 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9592 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9593 !NewFD->hasAttr<SectionAttr>()) 9594 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9595 Context, PragmaClangTextSection.SectionName, 9596 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9597 9598 // Apply an implicit SectionAttr if #pragma code_seg is active. 9599 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9600 !NewFD->hasAttr<SectionAttr>()) { 9601 NewFD->addAttr(SectionAttr::CreateImplicit( 9602 Context, CodeSegStack.CurrentValue->getString(), 9603 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9604 SectionAttr::Declspec_allocate)); 9605 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9606 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9607 ASTContext::PSF_Read, 9608 NewFD)) 9609 NewFD->dropAttr<SectionAttr>(); 9610 } 9611 9612 // Apply an implicit CodeSegAttr from class declspec or 9613 // apply an implicit SectionAttr from #pragma code_seg if active. 9614 if (!NewFD->hasAttr<CodeSegAttr>()) { 9615 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9616 D.isFunctionDefinition())) { 9617 NewFD->addAttr(SAttr); 9618 } 9619 } 9620 9621 // Handle attributes. 9622 ProcessDeclAttributes(S, NewFD, D); 9623 9624 if (getLangOpts().OpenCL) { 9625 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9626 // type declaration will generate a compilation error. 9627 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9628 if (AddressSpace != LangAS::Default) { 9629 Diag(NewFD->getLocation(), 9630 diag::err_opencl_return_value_with_address_space); 9631 NewFD->setInvalidDecl(); 9632 } 9633 } 9634 9635 if (!getLangOpts().CPlusPlus) { 9636 // Perform semantic checking on the function declaration. 9637 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9638 CheckMain(NewFD, D.getDeclSpec()); 9639 9640 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9641 CheckMSVCRTEntryPoint(NewFD); 9642 9643 if (!NewFD->isInvalidDecl()) 9644 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9645 isMemberSpecialization)); 9646 else if (!Previous.empty()) 9647 // Recover gracefully from an invalid redeclaration. 9648 D.setRedeclaration(true); 9649 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9650 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9651 "previous declaration set still overloaded"); 9652 9653 // Diagnose no-prototype function declarations with calling conventions that 9654 // don't support variadic calls. Only do this in C and do it after merging 9655 // possibly prototyped redeclarations. 9656 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9657 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9658 CallingConv CC = FT->getExtInfo().getCC(); 9659 if (!supportsVariadicCall(CC)) { 9660 // Windows system headers sometimes accidentally use stdcall without 9661 // (void) parameters, so we relax this to a warning. 9662 int DiagID = 9663 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9664 Diag(NewFD->getLocation(), DiagID) 9665 << FunctionType::getNameForCallConv(CC); 9666 } 9667 } 9668 9669 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9670 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9671 checkNonTrivialCUnion(NewFD->getReturnType(), 9672 NewFD->getReturnTypeSourceRange().getBegin(), 9673 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9674 } else { 9675 // C++11 [replacement.functions]p3: 9676 // The program's definitions shall not be specified as inline. 9677 // 9678 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9679 // 9680 // Suppress the diagnostic if the function is __attribute__((used)), since 9681 // that forces an external definition to be emitted. 9682 if (D.getDeclSpec().isInlineSpecified() && 9683 NewFD->isReplaceableGlobalAllocationFunction() && 9684 !NewFD->hasAttr<UsedAttr>()) 9685 Diag(D.getDeclSpec().getInlineSpecLoc(), 9686 diag::ext_operator_new_delete_declared_inline) 9687 << NewFD->getDeclName(); 9688 9689 // If the declarator is a template-id, translate the parser's template 9690 // argument list into our AST format. 9691 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9692 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9693 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9694 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9695 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9696 TemplateId->NumArgs); 9697 translateTemplateArguments(TemplateArgsPtr, 9698 TemplateArgs); 9699 9700 HasExplicitTemplateArgs = true; 9701 9702 if (NewFD->isInvalidDecl()) { 9703 HasExplicitTemplateArgs = false; 9704 } else if (FunctionTemplate) { 9705 // Function template with explicit template arguments. 9706 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9707 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9708 9709 HasExplicitTemplateArgs = false; 9710 } else { 9711 assert((isFunctionTemplateSpecialization || 9712 D.getDeclSpec().isFriendSpecified()) && 9713 "should have a 'template<>' for this decl"); 9714 // "friend void foo<>(int);" is an implicit specialization decl. 9715 isFunctionTemplateSpecialization = true; 9716 } 9717 } else if (isFriend && isFunctionTemplateSpecialization) { 9718 // This combination is only possible in a recovery case; the user 9719 // wrote something like: 9720 // template <> friend void foo(int); 9721 // which we're recovering from as if the user had written: 9722 // friend void foo<>(int); 9723 // Go ahead and fake up a template id. 9724 HasExplicitTemplateArgs = true; 9725 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9726 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9727 } 9728 9729 // We do not add HD attributes to specializations here because 9730 // they may have different constexpr-ness compared to their 9731 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9732 // may end up with different effective targets. Instead, a 9733 // specialization inherits its target attributes from its template 9734 // in the CheckFunctionTemplateSpecialization() call below. 9735 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9736 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9737 9738 // If it's a friend (and only if it's a friend), it's possible 9739 // that either the specialized function type or the specialized 9740 // template is dependent, and therefore matching will fail. In 9741 // this case, don't check the specialization yet. 9742 if (isFunctionTemplateSpecialization && isFriend && 9743 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9744 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9745 TemplateArgs.arguments()))) { 9746 assert(HasExplicitTemplateArgs && 9747 "friend function specialization without template args"); 9748 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9749 Previous)) 9750 NewFD->setInvalidDecl(); 9751 } else if (isFunctionTemplateSpecialization) { 9752 if (CurContext->isDependentContext() && CurContext->isRecord() 9753 && !isFriend) { 9754 isDependentClassScopeExplicitSpecialization = true; 9755 } else if (!NewFD->isInvalidDecl() && 9756 CheckFunctionTemplateSpecialization( 9757 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9758 Previous)) 9759 NewFD->setInvalidDecl(); 9760 9761 // C++ [dcl.stc]p1: 9762 // A storage-class-specifier shall not be specified in an explicit 9763 // specialization (14.7.3) 9764 FunctionTemplateSpecializationInfo *Info = 9765 NewFD->getTemplateSpecializationInfo(); 9766 if (Info && SC != SC_None) { 9767 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9768 Diag(NewFD->getLocation(), 9769 diag::err_explicit_specialization_inconsistent_storage_class) 9770 << SC 9771 << FixItHint::CreateRemoval( 9772 D.getDeclSpec().getStorageClassSpecLoc()); 9773 9774 else 9775 Diag(NewFD->getLocation(), 9776 diag::ext_explicit_specialization_storage_class) 9777 << FixItHint::CreateRemoval( 9778 D.getDeclSpec().getStorageClassSpecLoc()); 9779 } 9780 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9781 if (CheckMemberSpecialization(NewFD, Previous)) 9782 NewFD->setInvalidDecl(); 9783 } 9784 9785 // Perform semantic checking on the function declaration. 9786 if (!isDependentClassScopeExplicitSpecialization) { 9787 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9788 CheckMain(NewFD, D.getDeclSpec()); 9789 9790 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9791 CheckMSVCRTEntryPoint(NewFD); 9792 9793 if (!NewFD->isInvalidDecl()) 9794 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9795 isMemberSpecialization)); 9796 else if (!Previous.empty()) 9797 // Recover gracefully from an invalid redeclaration. 9798 D.setRedeclaration(true); 9799 } 9800 9801 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9802 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9803 "previous declaration set still overloaded"); 9804 9805 NamedDecl *PrincipalDecl = (FunctionTemplate 9806 ? cast<NamedDecl>(FunctionTemplate) 9807 : NewFD); 9808 9809 if (isFriend && NewFD->getPreviousDecl()) { 9810 AccessSpecifier Access = AS_public; 9811 if (!NewFD->isInvalidDecl()) 9812 Access = NewFD->getPreviousDecl()->getAccess(); 9813 9814 NewFD->setAccess(Access); 9815 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9816 } 9817 9818 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9819 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9820 PrincipalDecl->setNonMemberOperator(); 9821 9822 // If we have a function template, check the template parameter 9823 // list. This will check and merge default template arguments. 9824 if (FunctionTemplate) { 9825 FunctionTemplateDecl *PrevTemplate = 9826 FunctionTemplate->getPreviousDecl(); 9827 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9828 PrevTemplate ? PrevTemplate->getTemplateParameters() 9829 : nullptr, 9830 D.getDeclSpec().isFriendSpecified() 9831 ? (D.isFunctionDefinition() 9832 ? TPC_FriendFunctionTemplateDefinition 9833 : TPC_FriendFunctionTemplate) 9834 : (D.getCXXScopeSpec().isSet() && 9835 DC && DC->isRecord() && 9836 DC->isDependentContext()) 9837 ? TPC_ClassTemplateMember 9838 : TPC_FunctionTemplate); 9839 } 9840 9841 if (NewFD->isInvalidDecl()) { 9842 // Ignore all the rest of this. 9843 } else if (!D.isRedeclaration()) { 9844 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9845 AddToScope }; 9846 // Fake up an access specifier if it's supposed to be a class member. 9847 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9848 NewFD->setAccess(AS_public); 9849 9850 // Qualified decls generally require a previous declaration. 9851 if (D.getCXXScopeSpec().isSet()) { 9852 // ...with the major exception of templated-scope or 9853 // dependent-scope friend declarations. 9854 9855 // TODO: we currently also suppress this check in dependent 9856 // contexts because (1) the parameter depth will be off when 9857 // matching friend templates and (2) we might actually be 9858 // selecting a friend based on a dependent factor. But there 9859 // are situations where these conditions don't apply and we 9860 // can actually do this check immediately. 9861 // 9862 // Unless the scope is dependent, it's always an error if qualified 9863 // redeclaration lookup found nothing at all. Diagnose that now; 9864 // nothing will diagnose that error later. 9865 if (isFriend && 9866 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9867 (!Previous.empty() && CurContext->isDependentContext()))) { 9868 // ignore these 9869 } else if (NewFD->isCPUDispatchMultiVersion() || 9870 NewFD->isCPUSpecificMultiVersion()) { 9871 // ignore this, we allow the redeclaration behavior here to create new 9872 // versions of the function. 9873 } else { 9874 // The user tried to provide an out-of-line definition for a 9875 // function that is a member of a class or namespace, but there 9876 // was no such member function declared (C++ [class.mfct]p2, 9877 // C++ [namespace.memdef]p2). For example: 9878 // 9879 // class X { 9880 // void f() const; 9881 // }; 9882 // 9883 // void X::f() { } // ill-formed 9884 // 9885 // Complain about this problem, and attempt to suggest close 9886 // matches (e.g., those that differ only in cv-qualifiers and 9887 // whether the parameter types are references). 9888 9889 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9890 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9891 AddToScope = ExtraArgs.AddToScope; 9892 return Result; 9893 } 9894 } 9895 9896 // Unqualified local friend declarations are required to resolve 9897 // to something. 9898 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9899 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9900 *this, Previous, NewFD, ExtraArgs, true, S)) { 9901 AddToScope = ExtraArgs.AddToScope; 9902 return Result; 9903 } 9904 } 9905 } else if (!D.isFunctionDefinition() && 9906 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9907 !isFriend && !isFunctionTemplateSpecialization && 9908 !isMemberSpecialization) { 9909 // An out-of-line member function declaration must also be a 9910 // definition (C++ [class.mfct]p2). 9911 // Note that this is not the case for explicit specializations of 9912 // function templates or member functions of class templates, per 9913 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9914 // extension for compatibility with old SWIG code which likes to 9915 // generate them. 9916 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9917 << D.getCXXScopeSpec().getRange(); 9918 } 9919 } 9920 9921 // If this is the first declaration of a library builtin function, add 9922 // attributes as appropriate. 9923 if (!D.isRedeclaration() && 9924 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9925 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9926 if (unsigned BuiltinID = II->getBuiltinID()) { 9927 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9928 // Validate the type matches unless this builtin is specified as 9929 // matching regardless of its declared type. 9930 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9931 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9932 } else { 9933 ASTContext::GetBuiltinTypeError Error; 9934 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9935 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9936 9937 if (!Error && !BuiltinType.isNull() && 9938 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9939 NewFD->getType(), BuiltinType)) 9940 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9941 } 9942 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9943 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9944 // FIXME: We should consider this a builtin only in the std namespace. 9945 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9946 } 9947 } 9948 } 9949 } 9950 9951 ProcessPragmaWeak(S, NewFD); 9952 checkAttributesAfterMerging(*this, *NewFD); 9953 9954 AddKnownFunctionAttributes(NewFD); 9955 9956 if (NewFD->hasAttr<OverloadableAttr>() && 9957 !NewFD->getType()->getAs<FunctionProtoType>()) { 9958 Diag(NewFD->getLocation(), 9959 diag::err_attribute_overloadable_no_prototype) 9960 << NewFD; 9961 9962 // Turn this into a variadic function with no parameters. 9963 const auto *FT = NewFD->getType()->castAs<FunctionType>(); 9964 FunctionProtoType::ExtProtoInfo EPI( 9965 Context.getDefaultCallingConvention(true, false)); 9966 EPI.Variadic = true; 9967 EPI.ExtInfo = FT->getExtInfo(); 9968 9969 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9970 NewFD->setType(R); 9971 } 9972 9973 // If there's a #pragma GCC visibility in scope, and this isn't a class 9974 // member, set the visibility of this function. 9975 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9976 AddPushedVisibilityAttribute(NewFD); 9977 9978 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9979 // marking the function. 9980 AddCFAuditedAttribute(NewFD); 9981 9982 // If this is a function definition, check if we have to apply optnone due to 9983 // a pragma. 9984 if(D.isFunctionDefinition()) 9985 AddRangeBasedOptnone(NewFD); 9986 9987 // If this is the first declaration of an extern C variable, update 9988 // the map of such variables. 9989 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9990 isIncompleteDeclExternC(*this, NewFD)) 9991 RegisterLocallyScopedExternCDecl(NewFD, S); 9992 9993 // Set this FunctionDecl's range up to the right paren. 9994 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9995 9996 if (D.isRedeclaration() && !Previous.empty()) { 9997 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9998 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9999 isMemberSpecialization || 10000 isFunctionTemplateSpecialization, 10001 D.isFunctionDefinition()); 10002 } 10003 10004 if (getLangOpts().CUDA) { 10005 IdentifierInfo *II = NewFD->getIdentifier(); 10006 if (II && II->isStr(getCudaConfigureFuncName()) && 10007 !NewFD->isInvalidDecl() && 10008 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 10009 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 10010 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 10011 << getCudaConfigureFuncName(); 10012 Context.setcudaConfigureCallDecl(NewFD); 10013 } 10014 10015 // Variadic functions, other than a *declaration* of printf, are not allowed 10016 // in device-side CUDA code, unless someone passed 10017 // -fcuda-allow-variadic-functions. 10018 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 10019 (NewFD->hasAttr<CUDADeviceAttr>() || 10020 NewFD->hasAttr<CUDAGlobalAttr>()) && 10021 !(II && II->isStr("printf") && NewFD->isExternC() && 10022 !D.isFunctionDefinition())) { 10023 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 10024 } 10025 } 10026 10027 MarkUnusedFileScopedDecl(NewFD); 10028 10029 10030 10031 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 10032 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 10033 if (SC == SC_Static) { 10034 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 10035 D.setInvalidType(); 10036 } 10037 10038 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 10039 if (!NewFD->getReturnType()->isVoidType()) { 10040 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 10041 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 10042 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 10043 : FixItHint()); 10044 D.setInvalidType(); 10045 } 10046 10047 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 10048 for (auto Param : NewFD->parameters()) 10049 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 10050 10051 if (getLangOpts().OpenCLCPlusPlus) { 10052 if (DC->isRecord()) { 10053 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 10054 D.setInvalidType(); 10055 } 10056 if (FunctionTemplate) { 10057 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10058 D.setInvalidType(); 10059 } 10060 } 10061 } 10062 10063 if (getLangOpts().CPlusPlus) { 10064 if (FunctionTemplate) { 10065 if (NewFD->isInvalidDecl()) 10066 FunctionTemplate->setInvalidDecl(); 10067 return FunctionTemplate; 10068 } 10069 10070 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10071 CompleteMemberSpecialization(NewFD, Previous); 10072 } 10073 10074 for (const ParmVarDecl *Param : NewFD->parameters()) { 10075 QualType PT = Param->getType(); 10076 10077 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10078 // types. 10079 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10080 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10081 QualType ElemTy = PipeTy->getElementType(); 10082 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10083 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10084 D.setInvalidType(); 10085 } 10086 } 10087 } 10088 } 10089 10090 // Here we have an function template explicit specialization at class scope. 10091 // The actual specialization will be postponed to template instatiation 10092 // time via the ClassScopeFunctionSpecializationDecl node. 10093 if (isDependentClassScopeExplicitSpecialization) { 10094 ClassScopeFunctionSpecializationDecl *NewSpec = 10095 ClassScopeFunctionSpecializationDecl::Create( 10096 Context, CurContext, NewFD->getLocation(), 10097 cast<CXXMethodDecl>(NewFD), 10098 HasExplicitTemplateArgs, TemplateArgs); 10099 CurContext->addDecl(NewSpec); 10100 AddToScope = false; 10101 } 10102 10103 // Diagnose availability attributes. Availability cannot be used on functions 10104 // that are run during load/unload. 10105 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10106 if (NewFD->hasAttr<ConstructorAttr>()) { 10107 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10108 << 1; 10109 NewFD->dropAttr<AvailabilityAttr>(); 10110 } 10111 if (NewFD->hasAttr<DestructorAttr>()) { 10112 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10113 << 2; 10114 NewFD->dropAttr<AvailabilityAttr>(); 10115 } 10116 } 10117 10118 // Diagnose no_builtin attribute on function declaration that are not a 10119 // definition. 10120 // FIXME: We should really be doing this in 10121 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10122 // the FunctionDecl and at this point of the code 10123 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10124 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10125 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10126 switch (D.getFunctionDefinitionKind()) { 10127 case FunctionDefinitionKind::Defaulted: 10128 case FunctionDefinitionKind::Deleted: 10129 Diag(NBA->getLocation(), 10130 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10131 << NBA->getSpelling(); 10132 break; 10133 case FunctionDefinitionKind::Declaration: 10134 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10135 << NBA->getSpelling(); 10136 break; 10137 case FunctionDefinitionKind::Definition: 10138 break; 10139 } 10140 10141 return NewFD; 10142 } 10143 10144 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10145 /// when __declspec(code_seg) "is applied to a class, all member functions of 10146 /// the class and nested classes -- this includes compiler-generated special 10147 /// member functions -- are put in the specified segment." 10148 /// The actual behavior is a little more complicated. The Microsoft compiler 10149 /// won't check outer classes if there is an active value from #pragma code_seg. 10150 /// The CodeSeg is always applied from the direct parent but only from outer 10151 /// classes when the #pragma code_seg stack is empty. See: 10152 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10153 /// available since MS has removed the page. 10154 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10155 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10156 if (!Method) 10157 return nullptr; 10158 const CXXRecordDecl *Parent = Method->getParent(); 10159 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10160 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10161 NewAttr->setImplicit(true); 10162 return NewAttr; 10163 } 10164 10165 // The Microsoft compiler won't check outer classes for the CodeSeg 10166 // when the #pragma code_seg stack is active. 10167 if (S.CodeSegStack.CurrentValue) 10168 return nullptr; 10169 10170 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10171 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10172 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10173 NewAttr->setImplicit(true); 10174 return NewAttr; 10175 } 10176 } 10177 return nullptr; 10178 } 10179 10180 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10181 /// containing class. Otherwise it will return implicit SectionAttr if the 10182 /// function is a definition and there is an active value on CodeSegStack 10183 /// (from the current #pragma code-seg value). 10184 /// 10185 /// \param FD Function being declared. 10186 /// \param IsDefinition Whether it is a definition or just a declarartion. 10187 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10188 /// nullptr if no attribute should be added. 10189 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10190 bool IsDefinition) { 10191 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10192 return A; 10193 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10194 CodeSegStack.CurrentValue) 10195 return SectionAttr::CreateImplicit( 10196 getASTContext(), CodeSegStack.CurrentValue->getString(), 10197 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10198 SectionAttr::Declspec_allocate); 10199 return nullptr; 10200 } 10201 10202 /// Determines if we can perform a correct type check for \p D as a 10203 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10204 /// best-effort check. 10205 /// 10206 /// \param NewD The new declaration. 10207 /// \param OldD The old declaration. 10208 /// \param NewT The portion of the type of the new declaration to check. 10209 /// \param OldT The portion of the type of the old declaration to check. 10210 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10211 QualType NewT, QualType OldT) { 10212 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10213 return true; 10214 10215 // For dependently-typed local extern declarations and friends, we can't 10216 // perform a correct type check in general until instantiation: 10217 // 10218 // int f(); 10219 // template<typename T> void g() { T f(); } 10220 // 10221 // (valid if g() is only instantiated with T = int). 10222 if (NewT->isDependentType() && 10223 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10224 return false; 10225 10226 // Similarly, if the previous declaration was a dependent local extern 10227 // declaration, we don't really know its type yet. 10228 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10229 return false; 10230 10231 return true; 10232 } 10233 10234 /// Checks if the new declaration declared in dependent context must be 10235 /// put in the same redeclaration chain as the specified declaration. 10236 /// 10237 /// \param D Declaration that is checked. 10238 /// \param PrevDecl Previous declaration found with proper lookup method for the 10239 /// same declaration name. 10240 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10241 /// belongs to. 10242 /// 10243 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10244 if (!D->getLexicalDeclContext()->isDependentContext()) 10245 return true; 10246 10247 // Don't chain dependent friend function definitions until instantiation, to 10248 // permit cases like 10249 // 10250 // void func(); 10251 // template<typename T> class C1 { friend void func() {} }; 10252 // template<typename T> class C2 { friend void func() {} }; 10253 // 10254 // ... which is valid if only one of C1 and C2 is ever instantiated. 10255 // 10256 // FIXME: This need only apply to function definitions. For now, we proxy 10257 // this by checking for a file-scope function. We do not want this to apply 10258 // to friend declarations nominating member functions, because that gets in 10259 // the way of access checks. 10260 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10261 return false; 10262 10263 auto *VD = dyn_cast<ValueDecl>(D); 10264 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10265 return !VD || !PrevVD || 10266 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10267 PrevVD->getType()); 10268 } 10269 10270 /// Check the target attribute of the function for MultiVersion 10271 /// validity. 10272 /// 10273 /// Returns true if there was an error, false otherwise. 10274 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10275 const auto *TA = FD->getAttr<TargetAttr>(); 10276 assert(TA && "MultiVersion Candidate requires a target attribute"); 10277 ParsedTargetAttr ParseInfo = TA->parse(); 10278 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10279 enum ErrType { Feature = 0, Architecture = 1 }; 10280 10281 if (!ParseInfo.Architecture.empty() && 10282 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10283 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10284 << Architecture << ParseInfo.Architecture; 10285 return true; 10286 } 10287 10288 for (const auto &Feat : ParseInfo.Features) { 10289 auto BareFeat = StringRef{Feat}.substr(1); 10290 if (Feat[0] == '-') { 10291 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10292 << Feature << ("no-" + BareFeat).str(); 10293 return true; 10294 } 10295 10296 if (!TargetInfo.validateCpuSupports(BareFeat) || 10297 !TargetInfo.isValidFeatureName(BareFeat)) { 10298 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10299 << Feature << BareFeat; 10300 return true; 10301 } 10302 } 10303 return false; 10304 } 10305 10306 // Provide a white-list of attributes that are allowed to be combined with 10307 // multiversion functions. 10308 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10309 MultiVersionKind MVType) { 10310 // Note: this list/diagnosis must match the list in 10311 // checkMultiversionAttributesAllSame. 10312 switch (Kind) { 10313 default: 10314 return false; 10315 case attr::Used: 10316 return MVType == MultiVersionKind::Target; 10317 case attr::NonNull: 10318 case attr::NoThrow: 10319 return true; 10320 } 10321 } 10322 10323 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10324 const FunctionDecl *FD, 10325 const FunctionDecl *CausedFD, 10326 MultiVersionKind MVType) { 10327 const auto Diagnose = [FD, CausedFD, MVType](Sema &S, const Attr *A) { 10328 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10329 << static_cast<unsigned>(MVType) << A; 10330 if (CausedFD) 10331 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10332 return true; 10333 }; 10334 10335 for (const Attr *A : FD->attrs()) { 10336 switch (A->getKind()) { 10337 case attr::CPUDispatch: 10338 case attr::CPUSpecific: 10339 if (MVType != MultiVersionKind::CPUDispatch && 10340 MVType != MultiVersionKind::CPUSpecific) 10341 return Diagnose(S, A); 10342 break; 10343 case attr::Target: 10344 if (MVType != MultiVersionKind::Target) 10345 return Diagnose(S, A); 10346 break; 10347 case attr::TargetClones: 10348 if (MVType != MultiVersionKind::TargetClones) 10349 return Diagnose(S, A); 10350 break; 10351 default: 10352 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10353 return Diagnose(S, A); 10354 break; 10355 } 10356 } 10357 return false; 10358 } 10359 10360 bool Sema::areMultiversionVariantFunctionsCompatible( 10361 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10362 const PartialDiagnostic &NoProtoDiagID, 10363 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10364 const PartialDiagnosticAt &NoSupportDiagIDAt, 10365 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10366 bool ConstexprSupported, bool CLinkageMayDiffer) { 10367 enum DoesntSupport { 10368 FuncTemplates = 0, 10369 VirtFuncs = 1, 10370 DeducedReturn = 2, 10371 Constructors = 3, 10372 Destructors = 4, 10373 DeletedFuncs = 5, 10374 DefaultedFuncs = 6, 10375 ConstexprFuncs = 7, 10376 ConstevalFuncs = 8, 10377 Lambda = 9, 10378 }; 10379 enum Different { 10380 CallingConv = 0, 10381 ReturnType = 1, 10382 ConstexprSpec = 2, 10383 InlineSpec = 3, 10384 Linkage = 4, 10385 LanguageLinkage = 5, 10386 }; 10387 10388 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10389 !OldFD->getType()->getAs<FunctionProtoType>()) { 10390 Diag(OldFD->getLocation(), NoProtoDiagID); 10391 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10392 return true; 10393 } 10394 10395 if (NoProtoDiagID.getDiagID() != 0 && 10396 !NewFD->getType()->getAs<FunctionProtoType>()) 10397 return Diag(NewFD->getLocation(), NoProtoDiagID); 10398 10399 if (!TemplatesSupported && 10400 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10401 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10402 << FuncTemplates; 10403 10404 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10405 if (NewCXXFD->isVirtual()) 10406 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10407 << VirtFuncs; 10408 10409 if (isa<CXXConstructorDecl>(NewCXXFD)) 10410 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10411 << Constructors; 10412 10413 if (isa<CXXDestructorDecl>(NewCXXFD)) 10414 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10415 << Destructors; 10416 } 10417 10418 if (NewFD->isDeleted()) 10419 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10420 << DeletedFuncs; 10421 10422 if (NewFD->isDefaulted()) 10423 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10424 << DefaultedFuncs; 10425 10426 if (!ConstexprSupported && NewFD->isConstexpr()) 10427 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10428 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10429 10430 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10431 const auto *NewType = cast<FunctionType>(NewQType); 10432 QualType NewReturnType = NewType->getReturnType(); 10433 10434 if (NewReturnType->isUndeducedType()) 10435 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10436 << DeducedReturn; 10437 10438 // Ensure the return type is identical. 10439 if (OldFD) { 10440 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10441 const auto *OldType = cast<FunctionType>(OldQType); 10442 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10443 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10444 10445 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10446 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10447 10448 QualType OldReturnType = OldType->getReturnType(); 10449 10450 if (OldReturnType != NewReturnType) 10451 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10452 10453 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10454 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10455 10456 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10457 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10458 10459 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 10460 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10461 10462 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10463 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 10464 10465 if (CheckEquivalentExceptionSpec( 10466 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10467 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10468 return true; 10469 } 10470 return false; 10471 } 10472 10473 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10474 const FunctionDecl *NewFD, 10475 bool CausesMV, 10476 MultiVersionKind MVType) { 10477 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10478 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10479 if (OldFD) 10480 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10481 return true; 10482 } 10483 10484 bool IsCPUSpecificCPUDispatchMVType = 10485 MVType == MultiVersionKind::CPUDispatch || 10486 MVType == MultiVersionKind::CPUSpecific; 10487 10488 if (CausesMV && OldFD && 10489 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10490 return true; 10491 10492 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10493 return true; 10494 10495 // Only allow transition to MultiVersion if it hasn't been used. 10496 if (OldFD && CausesMV && OldFD->isUsed(false)) 10497 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10498 10499 return S.areMultiversionVariantFunctionsCompatible( 10500 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10501 PartialDiagnosticAt(NewFD->getLocation(), 10502 S.PDiag(diag::note_multiversioning_caused_here)), 10503 PartialDiagnosticAt(NewFD->getLocation(), 10504 S.PDiag(diag::err_multiversion_doesnt_support) 10505 << static_cast<unsigned>(MVType)), 10506 PartialDiagnosticAt(NewFD->getLocation(), 10507 S.PDiag(diag::err_multiversion_diff)), 10508 /*TemplatesSupported=*/false, 10509 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10510 /*CLinkageMayDiffer=*/false); 10511 } 10512 10513 /// Check the validity of a multiversion function declaration that is the 10514 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10515 /// 10516 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10517 /// 10518 /// Returns true if there was an error, false otherwise. 10519 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10520 MultiVersionKind MVType, 10521 const TargetAttr *TA) { 10522 assert(MVType != MultiVersionKind::None && 10523 "Function lacks multiversion attribute"); 10524 10525 // Target only causes MV if it is default, otherwise this is a normal 10526 // function. 10527 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10528 return false; 10529 10530 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10531 FD->setInvalidDecl(); 10532 return true; 10533 } 10534 10535 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10536 FD->setInvalidDecl(); 10537 return true; 10538 } 10539 10540 FD->setIsMultiVersion(); 10541 return false; 10542 } 10543 10544 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10545 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10546 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10547 return true; 10548 } 10549 10550 return false; 10551 } 10552 10553 static bool CheckTargetCausesMultiVersioning( 10554 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10555 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10556 LookupResult &Previous) { 10557 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10558 ParsedTargetAttr NewParsed = NewTA->parse(); 10559 // Sort order doesn't matter, it just needs to be consistent. 10560 llvm::sort(NewParsed.Features); 10561 10562 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10563 // to change, this is a simple redeclaration. 10564 if (!NewTA->isDefaultVersion() && 10565 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10566 return false; 10567 10568 // Otherwise, this decl causes MultiVersioning. 10569 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10570 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10571 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10572 NewFD->setInvalidDecl(); 10573 return true; 10574 } 10575 10576 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10577 MultiVersionKind::Target)) { 10578 NewFD->setInvalidDecl(); 10579 return true; 10580 } 10581 10582 if (CheckMultiVersionValue(S, NewFD)) { 10583 NewFD->setInvalidDecl(); 10584 return true; 10585 } 10586 10587 // If this is 'default', permit the forward declaration. 10588 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10589 Redeclaration = true; 10590 OldDecl = OldFD; 10591 OldFD->setIsMultiVersion(); 10592 NewFD->setIsMultiVersion(); 10593 return false; 10594 } 10595 10596 if (CheckMultiVersionValue(S, OldFD)) { 10597 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10598 NewFD->setInvalidDecl(); 10599 return true; 10600 } 10601 10602 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10603 10604 if (OldParsed == NewParsed) { 10605 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10606 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10607 NewFD->setInvalidDecl(); 10608 return true; 10609 } 10610 10611 for (const auto *FD : OldFD->redecls()) { 10612 const auto *CurTA = FD->getAttr<TargetAttr>(); 10613 // We allow forward declarations before ANY multiversioning attributes, but 10614 // nothing after the fact. 10615 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10616 (!CurTA || CurTA->isInherited())) { 10617 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10618 << 0; 10619 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10620 NewFD->setInvalidDecl(); 10621 return true; 10622 } 10623 } 10624 10625 OldFD->setIsMultiVersion(); 10626 NewFD->setIsMultiVersion(); 10627 Redeclaration = false; 10628 MergeTypeWithPrevious = false; 10629 OldDecl = nullptr; 10630 Previous.clear(); 10631 return false; 10632 } 10633 10634 static bool MultiVersionTypesCompatible(MultiVersionKind Old, 10635 MultiVersionKind New) { 10636 if (Old == New || Old == MultiVersionKind::None || 10637 New == MultiVersionKind::None) 10638 return true; 10639 10640 return (Old == MultiVersionKind::CPUDispatch && 10641 New == MultiVersionKind::CPUSpecific) || 10642 (Old == MultiVersionKind::CPUSpecific && 10643 New == MultiVersionKind::CPUDispatch); 10644 } 10645 10646 /// Check the validity of a new function declaration being added to an existing 10647 /// multiversioned declaration collection. 10648 static bool CheckMultiVersionAdditionalDecl( 10649 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10650 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10651 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10652 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, 10653 bool &MergeTypeWithPrevious, LookupResult &Previous) { 10654 10655 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10656 // Disallow mixing of multiversioning types. 10657 if (!MultiVersionTypesCompatible(OldMVType, NewMVType)) { 10658 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10659 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10660 NewFD->setInvalidDecl(); 10661 return true; 10662 } 10663 10664 ParsedTargetAttr NewParsed; 10665 if (NewTA) { 10666 NewParsed = NewTA->parse(); 10667 llvm::sort(NewParsed.Features); 10668 } 10669 10670 bool UseMemberUsingDeclRules = 10671 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10672 10673 // Next, check ALL non-overloads to see if this is a redeclaration of a 10674 // previous member of the MultiVersion set. 10675 for (NamedDecl *ND : Previous) { 10676 FunctionDecl *CurFD = ND->getAsFunction(); 10677 if (!CurFD) 10678 continue; 10679 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10680 continue; 10681 10682 switch (NewMVType) { 10683 case MultiVersionKind::None: 10684 assert(OldMVType == MultiVersionKind::TargetClones && 10685 "Only target_clones can be omitted in subsequent declarations"); 10686 break; 10687 case MultiVersionKind::Target: { 10688 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10689 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10690 NewFD->setIsMultiVersion(); 10691 Redeclaration = true; 10692 OldDecl = ND; 10693 return false; 10694 } 10695 10696 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10697 if (CurParsed == NewParsed) { 10698 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10699 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10700 NewFD->setInvalidDecl(); 10701 return true; 10702 } 10703 break; 10704 } 10705 case MultiVersionKind::TargetClones: { 10706 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>(); 10707 Redeclaration = true; 10708 OldDecl = CurFD; 10709 MergeTypeWithPrevious = true; 10710 NewFD->setIsMultiVersion(); 10711 10712 if (CurClones && NewClones && 10713 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || 10714 !std::equal(CurClones->featuresStrs_begin(), 10715 CurClones->featuresStrs_end(), 10716 NewClones->featuresStrs_begin()))) { 10717 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match); 10718 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10719 NewFD->setInvalidDecl(); 10720 return true; 10721 } 10722 10723 return false; 10724 } 10725 case MultiVersionKind::CPUSpecific: 10726 case MultiVersionKind::CPUDispatch: { 10727 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10728 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10729 // Handle CPUDispatch/CPUSpecific versions. 10730 // Only 1 CPUDispatch function is allowed, this will make it go through 10731 // the redeclaration errors. 10732 if (NewMVType == MultiVersionKind::CPUDispatch && 10733 CurFD->hasAttr<CPUDispatchAttr>()) { 10734 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10735 std::equal( 10736 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10737 NewCPUDisp->cpus_begin(), 10738 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10739 return Cur->getName() == New->getName(); 10740 })) { 10741 NewFD->setIsMultiVersion(); 10742 Redeclaration = true; 10743 OldDecl = ND; 10744 return false; 10745 } 10746 10747 // If the declarations don't match, this is an error condition. 10748 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10749 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10750 NewFD->setInvalidDecl(); 10751 return true; 10752 } 10753 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10754 10755 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10756 std::equal( 10757 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10758 NewCPUSpec->cpus_begin(), 10759 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10760 return Cur->getName() == New->getName(); 10761 })) { 10762 NewFD->setIsMultiVersion(); 10763 Redeclaration = true; 10764 OldDecl = ND; 10765 return false; 10766 } 10767 10768 // Only 1 version of CPUSpecific is allowed for each CPU. 10769 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10770 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10771 if (CurII == NewII) { 10772 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10773 << NewII; 10774 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10775 NewFD->setInvalidDecl(); 10776 return true; 10777 } 10778 } 10779 } 10780 } 10781 break; 10782 } 10783 } 10784 } 10785 10786 // Else, this is simply a non-redecl case. Checking the 'value' is only 10787 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10788 // handled in the attribute adding step. 10789 if (NewMVType == MultiVersionKind::Target && 10790 CheckMultiVersionValue(S, NewFD)) { 10791 NewFD->setInvalidDecl(); 10792 return true; 10793 } 10794 10795 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10796 !OldFD->isMultiVersion(), NewMVType)) { 10797 NewFD->setInvalidDecl(); 10798 return true; 10799 } 10800 10801 // Permit forward declarations in the case where these two are compatible. 10802 if (!OldFD->isMultiVersion()) { 10803 OldFD->setIsMultiVersion(); 10804 NewFD->setIsMultiVersion(); 10805 Redeclaration = true; 10806 OldDecl = OldFD; 10807 return false; 10808 } 10809 10810 NewFD->setIsMultiVersion(); 10811 Redeclaration = false; 10812 MergeTypeWithPrevious = false; 10813 OldDecl = nullptr; 10814 Previous.clear(); 10815 return false; 10816 } 10817 10818 /// Check the validity of a mulitversion function declaration. 10819 /// Also sets the multiversion'ness' of the function itself. 10820 /// 10821 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10822 /// 10823 /// Returns true if there was an error, false otherwise. 10824 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10825 bool &Redeclaration, NamedDecl *&OldDecl, 10826 bool &MergeTypeWithPrevious, 10827 LookupResult &Previous) { 10828 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10829 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10830 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10831 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); 10832 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10833 10834 // Main isn't allowed to become a multiversion function, however it IS 10835 // permitted to have 'main' be marked with the 'target' optimization hint. 10836 if (NewFD->isMain()) { 10837 if (MVType != MultiVersionKind::None && 10838 !(MVType == MultiVersionKind::Target && !NewTA->isDefaultVersion())) { 10839 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10840 NewFD->setInvalidDecl(); 10841 return true; 10842 } 10843 return false; 10844 } 10845 10846 if (!OldDecl || !OldDecl->getAsFunction() || 10847 OldDecl->getDeclContext()->getRedeclContext() != 10848 NewFD->getDeclContext()->getRedeclContext()) { 10849 // If there's no previous declaration, AND this isn't attempting to cause 10850 // multiversioning, this isn't an error condition. 10851 if (MVType == MultiVersionKind::None) 10852 return false; 10853 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10854 } 10855 10856 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10857 10858 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10859 return false; 10860 10861 // Multiversioned redeclarations aren't allowed to omit the attribute, except 10862 // for target_clones. 10863 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None && 10864 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) { 10865 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10866 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10867 NewFD->setInvalidDecl(); 10868 return true; 10869 } 10870 10871 if (!OldFD->isMultiVersion()) { 10872 switch (MVType) { 10873 case MultiVersionKind::Target: 10874 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10875 Redeclaration, OldDecl, 10876 MergeTypeWithPrevious, Previous); 10877 case MultiVersionKind::TargetClones: 10878 if (OldFD->isUsed(false)) { 10879 NewFD->setInvalidDecl(); 10880 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10881 } 10882 OldFD->setIsMultiVersion(); 10883 break; 10884 case MultiVersionKind::CPUDispatch: 10885 case MultiVersionKind::CPUSpecific: 10886 case MultiVersionKind::None: 10887 break; 10888 } 10889 } 10890 // Handle the target potentially causes multiversioning case. 10891 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10892 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10893 Redeclaration, OldDecl, 10894 MergeTypeWithPrevious, Previous); 10895 10896 // At this point, we have a multiversion function decl (in OldFD) AND an 10897 // appropriate attribute in the current function decl. Resolve that these are 10898 // still compatible with previous declarations. 10899 return CheckMultiVersionAdditionalDecl( 10900 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, NewClones, 10901 Redeclaration, OldDecl, MergeTypeWithPrevious, Previous); 10902 } 10903 10904 /// Perform semantic checking of a new function declaration. 10905 /// 10906 /// Performs semantic analysis of the new function declaration 10907 /// NewFD. This routine performs all semantic checking that does not 10908 /// require the actual declarator involved in the declaration, and is 10909 /// used both for the declaration of functions as they are parsed 10910 /// (called via ActOnDeclarator) and for the declaration of functions 10911 /// that have been instantiated via C++ template instantiation (called 10912 /// via InstantiateDecl). 10913 /// 10914 /// \param IsMemberSpecialization whether this new function declaration is 10915 /// a member specialization (that replaces any definition provided by the 10916 /// previous declaration). 10917 /// 10918 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10919 /// 10920 /// \returns true if the function declaration is a redeclaration. 10921 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10922 LookupResult &Previous, 10923 bool IsMemberSpecialization) { 10924 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10925 "Variably modified return types are not handled here"); 10926 10927 // Determine whether the type of this function should be merged with 10928 // a previous visible declaration. This never happens for functions in C++, 10929 // and always happens in C if the previous declaration was visible. 10930 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10931 !Previous.isShadowed(); 10932 10933 bool Redeclaration = false; 10934 NamedDecl *OldDecl = nullptr; 10935 bool MayNeedOverloadableChecks = false; 10936 10937 // Merge or overload the declaration with an existing declaration of 10938 // the same name, if appropriate. 10939 if (!Previous.empty()) { 10940 // Determine whether NewFD is an overload of PrevDecl or 10941 // a declaration that requires merging. If it's an overload, 10942 // there's no more work to do here; we'll just add the new 10943 // function to the scope. 10944 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10945 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10946 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10947 Redeclaration = true; 10948 OldDecl = Candidate; 10949 } 10950 } else { 10951 MayNeedOverloadableChecks = true; 10952 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10953 /*NewIsUsingDecl*/ false)) { 10954 case Ovl_Match: 10955 Redeclaration = true; 10956 break; 10957 10958 case Ovl_NonFunction: 10959 Redeclaration = true; 10960 break; 10961 10962 case Ovl_Overload: 10963 Redeclaration = false; 10964 break; 10965 } 10966 } 10967 } 10968 10969 // Check for a previous extern "C" declaration with this name. 10970 if (!Redeclaration && 10971 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10972 if (!Previous.empty()) { 10973 // This is an extern "C" declaration with the same name as a previous 10974 // declaration, and thus redeclares that entity... 10975 Redeclaration = true; 10976 OldDecl = Previous.getFoundDecl(); 10977 MergeTypeWithPrevious = false; 10978 10979 // ... except in the presence of __attribute__((overloadable)). 10980 if (OldDecl->hasAttr<OverloadableAttr>() || 10981 NewFD->hasAttr<OverloadableAttr>()) { 10982 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10983 MayNeedOverloadableChecks = true; 10984 Redeclaration = false; 10985 OldDecl = nullptr; 10986 } 10987 } 10988 } 10989 } 10990 10991 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10992 MergeTypeWithPrevious, Previous)) 10993 return Redeclaration; 10994 10995 // PPC MMA non-pointer types are not allowed as function return types. 10996 if (Context.getTargetInfo().getTriple().isPPC64() && 10997 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10998 NewFD->setInvalidDecl(); 10999 } 11000 11001 // C++11 [dcl.constexpr]p8: 11002 // A constexpr specifier for a non-static member function that is not 11003 // a constructor declares that member function to be const. 11004 // 11005 // This needs to be delayed until we know whether this is an out-of-line 11006 // definition of a static member function. 11007 // 11008 // This rule is not present in C++1y, so we produce a backwards 11009 // compatibility warning whenever it happens in C++11. 11010 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 11011 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 11012 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 11013 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 11014 CXXMethodDecl *OldMD = nullptr; 11015 if (OldDecl) 11016 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 11017 if (!OldMD || !OldMD->isStatic()) { 11018 const FunctionProtoType *FPT = 11019 MD->getType()->castAs<FunctionProtoType>(); 11020 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11021 EPI.TypeQuals.addConst(); 11022 MD->setType(Context.getFunctionType(FPT->getReturnType(), 11023 FPT->getParamTypes(), EPI)); 11024 11025 // Warn that we did this, if we're not performing template instantiation. 11026 // In that case, we'll have warned already when the template was defined. 11027 if (!inTemplateInstantiation()) { 11028 SourceLocation AddConstLoc; 11029 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 11030 .IgnoreParens().getAs<FunctionTypeLoc>()) 11031 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 11032 11033 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 11034 << FixItHint::CreateInsertion(AddConstLoc, " const"); 11035 } 11036 } 11037 } 11038 11039 if (Redeclaration) { 11040 // NewFD and OldDecl represent declarations that need to be 11041 // merged. 11042 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 11043 NewFD->setInvalidDecl(); 11044 return Redeclaration; 11045 } 11046 11047 Previous.clear(); 11048 Previous.addDecl(OldDecl); 11049 11050 if (FunctionTemplateDecl *OldTemplateDecl = 11051 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 11052 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 11053 FunctionTemplateDecl *NewTemplateDecl 11054 = NewFD->getDescribedFunctionTemplate(); 11055 assert(NewTemplateDecl && "Template/non-template mismatch"); 11056 11057 // The call to MergeFunctionDecl above may have created some state in 11058 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 11059 // can add it as a redeclaration. 11060 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 11061 11062 NewFD->setPreviousDeclaration(OldFD); 11063 if (NewFD->isCXXClassMember()) { 11064 NewFD->setAccess(OldTemplateDecl->getAccess()); 11065 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 11066 } 11067 11068 // If this is an explicit specialization of a member that is a function 11069 // template, mark it as a member specialization. 11070 if (IsMemberSpecialization && 11071 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 11072 NewTemplateDecl->setMemberSpecialization(); 11073 assert(OldTemplateDecl->isMemberSpecialization()); 11074 // Explicit specializations of a member template do not inherit deleted 11075 // status from the parent member template that they are specializing. 11076 if (OldFD->isDeleted()) { 11077 // FIXME: This assert will not hold in the presence of modules. 11078 assert(OldFD->getCanonicalDecl() == OldFD); 11079 // FIXME: We need an update record for this AST mutation. 11080 OldFD->setDeletedAsWritten(false); 11081 } 11082 } 11083 11084 } else { 11085 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 11086 auto *OldFD = cast<FunctionDecl>(OldDecl); 11087 // This needs to happen first so that 'inline' propagates. 11088 NewFD->setPreviousDeclaration(OldFD); 11089 if (NewFD->isCXXClassMember()) 11090 NewFD->setAccess(OldFD->getAccess()); 11091 } 11092 } 11093 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 11094 !NewFD->getAttr<OverloadableAttr>()) { 11095 assert((Previous.empty() || 11096 llvm::any_of(Previous, 11097 [](const NamedDecl *ND) { 11098 return ND->hasAttr<OverloadableAttr>(); 11099 })) && 11100 "Non-redecls shouldn't happen without overloadable present"); 11101 11102 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 11103 const auto *FD = dyn_cast<FunctionDecl>(ND); 11104 return FD && !FD->hasAttr<OverloadableAttr>(); 11105 }); 11106 11107 if (OtherUnmarkedIter != Previous.end()) { 11108 Diag(NewFD->getLocation(), 11109 diag::err_attribute_overloadable_multiple_unmarked_overloads); 11110 Diag((*OtherUnmarkedIter)->getLocation(), 11111 diag::note_attribute_overloadable_prev_overload) 11112 << false; 11113 11114 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 11115 } 11116 } 11117 11118 if (LangOpts.OpenMP) 11119 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 11120 11121 // Semantic checking for this function declaration (in isolation). 11122 11123 if (getLangOpts().CPlusPlus) { 11124 // C++-specific checks. 11125 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 11126 CheckConstructor(Constructor); 11127 } else if (CXXDestructorDecl *Destructor = 11128 dyn_cast<CXXDestructorDecl>(NewFD)) { 11129 CXXRecordDecl *Record = Destructor->getParent(); 11130 QualType ClassType = Context.getTypeDeclType(Record); 11131 11132 // FIXME: Shouldn't we be able to perform this check even when the class 11133 // type is dependent? Both gcc and edg can handle that. 11134 if (!ClassType->isDependentType()) { 11135 DeclarationName Name 11136 = Context.DeclarationNames.getCXXDestructorName( 11137 Context.getCanonicalType(ClassType)); 11138 if (NewFD->getDeclName() != Name) { 11139 Diag(NewFD->getLocation(), diag::err_destructor_name); 11140 NewFD->setInvalidDecl(); 11141 return Redeclaration; 11142 } 11143 } 11144 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 11145 if (auto *TD = Guide->getDescribedFunctionTemplate()) 11146 CheckDeductionGuideTemplate(TD); 11147 11148 // A deduction guide is not on the list of entities that can be 11149 // explicitly specialized. 11150 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 11151 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 11152 << /*explicit specialization*/ 1; 11153 } 11154 11155 // Find any virtual functions that this function overrides. 11156 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 11157 if (!Method->isFunctionTemplateSpecialization() && 11158 !Method->getDescribedFunctionTemplate() && 11159 Method->isCanonicalDecl()) { 11160 AddOverriddenMethods(Method->getParent(), Method); 11161 } 11162 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 11163 // C++2a [class.virtual]p6 11164 // A virtual method shall not have a requires-clause. 11165 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 11166 diag::err_constrained_virtual_method); 11167 11168 if (Method->isStatic()) 11169 checkThisInStaticMemberFunctionType(Method); 11170 } 11171 11172 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 11173 ActOnConversionDeclarator(Conversion); 11174 11175 // Extra checking for C++ overloaded operators (C++ [over.oper]). 11176 if (NewFD->isOverloadedOperator() && 11177 CheckOverloadedOperatorDeclaration(NewFD)) { 11178 NewFD->setInvalidDecl(); 11179 return Redeclaration; 11180 } 11181 11182 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11183 if (NewFD->getLiteralIdentifier() && 11184 CheckLiteralOperatorDeclaration(NewFD)) { 11185 NewFD->setInvalidDecl(); 11186 return Redeclaration; 11187 } 11188 11189 // In C++, check default arguments now that we have merged decls. Unless 11190 // the lexical context is the class, because in this case this is done 11191 // during delayed parsing anyway. 11192 if (!CurContext->isRecord()) 11193 CheckCXXDefaultArguments(NewFD); 11194 11195 // If this function is declared as being extern "C", then check to see if 11196 // the function returns a UDT (class, struct, or union type) that is not C 11197 // compatible, and if it does, warn the user. 11198 // But, issue any diagnostic on the first declaration only. 11199 if (Previous.empty() && NewFD->isExternC()) { 11200 QualType R = NewFD->getReturnType(); 11201 if (R->isIncompleteType() && !R->isVoidType()) 11202 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11203 << NewFD << R; 11204 else if (!R.isPODType(Context) && !R->isVoidType() && 11205 !R->isObjCObjectPointerType()) 11206 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11207 } 11208 11209 // C++1z [dcl.fct]p6: 11210 // [...] whether the function has a non-throwing exception-specification 11211 // [is] part of the function type 11212 // 11213 // This results in an ABI break between C++14 and C++17 for functions whose 11214 // declared type includes an exception-specification in a parameter or 11215 // return type. (Exception specifications on the function itself are OK in 11216 // most cases, and exception specifications are not permitted in most other 11217 // contexts where they could make it into a mangling.) 11218 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11219 auto HasNoexcept = [&](QualType T) -> bool { 11220 // Strip off declarator chunks that could be between us and a function 11221 // type. We don't need to look far, exception specifications are very 11222 // restricted prior to C++17. 11223 if (auto *RT = T->getAs<ReferenceType>()) 11224 T = RT->getPointeeType(); 11225 else if (T->isAnyPointerType()) 11226 T = T->getPointeeType(); 11227 else if (auto *MPT = T->getAs<MemberPointerType>()) 11228 T = MPT->getPointeeType(); 11229 if (auto *FPT = T->getAs<FunctionProtoType>()) 11230 if (FPT->isNothrow()) 11231 return true; 11232 return false; 11233 }; 11234 11235 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11236 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11237 for (QualType T : FPT->param_types()) 11238 AnyNoexcept |= HasNoexcept(T); 11239 if (AnyNoexcept) 11240 Diag(NewFD->getLocation(), 11241 diag::warn_cxx17_compat_exception_spec_in_signature) 11242 << NewFD; 11243 } 11244 11245 if (!Redeclaration && LangOpts.CUDA) 11246 checkCUDATargetOverload(NewFD, Previous); 11247 } 11248 return Redeclaration; 11249 } 11250 11251 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11252 // C++11 [basic.start.main]p3: 11253 // A program that [...] declares main to be inline, static or 11254 // constexpr is ill-formed. 11255 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11256 // appear in a declaration of main. 11257 // static main is not an error under C99, but we should warn about it. 11258 // We accept _Noreturn main as an extension. 11259 if (FD->getStorageClass() == SC_Static) 11260 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11261 ? diag::err_static_main : diag::warn_static_main) 11262 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11263 if (FD->isInlineSpecified()) 11264 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11265 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11266 if (DS.isNoreturnSpecified()) { 11267 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11268 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11269 Diag(NoreturnLoc, diag::ext_noreturn_main); 11270 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11271 << FixItHint::CreateRemoval(NoreturnRange); 11272 } 11273 if (FD->isConstexpr()) { 11274 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11275 << FD->isConsteval() 11276 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11277 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11278 } 11279 11280 if (getLangOpts().OpenCL) { 11281 Diag(FD->getLocation(), diag::err_opencl_no_main) 11282 << FD->hasAttr<OpenCLKernelAttr>(); 11283 FD->setInvalidDecl(); 11284 return; 11285 } 11286 11287 QualType T = FD->getType(); 11288 assert(T->isFunctionType() && "function decl is not of function type"); 11289 const FunctionType* FT = T->castAs<FunctionType>(); 11290 11291 // Set default calling convention for main() 11292 if (FT->getCallConv() != CC_C) { 11293 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11294 FD->setType(QualType(FT, 0)); 11295 T = Context.getCanonicalType(FD->getType()); 11296 } 11297 11298 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11299 // In C with GNU extensions we allow main() to have non-integer return 11300 // type, but we should warn about the extension, and we disable the 11301 // implicit-return-zero rule. 11302 11303 // GCC in C mode accepts qualified 'int'. 11304 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11305 FD->setHasImplicitReturnZero(true); 11306 else { 11307 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11308 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11309 if (RTRange.isValid()) 11310 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11311 << FixItHint::CreateReplacement(RTRange, "int"); 11312 } 11313 } else { 11314 // In C and C++, main magically returns 0 if you fall off the end; 11315 // set the flag which tells us that. 11316 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11317 11318 // All the standards say that main() should return 'int'. 11319 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11320 FD->setHasImplicitReturnZero(true); 11321 else { 11322 // Otherwise, this is just a flat-out error. 11323 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11324 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11325 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11326 : FixItHint()); 11327 FD->setInvalidDecl(true); 11328 } 11329 } 11330 11331 // Treat protoless main() as nullary. 11332 if (isa<FunctionNoProtoType>(FT)) return; 11333 11334 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11335 unsigned nparams = FTP->getNumParams(); 11336 assert(FD->getNumParams() == nparams); 11337 11338 bool HasExtraParameters = (nparams > 3); 11339 11340 if (FTP->isVariadic()) { 11341 Diag(FD->getLocation(), diag::ext_variadic_main); 11342 // FIXME: if we had information about the location of the ellipsis, we 11343 // could add a FixIt hint to remove it as a parameter. 11344 } 11345 11346 // Darwin passes an undocumented fourth argument of type char**. If 11347 // other platforms start sprouting these, the logic below will start 11348 // getting shifty. 11349 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11350 HasExtraParameters = false; 11351 11352 if (HasExtraParameters) { 11353 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11354 FD->setInvalidDecl(true); 11355 nparams = 3; 11356 } 11357 11358 // FIXME: a lot of the following diagnostics would be improved 11359 // if we had some location information about types. 11360 11361 QualType CharPP = 11362 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11363 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11364 11365 for (unsigned i = 0; i < nparams; ++i) { 11366 QualType AT = FTP->getParamType(i); 11367 11368 bool mismatch = true; 11369 11370 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11371 mismatch = false; 11372 else if (Expected[i] == CharPP) { 11373 // As an extension, the following forms are okay: 11374 // char const ** 11375 // char const * const * 11376 // char * const * 11377 11378 QualifierCollector qs; 11379 const PointerType* PT; 11380 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11381 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11382 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11383 Context.CharTy)) { 11384 qs.removeConst(); 11385 mismatch = !qs.empty(); 11386 } 11387 } 11388 11389 if (mismatch) { 11390 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11391 // TODO: suggest replacing given type with expected type 11392 FD->setInvalidDecl(true); 11393 } 11394 } 11395 11396 if (nparams == 1 && !FD->isInvalidDecl()) { 11397 Diag(FD->getLocation(), diag::warn_main_one_arg); 11398 } 11399 11400 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11401 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11402 FD->setInvalidDecl(); 11403 } 11404 } 11405 11406 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11407 11408 // Default calling convention for main and wmain is __cdecl 11409 if (FD->getName() == "main" || FD->getName() == "wmain") 11410 return false; 11411 11412 // Default calling convention for MinGW is __cdecl 11413 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11414 if (T.isWindowsGNUEnvironment()) 11415 return false; 11416 11417 // Default calling convention for WinMain, wWinMain and DllMain 11418 // is __stdcall on 32 bit Windows 11419 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11420 return true; 11421 11422 return false; 11423 } 11424 11425 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11426 QualType T = FD->getType(); 11427 assert(T->isFunctionType() && "function decl is not of function type"); 11428 const FunctionType *FT = T->castAs<FunctionType>(); 11429 11430 // Set an implicit return of 'zero' if the function can return some integral, 11431 // enumeration, pointer or nullptr type. 11432 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11433 FT->getReturnType()->isAnyPointerType() || 11434 FT->getReturnType()->isNullPtrType()) 11435 // DllMain is exempt because a return value of zero means it failed. 11436 if (FD->getName() != "DllMain") 11437 FD->setHasImplicitReturnZero(true); 11438 11439 // Explicity specified calling conventions are applied to MSVC entry points 11440 if (!hasExplicitCallingConv(T)) { 11441 if (isDefaultStdCall(FD, *this)) { 11442 if (FT->getCallConv() != CC_X86StdCall) { 11443 FT = Context.adjustFunctionType( 11444 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11445 FD->setType(QualType(FT, 0)); 11446 } 11447 } else if (FT->getCallConv() != CC_C) { 11448 FT = Context.adjustFunctionType(FT, 11449 FT->getExtInfo().withCallingConv(CC_C)); 11450 FD->setType(QualType(FT, 0)); 11451 } 11452 } 11453 11454 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11455 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11456 FD->setInvalidDecl(); 11457 } 11458 } 11459 11460 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11461 // FIXME: Need strict checking. In C89, we need to check for 11462 // any assignment, increment, decrement, function-calls, or 11463 // commas outside of a sizeof. In C99, it's the same list, 11464 // except that the aforementioned are allowed in unevaluated 11465 // expressions. Everything else falls under the 11466 // "may accept other forms of constant expressions" exception. 11467 // 11468 // Regular C++ code will not end up here (exceptions: language extensions, 11469 // OpenCL C++ etc), so the constant expression rules there don't matter. 11470 if (Init->isValueDependent()) { 11471 assert(Init->containsErrors() && 11472 "Dependent code should only occur in error-recovery path."); 11473 return true; 11474 } 11475 const Expr *Culprit; 11476 if (Init->isConstantInitializer(Context, false, &Culprit)) 11477 return false; 11478 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11479 << Culprit->getSourceRange(); 11480 return true; 11481 } 11482 11483 namespace { 11484 // Visits an initialization expression to see if OrigDecl is evaluated in 11485 // its own initialization and throws a warning if it does. 11486 class SelfReferenceChecker 11487 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11488 Sema &S; 11489 Decl *OrigDecl; 11490 bool isRecordType; 11491 bool isPODType; 11492 bool isReferenceType; 11493 11494 bool isInitList; 11495 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11496 11497 public: 11498 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11499 11500 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11501 S(S), OrigDecl(OrigDecl) { 11502 isPODType = false; 11503 isRecordType = false; 11504 isReferenceType = false; 11505 isInitList = false; 11506 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11507 isPODType = VD->getType().isPODType(S.Context); 11508 isRecordType = VD->getType()->isRecordType(); 11509 isReferenceType = VD->getType()->isReferenceType(); 11510 } 11511 } 11512 11513 // For most expressions, just call the visitor. For initializer lists, 11514 // track the index of the field being initialized since fields are 11515 // initialized in order allowing use of previously initialized fields. 11516 void CheckExpr(Expr *E) { 11517 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11518 if (!InitList) { 11519 Visit(E); 11520 return; 11521 } 11522 11523 // Track and increment the index here. 11524 isInitList = true; 11525 InitFieldIndex.push_back(0); 11526 for (auto Child : InitList->children()) { 11527 CheckExpr(cast<Expr>(Child)); 11528 ++InitFieldIndex.back(); 11529 } 11530 InitFieldIndex.pop_back(); 11531 } 11532 11533 // Returns true if MemberExpr is checked and no further checking is needed. 11534 // Returns false if additional checking is required. 11535 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11536 llvm::SmallVector<FieldDecl*, 4> Fields; 11537 Expr *Base = E; 11538 bool ReferenceField = false; 11539 11540 // Get the field members used. 11541 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11542 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11543 if (!FD) 11544 return false; 11545 Fields.push_back(FD); 11546 if (FD->getType()->isReferenceType()) 11547 ReferenceField = true; 11548 Base = ME->getBase()->IgnoreParenImpCasts(); 11549 } 11550 11551 // Keep checking only if the base Decl is the same. 11552 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11553 if (!DRE || DRE->getDecl() != OrigDecl) 11554 return false; 11555 11556 // A reference field can be bound to an unininitialized field. 11557 if (CheckReference && !ReferenceField) 11558 return true; 11559 11560 // Convert FieldDecls to their index number. 11561 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11562 for (const FieldDecl *I : llvm::reverse(Fields)) 11563 UsedFieldIndex.push_back(I->getFieldIndex()); 11564 11565 // See if a warning is needed by checking the first difference in index 11566 // numbers. If field being used has index less than the field being 11567 // initialized, then the use is safe. 11568 for (auto UsedIter = UsedFieldIndex.begin(), 11569 UsedEnd = UsedFieldIndex.end(), 11570 OrigIter = InitFieldIndex.begin(), 11571 OrigEnd = InitFieldIndex.end(); 11572 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11573 if (*UsedIter < *OrigIter) 11574 return true; 11575 if (*UsedIter > *OrigIter) 11576 break; 11577 } 11578 11579 // TODO: Add a different warning which will print the field names. 11580 HandleDeclRefExpr(DRE); 11581 return true; 11582 } 11583 11584 // For most expressions, the cast is directly above the DeclRefExpr. 11585 // For conditional operators, the cast can be outside the conditional 11586 // operator if both expressions are DeclRefExpr's. 11587 void HandleValue(Expr *E) { 11588 E = E->IgnoreParens(); 11589 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11590 HandleDeclRefExpr(DRE); 11591 return; 11592 } 11593 11594 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11595 Visit(CO->getCond()); 11596 HandleValue(CO->getTrueExpr()); 11597 HandleValue(CO->getFalseExpr()); 11598 return; 11599 } 11600 11601 if (BinaryConditionalOperator *BCO = 11602 dyn_cast<BinaryConditionalOperator>(E)) { 11603 Visit(BCO->getCond()); 11604 HandleValue(BCO->getFalseExpr()); 11605 return; 11606 } 11607 11608 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11609 HandleValue(OVE->getSourceExpr()); 11610 return; 11611 } 11612 11613 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11614 if (BO->getOpcode() == BO_Comma) { 11615 Visit(BO->getLHS()); 11616 HandleValue(BO->getRHS()); 11617 return; 11618 } 11619 } 11620 11621 if (isa<MemberExpr>(E)) { 11622 if (isInitList) { 11623 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11624 false /*CheckReference*/)) 11625 return; 11626 } 11627 11628 Expr *Base = E->IgnoreParenImpCasts(); 11629 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11630 // Check for static member variables and don't warn on them. 11631 if (!isa<FieldDecl>(ME->getMemberDecl())) 11632 return; 11633 Base = ME->getBase()->IgnoreParenImpCasts(); 11634 } 11635 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11636 HandleDeclRefExpr(DRE); 11637 return; 11638 } 11639 11640 Visit(E); 11641 } 11642 11643 // Reference types not handled in HandleValue are handled here since all 11644 // uses of references are bad, not just r-value uses. 11645 void VisitDeclRefExpr(DeclRefExpr *E) { 11646 if (isReferenceType) 11647 HandleDeclRefExpr(E); 11648 } 11649 11650 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11651 if (E->getCastKind() == CK_LValueToRValue) { 11652 HandleValue(E->getSubExpr()); 11653 return; 11654 } 11655 11656 Inherited::VisitImplicitCastExpr(E); 11657 } 11658 11659 void VisitMemberExpr(MemberExpr *E) { 11660 if (isInitList) { 11661 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11662 return; 11663 } 11664 11665 // Don't warn on arrays since they can be treated as pointers. 11666 if (E->getType()->canDecayToPointerType()) return; 11667 11668 // Warn when a non-static method call is followed by non-static member 11669 // field accesses, which is followed by a DeclRefExpr. 11670 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11671 bool Warn = (MD && !MD->isStatic()); 11672 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11673 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11674 if (!isa<FieldDecl>(ME->getMemberDecl())) 11675 Warn = false; 11676 Base = ME->getBase()->IgnoreParenImpCasts(); 11677 } 11678 11679 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11680 if (Warn) 11681 HandleDeclRefExpr(DRE); 11682 return; 11683 } 11684 11685 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11686 // Visit that expression. 11687 Visit(Base); 11688 } 11689 11690 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11691 Expr *Callee = E->getCallee(); 11692 11693 if (isa<UnresolvedLookupExpr>(Callee)) 11694 return Inherited::VisitCXXOperatorCallExpr(E); 11695 11696 Visit(Callee); 11697 for (auto Arg: E->arguments()) 11698 HandleValue(Arg->IgnoreParenImpCasts()); 11699 } 11700 11701 void VisitUnaryOperator(UnaryOperator *E) { 11702 // For POD record types, addresses of its own members are well-defined. 11703 if (E->getOpcode() == UO_AddrOf && isRecordType && 11704 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11705 if (!isPODType) 11706 HandleValue(E->getSubExpr()); 11707 return; 11708 } 11709 11710 if (E->isIncrementDecrementOp()) { 11711 HandleValue(E->getSubExpr()); 11712 return; 11713 } 11714 11715 Inherited::VisitUnaryOperator(E); 11716 } 11717 11718 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11719 11720 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11721 if (E->getConstructor()->isCopyConstructor()) { 11722 Expr *ArgExpr = E->getArg(0); 11723 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11724 if (ILE->getNumInits() == 1) 11725 ArgExpr = ILE->getInit(0); 11726 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11727 if (ICE->getCastKind() == CK_NoOp) 11728 ArgExpr = ICE->getSubExpr(); 11729 HandleValue(ArgExpr); 11730 return; 11731 } 11732 Inherited::VisitCXXConstructExpr(E); 11733 } 11734 11735 void VisitCallExpr(CallExpr *E) { 11736 // Treat std::move as a use. 11737 if (E->isCallToStdMove()) { 11738 HandleValue(E->getArg(0)); 11739 return; 11740 } 11741 11742 Inherited::VisitCallExpr(E); 11743 } 11744 11745 void VisitBinaryOperator(BinaryOperator *E) { 11746 if (E->isCompoundAssignmentOp()) { 11747 HandleValue(E->getLHS()); 11748 Visit(E->getRHS()); 11749 return; 11750 } 11751 11752 Inherited::VisitBinaryOperator(E); 11753 } 11754 11755 // A custom visitor for BinaryConditionalOperator is needed because the 11756 // regular visitor would check the condition and true expression separately 11757 // but both point to the same place giving duplicate diagnostics. 11758 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11759 Visit(E->getCond()); 11760 Visit(E->getFalseExpr()); 11761 } 11762 11763 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11764 Decl* ReferenceDecl = DRE->getDecl(); 11765 if (OrigDecl != ReferenceDecl) return; 11766 unsigned diag; 11767 if (isReferenceType) { 11768 diag = diag::warn_uninit_self_reference_in_reference_init; 11769 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11770 diag = diag::warn_static_self_reference_in_init; 11771 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11772 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11773 DRE->getDecl()->getType()->isRecordType()) { 11774 diag = diag::warn_uninit_self_reference_in_init; 11775 } else { 11776 // Local variables will be handled by the CFG analysis. 11777 return; 11778 } 11779 11780 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11781 S.PDiag(diag) 11782 << DRE->getDecl() << OrigDecl->getLocation() 11783 << DRE->getSourceRange()); 11784 } 11785 }; 11786 11787 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11788 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11789 bool DirectInit) { 11790 // Parameters arguments are occassionially constructed with itself, 11791 // for instance, in recursive functions. Skip them. 11792 if (isa<ParmVarDecl>(OrigDecl)) 11793 return; 11794 11795 E = E->IgnoreParens(); 11796 11797 // Skip checking T a = a where T is not a record or reference type. 11798 // Doing so is a way to silence uninitialized warnings. 11799 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11800 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11801 if (ICE->getCastKind() == CK_LValueToRValue) 11802 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11803 if (DRE->getDecl() == OrigDecl) 11804 return; 11805 11806 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11807 } 11808 } // end anonymous namespace 11809 11810 namespace { 11811 // Simple wrapper to add the name of a variable or (if no variable is 11812 // available) a DeclarationName into a diagnostic. 11813 struct VarDeclOrName { 11814 VarDecl *VDecl; 11815 DeclarationName Name; 11816 11817 friend const Sema::SemaDiagnosticBuilder & 11818 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11819 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11820 } 11821 }; 11822 } // end anonymous namespace 11823 11824 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11825 DeclarationName Name, QualType Type, 11826 TypeSourceInfo *TSI, 11827 SourceRange Range, bool DirectInit, 11828 Expr *Init) { 11829 bool IsInitCapture = !VDecl; 11830 assert((!VDecl || !VDecl->isInitCapture()) && 11831 "init captures are expected to be deduced prior to initialization"); 11832 11833 VarDeclOrName VN{VDecl, Name}; 11834 11835 DeducedType *Deduced = Type->getContainedDeducedType(); 11836 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11837 11838 // C++11 [dcl.spec.auto]p3 11839 if (!Init) { 11840 assert(VDecl && "no init for init capture deduction?"); 11841 11842 // Except for class argument deduction, and then for an initializing 11843 // declaration only, i.e. no static at class scope or extern. 11844 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11845 VDecl->hasExternalStorage() || 11846 VDecl->isStaticDataMember()) { 11847 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11848 << VDecl->getDeclName() << Type; 11849 return QualType(); 11850 } 11851 } 11852 11853 ArrayRef<Expr*> DeduceInits; 11854 if (Init) 11855 DeduceInits = Init; 11856 11857 if (DirectInit) { 11858 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11859 DeduceInits = PL->exprs(); 11860 } 11861 11862 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11863 assert(VDecl && "non-auto type for init capture deduction?"); 11864 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11865 InitializationKind Kind = InitializationKind::CreateForInit( 11866 VDecl->getLocation(), DirectInit, Init); 11867 // FIXME: Initialization should not be taking a mutable list of inits. 11868 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11869 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11870 InitsCopy); 11871 } 11872 11873 if (DirectInit) { 11874 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11875 DeduceInits = IL->inits(); 11876 } 11877 11878 // Deduction only works if we have exactly one source expression. 11879 if (DeduceInits.empty()) { 11880 // It isn't possible to write this directly, but it is possible to 11881 // end up in this situation with "auto x(some_pack...);" 11882 Diag(Init->getBeginLoc(), IsInitCapture 11883 ? diag::err_init_capture_no_expression 11884 : diag::err_auto_var_init_no_expression) 11885 << VN << Type << Range; 11886 return QualType(); 11887 } 11888 11889 if (DeduceInits.size() > 1) { 11890 Diag(DeduceInits[1]->getBeginLoc(), 11891 IsInitCapture ? diag::err_init_capture_multiple_expressions 11892 : diag::err_auto_var_init_multiple_expressions) 11893 << VN << Type << Range; 11894 return QualType(); 11895 } 11896 11897 Expr *DeduceInit = DeduceInits[0]; 11898 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11899 Diag(Init->getBeginLoc(), IsInitCapture 11900 ? diag::err_init_capture_paren_braces 11901 : diag::err_auto_var_init_paren_braces) 11902 << isa<InitListExpr>(Init) << VN << Type << Range; 11903 return QualType(); 11904 } 11905 11906 // Expressions default to 'id' when we're in a debugger. 11907 bool DefaultedAnyToId = false; 11908 if (getLangOpts().DebuggerCastResultToId && 11909 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11910 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11911 if (Result.isInvalid()) { 11912 return QualType(); 11913 } 11914 Init = Result.get(); 11915 DefaultedAnyToId = true; 11916 } 11917 11918 // C++ [dcl.decomp]p1: 11919 // If the assignment-expression [...] has array type A and no ref-qualifier 11920 // is present, e has type cv A 11921 if (VDecl && isa<DecompositionDecl>(VDecl) && 11922 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11923 DeduceInit->getType()->isConstantArrayType()) 11924 return Context.getQualifiedType(DeduceInit->getType(), 11925 Type.getQualifiers()); 11926 11927 QualType DeducedType; 11928 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11929 if (!IsInitCapture) 11930 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11931 else if (isa<InitListExpr>(Init)) 11932 Diag(Range.getBegin(), 11933 diag::err_init_capture_deduction_failure_from_init_list) 11934 << VN 11935 << (DeduceInit->getType().isNull() ? TSI->getType() 11936 : DeduceInit->getType()) 11937 << DeduceInit->getSourceRange(); 11938 else 11939 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11940 << VN << TSI->getType() 11941 << (DeduceInit->getType().isNull() ? TSI->getType() 11942 : DeduceInit->getType()) 11943 << DeduceInit->getSourceRange(); 11944 } 11945 11946 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11947 // 'id' instead of a specific object type prevents most of our usual 11948 // checks. 11949 // We only want to warn outside of template instantiations, though: 11950 // inside a template, the 'id' could have come from a parameter. 11951 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11952 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11953 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11954 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11955 } 11956 11957 return DeducedType; 11958 } 11959 11960 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11961 Expr *Init) { 11962 assert(!Init || !Init->containsErrors()); 11963 QualType DeducedType = deduceVarTypeFromInitializer( 11964 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11965 VDecl->getSourceRange(), DirectInit, Init); 11966 if (DeducedType.isNull()) { 11967 VDecl->setInvalidDecl(); 11968 return true; 11969 } 11970 11971 VDecl->setType(DeducedType); 11972 assert(VDecl->isLinkageValid()); 11973 11974 // In ARC, infer lifetime. 11975 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11976 VDecl->setInvalidDecl(); 11977 11978 if (getLangOpts().OpenCL) 11979 deduceOpenCLAddressSpace(VDecl); 11980 11981 // If this is a redeclaration, check that the type we just deduced matches 11982 // the previously declared type. 11983 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11984 // We never need to merge the type, because we cannot form an incomplete 11985 // array of auto, nor deduce such a type. 11986 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11987 } 11988 11989 // Check the deduced type is valid for a variable declaration. 11990 CheckVariableDeclarationType(VDecl); 11991 return VDecl->isInvalidDecl(); 11992 } 11993 11994 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11995 SourceLocation Loc) { 11996 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11997 Init = EWC->getSubExpr(); 11998 11999 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 12000 Init = CE->getSubExpr(); 12001 12002 QualType InitType = Init->getType(); 12003 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12004 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 12005 "shouldn't be called if type doesn't have a non-trivial C struct"); 12006 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 12007 for (auto I : ILE->inits()) { 12008 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 12009 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12010 continue; 12011 SourceLocation SL = I->getExprLoc(); 12012 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 12013 } 12014 return; 12015 } 12016 12017 if (isa<ImplicitValueInitExpr>(Init)) { 12018 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12019 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 12020 NTCUK_Init); 12021 } else { 12022 // Assume all other explicit initializers involving copying some existing 12023 // object. 12024 // TODO: ignore any explicit initializers where we can guarantee 12025 // copy-elision. 12026 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 12027 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 12028 } 12029 } 12030 12031 namespace { 12032 12033 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 12034 // Ignore unavailable fields. A field can be marked as unavailable explicitly 12035 // in the source code or implicitly by the compiler if it is in a union 12036 // defined in a system header and has non-trivial ObjC ownership 12037 // qualifications. We don't want those fields to participate in determining 12038 // whether the containing union is non-trivial. 12039 return FD->hasAttr<UnavailableAttr>(); 12040 } 12041 12042 struct DiagNonTrivalCUnionDefaultInitializeVisitor 12043 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12044 void> { 12045 using Super = 12046 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12047 void>; 12048 12049 DiagNonTrivalCUnionDefaultInitializeVisitor( 12050 QualType OrigTy, SourceLocation OrigLoc, 12051 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12052 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12053 12054 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 12055 const FieldDecl *FD, bool InNonTrivialUnion) { 12056 if (const auto *AT = S.Context.getAsArrayType(QT)) 12057 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12058 InNonTrivialUnion); 12059 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 12060 } 12061 12062 void visitARCStrong(QualType QT, const FieldDecl *FD, 12063 bool InNonTrivialUnion) { 12064 if (InNonTrivialUnion) 12065 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12066 << 1 << 0 << QT << FD->getName(); 12067 } 12068 12069 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12070 if (InNonTrivialUnion) 12071 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12072 << 1 << 0 << QT << FD->getName(); 12073 } 12074 12075 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12076 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12077 if (RD->isUnion()) { 12078 if (OrigLoc.isValid()) { 12079 bool IsUnion = false; 12080 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12081 IsUnion = OrigRD->isUnion(); 12082 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12083 << 0 << OrigTy << IsUnion << UseContext; 12084 // Reset OrigLoc so that this diagnostic is emitted only once. 12085 OrigLoc = SourceLocation(); 12086 } 12087 InNonTrivialUnion = true; 12088 } 12089 12090 if (InNonTrivialUnion) 12091 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12092 << 0 << 0 << QT.getUnqualifiedType() << ""; 12093 12094 for (const FieldDecl *FD : RD->fields()) 12095 if (!shouldIgnoreForRecordTriviality(FD)) 12096 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12097 } 12098 12099 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12100 12101 // The non-trivial C union type or the struct/union type that contains a 12102 // non-trivial C union. 12103 QualType OrigTy; 12104 SourceLocation OrigLoc; 12105 Sema::NonTrivialCUnionContext UseContext; 12106 Sema &S; 12107 }; 12108 12109 struct DiagNonTrivalCUnionDestructedTypeVisitor 12110 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 12111 using Super = 12112 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 12113 12114 DiagNonTrivalCUnionDestructedTypeVisitor( 12115 QualType OrigTy, SourceLocation OrigLoc, 12116 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12117 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12118 12119 void visitWithKind(QualType::DestructionKind DK, QualType QT, 12120 const FieldDecl *FD, bool InNonTrivialUnion) { 12121 if (const auto *AT = S.Context.getAsArrayType(QT)) 12122 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12123 InNonTrivialUnion); 12124 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 12125 } 12126 12127 void visitARCStrong(QualType QT, const FieldDecl *FD, 12128 bool InNonTrivialUnion) { 12129 if (InNonTrivialUnion) 12130 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12131 << 1 << 1 << QT << FD->getName(); 12132 } 12133 12134 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12135 if (InNonTrivialUnion) 12136 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12137 << 1 << 1 << QT << FD->getName(); 12138 } 12139 12140 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12141 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12142 if (RD->isUnion()) { 12143 if (OrigLoc.isValid()) { 12144 bool IsUnion = false; 12145 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12146 IsUnion = OrigRD->isUnion(); 12147 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12148 << 1 << OrigTy << IsUnion << UseContext; 12149 // Reset OrigLoc so that this diagnostic is emitted only once. 12150 OrigLoc = SourceLocation(); 12151 } 12152 InNonTrivialUnion = true; 12153 } 12154 12155 if (InNonTrivialUnion) 12156 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12157 << 0 << 1 << QT.getUnqualifiedType() << ""; 12158 12159 for (const FieldDecl *FD : RD->fields()) 12160 if (!shouldIgnoreForRecordTriviality(FD)) 12161 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12162 } 12163 12164 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12165 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 12166 bool InNonTrivialUnion) {} 12167 12168 // The non-trivial C union type or the struct/union type that contains a 12169 // non-trivial C union. 12170 QualType OrigTy; 12171 SourceLocation OrigLoc; 12172 Sema::NonTrivialCUnionContext UseContext; 12173 Sema &S; 12174 }; 12175 12176 struct DiagNonTrivalCUnionCopyVisitor 12177 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 12178 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 12179 12180 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 12181 Sema::NonTrivialCUnionContext UseContext, 12182 Sema &S) 12183 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12184 12185 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12186 const FieldDecl *FD, bool InNonTrivialUnion) { 12187 if (const auto *AT = S.Context.getAsArrayType(QT)) 12188 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12189 InNonTrivialUnion); 12190 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12191 } 12192 12193 void visitARCStrong(QualType QT, const FieldDecl *FD, 12194 bool InNonTrivialUnion) { 12195 if (InNonTrivialUnion) 12196 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12197 << 1 << 2 << QT << FD->getName(); 12198 } 12199 12200 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12201 if (InNonTrivialUnion) 12202 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12203 << 1 << 2 << QT << FD->getName(); 12204 } 12205 12206 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12207 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12208 if (RD->isUnion()) { 12209 if (OrigLoc.isValid()) { 12210 bool IsUnion = false; 12211 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12212 IsUnion = OrigRD->isUnion(); 12213 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12214 << 2 << OrigTy << IsUnion << UseContext; 12215 // Reset OrigLoc so that this diagnostic is emitted only once. 12216 OrigLoc = SourceLocation(); 12217 } 12218 InNonTrivialUnion = true; 12219 } 12220 12221 if (InNonTrivialUnion) 12222 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12223 << 0 << 2 << QT.getUnqualifiedType() << ""; 12224 12225 for (const FieldDecl *FD : RD->fields()) 12226 if (!shouldIgnoreForRecordTriviality(FD)) 12227 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12228 } 12229 12230 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12231 const FieldDecl *FD, bool InNonTrivialUnion) {} 12232 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12233 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12234 bool InNonTrivialUnion) {} 12235 12236 // The non-trivial C union type or the struct/union type that contains a 12237 // non-trivial C union. 12238 QualType OrigTy; 12239 SourceLocation OrigLoc; 12240 Sema::NonTrivialCUnionContext UseContext; 12241 Sema &S; 12242 }; 12243 12244 } // namespace 12245 12246 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12247 NonTrivialCUnionContext UseContext, 12248 unsigned NonTrivialKind) { 12249 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12250 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12251 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12252 "shouldn't be called if type doesn't have a non-trivial C union"); 12253 12254 if ((NonTrivialKind & NTCUK_Init) && 12255 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12256 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12257 .visit(QT, nullptr, false); 12258 if ((NonTrivialKind & NTCUK_Destruct) && 12259 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12260 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12261 .visit(QT, nullptr, false); 12262 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12263 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12264 .visit(QT, nullptr, false); 12265 } 12266 12267 /// AddInitializerToDecl - Adds the initializer Init to the 12268 /// declaration dcl. If DirectInit is true, this is C++ direct 12269 /// initialization rather than copy initialization. 12270 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12271 // If there is no declaration, there was an error parsing it. Just ignore 12272 // the initializer. 12273 if (!RealDecl || RealDecl->isInvalidDecl()) { 12274 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12275 return; 12276 } 12277 12278 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12279 // Pure-specifiers are handled in ActOnPureSpecifier. 12280 Diag(Method->getLocation(), diag::err_member_function_initialization) 12281 << Method->getDeclName() << Init->getSourceRange(); 12282 Method->setInvalidDecl(); 12283 return; 12284 } 12285 12286 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12287 if (!VDecl) { 12288 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12289 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12290 RealDecl->setInvalidDecl(); 12291 return; 12292 } 12293 12294 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12295 if (VDecl->getType()->isUndeducedType()) { 12296 // Attempt typo correction early so that the type of the init expression can 12297 // be deduced based on the chosen correction if the original init contains a 12298 // TypoExpr. 12299 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12300 if (!Res.isUsable()) { 12301 // There are unresolved typos in Init, just drop them. 12302 // FIXME: improve the recovery strategy to preserve the Init. 12303 RealDecl->setInvalidDecl(); 12304 return; 12305 } 12306 if (Res.get()->containsErrors()) { 12307 // Invalidate the decl as we don't know the type for recovery-expr yet. 12308 RealDecl->setInvalidDecl(); 12309 VDecl->setInit(Res.get()); 12310 return; 12311 } 12312 Init = Res.get(); 12313 12314 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12315 return; 12316 } 12317 12318 // dllimport cannot be used on variable definitions. 12319 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12320 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12321 VDecl->setInvalidDecl(); 12322 return; 12323 } 12324 12325 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12326 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12327 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12328 VDecl->setInvalidDecl(); 12329 return; 12330 } 12331 12332 if (!VDecl->getType()->isDependentType()) { 12333 // A definition must end up with a complete type, which means it must be 12334 // complete with the restriction that an array type might be completed by 12335 // the initializer; note that later code assumes this restriction. 12336 QualType BaseDeclType = VDecl->getType(); 12337 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12338 BaseDeclType = Array->getElementType(); 12339 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12340 diag::err_typecheck_decl_incomplete_type)) { 12341 RealDecl->setInvalidDecl(); 12342 return; 12343 } 12344 12345 // The variable can not have an abstract class type. 12346 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12347 diag::err_abstract_type_in_decl, 12348 AbstractVariableType)) 12349 VDecl->setInvalidDecl(); 12350 } 12351 12352 // If adding the initializer will turn this declaration into a definition, 12353 // and we already have a definition for this variable, diagnose or otherwise 12354 // handle the situation. 12355 if (VarDecl *Def = VDecl->getDefinition()) 12356 if (Def != VDecl && 12357 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12358 !VDecl->isThisDeclarationADemotedDefinition() && 12359 checkVarDeclRedefinition(Def, VDecl)) 12360 return; 12361 12362 if (getLangOpts().CPlusPlus) { 12363 // C++ [class.static.data]p4 12364 // If a static data member is of const integral or const 12365 // enumeration type, its declaration in the class definition can 12366 // specify a constant-initializer which shall be an integral 12367 // constant expression (5.19). In that case, the member can appear 12368 // in integral constant expressions. The member shall still be 12369 // defined in a namespace scope if it is used in the program and the 12370 // namespace scope definition shall not contain an initializer. 12371 // 12372 // We already performed a redefinition check above, but for static 12373 // data members we also need to check whether there was an in-class 12374 // declaration with an initializer. 12375 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12376 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12377 << VDecl->getDeclName(); 12378 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12379 diag::note_previous_initializer) 12380 << 0; 12381 return; 12382 } 12383 12384 if (VDecl->hasLocalStorage()) 12385 setFunctionHasBranchProtectedScope(); 12386 12387 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12388 VDecl->setInvalidDecl(); 12389 return; 12390 } 12391 } 12392 12393 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12394 // a kernel function cannot be initialized." 12395 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12396 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12397 VDecl->setInvalidDecl(); 12398 return; 12399 } 12400 12401 // The LoaderUninitialized attribute acts as a definition (of undef). 12402 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12403 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12404 VDecl->setInvalidDecl(); 12405 return; 12406 } 12407 12408 // Get the decls type and save a reference for later, since 12409 // CheckInitializerTypes may change it. 12410 QualType DclT = VDecl->getType(), SavT = DclT; 12411 12412 // Expressions default to 'id' when we're in a debugger 12413 // and we are assigning it to a variable of Objective-C pointer type. 12414 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12415 Init->getType() == Context.UnknownAnyTy) { 12416 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12417 if (Result.isInvalid()) { 12418 VDecl->setInvalidDecl(); 12419 return; 12420 } 12421 Init = Result.get(); 12422 } 12423 12424 // Perform the initialization. 12425 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12426 if (!VDecl->isInvalidDecl()) { 12427 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12428 InitializationKind Kind = InitializationKind::CreateForInit( 12429 VDecl->getLocation(), DirectInit, Init); 12430 12431 MultiExprArg Args = Init; 12432 if (CXXDirectInit) 12433 Args = MultiExprArg(CXXDirectInit->getExprs(), 12434 CXXDirectInit->getNumExprs()); 12435 12436 // Try to correct any TypoExprs in the initialization arguments. 12437 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12438 ExprResult Res = CorrectDelayedTyposInExpr( 12439 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12440 [this, Entity, Kind](Expr *E) { 12441 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12442 return Init.Failed() ? ExprError() : E; 12443 }); 12444 if (Res.isInvalid()) { 12445 VDecl->setInvalidDecl(); 12446 } else if (Res.get() != Args[Idx]) { 12447 Args[Idx] = Res.get(); 12448 } 12449 } 12450 if (VDecl->isInvalidDecl()) 12451 return; 12452 12453 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12454 /*TopLevelOfInitList=*/false, 12455 /*TreatUnavailableAsInvalid=*/false); 12456 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12457 if (Result.isInvalid()) { 12458 // If the provided initializer fails to initialize the var decl, 12459 // we attach a recovery expr for better recovery. 12460 auto RecoveryExpr = 12461 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12462 if (RecoveryExpr.get()) 12463 VDecl->setInit(RecoveryExpr.get()); 12464 return; 12465 } 12466 12467 Init = Result.getAs<Expr>(); 12468 } 12469 12470 // Check for self-references within variable initializers. 12471 // Variables declared within a function/method body (except for references) 12472 // are handled by a dataflow analysis. 12473 // This is undefined behavior in C++, but valid in C. 12474 if (getLangOpts().CPlusPlus) 12475 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12476 VDecl->getType()->isReferenceType()) 12477 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12478 12479 // If the type changed, it means we had an incomplete type that was 12480 // completed by the initializer. For example: 12481 // int ary[] = { 1, 3, 5 }; 12482 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12483 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12484 VDecl->setType(DclT); 12485 12486 if (!VDecl->isInvalidDecl()) { 12487 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12488 12489 if (VDecl->hasAttr<BlocksAttr>()) 12490 checkRetainCycles(VDecl, Init); 12491 12492 // It is safe to assign a weak reference into a strong variable. 12493 // Although this code can still have problems: 12494 // id x = self.weakProp; 12495 // id y = self.weakProp; 12496 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12497 // paths through the function. This should be revisited if 12498 // -Wrepeated-use-of-weak is made flow-sensitive. 12499 if (FunctionScopeInfo *FSI = getCurFunction()) 12500 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12501 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12502 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12503 Init->getBeginLoc())) 12504 FSI->markSafeWeakUse(Init); 12505 } 12506 12507 // The initialization is usually a full-expression. 12508 // 12509 // FIXME: If this is a braced initialization of an aggregate, it is not 12510 // an expression, and each individual field initializer is a separate 12511 // full-expression. For instance, in: 12512 // 12513 // struct Temp { ~Temp(); }; 12514 // struct S { S(Temp); }; 12515 // struct T { S a, b; } t = { Temp(), Temp() } 12516 // 12517 // we should destroy the first Temp before constructing the second. 12518 ExprResult Result = 12519 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12520 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12521 if (Result.isInvalid()) { 12522 VDecl->setInvalidDecl(); 12523 return; 12524 } 12525 Init = Result.get(); 12526 12527 // Attach the initializer to the decl. 12528 VDecl->setInit(Init); 12529 12530 if (VDecl->isLocalVarDecl()) { 12531 // Don't check the initializer if the declaration is malformed. 12532 if (VDecl->isInvalidDecl()) { 12533 // do nothing 12534 12535 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12536 // This is true even in C++ for OpenCL. 12537 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12538 CheckForConstantInitializer(Init, DclT); 12539 12540 // Otherwise, C++ does not restrict the initializer. 12541 } else if (getLangOpts().CPlusPlus) { 12542 // do nothing 12543 12544 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12545 // static storage duration shall be constant expressions or string literals. 12546 } else if (VDecl->getStorageClass() == SC_Static) { 12547 CheckForConstantInitializer(Init, DclT); 12548 12549 // C89 is stricter than C99 for aggregate initializers. 12550 // C89 6.5.7p3: All the expressions [...] in an initializer list 12551 // for an object that has aggregate or union type shall be 12552 // constant expressions. 12553 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12554 isa<InitListExpr>(Init)) { 12555 const Expr *Culprit; 12556 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12557 Diag(Culprit->getExprLoc(), 12558 diag::ext_aggregate_init_not_constant) 12559 << Culprit->getSourceRange(); 12560 } 12561 } 12562 12563 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12564 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12565 if (VDecl->hasLocalStorage()) 12566 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12567 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12568 VDecl->getLexicalDeclContext()->isRecord()) { 12569 // This is an in-class initialization for a static data member, e.g., 12570 // 12571 // struct S { 12572 // static const int value = 17; 12573 // }; 12574 12575 // C++ [class.mem]p4: 12576 // A member-declarator can contain a constant-initializer only 12577 // if it declares a static member (9.4) of const integral or 12578 // const enumeration type, see 9.4.2. 12579 // 12580 // C++11 [class.static.data]p3: 12581 // If a non-volatile non-inline const static data member is of integral 12582 // or enumeration type, its declaration in the class definition can 12583 // specify a brace-or-equal-initializer in which every initializer-clause 12584 // that is an assignment-expression is a constant expression. A static 12585 // data member of literal type can be declared in the class definition 12586 // with the constexpr specifier; if so, its declaration shall specify a 12587 // brace-or-equal-initializer in which every initializer-clause that is 12588 // an assignment-expression is a constant expression. 12589 12590 // Do nothing on dependent types. 12591 if (DclT->isDependentType()) { 12592 12593 // Allow any 'static constexpr' members, whether or not they are of literal 12594 // type. We separately check that every constexpr variable is of literal 12595 // type. 12596 } else if (VDecl->isConstexpr()) { 12597 12598 // Require constness. 12599 } else if (!DclT.isConstQualified()) { 12600 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12601 << Init->getSourceRange(); 12602 VDecl->setInvalidDecl(); 12603 12604 // We allow integer constant expressions in all cases. 12605 } else if (DclT->isIntegralOrEnumerationType()) { 12606 // Check whether the expression is a constant expression. 12607 SourceLocation Loc; 12608 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12609 // In C++11, a non-constexpr const static data member with an 12610 // in-class initializer cannot be volatile. 12611 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12612 else if (Init->isValueDependent()) 12613 ; // Nothing to check. 12614 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12615 ; // Ok, it's an ICE! 12616 else if (Init->getType()->isScopedEnumeralType() && 12617 Init->isCXX11ConstantExpr(Context)) 12618 ; // Ok, it is a scoped-enum constant expression. 12619 else if (Init->isEvaluatable(Context)) { 12620 // If we can constant fold the initializer through heroics, accept it, 12621 // but report this as a use of an extension for -pedantic. 12622 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12623 << Init->getSourceRange(); 12624 } else { 12625 // Otherwise, this is some crazy unknown case. Report the issue at the 12626 // location provided by the isIntegerConstantExpr failed check. 12627 Diag(Loc, diag::err_in_class_initializer_non_constant) 12628 << Init->getSourceRange(); 12629 VDecl->setInvalidDecl(); 12630 } 12631 12632 // We allow foldable floating-point constants as an extension. 12633 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12634 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12635 // it anyway and provide a fixit to add the 'constexpr'. 12636 if (getLangOpts().CPlusPlus11) { 12637 Diag(VDecl->getLocation(), 12638 diag::ext_in_class_initializer_float_type_cxx11) 12639 << DclT << Init->getSourceRange(); 12640 Diag(VDecl->getBeginLoc(), 12641 diag::note_in_class_initializer_float_type_cxx11) 12642 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12643 } else { 12644 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12645 << DclT << Init->getSourceRange(); 12646 12647 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12648 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12649 << Init->getSourceRange(); 12650 VDecl->setInvalidDecl(); 12651 } 12652 } 12653 12654 // Suggest adding 'constexpr' in C++11 for literal types. 12655 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12656 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12657 << DclT << Init->getSourceRange() 12658 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12659 VDecl->setConstexpr(true); 12660 12661 } else { 12662 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12663 << DclT << Init->getSourceRange(); 12664 VDecl->setInvalidDecl(); 12665 } 12666 } else if (VDecl->isFileVarDecl()) { 12667 // In C, extern is typically used to avoid tentative definitions when 12668 // declaring variables in headers, but adding an intializer makes it a 12669 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12670 // In C++, extern is often used to give implictly static const variables 12671 // external linkage, so don't warn in that case. If selectany is present, 12672 // this might be header code intended for C and C++ inclusion, so apply the 12673 // C++ rules. 12674 if (VDecl->getStorageClass() == SC_Extern && 12675 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12676 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12677 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12678 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12679 Diag(VDecl->getLocation(), diag::warn_extern_init); 12680 12681 // In Microsoft C++ mode, a const variable defined in namespace scope has 12682 // external linkage by default if the variable is declared with 12683 // __declspec(dllexport). 12684 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12685 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12686 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12687 VDecl->setStorageClass(SC_Extern); 12688 12689 // C99 6.7.8p4. All file scoped initializers need to be constant. 12690 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12691 CheckForConstantInitializer(Init, DclT); 12692 } 12693 12694 QualType InitType = Init->getType(); 12695 if (!InitType.isNull() && 12696 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12697 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12698 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12699 12700 // We will represent direct-initialization similarly to copy-initialization: 12701 // int x(1); -as-> int x = 1; 12702 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12703 // 12704 // Clients that want to distinguish between the two forms, can check for 12705 // direct initializer using VarDecl::getInitStyle(). 12706 // A major benefit is that clients that don't particularly care about which 12707 // exactly form was it (like the CodeGen) can handle both cases without 12708 // special case code. 12709 12710 // C++ 8.5p11: 12711 // The form of initialization (using parentheses or '=') is generally 12712 // insignificant, but does matter when the entity being initialized has a 12713 // class type. 12714 if (CXXDirectInit) { 12715 assert(DirectInit && "Call-style initializer must be direct init."); 12716 VDecl->setInitStyle(VarDecl::CallInit); 12717 } else if (DirectInit) { 12718 // This must be list-initialization. No other way is direct-initialization. 12719 VDecl->setInitStyle(VarDecl::ListInit); 12720 } 12721 12722 if (LangOpts.OpenMP && 12723 (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) && 12724 VDecl->isFileVarDecl()) 12725 DeclsToCheckForDeferredDiags.insert(VDecl); 12726 CheckCompleteVariableDeclaration(VDecl); 12727 } 12728 12729 /// ActOnInitializerError - Given that there was an error parsing an 12730 /// initializer for the given declaration, try to at least re-establish 12731 /// invariants such as whether a variable's type is either dependent or 12732 /// complete. 12733 void Sema::ActOnInitializerError(Decl *D) { 12734 // Our main concern here is re-establishing invariants like "a 12735 // variable's type is either dependent or complete". 12736 if (!D || D->isInvalidDecl()) return; 12737 12738 VarDecl *VD = dyn_cast<VarDecl>(D); 12739 if (!VD) return; 12740 12741 // Bindings are not usable if we can't make sense of the initializer. 12742 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12743 for (auto *BD : DD->bindings()) 12744 BD->setInvalidDecl(); 12745 12746 // Auto types are meaningless if we can't make sense of the initializer. 12747 if (VD->getType()->isUndeducedType()) { 12748 D->setInvalidDecl(); 12749 return; 12750 } 12751 12752 QualType Ty = VD->getType(); 12753 if (Ty->isDependentType()) return; 12754 12755 // Require a complete type. 12756 if (RequireCompleteType(VD->getLocation(), 12757 Context.getBaseElementType(Ty), 12758 diag::err_typecheck_decl_incomplete_type)) { 12759 VD->setInvalidDecl(); 12760 return; 12761 } 12762 12763 // Require a non-abstract type. 12764 if (RequireNonAbstractType(VD->getLocation(), Ty, 12765 diag::err_abstract_type_in_decl, 12766 AbstractVariableType)) { 12767 VD->setInvalidDecl(); 12768 return; 12769 } 12770 12771 // Don't bother complaining about constructors or destructors, 12772 // though. 12773 } 12774 12775 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12776 // If there is no declaration, there was an error parsing it. Just ignore it. 12777 if (!RealDecl) 12778 return; 12779 12780 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12781 QualType Type = Var->getType(); 12782 12783 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12784 if (isa<DecompositionDecl>(RealDecl)) { 12785 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12786 Var->setInvalidDecl(); 12787 return; 12788 } 12789 12790 if (Type->isUndeducedType() && 12791 DeduceVariableDeclarationType(Var, false, nullptr)) 12792 return; 12793 12794 // C++11 [class.static.data]p3: A static data member can be declared with 12795 // the constexpr specifier; if so, its declaration shall specify 12796 // a brace-or-equal-initializer. 12797 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12798 // the definition of a variable [...] or the declaration of a static data 12799 // member. 12800 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12801 !Var->isThisDeclarationADemotedDefinition()) { 12802 if (Var->isStaticDataMember()) { 12803 // C++1z removes the relevant rule; the in-class declaration is always 12804 // a definition there. 12805 if (!getLangOpts().CPlusPlus17 && 12806 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12807 Diag(Var->getLocation(), 12808 diag::err_constexpr_static_mem_var_requires_init) 12809 << Var; 12810 Var->setInvalidDecl(); 12811 return; 12812 } 12813 } else { 12814 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12815 Var->setInvalidDecl(); 12816 return; 12817 } 12818 } 12819 12820 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12821 // be initialized. 12822 if (!Var->isInvalidDecl() && 12823 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12824 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12825 bool HasConstExprDefaultConstructor = false; 12826 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12827 for (auto *Ctor : RD->ctors()) { 12828 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 12829 Ctor->getMethodQualifiers().getAddressSpace() == 12830 LangAS::opencl_constant) { 12831 HasConstExprDefaultConstructor = true; 12832 } 12833 } 12834 } 12835 if (!HasConstExprDefaultConstructor) { 12836 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12837 Var->setInvalidDecl(); 12838 return; 12839 } 12840 } 12841 12842 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12843 if (Var->getStorageClass() == SC_Extern) { 12844 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12845 << Var; 12846 Var->setInvalidDecl(); 12847 return; 12848 } 12849 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12850 diag::err_typecheck_decl_incomplete_type)) { 12851 Var->setInvalidDecl(); 12852 return; 12853 } 12854 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12855 if (!RD->hasTrivialDefaultConstructor()) { 12856 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12857 Var->setInvalidDecl(); 12858 return; 12859 } 12860 } 12861 // The declaration is unitialized, no need for further checks. 12862 return; 12863 } 12864 12865 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12866 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12867 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12868 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12869 NTCUC_DefaultInitializedObject, NTCUK_Init); 12870 12871 12872 switch (DefKind) { 12873 case VarDecl::Definition: 12874 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12875 break; 12876 12877 // We have an out-of-line definition of a static data member 12878 // that has an in-class initializer, so we type-check this like 12879 // a declaration. 12880 // 12881 LLVM_FALLTHROUGH; 12882 12883 case VarDecl::DeclarationOnly: 12884 // It's only a declaration. 12885 12886 // Block scope. C99 6.7p7: If an identifier for an object is 12887 // declared with no linkage (C99 6.2.2p6), the type for the 12888 // object shall be complete. 12889 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12890 !Var->hasLinkage() && !Var->isInvalidDecl() && 12891 RequireCompleteType(Var->getLocation(), Type, 12892 diag::err_typecheck_decl_incomplete_type)) 12893 Var->setInvalidDecl(); 12894 12895 // Make sure that the type is not abstract. 12896 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12897 RequireNonAbstractType(Var->getLocation(), Type, 12898 diag::err_abstract_type_in_decl, 12899 AbstractVariableType)) 12900 Var->setInvalidDecl(); 12901 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12902 Var->getStorageClass() == SC_PrivateExtern) { 12903 Diag(Var->getLocation(), diag::warn_private_extern); 12904 Diag(Var->getLocation(), diag::note_private_extern); 12905 } 12906 12907 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 12908 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12909 ExternalDeclarations.push_back(Var); 12910 12911 return; 12912 12913 case VarDecl::TentativeDefinition: 12914 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12915 // object that has file scope without an initializer, and without a 12916 // storage-class specifier or with the storage-class specifier "static", 12917 // constitutes a tentative definition. Note: A tentative definition with 12918 // external linkage is valid (C99 6.2.2p5). 12919 if (!Var->isInvalidDecl()) { 12920 if (const IncompleteArrayType *ArrayT 12921 = Context.getAsIncompleteArrayType(Type)) { 12922 if (RequireCompleteSizedType( 12923 Var->getLocation(), ArrayT->getElementType(), 12924 diag::err_array_incomplete_or_sizeless_type)) 12925 Var->setInvalidDecl(); 12926 } else if (Var->getStorageClass() == SC_Static) { 12927 // C99 6.9.2p3: If the declaration of an identifier for an object is 12928 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12929 // declared type shall not be an incomplete type. 12930 // NOTE: code such as the following 12931 // static struct s; 12932 // struct s { int a; }; 12933 // is accepted by gcc. Hence here we issue a warning instead of 12934 // an error and we do not invalidate the static declaration. 12935 // NOTE: to avoid multiple warnings, only check the first declaration. 12936 if (Var->isFirstDecl()) 12937 RequireCompleteType(Var->getLocation(), Type, 12938 diag::ext_typecheck_decl_incomplete_type); 12939 } 12940 } 12941 12942 // Record the tentative definition; we're done. 12943 if (!Var->isInvalidDecl()) 12944 TentativeDefinitions.push_back(Var); 12945 return; 12946 } 12947 12948 // Provide a specific diagnostic for uninitialized variable 12949 // definitions with incomplete array type. 12950 if (Type->isIncompleteArrayType()) { 12951 Diag(Var->getLocation(), 12952 diag::err_typecheck_incomplete_array_needs_initializer); 12953 Var->setInvalidDecl(); 12954 return; 12955 } 12956 12957 // Provide a specific diagnostic for uninitialized variable 12958 // definitions with reference type. 12959 if (Type->isReferenceType()) { 12960 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12961 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12962 Var->setInvalidDecl(); 12963 return; 12964 } 12965 12966 // Do not attempt to type-check the default initializer for a 12967 // variable with dependent type. 12968 if (Type->isDependentType()) 12969 return; 12970 12971 if (Var->isInvalidDecl()) 12972 return; 12973 12974 if (!Var->hasAttr<AliasAttr>()) { 12975 if (RequireCompleteType(Var->getLocation(), 12976 Context.getBaseElementType(Type), 12977 diag::err_typecheck_decl_incomplete_type)) { 12978 Var->setInvalidDecl(); 12979 return; 12980 } 12981 } else { 12982 return; 12983 } 12984 12985 // The variable can not have an abstract class type. 12986 if (RequireNonAbstractType(Var->getLocation(), Type, 12987 diag::err_abstract_type_in_decl, 12988 AbstractVariableType)) { 12989 Var->setInvalidDecl(); 12990 return; 12991 } 12992 12993 // Check for jumps past the implicit initializer. C++0x 12994 // clarifies that this applies to a "variable with automatic 12995 // storage duration", not a "local variable". 12996 // C++11 [stmt.dcl]p3 12997 // A program that jumps from a point where a variable with automatic 12998 // storage duration is not in scope to a point where it is in scope is 12999 // ill-formed unless the variable has scalar type, class type with a 13000 // trivial default constructor and a trivial destructor, a cv-qualified 13001 // version of one of these types, or an array of one of the preceding 13002 // types and is declared without an initializer. 13003 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 13004 if (const RecordType *Record 13005 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 13006 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 13007 // Mark the function (if we're in one) for further checking even if the 13008 // looser rules of C++11 do not require such checks, so that we can 13009 // diagnose incompatibilities with C++98. 13010 if (!CXXRecord->isPOD()) 13011 setFunctionHasBranchProtectedScope(); 13012 } 13013 } 13014 // In OpenCL, we can't initialize objects in the __local address space, 13015 // even implicitly, so don't synthesize an implicit initializer. 13016 if (getLangOpts().OpenCL && 13017 Var->getType().getAddressSpace() == LangAS::opencl_local) 13018 return; 13019 // C++03 [dcl.init]p9: 13020 // If no initializer is specified for an object, and the 13021 // object is of (possibly cv-qualified) non-POD class type (or 13022 // array thereof), the object shall be default-initialized; if 13023 // the object is of const-qualified type, the underlying class 13024 // type shall have a user-declared default 13025 // constructor. Otherwise, if no initializer is specified for 13026 // a non- static object, the object and its subobjects, if 13027 // any, have an indeterminate initial value); if the object 13028 // or any of its subobjects are of const-qualified type, the 13029 // program is ill-formed. 13030 // C++0x [dcl.init]p11: 13031 // If no initializer is specified for an object, the object is 13032 // default-initialized; [...]. 13033 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 13034 InitializationKind Kind 13035 = InitializationKind::CreateDefault(Var->getLocation()); 13036 13037 InitializationSequence InitSeq(*this, Entity, Kind, None); 13038 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 13039 13040 if (Init.get()) { 13041 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 13042 // This is important for template substitution. 13043 Var->setInitStyle(VarDecl::CallInit); 13044 } else if (Init.isInvalid()) { 13045 // If default-init fails, attach a recovery-expr initializer to track 13046 // that initialization was attempted and failed. 13047 auto RecoveryExpr = 13048 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 13049 if (RecoveryExpr.get()) 13050 Var->setInit(RecoveryExpr.get()); 13051 } 13052 13053 CheckCompleteVariableDeclaration(Var); 13054 } 13055 } 13056 13057 void Sema::ActOnCXXForRangeDecl(Decl *D) { 13058 // If there is no declaration, there was an error parsing it. Ignore it. 13059 if (!D) 13060 return; 13061 13062 VarDecl *VD = dyn_cast<VarDecl>(D); 13063 if (!VD) { 13064 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 13065 D->setInvalidDecl(); 13066 return; 13067 } 13068 13069 VD->setCXXForRangeDecl(true); 13070 13071 // for-range-declaration cannot be given a storage class specifier. 13072 int Error = -1; 13073 switch (VD->getStorageClass()) { 13074 case SC_None: 13075 break; 13076 case SC_Extern: 13077 Error = 0; 13078 break; 13079 case SC_Static: 13080 Error = 1; 13081 break; 13082 case SC_PrivateExtern: 13083 Error = 2; 13084 break; 13085 case SC_Auto: 13086 Error = 3; 13087 break; 13088 case SC_Register: 13089 Error = 4; 13090 break; 13091 } 13092 13093 // for-range-declaration cannot be given a storage class specifier con't. 13094 switch (VD->getTSCSpec()) { 13095 case TSCS_thread_local: 13096 Error = 6; 13097 break; 13098 case TSCS___thread: 13099 case TSCS__Thread_local: 13100 case TSCS_unspecified: 13101 break; 13102 } 13103 13104 if (Error != -1) { 13105 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 13106 << VD << Error; 13107 D->setInvalidDecl(); 13108 } 13109 } 13110 13111 StmtResult 13112 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 13113 IdentifierInfo *Ident, 13114 ParsedAttributes &Attrs, 13115 SourceLocation AttrEnd) { 13116 // C++1y [stmt.iter]p1: 13117 // A range-based for statement of the form 13118 // for ( for-range-identifier : for-range-initializer ) statement 13119 // is equivalent to 13120 // for ( auto&& for-range-identifier : for-range-initializer ) statement 13121 DeclSpec DS(Attrs.getPool().getFactory()); 13122 13123 const char *PrevSpec; 13124 unsigned DiagID; 13125 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 13126 getPrintingPolicy()); 13127 13128 Declarator D(DS, DeclaratorContext::ForInit); 13129 D.SetIdentifier(Ident, IdentLoc); 13130 D.takeAttributes(Attrs, AttrEnd); 13131 13132 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 13133 IdentLoc); 13134 Decl *Var = ActOnDeclarator(S, D); 13135 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 13136 FinalizeDeclaration(Var); 13137 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 13138 AttrEnd.isValid() ? AttrEnd : IdentLoc); 13139 } 13140 13141 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 13142 if (var->isInvalidDecl()) return; 13143 13144 MaybeAddCUDAConstantAttr(var); 13145 13146 if (getLangOpts().OpenCL) { 13147 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 13148 // initialiser 13149 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 13150 !var->hasInit()) { 13151 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 13152 << 1 /*Init*/; 13153 var->setInvalidDecl(); 13154 return; 13155 } 13156 } 13157 13158 // In Objective-C, don't allow jumps past the implicit initialization of a 13159 // local retaining variable. 13160 if (getLangOpts().ObjC && 13161 var->hasLocalStorage()) { 13162 switch (var->getType().getObjCLifetime()) { 13163 case Qualifiers::OCL_None: 13164 case Qualifiers::OCL_ExplicitNone: 13165 case Qualifiers::OCL_Autoreleasing: 13166 break; 13167 13168 case Qualifiers::OCL_Weak: 13169 case Qualifiers::OCL_Strong: 13170 setFunctionHasBranchProtectedScope(); 13171 break; 13172 } 13173 } 13174 13175 if (var->hasLocalStorage() && 13176 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 13177 setFunctionHasBranchProtectedScope(); 13178 13179 // Warn about externally-visible variables being defined without a 13180 // prior declaration. We only want to do this for global 13181 // declarations, but we also specifically need to avoid doing it for 13182 // class members because the linkage of an anonymous class can 13183 // change if it's later given a typedef name. 13184 if (var->isThisDeclarationADefinition() && 13185 var->getDeclContext()->getRedeclContext()->isFileContext() && 13186 var->isExternallyVisible() && var->hasLinkage() && 13187 !var->isInline() && !var->getDescribedVarTemplate() && 13188 !isa<VarTemplatePartialSpecializationDecl>(var) && 13189 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13190 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13191 var->getLocation())) { 13192 // Find a previous declaration that's not a definition. 13193 VarDecl *prev = var->getPreviousDecl(); 13194 while (prev && prev->isThisDeclarationADefinition()) 13195 prev = prev->getPreviousDecl(); 13196 13197 if (!prev) { 13198 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13199 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13200 << /* variable */ 0; 13201 } 13202 } 13203 13204 // Cache the result of checking for constant initialization. 13205 Optional<bool> CacheHasConstInit; 13206 const Expr *CacheCulprit = nullptr; 13207 auto checkConstInit = [&]() mutable { 13208 if (!CacheHasConstInit) 13209 CacheHasConstInit = var->getInit()->isConstantInitializer( 13210 Context, var->getType()->isReferenceType(), &CacheCulprit); 13211 return *CacheHasConstInit; 13212 }; 13213 13214 if (var->getTLSKind() == VarDecl::TLS_Static) { 13215 if (var->getType().isDestructedType()) { 13216 // GNU C++98 edits for __thread, [basic.start.term]p3: 13217 // The type of an object with thread storage duration shall not 13218 // have a non-trivial destructor. 13219 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13220 if (getLangOpts().CPlusPlus11) 13221 Diag(var->getLocation(), diag::note_use_thread_local); 13222 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13223 if (!checkConstInit()) { 13224 // GNU C++98 edits for __thread, [basic.start.init]p4: 13225 // An object of thread storage duration shall not require dynamic 13226 // initialization. 13227 // FIXME: Need strict checking here. 13228 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13229 << CacheCulprit->getSourceRange(); 13230 if (getLangOpts().CPlusPlus11) 13231 Diag(var->getLocation(), diag::note_use_thread_local); 13232 } 13233 } 13234 } 13235 13236 13237 if (!var->getType()->isStructureType() && var->hasInit() && 13238 isa<InitListExpr>(var->getInit())) { 13239 const auto *ILE = cast<InitListExpr>(var->getInit()); 13240 unsigned NumInits = ILE->getNumInits(); 13241 if (NumInits > 2) 13242 for (unsigned I = 0; I < NumInits; ++I) { 13243 const auto *Init = ILE->getInit(I); 13244 if (!Init) 13245 break; 13246 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13247 if (!SL) 13248 break; 13249 13250 unsigned NumConcat = SL->getNumConcatenated(); 13251 // Diagnose missing comma in string array initialization. 13252 // Do not warn when all the elements in the initializer are concatenated 13253 // together. Do not warn for macros too. 13254 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13255 bool OnlyOneMissingComma = true; 13256 for (unsigned J = I + 1; J < NumInits; ++J) { 13257 const auto *Init = ILE->getInit(J); 13258 if (!Init) 13259 break; 13260 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13261 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13262 OnlyOneMissingComma = false; 13263 break; 13264 } 13265 } 13266 13267 if (OnlyOneMissingComma) { 13268 SmallVector<FixItHint, 1> Hints; 13269 for (unsigned i = 0; i < NumConcat - 1; ++i) 13270 Hints.push_back(FixItHint::CreateInsertion( 13271 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13272 13273 Diag(SL->getStrTokenLoc(1), 13274 diag::warn_concatenated_literal_array_init) 13275 << Hints; 13276 Diag(SL->getBeginLoc(), 13277 diag::note_concatenated_string_literal_silence); 13278 } 13279 // In any case, stop now. 13280 break; 13281 } 13282 } 13283 } 13284 13285 13286 QualType type = var->getType(); 13287 13288 if (var->hasAttr<BlocksAttr>()) 13289 getCurFunction()->addByrefBlockVar(var); 13290 13291 Expr *Init = var->getInit(); 13292 bool GlobalStorage = var->hasGlobalStorage(); 13293 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13294 QualType baseType = Context.getBaseElementType(type); 13295 bool HasConstInit = true; 13296 13297 // Check whether the initializer is sufficiently constant. 13298 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 13299 !Init->isValueDependent() && 13300 (GlobalStorage || var->isConstexpr() || 13301 var->mightBeUsableInConstantExpressions(Context))) { 13302 // If this variable might have a constant initializer or might be usable in 13303 // constant expressions, check whether or not it actually is now. We can't 13304 // do this lazily, because the result might depend on things that change 13305 // later, such as which constexpr functions happen to be defined. 13306 SmallVector<PartialDiagnosticAt, 8> Notes; 13307 if (!getLangOpts().CPlusPlus11) { 13308 // Prior to C++11, in contexts where a constant initializer is required, 13309 // the set of valid constant initializers is described by syntactic rules 13310 // in [expr.const]p2-6. 13311 // FIXME: Stricter checking for these rules would be useful for constinit / 13312 // -Wglobal-constructors. 13313 HasConstInit = checkConstInit(); 13314 13315 // Compute and cache the constant value, and remember that we have a 13316 // constant initializer. 13317 if (HasConstInit) { 13318 (void)var->checkForConstantInitialization(Notes); 13319 Notes.clear(); 13320 } else if (CacheCulprit) { 13321 Notes.emplace_back(CacheCulprit->getExprLoc(), 13322 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13323 Notes.back().second << CacheCulprit->getSourceRange(); 13324 } 13325 } else { 13326 // Evaluate the initializer to see if it's a constant initializer. 13327 HasConstInit = var->checkForConstantInitialization(Notes); 13328 } 13329 13330 if (HasConstInit) { 13331 // FIXME: Consider replacing the initializer with a ConstantExpr. 13332 } else if (var->isConstexpr()) { 13333 SourceLocation DiagLoc = var->getLocation(); 13334 // If the note doesn't add any useful information other than a source 13335 // location, fold it into the primary diagnostic. 13336 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13337 diag::note_invalid_subexpr_in_const_expr) { 13338 DiagLoc = Notes[0].first; 13339 Notes.clear(); 13340 } 13341 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13342 << var << Init->getSourceRange(); 13343 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13344 Diag(Notes[I].first, Notes[I].second); 13345 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13346 auto *Attr = var->getAttr<ConstInitAttr>(); 13347 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13348 << Init->getSourceRange(); 13349 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13350 << Attr->getRange() << Attr->isConstinit(); 13351 for (auto &it : Notes) 13352 Diag(it.first, it.second); 13353 } else if (IsGlobal && 13354 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13355 var->getLocation())) { 13356 // Warn about globals which don't have a constant initializer. Don't 13357 // warn about globals with a non-trivial destructor because we already 13358 // warned about them. 13359 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13360 if (!(RD && !RD->hasTrivialDestructor())) { 13361 // checkConstInit() here permits trivial default initialization even in 13362 // C++11 onwards, where such an initializer is not a constant initializer 13363 // but nonetheless doesn't require a global constructor. 13364 if (!checkConstInit()) 13365 Diag(var->getLocation(), diag::warn_global_constructor) 13366 << Init->getSourceRange(); 13367 } 13368 } 13369 } 13370 13371 // Apply section attributes and pragmas to global variables. 13372 if (GlobalStorage && var->isThisDeclarationADefinition() && 13373 !inTemplateInstantiation()) { 13374 PragmaStack<StringLiteral *> *Stack = nullptr; 13375 int SectionFlags = ASTContext::PSF_Read; 13376 if (var->getType().isConstQualified()) { 13377 if (HasConstInit) 13378 Stack = &ConstSegStack; 13379 else { 13380 Stack = &BSSSegStack; 13381 SectionFlags |= ASTContext::PSF_Write; 13382 } 13383 } else if (var->hasInit() && HasConstInit) { 13384 Stack = &DataSegStack; 13385 SectionFlags |= ASTContext::PSF_Write; 13386 } else { 13387 Stack = &BSSSegStack; 13388 SectionFlags |= ASTContext::PSF_Write; 13389 } 13390 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13391 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13392 SectionFlags |= ASTContext::PSF_Implicit; 13393 UnifySection(SA->getName(), SectionFlags, var); 13394 } else if (Stack->CurrentValue) { 13395 SectionFlags |= ASTContext::PSF_Implicit; 13396 auto SectionName = Stack->CurrentValue->getString(); 13397 var->addAttr(SectionAttr::CreateImplicit( 13398 Context, SectionName, Stack->CurrentPragmaLocation, 13399 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13400 if (UnifySection(SectionName, SectionFlags, var)) 13401 var->dropAttr<SectionAttr>(); 13402 } 13403 13404 // Apply the init_seg attribute if this has an initializer. If the 13405 // initializer turns out to not be dynamic, we'll end up ignoring this 13406 // attribute. 13407 if (CurInitSeg && var->getInit()) 13408 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13409 CurInitSegLoc, 13410 AttributeCommonInfo::AS_Pragma)); 13411 } 13412 13413 // All the following checks are C++ only. 13414 if (!getLangOpts().CPlusPlus) { 13415 // If this variable must be emitted, add it as an initializer for the 13416 // current module. 13417 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13418 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13419 return; 13420 } 13421 13422 // Require the destructor. 13423 if (!type->isDependentType()) 13424 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13425 FinalizeVarWithDestructor(var, recordType); 13426 13427 // If this variable must be emitted, add it as an initializer for the current 13428 // module. 13429 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13430 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13431 13432 // Build the bindings if this is a structured binding declaration. 13433 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13434 CheckCompleteDecompositionDeclaration(DD); 13435 } 13436 13437 /// Check if VD needs to be dllexport/dllimport due to being in a 13438 /// dllexport/import function. 13439 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13440 assert(VD->isStaticLocal()); 13441 13442 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13443 13444 // Find outermost function when VD is in lambda function. 13445 while (FD && !getDLLAttr(FD) && 13446 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13447 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13448 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13449 } 13450 13451 if (!FD) 13452 return; 13453 13454 // Static locals inherit dll attributes from their function. 13455 if (Attr *A = getDLLAttr(FD)) { 13456 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13457 NewAttr->setInherited(true); 13458 VD->addAttr(NewAttr); 13459 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13460 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13461 NewAttr->setInherited(true); 13462 VD->addAttr(NewAttr); 13463 13464 // Export this function to enforce exporting this static variable even 13465 // if it is not used in this compilation unit. 13466 if (!FD->hasAttr<DLLExportAttr>()) 13467 FD->addAttr(NewAttr); 13468 13469 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13470 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13471 NewAttr->setInherited(true); 13472 VD->addAttr(NewAttr); 13473 } 13474 } 13475 13476 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13477 /// any semantic actions necessary after any initializer has been attached. 13478 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13479 // Note that we are no longer parsing the initializer for this declaration. 13480 ParsingInitForAutoVars.erase(ThisDecl); 13481 13482 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13483 if (!VD) 13484 return; 13485 13486 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13487 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13488 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13489 if (PragmaClangBSSSection.Valid) 13490 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13491 Context, PragmaClangBSSSection.SectionName, 13492 PragmaClangBSSSection.PragmaLocation, 13493 AttributeCommonInfo::AS_Pragma)); 13494 if (PragmaClangDataSection.Valid) 13495 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13496 Context, PragmaClangDataSection.SectionName, 13497 PragmaClangDataSection.PragmaLocation, 13498 AttributeCommonInfo::AS_Pragma)); 13499 if (PragmaClangRodataSection.Valid) 13500 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13501 Context, PragmaClangRodataSection.SectionName, 13502 PragmaClangRodataSection.PragmaLocation, 13503 AttributeCommonInfo::AS_Pragma)); 13504 if (PragmaClangRelroSection.Valid) 13505 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13506 Context, PragmaClangRelroSection.SectionName, 13507 PragmaClangRelroSection.PragmaLocation, 13508 AttributeCommonInfo::AS_Pragma)); 13509 } 13510 13511 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13512 for (auto *BD : DD->bindings()) { 13513 FinalizeDeclaration(BD); 13514 } 13515 } 13516 13517 checkAttributesAfterMerging(*this, *VD); 13518 13519 // Perform TLS alignment check here after attributes attached to the variable 13520 // which may affect the alignment have been processed. Only perform the check 13521 // if the target has a maximum TLS alignment (zero means no constraints). 13522 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13523 // Protect the check so that it's not performed on dependent types and 13524 // dependent alignments (we can't determine the alignment in that case). 13525 if (VD->getTLSKind() && !VD->hasDependentAlignment()) { 13526 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13527 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13528 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13529 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13530 << (unsigned)MaxAlignChars.getQuantity(); 13531 } 13532 } 13533 } 13534 13535 if (VD->isStaticLocal()) 13536 CheckStaticLocalForDllExport(VD); 13537 13538 // Perform check for initializers of device-side global variables. 13539 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13540 // 7.5). We must also apply the same checks to all __shared__ 13541 // variables whether they are local or not. CUDA also allows 13542 // constant initializers for __constant__ and __device__ variables. 13543 if (getLangOpts().CUDA) 13544 checkAllowedCUDAInitializer(VD); 13545 13546 // Grab the dllimport or dllexport attribute off of the VarDecl. 13547 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13548 13549 // Imported static data members cannot be defined out-of-line. 13550 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13551 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13552 VD->isThisDeclarationADefinition()) { 13553 // We allow definitions of dllimport class template static data members 13554 // with a warning. 13555 CXXRecordDecl *Context = 13556 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13557 bool IsClassTemplateMember = 13558 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13559 Context->getDescribedClassTemplate(); 13560 13561 Diag(VD->getLocation(), 13562 IsClassTemplateMember 13563 ? diag::warn_attribute_dllimport_static_field_definition 13564 : diag::err_attribute_dllimport_static_field_definition); 13565 Diag(IA->getLocation(), diag::note_attribute); 13566 if (!IsClassTemplateMember) 13567 VD->setInvalidDecl(); 13568 } 13569 } 13570 13571 // dllimport/dllexport variables cannot be thread local, their TLS index 13572 // isn't exported with the variable. 13573 if (DLLAttr && VD->getTLSKind()) { 13574 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13575 if (F && getDLLAttr(F)) { 13576 assert(VD->isStaticLocal()); 13577 // But if this is a static local in a dlimport/dllexport function, the 13578 // function will never be inlined, which means the var would never be 13579 // imported, so having it marked import/export is safe. 13580 } else { 13581 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13582 << DLLAttr; 13583 VD->setInvalidDecl(); 13584 } 13585 } 13586 13587 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13588 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13589 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13590 << Attr; 13591 VD->dropAttr<UsedAttr>(); 13592 } 13593 } 13594 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13595 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13596 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13597 << Attr; 13598 VD->dropAttr<RetainAttr>(); 13599 } 13600 } 13601 13602 const DeclContext *DC = VD->getDeclContext(); 13603 // If there's a #pragma GCC visibility in scope, and this isn't a class 13604 // member, set the visibility of this variable. 13605 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13606 AddPushedVisibilityAttribute(VD); 13607 13608 // FIXME: Warn on unused var template partial specializations. 13609 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13610 MarkUnusedFileScopedDecl(VD); 13611 13612 // Now we have parsed the initializer and can update the table of magic 13613 // tag values. 13614 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13615 !VD->getType()->isIntegralOrEnumerationType()) 13616 return; 13617 13618 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13619 const Expr *MagicValueExpr = VD->getInit(); 13620 if (!MagicValueExpr) { 13621 continue; 13622 } 13623 Optional<llvm::APSInt> MagicValueInt; 13624 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13625 Diag(I->getRange().getBegin(), 13626 diag::err_type_tag_for_datatype_not_ice) 13627 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13628 continue; 13629 } 13630 if (MagicValueInt->getActiveBits() > 64) { 13631 Diag(I->getRange().getBegin(), 13632 diag::err_type_tag_for_datatype_too_large) 13633 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13634 continue; 13635 } 13636 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13637 RegisterTypeTagForDatatype(I->getArgumentKind(), 13638 MagicValue, 13639 I->getMatchingCType(), 13640 I->getLayoutCompatible(), 13641 I->getMustBeNull()); 13642 } 13643 } 13644 13645 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13646 auto *VD = dyn_cast<VarDecl>(DD); 13647 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13648 } 13649 13650 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13651 ArrayRef<Decl *> Group) { 13652 SmallVector<Decl*, 8> Decls; 13653 13654 if (DS.isTypeSpecOwned()) 13655 Decls.push_back(DS.getRepAsDecl()); 13656 13657 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13658 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13659 bool DiagnosedMultipleDecomps = false; 13660 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13661 bool DiagnosedNonDeducedAuto = false; 13662 13663 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13664 if (Decl *D = Group[i]) { 13665 // For declarators, there are some additional syntactic-ish checks we need 13666 // to perform. 13667 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13668 if (!FirstDeclaratorInGroup) 13669 FirstDeclaratorInGroup = DD; 13670 if (!FirstDecompDeclaratorInGroup) 13671 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13672 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13673 !hasDeducedAuto(DD)) 13674 FirstNonDeducedAutoInGroup = DD; 13675 13676 if (FirstDeclaratorInGroup != DD) { 13677 // A decomposition declaration cannot be combined with any other 13678 // declaration in the same group. 13679 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13680 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13681 diag::err_decomp_decl_not_alone) 13682 << FirstDeclaratorInGroup->getSourceRange() 13683 << DD->getSourceRange(); 13684 DiagnosedMultipleDecomps = true; 13685 } 13686 13687 // A declarator that uses 'auto' in any way other than to declare a 13688 // variable with a deduced type cannot be combined with any other 13689 // declarator in the same group. 13690 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13691 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13692 diag::err_auto_non_deduced_not_alone) 13693 << FirstNonDeducedAutoInGroup->getType() 13694 ->hasAutoForTrailingReturnType() 13695 << FirstDeclaratorInGroup->getSourceRange() 13696 << DD->getSourceRange(); 13697 DiagnosedNonDeducedAuto = true; 13698 } 13699 } 13700 } 13701 13702 Decls.push_back(D); 13703 } 13704 } 13705 13706 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13707 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13708 handleTagNumbering(Tag, S); 13709 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13710 getLangOpts().CPlusPlus) 13711 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13712 } 13713 } 13714 13715 return BuildDeclaratorGroup(Decls); 13716 } 13717 13718 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13719 /// group, performing any necessary semantic checking. 13720 Sema::DeclGroupPtrTy 13721 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13722 // C++14 [dcl.spec.auto]p7: (DR1347) 13723 // If the type that replaces the placeholder type is not the same in each 13724 // deduction, the program is ill-formed. 13725 if (Group.size() > 1) { 13726 QualType Deduced; 13727 VarDecl *DeducedDecl = nullptr; 13728 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13729 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13730 if (!D || D->isInvalidDecl()) 13731 break; 13732 DeducedType *DT = D->getType()->getContainedDeducedType(); 13733 if (!DT || DT->getDeducedType().isNull()) 13734 continue; 13735 if (Deduced.isNull()) { 13736 Deduced = DT->getDeducedType(); 13737 DeducedDecl = D; 13738 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13739 auto *AT = dyn_cast<AutoType>(DT); 13740 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13741 diag::err_auto_different_deductions) 13742 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13743 << DeducedDecl->getDeclName() << DT->getDeducedType() 13744 << D->getDeclName(); 13745 if (DeducedDecl->hasInit()) 13746 Dia << DeducedDecl->getInit()->getSourceRange(); 13747 if (D->getInit()) 13748 Dia << D->getInit()->getSourceRange(); 13749 D->setInvalidDecl(); 13750 break; 13751 } 13752 } 13753 } 13754 13755 ActOnDocumentableDecls(Group); 13756 13757 return DeclGroupPtrTy::make( 13758 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13759 } 13760 13761 void Sema::ActOnDocumentableDecl(Decl *D) { 13762 ActOnDocumentableDecls(D); 13763 } 13764 13765 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13766 // Don't parse the comment if Doxygen diagnostics are ignored. 13767 if (Group.empty() || !Group[0]) 13768 return; 13769 13770 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13771 Group[0]->getLocation()) && 13772 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13773 Group[0]->getLocation())) 13774 return; 13775 13776 if (Group.size() >= 2) { 13777 // This is a decl group. Normally it will contain only declarations 13778 // produced from declarator list. But in case we have any definitions or 13779 // additional declaration references: 13780 // 'typedef struct S {} S;' 13781 // 'typedef struct S *S;' 13782 // 'struct S *pS;' 13783 // FinalizeDeclaratorGroup adds these as separate declarations. 13784 Decl *MaybeTagDecl = Group[0]; 13785 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13786 Group = Group.slice(1); 13787 } 13788 } 13789 13790 // FIMXE: We assume every Decl in the group is in the same file. 13791 // This is false when preprocessor constructs the group from decls in 13792 // different files (e. g. macros or #include). 13793 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13794 } 13795 13796 /// Common checks for a parameter-declaration that should apply to both function 13797 /// parameters and non-type template parameters. 13798 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13799 // Check that there are no default arguments inside the type of this 13800 // parameter. 13801 if (getLangOpts().CPlusPlus) 13802 CheckExtraCXXDefaultArguments(D); 13803 13804 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13805 if (D.getCXXScopeSpec().isSet()) { 13806 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13807 << D.getCXXScopeSpec().getRange(); 13808 } 13809 13810 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13811 // simple identifier except [...irrelevant cases...]. 13812 switch (D.getName().getKind()) { 13813 case UnqualifiedIdKind::IK_Identifier: 13814 break; 13815 13816 case UnqualifiedIdKind::IK_OperatorFunctionId: 13817 case UnqualifiedIdKind::IK_ConversionFunctionId: 13818 case UnqualifiedIdKind::IK_LiteralOperatorId: 13819 case UnqualifiedIdKind::IK_ConstructorName: 13820 case UnqualifiedIdKind::IK_DestructorName: 13821 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13822 case UnqualifiedIdKind::IK_DeductionGuideName: 13823 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13824 << GetNameForDeclarator(D).getName(); 13825 break; 13826 13827 case UnqualifiedIdKind::IK_TemplateId: 13828 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13829 // GetNameForDeclarator would not produce a useful name in this case. 13830 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13831 break; 13832 } 13833 } 13834 13835 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13836 /// to introduce parameters into function prototype scope. 13837 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13838 const DeclSpec &DS = D.getDeclSpec(); 13839 13840 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13841 13842 // C++03 [dcl.stc]p2 also permits 'auto'. 13843 StorageClass SC = SC_None; 13844 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13845 SC = SC_Register; 13846 // In C++11, the 'register' storage class specifier is deprecated. 13847 // In C++17, it is not allowed, but we tolerate it as an extension. 13848 if (getLangOpts().CPlusPlus11) { 13849 Diag(DS.getStorageClassSpecLoc(), 13850 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13851 : diag::warn_deprecated_register) 13852 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13853 } 13854 } else if (getLangOpts().CPlusPlus && 13855 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13856 SC = SC_Auto; 13857 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13858 Diag(DS.getStorageClassSpecLoc(), 13859 diag::err_invalid_storage_class_in_func_decl); 13860 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13861 } 13862 13863 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13864 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13865 << DeclSpec::getSpecifierName(TSCS); 13866 if (DS.isInlineSpecified()) 13867 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13868 << getLangOpts().CPlusPlus17; 13869 if (DS.hasConstexprSpecifier()) 13870 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13871 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13872 13873 DiagnoseFunctionSpecifiers(DS); 13874 13875 CheckFunctionOrTemplateParamDeclarator(S, D); 13876 13877 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13878 QualType parmDeclType = TInfo->getType(); 13879 13880 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13881 IdentifierInfo *II = D.getIdentifier(); 13882 if (II) { 13883 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13884 ForVisibleRedeclaration); 13885 LookupName(R, S); 13886 if (R.isSingleResult()) { 13887 NamedDecl *PrevDecl = R.getFoundDecl(); 13888 if (PrevDecl->isTemplateParameter()) { 13889 // Maybe we will complain about the shadowed template parameter. 13890 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13891 // Just pretend that we didn't see the previous declaration. 13892 PrevDecl = nullptr; 13893 } else if (S->isDeclScope(PrevDecl)) { 13894 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13895 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13896 13897 // Recover by removing the name 13898 II = nullptr; 13899 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13900 D.setInvalidType(true); 13901 } 13902 } 13903 } 13904 13905 // Temporarily put parameter variables in the translation unit, not 13906 // the enclosing context. This prevents them from accidentally 13907 // looking like class members in C++. 13908 ParmVarDecl *New = 13909 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13910 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13911 13912 if (D.isInvalidType()) 13913 New->setInvalidDecl(); 13914 13915 assert(S->isFunctionPrototypeScope()); 13916 assert(S->getFunctionPrototypeDepth() >= 1); 13917 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13918 S->getNextFunctionPrototypeIndex()); 13919 13920 // Add the parameter declaration into this scope. 13921 S->AddDecl(New); 13922 if (II) 13923 IdResolver.AddDecl(New); 13924 13925 ProcessDeclAttributes(S, New, D); 13926 13927 if (D.getDeclSpec().isModulePrivateSpecified()) 13928 Diag(New->getLocation(), diag::err_module_private_local) 13929 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13930 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13931 13932 if (New->hasAttr<BlocksAttr>()) { 13933 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13934 } 13935 13936 if (getLangOpts().OpenCL) 13937 deduceOpenCLAddressSpace(New); 13938 13939 return New; 13940 } 13941 13942 /// Synthesizes a variable for a parameter arising from a 13943 /// typedef. 13944 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13945 SourceLocation Loc, 13946 QualType T) { 13947 /* FIXME: setting StartLoc == Loc. 13948 Would it be worth to modify callers so as to provide proper source 13949 location for the unnamed parameters, embedding the parameter's type? */ 13950 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13951 T, Context.getTrivialTypeSourceInfo(T, Loc), 13952 SC_None, nullptr); 13953 Param->setImplicit(); 13954 return Param; 13955 } 13956 13957 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13958 // Don't diagnose unused-parameter errors in template instantiations; we 13959 // will already have done so in the template itself. 13960 if (inTemplateInstantiation()) 13961 return; 13962 13963 for (const ParmVarDecl *Parameter : Parameters) { 13964 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13965 !Parameter->hasAttr<UnusedAttr>()) { 13966 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13967 << Parameter->getDeclName(); 13968 } 13969 } 13970 } 13971 13972 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13973 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13974 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13975 return; 13976 13977 // Warn if the return value is pass-by-value and larger than the specified 13978 // threshold. 13979 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13980 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13981 if (Size > LangOpts.NumLargeByValueCopy) 13982 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13983 } 13984 13985 // Warn if any parameter is pass-by-value and larger than the specified 13986 // threshold. 13987 for (const ParmVarDecl *Parameter : Parameters) { 13988 QualType T = Parameter->getType(); 13989 if (T->isDependentType() || !T.isPODType(Context)) 13990 continue; 13991 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13992 if (Size > LangOpts.NumLargeByValueCopy) 13993 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13994 << Parameter << Size; 13995 } 13996 } 13997 13998 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13999 SourceLocation NameLoc, IdentifierInfo *Name, 14000 QualType T, TypeSourceInfo *TSInfo, 14001 StorageClass SC) { 14002 // In ARC, infer a lifetime qualifier for appropriate parameter types. 14003 if (getLangOpts().ObjCAutoRefCount && 14004 T.getObjCLifetime() == Qualifiers::OCL_None && 14005 T->isObjCLifetimeType()) { 14006 14007 Qualifiers::ObjCLifetime lifetime; 14008 14009 // Special cases for arrays: 14010 // - if it's const, use __unsafe_unretained 14011 // - otherwise, it's an error 14012 if (T->isArrayType()) { 14013 if (!T.isConstQualified()) { 14014 if (DelayedDiagnostics.shouldDelayDiagnostics()) 14015 DelayedDiagnostics.add( 14016 sema::DelayedDiagnostic::makeForbiddenType( 14017 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 14018 else 14019 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 14020 << TSInfo->getTypeLoc().getSourceRange(); 14021 } 14022 lifetime = Qualifiers::OCL_ExplicitNone; 14023 } else { 14024 lifetime = T->getObjCARCImplicitLifetime(); 14025 } 14026 T = Context.getLifetimeQualifiedType(T, lifetime); 14027 } 14028 14029 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 14030 Context.getAdjustedParameterType(T), 14031 TSInfo, SC, nullptr); 14032 14033 // Make a note if we created a new pack in the scope of a lambda, so that 14034 // we know that references to that pack must also be expanded within the 14035 // lambda scope. 14036 if (New->isParameterPack()) 14037 if (auto *LSI = getEnclosingLambda()) 14038 LSI->LocalPacks.push_back(New); 14039 14040 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 14041 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14042 checkNonTrivialCUnion(New->getType(), New->getLocation(), 14043 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 14044 14045 // Parameters can not be abstract class types. 14046 // For record types, this is done by the AbstractClassUsageDiagnoser once 14047 // the class has been completely parsed. 14048 if (!CurContext->isRecord() && 14049 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 14050 AbstractParamType)) 14051 New->setInvalidDecl(); 14052 14053 // Parameter declarators cannot be interface types. All ObjC objects are 14054 // passed by reference. 14055 if (T->isObjCObjectType()) { 14056 SourceLocation TypeEndLoc = 14057 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 14058 Diag(NameLoc, 14059 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 14060 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 14061 T = Context.getObjCObjectPointerType(T); 14062 New->setType(T); 14063 } 14064 14065 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 14066 // duration shall not be qualified by an address-space qualifier." 14067 // Since all parameters have automatic store duration, they can not have 14068 // an address space. 14069 if (T.getAddressSpace() != LangAS::Default && 14070 // OpenCL allows function arguments declared to be an array of a type 14071 // to be qualified with an address space. 14072 !(getLangOpts().OpenCL && 14073 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 14074 Diag(NameLoc, diag::err_arg_with_address_space); 14075 New->setInvalidDecl(); 14076 } 14077 14078 // PPC MMA non-pointer types are not allowed as function argument types. 14079 if (Context.getTargetInfo().getTriple().isPPC64() && 14080 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 14081 New->setInvalidDecl(); 14082 } 14083 14084 return New; 14085 } 14086 14087 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 14088 SourceLocation LocAfterDecls) { 14089 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 14090 14091 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 14092 // for a K&R function. 14093 if (!FTI.hasPrototype) { 14094 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 14095 --i; 14096 if (FTI.Params[i].Param == nullptr) { 14097 SmallString<256> Code; 14098 llvm::raw_svector_ostream(Code) 14099 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 14100 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 14101 << FTI.Params[i].Ident 14102 << FixItHint::CreateInsertion(LocAfterDecls, Code); 14103 14104 // Implicitly declare the argument as type 'int' for lack of a better 14105 // type. 14106 AttributeFactory attrs; 14107 DeclSpec DS(attrs); 14108 const char* PrevSpec; // unused 14109 unsigned DiagID; // unused 14110 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 14111 DiagID, Context.getPrintingPolicy()); 14112 // Use the identifier location for the type source range. 14113 DS.SetRangeStart(FTI.Params[i].IdentLoc); 14114 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 14115 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 14116 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 14117 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 14118 } 14119 } 14120 } 14121 } 14122 14123 Decl * 14124 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 14125 MultiTemplateParamsArg TemplateParameterLists, 14126 SkipBodyInfo *SkipBody) { 14127 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 14128 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 14129 Scope *ParentScope = FnBodyScope->getParent(); 14130 14131 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 14132 // we define a non-templated function definition, we will create a declaration 14133 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 14134 // The base function declaration will have the equivalent of an `omp declare 14135 // variant` annotation which specifies the mangled definition as a 14136 // specialization function under the OpenMP context defined as part of the 14137 // `omp begin declare variant`. 14138 SmallVector<FunctionDecl *, 4> Bases; 14139 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 14140 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 14141 ParentScope, D, TemplateParameterLists, Bases); 14142 14143 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 14144 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 14145 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 14146 14147 if (!Bases.empty()) 14148 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 14149 14150 return Dcl; 14151 } 14152 14153 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 14154 Consumer.HandleInlineFunctionDefinition(D); 14155 } 14156 14157 static bool 14158 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 14159 const FunctionDecl *&PossiblePrototype) { 14160 // Don't warn about invalid declarations. 14161 if (FD->isInvalidDecl()) 14162 return false; 14163 14164 // Or declarations that aren't global. 14165 if (!FD->isGlobal()) 14166 return false; 14167 14168 // Don't warn about C++ member functions. 14169 if (isa<CXXMethodDecl>(FD)) 14170 return false; 14171 14172 // Don't warn about 'main'. 14173 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 14174 if (IdentifierInfo *II = FD->getIdentifier()) 14175 if (II->isStr("main") || II->isStr("efi_main")) 14176 return false; 14177 14178 // Don't warn about inline functions. 14179 if (FD->isInlined()) 14180 return false; 14181 14182 // Don't warn about function templates. 14183 if (FD->getDescribedFunctionTemplate()) 14184 return false; 14185 14186 // Don't warn about function template specializations. 14187 if (FD->isFunctionTemplateSpecialization()) 14188 return false; 14189 14190 // Don't warn for OpenCL kernels. 14191 if (FD->hasAttr<OpenCLKernelAttr>()) 14192 return false; 14193 14194 // Don't warn on explicitly deleted functions. 14195 if (FD->isDeleted()) 14196 return false; 14197 14198 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14199 Prev; Prev = Prev->getPreviousDecl()) { 14200 // Ignore any declarations that occur in function or method 14201 // scope, because they aren't visible from the header. 14202 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14203 continue; 14204 14205 PossiblePrototype = Prev; 14206 return Prev->getType()->isFunctionNoProtoType(); 14207 } 14208 14209 return true; 14210 } 14211 14212 void 14213 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14214 const FunctionDecl *EffectiveDefinition, 14215 SkipBodyInfo *SkipBody) { 14216 const FunctionDecl *Definition = EffectiveDefinition; 14217 if (!Definition && 14218 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14219 return; 14220 14221 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14222 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14223 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14224 // A merged copy of the same function, instantiated as a member of 14225 // the same class, is OK. 14226 if (declaresSameEntity(OrigFD, OrigDef) && 14227 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14228 cast<Decl>(FD->getLexicalDeclContext()))) 14229 return; 14230 } 14231 } 14232 } 14233 14234 if (canRedefineFunction(Definition, getLangOpts())) 14235 return; 14236 14237 // Don't emit an error when this is redefinition of a typo-corrected 14238 // definition. 14239 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14240 return; 14241 14242 // If we don't have a visible definition of the function, and it's inline or 14243 // a template, skip the new definition. 14244 if (SkipBody && !hasVisibleDefinition(Definition) && 14245 (Definition->getFormalLinkage() == InternalLinkage || 14246 Definition->isInlined() || 14247 Definition->getDescribedFunctionTemplate() || 14248 Definition->getNumTemplateParameterLists())) { 14249 SkipBody->ShouldSkip = true; 14250 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14251 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14252 makeMergedDefinitionVisible(TD); 14253 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14254 return; 14255 } 14256 14257 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14258 Definition->getStorageClass() == SC_Extern) 14259 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14260 << FD << getLangOpts().CPlusPlus; 14261 else 14262 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14263 14264 Diag(Definition->getLocation(), diag::note_previous_definition); 14265 FD->setInvalidDecl(); 14266 } 14267 14268 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14269 Sema &S) { 14270 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14271 14272 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14273 LSI->CallOperator = CallOperator; 14274 LSI->Lambda = LambdaClass; 14275 LSI->ReturnType = CallOperator->getReturnType(); 14276 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14277 14278 if (LCD == LCD_None) 14279 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14280 else if (LCD == LCD_ByCopy) 14281 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14282 else if (LCD == LCD_ByRef) 14283 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14284 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14285 14286 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14287 LSI->Mutable = !CallOperator->isConst(); 14288 14289 // Add the captures to the LSI so they can be noted as already 14290 // captured within tryCaptureVar. 14291 auto I = LambdaClass->field_begin(); 14292 for (const auto &C : LambdaClass->captures()) { 14293 if (C.capturesVariable()) { 14294 VarDecl *VD = C.getCapturedVar(); 14295 if (VD->isInitCapture()) 14296 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14297 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14298 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14299 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14300 /*EllipsisLoc*/C.isPackExpansion() 14301 ? C.getEllipsisLoc() : SourceLocation(), 14302 I->getType(), /*Invalid*/false); 14303 14304 } else if (C.capturesThis()) { 14305 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14306 C.getCaptureKind() == LCK_StarThis); 14307 } else { 14308 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14309 I->getType()); 14310 } 14311 ++I; 14312 } 14313 } 14314 14315 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14316 SkipBodyInfo *SkipBody) { 14317 if (!D) { 14318 // Parsing the function declaration failed in some way. Push on a fake scope 14319 // anyway so we can try to parse the function body. 14320 PushFunctionScope(); 14321 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14322 return D; 14323 } 14324 14325 FunctionDecl *FD = nullptr; 14326 14327 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14328 FD = FunTmpl->getTemplatedDecl(); 14329 else 14330 FD = cast<FunctionDecl>(D); 14331 14332 // Do not push if it is a lambda because one is already pushed when building 14333 // the lambda in ActOnStartOfLambdaDefinition(). 14334 if (!isLambdaCallOperator(FD)) 14335 PushExpressionEvaluationContext( 14336 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14337 : ExprEvalContexts.back().Context); 14338 14339 // Check for defining attributes before the check for redefinition. 14340 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14341 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14342 FD->dropAttr<AliasAttr>(); 14343 FD->setInvalidDecl(); 14344 } 14345 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14346 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14347 FD->dropAttr<IFuncAttr>(); 14348 FD->setInvalidDecl(); 14349 } 14350 14351 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14352 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14353 Ctor->isDefaultConstructor() && 14354 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14355 // If this is an MS ABI dllexport default constructor, instantiate any 14356 // default arguments. 14357 InstantiateDefaultCtorDefaultArgs(Ctor); 14358 } 14359 } 14360 14361 // See if this is a redefinition. If 'will have body' (or similar) is already 14362 // set, then these checks were already performed when it was set. 14363 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14364 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14365 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14366 14367 // If we're skipping the body, we're done. Don't enter the scope. 14368 if (SkipBody && SkipBody->ShouldSkip) 14369 return D; 14370 } 14371 14372 // Mark this function as "will have a body eventually". This lets users to 14373 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14374 // this function. 14375 FD->setWillHaveBody(); 14376 14377 // If we are instantiating a generic lambda call operator, push 14378 // a LambdaScopeInfo onto the function stack. But use the information 14379 // that's already been calculated (ActOnLambdaExpr) to prime the current 14380 // LambdaScopeInfo. 14381 // When the template operator is being specialized, the LambdaScopeInfo, 14382 // has to be properly restored so that tryCaptureVariable doesn't try 14383 // and capture any new variables. In addition when calculating potential 14384 // captures during transformation of nested lambdas, it is necessary to 14385 // have the LSI properly restored. 14386 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14387 assert(inTemplateInstantiation() && 14388 "There should be an active template instantiation on the stack " 14389 "when instantiating a generic lambda!"); 14390 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14391 } else { 14392 // Enter a new function scope 14393 PushFunctionScope(); 14394 } 14395 14396 // Builtin functions cannot be defined. 14397 if (unsigned BuiltinID = FD->getBuiltinID()) { 14398 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14399 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14400 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14401 FD->setInvalidDecl(); 14402 } 14403 } 14404 14405 // The return type of a function definition must be complete 14406 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14407 QualType ResultType = FD->getReturnType(); 14408 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14409 !FD->isInvalidDecl() && 14410 RequireCompleteType(FD->getLocation(), ResultType, 14411 diag::err_func_def_incomplete_result)) 14412 FD->setInvalidDecl(); 14413 14414 if (FnBodyScope) 14415 PushDeclContext(FnBodyScope, FD); 14416 14417 // Check the validity of our function parameters 14418 CheckParmsForFunctionDef(FD->parameters(), 14419 /*CheckParameterNames=*/true); 14420 14421 // Add non-parameter declarations already in the function to the current 14422 // scope. 14423 if (FnBodyScope) { 14424 for (Decl *NPD : FD->decls()) { 14425 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14426 if (!NonParmDecl) 14427 continue; 14428 assert(!isa<ParmVarDecl>(NonParmDecl) && 14429 "parameters should not be in newly created FD yet"); 14430 14431 // If the decl has a name, make it accessible in the current scope. 14432 if (NonParmDecl->getDeclName()) 14433 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14434 14435 // Similarly, dive into enums and fish their constants out, making them 14436 // accessible in this scope. 14437 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14438 for (auto *EI : ED->enumerators()) 14439 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14440 } 14441 } 14442 } 14443 14444 // Introduce our parameters into the function scope 14445 for (auto Param : FD->parameters()) { 14446 Param->setOwningFunction(FD); 14447 14448 // If this has an identifier, add it to the scope stack. 14449 if (Param->getIdentifier() && FnBodyScope) { 14450 CheckShadow(FnBodyScope, Param); 14451 14452 PushOnScopeChains(Param, FnBodyScope); 14453 } 14454 } 14455 14456 // Ensure that the function's exception specification is instantiated. 14457 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14458 ResolveExceptionSpec(D->getLocation(), FPT); 14459 14460 // dllimport cannot be applied to non-inline function definitions. 14461 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14462 !FD->isTemplateInstantiation()) { 14463 assert(!FD->hasAttr<DLLExportAttr>()); 14464 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14465 FD->setInvalidDecl(); 14466 return D; 14467 } 14468 // We want to attach documentation to original Decl (which might be 14469 // a function template). 14470 ActOnDocumentableDecl(D); 14471 if (getCurLexicalContext()->isObjCContainer() && 14472 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14473 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14474 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14475 14476 return D; 14477 } 14478 14479 /// Given the set of return statements within a function body, 14480 /// compute the variables that are subject to the named return value 14481 /// optimization. 14482 /// 14483 /// Each of the variables that is subject to the named return value 14484 /// optimization will be marked as NRVO variables in the AST, and any 14485 /// return statement that has a marked NRVO variable as its NRVO candidate can 14486 /// use the named return value optimization. 14487 /// 14488 /// This function applies a very simplistic algorithm for NRVO: if every return 14489 /// statement in the scope of a variable has the same NRVO candidate, that 14490 /// candidate is an NRVO variable. 14491 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14492 ReturnStmt **Returns = Scope->Returns.data(); 14493 14494 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14495 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14496 if (!NRVOCandidate->isNRVOVariable()) 14497 Returns[I]->setNRVOCandidate(nullptr); 14498 } 14499 } 14500 } 14501 14502 bool Sema::canDelayFunctionBody(const Declarator &D) { 14503 // We can't delay parsing the body of a constexpr function template (yet). 14504 if (D.getDeclSpec().hasConstexprSpecifier()) 14505 return false; 14506 14507 // We can't delay parsing the body of a function template with a deduced 14508 // return type (yet). 14509 if (D.getDeclSpec().hasAutoTypeSpec()) { 14510 // If the placeholder introduces a non-deduced trailing return type, 14511 // we can still delay parsing it. 14512 if (D.getNumTypeObjects()) { 14513 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14514 if (Outer.Kind == DeclaratorChunk::Function && 14515 Outer.Fun.hasTrailingReturnType()) { 14516 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14517 return Ty.isNull() || !Ty->isUndeducedType(); 14518 } 14519 } 14520 return false; 14521 } 14522 14523 return true; 14524 } 14525 14526 bool Sema::canSkipFunctionBody(Decl *D) { 14527 // We cannot skip the body of a function (or function template) which is 14528 // constexpr, since we may need to evaluate its body in order to parse the 14529 // rest of the file. 14530 // We cannot skip the body of a function with an undeduced return type, 14531 // because any callers of that function need to know the type. 14532 if (const FunctionDecl *FD = D->getAsFunction()) { 14533 if (FD->isConstexpr()) 14534 return false; 14535 // We can't simply call Type::isUndeducedType here, because inside template 14536 // auto can be deduced to a dependent type, which is not considered 14537 // "undeduced". 14538 if (FD->getReturnType()->getContainedDeducedType()) 14539 return false; 14540 } 14541 return Consumer.shouldSkipFunctionBody(D); 14542 } 14543 14544 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14545 if (!Decl) 14546 return nullptr; 14547 if (FunctionDecl *FD = Decl->getAsFunction()) 14548 FD->setHasSkippedBody(); 14549 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14550 MD->setHasSkippedBody(); 14551 return Decl; 14552 } 14553 14554 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14555 return ActOnFinishFunctionBody(D, BodyArg, false); 14556 } 14557 14558 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14559 /// body. 14560 class ExitFunctionBodyRAII { 14561 public: 14562 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14563 ~ExitFunctionBodyRAII() { 14564 if (!IsLambda) 14565 S.PopExpressionEvaluationContext(); 14566 } 14567 14568 private: 14569 Sema &S; 14570 bool IsLambda = false; 14571 }; 14572 14573 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14574 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14575 14576 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14577 if (EscapeInfo.count(BD)) 14578 return EscapeInfo[BD]; 14579 14580 bool R = false; 14581 const BlockDecl *CurBD = BD; 14582 14583 do { 14584 R = !CurBD->doesNotEscape(); 14585 if (R) 14586 break; 14587 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14588 } while (CurBD); 14589 14590 return EscapeInfo[BD] = R; 14591 }; 14592 14593 // If the location where 'self' is implicitly retained is inside a escaping 14594 // block, emit a diagnostic. 14595 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14596 S.ImplicitlyRetainedSelfLocs) 14597 if (IsOrNestedInEscapingBlock(P.second)) 14598 S.Diag(P.first, diag::warn_implicitly_retains_self) 14599 << FixItHint::CreateInsertion(P.first, "self->"); 14600 } 14601 14602 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14603 bool IsInstantiation) { 14604 FunctionScopeInfo *FSI = getCurFunction(); 14605 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14606 14607 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 14608 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14609 14610 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14611 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14612 14613 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14614 CheckCompletedCoroutineBody(FD, Body); 14615 14616 { 14617 // Do not call PopExpressionEvaluationContext() if it is a lambda because 14618 // one is already popped when finishing the lambda in BuildLambdaExpr(). 14619 // This is meant to pop the context added in ActOnStartOfFunctionDef(). 14620 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14621 14622 if (FD) { 14623 FD->setBody(Body); 14624 FD->setWillHaveBody(false); 14625 14626 if (getLangOpts().CPlusPlus14) { 14627 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14628 FD->getReturnType()->isUndeducedType()) { 14629 // If the function has a deduced result type but contains no 'return' 14630 // statements, the result type as written must be exactly 'auto', and 14631 // the deduced result type is 'void'. 14632 if (!FD->getReturnType()->getAs<AutoType>()) { 14633 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14634 << FD->getReturnType(); 14635 FD->setInvalidDecl(); 14636 } else { 14637 // Substitute 'void' for the 'auto' in the type. 14638 TypeLoc ResultType = getReturnTypeLoc(FD); 14639 Context.adjustDeducedFunctionResultType( 14640 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14641 } 14642 } 14643 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14644 // In C++11, we don't use 'auto' deduction rules for lambda call 14645 // operators because we don't support return type deduction. 14646 auto *LSI = getCurLambda(); 14647 if (LSI->HasImplicitReturnType) { 14648 deduceClosureReturnType(*LSI); 14649 14650 // C++11 [expr.prim.lambda]p4: 14651 // [...] if there are no return statements in the compound-statement 14652 // [the deduced type is] the type void 14653 QualType RetType = 14654 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14655 14656 // Update the return type to the deduced type. 14657 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14658 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14659 Proto->getExtProtoInfo())); 14660 } 14661 } 14662 14663 // If the function implicitly returns zero (like 'main') or is naked, 14664 // don't complain about missing return statements. 14665 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14666 WP.disableCheckFallThrough(); 14667 14668 // MSVC permits the use of pure specifier (=0) on function definition, 14669 // defined at class scope, warn about this non-standard construct. 14670 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14671 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14672 14673 if (!FD->isInvalidDecl()) { 14674 // Don't diagnose unused parameters of defaulted or deleted functions. 14675 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14676 DiagnoseUnusedParameters(FD->parameters()); 14677 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14678 FD->getReturnType(), FD); 14679 14680 // If this is a structor, we need a vtable. 14681 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14682 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14683 else if (CXXDestructorDecl *Destructor = 14684 dyn_cast<CXXDestructorDecl>(FD)) 14685 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14686 14687 // Try to apply the named return value optimization. We have to check 14688 // if we can do this here because lambdas keep return statements around 14689 // to deduce an implicit return type. 14690 if (FD->getReturnType()->isRecordType() && 14691 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14692 computeNRVO(Body, FSI); 14693 } 14694 14695 // GNU warning -Wmissing-prototypes: 14696 // Warn if a global function is defined without a previous 14697 // prototype declaration. This warning is issued even if the 14698 // definition itself provides a prototype. The aim is to detect 14699 // global functions that fail to be declared in header files. 14700 const FunctionDecl *PossiblePrototype = nullptr; 14701 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14702 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14703 14704 if (PossiblePrototype) { 14705 // We found a declaration that is not a prototype, 14706 // but that could be a zero-parameter prototype 14707 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14708 TypeLoc TL = TI->getTypeLoc(); 14709 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14710 Diag(PossiblePrototype->getLocation(), 14711 diag::note_declaration_not_a_prototype) 14712 << (FD->getNumParams() != 0) 14713 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( 14714 FTL.getRParenLoc(), "void") 14715 : FixItHint{}); 14716 } 14717 } else { 14718 // Returns true if the token beginning at this Loc is `const`. 14719 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14720 const LangOptions &LangOpts) { 14721 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14722 if (LocInfo.first.isInvalid()) 14723 return false; 14724 14725 bool Invalid = false; 14726 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14727 if (Invalid) 14728 return false; 14729 14730 if (LocInfo.second > Buffer.size()) 14731 return false; 14732 14733 const char *LexStart = Buffer.data() + LocInfo.second; 14734 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14735 14736 return StartTok.consume_front("const") && 14737 (StartTok.empty() || isWhitespace(StartTok[0]) || 14738 StartTok.startswith("/*") || StartTok.startswith("//")); 14739 }; 14740 14741 auto findBeginLoc = [&]() { 14742 // If the return type has `const` qualifier, we want to insert 14743 // `static` before `const` (and not before the typename). 14744 if ((FD->getReturnType()->isAnyPointerType() && 14745 FD->getReturnType()->getPointeeType().isConstQualified()) || 14746 FD->getReturnType().isConstQualified()) { 14747 // But only do this if we can determine where the `const` is. 14748 14749 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14750 getLangOpts())) 14751 14752 return FD->getBeginLoc(); 14753 } 14754 return FD->getTypeSpecStartLoc(); 14755 }; 14756 Diag(FD->getTypeSpecStartLoc(), 14757 diag::note_static_for_internal_linkage) 14758 << /* function */ 1 14759 << (FD->getStorageClass() == SC_None 14760 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14761 : FixItHint{}); 14762 } 14763 14764 // GNU warning -Wstrict-prototypes 14765 // Warn if K&R function is defined without a previous declaration. 14766 // This warning is issued only if the definition itself does not 14767 // provide a prototype. Only K&R definitions do not provide a 14768 // prototype. 14769 if (!FD->hasWrittenPrototype()) { 14770 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14771 TypeLoc TL = TI->getTypeLoc(); 14772 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14773 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14774 } 14775 } 14776 14777 // Warn on CPUDispatch with an actual body. 14778 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14779 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14780 if (!CmpndBody->body_empty()) 14781 Diag(CmpndBody->body_front()->getBeginLoc(), 14782 diag::warn_dispatch_body_ignored); 14783 14784 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14785 const CXXMethodDecl *KeyFunction; 14786 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14787 MD->isVirtual() && 14788 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14789 MD == KeyFunction->getCanonicalDecl()) { 14790 // Update the key-function state if necessary for this ABI. 14791 if (FD->isInlined() && 14792 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14793 Context.setNonKeyFunction(MD); 14794 14795 // If the newly-chosen key function is already defined, then we 14796 // need to mark the vtable as used retroactively. 14797 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14798 const FunctionDecl *Definition; 14799 if (KeyFunction && KeyFunction->isDefined(Definition)) 14800 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14801 } else { 14802 // We just defined they key function; mark the vtable as used. 14803 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14804 } 14805 } 14806 } 14807 14808 assert( 14809 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14810 "Function parsing confused"); 14811 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14812 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14813 MD->setBody(Body); 14814 if (!MD->isInvalidDecl()) { 14815 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14816 MD->getReturnType(), MD); 14817 14818 if (Body) 14819 computeNRVO(Body, FSI); 14820 } 14821 if (FSI->ObjCShouldCallSuper) { 14822 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14823 << MD->getSelector().getAsString(); 14824 FSI->ObjCShouldCallSuper = false; 14825 } 14826 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14827 const ObjCMethodDecl *InitMethod = nullptr; 14828 bool isDesignated = 14829 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14830 assert(isDesignated && InitMethod); 14831 (void)isDesignated; 14832 14833 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14834 auto IFace = MD->getClassInterface(); 14835 if (!IFace) 14836 return false; 14837 auto SuperD = IFace->getSuperClass(); 14838 if (!SuperD) 14839 return false; 14840 return SuperD->getIdentifier() == 14841 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14842 }; 14843 // Don't issue this warning for unavailable inits or direct subclasses 14844 // of NSObject. 14845 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14846 Diag(MD->getLocation(), 14847 diag::warn_objc_designated_init_missing_super_call); 14848 Diag(InitMethod->getLocation(), 14849 diag::note_objc_designated_init_marked_here); 14850 } 14851 FSI->ObjCWarnForNoDesignatedInitChain = false; 14852 } 14853 if (FSI->ObjCWarnForNoInitDelegation) { 14854 // Don't issue this warning for unavaialable inits. 14855 if (!MD->isUnavailable()) 14856 Diag(MD->getLocation(), 14857 diag::warn_objc_secondary_init_missing_init_call); 14858 FSI->ObjCWarnForNoInitDelegation = false; 14859 } 14860 14861 diagnoseImplicitlyRetainedSelf(*this); 14862 } else { 14863 // Parsing the function declaration failed in some way. Pop the fake scope 14864 // we pushed on. 14865 PopFunctionScopeInfo(ActivePolicy, dcl); 14866 return nullptr; 14867 } 14868 14869 if (Body && FSI->HasPotentialAvailabilityViolations) 14870 DiagnoseUnguardedAvailabilityViolations(dcl); 14871 14872 assert(!FSI->ObjCShouldCallSuper && 14873 "This should only be set for ObjC methods, which should have been " 14874 "handled in the block above."); 14875 14876 // Verify and clean out per-function state. 14877 if (Body && (!FD || !FD->isDefaulted())) { 14878 // C++ constructors that have function-try-blocks can't have return 14879 // statements in the handlers of that block. (C++ [except.handle]p14) 14880 // Verify this. 14881 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14882 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14883 14884 // Verify that gotos and switch cases don't jump into scopes illegally. 14885 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) 14886 DiagnoseInvalidJumps(Body); 14887 14888 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14889 if (!Destructor->getParent()->isDependentType()) 14890 CheckDestructor(Destructor); 14891 14892 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14893 Destructor->getParent()); 14894 } 14895 14896 // If any errors have occurred, clear out any temporaries that may have 14897 // been leftover. This ensures that these temporaries won't be picked up 14898 // for deletion in some later function. 14899 if (hasUncompilableErrorOccurred() || 14900 getDiagnostics().getSuppressAllDiagnostics()) { 14901 DiscardCleanupsInEvaluationContext(); 14902 } 14903 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { 14904 // Since the body is valid, issue any analysis-based warnings that are 14905 // enabled. 14906 ActivePolicy = &WP; 14907 } 14908 14909 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14910 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14911 FD->setInvalidDecl(); 14912 14913 if (FD && FD->hasAttr<NakedAttr>()) { 14914 for (const Stmt *S : Body->children()) { 14915 // Allow local register variables without initializer as they don't 14916 // require prologue. 14917 bool RegisterVariables = false; 14918 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14919 for (const auto *Decl : DS->decls()) { 14920 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14921 RegisterVariables = 14922 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14923 if (!RegisterVariables) 14924 break; 14925 } 14926 } 14927 } 14928 if (RegisterVariables) 14929 continue; 14930 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14931 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14932 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14933 FD->setInvalidDecl(); 14934 break; 14935 } 14936 } 14937 } 14938 14939 assert(ExprCleanupObjects.size() == 14940 ExprEvalContexts.back().NumCleanupObjects && 14941 "Leftover temporaries in function"); 14942 assert(!Cleanup.exprNeedsCleanups() && 14943 "Unaccounted cleanups in function"); 14944 assert(MaybeODRUseExprs.empty() && 14945 "Leftover expressions for odr-use checking"); 14946 } 14947 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop 14948 // the declaration context below. Otherwise, we're unable to transform 14949 // 'this' expressions when transforming immediate context functions. 14950 14951 if (!IsInstantiation) 14952 PopDeclContext(); 14953 14954 PopFunctionScopeInfo(ActivePolicy, dcl); 14955 // If any errors have occurred, clear out any temporaries that may have 14956 // been leftover. This ensures that these temporaries won't be picked up for 14957 // deletion in some later function. 14958 if (hasUncompilableErrorOccurred()) { 14959 DiscardCleanupsInEvaluationContext(); 14960 } 14961 14962 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice || 14963 !LangOpts.OMPTargetTriples.empty())) || 14964 LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14965 auto ES = getEmissionStatus(FD); 14966 if (ES == Sema::FunctionEmissionStatus::Emitted || 14967 ES == Sema::FunctionEmissionStatus::Unknown) 14968 DeclsToCheckForDeferredDiags.insert(FD); 14969 } 14970 14971 if (FD && !FD->isDeleted()) 14972 checkTypeSupport(FD->getType(), FD->getLocation(), FD); 14973 14974 return dcl; 14975 } 14976 14977 /// When we finish delayed parsing of an attribute, we must attach it to the 14978 /// relevant Decl. 14979 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14980 ParsedAttributes &Attrs) { 14981 // Always attach attributes to the underlying decl. 14982 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14983 D = TD->getTemplatedDecl(); 14984 ProcessDeclAttributeList(S, D, Attrs); 14985 14986 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14987 if (Method->isStatic()) 14988 checkThisInStaticMemberFunctionAttributes(Method); 14989 } 14990 14991 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14992 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14993 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14994 IdentifierInfo &II, Scope *S) { 14995 // Find the scope in which the identifier is injected and the corresponding 14996 // DeclContext. 14997 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14998 // In that case, we inject the declaration into the translation unit scope 14999 // instead. 15000 Scope *BlockScope = S; 15001 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 15002 BlockScope = BlockScope->getParent(); 15003 15004 Scope *ContextScope = BlockScope; 15005 while (!ContextScope->getEntity()) 15006 ContextScope = ContextScope->getParent(); 15007 ContextRAII SavedContext(*this, ContextScope->getEntity()); 15008 15009 // Before we produce a declaration for an implicitly defined 15010 // function, see whether there was a locally-scoped declaration of 15011 // this name as a function or variable. If so, use that 15012 // (non-visible) declaration, and complain about it. 15013 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 15014 if (ExternCPrev) { 15015 // We still need to inject the function into the enclosing block scope so 15016 // that later (non-call) uses can see it. 15017 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 15018 15019 // C89 footnote 38: 15020 // If in fact it is not defined as having type "function returning int", 15021 // the behavior is undefined. 15022 if (!isa<FunctionDecl>(ExternCPrev) || 15023 !Context.typesAreCompatible( 15024 cast<FunctionDecl>(ExternCPrev)->getType(), 15025 Context.getFunctionNoProtoType(Context.IntTy))) { 15026 Diag(Loc, diag::ext_use_out_of_scope_declaration) 15027 << ExternCPrev << !getLangOpts().C99; 15028 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 15029 return ExternCPrev; 15030 } 15031 } 15032 15033 // Extension in C99. Legal in C90, but warn about it. 15034 unsigned diag_id; 15035 if (II.getName().startswith("__builtin_")) 15036 diag_id = diag::warn_builtin_unknown; 15037 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 15038 else if (getLangOpts().OpenCL) 15039 diag_id = diag::err_opencl_implicit_function_decl; 15040 else if (getLangOpts().C99) 15041 diag_id = diag::ext_implicit_function_decl; 15042 else 15043 diag_id = diag::warn_implicit_function_decl; 15044 15045 TypoCorrection Corrected; 15046 // Because typo correction is expensive, only do it if the implicit 15047 // function declaration is going to be treated as an error. 15048 // 15049 // Perform the corection before issuing the main diagnostic, as some consumers 15050 // use typo-correction callbacks to enhance the main diagnostic. 15051 if (S && !ExternCPrev && 15052 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) { 15053 DeclFilterCCC<FunctionDecl> CCC{}; 15054 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 15055 S, nullptr, CCC, CTK_NonError); 15056 } 15057 15058 Diag(Loc, diag_id) << &II; 15059 if (Corrected) 15060 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 15061 /*ErrorRecovery*/ false); 15062 15063 // If we found a prior declaration of this function, don't bother building 15064 // another one. We've already pushed that one into scope, so there's nothing 15065 // more to do. 15066 if (ExternCPrev) 15067 return ExternCPrev; 15068 15069 // Set a Declarator for the implicit definition: int foo(); 15070 const char *Dummy; 15071 AttributeFactory attrFactory; 15072 DeclSpec DS(attrFactory); 15073 unsigned DiagID; 15074 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 15075 Context.getPrintingPolicy()); 15076 (void)Error; // Silence warning. 15077 assert(!Error && "Error setting up implicit decl!"); 15078 SourceLocation NoLoc; 15079 Declarator D(DS, DeclaratorContext::Block); 15080 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 15081 /*IsAmbiguous=*/false, 15082 /*LParenLoc=*/NoLoc, 15083 /*Params=*/nullptr, 15084 /*NumParams=*/0, 15085 /*EllipsisLoc=*/NoLoc, 15086 /*RParenLoc=*/NoLoc, 15087 /*RefQualifierIsLvalueRef=*/true, 15088 /*RefQualifierLoc=*/NoLoc, 15089 /*MutableLoc=*/NoLoc, EST_None, 15090 /*ESpecRange=*/SourceRange(), 15091 /*Exceptions=*/nullptr, 15092 /*ExceptionRanges=*/nullptr, 15093 /*NumExceptions=*/0, 15094 /*NoexceptExpr=*/nullptr, 15095 /*ExceptionSpecTokens=*/nullptr, 15096 /*DeclsInPrototype=*/None, Loc, 15097 Loc, D), 15098 std::move(DS.getAttributes()), SourceLocation()); 15099 D.SetIdentifier(&II, Loc); 15100 15101 // Insert this function into the enclosing block scope. 15102 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 15103 FD->setImplicit(); 15104 15105 AddKnownFunctionAttributes(FD); 15106 15107 return FD; 15108 } 15109 15110 /// If this function is a C++ replaceable global allocation function 15111 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 15112 /// adds any function attributes that we know a priori based on the standard. 15113 /// 15114 /// We need to check for duplicate attributes both here and where user-written 15115 /// attributes are applied to declarations. 15116 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 15117 FunctionDecl *FD) { 15118 if (FD->isInvalidDecl()) 15119 return; 15120 15121 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 15122 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 15123 return; 15124 15125 Optional<unsigned> AlignmentParam; 15126 bool IsNothrow = false; 15127 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 15128 return; 15129 15130 // C++2a [basic.stc.dynamic.allocation]p4: 15131 // An allocation function that has a non-throwing exception specification 15132 // indicates failure by returning a null pointer value. Any other allocation 15133 // function never returns a null pointer value and indicates failure only by 15134 // throwing an exception [...] 15135 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 15136 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 15137 15138 // C++2a [basic.stc.dynamic.allocation]p2: 15139 // An allocation function attempts to allocate the requested amount of 15140 // storage. [...] If the request succeeds, the value returned by a 15141 // replaceable allocation function is a [...] pointer value p0 different 15142 // from any previously returned value p1 [...] 15143 // 15144 // However, this particular information is being added in codegen, 15145 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 15146 15147 // C++2a [basic.stc.dynamic.allocation]p2: 15148 // An allocation function attempts to allocate the requested amount of 15149 // storage. If it is successful, it returns the address of the start of a 15150 // block of storage whose length in bytes is at least as large as the 15151 // requested size. 15152 if (!FD->hasAttr<AllocSizeAttr>()) { 15153 FD->addAttr(AllocSizeAttr::CreateImplicit( 15154 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 15155 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 15156 } 15157 15158 // C++2a [basic.stc.dynamic.allocation]p3: 15159 // For an allocation function [...], the pointer returned on a successful 15160 // call shall represent the address of storage that is aligned as follows: 15161 // (3.1) If the allocation function takes an argument of type 15162 // std::align_val_t, the storage will have the alignment 15163 // specified by the value of this argument. 15164 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 15165 FD->addAttr(AllocAlignAttr::CreateImplicit( 15166 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 15167 } 15168 15169 // FIXME: 15170 // C++2a [basic.stc.dynamic.allocation]p3: 15171 // For an allocation function [...], the pointer returned on a successful 15172 // call shall represent the address of storage that is aligned as follows: 15173 // (3.2) Otherwise, if the allocation function is named operator new[], 15174 // the storage is aligned for any object that does not have 15175 // new-extended alignment ([basic.align]) and is no larger than the 15176 // requested size. 15177 // (3.3) Otherwise, the storage is aligned for any object that does not 15178 // have new-extended alignment and is of the requested size. 15179 } 15180 15181 /// Adds any function attributes that we know a priori based on 15182 /// the declaration of this function. 15183 /// 15184 /// These attributes can apply both to implicitly-declared builtins 15185 /// (like __builtin___printf_chk) or to library-declared functions 15186 /// like NSLog or printf. 15187 /// 15188 /// We need to check for duplicate attributes both here and where user-written 15189 /// attributes are applied to declarations. 15190 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 15191 if (FD->isInvalidDecl()) 15192 return; 15193 15194 // If this is a built-in function, map its builtin attributes to 15195 // actual attributes. 15196 if (unsigned BuiltinID = FD->getBuiltinID()) { 15197 // Handle printf-formatting attributes. 15198 unsigned FormatIdx; 15199 bool HasVAListArg; 15200 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15201 if (!FD->hasAttr<FormatAttr>()) { 15202 const char *fmt = "printf"; 15203 unsigned int NumParams = FD->getNumParams(); 15204 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15205 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15206 fmt = "NSString"; 15207 FD->addAttr(FormatAttr::CreateImplicit(Context, 15208 &Context.Idents.get(fmt), 15209 FormatIdx+1, 15210 HasVAListArg ? 0 : FormatIdx+2, 15211 FD->getLocation())); 15212 } 15213 } 15214 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15215 HasVAListArg)) { 15216 if (!FD->hasAttr<FormatAttr>()) 15217 FD->addAttr(FormatAttr::CreateImplicit(Context, 15218 &Context.Idents.get("scanf"), 15219 FormatIdx+1, 15220 HasVAListArg ? 0 : FormatIdx+2, 15221 FD->getLocation())); 15222 } 15223 15224 // Handle automatically recognized callbacks. 15225 SmallVector<int, 4> Encoding; 15226 if (!FD->hasAttr<CallbackAttr>() && 15227 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15228 FD->addAttr(CallbackAttr::CreateImplicit( 15229 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15230 15231 // Mark const if we don't care about errno and that is the only thing 15232 // preventing the function from being const. This allows IRgen to use LLVM 15233 // intrinsics for such functions. 15234 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15235 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15236 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15237 15238 // We make "fma" on GNU or Windows const because we know it does not set 15239 // errno in those environments even though it could set errno based on the 15240 // C standard. 15241 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15242 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) && 15243 !FD->hasAttr<ConstAttr>()) { 15244 switch (BuiltinID) { 15245 case Builtin::BI__builtin_fma: 15246 case Builtin::BI__builtin_fmaf: 15247 case Builtin::BI__builtin_fmal: 15248 case Builtin::BIfma: 15249 case Builtin::BIfmaf: 15250 case Builtin::BIfmal: 15251 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15252 break; 15253 default: 15254 break; 15255 } 15256 } 15257 15258 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15259 !FD->hasAttr<ReturnsTwiceAttr>()) 15260 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15261 FD->getLocation())); 15262 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15263 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15264 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15265 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15266 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15267 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15268 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15269 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15270 // Add the appropriate attribute, depending on the CUDA compilation mode 15271 // and which target the builtin belongs to. For example, during host 15272 // compilation, aux builtins are __device__, while the rest are __host__. 15273 if (getLangOpts().CUDAIsDevice != 15274 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15275 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15276 else 15277 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15278 } 15279 15280 // Add known guaranteed alignment for allocation functions. 15281 switch (BuiltinID) { 15282 case Builtin::BIaligned_alloc: 15283 if (!FD->hasAttr<AllocAlignAttr>()) 15284 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 15285 FD->getLocation())); 15286 LLVM_FALLTHROUGH; 15287 case Builtin::BIcalloc: 15288 case Builtin::BImalloc: 15289 case Builtin::BImemalign: 15290 case Builtin::BIrealloc: 15291 case Builtin::BIstrdup: 15292 case Builtin::BIstrndup: { 15293 if (!FD->hasAttr<AssumeAlignedAttr>()) { 15294 unsigned NewAlign = Context.getTargetInfo().getNewAlign() / 15295 Context.getTargetInfo().getCharWidth(); 15296 IntegerLiteral *Alignment = IntegerLiteral::Create( 15297 Context, Context.MakeIntValue(NewAlign, Context.UnsignedIntTy), 15298 Context.UnsignedIntTy, FD->getLocation()); 15299 FD->addAttr(AssumeAlignedAttr::CreateImplicit( 15300 Context, Alignment, /*Offset=*/nullptr, FD->getLocation())); 15301 } 15302 break; 15303 } 15304 default: 15305 break; 15306 } 15307 } 15308 15309 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15310 15311 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15312 // throw, add an implicit nothrow attribute to any extern "C" function we come 15313 // across. 15314 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15315 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15316 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15317 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15318 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15319 } 15320 15321 IdentifierInfo *Name = FD->getIdentifier(); 15322 if (!Name) 15323 return; 15324 if ((!getLangOpts().CPlusPlus && 15325 FD->getDeclContext()->isTranslationUnit()) || 15326 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15327 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15328 LinkageSpecDecl::lang_c)) { 15329 // Okay: this could be a libc/libm/Objective-C function we know 15330 // about. 15331 } else 15332 return; 15333 15334 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15335 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15336 // target-specific builtins, perhaps? 15337 if (!FD->hasAttr<FormatAttr>()) 15338 FD->addAttr(FormatAttr::CreateImplicit(Context, 15339 &Context.Idents.get("printf"), 2, 15340 Name->isStr("vasprintf") ? 0 : 3, 15341 FD->getLocation())); 15342 } 15343 15344 if (Name->isStr("__CFStringMakeConstantString")) { 15345 // We already have a __builtin___CFStringMakeConstantString, 15346 // but builds that use -fno-constant-cfstrings don't go through that. 15347 if (!FD->hasAttr<FormatArgAttr>()) 15348 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15349 FD->getLocation())); 15350 } 15351 } 15352 15353 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15354 TypeSourceInfo *TInfo) { 15355 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15356 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15357 15358 if (!TInfo) { 15359 assert(D.isInvalidType() && "no declarator info for valid type"); 15360 TInfo = Context.getTrivialTypeSourceInfo(T); 15361 } 15362 15363 // Scope manipulation handled by caller. 15364 TypedefDecl *NewTD = 15365 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15366 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15367 15368 // Bail out immediately if we have an invalid declaration. 15369 if (D.isInvalidType()) { 15370 NewTD->setInvalidDecl(); 15371 return NewTD; 15372 } 15373 15374 if (D.getDeclSpec().isModulePrivateSpecified()) { 15375 if (CurContext->isFunctionOrMethod()) 15376 Diag(NewTD->getLocation(), diag::err_module_private_local) 15377 << 2 << NewTD 15378 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15379 << FixItHint::CreateRemoval( 15380 D.getDeclSpec().getModulePrivateSpecLoc()); 15381 else 15382 NewTD->setModulePrivate(); 15383 } 15384 15385 // C++ [dcl.typedef]p8: 15386 // If the typedef declaration defines an unnamed class (or 15387 // enum), the first typedef-name declared by the declaration 15388 // to be that class type (or enum type) is used to denote the 15389 // class type (or enum type) for linkage purposes only. 15390 // We need to check whether the type was declared in the declaration. 15391 switch (D.getDeclSpec().getTypeSpecType()) { 15392 case TST_enum: 15393 case TST_struct: 15394 case TST_interface: 15395 case TST_union: 15396 case TST_class: { 15397 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15398 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15399 break; 15400 } 15401 15402 default: 15403 break; 15404 } 15405 15406 return NewTD; 15407 } 15408 15409 /// Check that this is a valid underlying type for an enum declaration. 15410 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15411 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15412 QualType T = TI->getType(); 15413 15414 if (T->isDependentType()) 15415 return false; 15416 15417 // This doesn't use 'isIntegralType' despite the error message mentioning 15418 // integral type because isIntegralType would also allow enum types in C. 15419 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15420 if (BT->isInteger()) 15421 return false; 15422 15423 if (T->isBitIntType()) 15424 return false; 15425 15426 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15427 } 15428 15429 /// Check whether this is a valid redeclaration of a previous enumeration. 15430 /// \return true if the redeclaration was invalid. 15431 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15432 QualType EnumUnderlyingTy, bool IsFixed, 15433 const EnumDecl *Prev) { 15434 if (IsScoped != Prev->isScoped()) { 15435 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15436 << Prev->isScoped(); 15437 Diag(Prev->getLocation(), diag::note_previous_declaration); 15438 return true; 15439 } 15440 15441 if (IsFixed && Prev->isFixed()) { 15442 if (!EnumUnderlyingTy->isDependentType() && 15443 !Prev->getIntegerType()->isDependentType() && 15444 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15445 Prev->getIntegerType())) { 15446 // TODO: Highlight the underlying type of the redeclaration. 15447 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15448 << EnumUnderlyingTy << Prev->getIntegerType(); 15449 Diag(Prev->getLocation(), diag::note_previous_declaration) 15450 << Prev->getIntegerTypeRange(); 15451 return true; 15452 } 15453 } else if (IsFixed != Prev->isFixed()) { 15454 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15455 << Prev->isFixed(); 15456 Diag(Prev->getLocation(), diag::note_previous_declaration); 15457 return true; 15458 } 15459 15460 return false; 15461 } 15462 15463 /// Get diagnostic %select index for tag kind for 15464 /// redeclaration diagnostic message. 15465 /// WARNING: Indexes apply to particular diagnostics only! 15466 /// 15467 /// \returns diagnostic %select index. 15468 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15469 switch (Tag) { 15470 case TTK_Struct: return 0; 15471 case TTK_Interface: return 1; 15472 case TTK_Class: return 2; 15473 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15474 } 15475 } 15476 15477 /// Determine if tag kind is a class-key compatible with 15478 /// class for redeclaration (class, struct, or __interface). 15479 /// 15480 /// \returns true iff the tag kind is compatible. 15481 static bool isClassCompatTagKind(TagTypeKind Tag) 15482 { 15483 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15484 } 15485 15486 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15487 TagTypeKind TTK) { 15488 if (isa<TypedefDecl>(PrevDecl)) 15489 return NTK_Typedef; 15490 else if (isa<TypeAliasDecl>(PrevDecl)) 15491 return NTK_TypeAlias; 15492 else if (isa<ClassTemplateDecl>(PrevDecl)) 15493 return NTK_Template; 15494 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15495 return NTK_TypeAliasTemplate; 15496 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15497 return NTK_TemplateTemplateArgument; 15498 switch (TTK) { 15499 case TTK_Struct: 15500 case TTK_Interface: 15501 case TTK_Class: 15502 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15503 case TTK_Union: 15504 return NTK_NonUnion; 15505 case TTK_Enum: 15506 return NTK_NonEnum; 15507 } 15508 llvm_unreachable("invalid TTK"); 15509 } 15510 15511 /// Determine whether a tag with a given kind is acceptable 15512 /// as a redeclaration of the given tag declaration. 15513 /// 15514 /// \returns true if the new tag kind is acceptable, false otherwise. 15515 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15516 TagTypeKind NewTag, bool isDefinition, 15517 SourceLocation NewTagLoc, 15518 const IdentifierInfo *Name) { 15519 // C++ [dcl.type.elab]p3: 15520 // The class-key or enum keyword present in the 15521 // elaborated-type-specifier shall agree in kind with the 15522 // declaration to which the name in the elaborated-type-specifier 15523 // refers. This rule also applies to the form of 15524 // elaborated-type-specifier that declares a class-name or 15525 // friend class since it can be construed as referring to the 15526 // definition of the class. Thus, in any 15527 // elaborated-type-specifier, the enum keyword shall be used to 15528 // refer to an enumeration (7.2), the union class-key shall be 15529 // used to refer to a union (clause 9), and either the class or 15530 // struct class-key shall be used to refer to a class (clause 9) 15531 // declared using the class or struct class-key. 15532 TagTypeKind OldTag = Previous->getTagKind(); 15533 if (OldTag != NewTag && 15534 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15535 return false; 15536 15537 // Tags are compatible, but we might still want to warn on mismatched tags. 15538 // Non-class tags can't be mismatched at this point. 15539 if (!isClassCompatTagKind(NewTag)) 15540 return true; 15541 15542 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15543 // by our warning analysis. We don't want to warn about mismatches with (eg) 15544 // declarations in system headers that are designed to be specialized, but if 15545 // a user asks us to warn, we should warn if their code contains mismatched 15546 // declarations. 15547 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15548 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15549 Loc); 15550 }; 15551 if (IsIgnoredLoc(NewTagLoc)) 15552 return true; 15553 15554 auto IsIgnored = [&](const TagDecl *Tag) { 15555 return IsIgnoredLoc(Tag->getLocation()); 15556 }; 15557 while (IsIgnored(Previous)) { 15558 Previous = Previous->getPreviousDecl(); 15559 if (!Previous) 15560 return true; 15561 OldTag = Previous->getTagKind(); 15562 } 15563 15564 bool isTemplate = false; 15565 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15566 isTemplate = Record->getDescribedClassTemplate(); 15567 15568 if (inTemplateInstantiation()) { 15569 if (OldTag != NewTag) { 15570 // In a template instantiation, do not offer fix-its for tag mismatches 15571 // since they usually mess up the template instead of fixing the problem. 15572 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15573 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15574 << getRedeclDiagFromTagKind(OldTag); 15575 // FIXME: Note previous location? 15576 } 15577 return true; 15578 } 15579 15580 if (isDefinition) { 15581 // On definitions, check all previous tags and issue a fix-it for each 15582 // one that doesn't match the current tag. 15583 if (Previous->getDefinition()) { 15584 // Don't suggest fix-its for redefinitions. 15585 return true; 15586 } 15587 15588 bool previousMismatch = false; 15589 for (const TagDecl *I : Previous->redecls()) { 15590 if (I->getTagKind() != NewTag) { 15591 // Ignore previous declarations for which the warning was disabled. 15592 if (IsIgnored(I)) 15593 continue; 15594 15595 if (!previousMismatch) { 15596 previousMismatch = true; 15597 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15598 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15599 << getRedeclDiagFromTagKind(I->getTagKind()); 15600 } 15601 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15602 << getRedeclDiagFromTagKind(NewTag) 15603 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15604 TypeWithKeyword::getTagTypeKindName(NewTag)); 15605 } 15606 } 15607 return true; 15608 } 15609 15610 // Identify the prevailing tag kind: this is the kind of the definition (if 15611 // there is a non-ignored definition), or otherwise the kind of the prior 15612 // (non-ignored) declaration. 15613 const TagDecl *PrevDef = Previous->getDefinition(); 15614 if (PrevDef && IsIgnored(PrevDef)) 15615 PrevDef = nullptr; 15616 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15617 if (Redecl->getTagKind() != NewTag) { 15618 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15619 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15620 << getRedeclDiagFromTagKind(OldTag); 15621 Diag(Redecl->getLocation(), diag::note_previous_use); 15622 15623 // If there is a previous definition, suggest a fix-it. 15624 if (PrevDef) { 15625 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15626 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15627 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15628 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15629 } 15630 } 15631 15632 return true; 15633 } 15634 15635 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15636 /// from an outer enclosing namespace or file scope inside a friend declaration. 15637 /// This should provide the commented out code in the following snippet: 15638 /// namespace N { 15639 /// struct X; 15640 /// namespace M { 15641 /// struct Y { friend struct /*N::*/ X; }; 15642 /// } 15643 /// } 15644 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15645 SourceLocation NameLoc) { 15646 // While the decl is in a namespace, do repeated lookup of that name and see 15647 // if we get the same namespace back. If we do not, continue until 15648 // translation unit scope, at which point we have a fully qualified NNS. 15649 SmallVector<IdentifierInfo *, 4> Namespaces; 15650 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15651 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15652 // This tag should be declared in a namespace, which can only be enclosed by 15653 // other namespaces. Bail if there's an anonymous namespace in the chain. 15654 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15655 if (!Namespace || Namespace->isAnonymousNamespace()) 15656 return FixItHint(); 15657 IdentifierInfo *II = Namespace->getIdentifier(); 15658 Namespaces.push_back(II); 15659 NamedDecl *Lookup = SemaRef.LookupSingleName( 15660 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15661 if (Lookup == Namespace) 15662 break; 15663 } 15664 15665 // Once we have all the namespaces, reverse them to go outermost first, and 15666 // build an NNS. 15667 SmallString<64> Insertion; 15668 llvm::raw_svector_ostream OS(Insertion); 15669 if (DC->isTranslationUnit()) 15670 OS << "::"; 15671 std::reverse(Namespaces.begin(), Namespaces.end()); 15672 for (auto *II : Namespaces) 15673 OS << II->getName() << "::"; 15674 return FixItHint::CreateInsertion(NameLoc, Insertion); 15675 } 15676 15677 /// Determine whether a tag originally declared in context \p OldDC can 15678 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15679 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15680 /// using-declaration). 15681 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15682 DeclContext *NewDC) { 15683 OldDC = OldDC->getRedeclContext(); 15684 NewDC = NewDC->getRedeclContext(); 15685 15686 if (OldDC->Equals(NewDC)) 15687 return true; 15688 15689 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15690 // encloses the other). 15691 if (S.getLangOpts().MSVCCompat && 15692 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15693 return true; 15694 15695 return false; 15696 } 15697 15698 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15699 /// former case, Name will be non-null. In the later case, Name will be null. 15700 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15701 /// reference/declaration/definition of a tag. 15702 /// 15703 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15704 /// trailing-type-specifier) other than one in an alias-declaration. 15705 /// 15706 /// \param SkipBody If non-null, will be set to indicate if the caller should 15707 /// skip the definition of this tag and treat it as if it were a declaration. 15708 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15709 SourceLocation KWLoc, CXXScopeSpec &SS, 15710 IdentifierInfo *Name, SourceLocation NameLoc, 15711 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15712 SourceLocation ModulePrivateLoc, 15713 MultiTemplateParamsArg TemplateParameterLists, 15714 bool &OwnedDecl, bool &IsDependent, 15715 SourceLocation ScopedEnumKWLoc, 15716 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15717 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15718 SkipBodyInfo *SkipBody) { 15719 // If this is not a definition, it must have a name. 15720 IdentifierInfo *OrigName = Name; 15721 assert((Name != nullptr || TUK == TUK_Definition) && 15722 "Nameless record must be a definition!"); 15723 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15724 15725 OwnedDecl = false; 15726 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15727 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15728 15729 // FIXME: Check member specializations more carefully. 15730 bool isMemberSpecialization = false; 15731 bool Invalid = false; 15732 15733 // We only need to do this matching if we have template parameters 15734 // or a scope specifier, which also conveniently avoids this work 15735 // for non-C++ cases. 15736 if (TemplateParameterLists.size() > 0 || 15737 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15738 if (TemplateParameterList *TemplateParams = 15739 MatchTemplateParametersToScopeSpecifier( 15740 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15741 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15742 if (Kind == TTK_Enum) { 15743 Diag(KWLoc, diag::err_enum_template); 15744 return nullptr; 15745 } 15746 15747 if (TemplateParams->size() > 0) { 15748 // This is a declaration or definition of a class template (which may 15749 // be a member of another template). 15750 15751 if (Invalid) 15752 return nullptr; 15753 15754 OwnedDecl = false; 15755 DeclResult Result = CheckClassTemplate( 15756 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15757 AS, ModulePrivateLoc, 15758 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15759 TemplateParameterLists.data(), SkipBody); 15760 return Result.get(); 15761 } else { 15762 // The "template<>" header is extraneous. 15763 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15764 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15765 isMemberSpecialization = true; 15766 } 15767 } 15768 15769 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15770 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15771 return nullptr; 15772 } 15773 15774 // Figure out the underlying type if this a enum declaration. We need to do 15775 // this early, because it's needed to detect if this is an incompatible 15776 // redeclaration. 15777 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15778 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15779 15780 if (Kind == TTK_Enum) { 15781 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15782 // No underlying type explicitly specified, or we failed to parse the 15783 // type, default to int. 15784 EnumUnderlying = Context.IntTy.getTypePtr(); 15785 } else if (UnderlyingType.get()) { 15786 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15787 // integral type; any cv-qualification is ignored. 15788 TypeSourceInfo *TI = nullptr; 15789 GetTypeFromParser(UnderlyingType.get(), &TI); 15790 EnumUnderlying = TI; 15791 15792 if (CheckEnumUnderlyingType(TI)) 15793 // Recover by falling back to int. 15794 EnumUnderlying = Context.IntTy.getTypePtr(); 15795 15796 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15797 UPPC_FixedUnderlyingType)) 15798 EnumUnderlying = Context.IntTy.getTypePtr(); 15799 15800 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15801 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15802 // of 'int'. However, if this is an unfixed forward declaration, don't set 15803 // the underlying type unless the user enables -fms-compatibility. This 15804 // makes unfixed forward declared enums incomplete and is more conforming. 15805 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15806 EnumUnderlying = Context.IntTy.getTypePtr(); 15807 } 15808 } 15809 15810 DeclContext *SearchDC = CurContext; 15811 DeclContext *DC = CurContext; 15812 bool isStdBadAlloc = false; 15813 bool isStdAlignValT = false; 15814 15815 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15816 if (TUK == TUK_Friend || TUK == TUK_Reference) 15817 Redecl = NotForRedeclaration; 15818 15819 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15820 /// implemented asks for structural equivalence checking, the returned decl 15821 /// here is passed back to the parser, allowing the tag body to be parsed. 15822 auto createTagFromNewDecl = [&]() -> TagDecl * { 15823 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15824 // If there is an identifier, use the location of the identifier as the 15825 // location of the decl, otherwise use the location of the struct/union 15826 // keyword. 15827 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15828 TagDecl *New = nullptr; 15829 15830 if (Kind == TTK_Enum) { 15831 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15832 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15833 // If this is an undefined enum, bail. 15834 if (TUK != TUK_Definition && !Invalid) 15835 return nullptr; 15836 if (EnumUnderlying) { 15837 EnumDecl *ED = cast<EnumDecl>(New); 15838 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15839 ED->setIntegerTypeSourceInfo(TI); 15840 else 15841 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15842 ED->setPromotionType(ED->getIntegerType()); 15843 } 15844 } else { // struct/union 15845 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15846 nullptr); 15847 } 15848 15849 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15850 // Add alignment attributes if necessary; these attributes are checked 15851 // when the ASTContext lays out the structure. 15852 // 15853 // It is important for implementing the correct semantics that this 15854 // happen here (in ActOnTag). The #pragma pack stack is 15855 // maintained as a result of parser callbacks which can occur at 15856 // many points during the parsing of a struct declaration (because 15857 // the #pragma tokens are effectively skipped over during the 15858 // parsing of the struct). 15859 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15860 AddAlignmentAttributesForRecord(RD); 15861 AddMsStructLayoutForRecord(RD); 15862 } 15863 } 15864 New->setLexicalDeclContext(CurContext); 15865 return New; 15866 }; 15867 15868 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15869 if (Name && SS.isNotEmpty()) { 15870 // We have a nested-name tag ('struct foo::bar'). 15871 15872 // Check for invalid 'foo::'. 15873 if (SS.isInvalid()) { 15874 Name = nullptr; 15875 goto CreateNewDecl; 15876 } 15877 15878 // If this is a friend or a reference to a class in a dependent 15879 // context, don't try to make a decl for it. 15880 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15881 DC = computeDeclContext(SS, false); 15882 if (!DC) { 15883 IsDependent = true; 15884 return nullptr; 15885 } 15886 } else { 15887 DC = computeDeclContext(SS, true); 15888 if (!DC) { 15889 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15890 << SS.getRange(); 15891 return nullptr; 15892 } 15893 } 15894 15895 if (RequireCompleteDeclContext(SS, DC)) 15896 return nullptr; 15897 15898 SearchDC = DC; 15899 // Look-up name inside 'foo::'. 15900 LookupQualifiedName(Previous, DC); 15901 15902 if (Previous.isAmbiguous()) 15903 return nullptr; 15904 15905 if (Previous.empty()) { 15906 // Name lookup did not find anything. However, if the 15907 // nested-name-specifier refers to the current instantiation, 15908 // and that current instantiation has any dependent base 15909 // classes, we might find something at instantiation time: treat 15910 // this as a dependent elaborated-type-specifier. 15911 // But this only makes any sense for reference-like lookups. 15912 if (Previous.wasNotFoundInCurrentInstantiation() && 15913 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15914 IsDependent = true; 15915 return nullptr; 15916 } 15917 15918 // A tag 'foo::bar' must already exist. 15919 Diag(NameLoc, diag::err_not_tag_in_scope) 15920 << Kind << Name << DC << SS.getRange(); 15921 Name = nullptr; 15922 Invalid = true; 15923 goto CreateNewDecl; 15924 } 15925 } else if (Name) { 15926 // C++14 [class.mem]p14: 15927 // If T is the name of a class, then each of the following shall have a 15928 // name different from T: 15929 // -- every member of class T that is itself a type 15930 if (TUK != TUK_Reference && TUK != TUK_Friend && 15931 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15932 return nullptr; 15933 15934 // If this is a named struct, check to see if there was a previous forward 15935 // declaration or definition. 15936 // FIXME: We're looking into outer scopes here, even when we 15937 // shouldn't be. Doing so can result in ambiguities that we 15938 // shouldn't be diagnosing. 15939 LookupName(Previous, S); 15940 15941 // When declaring or defining a tag, ignore ambiguities introduced 15942 // by types using'ed into this scope. 15943 if (Previous.isAmbiguous() && 15944 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15945 LookupResult::Filter F = Previous.makeFilter(); 15946 while (F.hasNext()) { 15947 NamedDecl *ND = F.next(); 15948 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15949 SearchDC->getRedeclContext())) 15950 F.erase(); 15951 } 15952 F.done(); 15953 } 15954 15955 // C++11 [namespace.memdef]p3: 15956 // If the name in a friend declaration is neither qualified nor 15957 // a template-id and the declaration is a function or an 15958 // elaborated-type-specifier, the lookup to determine whether 15959 // the entity has been previously declared shall not consider 15960 // any scopes outside the innermost enclosing namespace. 15961 // 15962 // MSVC doesn't implement the above rule for types, so a friend tag 15963 // declaration may be a redeclaration of a type declared in an enclosing 15964 // scope. They do implement this rule for friend functions. 15965 // 15966 // Does it matter that this should be by scope instead of by 15967 // semantic context? 15968 if (!Previous.empty() && TUK == TUK_Friend) { 15969 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15970 LookupResult::Filter F = Previous.makeFilter(); 15971 bool FriendSawTagOutsideEnclosingNamespace = false; 15972 while (F.hasNext()) { 15973 NamedDecl *ND = F.next(); 15974 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15975 if (DC->isFileContext() && 15976 !EnclosingNS->Encloses(ND->getDeclContext())) { 15977 if (getLangOpts().MSVCCompat) 15978 FriendSawTagOutsideEnclosingNamespace = true; 15979 else 15980 F.erase(); 15981 } 15982 } 15983 F.done(); 15984 15985 // Diagnose this MSVC extension in the easy case where lookup would have 15986 // unambiguously found something outside the enclosing namespace. 15987 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15988 NamedDecl *ND = Previous.getFoundDecl(); 15989 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15990 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15991 } 15992 } 15993 15994 // Note: there used to be some attempt at recovery here. 15995 if (Previous.isAmbiguous()) 15996 return nullptr; 15997 15998 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15999 // FIXME: This makes sure that we ignore the contexts associated 16000 // with C structs, unions, and enums when looking for a matching 16001 // tag declaration or definition. See the similar lookup tweak 16002 // in Sema::LookupName; is there a better way to deal with this? 16003 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 16004 SearchDC = SearchDC->getParent(); 16005 } 16006 } 16007 16008 if (Previous.isSingleResult() && 16009 Previous.getFoundDecl()->isTemplateParameter()) { 16010 // Maybe we will complain about the shadowed template parameter. 16011 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 16012 // Just pretend that we didn't see the previous declaration. 16013 Previous.clear(); 16014 } 16015 16016 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 16017 DC->Equals(getStdNamespace())) { 16018 if (Name->isStr("bad_alloc")) { 16019 // This is a declaration of or a reference to "std::bad_alloc". 16020 isStdBadAlloc = true; 16021 16022 // If std::bad_alloc has been implicitly declared (but made invisible to 16023 // name lookup), fill in this implicit declaration as the previous 16024 // declaration, so that the declarations get chained appropriately. 16025 if (Previous.empty() && StdBadAlloc) 16026 Previous.addDecl(getStdBadAlloc()); 16027 } else if (Name->isStr("align_val_t")) { 16028 isStdAlignValT = true; 16029 if (Previous.empty() && StdAlignValT) 16030 Previous.addDecl(getStdAlignValT()); 16031 } 16032 } 16033 16034 // If we didn't find a previous declaration, and this is a reference 16035 // (or friend reference), move to the correct scope. In C++, we 16036 // also need to do a redeclaration lookup there, just in case 16037 // there's a shadow friend decl. 16038 if (Name && Previous.empty() && 16039 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 16040 if (Invalid) goto CreateNewDecl; 16041 assert(SS.isEmpty()); 16042 16043 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 16044 // C++ [basic.scope.pdecl]p5: 16045 // -- for an elaborated-type-specifier of the form 16046 // 16047 // class-key identifier 16048 // 16049 // if the elaborated-type-specifier is used in the 16050 // decl-specifier-seq or parameter-declaration-clause of a 16051 // function defined in namespace scope, the identifier is 16052 // declared as a class-name in the namespace that contains 16053 // the declaration; otherwise, except as a friend 16054 // declaration, the identifier is declared in the smallest 16055 // non-class, non-function-prototype scope that contains the 16056 // declaration. 16057 // 16058 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 16059 // C structs and unions. 16060 // 16061 // It is an error in C++ to declare (rather than define) an enum 16062 // type, including via an elaborated type specifier. We'll 16063 // diagnose that later; for now, declare the enum in the same 16064 // scope as we would have picked for any other tag type. 16065 // 16066 // GNU C also supports this behavior as part of its incomplete 16067 // enum types extension, while GNU C++ does not. 16068 // 16069 // Find the context where we'll be declaring the tag. 16070 // FIXME: We would like to maintain the current DeclContext as the 16071 // lexical context, 16072 SearchDC = getTagInjectionContext(SearchDC); 16073 16074 // Find the scope where we'll be declaring the tag. 16075 S = getTagInjectionScope(S, getLangOpts()); 16076 } else { 16077 assert(TUK == TUK_Friend); 16078 // C++ [namespace.memdef]p3: 16079 // If a friend declaration in a non-local class first declares a 16080 // class or function, the friend class or function is a member of 16081 // the innermost enclosing namespace. 16082 SearchDC = SearchDC->getEnclosingNamespaceContext(); 16083 } 16084 16085 // In C++, we need to do a redeclaration lookup to properly 16086 // diagnose some problems. 16087 // FIXME: redeclaration lookup is also used (with and without C++) to find a 16088 // hidden declaration so that we don't get ambiguity errors when using a 16089 // type declared by an elaborated-type-specifier. In C that is not correct 16090 // and we should instead merge compatible types found by lookup. 16091 if (getLangOpts().CPlusPlus) { 16092 // FIXME: This can perform qualified lookups into function contexts, 16093 // which are meaningless. 16094 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16095 LookupQualifiedName(Previous, SearchDC); 16096 } else { 16097 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16098 LookupName(Previous, S); 16099 } 16100 } 16101 16102 // If we have a known previous declaration to use, then use it. 16103 if (Previous.empty() && SkipBody && SkipBody->Previous) 16104 Previous.addDecl(SkipBody->Previous); 16105 16106 if (!Previous.empty()) { 16107 NamedDecl *PrevDecl = Previous.getFoundDecl(); 16108 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 16109 16110 // It's okay to have a tag decl in the same scope as a typedef 16111 // which hides a tag decl in the same scope. Finding this 16112 // with a redeclaration lookup can only actually happen in C++. 16113 // 16114 // This is also okay for elaborated-type-specifiers, which is 16115 // technically forbidden by the current standard but which is 16116 // okay according to the likely resolution of an open issue; 16117 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 16118 if (getLangOpts().CPlusPlus) { 16119 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16120 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 16121 TagDecl *Tag = TT->getDecl(); 16122 if (Tag->getDeclName() == Name && 16123 Tag->getDeclContext()->getRedeclContext() 16124 ->Equals(TD->getDeclContext()->getRedeclContext())) { 16125 PrevDecl = Tag; 16126 Previous.clear(); 16127 Previous.addDecl(Tag); 16128 Previous.resolveKind(); 16129 } 16130 } 16131 } 16132 } 16133 16134 // If this is a redeclaration of a using shadow declaration, it must 16135 // declare a tag in the same context. In MSVC mode, we allow a 16136 // redefinition if either context is within the other. 16137 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 16138 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 16139 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 16140 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 16141 !(OldTag && isAcceptableTagRedeclContext( 16142 *this, OldTag->getDeclContext(), SearchDC))) { 16143 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 16144 Diag(Shadow->getTargetDecl()->getLocation(), 16145 diag::note_using_decl_target); 16146 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 16147 << 0; 16148 // Recover by ignoring the old declaration. 16149 Previous.clear(); 16150 goto CreateNewDecl; 16151 } 16152 } 16153 16154 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 16155 // If this is a use of a previous tag, or if the tag is already declared 16156 // in the same scope (so that the definition/declaration completes or 16157 // rementions the tag), reuse the decl. 16158 if (TUK == TUK_Reference || TUK == TUK_Friend || 16159 isDeclInScope(DirectPrevDecl, SearchDC, S, 16160 SS.isNotEmpty() || isMemberSpecialization)) { 16161 // Make sure that this wasn't declared as an enum and now used as a 16162 // struct or something similar. 16163 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 16164 TUK == TUK_Definition, KWLoc, 16165 Name)) { 16166 bool SafeToContinue 16167 = (PrevTagDecl->getTagKind() != TTK_Enum && 16168 Kind != TTK_Enum); 16169 if (SafeToContinue) 16170 Diag(KWLoc, diag::err_use_with_wrong_tag) 16171 << Name 16172 << FixItHint::CreateReplacement(SourceRange(KWLoc), 16173 PrevTagDecl->getKindName()); 16174 else 16175 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 16176 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 16177 16178 if (SafeToContinue) 16179 Kind = PrevTagDecl->getTagKind(); 16180 else { 16181 // Recover by making this an anonymous redefinition. 16182 Name = nullptr; 16183 Previous.clear(); 16184 Invalid = true; 16185 } 16186 } 16187 16188 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 16189 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 16190 if (TUK == TUK_Reference || TUK == TUK_Friend) 16191 return PrevTagDecl; 16192 16193 QualType EnumUnderlyingTy; 16194 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16195 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 16196 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 16197 EnumUnderlyingTy = QualType(T, 0); 16198 16199 // All conflicts with previous declarations are recovered by 16200 // returning the previous declaration, unless this is a definition, 16201 // in which case we want the caller to bail out. 16202 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 16203 ScopedEnum, EnumUnderlyingTy, 16204 IsFixed, PrevEnum)) 16205 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 16206 } 16207 16208 // C++11 [class.mem]p1: 16209 // A member shall not be declared twice in the member-specification, 16210 // except that a nested class or member class template can be declared 16211 // and then later defined. 16212 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 16213 S->isDeclScope(PrevDecl)) { 16214 Diag(NameLoc, diag::ext_member_redeclared); 16215 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 16216 } 16217 16218 if (!Invalid) { 16219 // If this is a use, just return the declaration we found, unless 16220 // we have attributes. 16221 if (TUK == TUK_Reference || TUK == TUK_Friend) { 16222 if (!Attrs.empty()) { 16223 // FIXME: Diagnose these attributes. For now, we create a new 16224 // declaration to hold them. 16225 } else if (TUK == TUK_Reference && 16226 (PrevTagDecl->getFriendObjectKind() == 16227 Decl::FOK_Undeclared || 16228 PrevDecl->getOwningModule() != getCurrentModule()) && 16229 SS.isEmpty()) { 16230 // This declaration is a reference to an existing entity, but 16231 // has different visibility from that entity: it either makes 16232 // a friend visible or it makes a type visible in a new module. 16233 // In either case, create a new declaration. We only do this if 16234 // the declaration would have meant the same thing if no prior 16235 // declaration were found, that is, if it was found in the same 16236 // scope where we would have injected a declaration. 16237 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16238 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16239 return PrevTagDecl; 16240 // This is in the injected scope, create a new declaration in 16241 // that scope. 16242 S = getTagInjectionScope(S, getLangOpts()); 16243 } else { 16244 return PrevTagDecl; 16245 } 16246 } 16247 16248 // Diagnose attempts to redefine a tag. 16249 if (TUK == TUK_Definition) { 16250 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16251 // If we're defining a specialization and the previous definition 16252 // is from an implicit instantiation, don't emit an error 16253 // here; we'll catch this in the general case below. 16254 bool IsExplicitSpecializationAfterInstantiation = false; 16255 if (isMemberSpecialization) { 16256 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16257 IsExplicitSpecializationAfterInstantiation = 16258 RD->getTemplateSpecializationKind() != 16259 TSK_ExplicitSpecialization; 16260 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16261 IsExplicitSpecializationAfterInstantiation = 16262 ED->getTemplateSpecializationKind() != 16263 TSK_ExplicitSpecialization; 16264 } 16265 16266 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16267 // not keep more that one definition around (merge them). However, 16268 // ensure the decl passes the structural compatibility check in 16269 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16270 NamedDecl *Hidden = nullptr; 16271 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16272 // There is a definition of this tag, but it is not visible. We 16273 // explicitly make use of C++'s one definition rule here, and 16274 // assume that this definition is identical to the hidden one 16275 // we already have. Make the existing definition visible and 16276 // use it in place of this one. 16277 if (!getLangOpts().CPlusPlus) { 16278 // Postpone making the old definition visible until after we 16279 // complete parsing the new one and do the structural 16280 // comparison. 16281 SkipBody->CheckSameAsPrevious = true; 16282 SkipBody->New = createTagFromNewDecl(); 16283 SkipBody->Previous = Def; 16284 return Def; 16285 } else { 16286 SkipBody->ShouldSkip = true; 16287 SkipBody->Previous = Def; 16288 makeMergedDefinitionVisible(Hidden); 16289 // Carry on and handle it like a normal definition. We'll 16290 // skip starting the definitiion later. 16291 } 16292 } else if (!IsExplicitSpecializationAfterInstantiation) { 16293 // A redeclaration in function prototype scope in C isn't 16294 // visible elsewhere, so merely issue a warning. 16295 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16296 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16297 else 16298 Diag(NameLoc, diag::err_redefinition) << Name; 16299 notePreviousDefinition(Def, 16300 NameLoc.isValid() ? NameLoc : KWLoc); 16301 // If this is a redefinition, recover by making this 16302 // struct be anonymous, which will make any later 16303 // references get the previous definition. 16304 Name = nullptr; 16305 Previous.clear(); 16306 Invalid = true; 16307 } 16308 } else { 16309 // If the type is currently being defined, complain 16310 // about a nested redefinition. 16311 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16312 if (TD->isBeingDefined()) { 16313 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16314 Diag(PrevTagDecl->getLocation(), 16315 diag::note_previous_definition); 16316 Name = nullptr; 16317 Previous.clear(); 16318 Invalid = true; 16319 } 16320 } 16321 16322 // Okay, this is definition of a previously declared or referenced 16323 // tag. We're going to create a new Decl for it. 16324 } 16325 16326 // Okay, we're going to make a redeclaration. If this is some kind 16327 // of reference, make sure we build the redeclaration in the same DC 16328 // as the original, and ignore the current access specifier. 16329 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16330 SearchDC = PrevTagDecl->getDeclContext(); 16331 AS = AS_none; 16332 } 16333 } 16334 // If we get here we have (another) forward declaration or we 16335 // have a definition. Just create a new decl. 16336 16337 } else { 16338 // If we get here, this is a definition of a new tag type in a nested 16339 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16340 // new decl/type. We set PrevDecl to NULL so that the entities 16341 // have distinct types. 16342 Previous.clear(); 16343 } 16344 // If we get here, we're going to create a new Decl. If PrevDecl 16345 // is non-NULL, it's a definition of the tag declared by 16346 // PrevDecl. If it's NULL, we have a new definition. 16347 16348 // Otherwise, PrevDecl is not a tag, but was found with tag 16349 // lookup. This is only actually possible in C++, where a few 16350 // things like templates still live in the tag namespace. 16351 } else { 16352 // Use a better diagnostic if an elaborated-type-specifier 16353 // found the wrong kind of type on the first 16354 // (non-redeclaration) lookup. 16355 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16356 !Previous.isForRedeclaration()) { 16357 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16358 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16359 << Kind; 16360 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16361 Invalid = true; 16362 16363 // Otherwise, only diagnose if the declaration is in scope. 16364 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16365 SS.isNotEmpty() || isMemberSpecialization)) { 16366 // do nothing 16367 16368 // Diagnose implicit declarations introduced by elaborated types. 16369 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16370 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16371 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16372 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16373 Invalid = true; 16374 16375 // Otherwise it's a declaration. Call out a particularly common 16376 // case here. 16377 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16378 unsigned Kind = 0; 16379 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16380 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16381 << Name << Kind << TND->getUnderlyingType(); 16382 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16383 Invalid = true; 16384 16385 // Otherwise, diagnose. 16386 } else { 16387 // The tag name clashes with something else in the target scope, 16388 // issue an error and recover by making this tag be anonymous. 16389 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16390 notePreviousDefinition(PrevDecl, NameLoc); 16391 Name = nullptr; 16392 Invalid = true; 16393 } 16394 16395 // The existing declaration isn't relevant to us; we're in a 16396 // new scope, so clear out the previous declaration. 16397 Previous.clear(); 16398 } 16399 } 16400 16401 CreateNewDecl: 16402 16403 TagDecl *PrevDecl = nullptr; 16404 if (Previous.isSingleResult()) 16405 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16406 16407 // If there is an identifier, use the location of the identifier as the 16408 // location of the decl, otherwise use the location of the struct/union 16409 // keyword. 16410 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16411 16412 // Otherwise, create a new declaration. If there is a previous 16413 // declaration of the same entity, the two will be linked via 16414 // PrevDecl. 16415 TagDecl *New; 16416 16417 if (Kind == TTK_Enum) { 16418 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16419 // enum X { A, B, C } D; D should chain to X. 16420 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16421 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16422 ScopedEnumUsesClassTag, IsFixed); 16423 16424 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16425 StdAlignValT = cast<EnumDecl>(New); 16426 16427 // If this is an undefined enum, warn. 16428 if (TUK != TUK_Definition && !Invalid) { 16429 TagDecl *Def; 16430 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16431 // C++0x: 7.2p2: opaque-enum-declaration. 16432 // Conflicts are diagnosed above. Do nothing. 16433 } 16434 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16435 Diag(Loc, diag::ext_forward_ref_enum_def) 16436 << New; 16437 Diag(Def->getLocation(), diag::note_previous_definition); 16438 } else { 16439 unsigned DiagID = diag::ext_forward_ref_enum; 16440 if (getLangOpts().MSVCCompat) 16441 DiagID = diag::ext_ms_forward_ref_enum; 16442 else if (getLangOpts().CPlusPlus) 16443 DiagID = diag::err_forward_ref_enum; 16444 Diag(Loc, DiagID); 16445 } 16446 } 16447 16448 if (EnumUnderlying) { 16449 EnumDecl *ED = cast<EnumDecl>(New); 16450 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16451 ED->setIntegerTypeSourceInfo(TI); 16452 else 16453 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16454 ED->setPromotionType(ED->getIntegerType()); 16455 assert(ED->isComplete() && "enum with type should be complete"); 16456 } 16457 } else { 16458 // struct/union/class 16459 16460 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16461 // struct X { int A; } D; D should chain to X. 16462 if (getLangOpts().CPlusPlus) { 16463 // FIXME: Look for a way to use RecordDecl for simple structs. 16464 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16465 cast_or_null<CXXRecordDecl>(PrevDecl)); 16466 16467 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16468 StdBadAlloc = cast<CXXRecordDecl>(New); 16469 } else 16470 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16471 cast_or_null<RecordDecl>(PrevDecl)); 16472 } 16473 16474 // C++11 [dcl.type]p3: 16475 // A type-specifier-seq shall not define a class or enumeration [...]. 16476 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16477 TUK == TUK_Definition) { 16478 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16479 << Context.getTagDeclType(New); 16480 Invalid = true; 16481 } 16482 16483 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16484 DC->getDeclKind() == Decl::Enum) { 16485 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16486 << Context.getTagDeclType(New); 16487 Invalid = true; 16488 } 16489 16490 // Maybe add qualifier info. 16491 if (SS.isNotEmpty()) { 16492 if (SS.isSet()) { 16493 // If this is either a declaration or a definition, check the 16494 // nested-name-specifier against the current context. 16495 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16496 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16497 isMemberSpecialization)) 16498 Invalid = true; 16499 16500 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16501 if (TemplateParameterLists.size() > 0) { 16502 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16503 } 16504 } 16505 else 16506 Invalid = true; 16507 } 16508 16509 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16510 // Add alignment attributes if necessary; these attributes are checked when 16511 // the ASTContext lays out the structure. 16512 // 16513 // It is important for implementing the correct semantics that this 16514 // happen here (in ActOnTag). The #pragma pack stack is 16515 // maintained as a result of parser callbacks which can occur at 16516 // many points during the parsing of a struct declaration (because 16517 // the #pragma tokens are effectively skipped over during the 16518 // parsing of the struct). 16519 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16520 AddAlignmentAttributesForRecord(RD); 16521 AddMsStructLayoutForRecord(RD); 16522 } 16523 } 16524 16525 if (ModulePrivateLoc.isValid()) { 16526 if (isMemberSpecialization) 16527 Diag(New->getLocation(), diag::err_module_private_specialization) 16528 << 2 16529 << FixItHint::CreateRemoval(ModulePrivateLoc); 16530 // __module_private__ does not apply to local classes. However, we only 16531 // diagnose this as an error when the declaration specifiers are 16532 // freestanding. Here, we just ignore the __module_private__. 16533 else if (!SearchDC->isFunctionOrMethod()) 16534 New->setModulePrivate(); 16535 } 16536 16537 // If this is a specialization of a member class (of a class template), 16538 // check the specialization. 16539 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16540 Invalid = true; 16541 16542 // If we're declaring or defining a tag in function prototype scope in C, 16543 // note that this type can only be used within the function and add it to 16544 // the list of decls to inject into the function definition scope. 16545 if ((Name || Kind == TTK_Enum) && 16546 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16547 if (getLangOpts().CPlusPlus) { 16548 // C++ [dcl.fct]p6: 16549 // Types shall not be defined in return or parameter types. 16550 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16551 Diag(Loc, diag::err_type_defined_in_param_type) 16552 << Name; 16553 Invalid = true; 16554 } 16555 } else if (!PrevDecl) { 16556 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16557 } 16558 } 16559 16560 if (Invalid) 16561 New->setInvalidDecl(); 16562 16563 // Set the lexical context. If the tag has a C++ scope specifier, the 16564 // lexical context will be different from the semantic context. 16565 New->setLexicalDeclContext(CurContext); 16566 16567 // Mark this as a friend decl if applicable. 16568 // In Microsoft mode, a friend declaration also acts as a forward 16569 // declaration so we always pass true to setObjectOfFriendDecl to make 16570 // the tag name visible. 16571 if (TUK == TUK_Friend) 16572 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16573 16574 // Set the access specifier. 16575 if (!Invalid && SearchDC->isRecord()) 16576 SetMemberAccessSpecifier(New, PrevDecl, AS); 16577 16578 if (PrevDecl) 16579 CheckRedeclarationInModule(New, PrevDecl); 16580 16581 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16582 New->startDefinition(); 16583 16584 ProcessDeclAttributeList(S, New, Attrs); 16585 AddPragmaAttributes(S, New); 16586 16587 // If this has an identifier, add it to the scope stack. 16588 if (TUK == TUK_Friend) { 16589 // We might be replacing an existing declaration in the lookup tables; 16590 // if so, borrow its access specifier. 16591 if (PrevDecl) 16592 New->setAccess(PrevDecl->getAccess()); 16593 16594 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16595 DC->makeDeclVisibleInContext(New); 16596 if (Name) // can be null along some error paths 16597 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16598 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16599 } else if (Name) { 16600 S = getNonFieldDeclScope(S); 16601 PushOnScopeChains(New, S, true); 16602 } else { 16603 CurContext->addDecl(New); 16604 } 16605 16606 // If this is the C FILE type, notify the AST context. 16607 if (IdentifierInfo *II = New->getIdentifier()) 16608 if (!New->isInvalidDecl() && 16609 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16610 II->isStr("FILE")) 16611 Context.setFILEDecl(New); 16612 16613 if (PrevDecl) 16614 mergeDeclAttributes(New, PrevDecl); 16615 16616 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16617 inferGslOwnerPointerAttribute(CXXRD); 16618 16619 // If there's a #pragma GCC visibility in scope, set the visibility of this 16620 // record. 16621 AddPushedVisibilityAttribute(New); 16622 16623 if (isMemberSpecialization && !New->isInvalidDecl()) 16624 CompleteMemberSpecialization(New, Previous); 16625 16626 OwnedDecl = true; 16627 // In C++, don't return an invalid declaration. We can't recover well from 16628 // the cases where we make the type anonymous. 16629 if (Invalid && getLangOpts().CPlusPlus) { 16630 if (New->isBeingDefined()) 16631 if (auto RD = dyn_cast<RecordDecl>(New)) 16632 RD->completeDefinition(); 16633 return nullptr; 16634 } else if (SkipBody && SkipBody->ShouldSkip) { 16635 return SkipBody->Previous; 16636 } else { 16637 return New; 16638 } 16639 } 16640 16641 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16642 AdjustDeclIfTemplate(TagD); 16643 TagDecl *Tag = cast<TagDecl>(TagD); 16644 16645 // Enter the tag context. 16646 PushDeclContext(S, Tag); 16647 16648 ActOnDocumentableDecl(TagD); 16649 16650 // If there's a #pragma GCC visibility in scope, set the visibility of this 16651 // record. 16652 AddPushedVisibilityAttribute(Tag); 16653 } 16654 16655 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16656 SkipBodyInfo &SkipBody) { 16657 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16658 return false; 16659 16660 // Make the previous decl visible. 16661 makeMergedDefinitionVisible(SkipBody.Previous); 16662 return true; 16663 } 16664 16665 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16666 assert(isa<ObjCContainerDecl>(IDecl) && 16667 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16668 DeclContext *OCD = cast<DeclContext>(IDecl); 16669 assert(OCD->getLexicalParent() == CurContext && 16670 "The next DeclContext should be lexically contained in the current one."); 16671 CurContext = OCD; 16672 return IDecl; 16673 } 16674 16675 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16676 SourceLocation FinalLoc, 16677 bool IsFinalSpelledSealed, 16678 bool IsAbstract, 16679 SourceLocation LBraceLoc) { 16680 AdjustDeclIfTemplate(TagD); 16681 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16682 16683 FieldCollector->StartClass(); 16684 16685 if (!Record->getIdentifier()) 16686 return; 16687 16688 if (IsAbstract) 16689 Record->markAbstract(); 16690 16691 if (FinalLoc.isValid()) { 16692 Record->addAttr(FinalAttr::Create( 16693 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16694 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16695 } 16696 // C++ [class]p2: 16697 // [...] The class-name is also inserted into the scope of the 16698 // class itself; this is known as the injected-class-name. For 16699 // purposes of access checking, the injected-class-name is treated 16700 // as if it were a public member name. 16701 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16702 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16703 Record->getLocation(), Record->getIdentifier(), 16704 /*PrevDecl=*/nullptr, 16705 /*DelayTypeCreation=*/true); 16706 Context.getTypeDeclType(InjectedClassName, Record); 16707 InjectedClassName->setImplicit(); 16708 InjectedClassName->setAccess(AS_public); 16709 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16710 InjectedClassName->setDescribedClassTemplate(Template); 16711 PushOnScopeChains(InjectedClassName, S); 16712 assert(InjectedClassName->isInjectedClassName() && 16713 "Broken injected-class-name"); 16714 } 16715 16716 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16717 SourceRange BraceRange) { 16718 AdjustDeclIfTemplate(TagD); 16719 TagDecl *Tag = cast<TagDecl>(TagD); 16720 Tag->setBraceRange(BraceRange); 16721 16722 // Make sure we "complete" the definition even it is invalid. 16723 if (Tag->isBeingDefined()) { 16724 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16725 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16726 RD->completeDefinition(); 16727 } 16728 16729 if (isa<CXXRecordDecl>(Tag)) { 16730 FieldCollector->FinishClass(); 16731 } 16732 16733 // Exit this scope of this tag's definition. 16734 PopDeclContext(); 16735 16736 if (getCurLexicalContext()->isObjCContainer() && 16737 Tag->getDeclContext()->isFileContext()) 16738 Tag->setTopLevelDeclInObjCContainer(); 16739 16740 // Notify the consumer that we've defined a tag. 16741 if (!Tag->isInvalidDecl()) 16742 Consumer.HandleTagDeclDefinition(Tag); 16743 16744 // Clangs implementation of #pragma align(packed) differs in bitfield layout 16745 // from XLs and instead matches the XL #pragma pack(1) behavior. 16746 if (Context.getTargetInfo().getTriple().isOSAIX() && 16747 AlignPackStack.hasValue()) { 16748 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 16749 // Only diagnose #pragma align(packed). 16750 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 16751 return; 16752 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 16753 if (!RD) 16754 return; 16755 // Only warn if there is at least 1 bitfield member. 16756 if (llvm::any_of(RD->fields(), 16757 [](const FieldDecl *FD) { return FD->isBitField(); })) 16758 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 16759 } 16760 } 16761 16762 void Sema::ActOnObjCContainerFinishDefinition() { 16763 // Exit this scope of this interface definition. 16764 PopDeclContext(); 16765 } 16766 16767 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16768 assert(DC == CurContext && "Mismatch of container contexts"); 16769 OriginalLexicalContext = DC; 16770 ActOnObjCContainerFinishDefinition(); 16771 } 16772 16773 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16774 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16775 OriginalLexicalContext = nullptr; 16776 } 16777 16778 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16779 AdjustDeclIfTemplate(TagD); 16780 TagDecl *Tag = cast<TagDecl>(TagD); 16781 Tag->setInvalidDecl(); 16782 16783 // Make sure we "complete" the definition even it is invalid. 16784 if (Tag->isBeingDefined()) { 16785 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16786 RD->completeDefinition(); 16787 } 16788 16789 // We're undoing ActOnTagStartDefinition here, not 16790 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16791 // the FieldCollector. 16792 16793 PopDeclContext(); 16794 } 16795 16796 // Note that FieldName may be null for anonymous bitfields. 16797 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16798 IdentifierInfo *FieldName, 16799 QualType FieldTy, bool IsMsStruct, 16800 Expr *BitWidth, bool *ZeroWidth) { 16801 assert(BitWidth); 16802 if (BitWidth->containsErrors()) 16803 return ExprError(); 16804 16805 // Default to true; that shouldn't confuse checks for emptiness 16806 if (ZeroWidth) 16807 *ZeroWidth = true; 16808 16809 // C99 6.7.2.1p4 - verify the field type. 16810 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16811 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16812 // Handle incomplete and sizeless types with a specific error. 16813 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16814 diag::err_field_incomplete_or_sizeless)) 16815 return ExprError(); 16816 if (FieldName) 16817 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16818 << FieldName << FieldTy << BitWidth->getSourceRange(); 16819 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16820 << FieldTy << BitWidth->getSourceRange(); 16821 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16822 UPPC_BitFieldWidth)) 16823 return ExprError(); 16824 16825 // If the bit-width is type- or value-dependent, don't try to check 16826 // it now. 16827 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16828 return BitWidth; 16829 16830 llvm::APSInt Value; 16831 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16832 if (ICE.isInvalid()) 16833 return ICE; 16834 BitWidth = ICE.get(); 16835 16836 if (Value != 0 && ZeroWidth) 16837 *ZeroWidth = false; 16838 16839 // Zero-width bitfield is ok for anonymous field. 16840 if (Value == 0 && FieldName) 16841 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16842 16843 if (Value.isSigned() && Value.isNegative()) { 16844 if (FieldName) 16845 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16846 << FieldName << toString(Value, 10); 16847 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16848 << toString(Value, 10); 16849 } 16850 16851 // The size of the bit-field must not exceed our maximum permitted object 16852 // size. 16853 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16854 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16855 << !FieldName << FieldName << toString(Value, 10); 16856 } 16857 16858 if (!FieldTy->isDependentType()) { 16859 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16860 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16861 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16862 16863 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16864 // ABI. 16865 bool CStdConstraintViolation = 16866 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16867 bool MSBitfieldViolation = 16868 Value.ugt(TypeStorageSize) && 16869 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16870 if (CStdConstraintViolation || MSBitfieldViolation) { 16871 unsigned DiagWidth = 16872 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16873 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16874 << (bool)FieldName << FieldName << toString(Value, 10) 16875 << !CStdConstraintViolation << DiagWidth; 16876 } 16877 16878 // Warn on types where the user might conceivably expect to get all 16879 // specified bits as value bits: that's all integral types other than 16880 // 'bool'. 16881 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16882 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16883 << FieldName << toString(Value, 10) 16884 << (unsigned)TypeWidth; 16885 } 16886 } 16887 16888 return BitWidth; 16889 } 16890 16891 /// ActOnField - Each field of a C struct/union is passed into this in order 16892 /// to create a FieldDecl object for it. 16893 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16894 Declarator &D, Expr *BitfieldWidth) { 16895 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16896 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16897 /*InitStyle=*/ICIS_NoInit, AS_public); 16898 return Res; 16899 } 16900 16901 /// HandleField - Analyze a field of a C struct or a C++ data member. 16902 /// 16903 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16904 SourceLocation DeclStart, 16905 Declarator &D, Expr *BitWidth, 16906 InClassInitStyle InitStyle, 16907 AccessSpecifier AS) { 16908 if (D.isDecompositionDeclarator()) { 16909 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16910 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16911 << Decomp.getSourceRange(); 16912 return nullptr; 16913 } 16914 16915 IdentifierInfo *II = D.getIdentifier(); 16916 SourceLocation Loc = DeclStart; 16917 if (II) Loc = D.getIdentifierLoc(); 16918 16919 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16920 QualType T = TInfo->getType(); 16921 if (getLangOpts().CPlusPlus) { 16922 CheckExtraCXXDefaultArguments(D); 16923 16924 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16925 UPPC_DataMemberType)) { 16926 D.setInvalidType(); 16927 T = Context.IntTy; 16928 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16929 } 16930 } 16931 16932 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16933 16934 if (D.getDeclSpec().isInlineSpecified()) 16935 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16936 << getLangOpts().CPlusPlus17; 16937 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16938 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16939 diag::err_invalid_thread) 16940 << DeclSpec::getSpecifierName(TSCS); 16941 16942 // Check to see if this name was declared as a member previously 16943 NamedDecl *PrevDecl = nullptr; 16944 LookupResult Previous(*this, II, Loc, LookupMemberName, 16945 ForVisibleRedeclaration); 16946 LookupName(Previous, S); 16947 switch (Previous.getResultKind()) { 16948 case LookupResult::Found: 16949 case LookupResult::FoundUnresolvedValue: 16950 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16951 break; 16952 16953 case LookupResult::FoundOverloaded: 16954 PrevDecl = Previous.getRepresentativeDecl(); 16955 break; 16956 16957 case LookupResult::NotFound: 16958 case LookupResult::NotFoundInCurrentInstantiation: 16959 case LookupResult::Ambiguous: 16960 break; 16961 } 16962 Previous.suppressDiagnostics(); 16963 16964 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16965 // Maybe we will complain about the shadowed template parameter. 16966 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16967 // Just pretend that we didn't see the previous declaration. 16968 PrevDecl = nullptr; 16969 } 16970 16971 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16972 PrevDecl = nullptr; 16973 16974 bool Mutable 16975 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16976 SourceLocation TSSL = D.getBeginLoc(); 16977 FieldDecl *NewFD 16978 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16979 TSSL, AS, PrevDecl, &D); 16980 16981 if (NewFD->isInvalidDecl()) 16982 Record->setInvalidDecl(); 16983 16984 if (D.getDeclSpec().isModulePrivateSpecified()) 16985 NewFD->setModulePrivate(); 16986 16987 if (NewFD->isInvalidDecl() && PrevDecl) { 16988 // Don't introduce NewFD into scope; there's already something 16989 // with the same name in the same scope. 16990 } else if (II) { 16991 PushOnScopeChains(NewFD, S); 16992 } else 16993 Record->addDecl(NewFD); 16994 16995 return NewFD; 16996 } 16997 16998 /// Build a new FieldDecl and check its well-formedness. 16999 /// 17000 /// This routine builds a new FieldDecl given the fields name, type, 17001 /// record, etc. \p PrevDecl should refer to any previous declaration 17002 /// with the same name and in the same scope as the field to be 17003 /// created. 17004 /// 17005 /// \returns a new FieldDecl. 17006 /// 17007 /// \todo The Declarator argument is a hack. It will be removed once 17008 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 17009 TypeSourceInfo *TInfo, 17010 RecordDecl *Record, SourceLocation Loc, 17011 bool Mutable, Expr *BitWidth, 17012 InClassInitStyle InitStyle, 17013 SourceLocation TSSL, 17014 AccessSpecifier AS, NamedDecl *PrevDecl, 17015 Declarator *D) { 17016 IdentifierInfo *II = Name.getAsIdentifierInfo(); 17017 bool InvalidDecl = false; 17018 if (D) InvalidDecl = D->isInvalidType(); 17019 17020 // If we receive a broken type, recover by assuming 'int' and 17021 // marking this declaration as invalid. 17022 if (T.isNull() || T->containsErrors()) { 17023 InvalidDecl = true; 17024 T = Context.IntTy; 17025 } 17026 17027 QualType EltTy = Context.getBaseElementType(T); 17028 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 17029 if (RequireCompleteSizedType(Loc, EltTy, 17030 diag::err_field_incomplete_or_sizeless)) { 17031 // Fields of incomplete type force their record to be invalid. 17032 Record->setInvalidDecl(); 17033 InvalidDecl = true; 17034 } else { 17035 NamedDecl *Def; 17036 EltTy->isIncompleteType(&Def); 17037 if (Def && Def->isInvalidDecl()) { 17038 Record->setInvalidDecl(); 17039 InvalidDecl = true; 17040 } 17041 } 17042 } 17043 17044 // TR 18037 does not allow fields to be declared with address space 17045 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 17046 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 17047 Diag(Loc, diag::err_field_with_address_space); 17048 Record->setInvalidDecl(); 17049 InvalidDecl = true; 17050 } 17051 17052 if (LangOpts.OpenCL) { 17053 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 17054 // used as structure or union field: image, sampler, event or block types. 17055 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 17056 T->isBlockPointerType()) { 17057 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 17058 Record->setInvalidDecl(); 17059 InvalidDecl = true; 17060 } 17061 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 17062 // is enabled. 17063 if (BitWidth && !getOpenCLOptions().isAvailableOption( 17064 "__cl_clang_bitfields", LangOpts)) { 17065 Diag(Loc, diag::err_opencl_bitfields); 17066 InvalidDecl = true; 17067 } 17068 } 17069 17070 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 17071 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 17072 T.hasQualifiers()) { 17073 InvalidDecl = true; 17074 Diag(Loc, diag::err_anon_bitfield_qualifiers); 17075 } 17076 17077 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17078 // than a variably modified type. 17079 if (!InvalidDecl && T->isVariablyModifiedType()) { 17080 if (!tryToFixVariablyModifiedVarType( 17081 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 17082 InvalidDecl = true; 17083 } 17084 17085 // Fields can not have abstract class types 17086 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 17087 diag::err_abstract_type_in_decl, 17088 AbstractFieldType)) 17089 InvalidDecl = true; 17090 17091 bool ZeroWidth = false; 17092 if (InvalidDecl) 17093 BitWidth = nullptr; 17094 // If this is declared as a bit-field, check the bit-field. 17095 if (BitWidth) { 17096 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 17097 &ZeroWidth).get(); 17098 if (!BitWidth) { 17099 InvalidDecl = true; 17100 BitWidth = nullptr; 17101 ZeroWidth = false; 17102 } 17103 } 17104 17105 // Check that 'mutable' is consistent with the type of the declaration. 17106 if (!InvalidDecl && Mutable) { 17107 unsigned DiagID = 0; 17108 if (T->isReferenceType()) 17109 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 17110 : diag::err_mutable_reference; 17111 else if (T.isConstQualified()) 17112 DiagID = diag::err_mutable_const; 17113 17114 if (DiagID) { 17115 SourceLocation ErrLoc = Loc; 17116 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 17117 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 17118 Diag(ErrLoc, DiagID); 17119 if (DiagID != diag::ext_mutable_reference) { 17120 Mutable = false; 17121 InvalidDecl = true; 17122 } 17123 } 17124 } 17125 17126 // C++11 [class.union]p8 (DR1460): 17127 // At most one variant member of a union may have a 17128 // brace-or-equal-initializer. 17129 if (InitStyle != ICIS_NoInit) 17130 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 17131 17132 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 17133 BitWidth, Mutable, InitStyle); 17134 if (InvalidDecl) 17135 NewFD->setInvalidDecl(); 17136 17137 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 17138 Diag(Loc, diag::err_duplicate_member) << II; 17139 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17140 NewFD->setInvalidDecl(); 17141 } 17142 17143 if (!InvalidDecl && getLangOpts().CPlusPlus) { 17144 if (Record->isUnion()) { 17145 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17146 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17147 if (RDecl->getDefinition()) { 17148 // C++ [class.union]p1: An object of a class with a non-trivial 17149 // constructor, a non-trivial copy constructor, a non-trivial 17150 // destructor, or a non-trivial copy assignment operator 17151 // cannot be a member of a union, nor can an array of such 17152 // objects. 17153 if (CheckNontrivialField(NewFD)) 17154 NewFD->setInvalidDecl(); 17155 } 17156 } 17157 17158 // C++ [class.union]p1: If a union contains a member of reference type, 17159 // the program is ill-formed, except when compiling with MSVC extensions 17160 // enabled. 17161 if (EltTy->isReferenceType()) { 17162 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 17163 diag::ext_union_member_of_reference_type : 17164 diag::err_union_member_of_reference_type) 17165 << NewFD->getDeclName() << EltTy; 17166 if (!getLangOpts().MicrosoftExt) 17167 NewFD->setInvalidDecl(); 17168 } 17169 } 17170 } 17171 17172 // FIXME: We need to pass in the attributes given an AST 17173 // representation, not a parser representation. 17174 if (D) { 17175 // FIXME: The current scope is almost... but not entirely... correct here. 17176 ProcessDeclAttributes(getCurScope(), NewFD, *D); 17177 17178 if (NewFD->hasAttrs()) 17179 CheckAlignasUnderalignment(NewFD); 17180 } 17181 17182 // In auto-retain/release, infer strong retension for fields of 17183 // retainable type. 17184 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 17185 NewFD->setInvalidDecl(); 17186 17187 if (T.isObjCGCWeak()) 17188 Diag(Loc, diag::warn_attribute_weak_on_field); 17189 17190 // PPC MMA non-pointer types are not allowed as field types. 17191 if (Context.getTargetInfo().getTriple().isPPC64() && 17192 CheckPPCMMAType(T, NewFD->getLocation())) 17193 NewFD->setInvalidDecl(); 17194 17195 NewFD->setAccess(AS); 17196 return NewFD; 17197 } 17198 17199 bool Sema::CheckNontrivialField(FieldDecl *FD) { 17200 assert(FD); 17201 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 17202 17203 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 17204 return false; 17205 17206 QualType EltTy = Context.getBaseElementType(FD->getType()); 17207 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17208 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17209 if (RDecl->getDefinition()) { 17210 // We check for copy constructors before constructors 17211 // because otherwise we'll never get complaints about 17212 // copy constructors. 17213 17214 CXXSpecialMember member = CXXInvalid; 17215 // We're required to check for any non-trivial constructors. Since the 17216 // implicit default constructor is suppressed if there are any 17217 // user-declared constructors, we just need to check that there is a 17218 // trivial default constructor and a trivial copy constructor. (We don't 17219 // worry about move constructors here, since this is a C++98 check.) 17220 if (RDecl->hasNonTrivialCopyConstructor()) 17221 member = CXXCopyConstructor; 17222 else if (!RDecl->hasTrivialDefaultConstructor()) 17223 member = CXXDefaultConstructor; 17224 else if (RDecl->hasNonTrivialCopyAssignment()) 17225 member = CXXCopyAssignment; 17226 else if (RDecl->hasNonTrivialDestructor()) 17227 member = CXXDestructor; 17228 17229 if (member != CXXInvalid) { 17230 if (!getLangOpts().CPlusPlus11 && 17231 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 17232 // Objective-C++ ARC: it is an error to have a non-trivial field of 17233 // a union. However, system headers in Objective-C programs 17234 // occasionally have Objective-C lifetime objects within unions, 17235 // and rather than cause the program to fail, we make those 17236 // members unavailable. 17237 SourceLocation Loc = FD->getLocation(); 17238 if (getSourceManager().isInSystemHeader(Loc)) { 17239 if (!FD->hasAttr<UnavailableAttr>()) 17240 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 17241 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 17242 return false; 17243 } 17244 } 17245 17246 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17247 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17248 diag::err_illegal_union_or_anon_struct_member) 17249 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17250 DiagnoseNontrivial(RDecl, member); 17251 return !getLangOpts().CPlusPlus11; 17252 } 17253 } 17254 } 17255 17256 return false; 17257 } 17258 17259 /// TranslateIvarVisibility - Translate visibility from a token ID to an 17260 /// AST enum value. 17261 static ObjCIvarDecl::AccessControl 17262 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17263 switch (ivarVisibility) { 17264 default: llvm_unreachable("Unknown visitibility kind"); 17265 case tok::objc_private: return ObjCIvarDecl::Private; 17266 case tok::objc_public: return ObjCIvarDecl::Public; 17267 case tok::objc_protected: return ObjCIvarDecl::Protected; 17268 case tok::objc_package: return ObjCIvarDecl::Package; 17269 } 17270 } 17271 17272 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 17273 /// in order to create an IvarDecl object for it. 17274 Decl *Sema::ActOnIvar(Scope *S, 17275 SourceLocation DeclStart, 17276 Declarator &D, Expr *BitfieldWidth, 17277 tok::ObjCKeywordKind Visibility) { 17278 17279 IdentifierInfo *II = D.getIdentifier(); 17280 Expr *BitWidth = (Expr*)BitfieldWidth; 17281 SourceLocation Loc = DeclStart; 17282 if (II) Loc = D.getIdentifierLoc(); 17283 17284 // FIXME: Unnamed fields can be handled in various different ways, for 17285 // example, unnamed unions inject all members into the struct namespace! 17286 17287 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17288 QualType T = TInfo->getType(); 17289 17290 if (BitWidth) { 17291 // 6.7.2.1p3, 6.7.2.1p4 17292 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17293 if (!BitWidth) 17294 D.setInvalidType(); 17295 } else { 17296 // Not a bitfield. 17297 17298 // validate II. 17299 17300 } 17301 if (T->isReferenceType()) { 17302 Diag(Loc, diag::err_ivar_reference_type); 17303 D.setInvalidType(); 17304 } 17305 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17306 // than a variably modified type. 17307 else if (T->isVariablyModifiedType()) { 17308 if (!tryToFixVariablyModifiedVarType( 17309 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17310 D.setInvalidType(); 17311 } 17312 17313 // Get the visibility (access control) for this ivar. 17314 ObjCIvarDecl::AccessControl ac = 17315 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17316 : ObjCIvarDecl::None; 17317 // Must set ivar's DeclContext to its enclosing interface. 17318 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17319 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17320 return nullptr; 17321 ObjCContainerDecl *EnclosingContext; 17322 if (ObjCImplementationDecl *IMPDecl = 17323 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17324 if (LangOpts.ObjCRuntime.isFragile()) { 17325 // Case of ivar declared in an implementation. Context is that of its class. 17326 EnclosingContext = IMPDecl->getClassInterface(); 17327 assert(EnclosingContext && "Implementation has no class interface!"); 17328 } 17329 else 17330 EnclosingContext = EnclosingDecl; 17331 } else { 17332 if (ObjCCategoryDecl *CDecl = 17333 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17334 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17335 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17336 return nullptr; 17337 } 17338 } 17339 EnclosingContext = EnclosingDecl; 17340 } 17341 17342 // Construct the decl. 17343 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17344 DeclStart, Loc, II, T, 17345 TInfo, ac, (Expr *)BitfieldWidth); 17346 17347 if (II) { 17348 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17349 ForVisibleRedeclaration); 17350 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17351 && !isa<TagDecl>(PrevDecl)) { 17352 Diag(Loc, diag::err_duplicate_member) << II; 17353 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17354 NewID->setInvalidDecl(); 17355 } 17356 } 17357 17358 // Process attributes attached to the ivar. 17359 ProcessDeclAttributes(S, NewID, D); 17360 17361 if (D.isInvalidType()) 17362 NewID->setInvalidDecl(); 17363 17364 // In ARC, infer 'retaining' for ivars of retainable type. 17365 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17366 NewID->setInvalidDecl(); 17367 17368 if (D.getDeclSpec().isModulePrivateSpecified()) 17369 NewID->setModulePrivate(); 17370 17371 if (II) { 17372 // FIXME: When interfaces are DeclContexts, we'll need to add 17373 // these to the interface. 17374 S->AddDecl(NewID); 17375 IdResolver.AddDecl(NewID); 17376 } 17377 17378 if (LangOpts.ObjCRuntime.isNonFragile() && 17379 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17380 Diag(Loc, diag::warn_ivars_in_interface); 17381 17382 return NewID; 17383 } 17384 17385 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17386 /// class and class extensions. For every class \@interface and class 17387 /// extension \@interface, if the last ivar is a bitfield of any type, 17388 /// then add an implicit `char :0` ivar to the end of that interface. 17389 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17390 SmallVectorImpl<Decl *> &AllIvarDecls) { 17391 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17392 return; 17393 17394 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17395 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17396 17397 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17398 return; 17399 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17400 if (!ID) { 17401 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17402 if (!CD->IsClassExtension()) 17403 return; 17404 } 17405 // No need to add this to end of @implementation. 17406 else 17407 return; 17408 } 17409 // All conditions are met. Add a new bitfield to the tail end of ivars. 17410 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17411 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17412 17413 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17414 DeclLoc, DeclLoc, nullptr, 17415 Context.CharTy, 17416 Context.getTrivialTypeSourceInfo(Context.CharTy, 17417 DeclLoc), 17418 ObjCIvarDecl::Private, BW, 17419 true); 17420 AllIvarDecls.push_back(Ivar); 17421 } 17422 17423 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17424 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17425 SourceLocation RBrac, 17426 const ParsedAttributesView &Attrs) { 17427 assert(EnclosingDecl && "missing record or interface decl"); 17428 17429 // If this is an Objective-C @implementation or category and we have 17430 // new fields here we should reset the layout of the interface since 17431 // it will now change. 17432 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17433 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17434 switch (DC->getKind()) { 17435 default: break; 17436 case Decl::ObjCCategory: 17437 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17438 break; 17439 case Decl::ObjCImplementation: 17440 Context. 17441 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17442 break; 17443 } 17444 } 17445 17446 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17447 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17448 17449 // Start counting up the number of named members; make sure to include 17450 // members of anonymous structs and unions in the total. 17451 unsigned NumNamedMembers = 0; 17452 if (Record) { 17453 for (const auto *I : Record->decls()) { 17454 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17455 if (IFD->getDeclName()) 17456 ++NumNamedMembers; 17457 } 17458 } 17459 17460 // Verify that all the fields are okay. 17461 SmallVector<FieldDecl*, 32> RecFields; 17462 17463 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17464 i != end; ++i) { 17465 FieldDecl *FD = cast<FieldDecl>(*i); 17466 17467 // Get the type for the field. 17468 const Type *FDTy = FD->getType().getTypePtr(); 17469 17470 if (!FD->isAnonymousStructOrUnion()) { 17471 // Remember all fields written by the user. 17472 RecFields.push_back(FD); 17473 } 17474 17475 // If the field is already invalid for some reason, don't emit more 17476 // diagnostics about it. 17477 if (FD->isInvalidDecl()) { 17478 EnclosingDecl->setInvalidDecl(); 17479 continue; 17480 } 17481 17482 // C99 6.7.2.1p2: 17483 // A structure or union shall not contain a member with 17484 // incomplete or function type (hence, a structure shall not 17485 // contain an instance of itself, but may contain a pointer to 17486 // an instance of itself), except that the last member of a 17487 // structure with more than one named member may have incomplete 17488 // array type; such a structure (and any union containing, 17489 // possibly recursively, a member that is such a structure) 17490 // shall not be a member of a structure or an element of an 17491 // array. 17492 bool IsLastField = (i + 1 == Fields.end()); 17493 if (FDTy->isFunctionType()) { 17494 // Field declared as a function. 17495 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17496 << FD->getDeclName(); 17497 FD->setInvalidDecl(); 17498 EnclosingDecl->setInvalidDecl(); 17499 continue; 17500 } else if (FDTy->isIncompleteArrayType() && 17501 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17502 if (Record) { 17503 // Flexible array member. 17504 // Microsoft and g++ is more permissive regarding flexible array. 17505 // It will accept flexible array in union and also 17506 // as the sole element of a struct/class. 17507 unsigned DiagID = 0; 17508 if (!Record->isUnion() && !IsLastField) { 17509 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17510 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17511 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17512 FD->setInvalidDecl(); 17513 EnclosingDecl->setInvalidDecl(); 17514 continue; 17515 } else if (Record->isUnion()) 17516 DiagID = getLangOpts().MicrosoftExt 17517 ? diag::ext_flexible_array_union_ms 17518 : getLangOpts().CPlusPlus 17519 ? diag::ext_flexible_array_union_gnu 17520 : diag::err_flexible_array_union; 17521 else if (NumNamedMembers < 1) 17522 DiagID = getLangOpts().MicrosoftExt 17523 ? diag::ext_flexible_array_empty_aggregate_ms 17524 : getLangOpts().CPlusPlus 17525 ? diag::ext_flexible_array_empty_aggregate_gnu 17526 : diag::err_flexible_array_empty_aggregate; 17527 17528 if (DiagID) 17529 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17530 << Record->getTagKind(); 17531 // While the layout of types that contain virtual bases is not specified 17532 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17533 // virtual bases after the derived members. This would make a flexible 17534 // array member declared at the end of an object not adjacent to the end 17535 // of the type. 17536 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17537 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17538 << FD->getDeclName() << Record->getTagKind(); 17539 if (!getLangOpts().C99) 17540 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17541 << FD->getDeclName() << Record->getTagKind(); 17542 17543 // If the element type has a non-trivial destructor, we would not 17544 // implicitly destroy the elements, so disallow it for now. 17545 // 17546 // FIXME: GCC allows this. We should probably either implicitly delete 17547 // the destructor of the containing class, or just allow this. 17548 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17549 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17550 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17551 << FD->getDeclName() << FD->getType(); 17552 FD->setInvalidDecl(); 17553 EnclosingDecl->setInvalidDecl(); 17554 continue; 17555 } 17556 // Okay, we have a legal flexible array member at the end of the struct. 17557 Record->setHasFlexibleArrayMember(true); 17558 } else { 17559 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17560 // unless they are followed by another ivar. That check is done 17561 // elsewhere, after synthesized ivars are known. 17562 } 17563 } else if (!FDTy->isDependentType() && 17564 RequireCompleteSizedType( 17565 FD->getLocation(), FD->getType(), 17566 diag::err_field_incomplete_or_sizeless)) { 17567 // Incomplete type 17568 FD->setInvalidDecl(); 17569 EnclosingDecl->setInvalidDecl(); 17570 continue; 17571 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17572 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17573 // A type which contains a flexible array member is considered to be a 17574 // flexible array member. 17575 Record->setHasFlexibleArrayMember(true); 17576 if (!Record->isUnion()) { 17577 // If this is a struct/class and this is not the last element, reject 17578 // it. Note that GCC supports variable sized arrays in the middle of 17579 // structures. 17580 if (!IsLastField) 17581 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17582 << FD->getDeclName() << FD->getType(); 17583 else { 17584 // We support flexible arrays at the end of structs in 17585 // other structs as an extension. 17586 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17587 << FD->getDeclName(); 17588 } 17589 } 17590 } 17591 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17592 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17593 diag::err_abstract_type_in_decl, 17594 AbstractIvarType)) { 17595 // Ivars can not have abstract class types 17596 FD->setInvalidDecl(); 17597 } 17598 if (Record && FDTTy->getDecl()->hasObjectMember()) 17599 Record->setHasObjectMember(true); 17600 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17601 Record->setHasVolatileMember(true); 17602 } else if (FDTy->isObjCObjectType()) { 17603 /// A field cannot be an Objective-c object 17604 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17605 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17606 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17607 FD->setType(T); 17608 } else if (Record && Record->isUnion() && 17609 FD->getType().hasNonTrivialObjCLifetime() && 17610 getSourceManager().isInSystemHeader(FD->getLocation()) && 17611 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17612 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17613 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17614 // For backward compatibility, fields of C unions declared in system 17615 // headers that have non-trivial ObjC ownership qualifications are marked 17616 // as unavailable unless the qualifier is explicit and __strong. This can 17617 // break ABI compatibility between programs compiled with ARC and MRR, but 17618 // is a better option than rejecting programs using those unions under 17619 // ARC. 17620 FD->addAttr(UnavailableAttr::CreateImplicit( 17621 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17622 FD->getLocation())); 17623 } else if (getLangOpts().ObjC && 17624 getLangOpts().getGC() != LangOptions::NonGC && Record && 17625 !Record->hasObjectMember()) { 17626 if (FD->getType()->isObjCObjectPointerType() || 17627 FD->getType().isObjCGCStrong()) 17628 Record->setHasObjectMember(true); 17629 else if (Context.getAsArrayType(FD->getType())) { 17630 QualType BaseType = Context.getBaseElementType(FD->getType()); 17631 if (BaseType->isRecordType() && 17632 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17633 Record->setHasObjectMember(true); 17634 else if (BaseType->isObjCObjectPointerType() || 17635 BaseType.isObjCGCStrong()) 17636 Record->setHasObjectMember(true); 17637 } 17638 } 17639 17640 if (Record && !getLangOpts().CPlusPlus && 17641 !shouldIgnoreForRecordTriviality(FD)) { 17642 QualType FT = FD->getType(); 17643 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17644 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17645 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17646 Record->isUnion()) 17647 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17648 } 17649 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17650 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17651 Record->setNonTrivialToPrimitiveCopy(true); 17652 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17653 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17654 } 17655 if (FT.isDestructedType()) { 17656 Record->setNonTrivialToPrimitiveDestroy(true); 17657 Record->setParamDestroyedInCallee(true); 17658 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17659 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17660 } 17661 17662 if (const auto *RT = FT->getAs<RecordType>()) { 17663 if (RT->getDecl()->getArgPassingRestrictions() == 17664 RecordDecl::APK_CanNeverPassInRegs) 17665 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17666 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17667 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17668 } 17669 17670 if (Record && FD->getType().isVolatileQualified()) 17671 Record->setHasVolatileMember(true); 17672 // Keep track of the number of named members. 17673 if (FD->getIdentifier()) 17674 ++NumNamedMembers; 17675 } 17676 17677 // Okay, we successfully defined 'Record'. 17678 if (Record) { 17679 bool Completed = false; 17680 if (CXXRecord) { 17681 if (!CXXRecord->isInvalidDecl()) { 17682 // Set access bits correctly on the directly-declared conversions. 17683 for (CXXRecordDecl::conversion_iterator 17684 I = CXXRecord->conversion_begin(), 17685 E = CXXRecord->conversion_end(); I != E; ++I) 17686 I.setAccess((*I)->getAccess()); 17687 } 17688 17689 // Add any implicitly-declared members to this class. 17690 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17691 17692 if (!CXXRecord->isDependentType()) { 17693 if (!CXXRecord->isInvalidDecl()) { 17694 // If we have virtual base classes, we may end up finding multiple 17695 // final overriders for a given virtual function. Check for this 17696 // problem now. 17697 if (CXXRecord->getNumVBases()) { 17698 CXXFinalOverriderMap FinalOverriders; 17699 CXXRecord->getFinalOverriders(FinalOverriders); 17700 17701 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17702 MEnd = FinalOverriders.end(); 17703 M != MEnd; ++M) { 17704 for (OverridingMethods::iterator SO = M->second.begin(), 17705 SOEnd = M->second.end(); 17706 SO != SOEnd; ++SO) { 17707 assert(SO->second.size() > 0 && 17708 "Virtual function without overriding functions?"); 17709 if (SO->second.size() == 1) 17710 continue; 17711 17712 // C++ [class.virtual]p2: 17713 // In a derived class, if a virtual member function of a base 17714 // class subobject has more than one final overrider the 17715 // program is ill-formed. 17716 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17717 << (const NamedDecl *)M->first << Record; 17718 Diag(M->first->getLocation(), 17719 diag::note_overridden_virtual_function); 17720 for (OverridingMethods::overriding_iterator 17721 OM = SO->second.begin(), 17722 OMEnd = SO->second.end(); 17723 OM != OMEnd; ++OM) 17724 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17725 << (const NamedDecl *)M->first << OM->Method->getParent(); 17726 17727 Record->setInvalidDecl(); 17728 } 17729 } 17730 CXXRecord->completeDefinition(&FinalOverriders); 17731 Completed = true; 17732 } 17733 } 17734 } 17735 } 17736 17737 if (!Completed) 17738 Record->completeDefinition(); 17739 17740 // Handle attributes before checking the layout. 17741 ProcessDeclAttributeList(S, Record, Attrs); 17742 17743 // We may have deferred checking for a deleted destructor. Check now. 17744 if (CXXRecord) { 17745 auto *Dtor = CXXRecord->getDestructor(); 17746 if (Dtor && Dtor->isImplicit() && 17747 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17748 CXXRecord->setImplicitDestructorIsDeleted(); 17749 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17750 } 17751 } 17752 17753 if (Record->hasAttrs()) { 17754 CheckAlignasUnderalignment(Record); 17755 17756 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17757 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17758 IA->getRange(), IA->getBestCase(), 17759 IA->getInheritanceModel()); 17760 } 17761 17762 // Check if the structure/union declaration is a type that can have zero 17763 // size in C. For C this is a language extension, for C++ it may cause 17764 // compatibility problems. 17765 bool CheckForZeroSize; 17766 if (!getLangOpts().CPlusPlus) { 17767 CheckForZeroSize = true; 17768 } else { 17769 // For C++ filter out types that cannot be referenced in C code. 17770 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17771 CheckForZeroSize = 17772 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17773 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17774 CXXRecord->isCLike(); 17775 } 17776 if (CheckForZeroSize) { 17777 bool ZeroSize = true; 17778 bool IsEmpty = true; 17779 unsigned NonBitFields = 0; 17780 for (RecordDecl::field_iterator I = Record->field_begin(), 17781 E = Record->field_end(); 17782 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17783 IsEmpty = false; 17784 if (I->isUnnamedBitfield()) { 17785 if (!I->isZeroLengthBitField(Context)) 17786 ZeroSize = false; 17787 } else { 17788 ++NonBitFields; 17789 QualType FieldType = I->getType(); 17790 if (FieldType->isIncompleteType() || 17791 !Context.getTypeSizeInChars(FieldType).isZero()) 17792 ZeroSize = false; 17793 } 17794 } 17795 17796 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17797 // allowed in C++, but warn if its declaration is inside 17798 // extern "C" block. 17799 if (ZeroSize) { 17800 Diag(RecLoc, getLangOpts().CPlusPlus ? 17801 diag::warn_zero_size_struct_union_in_extern_c : 17802 diag::warn_zero_size_struct_union_compat) 17803 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17804 } 17805 17806 // Structs without named members are extension in C (C99 6.7.2.1p7), 17807 // but are accepted by GCC. 17808 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17809 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17810 diag::ext_no_named_members_in_struct_union) 17811 << Record->isUnion(); 17812 } 17813 } 17814 } else { 17815 ObjCIvarDecl **ClsFields = 17816 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17817 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17818 ID->setEndOfDefinitionLoc(RBrac); 17819 // Add ivar's to class's DeclContext. 17820 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17821 ClsFields[i]->setLexicalDeclContext(ID); 17822 ID->addDecl(ClsFields[i]); 17823 } 17824 // Must enforce the rule that ivars in the base classes may not be 17825 // duplicates. 17826 if (ID->getSuperClass()) 17827 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17828 } else if (ObjCImplementationDecl *IMPDecl = 17829 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17830 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17831 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17832 // Ivar declared in @implementation never belongs to the implementation. 17833 // Only it is in implementation's lexical context. 17834 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17835 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17836 IMPDecl->setIvarLBraceLoc(LBrac); 17837 IMPDecl->setIvarRBraceLoc(RBrac); 17838 } else if (ObjCCategoryDecl *CDecl = 17839 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17840 // case of ivars in class extension; all other cases have been 17841 // reported as errors elsewhere. 17842 // FIXME. Class extension does not have a LocEnd field. 17843 // CDecl->setLocEnd(RBrac); 17844 // Add ivar's to class extension's DeclContext. 17845 // Diagnose redeclaration of private ivars. 17846 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17847 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17848 if (IDecl) { 17849 if (const ObjCIvarDecl *ClsIvar = 17850 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17851 Diag(ClsFields[i]->getLocation(), 17852 diag::err_duplicate_ivar_declaration); 17853 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17854 continue; 17855 } 17856 for (const auto *Ext : IDecl->known_extensions()) { 17857 if (const ObjCIvarDecl *ClsExtIvar 17858 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17859 Diag(ClsFields[i]->getLocation(), 17860 diag::err_duplicate_ivar_declaration); 17861 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17862 continue; 17863 } 17864 } 17865 } 17866 ClsFields[i]->setLexicalDeclContext(CDecl); 17867 CDecl->addDecl(ClsFields[i]); 17868 } 17869 CDecl->setIvarLBraceLoc(LBrac); 17870 CDecl->setIvarRBraceLoc(RBrac); 17871 } 17872 } 17873 } 17874 17875 /// Determine whether the given integral value is representable within 17876 /// the given type T. 17877 static bool isRepresentableIntegerValue(ASTContext &Context, 17878 llvm::APSInt &Value, 17879 QualType T) { 17880 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17881 "Integral type required!"); 17882 unsigned BitWidth = Context.getIntWidth(T); 17883 17884 if (Value.isUnsigned() || Value.isNonNegative()) { 17885 if (T->isSignedIntegerOrEnumerationType()) 17886 --BitWidth; 17887 return Value.getActiveBits() <= BitWidth; 17888 } 17889 return Value.getMinSignedBits() <= BitWidth; 17890 } 17891 17892 // Given an integral type, return the next larger integral type 17893 // (or a NULL type of no such type exists). 17894 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17895 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17896 // enum checking below. 17897 assert((T->isIntegralType(Context) || 17898 T->isEnumeralType()) && "Integral type required!"); 17899 const unsigned NumTypes = 4; 17900 QualType SignedIntegralTypes[NumTypes] = { 17901 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17902 }; 17903 QualType UnsignedIntegralTypes[NumTypes] = { 17904 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17905 Context.UnsignedLongLongTy 17906 }; 17907 17908 unsigned BitWidth = Context.getTypeSize(T); 17909 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17910 : UnsignedIntegralTypes; 17911 for (unsigned I = 0; I != NumTypes; ++I) 17912 if (Context.getTypeSize(Types[I]) > BitWidth) 17913 return Types[I]; 17914 17915 return QualType(); 17916 } 17917 17918 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17919 EnumConstantDecl *LastEnumConst, 17920 SourceLocation IdLoc, 17921 IdentifierInfo *Id, 17922 Expr *Val) { 17923 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17924 llvm::APSInt EnumVal(IntWidth); 17925 QualType EltTy; 17926 17927 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17928 Val = nullptr; 17929 17930 if (Val) 17931 Val = DefaultLvalueConversion(Val).get(); 17932 17933 if (Val) { 17934 if (Enum->isDependentType() || Val->isTypeDependent() || 17935 Val->containsErrors()) 17936 EltTy = Context.DependentTy; 17937 else { 17938 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17939 // underlying type, but do allow it in all other contexts. 17940 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17941 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17942 // constant-expression in the enumerator-definition shall be a converted 17943 // constant expression of the underlying type. 17944 EltTy = Enum->getIntegerType(); 17945 ExprResult Converted = 17946 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17947 CCEK_Enumerator); 17948 if (Converted.isInvalid()) 17949 Val = nullptr; 17950 else 17951 Val = Converted.get(); 17952 } else if (!Val->isValueDependent() && 17953 !(Val = 17954 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17955 .get())) { 17956 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17957 } else { 17958 if (Enum->isComplete()) { 17959 EltTy = Enum->getIntegerType(); 17960 17961 // In Obj-C and Microsoft mode, require the enumeration value to be 17962 // representable in the underlying type of the enumeration. In C++11, 17963 // we perform a non-narrowing conversion as part of converted constant 17964 // expression checking. 17965 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17966 if (Context.getTargetInfo() 17967 .getTriple() 17968 .isWindowsMSVCEnvironment()) { 17969 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17970 } else { 17971 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17972 } 17973 } 17974 17975 // Cast to the underlying type. 17976 Val = ImpCastExprToType(Val, EltTy, 17977 EltTy->isBooleanType() ? CK_IntegralToBoolean 17978 : CK_IntegralCast) 17979 .get(); 17980 } else if (getLangOpts().CPlusPlus) { 17981 // C++11 [dcl.enum]p5: 17982 // If the underlying type is not fixed, the type of each enumerator 17983 // is the type of its initializing value: 17984 // - If an initializer is specified for an enumerator, the 17985 // initializing value has the same type as the expression. 17986 EltTy = Val->getType(); 17987 } else { 17988 // C99 6.7.2.2p2: 17989 // The expression that defines the value of an enumeration constant 17990 // shall be an integer constant expression that has a value 17991 // representable as an int. 17992 17993 // Complain if the value is not representable in an int. 17994 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17995 Diag(IdLoc, diag::ext_enum_value_not_int) 17996 << toString(EnumVal, 10) << Val->getSourceRange() 17997 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17998 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17999 // Force the type of the expression to 'int'. 18000 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 18001 } 18002 EltTy = Val->getType(); 18003 } 18004 } 18005 } 18006 } 18007 18008 if (!Val) { 18009 if (Enum->isDependentType()) 18010 EltTy = Context.DependentTy; 18011 else if (!LastEnumConst) { 18012 // C++0x [dcl.enum]p5: 18013 // If the underlying type is not fixed, the type of each enumerator 18014 // is the type of its initializing value: 18015 // - If no initializer is specified for the first enumerator, the 18016 // initializing value has an unspecified integral type. 18017 // 18018 // GCC uses 'int' for its unspecified integral type, as does 18019 // C99 6.7.2.2p3. 18020 if (Enum->isFixed()) { 18021 EltTy = Enum->getIntegerType(); 18022 } 18023 else { 18024 EltTy = Context.IntTy; 18025 } 18026 } else { 18027 // Assign the last value + 1. 18028 EnumVal = LastEnumConst->getInitVal(); 18029 ++EnumVal; 18030 EltTy = LastEnumConst->getType(); 18031 18032 // Check for overflow on increment. 18033 if (EnumVal < LastEnumConst->getInitVal()) { 18034 // C++0x [dcl.enum]p5: 18035 // If the underlying type is not fixed, the type of each enumerator 18036 // is the type of its initializing value: 18037 // 18038 // - Otherwise the type of the initializing value is the same as 18039 // the type of the initializing value of the preceding enumerator 18040 // unless the incremented value is not representable in that type, 18041 // in which case the type is an unspecified integral type 18042 // sufficient to contain the incremented value. If no such type 18043 // exists, the program is ill-formed. 18044 QualType T = getNextLargerIntegralType(Context, EltTy); 18045 if (T.isNull() || Enum->isFixed()) { 18046 // There is no integral type larger enough to represent this 18047 // value. Complain, then allow the value to wrap around. 18048 EnumVal = LastEnumConst->getInitVal(); 18049 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 18050 ++EnumVal; 18051 if (Enum->isFixed()) 18052 // When the underlying type is fixed, this is ill-formed. 18053 Diag(IdLoc, diag::err_enumerator_wrapped) 18054 << toString(EnumVal, 10) 18055 << EltTy; 18056 else 18057 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 18058 << toString(EnumVal, 10); 18059 } else { 18060 EltTy = T; 18061 } 18062 18063 // Retrieve the last enumerator's value, extent that type to the 18064 // type that is supposed to be large enough to represent the incremented 18065 // value, then increment. 18066 EnumVal = LastEnumConst->getInitVal(); 18067 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18068 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 18069 ++EnumVal; 18070 18071 // If we're not in C++, diagnose the overflow of enumerator values, 18072 // which in C99 means that the enumerator value is not representable in 18073 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 18074 // permits enumerator values that are representable in some larger 18075 // integral type. 18076 if (!getLangOpts().CPlusPlus && !T.isNull()) 18077 Diag(IdLoc, diag::warn_enum_value_overflow); 18078 } else if (!getLangOpts().CPlusPlus && 18079 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18080 // Enforce C99 6.7.2.2p2 even when we compute the next value. 18081 Diag(IdLoc, diag::ext_enum_value_not_int) 18082 << toString(EnumVal, 10) << 1; 18083 } 18084 } 18085 } 18086 18087 if (!EltTy->isDependentType()) { 18088 // Make the enumerator value match the signedness and size of the 18089 // enumerator's type. 18090 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 18091 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18092 } 18093 18094 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 18095 Val, EnumVal); 18096 } 18097 18098 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 18099 SourceLocation IILoc) { 18100 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 18101 !getLangOpts().CPlusPlus) 18102 return SkipBodyInfo(); 18103 18104 // We have an anonymous enum definition. Look up the first enumerator to 18105 // determine if we should merge the definition with an existing one and 18106 // skip the body. 18107 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 18108 forRedeclarationInCurContext()); 18109 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 18110 if (!PrevECD) 18111 return SkipBodyInfo(); 18112 18113 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 18114 NamedDecl *Hidden; 18115 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 18116 SkipBodyInfo Skip; 18117 Skip.Previous = Hidden; 18118 return Skip; 18119 } 18120 18121 return SkipBodyInfo(); 18122 } 18123 18124 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 18125 SourceLocation IdLoc, IdentifierInfo *Id, 18126 const ParsedAttributesView &Attrs, 18127 SourceLocation EqualLoc, Expr *Val) { 18128 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 18129 EnumConstantDecl *LastEnumConst = 18130 cast_or_null<EnumConstantDecl>(lastEnumConst); 18131 18132 // The scope passed in may not be a decl scope. Zip up the scope tree until 18133 // we find one that is. 18134 S = getNonFieldDeclScope(S); 18135 18136 // Verify that there isn't already something declared with this name in this 18137 // scope. 18138 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 18139 LookupName(R, S); 18140 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 18141 18142 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18143 // Maybe we will complain about the shadowed template parameter. 18144 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 18145 // Just pretend that we didn't see the previous declaration. 18146 PrevDecl = nullptr; 18147 } 18148 18149 // C++ [class.mem]p15: 18150 // If T is the name of a class, then each of the following shall have a name 18151 // different from T: 18152 // - every enumerator of every member of class T that is an unscoped 18153 // enumerated type 18154 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 18155 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 18156 DeclarationNameInfo(Id, IdLoc)); 18157 18158 EnumConstantDecl *New = 18159 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 18160 if (!New) 18161 return nullptr; 18162 18163 if (PrevDecl) { 18164 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 18165 // Check for other kinds of shadowing not already handled. 18166 CheckShadow(New, PrevDecl, R); 18167 } 18168 18169 // When in C++, we may get a TagDecl with the same name; in this case the 18170 // enum constant will 'hide' the tag. 18171 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 18172 "Received TagDecl when not in C++!"); 18173 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 18174 if (isa<EnumConstantDecl>(PrevDecl)) 18175 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 18176 else 18177 Diag(IdLoc, diag::err_redefinition) << Id; 18178 notePreviousDefinition(PrevDecl, IdLoc); 18179 return nullptr; 18180 } 18181 } 18182 18183 // Process attributes. 18184 ProcessDeclAttributeList(S, New, Attrs); 18185 AddPragmaAttributes(S, New); 18186 18187 // Register this decl in the current scope stack. 18188 New->setAccess(TheEnumDecl->getAccess()); 18189 PushOnScopeChains(New, S); 18190 18191 ActOnDocumentableDecl(New); 18192 18193 return New; 18194 } 18195 18196 // Returns true when the enum initial expression does not trigger the 18197 // duplicate enum warning. A few common cases are exempted as follows: 18198 // Element2 = Element1 18199 // Element2 = Element1 + 1 18200 // Element2 = Element1 - 1 18201 // Where Element2 and Element1 are from the same enum. 18202 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 18203 Expr *InitExpr = ECD->getInitExpr(); 18204 if (!InitExpr) 18205 return true; 18206 InitExpr = InitExpr->IgnoreImpCasts(); 18207 18208 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 18209 if (!BO->isAdditiveOp()) 18210 return true; 18211 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 18212 if (!IL) 18213 return true; 18214 if (IL->getValue() != 1) 18215 return true; 18216 18217 InitExpr = BO->getLHS(); 18218 } 18219 18220 // This checks if the elements are from the same enum. 18221 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 18222 if (!DRE) 18223 return true; 18224 18225 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 18226 if (!EnumConstant) 18227 return true; 18228 18229 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 18230 Enum) 18231 return true; 18232 18233 return false; 18234 } 18235 18236 // Emits a warning when an element is implicitly set a value that 18237 // a previous element has already been set to. 18238 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 18239 EnumDecl *Enum, QualType EnumType) { 18240 // Avoid anonymous enums 18241 if (!Enum->getIdentifier()) 18242 return; 18243 18244 // Only check for small enums. 18245 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18246 return; 18247 18248 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18249 return; 18250 18251 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18252 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18253 18254 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18255 18256 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18257 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18258 18259 // Use int64_t as a key to avoid needing special handling for map keys. 18260 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18261 llvm::APSInt Val = D->getInitVal(); 18262 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18263 }; 18264 18265 DuplicatesVector DupVector; 18266 ValueToVectorMap EnumMap; 18267 18268 // Populate the EnumMap with all values represented by enum constants without 18269 // an initializer. 18270 for (auto *Element : Elements) { 18271 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18272 18273 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18274 // this constant. Skip this enum since it may be ill-formed. 18275 if (!ECD) { 18276 return; 18277 } 18278 18279 // Constants with initalizers are handled in the next loop. 18280 if (ECD->getInitExpr()) 18281 continue; 18282 18283 // Duplicate values are handled in the next loop. 18284 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18285 } 18286 18287 if (EnumMap.size() == 0) 18288 return; 18289 18290 // Create vectors for any values that has duplicates. 18291 for (auto *Element : Elements) { 18292 // The last loop returned if any constant was null. 18293 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18294 if (!ValidDuplicateEnum(ECD, Enum)) 18295 continue; 18296 18297 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18298 if (Iter == EnumMap.end()) 18299 continue; 18300 18301 DeclOrVector& Entry = Iter->second; 18302 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18303 // Ensure constants are different. 18304 if (D == ECD) 18305 continue; 18306 18307 // Create new vector and push values onto it. 18308 auto Vec = std::make_unique<ECDVector>(); 18309 Vec->push_back(D); 18310 Vec->push_back(ECD); 18311 18312 // Update entry to point to the duplicates vector. 18313 Entry = Vec.get(); 18314 18315 // Store the vector somewhere we can consult later for quick emission of 18316 // diagnostics. 18317 DupVector.emplace_back(std::move(Vec)); 18318 continue; 18319 } 18320 18321 ECDVector *Vec = Entry.get<ECDVector*>(); 18322 // Make sure constants are not added more than once. 18323 if (*Vec->begin() == ECD) 18324 continue; 18325 18326 Vec->push_back(ECD); 18327 } 18328 18329 // Emit diagnostics. 18330 for (const auto &Vec : DupVector) { 18331 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18332 18333 // Emit warning for one enum constant. 18334 auto *FirstECD = Vec->front(); 18335 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18336 << FirstECD << toString(FirstECD->getInitVal(), 10) 18337 << FirstECD->getSourceRange(); 18338 18339 // Emit one note for each of the remaining enum constants with 18340 // the same value. 18341 for (auto *ECD : llvm::drop_begin(*Vec)) 18342 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18343 << ECD << toString(ECD->getInitVal(), 10) 18344 << ECD->getSourceRange(); 18345 } 18346 } 18347 18348 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18349 bool AllowMask) const { 18350 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18351 assert(ED->isCompleteDefinition() && "expected enum definition"); 18352 18353 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18354 llvm::APInt &FlagBits = R.first->second; 18355 18356 if (R.second) { 18357 for (auto *E : ED->enumerators()) { 18358 const auto &EVal = E->getInitVal(); 18359 // Only single-bit enumerators introduce new flag values. 18360 if (EVal.isPowerOf2()) 18361 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18362 } 18363 } 18364 18365 // A value is in a flag enum if either its bits are a subset of the enum's 18366 // flag bits (the first condition) or we are allowing masks and the same is 18367 // true of its complement (the second condition). When masks are allowed, we 18368 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18369 // 18370 // While it's true that any value could be used as a mask, the assumption is 18371 // that a mask will have all of the insignificant bits set. Anything else is 18372 // likely a logic error. 18373 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18374 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18375 } 18376 18377 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18378 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18379 const ParsedAttributesView &Attrs) { 18380 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18381 QualType EnumType = Context.getTypeDeclType(Enum); 18382 18383 ProcessDeclAttributeList(S, Enum, Attrs); 18384 18385 if (Enum->isDependentType()) { 18386 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18387 EnumConstantDecl *ECD = 18388 cast_or_null<EnumConstantDecl>(Elements[i]); 18389 if (!ECD) continue; 18390 18391 ECD->setType(EnumType); 18392 } 18393 18394 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18395 return; 18396 } 18397 18398 // TODO: If the result value doesn't fit in an int, it must be a long or long 18399 // long value. ISO C does not support this, but GCC does as an extension, 18400 // emit a warning. 18401 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18402 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18403 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18404 18405 // Verify that all the values are okay, compute the size of the values, and 18406 // reverse the list. 18407 unsigned NumNegativeBits = 0; 18408 unsigned NumPositiveBits = 0; 18409 18410 // Keep track of whether all elements have type int. 18411 bool AllElementsInt = true; 18412 18413 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18414 EnumConstantDecl *ECD = 18415 cast_or_null<EnumConstantDecl>(Elements[i]); 18416 if (!ECD) continue; // Already issued a diagnostic. 18417 18418 const llvm::APSInt &InitVal = ECD->getInitVal(); 18419 18420 // Keep track of the size of positive and negative values. 18421 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18422 NumPositiveBits = std::max(NumPositiveBits, 18423 (unsigned)InitVal.getActiveBits()); 18424 else 18425 NumNegativeBits = std::max(NumNegativeBits, 18426 (unsigned)InitVal.getMinSignedBits()); 18427 18428 // Keep track of whether every enum element has type int (very common). 18429 if (AllElementsInt) 18430 AllElementsInt = ECD->getType() == Context.IntTy; 18431 } 18432 18433 // Figure out the type that should be used for this enum. 18434 QualType BestType; 18435 unsigned BestWidth; 18436 18437 // C++0x N3000 [conv.prom]p3: 18438 // An rvalue of an unscoped enumeration type whose underlying 18439 // type is not fixed can be converted to an rvalue of the first 18440 // of the following types that can represent all the values of 18441 // the enumeration: int, unsigned int, long int, unsigned long 18442 // int, long long int, or unsigned long long int. 18443 // C99 6.4.4.3p2: 18444 // An identifier declared as an enumeration constant has type int. 18445 // The C99 rule is modified by a gcc extension 18446 QualType BestPromotionType; 18447 18448 bool Packed = Enum->hasAttr<PackedAttr>(); 18449 // -fshort-enums is the equivalent to specifying the packed attribute on all 18450 // enum definitions. 18451 if (LangOpts.ShortEnums) 18452 Packed = true; 18453 18454 // If the enum already has a type because it is fixed or dictated by the 18455 // target, promote that type instead of analyzing the enumerators. 18456 if (Enum->isComplete()) { 18457 BestType = Enum->getIntegerType(); 18458 if (BestType->isPromotableIntegerType()) 18459 BestPromotionType = Context.getPromotedIntegerType(BestType); 18460 else 18461 BestPromotionType = BestType; 18462 18463 BestWidth = Context.getIntWidth(BestType); 18464 } 18465 else if (NumNegativeBits) { 18466 // If there is a negative value, figure out the smallest integer type (of 18467 // int/long/longlong) that fits. 18468 // If it's packed, check also if it fits a char or a short. 18469 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18470 BestType = Context.SignedCharTy; 18471 BestWidth = CharWidth; 18472 } else if (Packed && NumNegativeBits <= ShortWidth && 18473 NumPositiveBits < ShortWidth) { 18474 BestType = Context.ShortTy; 18475 BestWidth = ShortWidth; 18476 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18477 BestType = Context.IntTy; 18478 BestWidth = IntWidth; 18479 } else { 18480 BestWidth = Context.getTargetInfo().getLongWidth(); 18481 18482 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18483 BestType = Context.LongTy; 18484 } else { 18485 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18486 18487 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18488 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18489 BestType = Context.LongLongTy; 18490 } 18491 } 18492 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18493 } else { 18494 // If there is no negative value, figure out the smallest type that fits 18495 // all of the enumerator values. 18496 // If it's packed, check also if it fits a char or a short. 18497 if (Packed && NumPositiveBits <= CharWidth) { 18498 BestType = Context.UnsignedCharTy; 18499 BestPromotionType = Context.IntTy; 18500 BestWidth = CharWidth; 18501 } else if (Packed && NumPositiveBits <= ShortWidth) { 18502 BestType = Context.UnsignedShortTy; 18503 BestPromotionType = Context.IntTy; 18504 BestWidth = ShortWidth; 18505 } else if (NumPositiveBits <= IntWidth) { 18506 BestType = Context.UnsignedIntTy; 18507 BestWidth = IntWidth; 18508 BestPromotionType 18509 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18510 ? Context.UnsignedIntTy : Context.IntTy; 18511 } else if (NumPositiveBits <= 18512 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18513 BestType = Context.UnsignedLongTy; 18514 BestPromotionType 18515 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18516 ? Context.UnsignedLongTy : Context.LongTy; 18517 } else { 18518 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18519 assert(NumPositiveBits <= BestWidth && 18520 "How could an initializer get larger than ULL?"); 18521 BestType = Context.UnsignedLongLongTy; 18522 BestPromotionType 18523 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18524 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18525 } 18526 } 18527 18528 // Loop over all of the enumerator constants, changing their types to match 18529 // the type of the enum if needed. 18530 for (auto *D : Elements) { 18531 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18532 if (!ECD) continue; // Already issued a diagnostic. 18533 18534 // Standard C says the enumerators have int type, but we allow, as an 18535 // extension, the enumerators to be larger than int size. If each 18536 // enumerator value fits in an int, type it as an int, otherwise type it the 18537 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18538 // that X has type 'int', not 'unsigned'. 18539 18540 // Determine whether the value fits into an int. 18541 llvm::APSInt InitVal = ECD->getInitVal(); 18542 18543 // If it fits into an integer type, force it. Otherwise force it to match 18544 // the enum decl type. 18545 QualType NewTy; 18546 unsigned NewWidth; 18547 bool NewSign; 18548 if (!getLangOpts().CPlusPlus && 18549 !Enum->isFixed() && 18550 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18551 NewTy = Context.IntTy; 18552 NewWidth = IntWidth; 18553 NewSign = true; 18554 } else if (ECD->getType() == BestType) { 18555 // Already the right type! 18556 if (getLangOpts().CPlusPlus) 18557 // C++ [dcl.enum]p4: Following the closing brace of an 18558 // enum-specifier, each enumerator has the type of its 18559 // enumeration. 18560 ECD->setType(EnumType); 18561 continue; 18562 } else { 18563 NewTy = BestType; 18564 NewWidth = BestWidth; 18565 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18566 } 18567 18568 // Adjust the APSInt value. 18569 InitVal = InitVal.extOrTrunc(NewWidth); 18570 InitVal.setIsSigned(NewSign); 18571 ECD->setInitVal(InitVal); 18572 18573 // Adjust the Expr initializer and type. 18574 if (ECD->getInitExpr() && 18575 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18576 ECD->setInitExpr(ImplicitCastExpr::Create( 18577 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18578 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 18579 if (getLangOpts().CPlusPlus) 18580 // C++ [dcl.enum]p4: Following the closing brace of an 18581 // enum-specifier, each enumerator has the type of its 18582 // enumeration. 18583 ECD->setType(EnumType); 18584 else 18585 ECD->setType(NewTy); 18586 } 18587 18588 Enum->completeDefinition(BestType, BestPromotionType, 18589 NumPositiveBits, NumNegativeBits); 18590 18591 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18592 18593 if (Enum->isClosedFlag()) { 18594 for (Decl *D : Elements) { 18595 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18596 if (!ECD) continue; // Already issued a diagnostic. 18597 18598 llvm::APSInt InitVal = ECD->getInitVal(); 18599 if (InitVal != 0 && !InitVal.isPowerOf2() && 18600 !IsValueInFlagEnum(Enum, InitVal, true)) 18601 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18602 << ECD << Enum; 18603 } 18604 } 18605 18606 // Now that the enum type is defined, ensure it's not been underaligned. 18607 if (Enum->hasAttrs()) 18608 CheckAlignasUnderalignment(Enum); 18609 } 18610 18611 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18612 SourceLocation StartLoc, 18613 SourceLocation EndLoc) { 18614 StringLiteral *AsmString = cast<StringLiteral>(expr); 18615 18616 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18617 AsmString, StartLoc, 18618 EndLoc); 18619 CurContext->addDecl(New); 18620 return New; 18621 } 18622 18623 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18624 IdentifierInfo* AliasName, 18625 SourceLocation PragmaLoc, 18626 SourceLocation NameLoc, 18627 SourceLocation AliasNameLoc) { 18628 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18629 LookupOrdinaryName); 18630 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18631 AttributeCommonInfo::AS_Pragma); 18632 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18633 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info); 18634 18635 // If a declaration that: 18636 // 1) declares a function or a variable 18637 // 2) has external linkage 18638 // already exists, add a label attribute to it. 18639 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18640 if (isDeclExternC(PrevDecl)) 18641 PrevDecl->addAttr(Attr); 18642 else 18643 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18644 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18645 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18646 } else 18647 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18648 } 18649 18650 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18651 SourceLocation PragmaLoc, 18652 SourceLocation NameLoc) { 18653 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18654 18655 if (PrevDecl) { 18656 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18657 } else { 18658 (void)WeakUndeclaredIdentifiers.insert( 18659 std::pair<IdentifierInfo*,WeakInfo> 18660 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18661 } 18662 } 18663 18664 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18665 IdentifierInfo* AliasName, 18666 SourceLocation PragmaLoc, 18667 SourceLocation NameLoc, 18668 SourceLocation AliasNameLoc) { 18669 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18670 LookupOrdinaryName); 18671 WeakInfo W = WeakInfo(Name, NameLoc); 18672 18673 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18674 if (!PrevDecl->hasAttr<AliasAttr>()) 18675 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18676 DeclApplyPragmaWeak(TUScope, ND, W); 18677 } else { 18678 (void)WeakUndeclaredIdentifiers.insert( 18679 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18680 } 18681 } 18682 18683 Decl *Sema::getObjCDeclContext() const { 18684 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18685 } 18686 18687 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18688 bool Final) { 18689 assert(FD && "Expected non-null FunctionDecl"); 18690 18691 // SYCL functions can be template, so we check if they have appropriate 18692 // attribute prior to checking if it is a template. 18693 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18694 return FunctionEmissionStatus::Emitted; 18695 18696 // Templates are emitted when they're instantiated. 18697 if (FD->isDependentContext()) 18698 return FunctionEmissionStatus::TemplateDiscarded; 18699 18700 // Check whether this function is an externally visible definition. 18701 auto IsEmittedForExternalSymbol = [this, FD]() { 18702 // We have to check the GVA linkage of the function's *definition* -- if we 18703 // only have a declaration, we don't know whether or not the function will 18704 // be emitted, because (say) the definition could include "inline". 18705 FunctionDecl *Def = FD->getDefinition(); 18706 18707 return Def && !isDiscardableGVALinkage( 18708 getASTContext().GetGVALinkageForFunction(Def)); 18709 }; 18710 18711 if (LangOpts.OpenMPIsDevice) { 18712 // In OpenMP device mode we will not emit host only functions, or functions 18713 // we don't need due to their linkage. 18714 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18715 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18716 // DevTy may be changed later by 18717 // #pragma omp declare target to(*) device_type(*). 18718 // Therefore DevTy having no value does not imply host. The emission status 18719 // will be checked again at the end of compilation unit with Final = true. 18720 if (DevTy.hasValue()) 18721 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18722 return FunctionEmissionStatus::OMPDiscarded; 18723 // If we have an explicit value for the device type, or we are in a target 18724 // declare context, we need to emit all extern and used symbols. 18725 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 18726 if (IsEmittedForExternalSymbol()) 18727 return FunctionEmissionStatus::Emitted; 18728 // Device mode only emits what it must, if it wasn't tagged yet and needed, 18729 // we'll omit it. 18730 if (Final) 18731 return FunctionEmissionStatus::OMPDiscarded; 18732 } else if (LangOpts.OpenMP > 45) { 18733 // In OpenMP host compilation prior to 5.0 everything was an emitted host 18734 // function. In 5.0, no_host was introduced which might cause a function to 18735 // be ommitted. 18736 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18737 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18738 if (DevTy.hasValue()) 18739 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 18740 return FunctionEmissionStatus::OMPDiscarded; 18741 } 18742 18743 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 18744 return FunctionEmissionStatus::Emitted; 18745 18746 if (LangOpts.CUDA) { 18747 // When compiling for device, host functions are never emitted. Similarly, 18748 // when compiling for host, device and global functions are never emitted. 18749 // (Technically, we do emit a host-side stub for global functions, but this 18750 // doesn't count for our purposes here.) 18751 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18752 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18753 return FunctionEmissionStatus::CUDADiscarded; 18754 if (!LangOpts.CUDAIsDevice && 18755 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18756 return FunctionEmissionStatus::CUDADiscarded; 18757 18758 if (IsEmittedForExternalSymbol()) 18759 return FunctionEmissionStatus::Emitted; 18760 } 18761 18762 // Otherwise, the function is known-emitted if it's in our set of 18763 // known-emitted functions. 18764 return FunctionEmissionStatus::Unknown; 18765 } 18766 18767 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18768 // Host-side references to a __global__ function refer to the stub, so the 18769 // function itself is never emitted and therefore should not be marked. 18770 // If we have host fn calls kernel fn calls host+device, the HD function 18771 // does not get instantiated on the host. We model this by omitting at the 18772 // call to the kernel from the callgraph. This ensures that, when compiling 18773 // for host, only HD functions actually called from the host get marked as 18774 // known-emitted. 18775 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18776 IdentifyCUDATarget(Callee) == CFT_Global; 18777 } 18778